Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore(frontend): retire some legacy supports (#8331)
Liu Jicfec05559289
diff --git a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vueindex 61085b35a2..d394c867ba 100644--- a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue+++ b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue@@ -222,12 +222,9 @@ import {import {experimentalCreateIssueByPlan,hasFeature,- useActuatorV1Store,useCurrentUserV1,- useDatabaseV1Store,useEnvironmentV1Store,useInstanceV1Store,- useIssueStore,useProjectV1Store,} from "@/store";import {@@ -237,9 +234,6 @@ import {UNKNOWN_ID,ComposedInstance,unknownInstance,- IssueCreate,- CreateDatabaseContext,- PITRContext,} from "@/types";import { INTERNAL_RDS_INSTANCE_USER_LIST } from "@/types/InstanceUser";import { UserRole } from "@/types/proto/v1/auth_service";@@ -261,7 +255,6 @@ import {hasWorkspacePermissionV1,instanceV1HasCollationAndCharacterSet,instanceV1HasCreateDatabase,- issueSlug,} from "@/utils";import { trySetDefaultAssigneeByEnvironmentAndDeploymentType } from "../IssueV1/logic/initialize/assignee";import {@@ -316,9 +309,6 @@ const router = useRouter();const currentUserV1 = useCurrentUserV1();const environmentV1Store = useEnvironmentV1Store();const projectV1Store = useProjectV1Store();-const developmentUseV1IssueUI = computed(() => {- return !!useActuatorV1Store().serverInfo?.developmentUseV2Scheduler;-});const showAssigneeSelect = computed(() => {// If the role can't change assignee after creating the issue, then we will show the@@ -560,117 +550,9 @@ const createV1 = async () => {state.creating = false;}};-const createLegacy = async () => {- if (!allowCreate.value) {- return;- }-- let newIssue: IssueCreate;-- const databaseName = state.databaseName;- const tableName = state.tableName;- const instanceId = Number(state.instanceId);- let owner = "";- if (requireDatabaseOwnerName.value && state.instanceRole) {- const instanceUser = await instanceV1Store.fetchInstanceRoleByName(- state.instanceRole- );- owner = instanceUser.roleName;- }-- if (isTenantProject.value) {- if (!hasFeature("bb.feature.multi-tenancy")) {- state.showFeatureModal = true;- return;- }- }- // Do not submit non-selected optional labels- const labels = Object.keys(state.labels)- .map((key) => {- const value = state.labels[key];- return { key, value };- })- .filter((kv) => !!kv.value);-- const createDatabaseContext: CreateDatabaseContext = {- instanceId,- databaseName: databaseName,- tableName: tableName,- owner,- characterSet:- state.characterSet ||- defaultCharsetOfEngineV1(selectedInstance.value.engine),- collation:- state.collation ||- defaultCollationOfEngineV1(selectedInstance.value.engine),- cluster: state.cluster,- labels: JSON.stringify(labels),- };-- if (props.backup) {- // If props.backup is specified, we create a PITR issue- // with createDatabaseContext- const { instance, database } = extractDatabaseResourceName(- props.backup.name- );- const db = await useDatabaseV1Store().getOrFetchDatabaseByName(- `instances/${instance}/databases/${database}`- );- const createContext: PITRContext = {- databaseId: Number(db.uid),- backupId: Number(props.backup.uid),- createDatabaseContext,- };- const backupTitle = extractBackupResourceName(props.backup.name);- newIssue = {- name: `Create database '${databaseName}' from backup '${backupTitle}'`,- type: "bb.issue.database.restore.pitr",- description: `Creating database '${databaseName}' from backup '${backupTitle}'`,- assigneeId: parseInt(state.assigneeId!, 10),- projectId: parseInt(state.projectId!, 10),- pipeline: {- stageList: [],- name: "",- },- createContext,- payload: {},- };- } else {- // Otherwise we create a simple database.create issue.- newIssue = {- name: `Create database '${databaseName}'`,- type: "bb.issue.database.create",- description: "",- assigneeId: parseInt(state.assigneeId!, 10),- projectId: parseInt(state.projectId!, 10),- pipeline: {- stageList: [],- name: "",- },- createContext: createDatabaseContext,- payload: {},- };- }-- state.creating = true;- useIssueStore()- .createIssue(newIssue)- .then(- (createdIssue) => {- router.push(`/issue/${issueSlug(createdIssue.name, createdIssue.id)}`);- },- () => {- state.creating = false;- }- );-};const create = async () => {- if (developmentUseV1IssueUI.value) {- await createV1();- } else {- await createLegacy();- }+ await createV1();};// update `state.labelList` when selected Environment changeddiff --git a/frontend/src/components/DatabaseBackup/BackupTable.vue b/frontend/src/components/DatabaseBackup/BackupTable.vueindex 44f0c2d907..a724fbc615 100644--- a/frontend/src/components/DatabaseBackup/BackupTable.vue+++ b/frontend/src/components/DatabaseBackup/BackupTable.vue@@ -156,18 +156,8 @@ import {import EllipsisText from "@/components/EllipsisText.vue";import HumanizeDate from "@/components/misc/HumanizeDate.vue";import { Drawer, DrawerContent } from "@/components/v2";-import {- experimentalCreateIssueByPlan,- useActuatorV1Store,- useIssueStore,- useSubscriptionV1Store,-} from "@/store";-import {- ComposedDatabase,- IssueCreate,- PITRContext,- SYSTEM_BOT_ID,-} from "@/types";+import { experimentalCreateIssueByPlan, useSubscriptionV1Store } from "@/store";+import { ComposedDatabase } from "@/types";import { Engine } from "@/types/proto/v1/common";import {Backup,@@ -177,7 +167,7 @@ import {import { DeploymentType } from "@/types/proto/v1/deployment";import { Issue, Issue_Type } from "@/types/proto/v1/issue_service";import { Plan, Plan_Spec } from "@/types/proto/v1/rollout_service";-import { extractBackupResourceName, issueSlug } from "@/utils";+import { extractBackupResourceName } from "@/utils";import { trySetDefaultAssigneeByEnvironmentAndDeploymentType } from "../IssueV1/logic/initialize/assignee";export type BackupRow = BBGridRow<Backup>;@@ -216,9 +206,6 @@ const props = defineProps({const router = useRouter();const { t } = useI18n();-const developmentUseV1IssueUI = computed(() => {- return !!useActuatorV1Store().serverInfo?.developmentUseV2Scheduler;-});const state = reactive<LocalState>({restoreBackupContext: undefined,@@ -384,61 +371,8 @@ const doRestoreInPlaceV1 = async () => {state.creatingRestoreIssue = false;}};-const doRestoreInPlaceLegacy = async () => {- const { restoreBackupContext } = state;- if (!restoreBackupContext) {- return;- }-- if (!hasPITRFeature.value) {- state.showFeatureModal = true;- return;- }-- state.creatingRestoreIssue = true;-- try {- const { backup } = restoreBackupContext;- const { database } = props;-- const issueNameParts: string[] = [- `Restore database [${database.databaseName}]`,- `to backup snapshot [${extractBackupResourceName(- restoreBackupContext.backup.name- )}]`,- ];-- const issueStore = useIssueStore();- const createContext: PITRContext = {- databaseId: Number(database.uid),- backupId: Number(backup.uid),- };- const issueCreate: IssueCreate = {- name: issueNameParts.join(" "),- type: "bb.issue.database.restore.pitr",- description: "",- assigneeId: SYSTEM_BOT_ID,- projectId: Number(database.projectEntity.uid),- payload: {},- createContext,- };-- await issueStore.validateIssue(issueCreate);-- const issue = await issueStore.createIssue(issueCreate);-- const slug = issueSlug(issue.name, issue.id);- router.push(`/issue/${slug}`);- } catch {- state.creatingRestoreIssue = false;- }-};const doRestoreInPlace = async () => {- if (developmentUseV1IssueUI.value) {- await doRestoreInPlaceV1();- } else {- await doRestoreInPlaceLegacy();- }+ await doRestoreInPlaceV1();};</script>diff --git a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vueindex 040e3f749d..9cb769a5e5 100644--- a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue+++ b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue@@ -155,12 +155,8 @@ import BBContextMenuButton, {} from "@/bbkit/BBContextMenuButton.vue";import { Drawer, DrawerContent } from "@/components/v2";import { usePITRLogic } from "@/plugins";-import {- experimentalCreateIssueByPlan,- useActuatorV1Store,- useSubscriptionV1Store,-} from "@/store";-import { ComposedDatabase, CreateDatabaseContext } from "@/types";+import { experimentalCreateIssueByPlan, useSubscriptionV1Store } from "@/store";+import { ComposedDatabase } from "@/types";import { DeploymentType } from "@/types/proto/v1/deployment";import { Issue, Issue_Type } from "@/types/proto/v1/issue_service";import {@@ -168,7 +164,6 @@ import {Plan_RestoreDatabaseConfig,Plan_Spec,} from "@/types/proto/v1/rollout_service";-import { issueSlug } from "@/utils";import RestoreTargetForm from "../DatabaseBackup/RestoreTargetForm.vue";import { trySetDefaultAssigneeByEnvironmentAndDeploymentType } from "../IssueV1/logic/initialize/assignee";import ChangeHistoryBrief from "./ChangeHistoryBrief.vue";@@ -217,9 +212,6 @@ const state = reactive<LocalState>({showFeatureModal: false,});-const developmentUseV1IssueUI = computed(() => {- return !!useActuatorV1Store().serverInfo?.developmentUseV2Scheduler;-});const createDatabaseForm = ref<InstanceType<typeof CreatePITRDatabaseForm>>();const hasPITRFeature = computed(() => {@@ -231,8 +223,9 @@ const hasPITRFeature = computed(() => {const timezone = computed(() => "UTC" + dayjs().format("ZZ"));-const { pitrAvailable, doneBackupList, lastChangeHistory, createPITRIssue } =- usePITRLogic(toRef(props, "database"));+const { pitrAvailable, doneBackupList, lastChangeHistory } = usePITRLogic(+ toRef(props, "database")+);const pitrButtonDisabled = computed((): boolean => {return !props.allowAdmin || !pitrAvailable.value.result;@@ -365,6 +358,7 @@ const onConfirmV1 = async () => {restoreDatabaseConfig.createDatabaseConfig = {target: database.instance,database: context.databaseName,+ environment: database.environment,table: "",backup: "",characterSet: context.characterSet,@@ -419,77 +413,8 @@ const onConfirmV1 = async () => {resetUI();}};-const onConfirmLegacy = async () => {- if (!hasPITRFeature.value) {- state.showFeatureModal = true;- return;- }-- if (!isValidParams.value) {- return;- }-- state.loading = true;-- try {- let createDatabaseContext: CreateDatabaseContext | undefined = undefined;- const { target, createContext: context } = state;- if (target === "NEW" && context) {- createDatabaseContext = {- projectId: Number(context.projectId),- environmentId: Number(context.environmentId),- instanceId: Number(context.instanceId),- databaseName: context.databaseName,- tableName: "",- characterSet: context.characterSet,- collation: context.collation,- owner: "",- cluster: "",- } as CreateDatabaseContext;- // Do not submit non-selected optional labels- const labels = Object.keys(context.labels)- .map((key) => {- const value = context.labels[key];- return { key, value };- })- .filter((kv) => !!kv.value);- createDatabaseContext.labels = JSON.stringify(labels);- }-- const issueNameParts: string[] = [- `Restore database [${props.database.databaseName}]`,- ];- if (state.mode === "CUSTOM") {- const datetime = dayjs(state.pitrTimestampMS).format(- "YYYY-MM-DD HH:mm:ss"- );- issueNameParts.push(`to [${datetime} ${timezone.value}]`);- } else {- issueNameParts.push(- `before migration version [${lastChangeHistory.value!.version}]`- );- }- const issue = await createPITRIssue(- Math.floor(state.pitrTimestampMS / 1000),- createDatabaseContext,- {- name: issueNameParts.join(" "),- }- );- const slug = issueSlug(issue.name, issue.id);- router.push(`/issue/${slug}`);- } catch (ex) {- // TODO: error handling- } finally {- resetUI();- }-};const onConfirm = async () => {- if (developmentUseV1IssueUI.value) {- await onConfirmV1();- } else {- await onConfirmLegacy();- }+ await onConfirmV1();};</script>diff --git a/frontend/src/components/Issue/AssigneeAttentionButton.vue b/frontend/src/components/Issue/AssigneeAttentionButton.vuedeleted file mode 100644index 93d9f50922..0000000000--- a/frontend/src/components/Issue/AssigneeAttentionButton.vue+++ /dev/null@@ -1,132 +0,0 @@-<template>- <NTooltip v-if="showNotifyAssignee">- <template #trigger>- <button- class="p-0.5 rounded"- :class="[- isAssigneeAttentionOn- ? 'cursor-default'- : 'cursor-pointer hover:bg-control-bg-hover',- ]"- v-bind="$attrs"- @click="notifyAssignee"- >- <heroicons-outline:bell-alert- class="w-4 h-4"- :class="[isAssigneeAttentionOn ? 'text-accent' : 'text-main']"- />- </button>- </template>-- <span class="whitespace-nowrap">- <template v-if="isAssigneeAttentionOn">- {{ $t("issue.assignee-attention.needs-attention") }}- </template>- <template v-else>- {{ $t("issue.assignee-attention.click-to-mark") }}- </template>- </span>- </NTooltip>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { pushNotification, useCurrentUserV1, useIssueStore } from "@/store";-import { useSettingV1Store } from "@/store/modules/v1/setting";-import { Issue } from "@/types";-import { Workflow } from "@/types/proto/v1/project_service";-import { AppIMSetting_IMType } from "@/types/proto/v1/setting_service";-import { extractUserUID } from "@/utils";-import { useIssueLogic } from "./logic";--const { t } = useI18n();-const currentUserV1 = useCurrentUserV1();-const settingV1Store = useSettingV1Store();-const { create, project, issue } = useIssueLogic();--const showNotifyAssignee = computed(() => {- if (create.value) {- return false;- }- if (project.value.workflow === Workflow.VCS) {- return false;- }-- const issueEntity = issue.value as Issue;-- if (issueEntity.status !== "OPEN") {- return false;- }- const currentUserUID = extractUserUID(currentUserV1.value.name);- if (- issueEntity.assigneeNeedAttention &&- currentUserUID === String(issueEntity.assignee.id)- ) {- // Also show the icon for assignee if need attention.- return true;- }-- return currentUserUID === String(issueEntity.creator.id);-});--const isAssigneeAttentionOn = computed(() => {- return (issue.value as Issue).assigneeNeedAttention;-});--const externalApprovalSetting = computed(- (): { enabled: boolean; type: string } => {- const setting = settingV1Store.getSettingByName("bb.app.im");- if (- setting?.value?.appImSettingValue?.imType === AppIMSetting_IMType.FEISHU- ) {- return {- type: "feishu",- enabled:- setting?.value?.appImSettingValue.externalApproval?.enabled ?? false,- };- }- return {- enabled: false,- type: "",- };- }-);--const imTypeName = computed((): string => {- const { enabled, type } = externalApprovalSetting.value;- if (!enabled) return t("common.im");- return t(`common.${type}`);-});--const notifyAssignee = () => {- if (!showNotifyAssignee.value) return;- if (isAssigneeAttentionOn.value) return;-- const issueEntity = issue.value as Issue;-- useIssueStore()- .patchIssue({- issueId: (issue.value as Issue).id,- issuePatch: {- assigneeNeedAttention: true,- },- })- .then(() => {- const message = externalApprovalSetting.value.enabled- ? t("issue.assignee-attention.send-approval-request-successfully", {- im: imTypeName.value,- })- : t("issue.assignee-attention.send-attention-request-successfully", {- principal: issueEntity.assignee.name,- });-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: message,- });- });-};-</script>diff --git a/frontend/src/components/Issue/BatchIssueActions.vue b/frontend/src/components/Issue/BatchIssueActions.vuedeleted file mode 100644index 8ed7ead93c..0000000000--- a/frontend/src/components/Issue/BatchIssueActions.vue+++ /dev/null@@ -1,250 +0,0 @@-<template>- <BBTooltipButton- type="primary"- :disabled="!isTransitionApplicableForAllIssues('RESOLVE')"- tooltip-mode="DISABLED-ONLY"- @click="startBatchIssueTransition('RESOLVE')"- >- {{ $t("issue.batch-transition.resolve") }}- <template #tooltip>- <div class="whitespace-nowrap">- {{- $t("issue.batch-transition.not-allowed-tips", {- operation: $t("issue.batch-transition.resolved"),- })- }}- </div>- </template>- </BBTooltipButton>-- <BBTooltipButton- type="normal"- :disabled="!isTransitionApplicableForAllIssues('CANCEL')"- tooltip-mode="DISABLED-ONLY"- @click="startBatchIssueTransition('CANCEL')"- >- {{ $t("issue.batch-transition.cancel") }}- <template #tooltip>- <div class="whitespace-nowrap">- {{- $t("issue.batch-transition.not-allowed-tips", {- operation: $t("issue.batch-transition.cancelled"),- })- }}- </div>- </template>- </BBTooltipButton>-- <BBTooltipButton- type="normal"- :disabled="!isTransitionApplicableForAllIssues('REOPEN')"- tooltip-mode="DISABLED-ONLY"- @click="startBatchIssueTransition('REOPEN')"- >- {{ $t("issue.batch-transition.reopen") }}- <template #tooltip>- <div class="whitespace-nowrap">- {{- $t("issue.batch-transition.not-allowed-tips", {- operation: $t("issue.batch-transition.reopened"),- })- }}- </div>- </template>- </BBTooltipButton>-- <BBModal- v-if="state.modal.show"- :title="state.modal.title"- class="relative overflow-hidden"- @close="state.modal.show = false"- >- <div- v-if="state.isRequesting"- class="absolute inset-0 flex flex-col items-center justify-center bg-white/70"- >- <BBSpin />- <div class="flex items-center textlabel">- <span>{{ $t("common.updating") }}</span>- <span v-if="state.stats"- >({{ state.stats.success }} / {{ state.stats.total }})</span- >- </div>- </div>-- <div>- <div class="sm:col-span-4 w-112 min-w-full">- <label for="about" class="textlabel">- {{ $t("issue.status-transition.form.note") }}- </label>- <div class="mt-1">- <textarea- ref="commentTextArea"- v-model="state.modal.comment"- rows="3"- class="textarea block w-full resize-none mt-1 text-sm text-control rounded-md whitespace-pre-wrap"- :placeholder="$t('issue.status-transition.form.placeholder')"- @input="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- @focus="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- ></textarea>- </div>- </div>- </div>-- <!-- Update button group -->- <div class="flex justify-end items-center pt-5">- <button- type="button"- class="btn-normal mt-3 px-4 py-2 sm:mt-0 sm:w-auto"- @click.prevent="state.modal.show = false"- >- {{ $t("common.cancel") }}- </button>- <button- type="button"- class="ml-3 px-4 py-2"- :class="state.modal.okButtonClass"- @click="doBatchIssueTransition(state.modal.transition!)"- >- {{ state.modal.okButtonText }}- </button>- </div>- </BBModal>-</template>--<script lang="ts" setup>-import { computed, PropType, reactive } from "vue";-import { useI18n } from "vue-i18n";-import { pushNotification, refreshIssueList, useIssueStore } from "@/store";-import type {- Issue,- IssueStatusPatch,- IssueStatusTransition,- IssueStatusTransitionType,-} from "@/types";-import { ISSUE_STATUS_TRANSITION_LIST } from "@/types";-import { calcApplicableIssueStatusTransitionList } from "./logic";--type RequestStats = {- total: number;- success: number;- failed: number;-};--type ModalProps = {- show: boolean;- title: string;- comment: string;- transition?: IssueStatusTransition;- okButtonText: string;- okButtonClass?: string;-};--type LocalState = {- isRequesting: boolean;- modal: ModalProps;- stats?: RequestStats;-};--const props = defineProps({- issueList: {- type: Array as PropType<Issue[]>,- default: () => [],- },-});--const state = reactive<LocalState>({- isRequesting: false,- modal: {- show: false,- title: "",- comment: "",- okButtonText: "",- },-});--const issueStore = useIssueStore();-const { t } = useI18n();--const issueTransitionList = computed(() => {- return props.issueList.map((issue) => {- const transitions = calcApplicableIssueStatusTransitionList(issue);- return { issue, transitions };- });-});--const isTransitionApplicableForAllIssues = (- type: IssueStatusTransitionType-): boolean => {- return issueTransitionList.value.every((item) => {- return (- item.transitions.findIndex((transition) => transition.type === type) >= 0- );- });-};--const startBatchIssueTransition = (type: IssueStatusTransitionType) => {- const { modal } = state;- modal.show = true;- const transition = ISSUE_STATUS_TRANSITION_LIST.get(type)!;- modal.transition = transition;- modal.comment = "";- modal.okButtonClass = transition.buttonClass;- modal.okButtonText = t(transition.buttonName);- modal.title = t("issue.batch-transition.action-n-issues", {- action: t(`issue.batch-transition.${type.toLowerCase()}`),- n: props.issueList.length,- });-};--const doBatchIssueTransition = async (transition: IssueStatusTransition) => {- const issueStatusPatch: IssueStatusPatch = {- status: transition.to,- comment: state.modal.comment,- };-- const stats = reactive<RequestStats>({- total: props.issueList.length,- success: 0,- failed: 0,- });-- const doSingleIssueTransition = async (issue: Issue, index: number) => {- const request = issueStore.updateIssueStatus({- issueId: issue.id,- issueStatusPatch,- });- request.then(- () => stats.success++,- () => stats.failed++- );-- return request;- };-- state.isRequesting = true;- state.stats = stats;- try {- const requestList = props.issueList.map(doSingleIssueTransition);- await Promise.allSettled(requestList);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("issue.batch-transition.successfully-updated-n-issues", {- n: stats.success,- }),- });- } finally {- state.isRequesting = false;- refreshIssueList();- }-};-</script>diff --git a/frontend/src/components/Issue/GrantRequestIssueSidebar.vue b/frontend/src/components/Issue/GrantRequestIssueSidebar.vuedeleted file mode 100644index 3f19467f6d..0000000000--- a/frontend/src/components/Issue/GrantRequestIssueSidebar.vue+++ /dev/null@@ -1,110 +0,0 @@-<template>- <aside class="pr-0.5">- <h2 class="sr-only">Details</h2>- <div class="grid gap-y-6 gap-x-1 grid-cols-3">- <template v-if="!create">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.status") }}- </h2>- <div class="col-span-2">- <span class="flex items-center space-x-2">- <IssueStatusIcon- :issue-status="(issue as Issue).status"- :size="'normal'"- />- <span class="text-main capitalize">- {{ (issue as Issue).status.toLowerCase() }}- </span>- </span>- </div>- </template>-- <template v-if="!create">- <IssueReviewSidebarSection />- </template>- </div>-- <div- class="mt-6 border-t border-block-border pt-6 grid gap-y-6 gap-x-1 grid-cols-3"- >- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.project") }}- </h2>- <ProjectV1Name- :project="project"- :link="true"- :plain="true"- class="col-span-2 text-sm font-medium text-main hover:underline"- />-- <template v-if="!create">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.updated-at") }}- </h2>- <span class="textfield col-span-2">- {{ dayjs((issue as Issue).updatedTs * 1000).format("LLL") }}</span- >-- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.created-at") }}- </h2>- <span class="textfield col-span-2">- {{ dayjs((issue as Issue).createdTs * 1000).format("LLL") }}</span- >- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.creator") }}- </h2>- <ul class="col-span-2">- <li class="flex justify-start items-center space-x-2">- <div class="flex-shrink-0">- <PrincipalAvatar- :principal="(issue as Issue).creator"- :size="'SMALL'"- />- </div>- <router-link- :to="`/u/${(issue as Issue).creator.id}`"- class="text-sm font-medium text-main hover:underline"- >- {{ (issue as Issue).creator.name }}- </router-link>- </li>- </ul>- </template>- </div>- <IssueSubscriberPanel- v-if="!create"- :issue="(issue as Issue)"- @add-subscriber-id="(subscriberId) => addSubscriberId(subscriberId)"- @remove-subscriber-id="(subscriberId) => removeSubscriberId(subscriberId)"- />- </aside>-</template>--<script lang="ts" setup>-import dayjs from "dayjs";-import isSameOrAfter from "dayjs/plugin/isSameOrAfter";-import { computed } from "vue";-import { useProjectV1Store } from "@/store";-import { Issue, IssueCreate } from "@/types";-import PrincipalAvatar from "../PrincipalAvatar.vue";-import { ProjectV1Name } from "../v2";-import IssueStatusIcon from "./IssueStatusIcon.vue";-import IssueSubscriberPanel from "./IssueSubscriberPanel.vue";-import { useExtraIssueLogic, useIssueLogic } from "./logic";-import { IssueReviewSidebarSection } from "./review";--dayjs.extend(isSameOrAfter);--const projectV1Store = useProjectV1Store();--const { create, issue } = useIssueLogic();-const { addSubscriberId, removeSubscriberId } = useExtraIssueLogic();--const project = computed(() => {- const projectId = create.value- ? (issue.value as IssueCreate).projectId- : (issue.value as Issue).project.id;- return projectV1Store.getProjectByUID(String(projectId));-});-</script>diff --git a/frontend/src/components/Issue/IssueActivityPanel.vue b/frontend/src/components/Issue/IssueActivityPanel.vuedeleted file mode 100644index 747cf25c9c..0000000000--- a/frontend/src/components/Issue/IssueActivityPanel.vue+++ /dev/null@@ -1,332 +0,0 @@-<template>- <div id="activity">- <div class="divide-y divide-block-border">- <div class="pb-4">- <h2 id="activity-title" class="text-lg font-medium text-main">- {{ $t("common.activity") }}- </h2>- </div>- <div class="pt-6">- <!-- Activity feed-->- <ul>- <ActivityItem- v-for="(item, index) in activityList"- :key="item.activity.name"- :activity-list="activityList"- :issue="issue"- :index="index"- :activity="item.activity"- :similar="item.similar"- >- <template v-if="allowEditActivity(item.activity)" #subject-suffix>- <div class="space-x-2 flex items-center text-control-light">- <!-- mr-2 is to vertical align with the text description edit button-->- <div- v-if="!state.editCommentMode"- class="mr-2 flex items-center space-x-2"- >- <!-- Edit Comment Button-->- <button- class="btn-icon"- @click.prevent="onUpdateComment(item.activity)"- >- <heroicons-outline:pencil class="w-4 h-4" />- </button>- </div>- </div>- </template>-- <template #comment>- <MarkdownEditor- v-if="item.activity.comment"- :mode="- state.editCommentMode &&- state.activeActivity?.name === item.activity.name- ? 'editor'- : 'preview'- "- :content="item.activity.comment"- :issue-list="issueList"- @change="(val: string) => state.editComment = val"- @submit="doUpdateComment"- @cancel="cancelEditComment"- />- <div- v-if="- state.editCommentMode &&- state.activeActivity?.name === item.activity.name- "- class="flex space-x-2 mt-4 items-center justify-end"- >- <button- type="button"- class="btn-normal border-none"- @click.prevent="cancelEditComment"- >- {{ $t("common.cancel") }}- </button>- <button- type="button"- class="btn-normal"- :disabled="!allowUpdateComment"- @click.prevent="doUpdateComment"- >- {{ $t("common.save") }}- </button>- </div>- </template>- </ActivityItem>- </ul>-- <div v-if="!state.editCommentMode">- <div class="flex">- <div class="flex-shrink-0">- <div class="relative">- <UserAvatar :user="currentUserV1" />- <span- class="absolute -bottom-0.5 -right-1 bg-white rounded-tl px-0.5 py-px"- >- <!-- Heroicon name: solid/chat-alt -->- <heroicons-solid:chat-alt- class="h-3.5 w-3.5 text-control-light"- />- </span>- </div>- </div>- <div class="ml-3 min-w-0 flex-1">- <label for="comment" class="sr-only">- {{ $t("issue.add-a-comment") }}- </label>- <MarkdownEditor- mode="editor"- :content="state.newComment"- :issue-list="issueList"- @change="(val: string) => state.newComment = val"- @submit="doCreateComment(state.newComment)"- />- <div class="mt-4 flex items-center justify-between space-x-4">- <div>- <button- type="button"- class="btn-normal"- :disabled="state.newComment.length == 0"- @click.prevent="doCreateComment(state.newComment)"- >- {{ $t("common.comment") }}- </button>- </div>- </div>- </div>- </div>- </div>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import {- computed,- reactive,- watch,- watchEffect,- Ref,- ref,- onMounted,-} from "vue";-import { useRoute } from "vue-router";-import { IssueBuiltinFieldId } from "@/plugins";-import {- useIssueSubscriberStore,- useIssueV1Store,- useIssueStore,- useActivityV1Store,- useCurrentUserV1,- useCurrentUser,-} from "@/store";-import { getLogId } from "@/store/modules/v1/common";-import type {- Issue,- ActivityIssueFieldUpdatePayload,- IssueSubscriber,- ActivityIssueCommentCreatePayload,-} from "@/types";-import { LogEntity, LogEntity_Action } from "@/types/proto/v1/logging_service";-import { extractUserResourceName } from "@/utils";-import UserAvatar from "../User/UserAvatar.vue";-import { ActivityItem, DistinctActivity, isSimilarActivity } from "./activity";-import { useExtraIssueLogic, useIssueLogic } from "./logic";--interface LocalState {- editCommentMode: boolean;- activeActivity?: LogEntity;- editComment: string;- newComment: string;-}--const issueStore = useIssueStore();-const issueV1Store = useIssueV1Store();-const activityV1Store = useActivityV1Store();-const route = useRoute();--const logic = useIssueLogic();-const issue = logic.issue as Ref<Issue>;-const issueList = ref<Issue[]>([]);-const { addSubscriberId } = useExtraIssueLogic();--const state = reactive<LocalState>({- editCommentMode: false,- editComment: "",- newComment: "",-});--const currentUser = useCurrentUser();-const currentUserV1 = useCurrentUserV1();--const prepareActivityList = async () => {- const [_, list] = await Promise.all([- activityV1Store.fetchActivityListForIssue(issue.value),- issueStore.fetchIssueList({ projectId: issue.value.project.id }),- ]);-- issueList.value = list;-};--watchEffect(prepareActivityList);--// Need to use computed to make list reactive to activity list changes.-const activityList = computed((): DistinctActivity[] => {- const list = activityV1Store- .getActivityListByIssue(issue.value.id)- .filter((activity) => {- if (activity.action === LogEntity_Action.ACTION_ISSUE_APPROVAL_NOTIFY) {- return false;- }-- if (activity.action === LogEntity_Action.ACTION_ISSUE_FIELD_UPDATE) {- const containUserVisibleChange =- (JSON.parse(activity.payload) as ActivityIssueFieldUpdatePayload)- .fieldId !== IssueBuiltinFieldId.SUBSCRIBER_LIST;- return containUserVisibleChange;- }- return true;- });-- const distinctActivityList: DistinctActivity[] = [];- for (let i = 0; i < list.length; i++) {- const activity = list[i];- if (distinctActivityList.length === 0) {- distinctActivityList.push({ activity, similar: [] });- continue;- }-- const prev = distinctActivityList[distinctActivityList.length - 1];- if (isSimilarActivity(prev.activity, activity)) {- prev.similar.push(activity);- } else {- distinctActivityList.push({ activity, similar: [] });- }- }-- return distinctActivityList;-});--const subscriberList = computed((): IssueSubscriber[] => {- return useIssueSubscriberStore().subscriberListByIssue(issue.value.id);-});--const cancelEditComment = () => {- state.activeActivity = undefined;- state.editCommentMode = false;- state.editComment = "";-};--const doCreateComment = (comment: string) => {- issueV1Store- .createIssueComment({- issueId: issue.value.id,- comment,- })- .then(() => {- state.newComment = "";-- // Because the user just added a comment and we assume she is interested in this- // issue, and we add her to the subscriber list if she is not there- let isSubscribed = false;- for (const subscriber of subscriberList.value) {- if (subscriber.subscriber.id == currentUser.value.id) {- isSubscribed = true;- break;- }- }- if (!isSubscribed) {- addSubscriberId(currentUser.value.id);- }- });-};--const allowEditActivity = (activity: LogEntity) => {- if (activity.action !== LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE) {- return false;- }- if (currentUserV1.value.email !== extractUserResourceName(activity.creator)) {- return false;- }- const payload = JSON.parse(- activity.payload- ) as ActivityIssueCommentCreatePayload;- if (payload && payload.externalApprovalEvent) {- return false;- }- return true;-};--const onUpdateComment = (activity: LogEntity) => {- state.activeActivity = activity;- state.editCommentMode = true;- state.editComment = activity.comment;-};--const doUpdateComment = () => {- if (!state.activeActivity) {- return;- }- if (!state.editComment) {- return;- }- const activityId = getLogId(state.activeActivity.name);- issueV1Store- .updateIssueComment({- commentId: `${activityId}`,- issueId: issue.value.id,- comment: state.editComment,- })- .then(() => {- cancelEditComment();- });-};--const allowUpdateComment = computed(() => {- return (- state.editComment && state.editComment != state.activeActivity!.comment- );-});--onMounted(() => {- watch(- () => route.hash,- (hash) => {- if (hash.match(/^#activity(\d+)/)) {- // use '#activity' element as a fallback- const elem =- document.querySelector(hash) || document.querySelector("#activity");- // We use `setTimeout` here since this should be executed very late.- setTimeout(() => elem?.scrollIntoView());- }- },- {- immediate: true,- }- );-});-</script>diff --git a/frontend/src/components/Issue/IssueBanner.vue b/frontend/src/components/Issue/IssueBanner.vuedeleted file mode 100644index 3066b1dff8..0000000000--- a/frontend/src/components/Issue/IssueBanner.vue+++ /dev/null@@ -1,112 +0,0 @@-<template>- <template v-if="showPendingReview">- <div- class="h-8 w-full text-base font-medium bg-accent text-white flex justify-center items-center"- >- {{ $t("issue.waiting-for-review") }}- </div>- </template>- <template v-else-if="showRejectedReview">- <div- class="h-8 w-full text-base font-medium bg-warning text-white flex justify-center items-center"- >- {{ $t("issue.review-sent-back") }}- </div>- </template>- <template v-else>- <div- v-if="showCancelBanner"- class="h-8 w-full text-base font-medium bg-gray-400 text-white flex justify-center items-center"- >- {{ $t("common.canceled") }}- </div>- <div- v-else-if="showSuccessBanner"- class="h-8 w-full text-base font-medium bg-success text-white flex justify-center items-center"- >- {{ $t("common.done") }}- </div>- <div- v-else-if="showPendingRollout"- class="h-8 w-full text-base font-medium bg-accent text-white flex justify-center items-center"- >- {{ $t("issue.waiting-to-rollout") }}- </div>- <div- v-else-if="showEarliestAllowedTimeBanner"- class="h-8 w-full text-base font-medium bg-accent text-white flex justify-center items-center"- >- {{- $t("issue.waiting-earliest-allowed-time", { time: earliestAllowedTime })- }}- </div>- </template>-</template>--<script lang="ts" setup>-import dayjs from "dayjs";-import { computed, Ref } from "vue";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { Issue } from "@/types";-import { Issue_Approver_Status } from "@/types/proto/v1/issue_service";-import { activeTask, isDatabaseRelatedIssueType } from "@/utils";-import { useIssueLogic } from "./logic";--const issueContext = useIssueLogic();-const issue = issueContext.issue as Ref<Issue>;-const reviewContext = useIssueReviewContext();--const showPendingReview = computed(() => {- if (issueContext.create.value) return false;- if (issue.value.status !== "OPEN") return false;- return reviewContext.status.value === Issue_Approver_Status.PENDING;-});--const showRejectedReview = computed(() => {- if (issueContext.create.value) return false;- if (issue.value.status !== "OPEN") return false;- return reviewContext.status.value === Issue_Approver_Status.REJECTED;-});--const showCancelBanner = computed(() => {- return issue.value.status === "CANCELED";-});--const showSuccessBanner = computed(() => {- return issue.value.status === "DONE";-});--const showPendingRollout = computed(() => {- if (issue.value.status !== "OPEN") return false;- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return false;- }-- const task = activeTask(issue.value.pipeline!);- return task.status == "PENDING_APPROVAL";-});--const showEarliestAllowedTimeBanner = computed(() => {- if (issue.value.status !== "OPEN") return false;- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return false;- }-- const task = activeTask(issue.value.pipeline!);-- if (task.status !== "PENDING") {- return false;- }-- const now = Math.floor(Date.now() / 1000);- return task.earliestAllowedTs > now;-});--const earliestAllowedTime = computed(() => {- const task = activeTask(issue.value.pipeline!);- const tz = "UTC" + dayjs().format("ZZ");- return dayjs(task.earliestAllowedTs * 1000).format(- `YYYY-MM-DD HH:mm:ss ${tz}`- );-});-</script>diff --git a/frontend/src/components/Issue/IssueDescriptionPanel.vue b/frontend/src/components/Issue/IssueDescriptionPanel.vuedeleted file mode 100644index 3608c19bb6..0000000000--- a/frontend/src/components/Issue/IssueDescriptionPanel.vue+++ /dev/null@@ -1,181 +0,0 @@-<template>- <!-- Description Bar -->- <div class="flex justify-between items-center">- <div class="textlabel !leading-7">{{ descriptionTitle }}</div>- <div v-if="!create" class="space-x-2 mt-0.5">- <NButton- v-if="allowEditNameAndDescription && !state.editing"- size="tiny"- @click.prevent="beginEdit"- >- {{ $t("common.edit") }}- </NButton>- <NButton- v-if="state.editing"- size="tiny"- :disabled="state.editDescription == issue.description"- @click.prevent="saveEdit"- >- {{ $t("common.save") }}- </NButton>- <NButton- v-if="state.editing"- size="tiny"- quaternary- @click.prevent="cancelEdit"- >- {{ $t("common.cancel") }}- </NButton>- </div>- </div>- <div class="mt-2 w-full px-[2px]">- <textarea- ref="editDescriptionTextArea"- v-model="state.editDescription"- :rows="create ? 5 : 3"- class="w-full resize-none whitespace-pre-wrap border-white focus:border-white outline-none"- :class="state.editing ? 'focus:ring-control focus-visible:ring-2' : ''"- :style="- state.editing- ? ''- : '-webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none'- "- :placeholder="$t('issue.add-some-description')"- :readonly="!state.editing"- @input="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- // When creating the issue, we will emit the event on keystroke to update the in-memory state.- if (create) {- updateDescription(state.editDescription);- }- }- "- @focus="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- ></textarea>- </div>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import {- nextTick,- onMounted,- onUnmounted,- ref,- reactive,- watch,- computed,-} from "vue";-import { useI18n } from "vue-i18n";-import type { Issue } from "@/types";-import { isGrantRequestIssueType, sizeToFit } from "@/utils";-import { useExtraIssueLogic, useIssueLogic } from "./logic";--interface LocalState {- editing: boolean;- editDescription: string;-}--const { t } = useI18n();-const { issue, create } = useIssueLogic();-const { allowEditNameAndDescription, updateDescription } = useExtraIssueLogic();--const editDescriptionTextArea = ref();--const state = reactive<LocalState>({- editing: false,- editDescription: issue.value.description,-});--const isGrantRequestIssue = computed(() => {- return !!issue.value && isGrantRequestIssueType(issue.value.type);-});--const descriptionTitle = computed(() => {- return isGrantRequestIssue.value- ? t("common.reason")- : t("common.description");-});--const keyboardHandler = (e: KeyboardEvent) => {- if (- state.editing &&- editDescriptionTextArea.value === document.activeElement- ) {- if (e.code == "Escape") {- cancelEdit();- } else if (e.code == "Enter" && e.metaKey) {- if (state.editDescription != issue.value.description) {- saveEdit();- }- }- }-};--const resizeTextAreaHandler = () => {- sizeToFit(editDescriptionTextArea.value);-};--onMounted(() => {- document.addEventListener("keydown", keyboardHandler);- window.addEventListener("resize", resizeTextAreaHandler);- if (create.value) {- state.editing = true;- sizeToFit(editDescriptionTextArea.value);- }-});--onUnmounted(() => {- document.removeEventListener("keydown", keyboardHandler);- window.removeEventListener("resize", resizeTextAreaHandler);-});--// Reset the edit state after creating the issue.-watch(create, (curNew, prevNew) => {- if (!curNew && prevNew) {- state.editing = false;- }-});--watch(- () => issue.value,- (curIssue) => {- state.editDescription = curIssue.description;- nextTick(() => {- sizeToFit(editDescriptionTextArea.value);- });- },- { immediate: true }-);--const beginEdit = () => {- state.editDescription = issue.value.description;- state.editing = true;- nextTick(() => {- editDescriptionTextArea.value.focus();- });-};--const saveEdit = () => {- updateDescription(state.editDescription, (updatedIssue: Issue) => {- state.editDescription = updatedIssue.description;- state.editing = false;- nextTick(() => {- sizeToFit(editDescriptionTextArea.value);- });- });-};--const cancelEdit = () => {- state.editDescription = issue.value.description;- state.editing = false;- nextTick(() => {- sizeToFit(editDescriptionTextArea.value);- });-};-</script>diff --git a/frontend/src/components/Issue/IssueHighlightPanel.vue b/frontend/src/components/Issue/IssueHighlightPanel.vuedeleted file mode 100644index 53924c3dff..0000000000--- a/frontend/src/components/Issue/IssueHighlightPanel.vue+++ /dev/null@@ -1,302 +0,0 @@-<template>- <div class="md:flex md:items-center md:justify-between">- <div class="flex-1 min-w-0">- <div class="flex flex-col">- <div class="flex items-center gap-x-2">- <div v-if="!create">- <IssueStatusIcon- :issue-status="issue.status"- :task-status="issueTaskStatus"- />- </div>- <BBTextField- class="my-px px-2 flex-1 text-lg font-bold truncate"- :class="[create && '-ml-2']"- :disabled="!allowEditNameAndDescription"- :required="true"- :focus-on-mount="create"- :bordered="false"- :value="state.name"- :placeholder="'Issue name'"- @end-editing="(text: string) => trySaveName(text)"- />-- <div class="mt-4 flex space-x-3 md:mt-0 md:ml-4">- <div v-if="showExportCenterLink">- <router-link- class="btn-primary"- :to="{- name: 'workspace.export-center',- hash: `#${issue.id}`,- }"- >- <heroicons-outline:download class="w-5 h-5 mr-2" />- <span>{{ $t("export-center.self") }}</span>- </router-link>- </div>- <div v-else-if="showSQLEditorLink">- <button class="btn-primary" @click="gotoSQLEditor">- <heroicons-solid:terminal class="w-5 h-5 mr-2" />- <span>{{ $t("sql-editor.self") }}</span>- </button>- </div>- <IssueReviewButtonGroup v-else-if="showReviewButtonGroup" />- <CombinedRolloutButtonGroup v-else-if="showRolloutButtonGroup" />- </div>- </div>- <div v-if="!create">- <i18n-t- keypath="issue.opened-by-at"- tag="p"- class="text-sm text-control-light"- >- <template #creator>- <router-link- :to="`/u/${issue.creator.id}`"- class="font-medium text-control hover:underline"- >{{ issue.creator.name }}</router-link- >- </template>- <template #time>{{- dayjs(issue.createdTs * 1000).format("LLL")- }}</template>- </i18n-t>- <p- v-if="pushEvent"- class="mt-1 text-sm text-control-light flex flex-row items-center space-x-1"- >- <template v-if="pushEvent.vcsType.startsWith('GITLAB')">- <img class="h-4 w-auto" src="../../assets/gitlab-logo.svg" />- </template>- <template v-else-if="pushEvent.vcsType.startsWith('GITHUB')">- <img class="h-4 w-auto" src="../../assets/github-logo.svg" />- </template>- <template v-else-if="pushEvent.vcsType.startsWith('BITBUCKET')">- <img class="h-4 w-auto" src="../../assets/bitbucket-logo.svg" />- </template>- <a :href="vcsBranchUrl" target="_blank" class="normal-link">{{- `${vcsBranch}@${pushEvent.repositoryFullPath}`- }}</a>-- <i18n-t- v-if="commit && commit.id && commit.url"- keypath="issue.commit-by-at"- tag="span"- >- <template #id>- <a :href="commit.url" target="_blank" class="normal-link"- >{{ commit.id.substring(0, 7) }}:</a- >- </template>- <template #title>- <span class="text-main">{{ commit.title }}</span>- </template>- <template #author>{{ pushEvent.authorName }}</template>- <template #time>{{- dayjs(commit.createdTs * 1000).format("LLL")- }}</template>- </i18n-t>- </p>- </div>- <slot name="tips"></slot>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { head } from "lodash-es";-import { reactive, watch, computed, Ref } from "vue";-import { useRouter } from "vue-router";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { useCurrentUserV1, useDatabaseV1Store } from "@/store";-import {- TaskDatabaseSchemaUpdatePayload,- TaskDatabaseDataUpdatePayload,- Issue,- VCSPushEvent,- PresetRoleType,- GrantRequestPayload,- UNKNOWN_ID,-} from "@/types";-import {- activeTask,- connectionV1Slug,- extractUserUID,- isDatabaseRelatedIssueType,- isGrantRequestIssueType,-} from "@/utils";-import { convertFromCELString } from "@/utils/issue/cel";-import IssueStatusIcon from "./IssueStatusIcon.vue";-import { CombinedRolloutButtonGroup } from "./StatusTransitionButtonGroup";-import { useExtraIssueLogic, useIssueLogic } from "./logic";-import { IssueReviewButtonGroup } from "./review";--interface LocalState {- editing: boolean;- name: string;-}--const router = useRouter();-const currentUser = useCurrentUserV1();-const logic = useIssueLogic();-const create = logic.create;-const issue = logic.issue as Ref<Issue>;-const { allowEditNameAndDescription, updateName } = useExtraIssueLogic();-const issueReview = useIssueReviewContext();-const { done: reviewDone, error: reviewError } = issueReview;--const state = reactive<LocalState>({- editing: false,- name: issue.value.name,-});--const isFinishedGrantRequestIssueByCurrentUser = computed(() => {- if (create.value) return false;- if (issue.value.status !== "DONE") return false;- if (!isGrantRequestIssueType(issue.value.type)) return false;- if (- String(issue.value.creator.id) !== extractUserUID(currentUser.value.name)- ) {- return false;- }- return true;-});--const showExportCenterLink = computed(() => {- if (!isFinishedGrantRequestIssueByCurrentUser.value) return false;-- return (- issue.value.payload.grantRequest?.role === PresetRoleType.EXPORTER &&- // Show the export button only when the grant request condition is based on the statement.- // TODO: Use parsed CEL expression instead of string matching.- (issue.value.payload.grantRequest?.condition.expression || "").includes(- "request.statement == "- )- );-});--const showSQLEditorLink = computed(() => {- if (!isFinishedGrantRequestIssueByCurrentUser.value) return false;- return issue.value.payload.grantRequest?.role === PresetRoleType.QUERIER;-});--/**- * Send back / Approve- * + cancel issue (dropdown)- */-const showReviewButtonGroup = computed(() => {- if (create.value) return false;- if (reviewError.value) return false;- // User can cancel issue when it's in review.- if (isGrantRequestIssueType(issue.value.type)) return true;- return !reviewDone.value;-});--/**- * Rollout / Retry- * + cancel issue (dropdown)- * + skip all failed tasks in current stage (dropdown)- */-const showRolloutButtonGroup = computed(() => {- if (create.value) return true;- if (isGrantRequestIssueType(issue.value.type)) return false;-- return reviewDone.value;-});--const issueTaskStatus = computed(() => {- // For grant request issue, we always show the status as "PENDING_APPROVAL" as task status.- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return "PENDING_APPROVAL";- }-- return activeTask(issue.value.pipeline!).status;-});--watch(- () => issue.value,- (curIssue) => {- state.name = curIssue.name;- }-);--const pushEvent = computed((): VCSPushEvent | undefined => {- if (issue.value.type == "bb.issue.database.schema.update") {- const payload = activeTask(issue.value.pipeline!)- .payload as TaskDatabaseSchemaUpdatePayload;- return payload?.pushEvent;- } else if (issue.value.type == "bb.issue.database.data.update") {- const payload = activeTask(issue.value.pipeline!)- .payload as TaskDatabaseDataUpdatePayload;- return payload?.pushEvent;- }- return undefined;-});--const commit = computed(() => {- // Use commits[0] for new format- // Use fileCommit for legacy data (if possible)- // Use undefined otherwise- return head(pushEvent.value?.commits) ?? pushEvent.value?.fileCommit;-});--const vcsBranch = computed((): string => {- if (pushEvent.value) {- return pushEvent.value.ref.replace(/^refs\/heads\//g, "");- }- return "";-});--const vcsBranchUrl = computed((): string => {- if (pushEvent.value) {- if (pushEvent.value.vcsType == "GITLAB") {- return `${pushEvent.value.repositoryUrl}/-/tree/${vcsBranch.value}`;- } else if (pushEvent.value.vcsType == "GITHUB") {- return `${pushEvent.value.repositoryUrl}/tree/${vcsBranch.value}`;- } else if (pushEvent.value.vcsType == "BITBUCKET") {- return `${pushEvent.value.repositoryUrl}/src/${vcsBranch.value}`;- }- }- return "";-});--const trySaveName = (text: string) => {- state.name = text;- if (text != issue.value.name) {- updateName(state.name);- }-};--const gotoSQLEditor = async () => {- const grantRequest = issue.value.payload.grantRequest as GrantRequestPayload;- const conditionExpression = await convertFromCELString(- grantRequest.condition.expression- );- if (- conditionExpression.databaseResources !== undefined &&- conditionExpression.databaseResources.length > 0- ) {- const databaseResourceName = conditionExpression.databaseResources[0]- .databaseName as string;- const db = await useDatabaseV1Store().getOrFetchDatabaseByName(- databaseResourceName- );- if (db.uid !== String(UNKNOWN_ID)) {- const slug = connectionV1Slug(db.instanceEntity, db);- const url = router.resolve({- name: "sql-editor.detail",- params: {- connectionSlug: slug,- },- });- window.open(url.fullPath, "__BLANK");- return;- }- }- const url = router.resolve({- name: "sql-editor.home",- });- window.open(url.fullPath, "__BLANK");-};-</script>diff --git a/frontend/src/components/Issue/IssueOutputPanel.vue b/frontend/src/components/Issue/IssueOutputPanel.vuedeleted file mode 100644index 3cc3707524..0000000000--- a/frontend/src/components/Issue/IssueOutputPanel.vue+++ /dev/null@@ -1,170 +0,0 @@-<template>- <h2 class="px-4 text-lg font-medium">- Output- <span class="text-base font-normal text-control-light">- (these fields must be filled by the assignee before resolving the issue)- </span>- </h2>-- <div class="my-2 mx-4 space-y-2">- <template v-for="(field, index) in template.outputFieldList" :key="index">- <div class="flex flex-col space-y-1">- <div class="textlabel">- {{ field.name }}- <span class="text-red-600">*</span>- <template v-if="allowEditDatabase">- <router-link- :to="field.actionLink(issueContext)"- class="ml-2 normal-link"- >- {{ field.actionText }}- </router-link>- </template>- </div>- <template v-if="field.type == 'String'">- <div class="flex flex-row">- <input- type="text"- class="flex-1 min-w-0 block w-full px-3 py-2 rounded-l-md border border-r border-control-border focus:mr-0.5 focus:ring-control focus:border-control sm:text-sm disabled:bg-gray-50"- :disabled="!allowEditOutput"- :name="field.id"- :value="fieldValue(field)"- autocomplete="off"- @blur="(e: any) => updateCustomField(field, e.target.value)"- />- <!-- Disallow tabbing since the focus ring is partially covered by the text field due to overlaying -->- <button- tabindex="-1"- :disabled="!fieldValue(field)"- class="-ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light disabled:text-gray-300 bg-gray-50 hover:bg-gray-100 disabled:bg-gray-50 focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed"- @click.prevent="copyText(field)"- >- <heroicons-outline:clipboard class="w-6 h-6" />- </button>- <button- tabindex="-1"- :disabled="!isValidLink(fieldValue(field))"- class="-ml-px px-2 py-2 border border-gray-300 text-sm font-medium rounded-r-md text-control-light disabled:text-gray-300 bg-gray-50 hover:bg-gray-100 disabled:bg-gray-50 focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-1"- @click.prevent="goToLink(fieldValue(field))"- >- <heroicons-outline:external-link class="w-6 h-6" />- </button>- </div>- </template>- <div- v-if="field.type == 'Database'"- class="flex flex-row items-center space-x-2"- >- <!-- eslint-disable vue/attribute-hyphenation -->- <DatabaseSelect- class="mt-1 w-64"- :disabled="!allowEditDatabase"- :mode="'ENVIRONMENT'"- :environmentId="environmentId"- :selectedId="parseInt(fieldValue(field), 10) || UNKNOWN_ID"- @select-database-id="- (databaseId: number) => {- trySaveCustomField(field, databaseId);- }- "- />- <template v-if="field.viewLink(issueContext)">- <router-link- :to="field.viewLink(issueContext)"- class="ml-2 normal-link text-sm"- >- View- </router-link>- </template>- <div v-if="field.resolved(issueContext)" class="text-sm text-success">- {{ field.resolveStatusText(true) }}- </div>- <div v-else class="text-sm text-error">- {{ field.resolveStatusText(false) }}- </div>- </div>- </div>- </template>- </div>-</template>--<script lang="ts" setup>-import { toClipboard } from "@soerenmartius/vue3-clipboard";-import { isEqual } from "lodash-es";-import { computed, Ref } from "vue";-import { useRouter } from "vue-router";-import { OutputField, IssueContext } from "@/plugins";-import { pushNotification, useCurrentUser } from "@/store";-import { DatabaseId, Issue, UNKNOWN_ID } from "@/types";-import { activeEnvironment } from "@/utils";-import DatabaseSelect from "../DatabaseSelect.vue";-import { useExtraIssueLogic, useIssueLogic } from "./logic";--const router = useRouter();-const logic = useIssueLogic();-const issue = logic.issue as Ref<Issue>;-const template = logic.template;-const { allowEditOutput, updateCustomField } = useExtraIssueLogic();--const currentUser = useCurrentUser();--const environmentId = computed((): string => {- return String(activeEnvironment(issue.value.pipeline).id);-});--const fieldValue = (field: OutputField): string => {- return issue.value.payload[field.id];-};--const issueContext = computed((): IssueContext => {- return {- currentUser: currentUser.value,- create: false,- issue: issue.value,- };-});--const allowEditDatabase = computed((): boolean => {- if (!allowEditOutput.value) {- return false;- }- return (- issue.value.type == "bb.issue.database.create" ||- issue.value.type == "bb.issue.database.grant"- );-});--const isValidLink = (link: string): boolean => {- return link?.trim().length > 0;-};--const copyText = (field: OutputField) => {- toClipboard(issue.value.payload[field.id]).then(() => {- pushNotification({- module: "bytebase",- style: "INFO",- title: `${field.name} copied to clipboard.`,- });- });-};--const goToLink = (link: string) => {- const myLink = link.trim();- const parts = myLink.split("://");- if (parts.length > 1) {- window.open(myLink, "_blank");- } else {- if (!myLink.startsWith("/")) {- router.push("/" + myLink);- } else {- router.push(myLink);- }- }-};--const trySaveCustomField = (field: OutputField, value: string | DatabaseId) => {- if (!isEqual(value, fieldValue(field))) {- updateCustomField(field, value);- }-};-</script>diff --git a/frontend/src/components/Issue/IssueRollbackFromTips.vue b/frontend/src/components/Issue/IssueRollbackFromTips.vuedeleted file mode 100644index 25013e959c..0000000000--- a/frontend/src/components/Issue/IssueRollbackFromTips.vue+++ /dev/null@@ -1,109 +0,0 @@-<template>- <div- v-if="shouldShowTips"- class="mt-1 text-sm text-control-light flex flex-row items-center space-x-1"- >- <heroicons-outline:arrow-uturn-left class="w-4 h-4" />- <i18n-t keypath="issue.will-rollback" tag="span">- <template #link>- <router-link :to="rollbackIssueLink" class="normal-link">- <i18n-t keypath="issue.issue-link-with-task">- <template #issue>#{{ rollbackFromIssue.id }}</template>- <template #task>[{{ rollbackFromTask.name }}]</template>- </i18n-t>- </router-link>- </template>- </i18n-t>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { useRoute } from "vue-router";-import { getRollbackTaskMappingFromQuery } from "@/plugins/issue/logic/initialize/standard";-import { useIssueById } from "@/store";-import {- RollbackDetail,- Task,- TaskCreate,- TaskDatabaseDataUpdatePayload,-} from "@/types";-import { unknown, UNKNOWN_ID } from "@/types";-import { buildIssueLinkWithTask } from "@/utils";-import { flattenTaskList, useIssueLogic } from "./logic";--const { create, selectedTask } = useIssueLogic();-const route = useRoute();--const payload = computed(() => {- if (create.value) return undefined;-- const task = selectedTask.value as Task;- if (task.type === "bb.task.database.data.update") {- return task.payload as TaskDatabaseDataUpdatePayload | undefined;- }- return undefined;-});--const rollbackDetail = computed((): RollbackDetail | undefined => {- if (!create.value) return undefined;- // Try to find out the relationship between databaseId and rollback issue/task- // Id from the URL query.- const task = selectedTask.value as TaskCreate;- const { databaseId } = task;- if (!databaseId || databaseId === UNKNOWN_ID) return undefined;-- const mapping = getRollbackTaskMappingFromQuery(route);- return mapping.get(databaseId);-});--const rollbackFromIssueId = computed(() => {- if (create.value) {- return rollbackDetail.value?.issueId || UNKNOWN_ID;- }- return payload.value?.rollbackFromIssueId || UNKNOWN_ID;-});--const rollbackFromTaskId = computed(() => {- if (create.value) {- return rollbackDetail.value?.taskId || UNKNOWN_ID;- }- return payload.value?.rollbackFromTaskId || UNKNOWN_ID;-});--const rollbackFromIssue = useIssueById(- rollbackFromIssueId,- true /* Lazy fetch */-);--const rollbackFromTask = computed((): Task => {- const issue = rollbackFromIssue.value;- if (issue.id === UNKNOWN_ID) return unknown("TASK");-- const taskId = rollbackFromTaskId.value;- if (taskId === UNKNOWN_ID) return unknown("TASK");-- const task = flattenTaskList<Task>(issue).find((t) => t.id === taskId);- if (task) {- return task;- }-- return unknown("TASK");-});--const shouldShowTips = computed(() => {- // Show the tips when rollbackFromIssue and rollbackFromTask are both ready.- return (- rollbackFromIssue.value.id !== UNKNOWN_ID &&- rollbackFromTask.value.id !== UNKNOWN_ID- );-});--const rollbackIssueLink = computed(() => {- if (!shouldShowTips.value) return "";- return buildIssueLinkWithTask(- rollbackFromIssue.value,- rollbackFromTask.value- );-});-</script>diff --git a/frontend/src/components/Issue/IssueSidebar.vue b/frontend/src/components/Issue/IssueSidebar.vuedeleted file mode 100644index eaae134362..0000000000--- a/frontend/src/components/Issue/IssueSidebar.vue+++ /dev/null@@ -1,626 +0,0 @@-<template>- <aside class="pr-0.5">- <h2 class="sr-only">Details</h2>- <div class="grid gap-y-6 gap-x-1 grid-cols-3">- <template v-if="!create">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.status") }}- </h2>- <div class="col-span-2">- <span class="flex items-center space-x-2">- <IssueStatusIcon- :issue-status="(issue as Issue).status"- :size="'normal'"- />- <span class="text-main capitalize">- {{ (issue as Issue).status.toLowerCase() }}- </span>- </span>- </div>- </template>-- <template v-if="!create">- <IssueReviewSidebarSection />- </template>-- <h2 class="textlabel flex items-center col-span-1 col-start-1 gap-x-1">- <span>{{ $t("common.assignee") }}</span>- <span>- <NTooltip>- <template #trigger>- <heroicons-outline:question-mark-circle />- </template>- <div>{{ $t("issue.assignee-tooltip") }}</div>- </NTooltip>- </span>- <span v-if="create" class="text-red-600">*</span>- <AssigneeAttentionButton />- </h2>- <!-- Only DBA can be assigned to the issue -->- <div class="col-span-2" data-label="bb-assignee-select-container">- <MemberSelect- class="w-full"- :disabled="!allowEditAssignee"- :selected-id="assigneeId"- :custom-filter="filterUser"- data-label="bb-assignee-select"- @select-user-id="updateAssigneeId"- />- </div>-- <template v-for="(field, index) in template.inputFieldList" :key="index">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ field.name }}- <span v-if="field.required" class="text-red-600">*</span>- </h2>- <div class="col-span-2">- <template v-if="field.type == 'String'">- <BBTextField- class="text-sm"- :disabled="!allowEditCustomField(field)"- :required="true"- :value="fieldValue(field)"- :placeholder="field.placeholder"- @end-editing="(text: string) => trySaveCustomField(field, text)"- />- </template>- <template v-else-if="field.type == 'Boolean'">- <BBSwitch- :disabled="!allowEditCustomField(field)"- :value="fieldValue(field)"- @toggle="- (on: boolean) => {- trySaveCustomField(field, on);- }- "- />- </template>- </div>- </template>- </div>- <div- class="mt-6 border-t border-block-border pt-6 grid gap-y-6 gap-x-1 grid-cols-3"- >- <template v-if="showStageSelect">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.stage") }}- </h2>- <div class="col-span-2">- <StageSelect- :pipeline="(issue as Issue).pipeline!"- :selected-id="(selectedStage as Stage).id as number"- @select-stage-id="(stageId: number) => selectStageOrTask(stageId)"- />- </div>- </template>-- <template v-if="showTaskSelect">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.task") }}- </h2>- <div class="col-span-2">- <TaskSelect- :pipeline="(issue as Issue).pipeline!"- :stage="(selectedStage as Stage)"- :selected-id="(selectedTask as Task).id"- @select-task-id="(taskId: IdType) => selectTaskId(taskId)"- />- </div>- </template>-- <TaskRollbackView />-- <template v-if="!isTenantMode">- <!--- earliest-allowed-time is disabled in tenant mode for now- we will provide more powerful deployment schedule in deployment config- -->- <div>- <h2 class="textlabel flex items-center">- <span class="mr-1">{{ $t("task.rollout-time") }}</span>- <NTooltip>- <template #trigger>- <heroicons-outline:question-mark-circle class="h-4 w-4" />- </template>- <div class="w-60">- {{ $t("task.earliest-allowed-time-hint") }}- </div>- </NTooltip>- </h2>- <h2 class="text-gray-600 text-sm">- <span class="row-span-1">{{ "UTC" + dayjs().format("ZZ") }}</span>- </h2>- </div>-- <div class="col-span-2">- <n-date-picker- v-if="allowEditEarliestAllowedTime"- :value="- state.earliestAllowedTs ? state.earliestAllowedTs * 1000 : null- "- :is-date-disabled="isDayPassed"- :placeholder="$t('task.earliest-allowed-time-unset')"- class="w-full"- type="datetime"- clearable- @update:value="updateEarliestAllowedTs"- />-- <div v-else class="tooltip-wrapper">- <span class="tooltip w-48 textlabel">{{- $t("task.earliest-allowed-time-no-modify")- }}</span>- <span class="textfield col-span-2 text-sm font-medium text-main">- {{- selectedTask.earliestAllowedTs === 0- ? $t("task.earliest-allowed-time-unset")- : dayjs(selectedTask.earliestAllowedTs * 1000).format("LLL")- }}- </span>- </div>- </div>- </template>-- <template v-if="databaseName">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.database") }}- </h2>- <div- class="col-span-2 text-sm font-medium text-main truncate"- :class="isDatabaseCreated ? 'cursor-pointer hover:underline' : ''"- @click.prevent="- {- if (isDatabaseCreated) {- clickDatabase();- }- }- "- >- <div class="flex items-center gap-x-1">- <span>{{ databaseName }}</span>- <router-link- :to="`/environment/${environmentV1Slug(environment)}`"- class="col-span-2 text-sm font-medium text-main hover:underline"- >- ({{ environmentV1Name(environment) }})- </router-link>- <SQLEditorButtonV1- v-if="databaseEntity"- :database="databaseEntity"- />- </div>- <div class="text-control-light">{{ showDatabaseCreationLabel }}</div>- </div>- </template>-- <h2 class="textlabel flex items-center col-span-1 col-start-1">- <span class="mr-1">{{ $t("common.instance") }}</span>- <InstanceV1EngineIcon :instance="instance" />- </h2>- <div class="flex gap-x-1">- <router-link- v-if="allowManageInstance"- :to="`/instance/${instanceV1Slug(instance)}`"- class="col-span-2 text-sm font-medium text-main hover:underline"- >- {{ instanceV1Name(instance) }}- </router-link>- <span v-else class="col-span-2 text-sm font-medium text-main">- {{ instanceV1Name(instance) }}- </span>- <router-link- :to="`/environment/${environmentV1Slug(instance.environmentEntity)}`"- class="col-span-2 text-sm font-medium text-main hover:underline"- >- ({{ environmentV1Name(instance.environmentEntity) }})- </router-link>- </div>-- <template v-for="label in visibleLabelList" :key="label.key">- <h2- class="textlabel flex items-start col-span-1 col-start-1 capitalize"- >- {{ hidePrefix(label.key) }}- </h2>-- <div class="col-span-2 text-sm font-medium text-main">- {{ label.value }}- </div>- </template>- </div>- <div- class="mt-6 border-t border-block-border pt-6 grid gap-y-6 gap-x-1 grid-cols-3"- >- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.project") }}- </h2>- <ProjectV1Name- :project="project"- :link="true"- :plain="true"- class="col-span-2 text-sm font-medium text-main hover:underline"- />-- <template v-if="!create">- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.updated-at") }}- </h2>- <span class="textfield col-span-2">- {{ dayjs((issue as Issue).updatedTs * 1000).format("LLL") }}</span- >-- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.created-at") }}- </h2>- <span class="textfield col-span-2">- {{ dayjs((issue as Issue).createdTs * 1000).format("LLL") }}</span- >- <h2 class="textlabel flex items-center col-span-1 col-start-1">- {{ $t("common.creator") }}- </h2>- <ul class="col-span-2">- <li class="flex justify-start items-center space-x-2">- <div class="flex-shrink-0">- <PrincipalAvatar- :principal="(issue as Issue).creator"- :size="'SMALL'"- />- </div>- <router-link- :to="`/u/${(issue as Issue).creator.id}`"- class="text-sm font-medium text-main hover:underline"- >- {{ (issue as Issue).creator.name }}- </router-link>- </li>- </ul>- </template>- </div>- <IssueSubscriberPanel- v-if="!create"- :issue="(issue as Issue)"- @add-subscriber-id="(subscriberId) => addSubscriberId(subscriberId)"- @remove-subscriber-id="(subscriberId) => removeSubscriberId(subscriberId)"- />- <FeatureModal- :open="state.showFeatureModal"- :feature="'bb.feature.task-schedule-time'"- :instance="database?.instanceEntity"- @cancel="state.showFeatureModal = false"- />- </aside>-</template>--<script lang="ts" setup>-import dayjs from "dayjs";-import isSameOrAfter from "dayjs/plugin/isSameOrAfter";-import { isEqual } from "lodash-es";-import { NDatePicker, NTooltip } from "naive-ui";-import { computed, PropType, reactive, ref, watch, watchEffect } from "vue";-import { useRouter } from "vue-router";-import { SQLEditorButtonV1 } from "@/components/DatabaseDetail";-import { InstanceV1EngineIcon } from "@/components/v2";-import { ProjectV1Name } from "@/components/v2";-import { InputField } from "@/plugins";-import {- featureToRef,- useCurrentUserV1,- useDatabaseV1Store,- useEnvironmentV1Store,- useProjectV1Store,-} from "@/store";-import {- ComposedDatabase,- Issue,- IssueCreate,- Task,- TaskId,- Stage,- StageCreate,- UNKNOWN_ID,- ComposedInstance,-} from "@/types";-import { User } from "@/types/proto/v1/auth_service";-import { Environment } from "@/types/proto/v1/environment_service";-import {- allTaskList,- hasWorkspacePermissionV1,- hidePrefix,- taskSlug,- extractDatabaseNameFromTask,- PRESET_LABEL_KEYS,- extractUserUID,- instanceV1Slug,- instanceV1Name,- environmentV1Slug,- environmentV1Name,- databaseV1Slug,-} from "@/utils";-import MemberSelect from "../MemberSelect.vue";-import PrincipalAvatar from "../PrincipalAvatar.vue";-import IssueStatusIcon from "./IssueStatusIcon.vue";-import IssueSubscriberPanel from "./IssueSubscriberPanel.vue";-import StageSelect from "./StageSelect.vue";-import TaskSelect from "./TaskSelect.vue";-import {- allowUserToBeAssignee,- allowUserToChangeAssignee,- useCurrentRollOutPolicyForActiveEnvironment,- useExtraIssueLogic,- useIssueLogic,-} from "./logic";-import { IssueReviewSidebarSection } from "./review";-import TaskRollbackView from "./rollback/TaskRollbackView.vue";--dayjs.extend(isSameOrAfter);--interface LocalState {- earliestAllowedTs: number | null;- showFeatureModal: boolean;-}--const props = defineProps({- database: {- type: Object as PropType<ComposedDatabase | undefined>,- default: undefined,- },- instance: {- required: true,- type: Object as PropType<ComposedInstance>,- },-});--const router = useRouter();-const projectV1Store = useProjectV1Store();--const {- create,- issue,- template,- isTenantMode,- selectedStage,- selectedTask,- selectStageOrTask,-} = useIssueLogic();-const {- updateEarliestAllowedTime,- updateAssigneeId,- updateCustomField,- addSubscriberId,- removeSubscriberId,-} = useExtraIssueLogic();--const allowEdit = computed(() => {- if (create.value) {- return true;- }- // For now, we only allow assignee to update the field when the issue- // is 'OPEN'. This reduces flexibility as creator must ask assignee to- // change any fields if there is typo. On the other hand, this avoids- // the trouble that the creator changes field value when the creator- // is performing the issue based on the old value.- // For now, we choose to be on the safe side at the cost of flexibility.- const issueEntity = issue.value as Issue;- const currentUserUID = extractUserUID(currentUserV1.value.name);- return (- issueEntity.status === "OPEN" &&- String(issueEntity.assignee?.id) === currentUserUID- );-});--const now = new Date();-const state = reactive<LocalState>({- earliestAllowedTs: selectedTask.value.earliestAllowedTs,- showFeatureModal: false,-});--watch(selectedTask, (cur) => {- // we show user local time- state.earliestAllowedTs = cur.earliestAllowedTs;-});--const currentUserV1 = useCurrentUserV1();--const fieldValue = <T = string>(field: InputField): T => {- return (issue.value.payload as Record<string, any>)[field.id] as T;-};--const databaseName = computed((): string | undefined => {- return extractDatabaseNameFromTask(selectedTask.value);-});--const environment = computed((): Environment => {- const environmentId = create.value- ? (selectedStage.value as StageCreate).environmentId- : (selectedStage.value as Stage).environment.id;-- return useEnvironmentV1Store().getEnvironmentByUID(String(environmentId));-});--const project = computed(() => {- const projectUID = create.value- ? (issue.value as IssueCreate).projectId- : (issue.value as Issue).project.id;- return projectV1Store.getProjectByUID(String(projectUID));-});--const assigneeId = computed(() => {- if (create.value) {- return String((issue.value as IssueCreate).assigneeId);- }- return String((issue.value as Issue).assignee.id);-});--const databaseEntity = ref<ComposedDatabase>();--const visibleLabelList = computed(() => {- // transform non-reserved labels to db properties- if (!props.database) return [];-- const labelList: { key: string; value: string }[] = [];- for (const key in props.database.labels) {- if (PRESET_LABEL_KEYS.includes(key)) {- const value = props.database.labels[key];- labelList.push({ key, value });- }- }- return labelList;-});--const showStageSelect = computed((): boolean => {- return (- !create.value && allTaskList((issue.value as Issue).pipeline!).length > 1- );-});--const showTaskSelect = computed((): boolean => {- if (create.value) {- return false;- }- const { taskList } = selectedStage.value;- return taskList.length > 1;-});--const allowManageInstance = computed((): boolean => {- return hasWorkspacePermissionV1(- "bb.permission.workspace.manage-instance",- currentUserV1.value.userRole- );-});--const allowEditAssignee = computed(() => {- if (create.value) {- return true;- }- return allowUserToChangeAssignee(currentUserV1.value, issue.value as Issue);-});--const allowEditEarliestAllowedTime = computed(() => {- if (create.value) {- return true;- }- // only the assignee is allowed to modify EarliestAllowedTime- const issueEntity = issue.value as Issue;- const task = selectedTask.value as Task;- const currentUserUID = extractUserUID(currentUserV1.value.name);- return (- issueEntity.status === "OPEN" &&- (task.status === "PENDING" || task.status === "PENDING_APPROVAL") &&- currentUserUID === String(issueEntity.assignee.id)- );-});--const allowEditCustomField = (field: InputField) => {- return allowEdit.value && (create.value || field.allowEditAfterCreation);-};--const trySaveCustomField = (field: InputField, value: string | boolean) => {- if (!isEqual(value, fieldValue(field))) {- updateCustomField(field, value);- }-};--const isDatabaseCreated = computed(() => {- const stage = selectedStage.value as Stage;- if (stage.taskList[0].type == "bb.task.database.create") {- if (create.value) {- return false;- }- return stage.taskList[0].status == "DONE";- }- return true;-});--// We only show creation label for database create task-const showDatabaseCreationLabel = computed(() => {- const stage = selectedStage.value as Stage;- if (stage.taskList[0].type !== "bb.task.database.create") {- return "";- }- return isDatabaseCreated.value ? "(created)" : "(pending create)";-});--const clickDatabase = () => {- // If the database has not been created yet, do nothing- if (props.database) {- router.push({- name: "workspace.database.detail",- params: {- databaseSlug: databaseV1Slug(props.database),- },- });- } else {- useDatabaseV1Store()- .getOrFetchDatabaseByName(- `${props.instance.name}/databases/${databaseName.value!}`- )- .then((database) => {- router.push({- name: "workspace.database.detail",- params: {- databaseSlug: databaseV1Slug(database),- },- });- });- }-};--watchEffect(() => {- if (props.database) {- databaseEntity.value = props.database;- } else {- const name = databaseName.value;- if (name) {- const existed = useDatabaseV1Store().getDatabaseByName(- `${props.instance.name}/databases/${name}`- );- if (existed && existed.uid !== String(UNKNOWN_ID)) {- databaseEntity.value = existed;- } else {- databaseEntity.value = undefined;- }- } else {- databaseEntity.value = undefined;- }- }-});--const isDayPassed = (ts: number) => !dayjs(ts).isSameOrAfter(now, "day");--const hasInstanceFeature = featureToRef(- "bb.feature.task-schedule-time",- props.database?.instanceEntity-);--const updateEarliestAllowedTs = (newTimestampMS: number) => {- if (!hasInstanceFeature.value) {- state.showFeatureModal = true;- return;- }-- // n-date-picker would pass timestamp in millisecond.- // We divide it by 1000 to get timestamp in second- const newTs = newTimestampMS / 1000;- state.earliestAllowedTs = newTs;- updateEarliestAllowedTime(newTs);-};--const selectTaskId = (taskId: TaskId) => {- const taskList = (selectedStage.value as Stage).taskList;- const task = taskList.find((t) => t.id === taskId);- if (!task) return;- const slug = taskSlug(task.name, task.id);- const stage = selectedStage.value as Stage;- selectStageOrTask(stage.id as number, slug);-};-const rollOutPolicy = useCurrentRollOutPolicyForActiveEnvironment();-const filterUser = (user: User): boolean => {- return allowUserToBeAssignee(- user,- project.value,- project.value.iamPolicy,- rollOutPolicy.value.policy,- rollOutPolicy.value.assigneeGroup- );-};-</script>diff --git a/frontend/src/components/Issue/IssueStagePanel.vue b/frontend/src/components/Issue/IssueStagePanel.vuedeleted file mode 100644index f955a74723..0000000000--- a/frontend/src/components/Issue/IssueStagePanel.vue+++ /dev/null@@ -1,74 +0,0 @@-<template>- <div v-if="flattenTaskRunList.length > 0" class="space-y-4">- <template v-if="mode === 'single'">- <TaskRunTable :task-list="[task || stage.taskList[0]]" />- </template>- <template v-else-if="mode === 'merged'">- <TaskRunTable :task-list="stage.taskList" />- </template>- <template v-else>- <template v-for="(taskInStage, index) in stage.taskList" :key="index">- <div class="flex flex-row items-center space-x-1">- <heroicons-solid:arrow-narrow-right- v-if="stage.taskList.length > 1 && activeTask.id == taskInStage.id"- class="w-5 h-5 text-info"- />- <div v-if="stage.taskList.length > 1" class="textlabel">- <span v-if="stage.taskList.length > 1">- Step {{ index + 1 }} -- </span>- {{ taskInStage.name }}- </div>- </div>- <TaskRunTable :task-list="[taskInStage]" />- </template>- </template>- </div>-</template>--<script lang="ts" setup>-import { computed, Ref } from "vue";-import { Stage, Task, unknown } from "@/types";-import TaskRunTable from "./TaskRunTable.vue";-import { useIssueLogic } from "./logic";--type Mode = "normal" | "single" | "merged";--const {- selectedStage,- selectedTask,- isGhostMode,- isTenantMode,- isPITRMode,- activeTaskOfStage,-} = useIssueLogic();-const stage = selectedStage as Ref<Stage>;-const task = selectedTask as Ref<Task>;--const activeTask = computed((): Task => {- return activeTaskOfStage(stage.value);-});--/**- * normal mode: display multiple tables for each task in stage.taskList- * merged mode: merge all tasks' activities into one table- * single mode: show only selected task's activities- */-const mode = computed((): Mode => {- if (isGhostMode.value) return "merged";- if (isPITRMode.value) return "merged";- if (isTenantMode.value) return "single";- return "single";-});--const flattenTaskRunList = computed(() => {- if (mode.value === "single") {- return (task.value || stage.value.taskList[0] || unknown("TASK"))- .taskRunList;- }- if (mode.value === "merged" || mode.value === "normal") {- return stage.value.taskList.flatMap((task) => task.taskRunList);- }- return [];-});-</script>diff --git a/frontend/src/components/Issue/IssueStatusIcon.vue b/frontend/src/components/Issue/IssueStatusIcon.vuedeleted file mode 100644index dea07a1978..0000000000--- a/frontend/src/components/Issue/IssueStatusIcon.vue+++ /dev/null@@ -1,85 +0,0 @@-<template>- <span- class="flex items-center justify-center rounded-full select-none overflow-hidden"- :class="issueIconClass()"- >- <template v-if="issueStatus === `OPEN`">- <template v-if="taskStatus === 'RUNNING'">- <div class="flex h-2 w-2 relative overflow-visible">- <span- class="w-full h-full rounded-full z-0 absolute animate-ping-slow"- style="background-color: rgba(37, 99, 235, 0.5); /* bg-info/50 */"- aria-hidden="true"- ></span>- <span- class="w-full h-full rounded-full z-[1] bg-info"- aria-hidden="true"- ></span>- </div>- </template>- <span- v-else-if="taskStatus === 'FAILED'"- class="h-2 w-2 rounded-full text-center pb-6 font-normal text-base"- aria-hidden="true"- >!</span- >- <span- v-else- class="h-1.5 w-1.5 bg-info rounded-full"- aria-hidden="true"- ></span>- </template>- <template v-else-if="issueStatus === `DONE`">- <heroicons-solid:check class="w-4 h-4" />- </template>- <template v-else-if="issueStatus === `CANCELED`">- <heroicons-solid:minus class="w-5 h-5" />- </template>- </span>-</template>--<script lang="ts">-import { defineComponent, PropType } from "vue";-import { TaskStatus, IssueStatus } from "../../types";--type SizeType = "small" | "normal";--export default defineComponent({- name: "IssueStatusIcon",- props: {- issueStatus: {- required: true,- type: String as PropType<IssueStatus>,- },- // Specify taskStatus if we want to show the task specific status when issueStatus is OPEN.- taskStatus: {- type: String as PropType<TaskStatus>,- default: undefined,- },- size: {- type: String as PropType<SizeType>,- default: "normal",- },- },- setup(props) {- const issueIconClass = () => {- const iconClass = props.size === "normal" ? "w-5 h-5" : "w-4 h-4";- switch (props.issueStatus) {- case "OPEN":- if (props.taskStatus && props.taskStatus === "FAILED") {- return iconClass + " bg-error text-white";- }- return iconClass + " bg-white border-2 border-info text-info";- case "CANCELED":- return iconClass + " bg-white border-2 text-gray-400 border-gray-400";- case "DONE":- return iconClass + " bg-success text-white";- }- };-- return {- issueIconClass,- };- },-});-</script>diff --git a/frontend/src/components/Issue/IssueSubscriberPanel.vue b/frontend/src/components/Issue/IssueSubscriberPanel.vuedeleted file mode 100644index dd28144f18..0000000000--- a/frontend/src/components/Issue/IssueSubscriberPanel.vue+++ /dev/null@@ -1,115 +0,0 @@-<template>- <div- class="mt-6 border-t border-block-border pt-6 grid gap-y-4 gap-x-6 grid-cols-3"- >- <h2- class="textlabel flex items-center col-span-1 col-start-1 whitespace-nowrap"- >- {{ $t("issue.subscriber", subscriberList.length) }}- </h2>- <div v-if="subscriberList.length > 0" class="col-span-3 col-start-1">- <div class="flex space-x-1">- <template v-for="(subscriber, index) in subscriberList" :key="index">- <router-link- :to="`/u/${subscriber.subscriber.id}`"- class="hover:opacity-75"- >- <PrincipalAvatar- :principal="subscriber.subscriber"- :size="'SMALL'"- />- </router-link>- </template>- </div>- </div>- <button- type="button"- class="btn-normal items-center col-span-3 col-start-1"- @click.prevent="toggleSubscription"- >- <span class="w-full">- <heroicons-outline:ban- v-if="isCurrentUserSubscribed"- class="h-5 w-5 text-control inline -mt-0.5 mr-1"- />- <heroicons-solid:bell- v-else- class="h-5 w-5 text-control inline -mt-0.5 mr-1"- />- {{- isCurrentUserSubscribed- ? $t("issue.unsubscribe")- : $t("issue.subscribe")- }}- </span>- </button>- </div>-</template>--<script lang="ts">-import {- reactive,- PropType,- computed,- watchEffect,- defineComponent,-} from "vue";-import { useCurrentUser, useIssueSubscriberStore } from "@/store";-import { Issue, IssueSubscriber } from "../../types";-import PrincipalAvatar from "../PrincipalAvatar.vue";--// eslint-disable-next-line @typescript-eslint/no-empty-interface-interface LocalState {}--export default defineComponent({- name: "IssueSubscriberPanel",- components: { PrincipalAvatar },- props: {- issue: {- required: true,- type: Object as PropType<Issue>,- },- },- emits: ["add-subscriber-id", "remove-subscriber-id"],- setup(props, { emit }) {- const state = reactive<LocalState>({});- const issueSubscriberStore = useIssueSubscriberStore();-- const currentUser = useCurrentUser();-- const prepareSubscriberList = () => {- issueSubscriberStore.fetchSubscriberListByIssue(props.issue.id);- };-- watchEffect(prepareSubscriberList);-- const subscriberList = computed((): IssueSubscriber[] => {- return issueSubscriberStore.subscriberListByIssue(props.issue.id);- });-- const isCurrentUserSubscribed = computed((): boolean => {- for (const subscriber of subscriberList.value) {- if (currentUser.value.id == subscriber.subscriber.id) {- return true;- }- }- return false;- });-- const toggleSubscription = () => {- if (isCurrentUserSubscribed.value) {- emit("remove-subscriber-id", currentUser.value.id);- } else {- emit("add-subscriber-id", currentUser.value.id);- }- };-- return {- state,- subscriberList,- isCurrentUserSubscribed,- toggleSubscription,- };- },-});-</script>diff --git a/frontend/src/components/Issue/IssueTaskSDLPanel.vue b/frontend/src/components/Issue/IssueTaskSDLPanel.vuedeleted file mode 100644index c8291d832b..0000000000--- a/frontend/src/components/Issue/IssueTaskSDLPanel.vue+++ /dev/null@@ -1,307 +0,0 @@-<template>- <div v-if="!hasFeature('bb.feature.sql-review')">- <div class="flex space-x-4 flex-1">- <button- type="button"- class="btn-small py-0.5 inline-flex items-center text-accent"- @click.prevent="state.showFeatureModal = true"- >- 🎈{{ $t("sql-review.unlock-full-feature") }}- </button>- </div>- </div>- <div class="w-full">- <div- v-if="sdlState.loading"- class="h-20 flex flex-col items-center justify-center"- >- <BBSpin />- </div>- <template v-else-if="sdlState.detail">- <NTabs v-model:value="state.tab" class="mb-1">- <NTab name="diff" :disabled="!!sdlState.detail.error">- <div class="flex items-center gap-x-1">- {{ $t("issue.sdl.schema-change") }}- <NTooltip>- <template #trigger>- <heroicons:question-mark-circle class="w-4 h-4" />- </template>- <div class="whitespace-nowrap">- <span>{{ $t("issue.sdl.left-schema-may-change") }}</span>- <LearnMoreLink- url="https://www.bytebase.com/docs/change-database/state-based-migration/#caveats?source=console"- color="light"- class="ml-1"- />- </div>- </NTooltip>- </div>- </NTab>- <NTab name="statement" :disabled="!!sdlState.detail.error">- {{ $t("issue.sdl.generated-ddl-statements") }}- </NTab>- <NTab name="schema">- {{ $t("issue.sdl.full-schema") }}- </NTab>- </NTabs>-- <CodeDiff- v-if="state.tab === 'diff'"- :old-string="sdlState.detail.previousSDL"- :new-string="sdlState.detail.prettyExpectedSDL"- output-format="side-by-side"- data-label="bb-change-detail-code-diff-block"- />- <MonacoEditor- v-if="state.tab === 'statement'"- ref="editorRef"- class="w-full border h-auto max-h-[360px]"- data-label="bb-issue-sql-editor"- :value="sdlState.detail.diffDDL"- :readonly="true"- :auto-focus="false"- language="sql"- @ready="handleMonacoEditorReady"- />- <MonacoEditor- v-if="state.tab === 'schema'"- ref="editorRef"- class="w-full border h-auto max-h-[360px]"- data-label="bb-issue-sql-editor"- :value="sdlState.detail.expectedSDL"- :readonly="true"- :auto-focus="false"- :advices="markers"- language="sql"- @ready="handleMonacoEditorReady"- />- </template>- </div>- <FeatureModal- feature="bb.feature.sql-review"- :open="state.showFeatureModal"- @cancel="state.showFeatureModal = false"- />-</template>--<script lang="ts" setup>-import { NTabs, NTab, NTooltip } from "naive-ui";-import { CodeDiff } from "v-code-diff";-import { reactive, watch, computed, ref } from "vue";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import { sqlServiceClient } from "@/grpcweb";-import { useSilentRequest } from "@/plugins/silent-request";-import {- hasFeature,- pushNotification,- useChangeHistoryStore,- useDatabaseV1Store,-} from "@/store";-import { Task, TaskId } from "@/types";-import MonacoEditor from "../MonacoEditor";-import { useIssueLogic } from "./logic";-import { useSQLAdviceMarkers } from "./logic/useSQLAdviceMarkers";--type TabView = "diff" | "statement" | "schema";--type SDLDetail = {- error: string;- previousSDL: string;- prettyExpectedSDL: string;- expectedSDL: string;- diffDDL: string;-};--type SDLState = {- task: Task;- loading: boolean;- detail: SDLDetail | undefined;-};--interface LocalState {- showFeatureModal: boolean;- tab: TabView;-}--const databaseStore = useDatabaseV1Store();-const { selectedTask, selectedStatement } = useIssueLogic();--const state = reactive<LocalState>({- showFeatureModal: false,- tab: "diff",-});-const editorRef = ref<InstanceType<typeof MonacoEditor>>();--const useSDLState = () => {- const emptyState = (task: Task): SDLState => {- return {- task,- loading: true,- detail: undefined,- };- };-- const map = reactive(new Map<TaskId, SDLState>());-- const findLatestChangeHistoryId = (task: Task) => {- if (task.status !== "DONE") return undefined;- const list = task.taskRunList;- for (let i = list.length - 1; i >= 0; i--) {- const taskRun = list[i];- if (taskRun.status === "DONE") {- return taskRun.result.migrationId;- }- }- return undefined;- };-- const changeHistoryId = computed(() => {- const task = selectedTask.value as Task;- return findLatestChangeHistoryId(task);- });-- const fetchOngoingSDLDetail = async (- task: Task,- statement: string- ): Promise<SDLDetail | undefined> => {- if (!task.database) return undefined;- const database = await databaseStore.getOrFetchDatabaseByUID(- String(task.database.id)- );- const previousSDL = (- await databaseStore.fetchDatabaseSchema(- `${database.name}/schema`,- true // fetch SDL format- )- ).schema;- const expectedSDL = statement;-- const getSchemaDiff = async () => {- const { diff } = await databaseStore.diffSchema({- name: database.name,- schema: expectedSDL,- });- return diff ?? "";- };- const diffDDL = await useSilentRequest(getSchemaDiff);-- const { currentSchema, expectedSchema } = await sqlServiceClient.pretty({- engine: database.instanceEntity.engine,- currentSchema: previousSDL ?? "",- expectedSchema: expectedSDL ?? "",- });-- if (task.status === "DONE") {- throw new Error();- }-- return {- error: "",- previousSDL: currentSchema,- prettyExpectedSDL: expectedSchema,- expectedSDL,- diffDDL,- };- };-- const fetchSDLDetailFromChangeHistory = async (- task: Task,- changeHistoryId: string | undefined- ): Promise<SDLDetail | undefined> => {- if (!changeHistoryId) {- return undefined;- }- if (!task.database) return undefined;- const database = await databaseStore.getOrFetchDatabaseByUID(- String(task.database.id)- );- const history = await useChangeHistoryStore().fetchChangeHistory({- name: `${database.name}/changeHistories/${changeHistoryId}`,- sdlFormat: true,- });- // The latestChangeHistoryId might change during fetching the- // ChangeHistory.- // Should give up the result.- const latestChangeHistoryId = findLatestChangeHistoryId(task);- if (history.uid !== latestChangeHistoryId) {- throw new Error();- }- return {- error: "",- previousSDL: history.prevSchema,- prettyExpectedSDL: history.schema,- expectedSDL: history.schema,- diffDDL: history.statement,- };- };-- watch(- [- () => selectedTask.value as Task,- () => selectedStatement.value,- changeHistoryId,- ],- async ([task, statement, changeHistoryId]) => {- if (!map.has(task.id)) {- map.set(task.id, emptyState(task));- }- const finish = (detail?: SDLState["detail"]) => {- const state = map.get(task.id)!;- state.loading = false;- state.detail = detail;- };- try {- if (task.status === "DONE") {- const detail = await fetchSDLDetailFromChangeHistory(- task,- changeHistoryId- );- finish(detail);- } else {- const detail = await fetchOngoingSDLDetail(task, statement);- finish(detail);- }- } catch (err: any) {- // The task has been changed during the fetch- // The result is meaningless.- state.tab = "schema";- const message =- err.response?.data?.message ?? err.details ?? "Internal server error";-- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: message,- });- finish({- error: message,- diffDDL: "",- expectedSDL: statement,- previousSDL: "",- prettyExpectedSDL: "",- });- }- },- { immediate: true }- );-- return computed(() => {- const task = selectedTask.value as Task;- return map.get(task.id) ?? emptyState(task);- });-};--const sdlState = useSDLState();--const updateEditorHeight = () => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- editorRef.value?.setEditorContentHeight(contentHeight);-};--const handleMonacoEditorReady = () => {- updateEditorHeight();-};--const { markers } = useSQLAdviceMarkers();-</script>diff --git a/frontend/src/components/Issue/IssueTaskStatementPanel.vue b/frontend/src/components/Issue/IssueTaskStatementPanel.vuedeleted file mode 100644index 57b4db04b6..0000000000--- a/frontend/src/components/Issue/IssueTaskStatementPanel.vue+++ /dev/null@@ -1,755 +0,0 @@-<template>- <div- class="flex flex-col md:flex-row md:justify-between md:items-center gap-2 md:gap-4"- >- <div class="flex items-center space-x-4 flex-1">- <div class="flex items-center gap-x-1 text-sm font-medium">- <span- :class="- isEmpty(state.editStatement) ? 'text-red-600' : 'text-control'- "- >- <template v-if="language === 'sql'">- {{ $t("common.sql") }}- </template>- <template v-else>- {{ $t("common.statement") }}- </template>- </span>- <span v-if="create" class="text-red-600">*</span>- <NButton- v-if="!create && !hasFeature('bb.feature.sql-review')"- size="tiny"- @click.prevent="state.showFeatureModal = true"- >- 🎈{{ $t("sql-review.unlock-full-feature") }}- </NButton>- <span v-if="sqlHint && !readonly" class="text-accent">{{- `(${sqlHint})`- }}</span>- </div>- <NButton- v-if="create && allowApplyTaskStateToOthers"- :disabled="isEmpty(state.editStatement)"- size="tiny"- @click.prevent="applyTaskStateToOthers(selectedTask as TaskCreate)"- >- {{ $t("issue.apply-to-other-tasks") }}- </NButton>- </div>-- <div class="space-x-2 flex items-center">- <template v-if="create || state.editing">- <NCheckbox- v-if="allowFormatOnSave"- v-model:checked="formatOnSave"- size="small"- >- {{ $t("issue.format-on-save") }}- </NCheckbox>-- <UploadProgressButton- :upload="create ? handleUploadFile : handleUploadAndOverwrite"- size="tiny"- >- {{ $t("issue.upload-sql") }}- </UploadProgressButton>- </template>-- <template v-if="shouldShowStatementEditButtonForUI">- <!-- for small size sheets, show full featured UI editing button group -->- <NButton- v-if="!isTaskSheetOversize"- size="tiny"- @click.prevent="beginEdit"- >- {{ $t("common.edit") }}- </NButton>- <!-- for oversized sheets, only allow to upload and overwrite the sheet -->- <UploadProgressButton- v-else- :upload="handleUploadAndOverwrite"- size="tiny"- >- {{ $t("issue.upload-sql") }}- </UploadProgressButton>- </template>-- <template v-else-if="!create">- <NButton- v-if="state.editing"- size="tiny"- :disabled="!allowSaveSQL"- @click.prevent="saveEdit"- >- {{ $t("common.save") }}- </NButton>- <NButton- v-if="state.editing"- size="tiny"- quaternary- @click.prevent="cancelEdit"- >- {{ $t("common.cancel") }}- </NButton>- </template>- </div>- </div>- <label class="sr-only">{{ $t("common.sql-statement") }}</label>- <BBAttention- v-if="isTaskSheetOversize"- :class="'my-2'"- :style="`WARN`"- :title="$t('issue.statement-from-sheet-warning')"- >- <template v-if="state.taskSheetName" #action>- <DownloadSheetButton :sheet="state.taskSheetName" size="small" />- </template>- </BBAttention>- <div- class="whitespace-pre-wrap mt-2 w-full overflow-hidden"- :class="state.editing ? 'border-t border-x' : 'border-t border-x'"- >- <MonacoEditor- ref="editorRef"- class="w-full h-auto max-h-[360px] min-h-[120px]"- data-label="bb-issue-sql-editor"- :value="state.editStatement"- :readonly="readonly"- :auto-focus="false"- :language="language"- :dialect="dialect"- :advices="readonly ? markers : []"- @change="onStatementChange"- @ready="handleMonacoEditorReady"- />- </div>-- <FeatureModal- feature="bb.feature.sql-review"- :open="state.showFeatureModal"- @cancel="state.showFeatureModal = false"- />-</template>--<script lang="ts" setup>-import { useDialog, NButton, NCheckbox } from "naive-ui";-import { onMounted, reactive, watch, computed, ref, nextTick } from "vue";-import { useI18n } from "vue-i18n";-import {- hasFeature,- pushNotification,- useDBSchemaV1Store,- useUIStateStore,- useSheetV1Store,- useDatabaseV1Store,-} from "@/store";-import {- ComposedDatabase,- dialectOfEngineV1,- Issue,- SQLDialect,- Task,- TaskCreate,- TaskId,- UNKNOWN_ID,-} from "@/types";-import { TableMetadata } from "@/types/proto/store/database";-import {- Sheet_Visibility,- Sheet_Source,- Sheet_Type,-} from "@/types/proto/v1/sheet_service";-import {- extractSheetUID,- sheetNameOfTask,- useInstanceV1EditorLanguage,-} from "@/utils";-import MonacoEditor from "../MonacoEditor/MonacoEditor.vue";-import DownloadSheetButton from "../Sheet/DownloadSheetButton.vue";-import UploadProgressButton from "../misc/UploadProgressButton.vue";-import { isGroupingChangeIssue, useIssueLogic } from "./logic";-import { useSQLAdviceMarkers } from "./logic/useSQLAdviceMarkers";--interface LocalState {- taskSheetName?: string;- editing: boolean;- editStatement: string;- isUploadingFile: boolean;- showFeatureModal: boolean;-}--type LocalEditState = Pick<LocalState, "editing" | "editStatement">;--const EDITOR_MIN_HEIGHT = 120; // ~= 6 lines, a reasonable size to start writing SQL--defineProps({- sqlHint: {- required: false,- type: String,- default: undefined,- },-});--const {- create,- issue,- allowEditStatement,- selectedDatabase,- selectedStatement: statement,- selectedTask,- updateStatement,- updateSheetId,- allowApplyTaskStateToOthers,- applyTaskStateToOthers,-} = useIssueLogic();--const { t } = useI18n();-const overwriteSQLDialog = useDialog();-const uiStateStore = useUIStateStore();-const dbSchemaStore = useDBSchemaV1Store();-const sheetV1Store = useSheetV1Store();-const editorRef = ref<InstanceType<typeof MonacoEditor>>();--const state = reactive<LocalState>({- editing: false,- editStatement: statement.value,- isUploadingFile: false,- showFeatureModal: false,-});--const useTempEditState = (state: LocalState) => {- const { create, selectedTask, selectedStatement } = useIssueLogic();-- let stopWatching: (() => void) | null = null;-- const startWatching = () => {- const tempEditStateMap = new Map<TaskId, LocalEditState>();- const isSwitchingTask = ref(false);-- // The issue page is polling the issue entity, making the reference obj- // of `selectedTask` changes every time.- // So we need to watch the id instead of the object ref.- const selectedTaskId = computed(() => {- if (create.value) return UNKNOWN_ID;- return (selectedTask.value as Task).id;- });-- watch(selectedTaskId, () => {- isSwitchingTask.value = true;- nextTick(() => {- isSwitchingTask.value = false;- });- });-- const handleEditChange = () => {- // When we are switching between tasks, this will also be triggered.- // But we shouldn't update the temp store.- if (isSwitchingTask.value) {- return;- }- // Save the temp edit state before switching task.- tempEditStateMap.set(selectedTaskId.value, {- editing: state.editing,- editStatement: state.editStatement,- });- };-- const afterTaskIdChange = (id: TaskId) => {- // Try to restore the saved temp edit state after switching task.- const storedState = tempEditStateMap.get(id);- if (storedState) {- // If found the stored temp edit state, restore it.- Object.assign(state, storedState);- } else {- // Restore to the task's default state otherwise.- state.editing = false;- state.editStatement = selectedStatement.value;- }- };-- // Save the temp editing state before switching tasks- const stopWatchBeforeChange = watch(- [() => state.editing, () => state.editStatement],- handleEditChange,- { immediate: true }- );- const stopWatchAfterChange = watch(- selectedTaskId,- (id) => {- afterTaskIdChange(id);- },- { flush: "post" } // Listen to the event AFTER selectedTaskId changed- );-- return () => {- tempEditStateMap.clear();- stopWatchBeforeChange();- stopWatchAfterChange();- };- };-- watch(- create,- () => {- if (!create.value) {- // If we are opening an existed issue, we should listen and store the- // temp editing states.- stopWatching = startWatching();- } else {- // If we are creating an issue, we don't need the temp editing state- // feature since all tasks are still in editing mode.- stopWatching && stopWatching();- }- },- { immediate: true }- );-- const reset = () => {- stopWatching && stopWatching();-- if (!create.value) {- stopWatching = startWatching();- }- };-- return reset;-};--const resetTempEditState = useTempEditState(state);--const getOrFetchSheetStatementByName = async (- sheetName: string | undefined-) => {- if (!sheetName) {- return "";- }- const sheet = await sheetV1Store.getOrFetchSheetByName(sheetName);- if (!sheet) {- return "";- }- return new TextDecoder().decode(sheet.content);-};--/**- * to set the MonacoEditor as readonly- * This happens when- * - Not in edit mode- * - Disallowed to edit statement- */-const readonly = computed(() => {- return (- !state.editing ||- !allowEditStatement.value ||- isTaskSheetOversize.value ||- isGroupingChangeIssue(issue.value as Issue)- );-});--const { markers } = useSQLAdviceMarkers();--const language = useInstanceV1EditorLanguage(- computed(() => selectedDatabase.value?.instanceEntity)-);--const dialect = computed((): SQLDialect => {- const db = selectedDatabase.value;- return dialectOfEngineV1(db?.instanceEntity.engine);-});--const formatOnSave = computed({- get: () => uiStateStore.issueFormatStatementOnSave,- set: (value: boolean) => uiStateStore.setIssueFormatStatementOnSave(value),-});--const allowFormatOnSave = computed(() => language.value === "sql");--const isValidSheetName = computed(() => {- if (!state.taskSheetName) {- return false;- }- return extractSheetUID(state.taskSheetName) !== String(UNKNOWN_ID);-});--const isTaskSheetOversize = computed(() => {- if (!isValidSheetName.value) {- return false;- }-- const taskSheet = sheetV1Store.getSheetByName(state.taskSheetName!);- if (!taskSheet) {- return false;- }- return (- new TextDecoder().decode(taskSheet.content).length < taskSheet.contentSize- );-});--const shouldShowStatementEditButtonForUI = computed(() => {- // Need not to show "Edit" while the issue is still pending create.- if (create.value) {- return false;- }- // Will show another button group as [Upload][Cancel][Save]- // while editing- if (state.editing) {- return false;- }- // If the task or issue's statement is not allowed to be change.- if (!allowEditStatement.value) {- return false;- }- // Not allowed to change statement while grouping.- if (isGroupingChangeIssue(issue.value as Issue)) {- return false;- }-- return true;-});--onMounted(async () => {- if (create.value) {- state.editing = true;- } else {- const sheetName = sheetNameOfTask(selectedTask.value as Task);- if (sheetName) {- state.taskSheetName = sheetName;- }- }-});--// Reset the edit state after creating the issue.-watch(create, (curNew, prevNew) => {- if (!curNew && prevNew) {- if (formatOnSave.value) {- editorRef.value?.formatEditorContent();- }- state.editing = false;- updateEditorHeight();- }-});--watch(statement, (cur) => {- state.editStatement = cur;-});--watch(- selectedTask,- async () => {- const task = selectedTask.value;-- // TODO: remove legacy logic.- let sheetName;- if (create.value) {- const taskCreate = task as TaskCreate;- if (taskCreate.databaseId) {- const db = await useDatabaseV1Store().getOrFetchDatabaseByUID(- String(taskCreate.databaseId)- );- sheetName = `${db.project}/sheets/${taskCreate.sheetId}`;- }- } else {- sheetName = sheetNameOfTask(task as Task);- }-- if (sheetName) {- state.taskSheetName = sheetName;- } else {- state.taskSheetName = undefined;- }- },- {- immediate: true,- deep: true,- }-);--watch(- () => state.taskSheetName,- async () => {- if (isValidSheetName.value) {- state.editStatement = await getOrFetchSheetStatementByName(- state.taskSheetName- );- }- },- {- immediate: true,- }-);--const beginEdit = () => {- state.editing = true;-};--const saveEdit = async () => {- if (!selectedDatabase.value) {- return;- }- resetTempEditState();- if (allowFormatOnSave.value && formatOnSave.value) {- editorRef.value?.formatEditorContent();- }- await updateStatement(state.editStatement);- state.editing = false;-};--const handleUploadAndOverwrite = async (event: Event) => {- if (!selectedDatabase.value) {- return;- }- if (state.isUploadingFile) {- return;- }- try {- state.isUploadingFile = true;- await showOverwriteConfirmDialog();- const { filename, content: statement } = await handleUploadFileEvent(- event,- 100- );- const projectName = selectedDatabase.value.project;- // TODO: upload process- const sheet = await sheetV1Store.createSheet(projectName, {- title: filename,- content: new TextEncoder().encode(statement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- });-- resetTempEditState();- await updateSheetId(Number(extractSheetUID(sheet.name)));- if (selectedTask.value) {- updateEditorHeight();- }-- pushNotification({- module: "bytebase",- style: "INFO",- title: "File upload success",- });- } finally {- state.isUploadingFile = false;- state.editing = false;- }-};--const cancelEdit = async () => {- state.editStatement = await getOrFetchSheetStatementByName(- state.taskSheetName- );- state.editing = false;-};--const allowSaveSQL = computed((): boolean => {- if (state.editStatement === "") {- // Not allowed if the statement is empty.- return false;- }- if (state.editStatement === statement.value) {- // Not allowed if the statement is not modified.- return false;- }-- // Allowed to save otherwise- return true;-});--const showOverwriteConfirmDialog = () => {- return new Promise((resolve, reject) => {- // Show a confirm dialog before replacing if the editing statement is not empty.- overwriteSQLDialog.create({- positiveText: t("common.confirm"),- negativeText: t("common.cancel"),- title: t("issue.overwrite-current-statement"),- autoFocus: false,- closable: false,- maskClosable: false,- closeOnEsc: false,- onNegativeClick: () => {- reject();- },- onPositiveClick: () => {- resolve(undefined);- },- });- });-};--const handleUploadFile = async (event: Event, tick: (p: number) => void) => {- if (!selectedDatabase.value) {- return;- }- if (state.isUploadingFile) {- return;- }-- const readStatementFromUploadFileEvent = async () => {- state.isUploadingFile = true;- try {- const { content: statement } = await handleUploadFileEvent(event, 100);-- // Set statement to UI state for local editing.- // Postpone the sheet creation when the issue is really created.-- resetTempEditState();- await updateStatement(statement);- state.editing = false;- if (selectedTask.value) {- updateEditorHeight();- }- } finally {- state.isUploadingFile = false;- }- };-- if (state.editStatement) {- await showOverwriteConfirmDialog();- return readStatementFromUploadFileEvent();- }-- return readStatementFromUploadFileEvent();-};--const handleUploadFileEvent = (- event: Event,- maxFileSizeMB: number-): Promise<{- filename: string;- content: string;-}> => {- return new Promise((resolve, reject) => {- const target = event.target as HTMLInputElement;- const file = (target.files || [])[0];- const cleanup = () => {- // Note that once selected a file, selecting the same file again will not- // trigger <input type="file">'s change event.- // So we need to do some cleanup stuff here.- target.files = null;- target.value = "";- };-- if (!file) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "File not found",- });- cleanup();- reject();- return;- }- if (file.size > maxFileSizeMB * 1024 * 1024) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("issue.upload-sql-file-max-size-exceeded", {- size: `${maxFileSizeMB}MB`,- }),- });- cleanup();- reject();- return;- }-- const fr = new FileReader();- fr.onload = async () => {- const content = fr.result as string;- resolve({- filename: file.name,- content: content,- });- };- fr.onerror = () => {- pushNotification({- module: "bytebase",- style: "WARN",- title: "Read file error",- description: String(fr.error),- });- reject();- };- fr.readAsText(file);- cleanup();- });-};--const onStatementChange = (value: string) => {- if (readonly.value) {- return;- }-- state.editStatement = value;- if (create.value) {- // If we are creating an issue, emit the event immediately when every- // time the user types.- updateStatement(state.editStatement);- }-};--// Handle and update monaco editor auto completion context.-const useDatabaseAndTableList = () => {- const { selectedDatabase } = useIssueLogic();-- const databaseList = computed(() => {- if (selectedDatabase.value) return [selectedDatabase.value];- return [];- });-- watch(- databaseList,- (list) => {- list.forEach((db) => {- if (db.uid !== String(UNKNOWN_ID)) {- dbSchemaStore.getOrFetchDatabaseMetadata(db.name);- }- });- },- { immediate: true }- );-- const tableList = computed(() => {- return databaseList.value- .map((item) => dbSchemaStore.getTableList(item.name))- .flat();- });-- return { databaseList, tableList };-};--const { databaseList, tableList } = useDatabaseAndTableList();--const handleUpdateEditorAutoCompletionContext = async () => {- const databaseMap: Map<ComposedDatabase, TableMetadata[]> = new Map();- for (const database of databaseList.value) {- const tableList = await dbSchemaStore.getOrFetchTableList(database.name);- databaseMap.set(database, tableList);- }- editorRef.value?.setEditorAutoCompletionContextV1(databaseMap);-};--const updateEditorHeight = () => {- requestAnimationFrame(() => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- let actualHeight = contentHeight;- if (actualHeight < EDITOR_MIN_HEIGHT) {- actualHeight = EDITOR_MIN_HEIGHT;- }- editorRef.value?.setEditorContentHeight(actualHeight);- });-};--const handleMonacoEditorReady = () => {- handleUpdateEditorAutoCompletionContext();- updateEditorHeight();-};--watch([databaseList, tableList], () => {- handleUpdateEditorAutoCompletionContext();-});--watch(() => state.editing, updateEditorHeight);-watch(() => state.editStatement, updateEditorHeight);-</script>diff --git a/frontend/src/components/Issue/PipelineGhostFlow.vue b/frontend/src/components/Issue/PipelineGhostFlow.vuedeleted file mode 100644index b055426936..0000000000--- a/frontend/src/components/Issue/PipelineGhostFlow.vue+++ /dev/null@@ -1,197 +0,0 @@-<template>- <div class="divide-y relative">- <PipelineStageList />-- <div class="relative">- <div- ref="taskBar"- class="task-list gap-2 p-2 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 4xl:grid-cols-6 max-h-48 overflow-y-auto"- :class="{- 'more-bottom': taskBarScrollState.bottom,- 'more-top': taskBarScrollState.top,- }"- >- <template v-for="(task, i) in taskList" :key="i">- <div- class="task relative px-2 py-1 cursor-pointer border rounded lg:flex-1 flex justify-between items-center"- :class="taskClass(task)"- :data-task-id="create ? '' : (task as Task).id"- @click="onClickTask(task, i)"- >- <div class="flex-1 overflow-x-hidden">- <div class="flex items-center pb-1">- <div class="flex flex-1 items-center gap-x-1 overflow-x-hidden">- <TaskStatusIcon- :create="create"- :active="isActiveTask(task)"- :status="task.status"- :task="task"- class="transform scale-75"- />- <div class="name flex-1 space-x-1 overflow-x-hidden">- <heroicons-solid:arrow-narrow-right- v-if="isActiveTask(task)"- class="w-5 h-5 inline-block"- />- <span>{{ databaseOfTask(task).databaseName }}</span>- </div>- </div>-- <TaskExtraActionsButton :task="(task as Task)" />- </div>-- <div class="flex items-center justify-between px-1 py-1">- <div- class="flex flex-1 items-center whitespace-pre-wrap break-all"- >- {{ taskNameOfTask(task) }}- </div>- </div>- </div>-- <TaskProgressPie- v-if="- !create &&- task.type === 'bb.task.database.schema.update.ghost.sync'- "- :task="(task as Task)"- unit-key="row"- />-- <div- v-if="task.type === 'bb.task.database.schema.update.ghost.sync'"- class="hidden md:flex items-center justify-center w-4 h-2 overflow-visible absolute -right-[13px]"- >- <!-- show an arrow indicator between tasks -->- <heroicons-outline:chevron-right class="w-4 h-4" />- </div>- </div>- </template>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useVerticalScrollState } from "@/composables/useScrollState";-import { useDatabaseV1Store } from "@/store";-import type { Pipeline, Stage, StageCreate, Task, TaskCreate } from "@/types";-import { activeTask, taskSlug } from "@/utils";-import PipelineStageList from "./PipelineStageList.vue";-import { TaskExtraActionsButton } from "./StatusTransitionButtonGroup";-import TaskProgressPie from "./TaskProgressPie.vue";-import TaskStatusIcon from "./TaskStatusIcon.vue";-import { useIssueLogic } from "./logic";--const { t } = useI18n();-const databaseStore = useDatabaseV1Store();--const { create, issue, selectedStage, selectedTask, selectStageOrTask } =- useIssueLogic();-const taskBar = ref<HTMLDivElement>();-const taskBarScrollState = useVerticalScrollState(taskBar, 192);--const pipeline = computed(() => issue.value.pipeline!);--const taskList = computed(() => {- return selectedStage.value.taskList;-});--const databaseOfTask = (task: Task | TaskCreate) => {- const uid = create.value- ? String((task as TaskCreate).databaseId!)- : String((task as Task).database!.id);- return databaseStore.getDatabaseByUID(uid);-};--const isSelectedTask = (task: Task | TaskCreate): boolean => {- return task === selectedTask.value;-};--const isActiveTask = (task: Task | TaskCreate): boolean => {- if (create.value) {- return false;- }- task = task as Task;- return activeTask(pipeline.value as Pipeline).id === task.id;-};--const taskNameOfTask = (task: Task | TaskCreate) => {- return t(`task.type.${task.type.replace(/\./g, "-")}`);-};--const selectedStageIdOrIndex = computed(() => {- if (!create.value) {- return (selectedStage.value as Stage).id;- }- return (pipeline.value.stageList as StageCreate[]).indexOf(- selectedStage.value as StageCreate- );-});--const taskClass = (task: Task | TaskCreate): string[] => {- const classes: string[] = [];- if (isSelectedTask(task)) classes.push("selected");- if (isActiveTask(task)) classes.push("active");- if (create.value) classes.push("create");- classes.push(`status_${task.status.toLowerCase()}`);- return classes;-};--const onClickTask = (task: Task | TaskCreate, index: number) => {- const stageId = selectedStageIdOrIndex.value;- const taskName = task.name;- const taskId = create.value ? index + 1 : (task as Task).id;- const ts = taskSlug(taskName, taskId);-- selectStageOrTask(Number(stageId), ts);-};-</script>--<style scoped lang="postcss">-.task.selected {- @apply border-info;-}-.task .name {- @apply whitespace-pre-wrap break-all;-}-.task.active .name {- @apply font-bold;-}-.task.status_done .name {- @apply text-control;-}-.task.status_pending .name,-.task.status_pending_approval .name {- @apply text-control;-}-.task.active.status_pending .name,-.task.active.status_pending_approval .name {- @apply text-info;-}-.task.status_running .name {- @apply text-info;-}-.task.status_failed .name {- @apply text-red-500;-}--.task-list::before {- @apply absolute top-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;- content: "";- box-shadow: none;-}-.task-list::after {- @apply absolute bottom-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;- content: "";- box-shadow: none;-}-.task-list.more-top::before {- box-shadow: inset 0 0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);-}-.task-list.more-bottom::after {- box-shadow: inset 0 -0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);-}-</style>diff --git a/frontend/src/components/Issue/PipelinePITRFlow.vue b/frontend/src/components/Issue/PipelinePITRFlow.vuedeleted file mode 100644index c7e943c107..0000000000--- a/frontend/src/components/Issue/PipelinePITRFlow.vue+++ /dev/null@@ -1,167 +0,0 @@-<template>- <div class="divide-y">- <PipelineStageList />-- <div- v-if="taskList.length > 1"- class="task-list p-2 lg:flex lg:items-center relative space-y-2 lg:space-y-0"- >- <template v-for="(task, i) in taskList" :key="i">- <div- class="task px-2 py-1 cursor-pointer border rounded lg:flex-1 flex justify-between items-center overflow-x-hidden"- :class="taskClass(task)"- :data-task-id="create ? '' : (task as Task).id"- @click="onClickTask(task, i)"- >- <div class="flex-1">- <div class="flex items-center pb-1">- <div class="flex flex-1 items-center gap-x-1">- <TaskStatusIcon- :create="create"- :active="isActiveTask(task)"- :status="task.status"- :task="task"- class="transform scale-75"- />- <div class="name flex-1 space-x-1 overflow-x-hidden">- <heroicons-solid:arrow-narrow-right- v-if="isActiveTask(task)"- class="w-5 h-5 inline-block"- />- <span>{{ databaseNameOfTask(task) }}</span>- </div>- </div>- <TaskExtraActionsButton :task="(task as Task)" />- </div>-- <div class="flex items-center justify-between px-1 py-1">- <div- class="flex flex-1 items-center whitespace-pre-wrap break-all"- >- {{ taskNameOfTask(task) }}- </div>- </div>- </div>-- <TaskProgressPie- v-if="- !create && task.type === 'bb.task.database.restore.pitr.restore'- "- :task="(task as Task)"- >- <template #unit="{ unit }">{{ bytesToString(unit) }}</template>- </TaskProgressPie>- </div>-- <div- v-if="i < taskList.length - 1"- class="hidden lg:flex items-center justify-center w-4 h-2 overflow-visible relative"- >- <!-- show an arrow indicator between tasks -->- <heroicons-outline:chevron-right class="w-4 h-4" />- </div>- </template>- </div>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { Pipeline, Stage, StageCreate, Task, TaskCreate } from "@/types";-import {- activeTask,- extractDatabaseNameFromTask,- taskSlug,- bytesToString,-} from "@/utils";-import PipelineStageList from "./PipelineStageList.vue";-import { TaskExtraActionsButton } from "./StatusTransitionButtonGroup";-import TaskStatusIcon from "./TaskStatusIcon.vue";-import { useIssueLogic } from "./logic";--const { create, issue, selectedStage, selectedTask, selectStageOrTask } =- useIssueLogic();--const pipeline = computed(() => issue.value.pipeline!);--const taskList = computed(() => {- return selectedStage.value.taskList;-});--const databaseNameOfTask = (task: Task | TaskCreate): string => {- return extractDatabaseNameFromTask(task);-};--const isSelectedTask = (task: Task | TaskCreate): boolean => {- return task === selectedTask.value;-};--const isActiveTask = (task: Task | TaskCreate): boolean => {- if (create.value) {- return false;- }- task = task as Task;- return activeTask(pipeline.value as Pipeline).id === task.id;-};--const taskNameOfTask = (task: Task | TaskCreate) => {- // return t(`task.type.${task.type.replace(/\./g, "-")}`);- return task.name;-};--const selectedStageIdOrIndex = computed(() => {- if (!create.value) {- return (selectedStage.value as Stage).id;- }- return (pipeline.value.stageList as StageCreate[]).indexOf(- selectedStage.value as StageCreate- );-});--const taskClass = (task: Task | TaskCreate): string[] => {- const classes: string[] = [];- if (isSelectedTask(task)) classes.push("selected");- if (isActiveTask(task)) classes.push("active");- if (create.value) classes.push("create");- classes.push(`status_${task.status.toLowerCase()}`);- return classes;-};--const onClickTask = (task: Task | TaskCreate, index: number) => {- const stageId = selectedStageIdOrIndex.value;- const taskName = task.name;- const taskId = create.value ? index + 1 : (task as Task).id;- const ts = taskSlug(taskName, taskId);-- selectStageOrTask(Number(stageId), ts);-};-</script>--<style scoped lang="postcss">-.task.selected {- @apply border-info;-}-.task .name {- @apply whitespace-pre-wrap break-all;-}-.task.active .name {- @apply font-bold;-}-.task.status_done .name {- @apply text-control;-}-.task.status_pending .name,-.task.status_pending_approval .name {- @apply text-control;-}-.task.active.status_pending .name,-.task.active.status_pending_approval .name {- @apply text-info;-}-.task.status_running .name {- @apply text-info;-}-.task.status_failed .name {- @apply text-red-500;-}-</style>diff --git a/frontend/src/components/Issue/PipelineSimpleFlow.vue b/frontend/src/components/Issue/PipelineSimpleFlow.vuedeleted file mode 100644index 88ac46f027..0000000000--- a/frontend/src/components/Issue/PipelineSimpleFlow.vue+++ /dev/null@@ -1,238 +0,0 @@-<template>- <div class="pipeline-standard-flow divide-y">- <PipelineStageList />-- <div v-if="shouldShowTaskBar" class="relative">- <div- ref="taskBar"- class="task-list gap-2 p-2 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 3xl:grid-cols-5 4xl:grid-cols-6 max-h-48 overflow-y-auto"- :class="{- 'more-bottom': taskBarScrollState.bottom,- 'more-top': taskBarScrollState.top,- }"- >- <template v-for="(task, i) in taskList" :key="i">- <div- class="task px-2 py-1 cursor-pointer border rounded lg:flex-1 justify-between items-center overflow-hidden"- :class="taskClass(task)"- :data-task-id="create ? '' : (task as Task).id"- @click="onClickTask(task, i)"- >- <div class="flex items-center pb-1">- <div class="flex items-center flex-1 gap-x-1">- <TaskStatusIcon- :create="create"- :active="isActiveTask(task)"- :status="task.status"- :task="task"- class="transform scale-75"- />- <div class="name flex-1 space-x-1 overflow-x-hidden">- <heroicons-solid:arrow-narrow-right- v-if="isActiveTask(task)"- class="w-5 h-5 inline-block"- />- <span>{{ databaseForTask(task).databaseName }}</span>- <span- v-if="schemaVersionForTask(task)"- class="schema-version"- >- ({{ schemaVersionForTask(task) }})- </span>- </div>- </div>- <TaskExtraActionsButton :task="(task as Task)" />- </div>- <div class="flex items-center justify-between px-1 py-1">- <div class="flex flex-1 items-center whitespace-pre-wrap">- <InstanceV1Name- :instance="databaseForTask(task).instanceEntity"- :link="false"- />- </div>- </div>- </div>- </template>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, ref } from "vue";-import { useVerticalScrollState } from "@/composables/useScrollState";-import { useDatabaseV1Store, useInstanceV1Store } from "@/store";-import {- Pipeline,- Stage,- StageCreate,- Task,- TaskCreate,- TaskDatabaseCreatePayload,- unknownDatabase,-} from "@/types";-import { TenantMode, Workflow } from "@/types/proto/v1/project_service";-import { taskSlug } from "@/utils";-import { InstanceV1Name } from "../v2";-import { TaskExtraActionsButton } from "./StatusTransitionButtonGroup";-import { useIssueLogic } from "./logic";--const {- create,- issue,- project,- selectedStage,- selectedTask,- activeTaskOfPipeline,- selectStageOrTask,-} = useIssueLogic();-const databaseStore = useDatabaseV1Store();--const taskBar = ref<HTMLDivElement>();-const taskBarScrollState = useVerticalScrollState(taskBar, 192);--const pipeline = computed(() => issue.value.pipeline!);--const taskList = computed(() => selectedStage.value.taskList);--// Show the task bar when some of the stages have more than one tasks.-const shouldShowTaskBar = computed(() => {- return pipeline.value.stageList.some((stage) => stage.taskList.length > 1);-});--const isSelectedTask = (task: Task | TaskCreate): boolean => {- return task === selectedTask.value;-};--const isActiveTask = (task: Task | TaskCreate): boolean => {- if (create.value) return false;- task = task as Task;- return activeTaskOfPipeline(pipeline.value as Pipeline).id === task.id;-};--const extractCoreDatabaseInfoFromDatabaseCreateTask = (task: Task) => {- const payload = task.payload as TaskDatabaseCreatePayload;- const { databaseName } = payload;- const instance = useInstanceV1Store().getInstanceByUID(- String(task.instance.id)- );- return {- name: `${instance.name}/databases/${databaseName}`,- databaseName,- instance: instance.name,- instanceEntity: instance,- project: project.value.name,- projectEntity: project.value,- };-};--const databaseForTask = (task: Task | TaskCreate) => {- const taskEntity = task as Task;- const taskCreate = task as TaskCreate;- if (create.value) {- return databaseStore.getDatabaseByUID(String(taskCreate.databaseId!));- }-- if (- task.type === "bb.task.database.create" ||- task.type === "bb.task.database.restore"- ) {- // The database is not created yet.- // extract database info from the task's and payload's properties.- return extractCoreDatabaseInfoFromDatabaseCreateTask(taskEntity);- } else if (taskEntity.database) {- return databaseStore.getDatabaseByUID(String(taskEntity.database.id));- }- return unknownDatabase();-};--const schemaVersionForTask = (task: Task | TaskCreate): string => {- // show the schema version for a task if- // the project is standard mode and VCS workflow- if (create.value) return "";- if (project.value.tenantMode === TenantMode.TENANT_MODE_ENABLED) return "";- if (project.value.workflow === Workflow.UI) return "";-- // The schema version is specified in the filename- // parsed and stored to the payload.schemaVersion- // fallback to empty if we can't read the field.- const payload: any = (task as Task).payload || {};- return payload.schemaVersion || "";-};--const taskClass = (task: Task | TaskCreate) => {- const classes: string[] = [];- if (isSelectedTask(task)) classes.push("selected");- if (isActiveTask(task)) classes.push("active");- if (create.value) classes.push("create");- classes.push(`status_${task.status.toLowerCase()}`);- return classes;-};--const selectedStageIdOrIndex = computed(() => {- if (!create.value) {- return (selectedStage.value as Stage).id;- }- return (pipeline.value.stageList as StageCreate[]).indexOf(- selectedStage.value as StageCreate- );-});--const onClickTask = (task: Task | TaskCreate, index: number) => {- const stageId = selectedStageIdOrIndex.value;- const taskName = task.name;- const taskId = create.value ? index + 1 : (task as Task).id;- const ts = taskSlug(taskName, taskId);-- selectStageOrTask(Number(stageId), ts);-};-</script>--<style scoped lang="postcss">-.task.selected {- @apply border-info;-}-.task .name {- @apply whitespace-pre-wrap break-all;-}-.task .schema-version {- @apply text-sm;-}-.task.active .name {- @apply font-bold;-}-.task.status_done .name {- @apply text-control;-}-.task.status_pending .name,-.task.status_pending_approval .name {- @apply text-control;-}-.task.active.status_pending .name,-.task.active.status_pending_approval .name {- @apply text-info;-}-.task.status_running .name {- @apply text-info;-}-.task.status_failed .name {- @apply text-red-500;-}--.task-list::before {- @apply absolute top-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;- content: "";- box-shadow: none;-}-.task-list::after {- @apply absolute bottom-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;- content: "";- box-shadow: none;-}-.task-list.more-top::before {- box-shadow: inset 0 0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);-}-.task-list.more-bottom::after {- box-shadow: inset 0 -0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);-}-</style>diff --git a/frontend/src/components/Issue/PipelineStageList.vue b/frontend/src/components/Issue/PipelineStageList.vuedeleted file mode 100644index 8ccb7e48c7..0000000000--- a/frontend/src/components/Issue/PipelineStageList.vue+++ /dev/null@@ -1,171 +0,0 @@-<template>- <div class="max-w-full lg:flex divide-y lg:divide-y-0">- <div- v-for="(stage, i) in issue.pipeline?.stageList"- :key="i"- class="stage-item"- :class="stageClass(stage, i)"- >- <TaskStatusIcon- :create="create"- :active="isActiveStage(stage)"- :status="taskStatusOfStage(stage, i)"- :ignore-task-check-status="true"- />-- <div class="text" @click.prevent="onClickStage(stage, i)">- <span class="text-sm min-w-32 lg:min-w-fit with-underline">- {{ $t("common.stage") }} - {{ stage.name }}- </span>- <span class="text-xs flex flex-col gap-1 md:flex-row md:items-center">- <slot name="task-name-of-stage" :stage="stage" :index="i">- <div class="whitespace-pre-wrap break-all with-underline">- {{ taskNameOfStage(stage) }}- </div>- <StageSummary :stage="(stage as Stage)" />- </slot>- </span>- </div>-- <NPopover v-if="!isValidStage(stage, i)" trigger="hover" placement="top">- <template #trigger>- <span- class="ml-2 w-5 h-5 flex justify-center rounded-full select-none bg-error text-white hover:bg-error-hover font-normal absolute right-3"- @click="onClickStage(stage, i)"- >- !- </span>- </template>- <span>Missing SQL statement</span>- </NPopover>-- <!-- Arrow separator -->- <div- v-if="i < issue.pipeline!.stageList.length - 1"- class="hidden lg:block absolute top-0 bottom-0 right-0 w-5 pointer-events-none"- aria-hidden="true"- >- <svg- class="h-full w-full text-gray-300"- viewBox="0 0 22 80"- fill="none"- preserveAspectRatio="none"- >- <path- d="M0 -2L20 40L0 82"- vector-effect="non-scaling-stroke"- stroke="currentcolor"- stroke-linejoin="round"- />- </svg>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { NPopover } from "naive-ui";-import { Issue, Stage, StageCreate } from "@/types";-import { activeTaskInStage } from "@/utils";-import StageSummary from "./StageSummary.vue";-import TaskStatusIcon from "./TaskStatusIcon.vue";-import { useIssueLogic } from "./logic";--const {- create,- issue,- selectedStage,- isValidStage,- activeTaskOfPipeline,- activeTaskOfStage,- taskStatusOfStage,- selectStageOrTask,-} = useIssueLogic();--const isSelectedStage = (stage: Stage | StageCreate): boolean => {- return stage === selectedStage.value;-};--const isActiveStage = (stage: Stage | StageCreate): boolean => {- if (create.value) {- // In create mode we don't have an ActiveStage- return false;- }-- const activeTask = activeTaskOfPipeline((issue.value as Issue).pipeline!);- const taskFound = (stage as Stage).taskList.find(- (t) => t.id === activeTask.id- );- if (taskFound) {- // A stage is "Active" if the ActiveTaskOfPipeline is inside this stage- return true;- }-- return false;-};--const stageClass = (stage: Stage | StageCreate, index: number): string[] => {- const classList: string[] = [];-- if (!isValidStage(stage, index)) classList.push("invalid");- if (create.value) classList.push("create");- if (isSelectedStage(stage)) classList.push("selected");- if (isActiveStage(stage)) classList.push("active");- const task = activeTaskOfStage(stage as Stage);- classList.push(`status_${task.status.toLowerCase()}`);-- return classList;-};--const taskNameOfStage = (stage: Stage | StageCreate) => {- if (create.value) {- return stage.taskList[0].status;- }- return activeTaskInStage(stage as Stage).name;-};--const onClickStage = (stage: Stage | StageCreate, index: number) => {- if (create.value) {- selectStageOrTask(index);- return;- }- selectStageOrTask(Number((stage as Stage).id));-};-</script>--<style scoped>-.stage-item {- @apply cursor-default flex items-center justify-start w-full px-4 py-2 text-sm font-medium relative;- @apply lg:w-auto lg:flex-1;-}-.stage-item.invalid {- @apply pr-10;-}--.stage-item .text {- @apply cursor-pointer ml-4 flex-col space-y-1;-}-.stage-item.selected .text .with-underline {- @apply underline;-}-.stage-item.active .text {- @apply font-bold;-}-.stage-item.status_done .text {- @apply text-control;-}-.stage-item.status_pending .text,-.stage-item.status_pending_approval .text {- @apply text-control;-}-.stage-item.active.status_pending .text,-.stage-item.active.status_pending_approval .text {- @apply text-info;-}-.stage-item.status_running .text {- @apply text-info;-}-.stage-item.status_failed .text {- @apply text-red-500;-}-</style>diff --git a/frontend/src/components/Issue/PipelineTenantFlow.vue b/frontend/src/components/Issue/PipelineTenantFlow.vuedeleted file mode 100644index 966bcbb969..0000000000--- a/frontend/src/components/Issue/PipelineTenantFlow.vue+++ /dev/null@@ -1,173 +0,0 @@-<template>- <div class="divide-y">- <PipelineStageList />-- <div class="relative">- <div- ref="taskBar"- class="task-list gap-2 p-2 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 3xl:grid-cols-5 4xl:grid-cols-6 max-h-48 overflow-y-auto"- :class="{- 'more-bottom': taskBarScrollState.bottom,- 'more-top': taskBarScrollState.top,- }"- >- <div- v-for="(task, j) in taskList"- :key="j"- class="task px-2 py-1 cursor-pointer border rounded"- :class="taskClass(task)"- :data-task-id="create ? '' : (task as Task).id"- @click="onClickTask(task, j)"- >- <div class="flex items-center justify-between pb-1">- <div class="flex flex-1 items-center gap-x-1">- <TaskStatusIcon- :create="create"- :active="isActiveTask(task)"- :status="task.status"- :task="task"- class="transform scale-75"- />- <div class="name flex-1 space-x-1 overflow-x-hidden">- <heroicons-solid:arrow-narrow-right- v-if="isActiveTask(task)"- class="w-5 h-5 inline-block"- />- <span- >{{ j + 1 }} - {{ databaseForTask(task).databaseName }}</span- >- </div>- </div>- <TaskExtraActionsButton :task="(task as Task)" />- </div>- <div class="flex items-center justify-between px-1 py-1">- <div class="flex flex-1 items-center whitespace-pre-wrap">- <InstanceV1EngineIcon- :instance="databaseForTask(task).instanceEntity"- />- <span- class="flex-1 ml-2 overflow-x-hidden whitespace-nowrap overflow-ellipsis"- >{{- instanceV1Name(databaseForTask(task).instanceEntity)- }}</span- >- </div>- </div>- </div>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, ref } from "vue";-import { useVerticalScrollState } from "@/composables/useScrollState";-import { useDatabaseV1Store } from "@/store";-import type { Pipeline, Stage, StageCreate, Task, TaskCreate } from "@/types";-import { activeTask, taskSlug, instanceV1Name } from "@/utils";-import { InstanceV1EngineIcon } from "../v2";-import { TaskExtraActionsButton } from "./StatusTransitionButtonGroup";-import TaskStatusIcon from "./TaskStatusIcon.vue";-import { useIssueLogic } from "./logic";--const { create, issue, selectedStage, selectedTask, selectStageOrTask } =- useIssueLogic();--const pipeline = computed(() => issue.value.pipeline!);--const databaseStore = useDatabaseV1Store();-const taskBar = ref<HTMLDivElement>();-const taskBarScrollState = useVerticalScrollState(taskBar, 192);--const taskList = computed(() => selectedStage.value.taskList);--const isSelectedTask = (task: Task | TaskCreate): boolean => {- return task === selectedTask.value;-};--const isActiveTask = (task: Task | TaskCreate): boolean => {- if (create.value) return false;- task = task as Task;- return activeTask(pipeline.value as Pipeline).id === task.id;-};--const databaseForTask = (task: Task | TaskCreate) => {- const uid = create.value- ? String((task as TaskCreate).databaseId!)- : String((task as Task).database!.id);- return databaseStore.getDatabaseByUID(uid);-};--const selectedStageIdOrIndex = computed(() => {- if (!create.value) {- return (selectedStage.value as Stage).id;- }- return (pipeline.value.stageList as StageCreate[]).indexOf(- selectedStage.value as StageCreate- );-});--const taskClass = (task: Task | TaskCreate) => {- const classes: string[] = [];- if (isSelectedTask(task)) classes.push("selected");- if (isActiveTask(task)) classes.push("active");- if (create.value) classes.push("create");- classes.push(`status_${task.status.toLowerCase()}`);- return classes;-};--const onClickTask = (task: Task | TaskCreate, index: number) => {- const stageId = selectedStageIdOrIndex.value;- const taskName = task.name;- const taskId = create.value ? index + 1 : (task as Task).id;- const ts = taskSlug(taskName, taskId);-- selectStageOrTask(stageId, ts);-};-</script>--<style scoped lang="postcss">-.task.selected {- @apply border-info;-}-.task .name {- @apply whitespace-pre-wrap break-all;-}-.task.active .name {- @apply font-bold;-}-.task.status_done .name {- @apply text-control;-}-.task.status_pending .name,-.task.status_pending_approval .name {- @apply text-control;-}-.task.active.status_pending .name,-.task.active.status_pending_approval .name {- @apply text-info;-}-.task.status_running .name {- @apply text-info;-}-.task.status_failed .name {- @apply text-red-500;-}--.task-list::before {- @apply absolute top-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;- content: "";- box-shadow: none;-}-.task-list::after {- @apply absolute bottom-0 h-4 w-full -ml-2 z-10 pointer-events-none transition-shadow;- content: "";- box-shadow: none;-}-.task-list.more-top::before {- box-shadow: inset 0 0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);-}-.task-list.more-bottom::after {- box-shadow: inset 0 -0.5rem 0.25rem -0.25rem rgb(0 0 0 / 10%);-}-</style>diff --git a/frontend/src/components/Issue/RunTaskCheckButton.vue b/frontend/src/components/Issue/RunTaskCheckButton.vuedeleted file mode 100644index 9ab1fdeec3..0000000000--- a/frontend/src/components/Issue/RunTaskCheckButton.vue+++ /dev/null@@ -1,105 +0,0 @@-<template>- <ContextMenuButton- v-if="actionList.length > 0"- :action-list="actionList"- :disabled="hasRunningTaskCheck"- preference-key="issue.task.run-checks"- default-action-key="RUN-CHECKS"- @click="$emit('run-checks', ($event as ButtonAction).params.taskList)"- >- <template #icon>- <BBSpin v-if="hasRunningTaskCheck" class="w-4 h-4" />- <heroicons-outline:play v-else class="w-4 h-4" />- </template>- <template #default="{ action }">- <template v-if="hasRunningTaskCheck">- {{ $t("task.checking") }}- </template>- <template v-else>- {{ action.text }}- </template>- </template>- </ContextMenuButton>-</template>--<script setup lang="ts">-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { Issue, Task } from "@/types";-import { ContextMenuButton, ContextMenuButtonAction } from "../v2";-import { useIssueLogic } from "./logic";--type ButtonAction = ContextMenuButtonAction<{- taskList: Task[];-}>;--defineEmits<{- (event: "run-checks", taskList: Task[]): void;-}>();--const { t } = useI18n();-const context = useIssueLogic();--const allowRunCheckForIssue = computed(() => {- if (context.create.value) {- return false;- }- const issue = context.issue.value as Issue;- if (issue.status !== "OPEN") {- return false;- }- return true;-});--const actionList = computed(() => {- if (!allowRunCheckForIssue.value) return [];-- const actionList: ButtonAction[] = [];- const selectedTask = context.selectedTask.value as Task;- if (allowRunChecksForTask(selectedTask)) {- actionList.push({- key: "RUN-CHECKS",- text: t("task.run-checks"),- params: {- taskList: [selectedTask],- },- });-- // Don't only show 'run checks in current stage' if we don't show 'run checks'- // since that might be weird.- const taskListInStage = context.selectedStage.value.taskList as Task[];- const runnableTaskList = taskListInStage.filter((task) =>- allowRunChecksForTask(task)- );- if (runnableTaskList.length > 1) {- actionList.push({- key: "RUN-CHECKS-IN-CURRENT-STAGE",- text: t("task.run-checks-in-current-stage"),- params: {- taskList: runnableTaskList,- },- });- }- }- return actionList;-});--const hasRunningTaskCheck = computed((): boolean => {- if (context.create.value) return false;-- const selectedTask = context.selectedTask.value as Task;-- return selectedTask.taskCheckRunList.some(- (checkRun) => checkRun.status === "RUNNING"- );-});--const allowRunChecksForTask = (task: Task) => {- return (- task.status == "PENDING" ||- task.status == "PENDING_APPROVAL" ||- task.status == "RUNNING" ||- task.status == "FAILED"- );-};-</script>diff --git a/frontend/src/components/Issue/StageSelect.vue b/frontend/src/components/Issue/StageSelect.vuedeleted file mode 100644index 36baa2ef20..0000000000--- a/frontend/src/components/Issue/StageSelect.vue+++ /dev/null@@ -1,67 +0,0 @@-<template>- <BBSelect- :selected-item="state.selectedStage"- :item-list="pipeline.stageList"- fit-width="min"- @select-item="(stage) => $emit('select-stage-id', stage.id)"- >- <template #menuItem="{ item: stage }">- {{- isActiveStage(stage.id)- ? $t("issue.stage-select.active", { name: stage.name })- : stage.name- }}- </template>- </BBSelect>-</template>--<script lang="ts">-import { defineComponent, PropType, reactive, watch } from "vue";-import { UNKNOWN_ID, Pipeline, StageId, Stage } from "../../types";-import { activeStage } from "../../utils";--interface LocalState {- selectedStage: Stage | undefined;-}--export default defineComponent({- name: "StageSelect",- props: {- pipeline: {- required: true,- type: Object as PropType<Pipeline>,- },- selectedId: {- default: UNKNOWN_ID,- type: Number,- },- },- emits: ["select-stage-id"],- setup(props) {- const state = reactive<LocalState>({- selectedStage: undefined,- });-- watch(- [() => props.selectedId, () => props.pipeline],-- ([selectedId, pipeline]) => {- state.selectedStage = pipeline.stageList.find(- (stage) => stage.id === selectedId- );- },- { immediate: true }- );-- const isActiveStage = (stageId: StageId): boolean => {- const stage = activeStage(props.pipeline);- return stage.id == stageId;- };-- return {- state,- isActiveStage,- };- },-});-</script>diff --git a/frontend/src/components/Issue/StageSummary.vue b/frontend/src/components/Issue/StageSummary.vuedeleted file mode 100644index 5afe1277fe..0000000000--- a/frontend/src/components/Issue/StageSummary.vue+++ /dev/null@@ -1,46 +0,0 @@-<template>- <div class="!no-underline">- <span class="!no-underline">(</span>- <span class="!no-underline">{{ summary.done + summary.canceled }}</span>- <span class="!no-underline">/</span>- <span class="!no-underline">{{ summary.total }}</span>- <span class="!no-underline">)</span>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import type { Stage } from "@/types";--const props = defineProps<{- stage: Stage;-}>();--const summary = computed(() => {- const { taskList } = props.stage;- const summary = {- done: 0,- failed: 0,- canceled: 0,- running: 0,- total: taskList.length,- };- taskList.forEach((task) => {- switch (task.status) {- case "DONE":- summary.done++;- break;- case "FAILED":- summary.failed++;- break;- case "CANCELED":- summary.canceled++;- break;- case "RUNNING":- summary.running++;- break;- }- });- return summary;-});-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/BatchTaskActionDialog.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/BatchTaskActionDialog.vuedeleted file mode 100644index c41f5cfc24..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/BatchTaskActionDialog.vue+++ /dev/null@@ -1,49 +0,0 @@-<template>- <BBModal- :title="title"- class="relative overflow-hidden"- @close="$emit('cancel')"- >- <BatchTaskActionForm- :issue="issue"- :transition="transition"- :task-list="taskList"- :ok-text="okText"- :title="title"- @cancel="$emit('cancel')"- @finish="$emit('updated')"- />- </BBModal>-</template>--<script setup lang="ts">-import { Ref, computed } from "vue";-import { useI18n } from "vue-i18n";-import { Issue, Task } from "@/types";-import { TaskStatusTransition } from "@/utils";-import { useIssueLogic } from "../logic";-import BatchTaskActionForm from "./BatchTaskActionForm.vue";--const props = defineProps<{- transition: TaskStatusTransition;- taskList: Task[];-}>();-defineEmits<{- (event: "updated"): void;- (event: "cancel"): void;-}>();--const { t } = useI18n();-const issueLogic = useIssueLogic();-const issue = issueLogic.issue as Ref<Issue>;--const okText = computed(() => {- return t(props.transition.buttonName);-});--const title = computed(() => {- return t("task.action-failed-in-current-stage", {- action: okText.value,- });-});-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/BatchTaskActionForm.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/BatchTaskActionForm.vuedeleted file mode 100644index 19c5d5edec..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/BatchTaskActionForm.vue+++ /dev/null@@ -1,230 +0,0 @@-<template>- <div class="px-4 flex flex-col gap-y-6 divide-y divide-block-border">- <div class="mt-2 grid grid-cols-1 gap-x-4 sm:grid-cols-4">- <div class="sm:col-span-4 mb-4">- <label for="about" class="textlabel">- {{ $t("common.tasks") }}- </label>- <ul class="mt-1 max-h-[6rem] overflow-y-auto">- <li- v-for="item in distinctTaskList"- :key="item.task.id"- class="text-sm textinfolabel"- >- <span class="textinfolabel">- {{ item.task.name }}- </span>- <span v-if="item.similar.length > 0" class="ml-2 text-gray-400">- {{- $t("task.n-similar-tasks", {- count: item.similar.length + 1,- })- }}- </span>- </li>- </ul>- </div>-- <div class="sm:col-span-4 w-112 min-w-full">- <label for="about" class="textlabel">- {{ $t("issue.status-transition.form.note") }}- </label>- <div class="mt-1">- <textarea- ref="commentTextArea"- v-model="state.comment"- rows="3"- class="textarea block w-full resize-none mt-1 text-sm text-control rounded-md whitespace-pre-wrap"- :placeholder="$t('issue.status-transition.form.placeholder')"- @input="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- @focus="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- ></textarea>- </div>- </div>- </div>-- <!-- Update button group -->- <div class="flex justify-end items-center pt-5">- <button- type="button"- class="btn-normal mt-3 px-4 py-2 sm:mt-0 sm:w-auto"- @click.prevent="$emit('cancel')"- >- {{ cancelText }}- </button>- <button- type="button"- class="ml-3 px-4 py-2"- :class="submitButtonStyle"- @click.prevent="handleSubmit"- >- {{ displayingOkText }}- </button>- </div>-- <div- v-if="state.loading"- class="absolute inset-0 flex flex-col items-center justify-center bg-white/50 gap-y-1"- >- <BBSpin />- <div- class="flex items-center justify-center space-x-1 text-sm text-control"- >- <span>{{ progress.finished }}</span>- <span>/</span>- <span>{{ progress.total }}</span>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { groupBy } from "lodash-es";-import { computed, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { pushNotification, useTaskStore } from "@/store";-import { Issue, Task, TaskStatusPatch } from "@/types";-import { TaskStatusTransition } from "@/utils";-import { useIssueLogic } from "../logic";--interface LocalState {- success: Set<Task>;- failed: Set<Task>;- comment: string;- loading: boolean;-}-const props = withDefaults(- defineProps<{- issue: Issue;- okText?: string;- taskList: Task[];- transition: TaskStatusTransition;- title: string;- }>(),- {- okText: "",- loading: false,- }-);--const emit = defineEmits<{- (event: "cancel"): void;- (event: "finish"): void;-}>();--const { t } = useI18n();-const commentTextArea = ref("");-const taskStore = useTaskStore();-const { onStatusChanged } = useIssueLogic();--const state = reactive<LocalState>({- success: new Set(),- failed: new Set(),- comment: "",- loading: false,-});--const progress = computed(() => {- const finished = state.success.size + state.failed.size;- const total = props.taskList.length;- return { finished, total };-});--const cancelText = computed(() => t("common.cancel"));-const displayingOkText = computed(() => {- if (props.okText === cancelText.value) {- // We don't want to see [Cancel] [Cancel]- // So fall back to [Cancel] [Confirm] if okText===cancelText- return t("common.confirm");- }- return props.okText;-});--const submitButtonStyle = computed(() => {- switch (props.transition.type) {- case "RUN":- return "btn-primary";- case "ROLLOUT":- return "btn-primary";- case "RETRY":- return "btn-primary";- case "CANCEL":- return "btn-danger";- case "SKIP":- return "btn-primary";- case "RESTART":- return "btn-normal";- }- return ""; // only to make eslint happy-});--const distinctTaskList = computed(() => {- type DistinctTaskList = { task: Task; similar: Task[] };- const groups = groupBy(props.taskList, (task) => task.name);-- return Object.keys(groups).map<DistinctTaskList>((taskName) => {- const [task, ...similar] = groups[taskName];- return { task, similar };- });-});--const patchTaskStatus = async (task: Task) => {- const status = props.transition.to;- const comment = state.comment;-- const taskStatusPatch: TaskStatusPatch = {- status,- comment,- };- try {- const { issue } = props;- await taskStore.updateStatus({- issueId: issue.id,- pipelineId: issue.pipeline!.id,- taskId: task.id,- taskStatusPatch,- });- state.success.add(task);- } catch {- state.failed.add(task);- }-};--const handleSubmit = async () => {- state.loading = true;- state.success.clear();- state.failed.clear();- try {- const requests = props.taskList.map(patchTaskStatus);- await Promise.allSettled(requests);- const parts = [`${t("common.total")}: ${props.taskList.length}`];- const successCount = state.success.size;- const failedCount = state.failed.size;- if (successCount > 0) {- parts.push(`${t("common.success")}: ${successCount}`);- }- if (failedCount > 0) {- parts.push(`${t("common.failed")}: ${failedCount}`);- }- pushNotification({- module: "bytebase",- style:- failedCount > 0 ? (successCount > 0 ? "WARN" : "CRITICAL") : "SUCCESS",- title: props.title,- description: parts.join(", "),- });- emit("finish");- } finally {- onStatusChanged(true);- state.loading = false;- }-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/CombinedRolloutButtonGroup.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/CombinedRolloutButtonGroup.vuedeleted file mode 100644index 6677639666..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/CombinedRolloutButtonGroup.vue+++ /dev/null@@ -1,309 +0,0 @@-<template>- <template v-if="create">- <button- type="button"- class="btn-primary px-4 py-2"- :disabled="!allowCreate"- data-label="bb-issue-create-button"- @click.prevent="doCreate"- >- {{ $t("common.create") }}- </button>- </template>- <template v-else>- <div class="flex space-x-2">- <TaskStatusTransitionButtonGroup- v-if="applicableTaskStatusTransitionList.length > 0"- :issue-context="issueContext"- :task-status-transition-list="applicableTaskStatusTransitionList"- :stage-status-transition-list="applicableStageStatusTransitionList"- @apply-task-transition="tryStartStageOrTaskStatusTransition"- />- <IssueStatusTransitionButtonGroup- :display-mode="- applicableTaskStatusTransitionList.length === 0- ? 'BUTTON'- : 'DROPDOWN'- "- :issue-context="issueContext"- :extra-action-list="extraActionList"- :issue-status-transition-list="issueStatusTransitionActionList"- @apply-issue-transition="tryStartIssueStatusTransition"- @apply-batch-task-transition="tryStartBatchTaskTransition"- />- </div>-- <TaskStatusTransitionDialog- v-if="onGoingTaskOrStageStatusTransition && currentTask"- :task="currentTask"- :mode="onGoingTaskOrStageStatusTransition.mode"- :transition="onGoingTaskOrStageStatusTransition.transition"- @updated="onGoingTaskOrStageStatusTransition = undefined"- @cancel="onGoingTaskOrStageStatusTransition = undefined"- />-- <IssueStatusTransitionDialog- v-if="onGoingIssueStatusTransition"- :transition="onGoingIssueStatusTransition.transition"- @updated="onGoingIssueStatusTransition = undefined"- @cancel="onGoingIssueStatusTransition = undefined"- />-- <BatchTaskActionDialog- v-if="onGoingBatchTaskStatusTransition"- :transition="onGoingBatchTaskStatusTransition.transition"- :task-list="onGoingBatchTaskStatusTransition.taskList"- @updated="onGoingBatchTaskStatusTransition = undefined"- @cancel="onGoingBatchTaskStatusTransition = undefined"- />- </template>-</template>--<script lang="ts" setup>-import { cloneDeep, isEmpty } from "lodash-es";-import { computed, ref, Ref } from "vue";-import { useI18n } from "vue-i18n";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { convertUserToPrincipal, useCurrentUserV1 } from "@/store";-import type {- GrantRequestContext,- Issue,- IssueCreate,- IssueStatusTransition,- Task,- TaskCreate,-} from "@/types";-import { UNKNOWN_ID } from "@/types";-import {- activeStage,- canSkipTask,- isDatabaseRelatedIssueType,- isGrantRequestIssueType,- StageStatusTransition,- TASK_STATUS_TRANSITION_LIST,- TaskStatusTransition,-} from "@/utils";-import {- flattenTaskList,- useIssueTransitionLogic,- TaskTypeWithStatement,- useIssueLogic,-} from "../logic";-import BatchTaskActionDialog from "./BatchTaskActionDialog.vue";-import IssueStatusTransitionButtonGroup from "./IssueStatusTransitionButtonGroup.vue";-import IssueStatusTransitionDialog from "./IssueStatusTransitionDialog.vue";-import TaskStatusTransitionButtonGroup from "./TaskStatusTransitionButtonGroup.vue";-import TaskStatusTransitionDialog from "./TaskStatusTransitionDialog.vue";-import { ExtraActionOption, IssueContext } from "./common";--const { t } = useI18n();--const {- create,- issue,- template: issueTemplate,- activeTaskOfPipeline,- doCreate,- allowApplyTaskStatusTransition,-} = useIssueLogic();--const onGoingIssueStatusTransition = ref<{- transition: IssueStatusTransition;-}>();-const onGoingTaskOrStageStatusTransition = ref<{- mode: "STAGE" | "TASK";- transition: TaskStatusTransition | StageStatusTransition;-}>();-const onGoingBatchTaskStatusTransition = ref<{- transition: TaskStatusTransition;- taskList: Task[];-}>();--const currentUser = useCurrentUserV1();--const issueReview = useIssueReviewContext();-const { done: reviewDone } = issueReview;--const issueContext = computed((): IssueContext => {- return {- currentUser: convertUserToPrincipal(currentUser.value),- create: create.value,- issue: issue.value,- };-});--const {- applicableTaskStatusTransitionList,- applicableStageStatusTransitionList,- applicableIssueStatusTransitionList,-} = useIssueTransitionLogic(issue as Ref<Issue>);--const issueStatusTransitionActionList = computed(() => {- const actionList = cloneDeep(applicableIssueStatusTransitionList.value);- const resolveActionIndex = actionList.findIndex(- (item) => item.type === "RESOLVE"- );- // Hide resolve button when grant request issue isn't review done.- if (isGrantRequestIssueType(issue.value.type) && resolveActionIndex > -1) {- if (!reviewDone.value) {- actionList.splice(resolveActionIndex, 1);- }- }- return actionList;-});--const retryableTaskList = computed(() => {- if (create.value) return [];-- const issueEntity = issue.value as Issue;- if (issueEntity.status !== "OPEN") {- return [];- }- if (!isDatabaseRelatedIssueType(issueEntity.type)) {- return [];- }-- const currentStage = activeStage(issueEntity.pipeline!);- const RETRY = TASK_STATUS_TRANSITION_LIST.get("RETRY")!;- return currentStage.taskList.filter((task) => {- return (- task.status === "FAILED" && allowApplyTaskStatusTransition(task, RETRY.to)- );- });-});--const skippableTaskList = computed(() => {- if (create.value) return [];-- const issueEntity = issue.value as Issue;- if (issueEntity.status !== "OPEN") {- return [];- }- if (!isDatabaseRelatedIssueType(issueEntity.type)) {- return [];- }-- const currentStage = activeStage(issueEntity.pipeline!);- return currentStage.taskList.filter((task) =>- canSkipTask(- task,- issueEntity,- false /* !activeOnly */,- true /* failedOnly */- )- );-});--const extraActionList = computed(() => {- const list: ExtraActionOption[] = [];-- if (skippableTaskList.value.length > 0) {- list.push({- label: t("task.skip-failed-in-current-stage"),- key: "skip-failed-tasks-in-current-stage",- type: "TASK-BATCH",- transition: {- buttonType: "PRIMARY",- buttonName: t("task.skip"),- type: "SKIP",- to: "DONE",- },- target: skippableTaskList.value,- });- }-- return list;-});--const tryStartBatchTaskTransition = (- transition: TaskStatusTransition,- taskList: Task[]-) => {- if (transition.type === "SKIP") {- onGoingBatchTaskStatusTransition.value = {- transition,- taskList,- };- }-};--const tryStartStageOrTaskStatusTransition = (- transition: TaskStatusTransition | StageStatusTransition,- mode: "STAGE" | "TASK"-) => {- if (transition.type === "RETRY" && mode === "STAGE") {- // RETRYing current stage won't use stage status transition API endpoint.- // Use batch task status transition instead.- const taskList = retryableTaskList.value;- onGoingBatchTaskStatusTransition.value = {- transition,- taskList,- };- return;- }-- onGoingTaskOrStageStatusTransition.value = {- mode,- transition,- };-};--const currentTask = computed(() => {- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return undefined;- }- return activeTaskOfPipeline((issue.value as Issue).pipeline!);-});--const tryStartIssueStatusTransition = (transition: IssueStatusTransition) => {- onGoingIssueStatusTransition.value = {- transition,- };-};--const allowCreate = computed(() => {- const newIssue = issue.value as IssueCreate;-- if (isEmpty(newIssue.name)) {- return false;- }-- if (newIssue.assigneeId == UNKNOWN_ID) {- return false;- }-- if (isDatabaseRelatedIssueType(newIssue.type)) {- const allTaskList = flattenTaskList<TaskCreate>(newIssue);- for (const task of allTaskList) {- if (TaskTypeWithStatement.includes(task.type)) {- if (- isEmpty(task.statement) &&- ((task as TaskCreate).sheetId === undefined ||- (task as TaskCreate).sheetId === UNKNOWN_ID)- ) {- return false;- }- }- }- } else if (isGrantRequestIssueType(newIssue.type)) {- const createContext = newIssue.createContext as GrantRequestContext;- if (createContext.role === "EXPORTER") {- return (- createContext.databaseResources.length > 0 &&- createContext.statement !== ""- );- }- }-- const template = issueTemplate.value;- for (const field of template.inputFieldList) {- if (- field.type !== "Boolean" && // Switch is boolean value which always is present- !field.resolved(issueContext.value)- ) {- return false;- }- }- return true;-});-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/IssueStatusTransitionButtonGroup.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/IssueStatusTransitionButtonGroup.vuedeleted file mode 100644index 34651d7bfa..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/IssueStatusTransitionButtonGroup.vue+++ /dev/null@@ -1,140 +0,0 @@-<template>- <div v-if="displayMode === 'BUTTON'" class="flex items-center gap-x-2">- <button- v-for="(transition, index) in issueStatusTransitionList"- :key="index"- type="button"- :class="transition.buttonClass"- :disabled="!allowIssueStatusTransition(transition)"- @click.prevent="$emit('apply-issue-transition', transition)"- >- {{ $t(transition.buttonName) }}- </button>- <NDropdown- v-if="extraActionList.length > 0"- trigger="click"- placement="bottom-end"- :options="extraActionList"- @select="handleDropdownSelect"- >- <button- id="user-menu"- type="button"- class="text-control-light p-0.5 rounded hover:bg-control-bg-hover"- aria-label="User menu"- aria-haspopup="true"- >- <heroicons-solid:dots-vertical class="w-6 h-6" />- </button>- </NDropdown>- </div>-- <NDropdown- v-if="displayMode === 'DROPDOWN' && mergedDropdownActionList.length > 0"- trigger="click"- placement="bottom-end"- :options="mergedDropdownActionList"- @select="handleDropdownSelect"- >- <button- id="user-menu"- type="button"- class="text-control-light p-0.5 rounded hover:bg-control-bg-hover"- aria-label="User menu"- aria-haspopup="true"- >- <heroicons-solid:dots-vertical class="w-6 h-6" />- </button>- </NDropdown>-</template>--<script setup lang="ts">-import { DropdownOption } from "naive-ui";-import { Ref, computed } from "vue";-import { useI18n } from "vue-i18n";-import { Issue, IssueStatusTransition, Task } from "@/types";-import { TaskStatusTransition } from "@/utils";-import { useIssueLogic } from "../logic";-import { ExtraActionOption, IssueContext } from "./common";--const props = defineProps<{- issueContext: IssueContext;- displayMode: "BUTTON" | "DROPDOWN";- issueStatusTransitionList: IssueStatusTransition[];- extraActionList: ExtraActionOption[];-}>();--const emit = defineEmits<{- (event: "apply-issue-transition", transition: IssueStatusTransition): void;- (- event: "apply-batch-task-transition",- transition: TaskStatusTransition,- targets: Task[]- ): void;-}>();--const { t } = useI18n();-const issueLogic = useIssueLogic();-const issue = issueLogic.issue as Ref<Issue>;--const issueStatusTransitionDropdownOptions = computed(() => {- return props.issueStatusTransitionList.map<ExtraActionOption>(- (transition) => {- return {- key: transition.type,- label: t(transition.buttonName),- type: "ISSUE",- transition,- target: issue.value,- };- }- );-});-const mergedDropdownActionList = computed(() => {- if (issueStatusTransitionDropdownOptions.value.length > 0) {- // When there are something to do with tasks, they will be shown as big- // buttons.- // Now we display issue-level actions as a dropdown together with "extra"- // actions.- return [- ...issueStatusTransitionDropdownOptions.value,- ...props.extraActionList,- ];- } else {- // When we have nothing to do with tasks, show issue-level actions as big- // buttons. And show only "extra" actions as a dropdown.- return [...props.extraActionList];- }-});--const allowIssueStatusTransition = (- transition: IssueStatusTransition-): boolean => {- if (transition.type == "RESOLVE") {- const template = issueLogic.template.value;- // Returns false if any of the required output fields is not provided.- for (let i = 0; i < template.outputFieldList.length; i++) {- const field = template.outputFieldList[i];- if (!field.resolved(props.issueContext)) {- return false;- }- }- return true;- }- return true;-};--const handleDropdownSelect = (key: string, dropdownOption: DropdownOption) => {- const option = dropdownOption as ExtraActionOption;- if (option.type === "ISSUE") {- emit("apply-issue-transition", option.transition as IssueStatusTransition);- }- if (option.type === "TASK-BATCH") {- emit(- "apply-batch-task-transition",- option.transition as TaskStatusTransition,- option.target as Task[]- );- }-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/IssueStatusTransitionDialog.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/IssueStatusTransitionDialog.vuedeleted file mode 100644index 79d17c59ff..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/IssueStatusTransitionDialog.vue+++ /dev/null@@ -1,98 +0,0 @@-<template>- <BBModal- :title="title"- class="relative overflow-hidden"- @close="$emit('cancel')"- >- <div- v-if="isTransiting"- class="absolute inset-0 flex items-center justify-center bg-white/50"- >- <BBSpin />- </div>- <StatusTransitionForm- mode="ISSUE"- :issue="issue"- :transition="transition"- :ok-text="okText"- :output-field-list="outputFieldList"- @submit="onSubmit"- @cancel="$emit('cancel')"- />- </BBModal>-</template>--<script setup lang="ts">-import { Ref, computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useIssueStore } from "@/store";-import { Issue, IssueStatusTransition } from "@/types";-import {- isApplicableTransition,- useExtraIssueLogic,- useIssueLogic,- useIssueTransitionLogic,-} from "../logic";-import StatusTransitionForm from "./StatusTransitionForm.vue";--const props = defineProps<{- transition: IssueStatusTransition;-}>();-const emit = defineEmits<{- (event: "updated"): void;- (event: "cancel"): void;-}>();--const { t } = useI18n();-const issueLogic = useIssueLogic();-const issue = issueLogic.issue as Ref<Issue>;-const isTransiting = ref(false);--const { getApplicableIssueStatusTransitionList } =- useIssueTransitionLogic(issue);-const { changeIssueStatus } = useExtraIssueLogic();--const title = computed(() => {- const { transition } = props;-- switch (transition.type) {- case "RESOLVE":- return t("issue.status-transition.modal.resolve");- case "CANCEL":- return t("issue.status-transition.modal.cancel");- case "REOPEN":- return t("issue.status-transition.modal.reopen");- }- return "";-});--const okText = computed(() => {- return t(props.transition.buttonName);-});-const outputFieldList = computed(() => {- return issueLogic.template.value.outputFieldList;-});--const cleanup = () => {- isTransiting.value = false;- emit("cancel");-};--const onSubmit = async (comment: string) => {- isTransiting.value = true;- // Trying to avoid some kind of concurrency and race condition, we fetch the- // latest snapshot of issue from the server-side and check whether this- // transition is applicable again.- const latestIssue = await useIssueStore().fetchIssueById(issue.value.id);-- const { transition } = props;- const applicableList = getApplicableIssueStatusTransitionList(latestIssue);- if (!isApplicableTransition(transition, applicableList)) {- return cleanup();- }-- changeIssueStatus(transition.to, comment);- isTransiting.value = false;- emit("updated");-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/StandaloneIssueStatusTransitionButtonGroup.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/StandaloneIssueStatusTransitionButtonGroup.vuedeleted file mode 100644index 5d827aa74f..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/StandaloneIssueStatusTransitionButtonGroup.vue+++ /dev/null@@ -1,78 +0,0 @@-<template>- <template v-if="!create">- <IssueStatusTransitionButtonGroup- :display-mode="displayMode"- :issue-context="issueContext"- :extra-action-list="[]"- :issue-status-transition-list="issueStatusTransitionActionList"- @apply-issue-transition="tryStartIssueStatusTransition"- />-- <IssueStatusTransitionDialog- v-if="onGoingIssueStatusTransition"- :transition="onGoingIssueStatusTransition.transition"- @updated="onGoingIssueStatusTransition = undefined"- @cancel="onGoingIssueStatusTransition = undefined"- />- </template>-</template>--<script lang="ts" setup>-import { cloneDeep } from "lodash-es";-import { computed, ref, Ref } from "vue";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { convertUserToPrincipal, useCurrentUserV1 } from "@/store";-import type { Issue, IssueStatusTransition } from "@/types";-import { isGrantRequestIssueType } from "@/utils";-import { useIssueTransitionLogic, useIssueLogic } from "../logic";-import IssueStatusTransitionButtonGroup from "./IssueStatusTransitionButtonGroup.vue";-import IssueStatusTransitionDialog from "./IssueStatusTransitionDialog.vue";-import { IssueContext } from "./common";--defineProps<{- displayMode: "BUTTON" | "DROPDOWN";-}>();--const { create, issue } = useIssueLogic();--const onGoingIssueStatusTransition = ref<{- transition: IssueStatusTransition;-}>();--const currentUser = useCurrentUserV1();--const issueReview = useIssueReviewContext();-const { done: reviewDone } = issueReview;--const issueContext = computed((): IssueContext => {- return {- currentUser: convertUserToPrincipal(currentUser.value),- create: create.value,- issue: issue.value,- };-});--const { applicableIssueStatusTransitionList } = useIssueTransitionLogic(- issue as Ref<Issue>-);--const issueStatusTransitionActionList = computed(() => {- const actionList = cloneDeep(applicableIssueStatusTransitionList.value);- const resolveActionIndex = actionList.findIndex(- (item) => item.type === "RESOLVE"- );- // Hide resolve button when grant request issue isn't review done.- if (isGrantRequestIssueType(issue.value.type) && resolveActionIndex > -1) {- if (!reviewDone.value) {- actionList.splice(resolveActionIndex, 1);- }- }- return actionList;-});--const tryStartIssueStatusTransition = (transition: IssueStatusTransition) => {- onGoingIssueStatusTransition.value = {- transition,- };-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/StatusTransitionForm.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/StatusTransitionForm.vuedeleted file mode 100644index c6c6a7c1ee..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/StatusTransitionForm.vue+++ /dev/null@@ -1,325 +0,0 @@-<template>- <div class="px-4 space-y-6 divide-y divide-block-border">- <div class="mt-2 grid grid-cols-1 gap-x-4 sm:grid-cols-4">- <template v-if="mode == 'ISSUE' && transition.type == 'RESOLVE'">- <template v-for="(field, index) in outputFieldList" :key="index">- <div class="flex flex-row items-center text-sm">- <div class="sm:col-span-1">- <label class="textlabel">- {{ field.name }}- </label>- </div>- </div>- <div class="sm:col-span-4 sm:col-start-1">- <template v-if="field.type === 'String'">- <div class="mt-1 flex rounded-md shadow-sm">- <input- :id="field.id"- v-model="state.outputValueList[index]"- type="text"- disabled="true"- :name="field.id"- autocomplete="off"- class="w-full textfield"- />- </div>- </template>- <template v-if="field.type === 'Database'">- <DatabaseSelect- class="mt-1 w-64"- :disabled="true"- :mode="'ENVIRONMENT'"- :environment-id="environmentId"- :selected-id="state.outputValueList[index]"- @select-database-id="state.outputValueList[index] = $event"- />- </template>- </div>- <div v-if="index == outputFieldList.length - 1" class="mt-4" />- </template>- </template>-- <div v-if="showTaskCheckBar" class="sm:col-span-4 mb-4 space-y-4">- <template v-if="checkSummary.runningCount > 0">- <BBAttention- :style="'INFO'"- :title="`${checkSummary.runningCount} check(s) in progress...`"- />- </template>- <template v-else>- <BBAttention- v-if="checkSummary.errorCount > 0"- :style="'CRITICAL'"- :title="- allowSubmit- ? `Check found ${checkSummary.errorCount} error(s) and ${checkSummary.warnCount} warning(s)`- : `Check found ${checkSummary.errorCount} error(s) and ${checkSummary.warnCount} warning(s), please fix before proceeding`- "- />- <BBAttention- v-else-if="checkSummary.warnCount > 0"- :style="'WARN'"- :title="`Check found ${checkSummary.warnCount} warning(s)`"- />- </template>- <TaskCheckBar :task="task!" :allow-run-task="false" />- </div>-- <div v-if="showTaskList" class="sm:col-span-4 mb-4">- <label for="about" class="textlabel">- {{ $t("common.tasks") }}- </label>- <ul class="mt-1 max-h-[6rem] overflow-y-auto">- <li- v-for="item in distinctTaskList"- :key="item.task.id"- class="text-sm textinfolabel"- >- <span class="textinfolabel">- {{ item.task.name }}- </span>- <span v-if="item.similar.length > 0" class="ml-2 text-gray-400">- {{- $t("task.n-similar-tasks", {- count: item.similar.length + 1,- })- }}- </span>- </li>- </ul>- </div>-- <div class="sm:col-span-4 w-112 min-w-full">- <label for="about" class="textlabel">- {{ $t("issue.status-transition.form.note") }}- </label>- <div class="mt-1">- <textarea- ref="commentTextArea"- v-model="state.comment"- rows="3"- class="textarea block w-full resize-none mt-1 text-sm text-control rounded-md whitespace-pre-wrap"- :placeholder="$t('issue.status-transition.form.placeholder')"- @input="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- @focus="- (e) => {- sizeToFit(e.target as HTMLTextAreaElement);- }- "- ></textarea>- </div>- </div>- </div>-- <!-- Update button group -->- <div class="flex justify-end items-center pt-5">- <button- type="button"- class="btn-normal mt-3 px-4 py-2 sm:mt-0 sm:w-auto"- @click.prevent="$emit('cancel')"- >- {{ cancelText }}- </button>- <button- type="button"- class="ml-3 px-4 py-2"- :class="submitButtonStyle"- :disabled="!allowSubmit"- @click.prevent="$emit('submit', state.comment)"- >- {{ displayingOkText }}- </button>- </div>- </div>-</template>--<script lang="ts">-import { cloneDeep, groupBy } from "lodash-es";-import { computed, reactive, ref, PropType, defineComponent } from "vue";-import { useI18n } from "vue-i18n";-import DatabaseSelect from "@/components/DatabaseSelect.vue";-import { OutputField } from "@/plugins";-import { Issue, IssueStatusTransition, Task } from "@/types";-import {- activeEnvironment,- activeStage,- taskCheckRunSummary,- TaskStatusTransition,-} from "@/utils";-import TaskCheckBar from "../TaskCheckBar.vue";-import { useIssueLogic } from "../logic";--interface LocalState {- comment: string;- outputValueList: string[];-}--export default defineComponent({- name: "StatusTransitionForm",- components: { DatabaseSelect, TaskCheckBar },- props: {- mode: {- required: true,- type: String as PropType<"ISSUE" | "STAGE" | "TASK">,- },- okText: {- type: String,- default: "OK",- },- issue: {- required: true,- type: Object as PropType<Issue>,- },- // Applicable when mode = 'TASK'- task: {- type: Object as PropType<Task>,- default: undefined,- },- transition: {- required: true,- type: Object as PropType<IssueStatusTransition | TaskStatusTransition>,- },- outputFieldList: {- required: true,- type: Object as PropType<OutputField[]>,- },- },- emits: ["submit", "cancel"],- setup(props) {- const { t } = useI18n();- const commentTextArea = ref("");-- const state = reactive<LocalState>({- comment: "",- outputValueList: props.outputFieldList.map((field) =>- cloneDeep((props.issue.payload as Record<string, string>)[field.id])- ),- });-- const { allowApplyTaskStatusTransition } = useIssueLogic();-- const checkSummary = computed(() => taskCheckRunSummary(props.task));-- const cancelText = computed(() => t("common.cancel"));- const displayingOkText = computed(() => {- if (props.okText === cancelText.value) {- // We don't want to see [Cancel] [Cancel]- // So fall back to [Cancel] [Confirm] if okText===cancelText- return t("common.confirm");- }- return props.okText;- });-- const environmentId = computed(() => {- return String(activeEnvironment(props.issue.pipeline).id);- });-- // Code block below will raise an eslint ERROR.- // But I won't change it this time.- const submitButtonStyle = computed(() => {- switch (props.mode) {- case "ISSUE": {- switch ((props.transition as IssueStatusTransition).type) {- case "RESOLVE":- return "btn-success";- case "CANCEL":- return "btn-danger";- case "REOPEN":- return "btn-primary";- }- break; // only to make eslint happy- }- case "STAGE": // fallthrough the same as TASK- case "TASK": {- switch ((props.transition as TaskStatusTransition).type) {- case "RUN":- return "btn-primary";- case "ROLLOUT":- return "btn-primary";- case "RETRY":- return "btn-primary";- case "CANCEL":- return "btn-danger";- case "SKIP":- return "btn-primary";- case "RESTART":- return "btn-normal";- }- }- }- return ""; // only to make eslint happy- });-- const showTaskCheckBar = computed((): boolean => {- if (props.mode !== "TASK") return false;- const taskCheckCount = props.task?.taskCheckRunList.length ?? 0;- return taskCheckCount > 0;- });-- const showTaskList = computed((): boolean => {- return props.mode === "STAGE";- });-- const taskList = computed(() => {- const stage = activeStage(props.issue.pipeline!);- const transition = props.transition as TaskStatusTransition;- return stage.taskList.filter((task) => {- return allowApplyTaskStatusTransition(task, transition.to);- });- });-- const distinctTaskList = computed(() => {- type DistinctTaskList = { task: Task; similar: Task[] };- const groups = groupBy(taskList.value, (task) => task.name);-- return Object.keys(groups).map<DistinctTaskList>((taskName) => {- const [task, ...similar] = groups[taskName];- return { task, similar };- });- });-- // Code block below will raise an eslint ERROR.- // But I won't change it this time.- // Disable submit if in TASK mode and there exists RUNNING check or check error and we are transitioning to RUNNING- const allowSubmit = computed(() => {- switch (props.mode) {- case "ISSUE": {- return true;- }- case "STAGE": // fallthrough the same as TASK- case "TASK": {- switch ((props.transition as TaskStatusTransition).to) {- case "RUNNING":- case "PENDING": // fallthrough- return (- checkSummary.value.runningCount === 0 &&- checkSummary.value.errorCount === 0- );- default:- return true;- }- }- }- return false; // only to make eslint happy- });-- return {- state,- checkSummary,- cancelText,- displayingOkText,- environmentId,- showTaskCheckBar,- showTaskList,- distinctTaskList,- commentTextArea,- submitButtonStyle,- allowSubmit,- };- },-});-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskExtraActionsButton.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskExtraActionsButton.vuedeleted file mode 100644index 94f878d50a..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskExtraActionsButton.vue+++ /dev/null@@ -1,127 +0,0 @@-<template>- <NDropdown- v-if="allowSkipTask"- trigger="click"- placement="bottom-end"- :options="options"- @select="handleSelect"- >- <button- id="user-menu"- type="button"- class="text-control-light p-0.5 rounded hover:bg-control-bg-hover"- aria-label="User menu"- aria-haspopup="true"- v-bind="$attrs"- >- <heroicons-solid:dots-vertical class="w-4 h-4" />- </button>- </NDropdown>-- <BBModal- v-if="state.showModal"- :title="modalTitle"- class="relative overflow-hidden"- @close="state.showModal = false"- >- <StatusTransitionForm- mode="TASK"- :ok-text="confirmButtonText"- :issue="(issue as Issue)"- :task="task"- :transition="transition!"- :output-field-list="[]"- @submit="onSubmit"- @cancel="state.showModal = false"- />- </BBModal>-</template>--<script lang="ts" setup>-import { DropdownOption, NDropdown } from "naive-ui";-import { computed, PropType, reactive } from "vue";-import { useI18n } from "vue-i18n";-import type { Issue, Task } from "@/types";-import { canSkipTask, TaskStatusTransition } from "@/utils";-import { useExtraIssueLogic, useIssueLogic } from "../logic";-import StatusTransitionForm from "./StatusTransitionForm.vue";--type LocalState = {- showModal: boolean;- isLoading: boolean;-};--const props = defineProps({- task: {- type: Object as PropType<Task>,- required: true,- },-});--const state = reactive<LocalState>({- showModal: false,- isLoading: false,-});--const { t } = useI18n();--const { create, issue } = useIssueLogic();-const { changeTaskStatus } = useExtraIssueLogic();--const allowSkipTask = computed(() => {- if (create.value) {- return false;- }-- return canSkipTask(- props.task,- issue.value as Issue,- true /* activeOnly */,- false /* !failedOnly */- );-});--const options = computed(() => {- const list: DropdownOption[] = [];- if (allowSkipTask.value) {- list.push({- key: "skip",- label: t("task.skip"),- });- }- return list;-});--const handleSelect = (key: string) => {- if (key === "skip") {- state.showModal = true;- }-};--const confirmButtonText = computed(() => t("task.skip"));--const transition = computed((): TaskStatusTransition => {- return {- buttonType: "PRIMARY",- buttonName: t("task.skip"),- type: "SKIP",- to: "DONE",- };-});--const modalTitle = computed(() => {- return t("task.skip-modal-title", {- name: props.task.name,- });-});--const onSubmit = async (comment: string) => {- state.isLoading = true;- try {- changeTaskStatus(props.task, "DONE", comment);- } finally {- state.isLoading = false;- state.showModal = false;- }-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskStatusTransitionButtonGroup.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskStatusTransitionButtonGroup.vuedeleted file mode 100644index c0dd732e58..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskStatusTransitionButtonGroup.vue+++ /dev/null@@ -1,122 +0,0 @@-<template>- <div class="flex items-center gap-x-2">- <BBContextMenuButton- v-for="(transition, index) in taskStatusTransitionList"- :key="index"- data-label="bb-issue-status-transition-button"- :default-action-key="`${transition.type}-STAGE`"- :disabled="!allowApplyTaskTransition(transition)"- :action-list="getButtonActionListForTransition(transition)"- @click="(action) => onClickTaskStatusTransitionActionButton(action as TaskStatusTransitionButtonAction)"- />- </div>-</template>--<script lang="ts" setup>-import { Ref, computed } from "vue";-import { useI18n } from "vue-i18n";-import {- default as BBContextMenuButton,- type ButtonAction,-} from "@/bbkit/BBContextMenuButton.vue";-import { Issue } from "@/types";-import {- StageStatusTransition,- TaskStatusTransition,- isDatabaseRelatedIssueType,- taskCheckRunSummary,-} from "@/utils";-import { useIssueLogic } from "../logic";-import { IssueContext } from "./common";--export type TaskStatusTransitionButtonAction = ButtonAction<{- transition: TaskStatusTransition;- target: "TASK" | "STAGE";-}>;--const props = defineProps<{- issueContext: IssueContext;- taskStatusTransitionList: TaskStatusTransition[];- stageStatusTransitionList: StageStatusTransition[];-}>();--const emit = defineEmits<{- (- event: "apply-task-transition",- transition: TaskStatusTransition,- target: "TASK" | "STAGE"- ): void;-}>();--const { t } = useI18n();-const issueLogic = useIssueLogic();-const issue = issueLogic.issue as Ref<Issue>;--const currentTask = computed(() => {- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return undefined;- }- return issueLogic.activeTaskOfPipeline(issue.value.pipeline!);-});--const allowApplyTaskTransition = (transition: TaskStatusTransition) => {- if (transition.to === "PENDING") {- // "Approve" is disabled when the task checks are not ready.- const summary = taskCheckRunSummary(currentTask.value);- if (summary.runningCount > 0 || summary.errorCount > 0) {- return false;- }- }- return true;-};--const getButtonActionListForTransition = (transition: TaskStatusTransition) => {- const actionList: TaskStatusTransitionButtonAction[] = [];- const { type, buttonName, buttonType } = transition;- actionList.push({- key: `${type}-TASK`,- text: t(buttonName),- type: buttonType,- params: { transition, target: "TASK" },- });-- if (allowApplyTaskTransitionToStage(transition)) {- actionList.push({- key: `${type}-STAGE`,- text: t("issue.action-to-current-stage", {- action: t(buttonName),- }),- type: buttonType,- params: { transition, target: "STAGE" },- });- }-- return actionList;-};--const allowApplyTaskTransitionToStage = (transition: TaskStatusTransition) => {- // Only available for the issue type of schema.update and data.update.- const stage = currentTask.value?.stage;- if (!stage) return false;-- // Only available when the stage has multiple tasks.- if (stage.taskList.length <= 1) {- return false;- }-- // Available to apply a taskStatusTransition to the stage when the transition- // type is also applicable to the stage.- return (- props.stageStatusTransitionList.findIndex(- (t) => t.type === transition.type- ) >= 0- );-};--const onClickTaskStatusTransitionActionButton = (- action: TaskStatusTransitionButtonAction-) => {- const { transition, target } = action.params;- emit("apply-task-transition", transition, target);-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskStatusTransitionDialog.vue b/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskStatusTransitionDialog.vuedeleted file mode 100644index 38df001f86..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/TaskStatusTransitionDialog.vue+++ /dev/null@@ -1,150 +0,0 @@-<template>- <BBModal- :title="title"- class="relative overflow-hidden"- @close="$emit('cancel')"- >- <div- v-if="isTransiting"- class="absolute inset-0 flex items-center justify-center bg-white/50"- >- <BBSpin />- </div>- <StatusTransitionForm- :mode="mode"- :issue="issue"- :ok-text="okText"- :transition="props.transition"- :output-field-list="[]"- @submit="onSubmit"- @cancel="$emit('cancel')"- />- </BBModal>-</template>--<script setup lang="ts">-import { Ref, computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useIssueStore } from "@/store";-import { Issue, Stage, Task } from "@/types";-import { StageStatusTransition, TaskStatusTransition } from "@/utils";-import {- isApplicableTransition,- useExtraIssueLogic,- useIssueLogic,- useIssueTransitionLogic,-} from "../logic";-import StatusTransitionForm from "./StatusTransitionForm.vue";--const props = defineProps<{- mode: "TASK" | "STAGE";- transition: TaskStatusTransition | StageStatusTransition;- task: Task;-}>();-const emit = defineEmits<{- (event: "updated"): void;- (event: "cancel"): void;-}>();--const { t } = useI18n();-const issueLogic = useIssueLogic();-const issue = issueLogic.issue as Ref<Issue>;-const isTransiting = ref(false);--const {- getApplicableStageStatusTransitionList,- getApplicableTaskStatusTransitionList,-} = useIssueTransitionLogic(issue);-const { changeTaskStatus, changeStageAllTaskStatus } = useExtraIssueLogic();--const payload = computed(() => {- const { mode, task } = props;- return mode === "TASK" ? task : task.stage;-});--const actionText = computed(() => {- switch (props.transition.type) {- case "RUN":- return t("common.run");- case "ROLLOUT":- return t("common.rollout");- case "RETRY":- return t("common.retry");- case "CANCEL":- return t("common.cancel");- case "SKIP":- return t("common.skip");- case "RESTART":- return t("common.restart");- default:- console.assert(false, "should never reach this line");- return "";- }-});--const title = computed(() => {- const { task, mode } = props;- if (!task) return "";-- const type = mode === "TASK" ? t("common.task") : t("common.stage");- const name = payload.value.name;- return t("issue.status-transition.modal.title", {- action: actionText.value,- type: type.toLowerCase(),- name,- });-});--const okText = computed(() => {- const { task, mode, transition } = props;- if (!task) return "";- const button = t(transition.buttonName);- if (mode === "TASK") {- return button;- }-- // mode === 'STAGE'- const pendingApprovalTaskList = task.stage.taskList.filter((task) => {- return (- task.status === "PENDING_APPROVAL" &&- issueLogic.allowApplyTaskStatusTransition(task, "PENDING")- );- });- return t("issue.status-transition.modal.action-to-stage", {- action: button,- n: pendingApprovalTaskList.length,- });-});--const cleanup = () => {- isTransiting.value = false;- emit("cancel");-};--const onSubmit = async (comment: string) => {- isTransiting.value = true;- // Trying to avoid some kind of concurrency and race condition, we fetch the- // latest snapshot of issue from the server-side and check whether this- // transition is applicable again.- const latestIssue = await useIssueStore().fetchIssueById(issue.value.id);-- const { transition } = props;-- if (props.mode === "STAGE") {- const applicableList = getApplicableStageStatusTransitionList(latestIssue);- if (!isApplicableTransition(transition, applicableList)) {- return cleanup();- }- changeStageAllTaskStatus(payload.value as Stage, transition.to, comment);- } else if (props.mode === "TASK") {- const applicableList = getApplicableTaskStatusTransitionList(latestIssue);- if (!isApplicableTransition(transition, applicableList)) {- return cleanup();- }- changeTaskStatus(payload.value as Task, transition.to, comment);- }-- isTransiting.value = false;- emit("updated");-};-</script>diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/common.ts b/frontend/src/components/Issue/StatusTransitionButtonGroup/common.tsdeleted file mode 100644index 78a9a023af..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/common.ts+++ /dev/null@@ -1,30 +0,0 @@-import { type DropdownOption } from "naive-ui";-import {- Issue,- IssueCreate,- IssueStatusTransition,- Principal,- Task,-} from "@/types";-import { TaskStatusTransition } from "@/utils";--export type IssueContext = {- currentUser: Principal;- create: boolean;- issue: Issue | IssueCreate;-};--export type ExtraAction<T extends "ISSUE" | "TASK" | "TASK-BATCH"> = {- type: T;- transition: T extends "ISSUE" ? IssueStatusTransition : TaskStatusTransition;- target: T extends "ISSUE"- ? Issue- : T extends "TASK"- ? Task- : T extends "TASK-BATCH"- ? Task[]- : unknown;-};--export type ExtraActionOption = DropdownOption &- ExtraAction<"ISSUE" | "TASK" | "TASK-BATCH">;diff --git a/frontend/src/components/Issue/StatusTransitionButtonGroup/index.ts b/frontend/src/components/Issue/StatusTransitionButtonGroup/index.tsdeleted file mode 100644index a268a0522c..0000000000--- a/frontend/src/components/Issue/StatusTransitionButtonGroup/index.ts+++ /dev/null@@ -1,9 +0,0 @@-import CombinedRolloutButtonGroup from "./CombinedRolloutButtonGroup.vue";-import StandaloneIssueStatusTransitionButtonGroup from "./StandaloneIssueStatusTransitionButtonGroup.vue";-import TaskExtraActionsButton from "./TaskExtraActionsButton.vue";--export {- StandaloneIssueStatusTransitionButtonGroup,- CombinedRolloutButtonGroup,- TaskExtraActionsButton,-};diff --git a/frontend/src/components/Issue/TaskCheckBadgeBar.vue b/frontend/src/components/Issue/TaskCheckBadgeBar.vuedeleted file mode 100644index a662d850c1..0000000000--- a/frontend/src/components/Issue/TaskCheckBadgeBar.vue+++ /dev/null@@ -1,272 +0,0 @@-<template>- <div class="flex items-center flex-wrap gap-2 flex-1">- <template- v-for="(checkRun, index) in filteredTaskCheckRunList"- :key="index"- >- <button- class="inline-flex items-center px-3 py-0.5 rounded-full text-sm border border-control-border"- :class="buttonStyle(checkRun)"- @click.prevent="selectTaskCheckType(checkRun.type)"- >- <template v-if="checkRun.status == 'RUNNING'">- <TaskSpinner class="-ml-1 mr-1.5 h-4 w-4 text-info" />- </template>- <template v-else-if="checkRun.status == 'DONE'">- <template v-if="taskCheckStatus(checkRun) == 'SUCCESS'">- <heroicons-outline:check- class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-success"- />- </template>- <template v-else-if="taskCheckStatus(checkRun) == 'WARN'">- <heroicons-outline:exclamation- class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-warning"- />- </template>- <template v-else-if="taskCheckStatus(checkRun) == 'ERROR'">- <span class="mr-1.5 font-medium text-error" aria-hidden="true">- !- </span>- </template>- </template>- <template v-else-if="checkRun.status == 'FAILED'">- <span class="mr-1.5 font-medium text-error" aria-hidden="true">- !- </span>- </template>- <template v-else-if="checkRun.status == 'CANCELED'">- <heroicons-outline:ban- class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-control"- />- </template>- {{ name(checkRun) }}- </button>- </template>- </div>-</template>--<script lang="ts">-import { groupBy, maxBy } from "lodash-es";-import { computed, defineComponent, PropType, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { HiddenCheckTypes } from "@/utils";-import { TaskCheckRun, TaskCheckStatus, TaskCheckType } from "../../types";-import TaskSpinner from "./TaskSpinner.vue";--interface LocalState {- selectedTaskCheckType: TaskCheckType | undefined;-}--export default defineComponent({- name: "TaskCheckBadgeBar",- components: { TaskSpinner },- props: {- taskCheckRunList: {- required: true,- type: Object as PropType<TaskCheckRun[]>,- },- allowSelection: {- default: true,- type: Boolean,- },- stickySelection: {- default: false,- type: Boolean,- },- selectedTaskCheckType: {- type: String as PropType<TaskCheckType>,- default: undefined,- },- },- emits: ["select-task-check-type"],- setup(props, { emit }) {- const { t } = useI18n();- const state = reactive<LocalState>({- selectedTaskCheckType: props.selectedTaskCheckType,- });-- watch(- () => props.selectedTaskCheckType,- (curNew, _) => {- state.selectedTaskCheckType = curNew;- }- );-- const buttonStyle = (checkRun: TaskCheckRun): string => {- let bgColor = "";- let bgHoverColor = "";- let textColor = "";- switch (checkRun.status) {- case "RUNNING":- bgColor = "bg-blue-100";- bgHoverColor = "bg-blue-300";- textColor = "text-blue-800";- break;- case "FAILED":- bgColor = "bg-red-100";- bgHoverColor = "bg-red-300";- textColor = "text-red-800";- break;- case "CANCELED":- bgColor = "bg-yellow-100";- bgHoverColor = "bg-yellow-300";- textColor = "text-yellow-800";- break;- case "DONE":- switch (taskCheckStatus(checkRun)) {- case "SUCCESS":- bgColor = "bg-gray-100";- bgHoverColor = "bg-gray-300";- textColor = "text-gray-800";- break;- case "WARN":- bgColor = "bg-yellow-100";- bgHoverColor = "bg-yellow-300";- textColor = "text-yellow-800";- break;- case "ERROR":- bgColor = "bg-red-100";- bgHoverColor = "bg-red-300";- textColor = "text-red-800";- break;- }- break;- }-- const styleList: string[] = [textColor];- if (props.allowSelection) {- styleList.push("cursor-pointer", `hover:${bgHoverColor}`);- if (- props.stickySelection &&- checkRun.type == state.selectedTaskCheckType- ) {- styleList.push(bgHoverColor);- } else {- styleList.push(bgColor);- }- } else {- styleList.push(bgColor);- styleList.push("cursor-default");- }-- return styleList.join(" ");- };-- // For a particular check type, only returns the most recent one- const filteredTaskCheckRunList = computed((): TaskCheckRun[] => {- const groupByType = groupBy(- props.taskCheckRunList.filter((run) => !HiddenCheckTypes.has(run.type)),- (run) => run.type- );- /*- `groupByType` looks like: {- "bb.task-check.database.statement.compatibility": [run1, run2, ...],- "bb.task-check.database.statement.syntax": [run1, run2, ...],- ...- }- `result` is an array of the most recent TaskCheckRun in each group- */- const result = Object.keys(groupByType).map((type) => {- const groupList = groupByType[type];- const mostRecentInGroup = maxBy(groupList, (run) => run.updatedTs)!;- return mostRecentInGroup;- });-- return result.sort((a: TaskCheckRun, b: TaskCheckRun) => {- const taskCheckRunTypeOrder = (type: TaskCheckType) => {- const has = TaskCheckTypeOrderDict.has(type);- console.assert(has, `Missing TaskCheckType order of "${type}"`);- if (has) {- return TaskCheckTypeOrderDict.get(type)!;- }- // Fallback, types not defined in the dictionary will go to the tail.- return FAKE_MAX_TASK_CHECK_TYPE_ORDER;- };-- return taskCheckRunTypeOrder(a.type) - taskCheckRunTypeOrder(b.type);- });- });-- // Returns the most severe status- const taskCheckStatus = (taskCheckRun: TaskCheckRun): TaskCheckStatus => {- let value: TaskCheckStatus = "SUCCESS";- for (const result of taskCheckRun.result.resultList ?? []) {- if (result.status == "ERROR") {- return "ERROR";- }- if (result.status == "WARN") {- value = "WARN";- }- }- return value;- };-- const name = (taskCheckRun: TaskCheckRun): string => {- const { type } = taskCheckRun;- const has = TaskCheckTypeNameDict.has(type);- console.assert(has, `Missing TaskCheckType name of "${type}"`);- if (has) {- const key = TaskCheckTypeNameDict.get(type)!;- return t(key);- }- return type;- };-- const selectTaskCheckType = (type: TaskCheckType) => {- emit("select-task-check-type", type);- };-- return {- state,- buttonStyle,- filteredTaskCheckRunList,- taskCheckStatus,- name,- selectTaskCheckType,- };- },-});--// Defines the order of TaskCheckType-const TaskCheckTypeOrderList: TaskCheckType[] = [- "bb.task-check.pitr.mysql",- "bb.task-check.database.ghost.sync",- "bb.task-check.database.statement.compatibility",- "bb.task-check.database.statement.syntax",- "bb.task-check.database.statement.type",- "bb.task-check.database.connect",- "bb.task-check.database.statement.advise",- "bb.task-check.issue.lgtm",- "bb.task-check.database.statement.affected-rows.report",- "bb.task-check.database.statement.type.report",-];-const TaskCheckTypeOrderDict = new Map<TaskCheckType, number>(- TaskCheckTypeOrderList.map((type, index) => [type, index])-);-const FAKE_MAX_TASK_CHECK_TYPE_ORDER = 100;-TaskCheckTypeOrderDict.set(- "bb.task-check.database.statement.fake-advise",- FAKE_MAX_TASK_CHECK_TYPE_ORDER-);--// Defines the mapping from TaskCheckType to an i18n resource keypath-const TaskCheckTypeNameDict = new Map<TaskCheckType, string>([- ["bb.task-check.database.statement.fake-advise", "task.check-type.fake"],- ["bb.task-check.database.statement.syntax", "task.check-type.syntax"],- [- "bb.task-check.database.statement.compatibility",- "task.check-type.compatibility",- ],- ["bb.task-check.database.statement.advise", "task.check-type.sql-review"],- ["bb.task-check.database.statement.type", "task.check-type.statement-type"],- ["bb.task-check.database.connect", "task.check-type.connection"],- ["bb.task-check.database.ghost.sync", "task.check-type.ghost-sync"],- ["bb.task-check.issue.lgtm", "task.check-type.lgtm"],- ["bb.task-check.pitr.mysql", "task.check-type.pitr"],- [- "bb.task-check.database.statement.affected-rows.report",- "task.check-type.affected-rows",- ],- ["bb.task-check.database.statement.type.report", "task.check-type.sql-type"],-]);-</script>diff --git a/frontend/src/components/Issue/TaskCheckBar.vue b/frontend/src/components/Issue/TaskCheckBar.vuedeleted file mode 100644index 070d0ac040..0000000000--- a/frontend/src/components/Issue/TaskCheckBar.vue+++ /dev/null@@ -1,178 +0,0 @@-<template>- <div- v-if="task.taskCheckRunList.length > 0"- class="flex items-start space-x-4"- >- <div class="textlabel h-[26px] inline-flex items-center">- {{ $t("task.task-checks") }}- </div>-- <TaskCheckBadgeBar- :task-check-run-list="task.taskCheckRunList"- @select-task-check-type="viewCheckRunDetail"- />-- <RunTaskCheckButton v-if="allowRunTask" @run-checks="runChecks" />-- <BBModal- v-if="state.showModal"- :title="$t('task.check-result.title', { name: task.name })"- class="!w-[56rem]"- header-class="whitespace-pre-wrap break-all gap-x-1"- @close="dismissDialog"- >- <div class="space-y-4">- <div>- <TaskCheckBadgeBar- :task-check-run-list="task.taskCheckRunList"- :allow-selection="true"- :sticky-selection="true"- :selected-task-check-type="state.selectedTaskCheckType"- @select-task-check-type="viewCheckRunDetail"- />- </div>- <BBTabFilter- class="pt-4"- :tab-item-list="tabItemList"- :selected-index="state.selectedTabIndex"- @select-index="- (index: number) => {- state.selectedTabIndex = index;- }- "- />- <TaskCheckRunPanel- v-if="selectedTaskCheckRun"- :task-check-run="selectedTaskCheckRun"- :task="task"- />- <div class="pt-4 flex justify-end">- <button- type="button"- class="btn-primary py-2 px-4"- @click.prevent="dismissDialog"- >- {{ $t("common.close") }}- </button>- </div>- </div>- </BBModal>- </div>-</template>--<script lang="ts">-import { cloneDeep } from "lodash-es";-import { computed, defineComponent, PropType, reactive } from "vue";-import { useI18n } from "vue-i18n";-import { BBTabFilterItem } from "@/bbkit/types";-import { Task, TaskCheckRun, TaskCheckStatus, TaskCheckType } from "@/types";-import { humanizeTs } from "@/utils";-import RunTaskCheckButton from "./RunTaskCheckButton.vue";-import TaskCheckBadgeBar from "./TaskCheckBadgeBar.vue";-import TaskCheckRunPanel from "./TaskCheckRunPanel.vue";--interface LocalState {- showModal: boolean;- selectedTaskCheckType: TaskCheckType | undefined;- selectedTabIndex: number;-}--export default defineComponent({- name: "TaskCheckBar",- components: { TaskCheckBadgeBar, TaskCheckRunPanel, RunTaskCheckButton },- props: {- allowRunTask: {- type: Boolean,- default: true,- },- task: {- required: true,- type: Object as PropType<Task>,- },- },- emits: ["run-checks"],- setup(props, { emit }) {- const { t } = useI18n();-- const state = reactive<LocalState>({- showModal: false,- selectedTaskCheckType: undefined,- selectedTabIndex: 0,- });-- const tabTaskCheckRunList = computed((): TaskCheckRun[] => {- if (!state.selectedTaskCheckType) {- return [];- }-- const list: TaskCheckRun[] = [];- for (const check of props.task.taskCheckRunList) {- if (check.type == state.selectedTaskCheckType) {- list.push(check);- }- }- const clonedList = cloneDeep(list);- clonedList.sort(- (a: TaskCheckRun, b: TaskCheckRun) => b.createdTs - a.createdTs- );- return clonedList;- });-- const tabItemList = computed((): BBTabFilterItem[] => {- return tabTaskCheckRunList.value.map((item, index) => {- return {- title: index == 0 ? t("common.latest") : humanizeTs(item.createdTs),- alert: false,- };- });- });-- const selectedTaskCheckRun = computed(() => {- const type = state.selectedTaskCheckType;- const index = state.selectedTabIndex;- if (!type) return undefined;- return tabTaskCheckRunList.value[index];- });-- // Returns the most severe status- const taskCheckStatus = (taskCheckRun: TaskCheckRun): TaskCheckStatus => {- let value: TaskCheckStatus = "SUCCESS";- for (const result of taskCheckRun.result.resultList) {- if (result.status == "ERROR") {- return "ERROR";- }- if (result.status == "WARN") {- value = "WARN";- }- }- return value;- };-- const viewCheckRunDetail = (type: TaskCheckType) => {- state.selectedTaskCheckType = type;- state.selectedTabIndex = 0;- state.showModal = true;- };-- const dismissDialog = () => {- state.showModal = false;- state.selectedTaskCheckType = undefined;- };-- const runChecks = (taskList: Task[]) => {- emit("run-checks", taskList);- };-- return {- state,- tabTaskCheckRunList,- tabItemList,- selectedTaskCheckRun,- taskCheckStatus,- viewCheckRunDetail,- dismissDialog,- runChecks,- };- },-});-</script>diff --git a/frontend/src/components/Issue/TaskCheckResultDefinitionModal.vue b/frontend/src/components/Issue/TaskCheckResultDefinitionModal.vuedeleted file mode 100644index 12c79a14dc..0000000000--- a/frontend/src/components/Issue/TaskCheckResultDefinitionModal.vue+++ /dev/null@@ -1,33 +0,0 @@-<template>- <BBModal :title="$t('sql-review.view-definition')" @close="emit('cancel')">- <div class="space-y-4 w-[calc(100vw-5rem)] sm:w-[40rem] pb-1">- <div class="space-y-1">- <div class="flex flex-col gap-x-2 whitespace-pre-wrap">- {{ definition }}- </div>- </div>- <div class="mt-4 pt-2 border-t flex justify-end">- <button- type="button"- class="btn-normal py-2 px-4"- @click.prevent="emit('cancel')"- >- {{ $t("common.cancel") }}- </button>- </div>- </div>- </BBModal>-</template>--<script lang="ts" setup>-defineProps({- definition: {- required: true,- type: String,- },-});--const emit = defineEmits<{- (event: "cancel"): void;-}>();-</script>diff --git a/frontend/src/components/Issue/TaskCheckRunPanel.vue b/frontend/src/components/Issue/TaskCheckRunPanel.vuedeleted file mode 100644index 02f2487d1b..0000000000--- a/frontend/src/components/Issue/TaskCheckRunPanel.vue+++ /dev/null@@ -1,296 +0,0 @@-<template>- <div>- <BBTable- :column-list="COLUMN_LIST"- :data-source="tableRows"- :show-header="false"- :left-bordered="true"- :right-bordered="true"- :top-bordered="true"- :bottom-bordered="true"- :row-clickable="false"- >- <template #body="{ rowData: row }: { rowData: TableRow }">- <BBTableCell :left-padding="4" class="w-[1%]">- <!-- as narrow as possible -->- <div- class="relative w-5 h-5 flex flex-shrink-0 items-center justify-center rounded-full select-none"- :class="statusIconClass(row.checkResult.status)"- >- <template v-if="row.checkResult.status == 'SUCCESS'">- <heroicons-solid:check class="w-4 h-4" />- </template>- <template v-if="row.checkResult.status == 'WARN'">- <heroicons-outline:exclamation class="h-4 w-4" />- </template>- <template v-else-if="row.checkResult.status == 'ERROR'">- <span class="text-white font-medium text-base" aria-hidden="true"- >!</span- >- </template>- </div>- </BBTableCell>- <BBTableCell- v-if="showCategoryColumn"- class="min-w-[4rem] max-w-[6rem] whitespace-nowrap"- >- {{ row.category }}- </BBTableCell>- <BBTableCell class="w-[12rem] break-all">- {{ row.title }}- </BBTableCell>- <BBTableCell class="w-auto">- <span>{{ row.checkResult.content }}</span>- <template v-if="row.checkResult.details">- <span- class="ml-1 normal-link"- @click="state.activeResultDefinition = row.checkResult.details"- >{{ $t("sql-review.view-definition") }}</span- >- <span class="border-r border-control-border ml-1"></span>- </template>- <template- v-if="row.checkResult.namespace === 'bb.advisor' && getActiveRule(row.checkResult.title as RuleType)"- >- <span- class="ml-1 normal-link"- @click="setActiveRule(row.checkResult.title as RuleType)"- >{{ $t("sql-review.rule-detail") }}</span- >- <span class="border-r border-control-border ml-1"></span>- </template>- <a- v-if="row.link"- class="ml-1 normal-link"- :href="row.link.url"- :target="row.link.target"- >- {{ row.link.title }}- </a>- </BBTableCell>- </template>- </BBTable>-- <SQLRuleEditDialog- v-if="state.activeRule"- :editable="false"- :rule="state.activeRule"- :disabled="false"- @cancel="state.activeRule = undefined"- />-- <TaskCheckResultDefinitionModal- v-if="state.activeResultDefinition"- :definition="state.activeResultDefinition"- @cancel="state.activeResultDefinition = undefined"- />- </div>-</template>--<script lang="ts" setup>-import { computed, PropType, reactive } from "vue";-import { useI18n } from "vue-i18n";-import type { BBTableColumn } from "@/bbkit";-import { SQLRuleEditDialog } from "@/components/SQLReview/components";-import { useReviewPolicyByEnvironmentId } from "@/store";-import {- TaskCheckStatus,- TaskCheckRun,- TaskCheckResult,- GeneralErrorCode,- ruleTemplateMap,- getRuleLocalization,- SQLReviewPolicyErrorCode,- RuleType,- RuleTemplate,- Task,- findRuleTemplate,-} from "@/types";-import { LocalizedSQLRuleErrorCodes } from "./const";--interface ErrorCodeLink {- title: string;- target: string;- url: string;-}--type TableRow = {- checkResult: TaskCheckResult;- category: string;- title: string;- link: ErrorCodeLink | undefined;-};--type LocalState = {- activeRule?: RuleTemplate;- activeResultDefinition?: string;-};--const props = defineProps({- taskCheckRun: {- required: true,- type: Object as PropType<TaskCheckRun>,- },- task: {- required: true,- type: Object as PropType<Task>,- },-});--const state = reactive<LocalState>({- activeRule: undefined,-});--const { t } = useI18n();--const statusIconClass = (status: TaskCheckStatus) => {- switch (status) {- case "SUCCESS":- return "bg-success text-white";- case "WARN":- return "bg-warning text-white";- case "ERROR":- return "bg-error text-white";- }-};--const checkResultList = computed((): TaskCheckResult[] => {- if (props.taskCheckRun.status == "DONE") {- return props.taskCheckRun.result.resultList;- } else if (props.taskCheckRun.status == "FAILED") {- return [- {- status: "ERROR",- title: t("common.error"),- code: props.taskCheckRun.code,- content: props.taskCheckRun.result.detail,- namespace: "bb.core",- line: undefined,- column: undefined,- },- ];- } else if (props.taskCheckRun.status == "CANCELED") {- return [- {- status: "WARN",- title: t("common.canceled"),- code: props.taskCheckRun.code,- content: "",- namespace: "bb.core",- line: undefined,- column: undefined,- },- ];- }-- return [];-});--const categoryAndTitle = (checkResult: TaskCheckResult): [string, string] => {- if (checkResult.code === SQLReviewPolicyErrorCode.EMPTY_POLICY) {- const title = messageWithCode(checkResult.title, checkResult.code);- return ["", title];- }- if (LocalizedSQLRuleErrorCodes.has(checkResult.code)) {- const rule = ruleTemplateMap.get(checkResult.title as RuleType);- if (rule) {- const ruleLocalization = getRuleLocalization(rule.type);- const key = `sql-review.category.${rule.category.toLowerCase()}`;- const category = t(key);- const title = messageWithCode(ruleLocalization.title, checkResult.code);- return [category, title];- } else {- return ["", messageWithCode(checkResult.title, checkResult.code)];- }- }-- return ["", checkResult.title];-};--const messageWithCode = (message: string, code: number) => {- return `${message} #${code}`;-};--const errorCodeLink = (- checkResult: TaskCheckResult-): ErrorCodeLink | undefined => {- switch (checkResult.code) {- case undefined:- return;- case GeneralErrorCode.OK:- return;- case SQLReviewPolicyErrorCode.EMPTY_POLICY:- return {- title: t("sql-review.configure-policy"),- target: "_self",- url: "/setting/sql-review",- };- default: {- const url = `https://www.bytebase.com/docs/reference/error-code/${- checkResult.namespace === "bb.advisor" ? "advisor" : "core"- }?source=console#${checkResult.code}`;- return {- title: t("common.view-doc"),- target: "__blank",- url: url,- };- }- }-};--const tableRows = computed(() => {- return checkResultList.value.map<TableRow>((checkResult) => {- const [category, title] = categoryAndTitle(checkResult);- const link = errorCodeLink(checkResult);- return {- checkResult,- category,- title,- link,- };- });-});--const showCategoryColumn = computed((): boolean =>- tableRows.value.some((row) => row.category !== "")-);--const COLUMN_LIST = computed((): BBTableColumn[] => {- const STATUS = {- title: "Status",- };- const CATEGORY = {- title: "Category",- };- const TITLE = {- title: "Title",- };- const CONTENT = {- title: "Detail",- };- if (showCategoryColumn.value) {- return [STATUS, CATEGORY, TITLE, CONTENT];- }- return [STATUS, TITLE, CONTENT];-});--const reviewPolicy = useReviewPolicyByEnvironmentId(- computed(() => String(props.task.instance.environment.id))-);-const getActiveRule = (type: RuleType): RuleTemplate | undefined => {- const rule = reviewPolicy.value?.ruleList.find((rule) => rule.type === type);- if (!rule) {- return undefined;- }-- const ruleTemplate = findRuleTemplate(type);- if (!ruleTemplate) {- return undefined;- }- ruleTemplate.comment = rule.comment;- return ruleTemplate;-};-const setActiveRule = (type: RuleType) => {- state.activeRule = getActiveRule(type);-};-</script>diff --git a/frontend/src/components/Issue/TaskProgressPie.vue b/frontend/src/components/Issue/TaskProgressPie.vuedeleted file mode 100644index 3d7a5bed41..0000000000--- a/frontend/src/components/Issue/TaskProgressPie.vue+++ /dev/null@@ -1,157 +0,0 @@-<template>- <NPopover v-if="showProgress" placement="bottom" :disabled="!showPopover">- <template #trigger>- <BBProgressPie- class="w-10 h-10"- :class="task.status === 'DONE' ? 'text-success' : 'text-info'"- :thickness="3"- :percent="progress.percent"- >- <template #default="{ percent }">- <span v-if="task.status !== 'DONE'" class="text-xs">- {{ percent }}%- </span>- <span v-else>- <heroicons-outline:check class="w-8 h-8" />- </span>- </template>- </BBProgressPie>- </template>-- <div class="flex flex-col gap-y-2">- <div class="flex flex-col items-start">- <label class="textlabel">- {{- $t("task.progress.completed-units", {- units: unitStr,- })- }}- </label>- <span>- <slot name="unit" :unit="progress.completedUnit">- {{ progress.completedUnit }}- </slot>- </span>- </div>- <div class="flex flex-col items-start">- <label class="textlabel">- {{- $t("task.progress.total-units", {- units: unitStr,- })- }}- </label>- <span v-if="progress.totalUnit > 0">- <slot name="unit" :unit="progress.totalUnit">- {{ progress.totalUnit }}- </slot>- </span>- <span v-else class="text-gray-400">- {{ $t("task.progress.counting") }}- </span>- </div>- <div- v-if="task.status === 'RUNNING' && progress.eta > 0"- class="flex flex-col items-start whitespace-nowrap"- >- <label class="textlabel whitespace-nowrap">- <span>{{ $t("task.progress.eta") }}</span>- <span class="text-gray-400 text-xs">- UTC{{ dayjs().format("ZZ") }}- </span>- </label>- <span class="whitespace-nowrap">- {{ dayjs(progress.eta * 1000).format("YYYY-MM-DD HH:mm:ss") }}- </span>- </div>- </div>- </NPopover>-</template>--<script lang="ts" setup>-import { NPopover } from "naive-ui";-import { computed, PropType } from "vue";-import { useI18n } from "vue-i18n";-import { BBProgressPie } from "@/bbkit";-import type { Task, TaskProgress } from "@/types";-import { empty } from "@/types";--type ProgressSummary = TaskProgress & {- percent: number;- eta: number;-};--const props = defineProps({- task: {- type: Object as PropType<Task>,- required: true,- },- unitKey: {- type: String,- default: undefined,- },-});--const { t } = useI18n();--const showProgress = computed((): boolean => {- const { status } = props.task;-- return status === "PENDING" || status === "RUNNING";-});--const progress = computed((): ProgressSummary => {- const ZERO: ProgressSummary = {- ...empty("TASK_PROGRESS"),- percent: 0,- eta: 0,- };-- const { task } = props;-- if (task.status === "DONE") {- return { ...task.progress, percent: 100, eta: task.updatedTs };- }-- const { progress } = task;- if (progress.totalUnit > 0) {- const completedUnit = progress.completedUnit;- const totalUnit = Math.max(progress.completedUnit, progress.totalUnit);-- const p = completedUnit / totalUnit;- const percent = Math.floor(p * 100);-- const result: ProgressSummary = {- ...task.progress,- totalUnit,- percent,- eta: 0,- };-- const { updatedTs, createdTs } = progress;- if (updatedTs > 0 && createdTs > 0 && p > 0) {- const elapsedSeconds = progress.updatedTs - progress.createdTs;- const estimatedTotalSeconds = Math.floor(elapsedSeconds / p);- const eta = progress.createdTs + estimatedTotalSeconds;- result.eta = eta;- }-- return result;- }-- return ZERO;-});--const showPopover = computed((): boolean => {- return props.task.status !== "DONE";-});--const unitStr = computed(() => {- const { unitKey } = props;- if (!unitKey) {- return "";- }-- return t(`task.progress.units.${unitKey}`);-});-</script>diff --git a/frontend/src/components/Issue/TaskRunTable.vue b/frontend/src/components/Issue/TaskRunTable.vuedeleted file mode 100644index 77a6fa1603..0000000000--- a/frontend/src/components/Issue/TaskRunTable.vue+++ /dev/null@@ -1,187 +0,0 @@-<template>- <BBTable- :column-list="columnList"- :data-source="mergedTaskRunList"- :show-header="true"- :left-bordered="true"- :right-bordered="true"- :row-clickable="false"- >- <template- #body="{ rowData: { task, taskRun } }: { rowData: MergedTaskRunItem }"- >- <!-- Status icon -->- <BBTableCell :left-padding="4" class="table-cell w-4">- <div class="flex flex-row space-x-2">- <div- class="relative w-5 h-5 flex flex-shrink-0 items-center justify-center rounded-full select-none"- :class="statusIconClass(taskRun.status)"- >- <template v-if="taskRun.status == 'RUNNING'">- <span- class="h-2.5 w-2.5 bg-info rounded-full"- style="- animation: pulse 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;- "- aria-hidden="true"- />- </template>- <template v-else-if="taskRun.status == 'DONE'">- <heroicons-outline:check class="w-5 h-5" />- </template>- <template v-else-if="taskRun.status == 'FAILED'">- <span class="text-white font-medium text-base" aria-hidden="true"- >!</span- >- </template>- <template v-else-if="taskRun.status == 'CANCELED'">- <heroicons-outline:minus-sm class="w-5 h-5" />- </template>- </div>- </div>- </BBTableCell>- <!-- Comment message -->- <BBTableCell class="table-cell w-36 whitespace-pre-wrap break-words">- {{ comment(taskRun) }}- <template v-if="commentLink(task, taskRun).link">- <router-link- class="bb-comment-link ml-1 normal-link"- :to="commentLink(task, taskRun).link"- >{{ commentLink(task, taskRun).title }}</router-link- >- </template>- </BBTableCell>- <!-- Started -->- <BBTableCell class="table-cell w-12">- {{ dayjs(taskRun.createdTs * 1000).format("YYYY-MM-DD HH:mm") }}- </BBTableCell>- <!-- Ended -->- <BBTableCell class="table-cell w-12">- {{ humanizeDuration(taskRun.updatedTs - taskRun.createdTs) }}- </BBTableCell>- </template>- </BBTable>-</template>--<script lang="ts" setup>-import { computed, PropType } from "vue";-import { useI18n } from "vue-i18n";-import { BBTableColumn } from "@/bbkit/types";-import { useDatabaseV1Store } from "@/store";-import { MigrationErrorCode, Task, TaskRun, TaskRunStatus } from "@/types";-import { changeHistorySlug, databaseSlug, instanceSlug } from "@/utils";--type CommentLink = {- title: string;- link: string;-};--type MergedTaskRunItem = {- task: Task;- taskRun: TaskRun;-};--const props = defineProps({- taskList: {- required: true,- type: Array as PropType<Task[]>,- },-});--const { t } = useI18n();--const columnList = computed((): BBTableColumn[] => [- {- title: "",- },- {- title: t("task.comment"),- },- {- title: t("task.started"),- },- {- title: t("task.execution-time"),- },-]);--const mergedTaskRunList = computed(() => {- const taskRunList: MergedTaskRunItem[] = [];- props.taskList.forEach((task) => {- task.taskRunList.forEach((taskRun) => {- taskRunList.push({ task, taskRun });- });- });- taskRunList.sort((a, b) => {- return a.taskRun.updatedTs - b.taskRun.updatedTs;- });-- return taskRunList;-});--const statusIconClass = (status: TaskRunStatus) => {- switch (status) {- case "RUNNING":- return "bg-white border-2 border-info text-info";- case "DONE":- return "bg-success text-white";- case "FAILED":- return "bg-error text-white";- case "CANCELED":- return "bg-white border-2 border-gray-400 text-gray-400";- }-};--const comment = (taskRun: TaskRun): string => {- if (taskRun.status == "FAILED") {- return taskRun.result.detail;- }- // Returns result detail if we get the result, otherwise, returns the comment.- return taskRun.result.detail || taskRun.comment;-};--const commentLink = (task: Task, taskRun: TaskRun): CommentLink => {- if (taskRun.status == "DONE") {- switch (task.type) {- case "bb.task.database.schema.baseline":- case "bb.task.database.schema.update":- case "bb.task.database.schema.update-sdl":- case "bb.task.database.data.update": {- const db = useDatabaseV1Store().getDatabaseByUID(- String(task.database!.id)- );- const link = `/${db.name}/changeHistories/${changeHistorySlug(- taskRun.result.migrationId!,- taskRun.result.version!- )}`;- return {- title: t("task.view-change"),- link,- };- }- // TODO(jim): format for gh-ost related tasks- }- } else if (taskRun.status == "FAILED") {- if (taskRun.code == MigrationErrorCode.MIGRATION_SCHEMA_MISSING) {- return {- title: "Check instance",- link: `/instance/${instanceSlug(task.instance)}`,- };- } else if (- task.database &&- (taskRun.code == MigrationErrorCode.MIGRATION_ALREADY_APPLIED ||- taskRun.code == MigrationErrorCode.MIGRATION_OUT_OF_ORDER ||- taskRun.code == MigrationErrorCode.MIGRATION_BASELINE_MISSING)- ) {- return {- title: t("task.view-change-history"),- link: `/db/${databaseSlug(task.database!)}#change-history`,- };- }- }- return {- title: "",- link: "",- };-};-</script>diff --git a/frontend/src/components/Issue/TaskSelect.vue b/frontend/src/components/Issue/TaskSelect.vuedeleted file mode 100644index 70ad10313b..0000000000--- a/frontend/src/components/Issue/TaskSelect.vue+++ /dev/null@@ -1,80 +0,0 @@-<template>- <BBSelect- :selected-item="state.selectedTask"- :item-list="stage.taskList"- fit-width="min"- @select-item="(stage) => $emit('select-task-id', stage.id)"- >- <template #menuItem="{ item: task, index }">- {{ index + 1 }} -- {{- isActiveTask(task.id)- ? $t("issue.stage-select.active", { name: task.name })- : task.name- }}- </template>- </BBSelect>-</template>--<script lang="ts">-import { computed, defineComponent, PropType, reactive, watch } from "vue";-import { UNKNOWN_ID, Pipeline, TaskId, Stage, Task } from "../../types";-import { activeStage, activeTaskInStage } from "../../utils";--interface LocalState {- selectedId: number;- selectedTask: Task | undefined;-}--export default defineComponent({- name: "TaskSelect",- props: {- pipeline: {- required: true,- type: Object as PropType<Pipeline>,- },- stage: {- required: true,- type: Object as PropType<Stage>,- },- selectedId: {- default: UNKNOWN_ID,- type: Number as PropType<TaskId>,- },- },- emits: ["select-task-id"],- setup(props) {- const state = reactive<LocalState>({- selectedId: props.selectedId,- selectedTask: undefined,- });-- watch(- [() => props.selectedId, () => props.stage],- ([selectedId, stage]) => {- state.selectedTask = stage.taskList.find(- (task) => task.id === selectedId- );- },- { immediate: true }- );-- const isActiveStage = computed((): boolean => {- const stage = activeStage(props.pipeline);- return stage.id === props.stage.id;- });-- const isActiveTask = (taskId: TaskId): boolean => {- if (!isActiveStage.value) return false;- const task = activeTaskInStage(props.stage);- return task.id === taskId;- };-- return {- state,- isActiveStage,- isActiveTask,- };- },-});-</script>diff --git a/frontend/src/components/Issue/TaskSpinner.vue b/frontend/src/components/Issue/TaskSpinner.vuedeleted file mode 100644index 136816d722..0000000000--- a/frontend/src/components/Issue/TaskSpinner.vue+++ /dev/null@@ -1,30 +0,0 @@-<template>- <svg- class="animate-spin"- xmlns="http://www.w3.org/2000/svg"- fill="none"- viewBox="0 0 24 24"- >- <circle- class="opacity-25"- cx="12"- cy="12"- r="10"- stroke="currentColor"- stroke-width="4"- />- <path- class="opacity-75"- fill="currentColor"- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"- />- </svg>-</template>--<script lang="ts">-import { defineComponent } from "vue";--export default defineComponent({- name: "TaskSpinner",-});-</script>diff --git a/frontend/src/components/Issue/TaskStatusIcon.vue b/frontend/src/components/Issue/TaskStatusIcon.vuedeleted file mode 100644index e8cbcfd339..0000000000--- a/frontend/src/components/Issue/TaskStatusIcon.vue+++ /dev/null@@ -1,123 +0,0 @@-<template>- <div- class="relative flex flex-shrink-0 items-center justify-center rounded-full select-none w-6 h-6 overflow-hidden"- :class="classes"- >- <template v-if="taskCheckStatus === 'ERROR'">- <heroicons:exclamation-circle class="w-7 h-7 text-error" />- </template>- <template v-else-if="taskCheckStatus === 'WARN'">- <heroicons:exclamation-triangle class="w-7 h-7 text-warning" />- </template>- <template v-else-if="status === 'PENDING'">- <span- v-if="active"- class="h-2 w-2 bg-info rounded-full"- aria-hidden="true"- ></span>- <span- v-else- class="h-1.5 w-1.5 bg-control rounded-full"- aria-hidden="true"- ></span>- </template>- <template v-else-if="status === 'PENDING_APPROVAL'">- <heroicons-outline:user class="w-4 h-4" />- </template>- <template v-else-if="status === 'RUNNING'">- <div class="flex h-2.5 w-2.5 relative overflow-visible">- <span- class="w-full h-full rounded-full z-0 absolute animate-ping-slow"- style="background-color: rgba(37, 99, 235, 0.5); /* bg-info/50 */"- aria-hidden="true"- ></span>- <span- class="w-full h-full rounded-full z-[1] bg-info"- aria-hidden="true"- ></span>- </div>- </template>- <template v-else-if="status === 'DONE'">- <SkipIcon v-if="isSkipped" class="w-5 h-5" />- <heroicons-solid:check v-else class="w-5 h-5" />- </template>- <template v-else-if="status === 'FAILED'">- <span- class="h-2.5 w-2.5 rounded-full text-center pb-6 font-medium text-base"- aria-hidden="true"- >!</span- >- </template>- <template v-else-if="status === 'CANCELED'">- <heroicons-solid:minus-sm- class="w-6 h-6 rounded-full select-none bg-white border-2 border-gray-400 text-gray-400"- />- </template>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { checkStatusOfTask, isTaskSkipped } from "@/utils";-import type {- Task,- TaskCheckStatus,- TaskCreate,- TaskStatus,-} from "../../types";-import { SkipIcon } from "../Icon";--const props = defineProps<{- create: boolean;- active: boolean;- status: TaskStatus;- task?: Task | TaskCreate;- ignoreTaskCheckStatus?: boolean;-}>();--const isSkipped = computed(() => {- return !props.create && props.task && isTaskSkipped(props.task as Task);-});--const taskCheckStatus = computed((): TaskCheckStatus | undefined => {- if (props.ignoreTaskCheckStatus) return undefined;- if (!props.create && props.task) {- const task = props.task as Task;- return checkStatusOfTask(task);- }- return undefined;-});--const classes = computed((): string => {- if (taskCheckStatus.value === "ERROR") {- return "bg-white text-error !w-7";- }- if (taskCheckStatus.value === "WARN") {- return "bg-white text-warning !w-7";- }-- switch (props.status) {- case "PENDING":- if (!props.create && props.active) {- return "bg-white border-2 border-info text-info ";- }- return "bg-white border-2 border-control";- case "PENDING_APPROVAL":- if (!props.create && props.active) {- return "bg-white border-2 border-info text-info";- }- return "bg-white border-2 border-control";- case "RUNNING":- return "bg-white border-2 border-info text-info";- case "DONE":- if (isSkipped.value) {- return "bg-gray-200 text-gray-500";- }- return "bg-success text-white";- case "FAILED":- return "bg-error text-white";- default:- return "";- }-});-</script>diff --git a/frontend/src/components/Issue/form/GrantRequestExporterForm.vue b/frontend/src/components/Issue/form/GrantRequestExporterForm.vuedeleted file mode 100644index d38615d49f..0000000000--- a/frontend/src/components/Issue/form/GrantRequestExporterForm.vue+++ /dev/null@@ -1,130 +0,0 @@-<template>- <div- class="w-full mx-auto flex flex-col justify-start items-start mb-4 space-y-4"- >- <div class="w-full flex flex-col justify-start items-start">- <span class="flex items-center textlabel mb-2">- {{ $t("common.database") }}- </span>- <div- class="w-full flex flex-row justify-start items-start flex-wrap gap-2 gap-x-4"- >- <span- v-if="- exportMethod !== 'SQL' && selectedDatabaseResources.length === 0- "- >{{ $t("issue.grant-request.all-databases") }}</span- >- <DatabaseResourceTable- v-else- class="w-full"- :database-resource-list="selectedDatabaseResources"- />- </div>- </div>- <div- v-if="exportMethod === 'SQL'"- class="w-full flex flex-col justify-start items-start"- >- <span class="flex items-center textlabel mb-2">SQL</span>- <div class="w-full border rounded">- <MonacoEditor- class="w-full h-[300px] py-2"- readonly- :value="state.statement"- :auto-focus="false"- :language="'sql'"- />- </div>- </div>- <div class="w-full flex flex-col justify-start items-start">- <span class="flex items-center textlabel mb-2">- {{ $t("issue.grant-request.export-rows") }}- </span>- <div class="flex flex-row justify-start items-start">- {{ state.maxRowCount }}- </div>- </div>- <div class="w-full flex flex-col justify-start items-start">- <span class="flex items-center textlabel mb-2">- {{ $t("issue.grant-request.export-format") }}- </span>- <div class="flex flex-row justify-start items-start">- {{ state.exportFormat }}- </div>- </div>- <div class="w-full flex flex-col justify-start items-start">- <span class="flex items-center textlabel mb-2">- {{ $t("issue.grant-request.expired-at") }}- </span>- <div>- {{ state.expiredAt }}- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import dayjs from "dayjs";-import { computed, onMounted, reactive, ref } from "vue";-import MonacoEditor from "@/components/MonacoEditor";-import { GrantRequestPayload, Issue, PresetRoleType } from "@/types";-import { DatabaseResource } from "@/types";-import { convertFromCELString } from "@/utils/issue/cel";-import { useIssueLogic } from "../logic";-import DatabaseResourceTable from "../table/DatabaseResourceTable.vue";--interface LocalState {- maxRowCount: number;- exportFormat: "CSV" | "JSON";- statement: string;- expiredAt: string;-}--const { issue } = useIssueLogic();-const state = reactive<LocalState>({- maxRowCount: 1000,- exportFormat: "CSV",- statement: "",- expiredAt: "",-});-const selectedDatabaseResources = ref<DatabaseResource[]>([]);--const exportMethod = computed(() => {- return state.statement === "" ? "DATABASE" : "SQL";-});--onMounted(async () => {- const payload = ((issue.value as Issue).payload as any)- .grantRequest as GrantRequestPayload;- if (payload.role !== PresetRoleType.EXPORTER) {- throw "Only support EXPORTER role";- }-- const conditionExpression = await convertFromCELString(- payload.condition.expression- );- if (- conditionExpression.databaseResources !== undefined &&- conditionExpression.databaseResources.length > 0- ) {- selectedDatabaseResources.value = conditionExpression.databaseResources;- }- if (conditionExpression.expiredTime !== undefined) {- state.expiredAt = dayjs(new Date(conditionExpression.expiredTime)).format(- "LLL"- );- } else {- state.expiredAt = "-";- }- if (conditionExpression.statement !== undefined) {- state.statement = conditionExpression.statement;- }- if (conditionExpression.rowLimit !== undefined) {- state.maxRowCount = conditionExpression.rowLimit;- }- if (conditionExpression.exportFormat !== undefined) {- state.exportFormat = conditionExpression.exportFormat as "CSV" | "JSON";- }-});-</script>diff --git a/frontend/src/components/Issue/form/GrantRequestQuerierForm.vue b/frontend/src/components/Issue/form/GrantRequestQuerierForm.vuedeleted file mode 100644index 0f0fe53033..0000000000--- a/frontend/src/components/Issue/form/GrantRequestQuerierForm.vue+++ /dev/null@@ -1,88 +0,0 @@-<template>- <div- class="w-full mx-auto flex flex-col justify-start items-start space-y-4 gap-4 mb-4"- >- <div class="w-full flex flex-col justify-start items-start">- <span class="flex w-full items-center textlabel mb-2">- {{ $t("common.databases") }}- </span>- <div- class="w-full flex flex-row justify-start items-start flex-wrap gap-2 gap-x-4"- >- <span v-if="state.selectedDatabaseResourceList.length === 0">{{- $t("issue.grant-request.all-databases")- }}</span>- <DatabaseResourceTable- v-else- class="w-full"- :database-resource-list="state.selectedDatabaseResourceList"- />- </div>- </div>- <div class="w-full flex flex-col justify-start items-start">- <span class="flex w-full items-center textlabel mb-4">- {{ $t("issue.grant-request.expired-at") }}- </span>- <div>- {{ state.expiredAt }}- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import dayjs from "dayjs";-import { onMounted, reactive } from "vue";-import {- DatabaseResource,- GrantRequestPayload,- Issue,- PresetRoleType,-} from "@/types";-import { convertFromCELString } from "@/utils/issue/cel";-import { useIssueLogic } from "../logic";-import DatabaseResourceTable from "../table/DatabaseResourceTable.vue";--interface LocalState {- projectId?: string;- allDatabases: boolean;- selectedDatabaseResourceList: DatabaseResource[];- expireDays: number;- customDays: number;- // For reviewing- expiredAt: string;-}--const { issue } = useIssueLogic();-const state = reactive<LocalState>({- projectId: undefined,- allDatabases: true,- selectedDatabaseResourceList: [],- expireDays: 7,- customDays: 7,- expiredAt: "",-});--onMounted(async () => {- const payload = ((issue.value as Issue).payload as any)- .grantRequest as GrantRequestPayload;- if (payload.role !== PresetRoleType.QUERIER) {- throw "Only support QUERIER role";- }-- const conditionExpression = await convertFromCELString(- payload.condition.expression- );- if (conditionExpression.expiredTime !== undefined) {- state.expiredAt = dayjs(new Date(conditionExpression.expiredTime)).format(- "LLL"- );- }- if (- conditionExpression.databaseResources !== undefined &&- conditionExpression.databaseResources.length > 0- ) {- state.selectedDatabaseResourceList = conditionExpression.databaseResources;- }-});-</script>diff --git a/frontend/src/components/Issue/index.ts b/frontend/src/components/Issue/index.tsdeleted file mode 100644index a667ce1ebd..0000000000--- a/frontend/src/components/Issue/index.ts+++ /dev/null@@ -1,25 +0,0 @@-import IssueActivityPanel from "./IssueActivityPanel.vue";-import IssueBanner from "./IssueBanner.vue";-import IssueDescriptionPanel from "./IssueDescriptionPanel.vue";-import IssueHighlightPanel from "./IssueHighlightPanel.vue";-import IssueOutputPanel from "./IssueOutputPanel.vue";-import IssueSidebar from "./IssueSidebar.vue";-import IssueStagePanel from "./IssueStagePanel.vue";-import IssueTaskStatementPanel from "./IssueTaskStatementPanel.vue";-import PipelineSimpleFlow from "./PipelineSimpleFlow.vue";-import TaskCheckBar from "./TaskCheckBar.vue";-import IssueTable from "./table/IssueTable.vue";--export {- IssueBanner,- IssueHighlightPanel,- IssueStagePanel,- IssueOutputPanel,- IssueSidebar,- IssueTaskStatementPanel,- IssueDescriptionPanel,- IssueActivityPanel,- PipelineSimpleFlow,- TaskCheckBar,- IssueTable,-};diff --git a/frontend/src/components/Issue/layout/DatabaseRelatedDetail.vue b/frontend/src/components/Issue/layout/DatabaseRelatedDetail.vuedeleted file mode 100644index fe33ec936c..0000000000--- a/frontend/src/components/Issue/layout/DatabaseRelatedDetail.vue+++ /dev/null@@ -1,410 +0,0 @@-<template>- <component :is="logicProviderType" ref="issueLogic">- <div- id="issue-detail-top"- class="flex-1 overflow-auto focus:outline-none"- tabindex="0"- >- <IssueBanner v-if="!create" />-- <!-- Highlight Panel -->- <div class="bg-white px-4 pb-4">- <IssueHighlightPanel>- <template #tips>- <IssueRollbackFromTips />- </template>- </IssueHighlightPanel>- </div>-- <!-- Stage Flow Bar -->- <template v-if="showPipelineFlowBar">- <template v-if="isGhostMode">- <PipelineGhostFlow v-if="project" class="border-t border-b" />- </template>- <template v-else-if="isTenantMode">- <PipelineTenantFlow v-if="project" class="border-t border-b" />- </template>- <template v-else-if="isPITRMode">- <PipelinePITRFlow v-if="project" class="border-t border-b" />- </template>- <template v-else>- <PipelineSimpleFlow class="border-t border-b" />- </template>-- <IssueStagePanel- v-if="!create"- class="px-4 py-4 md:flex md:flex-col border-b"- />- </template>-- <!-- Output Panel -->- <!-- Only render the top border if PipelineFlowBar is not displayed, otherwise it would overlap with the bottom border of that -->- <div- v-if="showIssueOutputPanel"- class="px-2 py-4 md:flex md:flex-col"- :class="showPipelineFlowBar ? '' : 'lg:border-t'"- >- <IssueOutputPanel />- </div>-- <!-- Main Content -->- <main- class="flex-1 relative overflow-y-auto focus:outline-none"- :class="- showPipelineFlowBar && !showIssueOutputPanel- ? ''- : 'lg:border-t lg:border-block-border'- "- tabindex="-1"- >- <div class="flex max-w-3xl mx-auto px-6 lg:max-w-full">- <div- class="flex flex-col flex-1 lg:flex-row-reverse lg:col-span-2 overflow-x-hidden"- >- <div- class="py-6 lg:pl-4 lg:w-72 xl:w-96 lg:border-l lg:border-block-border overflow-hidden"- >- <IssueSidebar :database="selectedDatabase" :instance="instance" />- </div>- <div class="lg:hidden border-t border-block-border" />- <div class="w-full lg:w-auto lg:flex-1 py-4 pr-4 overflow-x-hidden">- <div v-if="!create" class="mb-4">- <TaskCheckBar- :task="(selectedTask as Task)"- @run-checks="runTaskChecks"- />- </div>- <section v-if="showIssueTaskSDLPanel" class="mb-4">- <IssueTaskSDLPanel />- </section>- <section v-if="showIssueTaskStatementPanel" class="border-b mb-4">- <IssueTaskStatementPanel :sql-hint="sqlHint()" />- </section>-- <IssueDescriptionPanel />-- <section- v-if="!create"- aria-labelledby="activity-title"- class="mt-4"- >- <IssueActivityPanel />- </section>- </div>- </div>- </div>- </main>- </div>- </component>-</template>--<script lang="ts" setup>-import { useDialog } from "naive-ui";-import { computed, onMounted, PropType, ref, watch, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute } from "vue-router";-import { defaultTemplate, templateForType } from "@/plugins";-import { useInstanceV1Store, useProjectV1Store, useTaskStore } from "@/store";-import type {- Issue,- IssueCreate,- Task,- TaskCreate,- MigrationType,-} from "@/types";-import { Engine } from "@/types/proto/v1/common";-import {- pipelineType,- PipelineType,- activeStage as activeStageOfPipeline,- activeTaskInStage,- activeTask as activeTaskOfPipeline,-} from "@/utils";-import IssueActivityPanel from "../IssueActivityPanel.vue";-import IssueBanner from "../IssueBanner.vue";-import IssueDescriptionPanel from "../IssueDescriptionPanel.vue";-import IssueHighlightPanel from "../IssueHighlightPanel.vue";-import IssueOutputPanel from "../IssueOutputPanel.vue";-import IssueRollbackFromTips from "../IssueRollbackFromTips.vue";-import IssueSidebar from "../IssueSidebar.vue";-import IssueStagePanel from "../IssueStagePanel.vue";-import IssueTaskSDLPanel from "../IssueTaskSDLPanel.vue";-import IssueTaskStatementPanel from "../IssueTaskStatementPanel.vue";-import PipelineGhostFlow from "../PipelineGhostFlow.vue";-import PipelinePITRFlow from "../PipelinePITRFlow.vue";-import PipelineSimpleFlow from "../PipelineSimpleFlow.vue";-import PipelineTenantFlow from "../PipelineTenantFlow.vue";-import TaskCheckBar from "../TaskCheckBar.vue";-import {- provideIssueLogic,- TenantModeProvider,- GhostModeProvider,- StandardModeProvider,- TaskTypeWithStatement,- IssueLogic,- useBaseIssueLogic,-} from "../logic";--const props = defineProps({- create: {- type: Boolean,- required: true,- },- issue: {- type: Object as PropType<Issue | IssueCreate>,- required: true,- },-});--const emit = defineEmits<{- (e: "status-changed", eager: boolean): void;-}>();--const { t } = useI18n();--const route = useRoute();--const taskStore = useTaskStore();-const projectV1Store = useProjectV1Store();--const create = computed(() => props.create);-const issue = computed(() => props.issue);--const dialog = useDialog();--const {- project,- isTenantMode,- isGhostMode,- isPITRMode,- createIssue,- selectedStage,- selectedTask,- selectedDatabase,- selectStageOrTask,- selectTask,- taskStatusOfStage,- isValidStage,- allowApplyIssueStatusTransition,- allowApplyTaskStatusTransition,- selectedStatement,- allowApplyTaskStateToOthers,- applyTaskStateToOthers,-} = useBaseIssueLogic({ issue, create });--const issueLogic = ref<IssueLogic>();--// Determine which type of IssueLogicProvider should be used-const logicProviderType = computed(() => {- if (isGhostMode.value) return GhostModeProvider;- if (isTenantMode.value) return TenantModeProvider;- return StandardModeProvider;-});--watchEffect(() => {- if (props.create) {- projectV1Store.getOrFetchProjectByUID(- String((props.issue as IssueCreate).projectId)- );- }-});--const issueTemplate = computed(- () => templateForType(props.issue.type) || defaultTemplate()-);--const runTaskChecks = (taskList: Task[]) => {- const requests = taskList.map((task) => {- return taskStore.runChecks({- issueId: (props.issue as Issue).id,- pipelineId: (props.issue as Issue).pipeline!.id,- taskId: task.id,- });- });- Promise.allSettled(requests).then(() => {- emit("status-changed", true);- });-};--const currentPipelineType = computed((): PipelineType => {- return pipelineType(props.issue.pipeline!);-});--const selectedMigrateType = computed((): MigrationType => {- const taskType = selectedTask.value.type;- if (taskType === "bb.task.database.schema.baseline") {- // The new version of BASELINE tasks- return "BASELINE";- }- if (!props.create && taskType === "bb.task.database.schema.update") {- // Legacy BASELINE task support- // Their `type`s are "bb.task.database.schema.update"- // And their `payload.migrationType`s are "BASELINE"- const { payload } = selectedTask.value as Task;- if ((payload as any).migrationType === "BASELINE") {- return "BASELINE";- }- }- if (taskType === "bb.task.database.data.update") {- // A "Change data" task- return "DATA";- }- // Fall back to MIGRATE otherwise- return "MIGRATE";-});--const showPipelineFlowBar = computed(() => {- return currentPipelineType.value !== "NO_PIPELINE";-});--const showIssueOutputPanel = computed(() => {- return !props.create && issueTemplate.value.outputFieldList.length > 0;-});--const showIssueTaskSDLPanel = computed(() => {- if (create.value) return false;- const task = selectedTask.value as Task;- return task.type === "bb.task.database.schema.update-sdl";-});--const showIssueTaskStatementPanel = computed(() => {- if (showIssueTaskSDLPanel.value) return false;-- const task = selectedTask.value;- if (task.type === "bb.task.database.schema.baseline" && !create.value) {- return false;- }- return TaskTypeWithStatement.includes(task.type);-});--const instance = computed(() => {- if (props.create) {- // If database is available, then we derive the instance from database because we always fetch database's instance.- if (selectedDatabase.value) {- return selectedDatabase.value.instanceEntity;- }- return useInstanceV1Store().getInstanceByUID(- String((selectedTask.value as TaskCreate).instanceId)- );- }-- return useInstanceV1Store().getInstanceByUID(- String((selectedTask.value as Task).instance.id)- );-});--const sqlHint = (): string | undefined => {- if (selectedMigrateType.value === "BASELINE") {- return t("issue.sql-hint.dont-apply-to-database-in-baseline-migration");- }- if (instance.value.engine === Engine.SNOWFLAKE) {- return t("issue.sql-hint.snowflake");- }- if (isTenantMode.value) {- return t("issue.sql-hint.change-will-apply-to-all-tasks-in-tenant-mode");- }- return undefined;-};--onMounted(() => {- // Always scroll to top, the scrollBehavior doesn't seem to work.- // The hypothesis is that because the scroll bar is in the nested- // route, thus setting the scrollBehavior in the global router- // won't work.- // BUT when we have a location.hash #activity(\d+) we won't scroll to the top,- // since #activity(\d+) is used as an activity anchor- if (!location.hash.match(/^#activity(\d+)/)) {- document.getElementById("issue-detail-top")!.scrollIntoView();- }-});--watch(- [- create,- issue,- () => route.query.sqlList as string,- () => route.query.sql as string,- issueLogic,- ],- ([create, issue, sqlList, sql, provider]) => {- if (create && issue && provider) {- if (sql) {- // If 'sql' in URL query, update the issueCreate's statement- // Only works for the first time.- // E.g. redirected from SQL editor when user wants to execute DML.- provider.updateStatement(sql);- } else {- // Initial the tasks's statement/sheetId in issueCreate from current route.- provider.initialTaskListStatementFromRoute();- }- }- }-);--// When activeTask is changed, we automatically select it.-// This enables users to know the pipeline status has changed and we may move forward.-const autoSelectWhenStatusChanged = (immediate: boolean) => {- const activeTask = computed((): Task | undefined => {- if (create.value) return undefined;- const { pipeline } = issue.value as Issue;- if (!pipeline) return undefined;- const task = activeTaskOfPipeline(pipeline);- return task;- });-- watch(- // Watch the task.id instead of the task object itself, Since the object might- // sometimes drift to another object reference when polling the issue.- () => activeTask.value?.id,- () => {- const task = activeTask.value;- if (!task) return;- selectTask(task);- },- // Also triggered when the first time the page is loaded.- { immediate }- );-};--const onStatusChanged = (eager: boolean) => emit("status-changed", eager);--if (route.query.stage || route.query.task) {- // If we have selected stage/task in URL, don't switch to activeTask immediately.- autoSelectWhenStatusChanged(false);-} else {- // Otherwise, automatically switch to the active task immediately.- autoSelectWhenStatusChanged(true);-}--provideIssueLogic(- {- create,- issue,- project,- template: issueTemplate,- selectedStage,- selectedTask,- selectedDatabase,- isTenantMode,- isGhostMode,- isPITRMode,- isValidStage,- taskStatusOfStage,- activeStageOfPipeline,- activeTaskOfPipeline,- activeTaskOfStage: activeTaskInStage,- selectStageOrTask,- selectTask,- onStatusChanged,- createIssue,- allowApplyIssueStatusTransition,- allowApplyTaskStatusTransition,- selectedStatement,- allowApplyTaskStateToOthers,- applyTaskStateToOthers,- dialog,- },- true- // This is the root logic, could be overwritten by other (standard, gh-ost, tenant...) logic providers.-);-</script>diff --git a/frontend/src/components/Issue/layout/GrantRequestDetail.vue b/frontend/src/components/Issue/layout/GrantRequestDetail.vuedeleted file mode 100644index 1a9c7f2b3d..0000000000--- a/frontend/src/components/Issue/layout/GrantRequestDetail.vue+++ /dev/null@@ -1,169 +0,0 @@-<template>- <component :is="GrantRequestModeProvider" ref="issueLogic">- <div- id="issue-detail-top"- class="flex-1 overflow-auto focus:outline-none"- tabindex="0"- >- <IssueBanner v-if="!create" />-- <!-- Highlight Panel -->- <div class="bg-white px-4 pb-4">- <IssueHighlightPanel />- </div>-- <!-- Main Content -->- <main- class="flex-1 relative overflow-y-auto focus:outline-none lg:border-t lg:border-block-border"- tabindex="-1"- >- <div class="flex max-w-3xl mx-auto px-6 lg:max-w-full">- <div- class="flex flex-col flex-1 lg:flex-row-reverse lg:col-span-2 overflow-x-hidden"- >- <div- v-if="!create"- class="py-6 lg:pl-4 lg:w-72 xl:w-96 lg:border-l lg:border-block-border overflow-hidden"- >- <GrantRequestIssueSidebar />- </div>- <div class="lg:hidden border-t border-block-border" />- <div class="w-full lg:w-auto lg:flex-1 py-4 pr-4 overflow-x-hidden">- <GrantRequestExporterForm v-if="requestRole === 'EXPORTER'" />- <GrantRequestQuerierForm v-if="requestRole === 'QUERIER'" />- <IssueDescriptionPanel />- <section- v-if="!create"- aria-labelledby="activity-title"- class="mt-4"- >- <IssueActivityPanel />- </section>- </div>- </div>- </div>- </main>- </div>- </component>-</template>--<script lang="ts" setup>-import { useDialog } from "naive-ui";-import { computed, onMounted, PropType, ref, watchEffect, watch } from "vue";-import { defaultTemplate, templateForType } from "@/plugins";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { useProjectIamPolicyStore, useProjectV1Store } from "@/store";-import {- GrantRequestContext,- GrantRequestPayload,- Issue,- IssueCreate,- UNKNOWN_ID,-} from "@/types";-import GrantRequestIssueSidebar from "../GrantRequestIssueSidebar.vue";-import IssueActivityPanel from "../IssueActivityPanel.vue";-import IssueBanner from "../IssueBanner.vue";-import IssueDescriptionPanel from "../IssueDescriptionPanel.vue";-import IssueHighlightPanel from "../IssueHighlightPanel.vue";-import GrantRequestExporterForm from "../form/GrantRequestExporterForm.vue";-import GrantRequestQuerierForm from "../form/GrantRequestQuerierForm.vue";-import {- provideIssueLogic,- IssueLogic,- GrantRequestModeProvider,-} from "../logic";-import { useGrantRequestIssueLogic } from "../logic/grantRequest";--const props = defineProps({- create: {- type: Boolean,- required: true,- },- issue: {- type: Object as PropType<Issue | IssueCreate>,- required: true,- },-});--const emit = defineEmits<{- (e: "status-changed", eager: boolean): void;-}>();--const projectV1Store = useProjectV1Store();--const create = computed(() => props.create);-const issue = computed(() => props.issue);--const dialog = useDialog();-const { project, createIssue } = useGrantRequestIssueLogic({ issue, create });-const reviewContext = useIssueReviewContext();-const issueLogic = ref<IssueLogic>();--watchEffect(() => {- if (props.create) {- const projectId = String((props.issue as IssueCreate).projectId);- if (projectId !== String(UNKNOWN_ID)) {- projectV1Store.getOrFetchProjectByUID(projectId);- }- }-});--const issueTemplate = computed(- () => templateForType(props.issue.type) || defaultTemplate()-);--const requestRole = computed(() => {- if (create.value) {- return ((issue.value as IssueCreate).createContext as GrantRequestContext)- .role;- } else {- const payload = ((issue.value as Issue).payload as any)- .grantRequest as GrantRequestPayload;- return payload.role.replace(/^roles\//, "");- }-});--onMounted(() => {- if (requestRole.value !== "EXPORTER" && requestRole.value !== "QUERIER") {- console.error("Invalid request role", requestRole.value);- return;- }- // Always scroll to top, the scrollBehavior doesn't seem to work.- // The hypothesis is that because the scroll bar is in the nested- // route, thus setting the scrollBehavior in the global router- // won't work.- // BUT when we have a location.hash #activity(\d+) we won't scroll to the top,- // since #activity(\d+) is used as an activity anchor- if (!location.hash.match(/^#activity(\d+)/)) {- document.getElementById("issue-detail-top")!.scrollIntoView();- }-});--const onStatusChanged = (eager: boolean) => emit("status-changed", eager);--watch(- () => reviewContext.done.value,- () => {- // After the grant request issue's review is done, we need to fetch the latest project IAM policy.- if (reviewContext.done.value) {- useProjectIamPolicyStore().fetchProjectIamPolicy(- project.value.name,- true /* Skip cache */- );- }- }-);--provideIssueLogic(- {- create,- issue,- project,- template: issueTemplate,- onStatusChanged,- createIssue,- dialog,- },- true-);-</script>diff --git a/frontend/src/components/Issue/logic/GhostModeProvider.ts b/frontend/src/components/Issue/logic/GhostModeProvider.tsdeleted file mode 100644index 9f5e790b94..0000000000--- a/frontend/src/components/Issue/logic/GhostModeProvider.ts+++ /dev/null@@ -1,303 +0,0 @@-import { cloneDeep } from "lodash-es";-import { v4 as uuidv4 } from "uuid";-import { computed, defineComponent } from "vue";-import {- useSheetV1Store,- useSheetStatementByUID,- useTaskStore,- useDatabaseV1Store,-} from "@/store";-import {- Issue,- IssueCreate,- Task,- TaskCreate,- TaskDatabaseSchemaUpdateGhostSyncPayload,- TaskStatus,- MigrationContext,- SheetId,- UNKNOWN_ID,-} from "@/types";-import {- Sheet_Visibility,- Sheet_Source,- Sheet_Type,-} from "@/types/proto/v1/sheet_service";-import { extractSheetUID, sheetIdOfTask } from "@/utils";-import {- flattenTaskList,- maybeFormatStatementOnSave,- TaskTypeWithStatement,- useCommonLogic,-} from "./common";-import { provideIssueLogic, useIssueLogic } from "./index";--export default defineComponent({- name: "GhostModeProvider",- setup() {- const {- create,- issue,- project,- selectedTask,- createIssue,- isTenantMode,- allowApplyTaskStatusTransition: baseAllowApplyTaskStatusTransition,- allowApplyTaskStateToOthers: baseAllowApplyTaskStateToOthers,- applyTaskStateToOthers: baseApplyTaskStateToOthers,- onStatusChanged,- } = useIssueLogic();- const databaseStore = useDatabaseV1Store();- const taskStore = useTaskStore();- const sheetV1Store = useSheetV1Store();-- const selectedStatement = computed(() => {- if (isTenantMode.value) {- // In tenant mode, the entire issue shares only one SQL statement- if (create.value) {- const issueCreate = issue.value as IssueCreate;- const context = issueCreate.createContext as MigrationContext;- return (- useSheetStatementByUID(String(context.detailList[0].sheetId))- .value || ""- );- } else {- const issueEntity = issue.value as Issue;- const task = issueEntity.pipeline!.stageList[0].taskList[0];- const payload =- task.payload as TaskDatabaseSchemaUpdateGhostSyncPayload;- return useSheetStatementByUID(String(payload.sheetId)).value || "";- }- } else {- // In standard pipeline, each ghost-sync task can hold its own- // statement- const task = selectedTask.value;- if (task.type === "bb.task.database.schema.update.ghost.sync") {- if (create.value) {- let statement = (task as TaskCreate).statement;- if ((task as TaskCreate).sheetId !== UNKNOWN_ID) {- statement =- useSheetStatementByUID(String((task as TaskCreate).sheetId))- .value || "";- }- return statement;- } else {- return (- useSheetStatementByUID(- String(sheetIdOfTask(task as Task) || UNKNOWN_ID)- ).value || ""- );- }- } else {- return "";- }- }- });-- const updateStatement = async (newStatement: string) => {- if (isTenantMode.value) {- if (create.value) {- const task = selectedTask.value as TaskCreate;- // For tenant deploy mode, we apply the statement to all stages and all tasks- const allTaskList = flattenTaskList<TaskCreate>(issue.value);- allTaskList.forEach((taskItem) => {- if (TaskTypeWithStatement.includes(taskItem.type)) {- if (task.sheetId) {- taskItem.statement = "";- taskItem.sheetId = task.sheetId;- } else {- taskItem.statement = newStatement;- }- }- });-- const issueCreate = issue.value as IssueCreate;- const context = issueCreate.createContext as MigrationContext;- // We also apply it back to the CreateContext- context.detailList.forEach((detail) => {- if (task.sheetId) {- detail.statement = "";- detail.sheetId = task.sheetId;- } else {- detail.statement = newStatement;- }- });- } else {- const sheetId = sheetIdOfTask(selectedTask.value as Task);- if (sheetId && sheetId !== UNKNOWN_ID) {- // Call patchAllTasksInIssue for tenant mode- const issueEntity = issue.value as Issue;- await taskStore.patchAllTasksInIssue({- issueId: issueEntity.id,- pipelineId: issueEntity.pipeline!.id,- taskPatch: {- sheetId,- },- });- onStatusChanged(true);- }- }- } else {- if (create.value) {- const task = selectedTask.value as TaskCreate;- task.statement = newStatement;- } else {- const task = selectedTask.value as Task;- // Create a new sheet instead of reusing the old one.- const sheet = await sheetV1Store.createSheet(project.value.name, {- title: uuidv4(),- content: new TextEncoder().encode(newStatement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- });-- await taskStore.patchTask({- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline!.id,- taskId: task.id,- taskPatch: {- sheetId: Number(extractSheetUID(sheet.name)),- },- });- onStatusChanged(true);- }- }- };-- const updateSheetId = (sheetId: SheetId) => {- if (isTenantMode.value) {- // For tenant deploy mode, we apply the sheetId to all stages and all tasks- const allTaskList = flattenTaskList<TaskCreate>(issue.value);- allTaskList.forEach((task) => {- task.statement = "";- task.sheetId = sheetId;- });-- const issueCreate = issue.value as IssueCreate;- const context = issueCreate.createContext as MigrationContext;- context.detailList.forEach((detail) => {- detail.statement = "";- detail.sheetId = sheetId;- });- } else {- const task = selectedTask.value as TaskCreate;- task.statement = "";- task.sheetId = sheetId;- }- };-- const doCreate = async () => {- const issueCreate = cloneDeep(issue.value as IssueCreate);-- if (isTenantMode.value) {- // for tenant pipeline- // createContext is up-to-date already- // so we just format the statement if needed- const context = issueCreate.createContext as MigrationContext;- for (const detail of context.detailList) {- const db = databaseStore.getDatabaseByUID(String(detail.databaseId!));- if (!detail.sheetId || detail.sheetId === UNKNOWN_ID) {- const statement = maybeFormatStatementOnSave(detail.statement, db);- const sheet = await sheetV1Store.createSheet(db.project, {- title: issueCreate.name + " - " + db.databaseName,- content: new TextEncoder().encode(statement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- payload: "{}",- });- detail.statement = "";- detail.sheetId = Number(extractSheetUID(sheet.name));- }- }- } else {- // for standard pipeline, we copy user edited tasks back to- // issue.createContext- // For each ghost-sync task, we copy its edited statement back to the- // createContext.detailList by its databaseId accordingly.- const createContext = issueCreate.createContext as MigrationContext;- const syncTaskList = flattenTaskList<TaskCreate>(issueCreate).filter(- (task) => task.type === "bb.task.database.schema.update.ghost.sync"- );- const detailList = createContext.detailList;- for (const task of syncTaskList) {- const { databaseId } = task;- if (!databaseId) return;- const detail = detailList.find(- (detail) => detail.databaseId === databaseId- );- if (detail) {- const db = databaseStore.getDatabaseByUID(String(databaseId));- if (!detail.sheetId || detail.sheetId === UNKNOWN_ID) {- const statement = maybeFormatStatementOnSave(task.statement, db);- const sheet = await sheetV1Store.createSheet(db.project, {- title: issueCreate.name + " - " + db.name,- content: new TextEncoder().encode(statement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- payload: "{}",- });- detail.statement = "";- detail.sheetId = Number(extractSheetUID(sheet.name));- }- detail.earliestAllowedTs = task.earliestAllowedTs;- }- }- }-- createIssue(issueCreate);- };-- const allowApplyTaskStatusTransition = (- task: Task,- to: TaskStatus- ): boolean => {- if (- task.type === "bb.task.database.schema.update.ghost.cutover" &&- task.status === "FAILED"- ) {- if (to === "PENDING" || to === "RUNNING") {- // RETRYing gh-ost cut-over task is not allowed (yet).- return false;- }- }- if (- task.type === "bb.task.database.schema.update.ghost.sync" &&- to === "CANCELED"- ) {- // CANCELing gh-ost sync task is allowed.- return true;- }- return baseAllowApplyTaskStatusTransition(task, to);- };-- const allowApplyTaskStateToOthers = computed(() => {- // We are never allowed to "apply task state to other stages" in tenant mode.- if (isTenantMode.value) return false;- return baseAllowApplyTaskStateToOthers.value;- });-- const applyTaskStateToOthers = (task: TaskCreate) => {- if (!allowApplyTaskStateToOthers.value) return;- return baseApplyTaskStateToOthers(task);- };-- const logic = {- ...useCommonLogic(),- selectedStatement,- doCreate,- allowApplyTaskStatusTransition,- allowApplyTaskStateToOthers,- applyTaskStateToOthers,- updateStatement,- updateSheetId,- };- provideIssueLogic(logic);- return logic;- },- render() {- return this.$slots.default?.();- },-});diff --git a/frontend/src/components/Issue/logic/GrantRequestModeProvider.ts b/frontend/src/components/Issue/logic/GrantRequestModeProvider.tsdeleted file mode 100644index afb21c9e27..0000000000--- a/frontend/src/components/Issue/logic/GrantRequestModeProvider.ts+++ /dev/null@@ -1,21 +0,0 @@-import { defineComponent, onMounted } from "vue";-import { useProjectV1Store } from "@/store";-import { provideIssueLogic, useCommonLogic } from "./index";--export default defineComponent({- name: "GrantRequestModeProvider",- setup() {- onMounted(() => {- useProjectV1Store().fetchProjectList();- });-- const logic = {- ...useCommonLogic(),- };- provideIssueLogic(logic);- return logic;- },- render() {- return this.$slots.default?.();- },-});diff --git a/frontend/src/components/Issue/logic/IssueLogic.ts b/frontend/src/components/Issue/logic/IssueLogic.tsdeleted file mode 100644index a68877555d..0000000000--- a/frontend/src/components/Issue/logic/IssueLogic.ts+++ /dev/null@@ -1,84 +0,0 @@-import { type useDialog } from "naive-ui";-import type { Ref } from "vue";-import { IssueTemplate } from "@/plugins";-import {- ComposedDatabase,- ComposedProject,- Issue,- IssueCreate,- IssuePatch,- IssueStatus,- Pipeline,- SheetId,- Stage,- StageCreate,- Task,- TaskCreate,- TaskId,- TaskPatch,- TaskStatus,-} from "@/types";--type IssueLogic = {- // base params- create: Ref<boolean>;- project: Ref<ComposedProject>;- issue: Ref<Issue | IssueCreate>;- template: Ref<IssueTemplate>;-- // states- selectedStage: Ref<Stage | StageCreate>;- selectedTask: Ref<Task | TaskCreate>;- selectedDatabase: Ref<ComposedDatabase | undefined>;-- // ui state logic- isTenantMode: Ref<boolean>;- isGhostMode: Ref<boolean>;- isPITRMode: Ref<boolean>;- isValidStage: (stage: Stage | StageCreate, index: number) => boolean;- activeStageOfPipeline: (pipeline: Pipeline) => Stage;- activeTaskOfPipeline: (pipeline: Pipeline) => Task;- activeTaskOfStage: (stage: Stage) => Task;- taskStatusOfStage: (stage: Stage | StageCreate, index: number) => TaskStatus;-- // api endpoint- patchTask: (- taskId: TaskId,- taskPatch: TaskPatch,- postUpdated?: (updatedTask: Task) => void- ) => any;- patchIssue: (- issuePatch: IssuePatch,- postUpdated?: (updatedIssue: Issue) => void- ) => any;- createIssue: (issueCreate: IssueCreate) => any;-- // state logic- initialTaskListStatementFromRoute: () => any;-- // edit logic- allowEditStatement: Ref<boolean>;- selectedStatement: Ref<string>;- updateStatement: (newStatement: string) => any;- updateSheetId: (sheetId: SheetId) => void;- allowApplyTaskStateToOthers: Ref<boolean>;- applyTaskStateToOthers: (task: TaskCreate) => any;- doCreate(): any;-- // events- onStatusChanged: (eager: boolean) => void;- selectStageOrTask: (- stageIdOrIndex: number,- taskSlug?: string | undefined- ) => void;- selectTask: (task: Task) => void;-- // status transition- allowApplyIssueStatusTransition(issue: Issue, to: IssueStatus): boolean;- allowApplyTaskStatusTransition(task: Task, to: TaskStatus): boolean;-- // misc- dialog: ReturnType<typeof useDialog>;-};--export default IssueLogic;diff --git a/frontend/src/components/Issue/logic/StandardModeProvider.ts b/frontend/src/components/Issue/logic/StandardModeProvider.tsdeleted file mode 100644index 298e63ac5e..0000000000--- a/frontend/src/components/Issue/logic/StandardModeProvider.ts+++ /dev/null@@ -1,16 +0,0 @@-import { defineComponent } from "vue";-import { useCommonLogic } from "./common";-import { provideIssueLogic } from "./index";--export default defineComponent({- name: "StandardModeProvider",- setup() {- const common = useCommonLogic();-- provideIssueLogic(common);- return common;- },- render() {- return this.$slots.default?.();- },-});diff --git a/frontend/src/components/Issue/logic/TenantModeProvider.ts b/frontend/src/components/Issue/logic/TenantModeProvider.tsdeleted file mode 100644index 80185f83ae..0000000000--- a/frontend/src/components/Issue/logic/TenantModeProvider.ts+++ /dev/null@@ -1,256 +0,0 @@-import { cloneDeep, head } from "lodash-es";-import { computed, defineComponent } from "vue";-import { useRoute } from "vue-router";-import {- useSheetV1Store,- useProjectV1Store,- useTaskStore,- useSheetStatementByUID,- useDatabaseV1Store,- useCurrentUserV1,-} from "@/store";-import { getProjectPathByLegacyProject } from "@/store/modules/v1/common";-import {- Issue,- IssueCreate,- Task,- TaskCreate,- TaskDatabaseSchemaUpdatePayload,- MigrationContext,- SheetId,- UNKNOWN_ID,- MigrationDetail,-} from "@/types";-import {- Sheet_Visibility,- Sheet_Source,- Sheet_Type,-} from "@/types/proto/v1/sheet_service";-import {- extractSheetUID,- extractUserUID,- hasWorkspacePermissionV1,- sheetIdOfTask,-} from "@/utils";-import {- errorAssertion,- flattenTaskList,- isTaskEditable,- maybeFormatStatementOnSave,- useCommonLogic,-} from "./common";-import { provideIssueLogic, useIssueLogic } from "./index";--export default defineComponent({- name: "TenantModeProvider",- setup() {- const { create, issue, selectedTask, createIssue, onStatusChanged } =- useIssueLogic();- const route = useRoute();- const currentUser = useCurrentUserV1();- const databaseStore = useDatabaseV1Store();- const sheetV1Store = useSheetV1Store();- const projectV1Store = useProjectV1Store();- const taskStore = useTaskStore();-- const isGroupingIssue = computed(() => {- return route.query.databaseGroupName;- });-- const allowEditStatement = computed(() => {- if (create.value) {- return true;- }-- const tasks = flattenTaskList<Task>(issue.value);- if (!tasks.every((task) => isTaskEditable(task))) {- return false;- }-- if (- hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- currentUser.value.userRole- )- ) {- return true;- }-- const creatorUID = String((issue.value as Issue).creator.id);- if (creatorUID === extractUserUID(currentUser.value.name)) {- return true;- }- return false;- });-- // In tenant mode, the entire issue shares only one SQL statement- const selectedStatement = computed(() => {- if (create.value) {- if (isGroupingIssue.value) {- return selectedTask.value.statement || "";- }-- const issueCreate = issue.value as IssueCreate;- const context = issueCreate.createContext as MigrationContext;- return context.detailList[0].statement;- } else {- const issueEntity = issue.value as Issue;- const task = issueEntity.pipeline!.stageList[0].taskList[0];- const payload = task.payload as TaskDatabaseSchemaUpdatePayload;- const selectedTaskSheetId = sheetIdOfTask(selectedTask.value as Task);- return (- useSheetStatementByUID(- String(selectedTaskSheetId || payload.sheetId || UNKNOWN_ID)- ).value || ""- );- }- });-- const updateStatement = async (newStatement: string) => {- if (create.value) {- // For grouping issue, we don't allow to modify statement.- if (isGroupingIssue.value) {- return;- }-- // For tenant deploy mode, we apply the statement to all stages and all tasks- const allTaskList = flattenTaskList<TaskCreate>(issue.value);- allTaskList.forEach((task) => {- task.statement = newStatement;- });-- const issueCreate = issue.value as IssueCreate;- const context = issueCreate.createContext as MigrationContext;- // We also apply it back to the CreateContext- context.detailList.forEach(- (detail) => (detail.statement = newStatement)- );- } else {- const issueEntity = issue.value as Issue;- const sheet = await sheetV1Store.createSheet(- getProjectPathByLegacyProject(issueEntity.project),- {- title: `Sheet for issue #${issueEntity.id}`,- content: new TextEncoder().encode(newStatement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- }- );- updateSheetId(Number(extractSheetUID(sheet.name)));- }- };-- const updateSheetId = (sheetId: SheetId) => {- if (create.value) {- // For tenant deploy mode, we apply the sheetId to all stages and all tasks.- const allTaskList = flattenTaskList<TaskCreate>(issue.value);- allTaskList.forEach((task) => {- task.statement = "";- task.sheetId = sheetId;- });-- const issueCreate = issue.value as IssueCreate;- const context = issueCreate.createContext as MigrationContext;- // We also apply it back to the CreateContext- context.detailList.forEach((detail) => {- detail.statement = "";- detail.sheetId = sheetId;- });- } else {- // Call patchAllTasksInIssue for tenant mode.- const issueEntity = issue.value as Issue;- taskStore- .patchAllTasksInIssue({- issueId: issueEntity.id,- pipelineId: issueEntity.pipeline!.id,- taskPatch: {- sheetId,- },- })- .then(() => {- onStatusChanged(true);- });- }- };-- // We are never allowed to "apply task state to other stages" in tenant mode.- const allowApplyTaskStateToOthers = computed(() => false);-- const doCreate = async () => {- const issueCreate = cloneDeep(issue.value as IssueCreate);-- // for multi-tenancy issue pipeline (M * N)- // createContext is up-to-date already- // so we just format the statement if needed- const context = issueCreate.createContext as MigrationContext;- const detail = head(context.detailList);- if (!detail) {- // throw error- return;- }- // For those database group issues, we create issue directly instead of creating sheets.- if (route.query.databaseGroupName) {- const taskList = flattenTaskList(issueCreate);- context.detailList = [];- for (const task of taskList) {- const migrationDetail: MigrationDetail = {- migrationType: detail.migrationType,- earliestAllowedTs: detail.earliestAllowedTs,- databaseGroupName: route.query.databaseGroupName as string,- databaseId: (task as any).databaseId,- statement: (task as any).statement,- sheetId: (task as any).sheetId,- };- const payload = (task as Task).payload;- if (payload && (payload as any).schemaGroupName) {- migrationDetail.schemaGroupName = (payload as any).schemaGroupName;- }- context.detailList.push(migrationDetail);- }- createIssue(issueCreate);- return;- }-- const db = databaseStore.getDatabaseByUID(String(detail.databaseId!));- if (!detail.sheetId || detail.sheetId === UNKNOWN_ID) {- const statement = maybeFormatStatementOnSave(detail.statement, db);- const project = await projectV1Store.getOrFetchProjectByUID(- `${issueCreate.projectId}`- );- const sheet = await sheetV1Store.createSheet(project.name, {- title: issueCreate.name + " - " + db.name,- content: new TextEncoder().encode(statement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- payload: "{}",- });- detail.statement = "";- detail.sheetId = Number(extractSheetUID(sheet.name));- }- for (const detailItem of context.detailList) {- detailItem.statement = "";- detailItem.sheetId = detail.sheetId;- }-- createIssue(issueCreate);- };-- const logic = {- ...useCommonLogic(),- allowEditStatement,- selectedStatement,- updateStatement,- updateSheetId,- allowApplyTaskStateToOthers,- applyTaskStateToOthers: errorAssertion,- doCreate,- };- provideIssueLogic(logic);- return logic;- },- render() {- return this.$slots.default?.();- },-});diff --git a/frontend/src/components/Issue/logic/assignee.ts b/frontend/src/components/Issue/logic/assignee.tsdeleted file mode 100644index ad40f6e896..0000000000--- a/frontend/src/components/Issue/logic/assignee.ts+++ /dev/null@@ -1,195 +0,0 @@-import { computed } from "vue";-import { useEnvironmentV1Store } from "@/store";-import {- usePolicyByParentAndType,- defaultApprovalStrategy,-} from "@/store/modules/v1/policy";-import {- Issue,- IssueCreate,- IssueType,- Pipeline,- SYSTEM_BOT_ID,-} from "@/types";-import { User } from "@/types/proto/v1/auth_service";-import { DeploymentType } from "@/types/proto/v1/deployment";-import { IamPolicy } from "@/types/proto/v1/iam_policy";-import {- Policy,- PolicyType,- ApprovalStrategy,- ApprovalGroup,-} from "@/types/proto/v1/org_policy_service";-import { Project } from "@/types/proto/v1/project_service";-import {- isDatabaseRelatedIssueType,- isOwnerOfProjectV1,- hasWorkspacePermissionV1,- extractUserUID,-} from "@/utils";-import { useIssueLogic } from ".";--export const useCurrentRollOutPolicyForActiveEnvironment = () => {- const { create, issue, activeStageOfPipeline } = useIssueLogic();-- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return computed(() => ({- policy: ApprovalStrategy.MANUAL,- assigneeGroup: undefined,- }));- }-- const activeEnvironment = computed(() => {- const environmentId = create.value- ? (issue.value as IssueCreate).pipeline!.stageList[0].environmentId- : activeStageOfPipeline(issue.value.pipeline as Pipeline).environment.id;- return useEnvironmentV1Store().getEnvironmentByUID(String(environmentId));- });-- const activeEnvironmentApprovalPolicy = usePolicyByParentAndType(- computed(() => ({- parentPath: activeEnvironment.value.name,- policyType: PolicyType.DEPLOYMENT_APPROVAL,- }))- );-- return computed(() => {- const policy = activeEnvironmentApprovalPolicy.value;- return extractRollOutPolicyValue(policy, issue.value.type);- });-};--export const extractRollOutPolicyValue = (- policy: Policy | undefined,- issueType: IssueType-): {- policy: ApprovalStrategy;- assigneeGroup?: ApprovalGroup;-} => {- if (!policy || !policy.deploymentApprovalPolicy) {- return {- policy: defaultApprovalStrategy,- assigneeGroup: ApprovalGroup.APPROVAL_GROUP_DBA,- };- }-- if (- policy.deploymentApprovalPolicy.defaultStrategy ===- ApprovalStrategy.AUTOMATIC- ) {- return { policy: ApprovalStrategy.AUTOMATIC };- }-- const deploymentType = issueTypeToV1DeploymentType(issueType);- const assigneeGroup =- policy.deploymentApprovalPolicy.deploymentApprovalStrategies.find(- (group) => group.deploymentType === deploymentType- );-- if (- !assigneeGroup ||- assigneeGroup.approvalGroup === ApprovalGroup.APPROVAL_GROUP_DBA- ) {- return {- policy: ApprovalStrategy.MANUAL,- assigneeGroup: ApprovalGroup.APPROVAL_GROUP_DBA,- };- }-- return {- policy: ApprovalStrategy.MANUAL,- assigneeGroup: ApprovalGroup.APPROVAL_GROUP_PROJECT_OWNER,- };-};--export const allowUserToBeAssignee = (- user: User,- project: Project,- projectIamPolicy: IamPolicy,- policy: ApprovalStrategy,- assigneeGroup: ApprovalGroup | undefined-): boolean => {- const hasWorkspaceIssueManagementPermission = hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- user.userRole- );-- if (policy === ApprovalStrategy.AUTOMATIC) {- // DBA / workspace owner- return hasWorkspaceIssueManagementPermission;- }-- if (assigneeGroup === ApprovalGroup.APPROVAL_GROUP_DBA) {- // DBA / workspace owner- return hasWorkspaceIssueManagementPermission;- }-- if (assigneeGroup === ApprovalGroup.APPROVAL_GROUP_PROJECT_OWNER) {- // Project owner- return isOwnerOfProjectV1(projectIamPolicy, user);- }-- console.assert(false, "should never reach this line");- return false;-};--export const allowUserToChangeAssignee = (user: User, issue: Issue) => {- if (issue.status !== "OPEN") {- return false;- }- if (- hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- user.userRole- )- ) {- return true;- }-- const userUID = extractUserUID(user.name);- if (String(issue.assignee.id) === String(SYSTEM_BOT_ID)) {- return userUID === String(issue.creator.id);- }- return userUID === String(issue.assignee.id);-};--export const allowProjectOwnerToApprove = (- policy: Policy,- issueType: IssueType-): boolean => {- const strategy =- policy.deploymentApprovalPolicy?.defaultStrategy ?? defaultApprovalStrategy;- if (strategy === ApprovalStrategy.AUTOMATIC) {- return false;- }-- const deploymentType = issueTypeToV1DeploymentType(issueType);- const assigneeGroup = (- policy.deploymentApprovalPolicy?.deploymentApprovalStrategies ?? []- ).find((group) => group.deploymentType === deploymentType);-- if (!assigneeGroup) {- return false;- }-- return (- assigneeGroup.approvalGroup === ApprovalGroup.APPROVAL_GROUP_PROJECT_OWNER- );-};--const issueTypeToV1DeploymentType = (issueType: IssueType): DeploymentType => {- switch (issueType) {- case "bb.issue.database.create":- return DeploymentType.DATABASE_CREATE;- case "bb.issue.database.schema.update":- return DeploymentType.DATABASE_DDL;- case "bb.issue.database.schema.update.ghost":- return DeploymentType.DATABASE_DDL_GHOST;- case "bb.issue.database.data.update":- return DeploymentType.DATABASE_DML;- case "bb.issue.database.restore.pitr":- return DeploymentType.DATABASE_RESTORE_PITR;- default:- return DeploymentType.DEPLOYMENT_TYPE_UNSPECIFIED;- }-};diff --git a/frontend/src/components/Issue/logic/base.ts b/frontend/src/components/Issue/logic/base.tsdeleted file mode 100644index 64044a96c3..0000000000--- a/frontend/src/components/Issue/logic/base.ts+++ /dev/null@@ -1,345 +0,0 @@-import { isEmpty } from "lodash-es";-import { v4 as uuidv4 } from "uuid";-import { computed, Ref } from "vue";-import { useRoute, useRouter } from "vue-router";-import {- useIssueStore,- useProjectV1Store,- useSheetV1Store,- useSheetStatementByUID,- useDatabaseV1Store,-} from "@/store";-import { sheetNamePrefix } from "@/store/modules/v1/common";-import {- Issue,- IssueCreate,- Stage,- StageCreate,- StageId,- Task,- TaskCreate,- TaskStatus,- UNKNOWN_ID,-} from "@/types";-import { TenantMode } from "@/types/proto/v1/project_service";-import {- Sheet_Visibility,- Sheet_Source,- Sheet_Type,-} from "@/types/proto/v1/sheet_service";-import {- activeStage,- activeTaskInStage,- extractSheetUID,- idFromSlug,- indexFromSlug,- issueSlug,- sheetIdOfTask,- stageSlug,- taskSlug,-} from "@/utils";-import { maybeCreateBackTraceComments } from "../rollback/common";-import { flattenTaskList, TaskTypeWithStatement } from "./common";--export const useBaseIssueLogic = (params: {- create: Ref<boolean>;- issue: Ref<Issue | IssueCreate>;-}) => {- const { create, issue } = params;- const route = useRoute();- const router = useRouter();- const issueStore = useIssueStore();- const projectV1Store = useProjectV1Store();- const databaseStore = useDatabaseV1Store();- const sheetV1Store = useSheetV1Store();-- const project = computed(() => {- const projectUID = create.value- ? (issue.value as IssueCreate).projectId- : (issue.value as Issue).project.id;- return projectV1Store.getProjectByUID(String(projectUID));- });-- const createIssue = async (issue: IssueCreate) => {- // Set issue.pipeline and issue.payload to empty- // because we are no longer passing parameters via issue.pipeline- // we are using issue.createContext instead- delete issue.pipeline;- issue.payload = {};-- const createdIssue = await issueStore.createIssue(issue);- await maybeCreateBackTraceComments(createdIssue);-- // Use replace to omit the new issue url in the navigation history.- router.replace(`/issue/${issueSlug(createdIssue.name, createdIssue.id)}`);- };-- const selectedStage = computed((): Stage | StageCreate => {- const stageSlug = route.query.stage as string;- const taskSlug = route.query.task as string;- // For stage slug, we support both index based and id based.- // Index based is used when creating the new task and is the one used when clicking the UI.- // Id based is used when the context only has access to the stage id (e.g. Task only contains StageId)- if (stageSlug) {- const index = indexFromSlug(stageSlug);- if (index < issue.value.pipeline!.stageList.length) {- return issue.value.pipeline!.stageList[index];- }- const stageId = idFromSlug(stageSlug);- const stageList = (issue.value as Issue).pipeline!.stageList;- for (const stage of stageList) {- if (stage.id == stageId) {- return stage;- }- }- } else if (!create.value && taskSlug) {- const taskId = idFromSlug(taskSlug);- const stageList = (issue.value as Issue).pipeline!.stageList;- for (const stage of stageList) {- for (const task of stage.taskList) {- if (task.id == taskId) {- return stage;- }- }- }- }- if (create.value) {- return issue.value.pipeline!.stageList[0];- }- return activeStage((issue.value as Issue).pipeline!);- });-- const selectStageOrTask = (- stageId: StageId,- taskSlug: string | undefined = undefined- ) => {- const stageList = issue.value.pipeline!.stageList;- const index = stageList.findIndex((item, index) => {- if (create.value) {- return index === stageId;- }- return (item as Stage).id == stageId;- });- router.replace({- name: "workspace.issue.detail",- query: {- ...route.query,- stage: stageSlug(stageList[index].name, index),- task: taskSlug,- },- hash: route.hash,- });- };-- const selectTask = (task: Task) => {- if (create.value) return;-- // Find the stage which the task belongs to- const stage = (issue.value as Issue).pipeline?.stageList.find(- (s) => s.taskList.findIndex((t) => t.id === task.id) >= 0- );- if (!stage) {- return;- }- const slug = taskSlug(task.name, task.id);- selectStageOrTask(stage.id, slug);- };-- const selectedTask = computed((): Task | TaskCreate => {- const taskSlug = route.query.task as string;- const { taskList } = selectedStage.value;- if (taskSlug) {- const index = indexFromSlug(taskSlug);- if (index < taskList.length) {- return taskList[index];- }- const id = idFromSlug(taskSlug);- for (let i = 0; i < taskList.length; i++) {- const task = taskList[i] as Task;- if (task.id === id) {- return task;- }- }- }- return taskList[0];- });-- const selectedDatabase = computed(() => {- const databaseId = create.value- ? (selectedTask.value as TaskCreate).databaseId- : (selectedTask.value as Task).database?.id;- if (!databaseId) {- return undefined;- }- return databaseStore.getDatabaseByUID(String(databaseId));- });-- const isGhostMode = computed((): boolean => {- return issue.value.type === "bb.issue.database.schema.update.ghost";- });-- const isTenantMode = computed((): boolean => {- // To sync databases schema in tenant mode, we use normal project logic to create issue.- if (create.value && route.query.mode !== "tenant") return false;- if (project.value.tenantMode !== TenantMode.TENANT_MODE_ENABLED)- return false;-- // We support single database migration in tenant mode projects.- // So a pipeline should be tenant mode when it contains more- // than one tasks.- return (- flattenTaskList(issue.value).filter((task) =>- TaskTypeWithStatement.includes(task.type)- ).length > 1- );- });-- const isPITRMode = computed((): boolean => {- const { type } = issue.value;- return (- type === "bb.issue.database.restore.pitr" ||- type === "bb.issue.database.create"- );- });-- const taskStatusOfStage = (stage: Stage | StageCreate) => {- if (create.value) {- return stage.taskList[0].status;- }- const activeTask = activeTaskInStage(stage as Stage);- return activeTask.status;- };-- const isValidStage = (stage: Stage | StageCreate) => {- if (!create.value) {- return true;- }-- for (const task of stage.taskList) {- if (TaskTypeWithStatement.includes(task.type)) {- if (- isEmpty((task as TaskCreate).statement) &&- ((task as TaskCreate).sheetId === undefined ||- (task as TaskCreate).sheetId === UNKNOWN_ID)- ) {- return false;- }- }- }- return true;- };-- const selectedStatement = computed((): string => {- const task = selectedTask.value;- if (create.value) {- const taskCreate = task as TaskCreate;- if (taskCreate.sheetId && taskCreate.sheetId !== UNKNOWN_ID) {- return useSheetStatementByUID(String(taskCreate.sheetId)).value || "";- }- return (task as TaskCreate).statement;- }- return (- useSheetStatementByUID(String(sheetIdOfTask(task as Task) || UNKNOWN_ID))- .value || ""- );- });-- const allowApplyTaskStateToOthers = computed(() => {- if (!create.value) {- return false;- }- const taskList = flattenTaskList<TaskCreate>(issue.value);- // Allowed when more than one tasks need SQL statement or sheet.- const count = taskList.filter((task) =>- TaskTypeWithStatement.includes(task.type)- ).length;-- return count > 1;- });-- const allowApplyIssueStatusTransition = () => {- // no extra logic by default- return true;- };-- const allowApplyTaskStatusTransition = (task: Task, to: TaskStatus) => {- if (to === "CANCELED") {- // All task types are not CANCELable by default.- // Might be overwritten by other issue logic providers.- return false;- }-- // no extra logic by default- return true;- };-- const applyTaskStateToOthers = async (task: TaskCreate) => {- const taskList = flattenTaskList<TaskCreate>(issue.value);- const sheetId = task.sheetId;- const statement = task.statement;- let sheet = undefined;-- if (sheetId && sheetId !== UNKNOWN_ID) {- sheet = await sheetV1Store.getOrFetchSheetByName(- `${project.value.name}/${sheetNamePrefix}${sheetId}`- );- }-- for (const taskItem of taskList) {- if (TaskTypeWithStatement.includes(taskItem.type)) {- if (sheet) {- if (- new TextDecoder().decode(sheet.content).length < sheet.contentSize- ) {- taskItem.sheetId = sheetId;- } else {- let database = "";- if (taskItem.databaseId) {- database = (- await databaseStore.getOrFetchDatabaseByUID(- String(taskItem.databaseId)- )- ).name;- }- const newSheet = await sheetV1Store.createSheet(- project.value.name,- {- title: uuidv4(),- content: new TextEncoder().encode(statement),- database: database,- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- payload: "{}",- }- );- taskItem.sheetId = Number(extractSheetUID(newSheet.name));- }- taskItem.statement = "";- } else {- taskItem.statement = statement;- }- }- }- };-- return {- project,- isTenantMode,- isGhostMode,- isPITRMode,- createIssue,- selectedStage,- selectedTask,- selectedDatabase,- selectStageOrTask,- selectTask,- taskStatusOfStage,- isValidStage,- selectedStatement,- allowApplyTaskStateToOthers,- applyTaskStateToOthers,- allowApplyIssueStatusTransition,- allowApplyTaskStatusTransition,- };-};diff --git a/frontend/src/components/Issue/logic/common.ts b/frontend/src/components/Issue/logic/common.tsdeleted file mode 100644index a577f16921..0000000000--- a/frontend/src/components/Issue/logic/common.ts+++ /dev/null@@ -1,457 +0,0 @@-import { cloneDeep, isNaN, isNumber } from "lodash-es";-import { v4 as uuidv4 } from "uuid";-import { computed } from "vue";-import { useRoute } from "vue-router";-import formatSQL from "@/components/MonacoEditor/sqlFormatter";-import { t } from "@/plugins/i18n";-import { maybeApplyRollbackParams } from "@/plugins/issue/logic/initialize/standard";-import {- useCurrentUserV1,- useDatabaseV1Store,- useIssueStore,- useSheetV1Store,- useTaskStore,- useUIStateStore,-} from "@/store";-import {- ComposedDatabase,- Issue,- IssueCreate,- IssuePatch,- IssueType,- Task,- TaskCreate,- TaskId,- TaskPatch,- TaskType,- MigrationDetail,- MigrationType,- SheetId,- MigrationContext,- UNKNOWN_ID,- languageOfEngineV1,- dialectOfEngineV1,-} from "@/types";-import {- Sheet_Visibility,- Sheet_Source,- Sheet_Type,-} from "@/types/proto/v1/sheet_service";-import {- defer,- extractSheetUID,- extractUserUID,- hasWorkspacePermissionV1,- isDev,- isTaskTriggeredByVCS,- taskCheckRunSummary,-} from "@/utils";-import { IssueLogic, useIssueLogic } from "./index";--export const useCommonLogic = () => {- const {- create,- issue,- project,- selectedTask,- createIssue,- onStatusChanged,- dialog,- } = useIssueLogic();- const route = useRoute();- const currentUserV1 = useCurrentUserV1();- const databaseStore = useDatabaseV1Store();- const issueStore = useIssueStore();- const taskStore = useTaskStore();- const sheetV1Store = useSheetV1Store();-- const patchIssue = (- issuePatch: IssuePatch,- postUpdated?: (updatedIssue: Issue) => void- ) => {- issueStore- .patchIssue({- issueId: (issue.value as Issue).id,- issuePatch,- })- .then((updatedIssue) => {- // issue/patchIssue already fetches the new issue, so we schedule- // the next poll in NORMAL_POLL_INTERVAL- onStatusChanged(false);- if (postUpdated) {- postUpdated(updatedIssue);- }- });- };-- const patchTask = (- taskId: TaskId,- taskPatch: TaskPatch,- postUpdated?: (updatedTask: Task) => void- ) => {- return taskStore- .patchTask({- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline!.id,- taskId,- taskPatch,- })- .then((updatedTask) => {- // For now, the only task/patchTask is to change statement, which will trigger async task check.- // Thus we use the short poll interval- onStatusChanged(true);- if (postUpdated) {- postUpdated(updatedTask);- }- });- };-- const initialTaskListStatementFromRoute = async () => {- if (!create.value) {- return;- }-- const taskList = flattenTaskList<TaskCreate>(issue.value).filter((task) =>- TaskTypeWithStatement.includes(task.type)- );- // route.query.databaseList is comma-splitted databaseId list- // e.g. databaseList=7002,7006,7014- const idListString = (route.query.databaseList as string) || "";- const databaseIdList = idListString.split(",");- if (databaseIdList.length === 0) {- return;- }-- // route.query.sheetId is an id of sheet. Mainly using in creating rollback issue.- const sheetId = Number(route.query.sheetId);- // route.query.sqlList is JSON string of a string array.- const sqlListString = (route.query.sqlList as string) || "";- if (isNumber(sheetId) && !isNaN(sheetId)) {- for (const databaseId of databaseIdList) {- const task = taskList.find(- (task) => task.databaseId === Number(databaseId)- );- const database = await databaseStore.getOrFetchDatabaseByUID(- databaseId- );- if (task) {- task.sheetId = sheetId;- const sheetName = `${database.project}/sheets/${sheetId}`;- const sheet = await sheetV1Store.getOrFetchSheetByName(sheetName);- task.statement = new TextDecoder().decode(sheet?.content);- }- }- } else if (sqlListString) {- const statementList = JSON.parse(sqlListString) as string[];- for (- let i = 0;- i < Math.min(databaseIdList.length, statementList.length);- i++- ) {- const task = taskList.find(- (task) => task.databaseId === Number(databaseIdList[i])- );- if (task) {- task.statement = statementList[i];- }- }- }- };-- const allowEditStatement = computed(() => {- // if creating an issue, it's editable- if (create.value) {- return true;- }-- const issueEntity = issue.value as Issue;-- if (issueEntity.type === "bb.issue.database.restore.pitr") {- return false;- }-- if (issueEntity.type === "bb.issue.database.create") {- // For standard mode projects, we are not allowed to edit the database- // creation SQL statement.- if (issueEntity.project.tenantMode !== "TENANT") {- return false;- }-- // We allow to edit create database statement for tenant project to give users a- // chance to edit the dumped schema from its peer databases, because the dumped schema- // may not be perfectly correct.- // So we fallthrough to the common checkpoints.- }-- // if not creating, we are allowed to edit sql statement only when:- // 1. issue.status is OPEN- // 2. AND currentUser is the creator- if (issueEntity.status !== "OPEN") {- return false;- }-- if (!isTaskEditable(selectedTask.value as Task)) {- return false;- }-- if (- String(issueEntity.creator.id) ===- extractUserUID(currentUserV1.value.name)- ) {- return true;- }-- if (- hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- currentUserV1.value.userRole- )- ) {- // Workspace OWNER/DBA are always allowed to edit.- return true;- }-- if (isTaskTriggeredByVCS(selectedTask.value as Task)) {- // If an issue is triggered by VCS, its creator will be 1 (SYSTEM_BOT_ID)- // We should "Allow" current user to edit the statement (via VCS).- return true;- }-- return false;- });-- const updateStatement = async (newStatement: string) => {- if (create.value) {- const task = selectedTask.value as TaskCreate;- task.statement = newStatement;- } else {- // Ask whether to apply the change to all pending tasks if possible.- const task = selectedTask.value as Task;- const issueEntity = issue.value as Issue;- const patchingTaskList = await getPatchingTaskList(- issueEntity,- task,- dialog- );- if (patchingTaskList.length === 0) return;-- // Create a new sheet instead of reusing the old one.- const sheet = await sheetV1Store.createSheet(project.value.name, {- title: uuidv4(),- content: new TextEncoder().encode(newStatement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- });-- const patchRequestList = patchingTaskList.map((task) => {- patchTask(task.id, { sheetId: Number(extractSheetUID(sheet.name)) });- });- await Promise.allSettled(patchRequestList);- }- };-- const updateSheetId = async (sheetId: SheetId) => {- if (create.value) {- const task = selectedTask.value as TaskCreate;- task.statement = "";- task.sheetId = sheetId;- } else {- const task = selectedTask.value as Task;- await patchTask(task.id, { sheetId });- }- };-- const doCreate = async () => {- const issueCreate = cloneDeep(issue.value as IssueCreate);- // for standard issue pipeline (1 * 1 or M * 1)- // copy user edited tasks back to issue.createContext- const taskCreateList = flattenTaskList<TaskCreate>(issueCreate);- const detailList: MigrationDetail[] = [];- for (const taskCreate of taskCreateList) {- const db = databaseStore.getDatabaseByUID(String(taskCreate.databaseId!));- const statement = maybeFormatStatementOnSave(taskCreate.statement, db);- const migrationDetail: MigrationDetail = {- migrationType: getMigrationTypeFromTask(taskCreate),- databaseId: taskCreate.databaseId,- statement: statement,- sheetId: taskCreate.sheetId,- earliestAllowedTs: taskCreate.earliestAllowedTs,- rollbackEnabled: taskCreate.rollbackEnabled,- };- // Create a new sheet to save statement.- if (!taskCreate.sheetId || taskCreate.sheetId === UNKNOWN_ID) {- const sheet = await sheetV1Store.createSheet(db.project, {- title: issueCreate.name + " - " + db.databaseName,- content: new TextEncoder().encode(statement),- visibility: Sheet_Visibility.VISIBILITY_PROJECT,- source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,- type: Sheet_Type.TYPE_SQL,- payload: "{}",- });- migrationDetail.sheetId = Number(extractSheetUID(sheet.name));- } else if (taskCreate.sheetId !== UNKNOWN_ID) {- const sheetName = `${db.project}/sheets/${taskCreate.sheetId}`;- const sheet = await sheetV1Store.getOrFetchSheetByName(sheetName);- if (- new TextDecoder().decode(sheet?.content).length === sheet?.contentSize- ) {- await sheetV1Store.patchSheet({- name: sheetName,- content: new TextEncoder().encode(statement),- });- }- }- migrationDetail.statement = "";- detailList.push(migrationDetail);- }-- const createContext: MigrationContext = {- detailList,- };- maybeApplyRollbackParams(createContext, route);- issueCreate.createContext = createContext;- createIssue(issueCreate);- };-- return {- patchIssue,- patchTask,- allowEditStatement,- initialTaskListStatementFromRoute,- updateStatement,- updateSheetId,- doCreate,- };-};--const getMigrationTypeFromTask = (task: Task | TaskCreate) => {- let migrationType: MigrationType;- if (task.type === "bb.task.database.schema.baseline") {- migrationType = "BASELINE";- } else if (task.type === "bb.task.database.data.update") {- migrationType = "DATA";- } else {- migrationType = "MIGRATE";- }- return migrationType;-};--export const TaskTypeWithStatement: TaskType[] = [- "bb.task.general",- "bb.task.database.create",- "bb.task.database.data.update",- "bb.task.database.schema.baseline",- "bb.task.database.schema.update",- "bb.task.database.schema.update-sdl",- "bb.task.database.schema.update.ghost.sync",-];--export const IssueTypeWithStatement: IssueType[] = [- "bb.issue.database.create",- "bb.issue.database.schema.update",- "bb.issue.database.data.update",- "bb.issue.database.schema.update.ghost",-];--export const flattenTaskList = <T extends Task | TaskCreate>(- issue: Issue | IssueCreate-) => {- const taskList = issue.pipeline?.stageList.flatMap(- (stage) => stage.taskList as T[]- );- return taskList || [];-};--export const maybeFormatStatementOnSave = (- statement: string,- database?: ComposedDatabase-): string => {- const uiStateStore = useUIStateStore();- if (!uiStateStore.issueFormatStatementOnSave) {- // Don't format if user disabled this feature- return statement;- }-- const language = languageOfEngineV1(database?.instanceEntity.engine);- if (language !== "sql") {- return statement;- }- const dialect = dialectOfEngineV1(database?.instanceEntity.engine);-- const result = formatSQL(statement, dialect);- if (!result.error) {- return result.data;- }-- // Fallback to the input statement if error occurs while formatting- return statement;-};--// To let us know if we reaches a logic branch unexpectedly.-export const errorAssertion = () => {- if (isDev()) {- throw new Error("should never reach here");- }-};--export const isTaskEditable = (task: Task): boolean => {- if (task.status === "PENDING_APPROVAL" || task.status === "FAILED") {- return true;- }- if (task.status === "PENDING") {- // If a task's status is "PENDING", its statement is editable if there- // are at least ONE ERROR task checks.- // Since once all its task checks are fulfilled, it might be queued by- // the scheduler.- // Editing a queued task's SQL statement is dangerous with kinds of race- // condition risks.- const summary = taskCheckRunSummary(task);- if (summary.errorCount > 0) {- return true;- }- }-- return false;-};--// Deprecated in favor of IssueV1.-// See https://github.com/bytebase/bytebase/pull/8054.-export const isGroupingChangeIssue = (_: Issue): boolean => {- return false;-};--export const getPatchingTaskList = async (- issue: Issue,- task: Task,- dialog: IssueLogic["dialog"]-) => {- const patchableTaskList = flattenTaskList<Task>(issue).filter(- (task) => TaskTypeWithStatement.includes(task.type) && isTaskEditable(task)- );- const d = defer<Task[]>();- if (patchableTaskList.length > 1) {- dialog.info({- title: t("task.apply-change-to-all-pending-tasks.title"),- style: "width: auto",- negativeText: t("task.apply-change-to-all-pending-tasks.current-only"),- positiveText: t("task.apply-change-to-all-pending-tasks.self"),- onPositiveClick: () => {- d.resolve(patchableTaskList);- },- onNegativeClick: () => {- d.resolve([task]);- },- autoFocus: false,- maskClosable: false,- closeOnEsc: false,- onClose: () => {- d.resolve([]);- },- });- } else {- d.resolve([task]);- }-- return d.promise;-};diff --git a/frontend/src/components/Issue/logic/extra.ts b/frontend/src/components/Issue/logic/extra.tsdeleted file mode 100644index 389bc4b22f..0000000000--- a/frontend/src/components/Issue/logic/extra.ts+++ /dev/null@@ -1,280 +0,0 @@-import { cloneDeep, isEqual } from "lodash-es";-import { computed, nextTick } from "vue";-import type { InputField, OutputField } from "@/plugins";-import {- useCurrentUserV1,- useIssueStore,- useIssueSubscriberStore,- useTaskStore,-} from "@/store";-import type {- Issue,- IssueCreate,- IssueStatus,- IssueStatusPatch,- PrincipalId,- Stage,- StageAllTaskStatusPatch,- Task,- TaskCreate,- TaskPatch,- TaskStatus,- TaskStatusPatch,-} from "@/types";-import { extractUserUID, hasWorkspacePermissionV1 } from "@/utils";-import { useIssueLogic } from "./index";--export const useExtraIssueLogic = () => {- const {- create,- issue,- isGhostMode,- selectedStage,- selectedTask,- selectStageOrTask,- selectTask,- onStatusChanged,- patchIssue,- patchTask,- } = useIssueLogic();- const issueStore = useIssueStore();- const issueSubscriberStore = useIssueSubscriberStore();- const taskStore = useTaskStore();- const currentUserV1 = useCurrentUserV1();- const currentUserUID = computed(() =>- extractUserUID(currentUserV1.value.name)- );-- const allowEditOutput = computed(() => {- if (create.value) {- return true;- }-- const issueEntity = issue.value as Issue;- return (- issueEntity.status === "OPEN" &&- String(issueEntity.assignee?.id) === currentUserUID.value- );- });-- const allowEditNameAndDescription = computed(() => {- if (create.value) {- return true;- }-- const issueEntity = issue.value as Issue;- if (issueEntity.status === "OPEN") {- if (- String(issueEntity.assignee.id) === currentUserUID.value ||- String(issueEntity.creator.id) === currentUserUID.value- ) {- // Allowed if current user is the assignee or creator.- return true;- }-- if (- hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- currentUserV1.value.userRole- )- ) {- // Allowed if RBAC is enabled and current is DBA or workspace owner.- return true;- }- }-- return false;- });-- const updateName = (- newName: string,- postUpdated?: (updatedIssue: Issue) => void- ) => {- if (create.value) {- issue.value.name = newName;- } else {- patchIssue(- {- name: newName,- },- postUpdated- );- }- };-- const updateDescription = (- newDescription: string,- postUpdated?: (updatedIssue: Issue) => void- ) => {- if (create.value) {- issue.value.description = newDescription;- } else {- patchIssue(- {- description: newDescription,- },- postUpdated- );- }- };-- const updateAssigneeId = (newAssigneeId: string) => {- if (create.value) {- (issue.value as IssueCreate).assigneeId = parseInt(newAssigneeId, 10);- } else {- patchIssue({- assigneeId: parseInt(newAssigneeId, 10),- });- }- };-- const updateEarliestAllowedTime = (newEarliestAllowedTsMs: number) => {- if (create.value) {- if (isGhostMode.value) {- // In gh-ost mode, when creating an issue, all sub-tasks in a stage- // share the same earliestAllowedTs.- // So updates on any one of them will be applied to others.- // (They can be updated independently after creation)- const taskList = selectedStage.value.taskList as TaskCreate[];- taskList.forEach((task) => {- task.earliestAllowedTs = newEarliestAllowedTsMs;- });- } else {- selectedTask.value.earliestAllowedTs = newEarliestAllowedTsMs;- }- } else {- const task = selectedTask.value as Task;- const taskPatch: TaskPatch = {- earliestAllowedTs: newEarliestAllowedTsMs,- updatedTs: task.updatedTs,- };- patchTask(task.id, taskPatch);- }- };-- const addSubscriberId = (subscriberId: PrincipalId) => {- issueSubscriberStore.createSubscriber({- issueId: (issue.value as Issue).id,- subscriberId,- });- };-- const removeSubscriberId = (subscriberId: PrincipalId) => {- issueSubscriberStore.deleteSubscriber({- issueId: (issue.value as Issue).id,- subscriberId,- });- };-- const updateCustomField = (field: InputField | OutputField, value: any) => {- const payload = issue.value.payload as Record<string, any>;- if (!isEqual(payload[field.id], value)) {- if (create.value) {- payload[field.id] = value;- } else {- const newPayload = cloneDeep(payload);- newPayload[field.id] = value;- patchIssue({- payload: newPayload,- });- }- }- };-- const changeIssueStatus = (newStatus: IssueStatus, comment: string) => {- const issueStatusPatch: IssueStatusPatch = {- status: newStatus,- comment: comment,- };- issueStore.updateIssueStatus({- issueId: (issue.value as Issue).id,- issueStatusPatch,- });- };-- const changeStageAllTaskStatus = (- stage: Stage,- newStatus: TaskStatus,- comment: string- ) => {- // Switch to the last task in this stage- const lastTask = stage.taskList[stage.taskList.length - 1];- selectStageOrTask(Number(stage.id));- nextTick(() => {- selectTask(lastTask);- });-- // Patch the stage- const stageAllTaskStatusPatch: StageAllTaskStatusPatch = {- id: stage.id,- status: newStatus,- comment,- updatedTs: Math.floor(Date.now() / 1000),- };- taskStore- .updateStageAllTaskStatus({- issue: issue.value as Issue,- stage,- patch: stageAllTaskStatusPatch,- })- .then(() => {- onStatusChanged(true);- });- };-- const changeTaskStatus = (- task: Task,- newStatus: TaskStatus,- comment: string- ) => {- // Switch to the stage view containing this task- selectStageOrTask(Number(task.stage.id));- nextTick().then(() => {- selectTask(task);- });-- const taskStatusPatch: TaskStatusPatch = {- status: newStatus,- comment: comment,- updatedTs: task.updatedTs,- };- taskStore- .updateStatus({- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline!.id,- taskId: task.id,- taskStatusPatch,- })- .then(() => {- onStatusChanged(true);- });- };-- const runTaskChecks = (task: Task) => {- taskStore- .runChecks({- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline!.id,- taskId: task.id,- })- .then(() => {- onStatusChanged(true);- });- };-- return {- allowEditOutput,- allowEditNameAndDescription,- updateName,- updateDescription,- updateAssigneeId,- updateEarliestAllowedTime,- addSubscriberId,- removeSubscriberId,- updateCustomField,- changeIssueStatus,- changeStageAllTaskStatus,- changeTaskStatus,- runTaskChecks,- };-};diff --git a/frontend/src/components/Issue/logic/grantRequest.ts b/frontend/src/components/Issue/logic/grantRequest.tsdeleted file mode 100644index 6b347cb2c0..0000000000--- a/frontend/src/components/Issue/logic/grantRequest.ts+++ /dev/null@@ -1,54 +0,0 @@-import { computed, Ref } from "vue";-import { useRouter } from "vue-router";-import { useIssueStore, useProjectV1Store } from "@/store";-import { Issue, IssueCreate, Task, TaskStatus } from "@/types";-import { issueSlug } from "@/utils";-import { maybeCreateBackTraceComments } from "../rollback/common";--export const useGrantRequestIssueLogic = (params: {- create: Ref<boolean>;- issue: Ref<Issue | IssueCreate>;-}) => {- const { create, issue } = params;- const router = useRouter();- const issueStore = useIssueStore();- const projectV1Store = useProjectV1Store();-- const project = computed(() => {- const projectUID = create.value- ? (issue.value as IssueCreate).projectId- : (issue.value as Issue).project.id;- return projectV1Store.getProjectByUID(String(projectUID));- });-- const createIssue = async (issue: IssueCreate) => {- const createdIssue = await issueStore.createIssue(issue);- await maybeCreateBackTraceComments(createdIssue);-- // Use replace to omit the new issue url in the navigation history.- router.replace(`/issue/${issueSlug(createdIssue.name, createdIssue.id)}`);- };-- const allowApplyIssueStatusTransition = () => {- // no extra logic by default- return true;- };-- const allowApplyTaskStatusTransition = (task: Task, to: TaskStatus) => {- if (to === "CANCELED") {- // All task types are not CANCELable by default.- // Might be overwritten by other issue logic providers.- return false;- }-- // no extra logic by default- return true;- };-- return {- project,- createIssue,- allowApplyIssueStatusTransition,- allowApplyTaskStatusTransition,- };-};diff --git a/frontend/src/components/Issue/logic/index.ts b/frontend/src/components/Issue/logic/index.tsdeleted file mode 100644index 25a79a9bd3..0000000000--- a/frontend/src/components/Issue/logic/index.ts+++ /dev/null@@ -1,37 +0,0 @@-import { inject, provide, InjectionKey } from "vue";-import GhostModeProvider from "./GhostModeProvider";-import GrantRequestModeProvider from "./GrantRequestModeProvider";-import type IssueLogic from "./IssueLogic";-import StandardModeProvider from "./StandardModeProvider";-import TenantModeProvider from "./TenantModeProvider";--export * from "./base";-export * from "./common";-export * from "./extra";-export * from "./assignee";-export * from "./transition";--export {- IssueLogic,- TenantModeProvider,- GhostModeProvider,- StandardModeProvider,- GrantRequestModeProvider,-};--export const KEY = Symbol("bb.issue.logic") as InjectionKey<IssueLogic>;--export const useIssueLogic = () => {- return inject(KEY)!;-};--export const provideIssueLogic = (logic: Partial<IssueLogic>, root = false) => {- if (!root) {- const parent = useIssueLogic();- logic = {- ...parent,- ...logic,- };- }- provide(KEY, logic as IssueLogic);-};diff --git a/frontend/src/components/Issue/logic/transition.ts b/frontend/src/components/Issue/logic/transition.tsdeleted file mode 100644index 11df9af5f5..0000000000--- a/frontend/src/components/Issue/logic/transition.ts+++ /dev/null@@ -1,295 +0,0 @@-import { computed, Ref } from "vue";-import { extractIssueReviewContext } from "@/plugins/issue/logic";-import { useCurrentUserV1, useProjectV1Store } from "@/store";-import {- Issue as LegacyIssue,- Pipeline,- IssueStatusTransitionType,- ISSUE_STATUS_TRANSITION_LIST,- IssueStatusTransition,- APPLICABLE_ISSUE_ACTION_LIST,-} from "@/types";-import { User } from "@/types/proto/v1/auth_service";-import { Issue } from "@/types/proto/v1/issue_service";-import {- activeStage,- activeTask,- allTaskList,- applicableTaskTransition,- StageStatusTransition,- TaskStatusTransition,- TASK_STATUS_TRANSITION_LIST,- isDatabaseRelatedIssueType,- extractUserUID,- hasWorkspacePermissionV1,- isOwnerOfProjectV1,- isGrantRequestIssueType,-} from "@/utils";-import { useIssueLogic } from ".";-import {- allowUserToBeAssignee,- useCurrentRollOutPolicyForActiveEnvironment,-} from "./";--export const useIssueTransitionLogic = (issue: Ref<LegacyIssue>) => {- const { create, activeTaskOfPipeline, allowApplyTaskStatusTransition } =- useIssueLogic();-- const currentUserV1 = useCurrentUserV1();- const rollOutPolicy = useCurrentRollOutPolicyForActiveEnvironment();-- const isAllowedToApplyTaskTransition = computed(() => {- if (create.value) {- return false;- }- if (!isDatabaseRelatedIssueType(issue.value.type)) {- return false;- }-- const project = useProjectV1Store().getProjectByUID(- String(issue.value.project.id)- );-- if (- allowUserToBeAssignee(- currentUserV1.value,- project,- project.iamPolicy,- rollOutPolicy.value.policy,- rollOutPolicy.value.assigneeGroup- )- ) {- return true;- }-- // Otherwise, only the assignee can apply task status transitions- // including roll out, cancel, retry, etc.- return (- String(issue.value.assignee.id) ===- extractUserUID(currentUserV1.value.name)- );- });-- const getApplicableIssueStatusTransitionList = (- issue: LegacyIssue- ): IssueStatusTransition[] => {- if (create.value) {- return [];- }- return calcApplicableIssueStatusTransitionList(issue);- };-- const getApplicableStageStatusTransitionList = (issue: LegacyIssue) => {- if (create.value) {- return [];- }- switch (issue.status) {- case "DONE":- case "CANCELED":- return [];- case "OPEN": {- const stageStatusTransitionList: StageStatusTransition[] = [];- if (isAllowedToApplyTaskTransition.value) {- const currentStage = activeStage(issue.pipeline as Pipeline);- // "Rollout" and "Retry" can be applied to current stage.- const ROLLOUT = TASK_STATUS_TRANSITION_LIST.get("ROLLOUT")!;- const pendingApprovalTaskList = currentStage.taskList.filter(- (task) => {- return (- task.status === "PENDING_APPROVAL" &&- allowApplyTaskStatusTransition(task, ROLLOUT.to)- );- }- );- // Allowing "Rollout" a stage when it has TWO OR MORE tasks- // are "PENDING_APPROVAL" (including the "activeTask" itself)- if (pendingApprovalTaskList.length >= 2) {- stageStatusTransitionList.push(ROLLOUT);- }-- const RETRY = TASK_STATUS_TRANSITION_LIST.get("RETRY")!;- const failedTaskList = currentStage.taskList.filter((task) => {- return (- task.status === "FAILED" &&- allowApplyTaskStatusTransition(task, RETRY.to)- );- });- // Allowing "Retry" a stage when it has TWO OR MORE tasks- // are "FAILED" (including the "activeTask" itself)- if (failedTaskList.length >= 2) {- stageStatusTransitionList.push(RETRY);- }- }-- return stageStatusTransitionList;- }- }- console.assert(false, "Should never reach this line");- };-- const getApplicableTaskStatusTransitionList = (- issue: LegacyIssue- ): TaskStatusTransition[] => {- if (create.value) {- return [];- }- switch (issue.status) {- case "DONE":- case "CANCELED":- return [];- case "OPEN": {- if (isAllowedToApplyTaskTransition.value) {- const currentTask = activeTaskOfPipeline(issue.pipeline as Pipeline);- return applicableTaskTransition(issue.pipeline as Pipeline).filter(- (transition) =>- allowApplyTaskStatusTransition(currentTask, transition.to)- );- }-- return [];- }- }- console.assert(false, "Should never reach this line");- };-- const applicableTaskStatusTransitionList = computed(() =>- getApplicableTaskStatusTransitionList(issue.value)- );-- const applicableStageStatusTransitionList = computed(() =>- getApplicableStageStatusTransitionList(issue.value)- );-- const applicableIssueStatusTransitionList = computed(() =>- getApplicableIssueStatusTransitionList(issue.value)- );-- return {- getApplicableIssueStatusTransitionList,- getApplicableStageStatusTransitionList,- getApplicableTaskStatusTransitionList,- applicableIssueStatusTransitionList,- applicableStageStatusTransitionList,- applicableTaskStatusTransitionList,- };-};--export const calcApplicableIssueStatusTransitionList = (- issue: LegacyIssue-): IssueStatusTransition[] => {- const issueEntity = issue as LegacyIssue;- const transitionTypeList: IssueStatusTransitionType[] = [];- const currentUserV1 = useCurrentUserV1();-- if (allowUserToApplyIssueStatusTransition(issueEntity, currentUserV1.value)) {- const actions = APPLICABLE_ISSUE_ACTION_LIST.get(issueEntity.status);- if (actions) {- transitionTypeList.push(...actions);- }- }-- const applicableTransitionList: IssueStatusTransition[] = [];- transitionTypeList.forEach((type) => {- const transition = ISSUE_STATUS_TRANSITION_LIST.get(type);- if (!transition) return;-- if (type === "RESOLVE") {- // If an issue is not "Approved" in review stage- // it cannot be Resolved.- if (!isIssueReviewDone(issue)) {- return;- }- } else if (type === "REOPEN") {- // Don't show the REOPEN button for request granting issues.- if (isGrantRequestIssueType(issue.type)) {- return;- }- }-- if (isDatabaseRelatedIssueType(issue.type)) {- const currentTask = activeTask(issue.pipeline as Pipeline);- const flattenTaskList = allTaskList(issue.pipeline as Pipeline);- if (flattenTaskList.some((task) => task.status === "RUNNING")) {- // Disallow any issue status transition if some of the tasks are in RUNNING state.- return;- }- if (type === "RESOLVE") {- if (transition.type === "RESOLVE" && flattenTaskList.length > 0) {- const lastTask = flattenTaskList[flattenTaskList.length - 1];- // Don't display the RESOLVE action if the pipeline doesn't reach the- // last task- if (lastTask.id !== currentTask.id) {- return;- }- // Don't display the RESOLVE action if the last task is not DONE.- if (currentTask.status !== "DONE") {- return;- }- }- }- }- applicableTransitionList.push(transition);- });- return applicableTransitionList;-};--export function isApplicableTransition<- T extends IssueStatusTransition | TaskStatusTransition | StageStatusTransition->(target: T, list: T[]): boolean {- return (- list.findIndex((applicable) => {- return applicable.to === target.to && applicable.type === target.type;- }) >= 0- );-}--const allowUserToApplyIssueStatusTransition = (- issue: LegacyIssue,- user: User-) => {- // Workspace level high-privileged user (DBA/OWNER) are always allowed.- if (- hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- user.userRole- )- ) {- return true;- }-- // Project owners are also allowed- const projectV1 = useProjectV1Store().getProjectByUID(- String(issue.project.id)- );- if (isOwnerOfProjectV1(projectV1.iamPolicy, user)) {- return true;- }-- // The creator and the assignee can apply issue status transition-- const currentUserUID = extractUserUID(user.name);-- if (currentUserUID === String(issue.creator?.id)) {- return true;- }- if (currentUserUID === String(issue.assignee?.id)) {- return true;- }-- return false;-};--function isIssueReviewDone(issue: LegacyIssue) {- const review = computed(() => {- try {- return Issue.fromJSON(issue.payload.approval);- } catch {- return Issue.fromJSON({});- }- });- const context = extractIssueReviewContext(- computed(() => issue),- review- );- return context.done.value;-}diff --git a/frontend/src/components/Issue/logic/useSQLAdviceMarkers.ts b/frontend/src/components/Issue/logic/useSQLAdviceMarkers.tsdeleted file mode 100644index dae159ae74..0000000000--- a/frontend/src/components/Issue/logic/useSQLAdviceMarkers.ts+++ /dev/null@@ -1,48 +0,0 @@-import { maxBy } from "lodash-es";-import { computed } from "vue";-import type { AdviceOption } from "@/components/MonacoEditor";-import type { Task, TaskCheckRun, TaskCheckType } from "@/types";-import { useIssueLogic } from ".";--export const useSQLAdviceMarkers = () => {- const { create, selectedTask } = useIssueLogic();- const markers = computed(() => {- if (create.value) return [];- const task = selectedTask.value as Task;-- const types: TaskCheckType[] = [- "bb.task-check.database.statement.advise",- "bb.task-check.database.statement.syntax",- ];- return types.flatMap((type) =>- getLatestAdviceOptions(- task.taskCheckRunList.filter((check) => check.type === type)- )- );- });- return { markers };-};--const getLatestAdviceOptions = (taskCheckRunList: TaskCheckRun[]) => {- const latest = maxBy(taskCheckRunList, (advice) => advice.id);- if (!latest) {- return [];- }- const { resultList = [] } = latest.result;- return resultList- .filter((result) => result.status === "ERROR" || result.status === "WARN")- .filter((result) => result.line !== undefined)- .map<AdviceOption>((result) => {- const line = result.line!;- const column = result.column ?? Number.MAX_SAFE_INTEGER;- return {- severity: result.status === "ERROR" ? "ERROR" : "WARNING",- message: result.content,- source: `${result.title} (${result.code})`,- startLineNumber: line,- endLineNumber: line,- startColumn: column,- endColumn: column,- };- });-};diff --git a/frontend/src/components/Issue/review/ApprovalTimeline.vue b/frontend/src/components/Issue/review/ApprovalTimeline.vuedeleted file mode 100644index 554c5330a3..0000000000--- a/frontend/src/components/Issue/review/ApprovalTimeline.vue+++ /dev/null@@ -1,119 +0,0 @@-<template>- <NTimeline :icon-size="20" size="medium" class="bb-approval-timeline">- <NTimelineItem v-for="step in steps" :key="step.index">- <template #icon>- <div- class="w-5 h-5 rounded-full flex items-center justify-center text-xs shrink-0"- :class="iconClass(step)"- >- <heroicons-outline:thumb-up- v-if="step.status === 'APPROVED'"- class="w-3.5 h-3.5 text-white"- />- <heroicons:pause-solid- v-else-if="step.status === 'REJECTED'"- class="w-3.5 h-3.5 text-white"- />- <template v-else-if="step.status === 'CURRENT'">- <heroicons-outline:external-link- v-if="isExternalApprovalStep(step.step)"- class="w-3.5 h-3.5"- />- <heroicons-outline:user v-else class="w-3.5 h-3.5" />- </template>- <template v-else>- {{ step.index + 1 }}- </template>- </div>- </template>-- <div class="flex-1 flex text-sm overflow-hidden" :class="itemClass(step)">- <template v-if="!isExternalApprovalStep(step.step)">- <div class="whitespace-nowrap shrink-0">- {{ approvalNodeText(step.step.nodes[0]) }}- </div>- <div class="mr-1.5 shrink-0">:</div>- <div class="flex-1 overflow-hidden">- <NEllipsis- v-if="step.status === 'APPROVED'"- class="inline-block"- :class="step.approver?.name === currentUser.name && 'font-bold'"- >- <span>{{ step.approver?.title }}</span>- <span v-if="step.approver?.name === currentUser.name">- ({{ $t("custom-approval.issue-review.you") }})- </span>- <span- v-if="step.approver?.name === USER_SYSTEM_BOT"- class="ml-2 inline-flex items-center px-1 py-0.5 rounded-lg text-xs font-semibold bg-green-100 text-green-800"- >- {{ $t("settings.members.system-bot") }}- </span>- </NEllipsis>- <Candidates v-else :step="step" />- </div>- </template>- <template v-else>- <div class="whitespace-nowrap shrink-0">- {{ approvalNodeText(step.step.nodes[0]) }}- </div>- <ExternalApprovalSyncButton />- </template>- </div>- </NTimelineItem>- </NTimeline>-</template>--<script lang="ts" setup>-import { NTimeline, NTimelineItem, NEllipsis } from "naive-ui";-import { storeToRefs } from "pinia";-import { useAuthStore } from "@/store";-import { WrappedReviewStep } from "@/types";-import { ApprovalStep } from "@/types/proto/v1/issue_service";-import { approvalNodeText } from "@/utils";-import Candidates from "./Candidates.vue";-import ExternalApprovalSyncButton from "./ExternalApprovalNodeSyncButton.vue";--const USER_SYSTEM_BOT = "users/1";--defineProps<{- steps: WrappedReviewStep[];-}>();--const { currentUser } = storeToRefs(useAuthStore());--const isExternalApprovalStep = (step: ApprovalStep) => {- return !!step.nodes[0]?.externalNodeId;-};--const iconClass = (step: WrappedReviewStep) => {- const { status } = step;- return [- status === "APPROVED" && "bg-success",- status === "REJECTED" && "bg-warning",- status === "CURRENT" && "bg-white border-[2px] border-info text-accent",- status === "PENDING" && "bg-white border-[3px] border-gray-300",- ];-};--const itemClass = (step: WrappedReviewStep) => {- const { status } = step;- return [- status === "APPROVED" && "text-control-light",- status === "REJECTED" && "text-control-light",- status === "CURRENT" && "text-accent",- status === "PENDING" && "text-control-placeholder",- ];-};-</script>--<style>-.bb-approval-timeline- .n-timeline-item- .n-timeline-item-timeline- .n-timeline-item-timeline__line {- --line-padding: 4px;- top: calc(var(--n-icon-size) + var(--line-padding)) !important;- bottom: calc(var(--line-padding)) !important;-}-</style>diff --git a/frontend/src/components/Issue/review/Candidates.vue b/frontend/src/components/Issue/review/Candidates.vuedeleted file mode 100644index f20d71d31c..0000000000--- a/frontend/src/components/Issue/review/Candidates.vue+++ /dev/null@@ -1,90 +0,0 @@-<template>- <NTooltip v-if="candidates.length === 0" placement="top">- <template #trigger>- <heroicons:exclamation-triangle class="w-4 h-4 inline-block" />- </template>-- <div class="w-[14rem]">- {{ $t("custom-approval.issue-review.no-one-matches-role") }}- </div>- </NTooltip>-- <NEllipsis- v-else- class="flex-1 truncate"- :tooltip="{- raw: true,- showArrow: false,- }"- :theme-overrides="{- peers: {- Tooltip: {- boxShadow: 'none',- },- },- }"- >- <div- v-for="(user, i) in candidates"- :key="user.name"- class="inline-flex flex-nowrap truncate"- >- <span- :class="user.name === currentUser.name && 'font-bold'"- class="truncate"- >- {{ user.title }}- </span>- <span v-if="user.name === currentUser.name" class="font-bold ml-1">- ({{ $t("custom-approval.issue-review.you") }})- </span>- <span v-if="i < candidates.length - 1" class="mr-1">,</span>- </div>-- <template #tooltip>- <div- class="w-[12rem] max-h-[18rem] flex flex-col border rounded bg-white shadow-md text-control-light overflow-y-hidden"- >- <div class="whitespace-nowrap pt-3 pb-2 px-2 border-b textlabel">- {{ approvalNodeText(step.step.nodes[0]) }}- </div>- <div class="flex-1 overflow-auto text-xs">- <div- v-for="user in candidates"- :key="user.name"- class="flex items-center py-1.5 px-2"- :class="[user.name === currentUser.name && 'font-bold']"- >- <PrincipalAvatar- :principal="convertUserToPrincipal(user)"- size="SMALL"- class="mr-2"- />- <span class="whitespace-nowrap">{{ user.title }}</span>- <span v-if="user.name === currentUser.name" class="ml-1">- ({{ $t("custom-approval.issue-review.you") }})- </span>- </div>- </div>- </div>- </template>- </NEllipsis>-</template>--<script lang="ts" setup>-import { NEllipsis, NTooltip } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed } from "vue";-import PrincipalAvatar from "@/components/PrincipalAvatar.vue";-import { convertUserToPrincipal, useAuthStore } from "@/store";-import { WrappedReviewStep } from "@/types";-import { approvalNodeText } from "@/utils";--const { currentUser } = storeToRefs(useAuthStore());--const props = defineProps<{- step: WrappedReviewStep;-}>();--const candidates = computed(() => props.step.candidates);-</script>diff --git a/frontend/src/components/Issue/review/CurrentApprover.vue b/frontend/src/components/Issue/review/CurrentApprover.vuedeleted file mode 100644index 0f7116ec96..0000000000--- a/frontend/src/components/Issue/review/CurrentApprover.vue+++ /dev/null@@ -1,67 +0,0 @@-<template>- <div class="flex flex-row items-center">- <template v-if="legacyIssue.status !== 'OPEN' || done">- <span>-</span>- </template>- <template v-else-if="!ready">- <BBSpin />- </template>- <template v-else-if="currentApprover">- <BBAvatar- :size="'SMALL'"- :username="currentApprover.title"- :email="currentApprover.email"- />- <span class="ml-2">- {{ currentApprover.title }}- </span>- </template>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import {- extractIssueReviewContext,- useWrappedReviewSteps,-} from "@/plugins/issue/logic";-import { useAuthStore } from "@/store";-import { Issue as LegacyIssue } from "@/types";-import { Issue } from "@/types/proto/v1/issue_service";--const props = defineProps<{- legacyIssue: LegacyIssue;-}>();--const issue = computed(() => {- try {- return Issue.fromJSON(props.legacyIssue.payload.approval);- } catch {- return Issue.fromJSON({});- }-});--const context = extractIssueReviewContext(- computed(() => props.legacyIssue),- issue-);-const { ready, done } = context;-const currentUserName = computed(() => useAuthStore().currentUser.name);-const legacyIssue = computed(() => props.legacyIssue);-const wrappedSteps = useWrappedReviewSteps(legacyIssue, context);--const currentStep = computed(() => {- return wrappedSteps.value?.find((step) => step.status === "CURRENT");-});--const currentApprover = computed(() => {- if (!currentStep.value) return undefined;- const me = currentStep.value.candidates.find(- (user) => user.name === currentUserName.value- );- // Show currentUser if currentUser is one of the validate approver candidates.- if (me) return me;- // Show the first approver candidate otherwise.- return currentStep.value.candidates[0];-});-</script>diff --git a/frontend/src/components/Issue/review/ExternalApprovalNodeSyncButton.vue b/frontend/src/components/Issue/review/ExternalApprovalNodeSyncButton.vuedeleted file mode 100644index 690bf2996d..0000000000--- a/frontend/src/components/Issue/review/ExternalApprovalNodeSyncButton.vue+++ /dev/null@@ -1,66 +0,0 @@-<template>- <NTooltip>- <template #trigger>- <NButton- size="tiny"- circle- class="!ml-1"- :loading="syncing"- :tertiary="synced"- :type="synced ? 'success' : 'default'"- @click="syncNow"- >- <template #icon>- <heroicons:arrow-path v-if="!synced" class="w-4 h-4" />- <heroicons:check v-else class="w-4 h-4" />- </template>- </NButton>- </template>-- <div class="whitespace-nowrap">- {{ $t("common.sync-now") }}- </div>- </NTooltip>-</template>--<script setup lang="ts">-import { NButton, NTooltip } from "naive-ui";-import { ref, Ref } from "vue";-import { useI18n } from "vue-i18n";-import { pushNotification, useIssueV1Store } from "@/store";-import { Issue } from "@/types";-import { useIssueLogic } from "../logic";--const { t } = useI18n();-const syncing = ref(false);-const synced = ref(false);-const issueLogic = useIssueLogic();-const issue = issueLogic.issue as Ref<Issue>;--const syncNow = async () => {- if (syncing.value || synced.value) return;-- syncing.value = true;- try {- await useIssueV1Store().fetchIssueByLegacyIssue(- issue.value,- true /* force */- );-- synced.value = true;- // Show 'synced' status for several seconds to avoid user clicking sync- // button too frequently.- setTimeout(() => {- synced.value = false;- }, 5000);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.success"),- });- } finally {- syncing.value = false;- }-};-</script>diff --git a/frontend/src/components/Issue/review/IssueReviewButtonGroup.vue b/frontend/src/components/Issue/review/IssueReviewButtonGroup.vuedeleted file mode 100644index 719cfe2e99..0000000000--- a/frontend/src/components/Issue/review/IssueReviewButtonGroup.vue+++ /dev/null@@ -1,227 +0,0 @@-<template>- <div class="flex items-stretch gap-x-4">- <button- v-if="allowReject"- class="btn-normal"- @click="showModal(Issue_Approver_Status.REJECTED)"- >- {{ $t("custom-approval.issue-review.send-back") }}- </button>-- <BBTooltipButton- v-if="allowApprove"- :disabled="disallowApproveReasonList.length > 0"- :tooltip-props="{- placement: 'bottom-end',- }"- type="primary"- tooltip-mode="DISABLED-ONLY"- @click="showModal(Issue_Approver_Status.APPROVED)"- >- {{ $t("common.approve") }}-- <template #tooltip>- <div class="whitespace-pre-line max-w-[20rem]">- <div v-for="(reason, i) in disallowApproveReasonList" :key="i">- {{ reason }}- </div>- </div>- </template>- </BBTooltipButton>-- <button- v-if="allowReRequestReview"- class="btn-primary"- @click="showModal(Issue_Approver_Status.PENDING)"- >- {{ $t("custom-approval.issue-review.re-request-review") }}- </button>-- <StandaloneIssueStatusTransitionButtonGroup- :display-mode="- allowApprove || allowReject || allowReRequestReview- ? 'DROPDOWN'- : 'BUTTON'- "- />- </div>-- <BBModal- v-if="state.modal"- :title="state.modal.title"- class="relative overflow-hidden !w-[30rem] !max-w-[30rem]"- header-class="overflow-hidden"- @close="state.modal = undefined"- >- <div- v-if="state.loading"- class="absolute inset-0 flex items-center justify-center bg-white/50"- >- <BBSpin />- </div>- <IssueReviewForm- :status="state.modal.status"- :ok-text="state.modal.okText"- :button-style="state.modal.buttonStyle"- :review-type="state.modal.reviewType"- @cancel="state.modal = undefined"- @confirm="handleModalConfirm"- />- </BBModal>-</template>--<script lang="ts" setup>-import { computed, reactive, Ref } from "vue";-import { useI18n } from "vue-i18n";-import { BBTooltipButton } from "@/bbkit";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import {- candidatesOfApprovalStep,- useCurrentUserV1,- useIssueV1Store,-} from "@/store";-import { Issue } from "@/types";-import { Issue_Approver_Status } from "@/types/proto/v1/issue_service";-import { extractUserUID, taskCheckRunSummary } from "@/utils";-import { StandaloneIssueStatusTransitionButtonGroup } from "../StatusTransitionButtonGroup";-import { useIssueLogic } from "../logic";-import IssueReviewForm from "./IssueReviewForm.vue";--type LocalState = {- modal?: {- title: string;- status: Issue_Approver_Status;- okText: string;- buttonStyle: "PRIMARY" | "ERROR" | "NORMAL";- reviewType: "APPROVAL" | "SEND_BACK" | "RE_REQUEST_REVIEW";- };- loading: boolean;-};--const state = reactive<LocalState>({- modal: undefined,- loading: false,-});--const { t } = useI18n();-const store = useIssueV1Store();-const currentUserV1 = useCurrentUserV1();-const issueContext = useIssueLogic();-const issue = issueContext.issue as Ref<Issue>;-const { flow, ready, status, done } = useIssueReviewContext();--const allowApproveOrReject = computed(() => {- if (issue.value.status === "CANCELED" || issue.value.status === "DONE") {- return false;- }-- if (!ready.value) return false;- if (done.value) return false;-- const index = flow.value.currentStepIndex;- const steps = flow.value.template.flow?.steps ?? [];- const step = steps[index];- if (!step) return false;- const candidates = candidatesOfApprovalStep(issue.value, step);- return candidates.includes(currentUserV1.value.name);-});--const allowApprove = computed(() => {- if (!allowApproveOrReject.value) return false;-- return status.value === Issue_Approver_Status.PENDING;-});-const allowReject = computed(() => {- if (!allowApproveOrReject.value) return false;- return status.value === Issue_Approver_Status.PENDING;-});--const allowReRequestReview = computed(() => {- return (- String(issue.value.creator.id) ===- extractUserUID(currentUserV1.value.name) &&- status.value === Issue_Approver_Status.REJECTED- );-});--const allTaskChecksPassed = computed(() => {- const taskList =- issue.value.pipeline?.stageList.flatMap((stage) => stage.taskList) ?? [];- return taskList.every((task) => {- const summary = taskCheckRunSummary(task);- return summary.errorCount === 0 && summary.runningCount === 0;- });-});--const disallowApproveReasonList = computed((): string[] => {- const reasons: string[] = [];- if (!allTaskChecksPassed.value) {- reasons.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"- )- );- }- return reasons;-});--const showModal = (status: Issue_Approver_Status) => {- state.modal = {- status,- title: "",- okText: "",- buttonStyle: "NORMAL",- reviewType: "APPROVAL",- };- switch (status) {- case Issue_Approver_Status.APPROVED:- state.modal.title = t("custom-approval.issue-review.approve-issue");- state.modal.okText = t("common.approval");- state.modal.buttonStyle = "PRIMARY";- state.modal.reviewType = "APPROVAL";- break;- case Issue_Approver_Status.REJECTED:- state.modal.title = t("custom-approval.issue-review.send-back-issue");- state.modal.okText = t("custom-approval.issue-review.send-back");- state.modal.buttonStyle = "PRIMARY";- state.modal.reviewType = "SEND_BACK";- break;- case Issue_Approver_Status.PENDING:- state.modal.title = t(- "custom-approval.issue-review.re-request-review-issue"- );- state.modal.okText = t("custom-approval.issue-review.re-request-review");- state.modal.buttonStyle = "PRIMARY";- state.modal.reviewType = "RE_REQUEST_REVIEW";- }-};--const handleModalConfirm = async (- {- status,- comment,- }: {- status: Issue_Approver_Status;- comment?: string;- },- onSuccess: () => void-) => {- state.loading = true;- try {- if (status === Issue_Approver_Status.APPROVED) {- await store.approveIssue(issue.value, comment);- onSuccess();- } else if (status === Issue_Approver_Status.PENDING) {- await store.requestIssue(issue.value, comment);- } else if (status === Issue_Approver_Status.REJECTED) {- await store.rejectIssue(issue.value, comment);- }- state.modal = undefined;-- // notify the issue logic to update issue status- issueContext.onStatusChanged(true);- } finally {- state.loading = false;- }-};-</script>diff --git a/frontend/src/components/Issue/review/IssueReviewForm.vue b/frontend/src/components/Issue/review/IssueReviewForm.vuedeleted file mode 100644index 21b404464f..0000000000--- a/frontend/src/components/Issue/review/IssueReviewForm.vue+++ /dev/null@@ -1,109 +0,0 @@-<template>- <div class="mt-2 flex flex-col gap-y-4">- <div class="text-sm">- {{ issue.name }}- </div>- <div class="flex flex-col gap-y-1">- <p class="textlabel">- {{ $t("common.comment") }}- <RequiredStar v-show="props.reviewType === 'SEND_BACK'" />- </p>- <AutoHeightTextarea- v-model:value="comment"- :placeholder="$t('issue.leave-a-comment')"- :max-height="160"- class="w-full"- />- </div>- <div class="py-1 flex justify-end gap-x-3">- <button class="btn-normal" @click="$emit('cancel')">- {{ $t("common.cancel") }}- </button>- <button- :class="- buttonStyle === 'PRIMARY'- ? 'btn-primary'- : buttonStyle === 'ERROR'- ? 'btn-danger'- : 'btn-normal'- "- :disabled="!allowConfirm"- @click="handleConfirm"- >- {{ okText }}- </button>- </div>- </div>-</template>--<script lang="ts" setup>-import { Ref, computed, ref } from "vue";-import RequiredStar from "@/components/RequiredStar.vue";-import AutoHeightTextarea from "@/components/misc/AutoHeightTextarea.vue";-import { Issue } from "@/types";-import { Issue_Approver_Status } from "@/types/proto/v1/issue_service";-import { useIssueLogic } from "../logic";--const props = defineProps<{- okText: string;- status: Issue_Approver_Status;- buttonStyle: "PRIMARY" | "ERROR" | "NORMAL";- reviewType: "APPROVAL" | "SEND_BACK" | "RE_REQUEST_REVIEW";-}>();--const emit = defineEmits<{- (event: "cancel"): void;- (- event: "confirm",- params: {- status: Issue_Approver_Status;- comment?: string;- },- onSuccess: () => void- ): void;-}>();--const issueContext = useIssueLogic();-const issue = issueContext.issue as Ref<Issue>;-const comment = ref("");--const allowConfirm = computed(() => {- if (props.reviewType === "SEND_BACK" && comment.value === "") {- return false;- }-- return true;-});--const handleConfirm = (e: MouseEvent) => {- const button = e.target as HTMLElement;- const { left, top, width, height } = button.getBoundingClientRect();- const { innerWidth: winWidth, innerHeight: winHeight } = window;- const onSuccess = () => {- if (props.status !== Issue_Approver_Status.APPROVED) {- return;- }- // import the effect lib asynchronously- import("canvas-confetti").then(({ default: confetti }) => {- // Create a confetti effect from the position of the LGTM button- confetti({- particleCount: 100,- spread: 70,- origin: {- x: (left + width / 2) / winWidth,- y: (top + height / 2) / winHeight,- },- });- });- };-- emit(- "confirm",- {- status: props.status,- comment: comment.value,- },- onSuccess- );-};-</script>diff --git a/frontend/src/components/Issue/review/IssueReviewPanel.vue b/frontend/src/components/Issue/review/IssueReviewPanel.vuedeleted file mode 100644index 1c1d3ef40e..0000000000--- a/frontend/src/components/Issue/review/IssueReviewPanel.vue+++ /dev/null@@ -1,21 +0,0 @@-<template>- <div v-if="ready && wrappedSteps" class="mt-1">- <ApprovalTimeline :steps="wrappedSteps" />- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { useWrappedReviewSteps } from "@/plugins/issue/logic";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { Issue } from "@/types";-import { useIssueLogic } from "../logic";-import ApprovalTimeline from "./ApprovalTimeline.vue";--const issueLogic = useIssueLogic();-const issue = computed(() => issueLogic.issue.value as Issue);-const context = useIssueReviewContext();-const { ready } = context;--const wrappedSteps = useWrappedReviewSteps(issue, context);-</script>diff --git a/frontend/src/components/Issue/review/IssueReviewSidebarSection.vue b/frontend/src/components/Issue/review/IssueReviewSidebarSection.vuedeleted file mode 100644index 1e104adfbd..0000000000--- a/frontend/src/components/Issue/review/IssueReviewSidebarSection.vue+++ /dev/null@@ -1,91 +0,0 @@-<template>- <h2 class="textlabel flex items-start col-span-1 col-start-1 pt-1">- <div class="flex items-center gap-x-1">- <span>{{ $t("issue.approval-flow.self") }}</span>- <NTooltip v-if="showApprovalTooltip">- <div class="max-w-[24rem]">- {{ $t("issue.approval-flow.tooltip") }}- </div>- <template #trigger>- <heroicons-outline:question-mark-circle />- </template>- </NTooltip>- </div>- </h2>- <div class="col-span-2">- <div- v-if="!ready"- class="flex items-center gap-x-2 mt-1 text-sm text-control-placeholder"- >- <BBSpin class="w-4 h-4" />- <span>- {{ $t("custom-approval.issue-review.generating-approval-flow") }}- </span>- </div>- <div v-else-if="error" class="flex items-center gap-x-2 mt-0.5">- <NTooltip>- <template #trigger>- <span class="text-error text-sm">{{ $t("common.error") }}</span>- </template>-- <div class="max-w-[20rem]">- {{ error }}- </div>- </NTooltip>- <NButton- size="tiny"- :loading="retrying"- @click="retryFindingApprovalFlow"- >{{ $t("common.retry") }}</NButton- >- </div>- <IssueReviewPanel v-else-if="steps.length > 0" />- <div- v-else- class="flex items-center mt-1 text-sm text-control-placeholder gap-x-1"- >- {{ $t("custom-approval.approval-flow.skip") }}- <FeatureBadgeForInstanceLicense- feature="bb.feature.custom-approval"- :instance="selectedDatabase?.instanceEntity"- />- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, Ref, ref } from "vue";-import { useIssueReviewContext } from "@/plugins/issue/logic/review/context";-import { useIssueV1Store } from "@/store";-import { Issue } from "@/types";-import { isGrantRequestIssueType } from "@/utils";-import { useIssueLogic } from "../logic";-import IssueReviewPanel from "./IssueReviewPanel.vue";--const store = useIssueV1Store();-const issueContext = useIssueLogic();-const { selectedDatabase } = issueContext;-const issue = issueContext.issue as Ref<Issue>;-const context = useIssueReviewContext();-const { ready, error, flow } = context;--const steps = computed(() => flow.value.template.flow?.steps ?? []);--const retrying = ref(false);-const retryFindingApprovalFlow = async () => {- retrying.value = true;- try {- await store.regenerateReview(issue.value);- } finally {- retrying.value = false;- }-};--const showApprovalTooltip = computed(() => {- // Don't show the tooltip if the issue type is grant request.- if (isGrantRequestIssueType(issue.value.type)) {- return false;- }- return true;-});-</script>diff --git a/frontend/src/components/Issue/review/index.ts b/frontend/src/components/Issue/review/index.tsdeleted file mode 100644index 56cc8d6f3a..0000000000--- a/frontend/src/components/Issue/review/index.ts+++ /dev/null@@ -1,11 +0,0 @@-import CurrentApprover from "./CurrentApprover.vue";-import IssueReviewButtonGroup from "./IssueReviewButtonGroup.vue";-import IssueReviewPanel from "./IssueReviewPanel.vue";-import IssueReviewSidebarSection from "./IssueReviewSidebarSection.vue";--export {- IssueReviewPanel,- IssueReviewButtonGroup,- IssueReviewSidebarSection,- CurrentApprover,-};diff --git a/frontend/src/components/Issue/rollback/LogButton.vue b/frontend/src/components/Issue/rollback/LogButton.vuedeleted file mode 100644index de5e61a0f0..0000000000--- a/frontend/src/components/Issue/rollback/LogButton.vue+++ /dev/null@@ -1,20 +0,0 @@-<template>- <div class="flex items-center h-[30px]">- <BBSwitch- :disabled="disabled"- :value="false"- :text="true"- @toggle="toggleRollback(true)"- />- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { BBSwitch } from "@/bbkit";-import { useRollbackLogic } from "./common";--const { allowRollback, toggleRollback } = useRollbackLogic();--const disabled = computed(() => !allowRollback.value);-</script>diff --git a/frontend/src/components/Issue/rollback/LoggingButton.vue b/frontend/src/components/Issue/rollback/LoggingButton.vuedeleted file mode 100644index 1540eaf3a8..0000000000--- a/frontend/src/components/Issue/rollback/LoggingButton.vue+++ /dev/null@@ -1,32 +0,0 @@-<template>- <div- class="select-none inline-flex items-center gap-x-1 h-[30px] text-control bg-white focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2"- >- <BBSpin class="w-4 h-4" />- <span class="text-sm leading-5 font-medium">{{- $t("task.rollback.generating")- }}</span>- <NTooltip v-if="!disabled" :animated="false" :delay="150">- <template #trigger>- <span- class="ml-1 py-0.5 px-1.5 text-xs flex items-center rounded border border-control-border hover:bg-control-bg-hover cursor-pointer"- @click="toggleRollback(false)"- >- {{ $t("common.cancel") }}- </span>- </template>-- <span>{{ $t("task.rollback.cancel-generating") }}</span>- </NTooltip>- </div>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useRollbackLogic } from "./common";--const { allowRollback, toggleRollback } = useRollbackLogic();--const disabled = computed(() => !allowRollback.value);-</script>diff --git a/frontend/src/components/Issue/rollback/RollbackStatus.vue b/frontend/src/components/Issue/rollback/RollbackStatus.vuedeleted file mode 100644index 95319fbde2..0000000000--- a/frontend/src/components/Issue/rollback/RollbackStatus.vue+++ /dev/null@@ -1,192 +0,0 @@-<template>- <div class="text-sm font-medium">- <template v-if="!payload?.rollbackEnabled">- <LogButton />- </template>- <template v-else>- <template v-if="payload?.rollbackSqlStatus === 'FAILED'">- <div class="tooltip-wrapper">- <NTooltip>- <template #trigger>- <span class="text-error">{{ $t("task.rollback.failed") }}</span>- </template>-- <div v-if="payload.rollbackError" class="max-w-[20rem]">- {{ payload.rollbackError }}- </div>- </NTooltip>- </div>- </template>- <template v-else-if="payload?.rollbackSqlStatus === 'DONE'">- <template v-if="taskRollbackBy && rollbackByIssue.id !== UNKNOWN_ID">- <router-link- :to="`/issue/${taskRollbackBy.rollbackByIssueId}`"- class="text-accent inline-flex gap-x-1"- >- <span>{{ $t("common.issue") }}</span>- <span>#{{ taskRollbackBy.rollbackByIssueId }}</span>- <IssueStatusIcon :issue-status="rollbackByIssue.status" />- </router-link>- </template>- <template v-else>- <button- v-if="allowPreviewRollback"- type="button"- class="btn-normal !px-3 !py-1"- @click.prevent="tryRollbackTask"- >- {{ $t("task.rollback.preview-rollback-issue") }}- </button>- <NTooltip v-else :disabled="!!payload?.rollbackSheetId">- <template #trigger>- <div- class="select-none inline-flex border border-control-border rounded-md bg-control-bg opacity-50 cursor-not-allowed px-3 py-1 text-sm leading-5 font-medium"- >- {{ $t("task.rollback.preview-rollback-issue") }}- </div>- </template>-- <div v-if="!payload?.rollbackSheetId" class="whitespace-pre-line">- {{ $t("task.rollback.empty-rollback-statement") }}- <LearnMoreLink- url="https://www.bytebase.com/docs/change-database/rollback-data-changes?source=console#why-i-get-the-rollback-sheet-is-empty"- color="light"- class="ml-1"- />- </div>- </NTooltip>- </template>- </template>- <template v-else>- <LoggingButton />- </template>- </template>- </div>-</template>-<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import { computed, reactive, type Ref } from "vue";-import { useRouter } from "vue-router";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import { useActivityV1Store, useIssueById, useSheetV1Store } from "@/store";-import {- ActivityIssueCommentCreatePayload,- Issue,- Task,- TaskDatabaseDataUpdatePayload,- TaskRollbackBy,- UNKNOWN_ID,-} from "@/types";-import { LogEntity_Action } from "@/types/proto/v1/logging_service";-import IssueStatusIcon from "../IssueStatusIcon.vue";-import { useIssueLogic } from "../logic";-import LogButton from "./LogButton.vue";-import LoggingButton from "./LoggingButton.vue";-import { useRollbackLogic } from "./common";--type LocalState = {- loading: boolean;- rollbackIssue: Issue | undefined;-};--const router = useRouter();-const sheetV1Store = useSheetV1Store();--const context = useIssueLogic();-const { allowRollback } = useRollbackLogic();--const issue = context.issue as Ref<Issue>;-const task = context.selectedTask as Ref<Task>;-const payload = computed(- () => task.value.payload as TaskDatabaseDataUpdatePayload | undefined-);--const state = reactive<LocalState>({- loading: false,- rollbackIssue: undefined,-});--const allowPreviewRollback = computed(() => {- if (!allowRollback.value) {- return false;- }- if (!payload.value?.rollbackSheetId) {- return false;- }- return true;-});--const taskRollbackBy = computed((): TaskRollbackBy | undefined => {- const activityList = useActivityV1Store().getActivityListByIssue(- issue.value.id- );- // Find the latest comment activity with TaskRollbackBy struct if possible.- for (let i = activityList.length - 1; i >= 0; i--) {- const activity = activityList[i];- if (activity.action !== LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE)- continue;- const payload = JSON.parse(activity.payload) as- | ActivityIssueCommentCreatePayload- | undefined;- if (!payload) continue;- const taskRollbackBy = payload.taskRollbackBy;- if (!taskRollbackBy) continue;- return taskRollbackBy;- }- return undefined;-});--const rollbackByIssue = useIssueById(- computed(() => taskRollbackBy.value?.rollbackByIssueId ?? UNKNOWN_ID)-);--const tryRollbackTask = async () => {- const navigateToRollbackIssue = () => {- if (!state.rollbackIssue) return;- router.push(`/issue/${state.rollbackIssue.id}`);- };-- if (state.rollbackIssue) {- return navigateToRollbackIssue();- }-- try {- state.loading = true;-- const issueName = [- `Rollback`,- `#${issue.value.id}`,- `${issue.value.name}`,- ].join(" ");-- const originalSheetUID = payload.value!.sheetId!;- const rollbackSheetUID = payload.value!.rollbackSheetId!;- const originalSheet = await sheetV1Store.getOrFetchSheetByUID(- String(originalSheetUID)- );- const description = [- "The original SQL statement:",- `${new TextDecoder().decode(originalSheet?.content)}`,- ].join("\n");-- router.push({- name: "workspace.issue.detail",- params: {- issueSlug: "new",- },- query: {- template: "bb.issue.database.data.update",- name: issueName,- project: issue.value.project.id,- databaseList: [task.value.database!.id].join(","),- rollbackIssueId: issue.value.id,- rollbackTaskIdList: [task.value.id].join(","),- sheetId: rollbackSheetUID,- description,- },- });- } finally {- state.loading = false;- }-};-</script>diff --git a/frontend/src/components/Issue/rollback/RollbackSwitch.vue b/frontend/src/components/Issue/rollback/RollbackSwitch.vuedeleted file mode 100644index a6b62e2e80..0000000000--- a/frontend/src/components/Issue/rollback/RollbackSwitch.vue+++ /dev/null@@ -1,17 +0,0 @@-<template>- <div class="flex items-center h-[30px]">- <BBSwitch- :disabled="!allowRollback"- :value="rollbackEnabled"- :text="true"- @toggle="toggleRollback"- />- </div>-</template>--<script lang="ts" setup>-import { BBSwitch } from "@/bbkit";-import { useRollbackLogic } from "./common";--const { allowRollback, rollbackEnabled, toggleRollback } = useRollbackLogic();-</script>diff --git a/frontend/src/components/Issue/rollback/TaskRollbackView.vue b/frontend/src/components/Issue/rollback/TaskRollbackView.vuedeleted file mode 100644index bd06f101b7..0000000000--- a/frontend/src/components/Issue/rollback/TaskRollbackView.vue+++ /dev/null@@ -1,38 +0,0 @@-<template>- <div v-if="rollbackUIType !== 'NONE'" class="contents">- <h2 class="textlabel flex items-center">- <span class="mr-1">{{ $t("task.rollback.sql-rollback") }}</span>- <NTooltip>- <template #trigger>- <heroicons-outline:question-mark-circle class="h-4 w-4" />- </template>- <i18n-t- tag="div"- keypath="task.rollback.sql-rollback-tips"- class="whitespace-pre-line"- >- <template #link>- <LearnMoreLink- url="https://www.bytebase.com/docs/change-database/rollback-data-changes?source=console"- color="light"- />- </template>- </i18n-t>- </NTooltip>- </h2>-- <div class="col-span-2 flex items-center">- <RollbackSwitch v-if="rollbackUIType === 'SWITCH'" />- <RollbackStatus v-if="rollbackUIType === 'FULL'" />- </div>- </div>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import RollbackStatus from "./RollbackStatus.vue";-import RollbackSwitch from "./RollbackSwitch.vue";-import { useRollbackLogic } from "./common";--const { rollbackUIType } = useRollbackLogic();-</script>diff --git a/frontend/src/components/Issue/rollback/common.ts b/frontend/src/components/Issue/rollback/common.tsdeleted file mode 100644index 69f335a684..0000000000--- a/frontend/src/components/Issue/rollback/common.ts+++ /dev/null@@ -1,281 +0,0 @@-import { head } from "lodash-es";-import { computed } from "vue";-import {- useIssueV1Store,- useCurrentUserV1,- useDatabaseV1Store,- useIssueStore,- useProjectV1Store,-} from "@/store";-import {- ComposedDatabase,- Issue,- IssueCreate,- IssueId,- MigrationContext,- Task,- TaskCreate,- TaskDatabaseDataUpdatePayload,- TaskId,- UNKNOWN_ID,-} from "@/types";-import { Engine } from "@/types/proto/v1/common";-import {- extractUserUID,- hasPermissionInProjectV1,- hasWorkspacePermissionV1,- isTaskCreate,- isTaskSkipped,- semverCompare,-} from "@/utils";-import { flattenTaskList, useIssueLogic } from "../logic";--const MIN_ROLLBACK_SQL_MYSQL_VERSION = "5.7.0";--export type RollbackUIType =- | "SWITCH" // Show a simple checkbox to turn on/off rollback- | "FULL" // Show featured rollback status- | "NONE"; // Nothing--export const useRollbackLogic = () => {- const currentUserV1 = useCurrentUserV1();- const context = useIssueLogic();- const {- create,- issue,- isTenantMode,- selectedTask: task,- patchTask,- } = context;-- // Decide with type of UI should be displayed.- const rollbackUIType = computed((): RollbackUIType => {- if (issue.value.type !== "bb.issue.database.data.update") {- return "NONE";- }- if (task.value.type !== "bb.task.database.data.update") {- return "NONE";- }- const database = databaseOfTask(task.value);- const { engine, engineVersion } = database.instanceEntity;- switch (engine) {- case Engine.MYSQL:- if (- !semverCompare(engineVersion, MIN_ROLLBACK_SQL_MYSQL_VERSION, "gte")- ) {- return "NONE";- }- break;- case Engine.ORACLE:- // We don't have a check for oracle similar to the MySQL version check.- break;- default:- return "NONE";- }-- if (create.value) {- return "SWITCH";- }- const taskEntity = task.value as Task;- if (taskEntity.status === "DONE") {- if (isTaskSkipped(taskEntity)) {- // Rollback is not available for skipped tasks.- return "NONE";- }- return "FULL";- }- if (taskEntity.status === "CANCELED") {- return "NONE";- }-- return "SWITCH";- });-- // Decide whether current user can operate.- const allowRollback = computed((): boolean => {- if (rollbackUIType.value === "NONE") {- return false;- }-- if (create.value) {- return true;- }-- const issueEntity = issue.value as Issue;- const user = currentUserV1.value;- const userUID = extractUserUID(user.name);-- if (userUID === String(issueEntity.creator.id)) {- // Allowed to the issue creator- return true;- }-- if (userUID === String(issueEntity.assignee.id)) {- // Allowed to the issue assignee- return true;- }-- const projectV1 = useProjectV1Store().getProjectByUID(- String(issueEntity.project.id)- );- if (- hasPermissionInProjectV1(- projectV1.iamPolicy,- user,- "bb.permission.project.admin-database"- )- ) {- return true;- }-- if (- hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- user.userRole- )- ) {- // Allowed to DBAs and workspace owners- return true;- }- return false;- });-- const rollbackEnabled = computed((): boolean => {- if (create.value) {- if (isTenantMode.value) {- // In tenant mode, all tasks share a common MigrationDetail- const issueCreate = issue.value as IssueCreate;- const createContext = issueCreate.createContext as MigrationContext;- const migrationDetail = head(createContext.detailList);- return migrationDetail?.rollbackEnabled ?? false;- }- // In standard mode, every task has a independent TaskCreate with its- // own rollbackEnabled field.- const taskCreate = task.value as TaskCreate;- return taskCreate.rollbackEnabled ?? false;- } else {- const taskEntity = task.value as Task;- const payload = taskEntity.payload as- | TaskDatabaseDataUpdatePayload- | undefined;- return payload?.rollbackEnabled ?? false;- }- });-- const toggleRollback = async (on: boolean) => {- if (create.value) {- if (isTenantMode.value) {- // In tenant mode, all tasks share a common MigrationDetail- const issueCreate = issue.value as IssueCreate;- const createContext = issueCreate.createContext as MigrationContext;- createContext.detailList.forEach((detail) => {- detail.rollbackEnabled = on;- });- } else {- // In standard mode, every task has a independent TaskCreate with its- // own rollbackEnabled field.- const taskCreate = task.value as TaskCreate;- taskCreate.rollbackEnabled = on;- }- } else {- // Once the issue has been created, we need to patch the task.- const taskEntity = task.value as Task;- await patchTask(taskEntity.id, {- rollbackEnabled: on,- });-- const issueEntity = issue.value as Issue;- const action = on ? "Enable" : "Disable";- try {- await useIssueV1Store().createIssueComment({- issueId: issueEntity.id,- comment: `${action} SQL rollback log for task [${taskEntity.name}].`,- payload: {- issueName: issueEntity.name,- },- });- } catch {- // do nothing- // failing to comment to won't be too bad- }- }- };-- return {- rollbackUIType,- allowRollback,- rollbackEnabled,- toggleRollback,- };-};--const databaseOfTask = (task: Task | TaskCreate): ComposedDatabase => {- const uid = isTaskCreate(task)- ? String((task as TaskCreate).databaseId!)- : String(task.database!.id);- return useDatabaseV1Store().getDatabaseByUID(uid);-};--export const maybeCreateBackTraceComments = async (newIssue: Issue) => {- if (newIssue.type !== "bb.issue.database.data.update") return;- const rollbackList = [] as Array<{- byTask: Task;- fromIssueId: IssueId;- fromTaskId: TaskId;- }>;- const taskList = flattenTaskList<Task>(newIssue);- for (let i = 0; i < taskList.length; i++) {- const byTask = taskList[i];- if (byTask.type !== "bb.task.database.data.update") continue;- const payload = byTask.payload as TaskDatabaseDataUpdatePayload;- if (!payload) continue;- if (- payload.rollbackFromIssueId &&- payload.rollbackFromIssueId !== UNKNOWN_ID &&- payload.rollbackFromTaskId &&- payload.rollbackFromTaskId !== UNKNOWN_ID- ) {- rollbackList.push({- byTask,- fromIssueId: payload.rollbackFromIssueId,- fromTaskId: payload.rollbackFromTaskId,- });- }- }- if (rollbackList.length === 0) return;-- const issueStore = useIssueStore();- for (let i = 0; i < rollbackList.length; i++) {- const { byTask, fromIssueId, fromTaskId } = rollbackList[i];- const fromIssue = await issueStore.getOrFetchIssueById(fromIssueId);- if (fromIssue.id === UNKNOWN_ID) continue;- const fromTask = flattenTaskList<Task>(fromIssue).find(- (task) => task.id === fromTaskId- );- if (!fromTask || fromTask.id === UNKNOWN_ID) continue;-- const comment = [- `Create issue #${newIssue.id}`,- "to rollback task",- `[${fromTask.name}]`,- ].join(" ");- try {- await useIssueV1Store().createIssueComment({- issueId: fromIssue.id,- comment,- payload: {- issueName: fromIssue.name,- taskRollbackBy: {- issueId: fromIssue.id,- taskId: fromTask.id,- rollbackByIssueId: newIssue.id,- rollbackByTaskId: byTask.id,- },- },- });- } catch {- // do nothing- // failing to comment to won't be too bad- }- }-};diff --git a/frontend/src/components/Issue/table/DatabaseResourceTable.vue b/frontend/src/components/Issue/table/DatabaseResourceTable.vuedeleted file mode 100644index ebd71a1ea5..0000000000--- a/frontend/src/components/Issue/table/DatabaseResourceTable.vue+++ /dev/null@@ -1,106 +0,0 @@-<template>- <BBGrid- :column-list="COLUMN_LIST"- :data-source="databaseResourceList"- :row-clickable="true"- row-key="name"- class="border"- >- <template #item="{ item }">- <div class="bb-grid-cell">- {{ extractDatabaseName(item) }}- </div>- <div class="bb-grid-cell">- <span class="line-clamp-1">{{ extractTableName(item) }}</span>- </div>- <div class="bb-grid-cell">- <EnvironmentV1Name- :environment="- extractComposedDatabase(item).effectiveEnvironmentEntity- "- />- </div>- <div class="bb-grid-cell">- <InstanceV1Name- :instance="extractComposedDatabase(item).instanceEntity"- />- </div>- </template>- </BBGrid>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBGridColumn } from "@/bbkit";-import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";-import { useDatabaseV1Store } from "@/store";-import { DatabaseResource } from "@/types";-import { DatabaseGroup } from "@/types/proto/v1/project_service";--const props = defineProps<{- databaseResourceList: DatabaseResource[];-}>();--defineEmits<{- (event: "edit", databaseGroup: DatabaseGroup): void;-}>();--const { t } = useI18n();-const databaseStore = useDatabaseV1Store();--const extractDatabaseName = (databaseResource: DatabaseResource) => {- const database = databaseStore.getDatabaseByName(- String(databaseResource.databaseName)- );- return database.databaseName;-};--const extractTableName = (databaseResource: DatabaseResource) => {- if (!databaseResource.schema && !databaseResource.table) {- return "*";- }- const names = [];- if (databaseResource.schema) {- names.push(databaseResource.schema);- }- names.push(databaseResource.table || "*");- return names.join(".");-};--const extractComposedDatabase = (databaseResource: DatabaseResource) => {- const database = databaseStore.getDatabaseByName(- String(databaseResource.databaseName)- );- return database;-};--watch(- () => props.databaseResourceList,- async () => {- for (const databaseResource of props.databaseResourceList) {- await databaseStore.getOrFetchDatabaseByName(- databaseResource.databaseName- );- }- },- {- immediate: true,- }-);--const COLUMN_LIST = computed(() => {- const columns: BBGridColumn[] = [- { title: t("common.database"), width: "1fr" },- { title: t("common.table"), width: "0.5fr" },- {- title: t("common.environment"),- width: "0.5fr",- },- { title: t("common.instance"), width: "1fr" },- ];-- return columns;-});-</script>diff --git a/frontend/src/components/Issue/table/IssueTable.vue b/frontend/src/components/Issue/table/IssueTable.vuedeleted file mode 100644index ece9e05e10..0000000000--- a/frontend/src/components/Issue/table/IssueTable.vue+++ /dev/null@@ -1,413 +0,0 @@-<template>- <BBTable- ref="tableRef"- :column-list="columnList"- :section-data-source="issueSectionList"- :show-header="true"- :custom-header="true"- :left-bordered="leftBordered"- :right-bordered="rightBordered"- :top-bordered="topBordered"- :bottom-bordered="bottomBordered"- v-bind="$attrs"- @click-row="clickIssue"- >- <template #header>- <th- v-for="(column, index) in columnList"- :key="index"- scope="col"- class="pl-2 first:pl-4 py-2 text-left text-xs font-medium text-gray-500 tracking-wider capitalize"- :class="[column.center && 'text-center pr-2']"- >- <template v-if="index === 0">- <input- v-if="issueList.length > 0"- type="checkbox"- class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"- :checked="allSelectionState.checked"- :indeterminate="allSelectionState.indeterminate"- @input="- setAllIssuesSelection(($event.target as HTMLInputElement).checked)- "- />- </template>- <template v-else>{{ $t(column.title) }}</template>- </th>- </template>- <template #body="{ rowData: issue }: { rowData: Issue }">- <BBTableCell- class="w-[1%]"- @click.stop="setIssueSelection(issue, !isIssueSelected(issue))"- >- <!-- width: 1% means as narrow as possible -->- <input- type="checkbox"- class="ml-2 h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"- :checked="isIssueSelected(issue)"- />- </BBTableCell>- <BBTableCell class="table-cell w-12">- <IssueStatusIcon- :issue-status="issue.status"- :task-status="issueTaskStatus(issue)"- />- </BBTableCell>- <BBTableCell class="table-cell">- <div class="flex items-center">- <div class="whitespace-nowrap mr-2 text-control">- <template v-if="mode == 'ALL'">- {{ issue.project.key }}-{{ issue.id }}- </template>- <template v-else> #{{ issue.id }} </template>- </div>- <div- class="truncate"- :class="{- 'font-semibold': isAssigneeAttentionOn(issue),- }"- >- {{ issue.name }}- </div>- <NTooltip v-if="isAssigneeAttentionOn(issue)">- <template #trigger>- <span>- <heroicons-outline:bell-alert- class="w-4 h-4 text-accent ml-1"- />- </span>- </template>- <span class="whitespace-nowrap">- {{ $t("issue.assignee-attention.needs-attention") }}- </span>- </NTooltip>- </div>- </BBTableCell>- <BBTableCell class="table-cell w-36">- <div- v-if="isDatabaseRelatedIssueType(issue.type)"- class="flex items-center"- >- {{ activeEnvironmentName(issue) }}- <ProductionEnvironmentIcon- class="ml-1"- :environment="activeEnvironment(issue.pipeline)"- />- </div>- <div v-else>-</div>- </BBTableCell>- <BBTableCell class="hidden sm:table-cell w-36">- <BBStepBar- :step-list="taskStepList(issue)"- @click-step="- (step: any) => {- clickIssueStep(issue, step);- }- "- />- </BBTableCell>- <BBTableCell class="hidden md:table-cell w-36">- {{ humanizeTs(issue.updatedTs) }}- </BBTableCell>- <BBTableCell class="hidden sm:table-cell w-36">- <CurrentApprover :legacy-issue="issue" />- </BBTableCell>- <BBTableCell class="hidden sm:table-cell w-36">- <div class="flex flex-row items-center">- <BBAvatar- :size="'SMALL'"- :username="- issue.assignee ? issue.assignee.name : $t('common.unassigned')- "- :email="issue.assignee?.email"- />- <span class="ml-2">- {{ issue.assignee ? issue.assignee.name : $t("common.unassigned") }}- </span>- </div>- </BBTableCell>- <BBTableCell class="hidden sm:table-cell w-36">- <div class="flex flex-row items-center">- <BBAvatar- :size="'SMALL'"- :username="issue.creator.name"- :email="issue.creator.email"- />- <span class="ml-2">- {{ issue.creator.name }}- </span>- </div>- </BBTableCell>- </template>- </BBTable>-- <div- v-if="isTableInViewport && selectedIssueList.length > 0"- class="sticky bottom-0 w-full bg-white flex items-center gap-x-2 px-4 py-2 border border-t-0"- >- <BatchIssueActions :issue-list="selectedIssueList" />- </div>-</template>--<script lang="ts" setup>-import { reactive, PropType, computed, watch, ref } from "vue";-import { useRouter } from "vue-router";-import type {- BBTableColumn,- BBStep,- BBStepStatus,- BBTableSectionDataSource,-} from "@/bbkit/types";-import ProductionEnvironmentIcon from "@/components/Environment/ProductionEnvironmentIcon.vue";-import BatchIssueActions from "@/components/Issue/BatchIssueActions.vue";-import IssueStatusIcon from "@/components/Issue/IssueStatusIcon.vue";-import { useElementVisibilityInScrollParent } from "@/composables/useElementVisibilityInScrollParent";-import { useCurrentUserV1 } from "@/store";-import type { Issue, IssueId, Task } from "@/types";-import {- issueSlug,- activeEnvironment,- activeTask,- stageSlug,- activeTaskInStage,- isDatabaseRelatedIssueType,- extractUserUID,-} from "@/utils";-import { CurrentApprover } from "../review";--type Mode = "ALL" | "PROJECT";--const columnList: BBTableColumn[] = [- {- title: "",- },- {- title: "",- },- {- title: "issue.table.name",- },- {- title: "issue.table.environment",- },- {- title: "issue.table.progress",- },- {- title: "issue.table.updated",- },- {- title: "issue.table.approver",- },- {- title: "issue.table.assignee",- },- {- title: "issue.table.creator",- },-];--interface LocalState {- dataSource: any[];- selectedIssueIdList: Set<IssueId>;-}--const props = defineProps({- title: {- type: String,- required: true,- },- issueList: {- type: Array as PropType<Issue[]>,- default: () => [],- },- mode: {- default: "ALL",- type: String as PropType<Mode>,- },- leftBordered: {- default: true,- type: Boolean,- },- rightBordered: {- default: true,- type: Boolean,- },- topBordered: {- default: true,- type: Boolean,- },- bottomBordered: {- default: true,- type: Boolean,- },-});-const router = useRouter();--const state = reactive<LocalState>({- dataSource: [],- selectedIssueIdList: new Set(),-});-const currentUserV1 = useCurrentUserV1();--const tableRef = ref<HTMLTableElement>();-const isTableInViewport = useElementVisibilityInScrollParent(tableRef);--const issueSectionList = computed((): BBTableSectionDataSource<Issue>[] => {- return [- {- title: props.title,- list: props.issueList,- },- ];-});--const selectedIssueList = computed(() => {- return props.issueList.filter((issue) =>- state.selectedIssueIdList.has(issue.id)- );-});--const issueTaskStatus = (issue: Issue) => {- // For grant request issue, we always show the status as "PENDING_APPROVAL" as task status.- if (!isDatabaseRelatedIssueType(issue.type)) {- return "PENDING_APPROVAL";- }-- return activeTask(issue.pipeline!).status;-};--const activeEnvironmentName = function (issue: Issue) {- return activeEnvironment(issue.pipeline).name;-};--const taskStepList = function (issue: Issue): BBStep[] {- if (!isDatabaseRelatedIssueType(issue.type)) {- return [- {- status:- issue.status === "OPEN" ? "PENDING_APPROVAL_ACTIVE" : issue.status,- payload: undefined,- },- ];- }-- return issue.pipeline!.stageList.map((stage) => {- const task = activeTaskInStage(stage);- let status: BBStepStatus = task.status;- if (status == "PENDING" || status == "PENDING_APPROVAL") {- if (activeTask(issue.pipeline!).id == task.id) {- status =- status == "PENDING" ? "PENDING_ACTIVE" : "PENDING_APPROVAL_ACTIVE";- }- }- return {- status,- payload: task,- };- });-};--const isIssueSelected = (issue: Issue): boolean => {- return state.selectedIssueIdList.has(issue.id);-};--const allSelectionState = computed(() => {- const set = state.selectedIssueIdList;-- const checked = props.issueList.every((issue) => set.has(issue.id));- const indeterminate =- !checked && props.issueList.some((issue) => set.has(issue.id));-- return {- checked,- indeterminate,- };-});--const setIssueSelection = (issue: Issue, selected: boolean) => {- if (selected) {- state.selectedIssueIdList.add(issue.id);- } else {- state.selectedIssueIdList.delete(issue.id);- }-};-const setAllIssuesSelection = (selected: boolean): void => {- const set = state.selectedIssueIdList;- const list = props.issueList;- if (selected) {- list.forEach((issue) => {- set.add(issue.id);- });- } else {- list.forEach((issue) => {- set.delete(issue.id);- });- }-};--const isAssigneeAttentionOn = (issue: Issue) => {- if (issue.project.workflowType === "VCS") {- return false;- }- if (issue.status !== "OPEN") {- return false;- }- if (extractUserUID(currentUserV1.value.name) === String(issue.assignee.id)) {- // True if current user is the assignee- return issue.assigneeNeedAttention;- }-- return false;-};--const clickIssue = (_: number, row: number, e: MouseEvent) => {- const issue = props.issueList[row];- const url = `/issue/${issueSlug(issue.name, issue.id)}`;- if (e.ctrlKey || e.metaKey) {- window.open(url, "_blank");- } else {- router.push(url);- }-};--const clickIssueStep = (issue: Issue, step: BBStep) => {- if (!isDatabaseRelatedIssueType(issue.type)) {- router.push({- name: "workspace.issue.detail",- params: {- issueSlug: issueSlug(issue.name, issue.id),- },- });- return;- }-- const task = step.payload as Task;- const stageIndex = issue.pipeline!.stageList.findIndex((item) => {- return item.id == task.stage.id;- });-- router.push({- name: "workspace.issue.detail",- params: {- issueSlug: issueSlug(issue.name, issue.id),- },- query: { stage: stageSlug(task.stage.name, stageIndex) },- });-};--watch(- () => props.issueList,- (list) => {- const oldIssueIdList = Array.from(state.selectedIssueIdList.values());- const newIssueIdList = new Set(list.map((issue) => issue.id));- oldIssueIdList.forEach((id) => {- // If a selected issue id doesn't appear in the new IssueList- // we should cancel its selection state.- if (!newIssueIdList.has(id)) {- state.selectedIssueIdList.delete(id);- }- });- }-);-</script>diff --git a/frontend/src/components/Issue/table/PagedIssueTable.vue b/frontend/src/components/Issue/table/PagedIssueTable.vuedeleted file mode 100644index 534e8ca918..0000000000--- a/frontend/src/components/Issue/table/PagedIssueTable.vue+++ /dev/null@@ -1,189 +0,0 @@-<template>- <slot name="table" :issue-list="state.issueList" :loading="state.loading" />-- <div- v-if="state.loading"- class="flex items-center justify-center py-2 text-gray-400 text-sm"- >- <BBSpin />- </div>-- <slot- v-if="!state.loading"- name="more"- :has-more="state.hasMore"- :fetch-next-page="fetchNextPage"- >- <div- v-if="!hideLoadMore && pageSize > 0 && state.hasMore"- class="flex items-center justify-center py-2 text-gray-400 text-sm hover:bg-gray-200 cursor-pointer"- @click="fetchNextPage"- >- {{ $t("common.load-more") }}- </div>- </slot>-</template>--<script lang="ts" setup>-import { useSessionStorage } from "@vueuse/core";-import { computed, PropType, reactive, watch } from "vue";-import {- buildQueryListByIssueFind,- useIsLoggedIn,- useIssueStore,- useRefreshIssueList,-} from "@/store";-import { Issue, IssueFind } from "@/types";--type LocalState = {- loading: boolean;- issueList: Issue[];- paginationToken: string;- hasMore: boolean;-};--/**- * It's complex and dangerous to cache the issue list.- * So we just memorize how many times the user clicks the "load more" button.- * And load the first N pages in the first fetch.- * E.g., the user clicked "load more" 4 times, then the first time will set limit- * to `pageSize * 5`.- */-type SessionState = {- // How many times the user clicks the "load more" button.- page: number;- // Help us to check if the session is outdated.- updatedTs: number;-};--const MAX_PAGE_SIZE = 1000;-const SESSION_LIFE = 1 * 60 * 1000; // 1 minute--const props = defineProps({- // A unique key to identify the session state.- sessionKey: {- type: String,- required: true,- },- issueFind: {- type: Object as PropType<IssueFind>,- default: undefined,- },- pageSize: {- type: Number,- default: 10,- },- hideLoadMore: {- type: Boolean,- default: false,- },-});--const state = reactive<LocalState>({- loading: false,- issueList: [],- paginationToken: "",- hasMore: true,-});--const sessionState = useSessionStorage<SessionState>(- `bb.page-issue-table.${props.sessionKey}`,- {- page: 1,- updatedTs: 0,- }-);--const issueStore = useIssueStore();-const isLoggedIn = useIsLoggedIn();--const limit = computed(() => {- if (props.pageSize <= 0) return MAX_PAGE_SIZE;- return props.pageSize;-});--const condition = computed(() => {- const issueFind = {- ...props.issueFind,- limit: limit.value,- };- return buildQueryListByIssueFind(issueFind).join("&");-});--const fetchData = (refresh = false) => {- if (!isLoggedIn.value) {- return;- }-- state.loading = true;-- const isFirstFetch = state.paginationToken === "";- const expectedRowCount = isFirstFetch- ? // Load one or more page for the first fetch to restore the session- limit.value * sessionState.value.page- : // Always load one page if NOT the first fetch- limit.value;-- issueStore- .fetchPagedIssueList({- ...props.issueFind,- limit: expectedRowCount,- token: state.paginationToken,- })- .then(({ nextToken, issueList }) => {- if (refresh) {- state.issueList = issueList;- } else {- state.issueList.push(...issueList);- }-- if (issueList.length < expectedRowCount) {- state.hasMore = false;- } else if (!isFirstFetch) {- // If we didn't reach the end, memorize we've clicked the "load more" button.- sessionState.value.page++;- }-- sessionState.value.updatedTs = Date.now();- state.paginationToken = nextToken;- })- .finally(() => {- state.loading = false;- });-};--const resetSession = () => {- sessionState.value = {- page: 1,- updatedTs: 0,- };-};--const refresh = () => {- state.paginationToken = "";- state.hasMore = true;- resetSession();- fetchData(true);-};--const fetchNextPage = () => {- fetchData(false);-};--if (Date.now() - sessionState.value.updatedTs > SESSION_LIFE) {- // Reset session if it's outdated.- resetSession();-}-fetchData(true);-watch(condition, refresh);-watch(isLoggedIn, () => {- // Reset session when logged out.- if (!isLoggedIn.value) {- resetSession();- }-});--useRefreshIssueList(() => {- refresh();-});-</script>diff --git a/frontend/src/components/Issue/table/WaitingForMyApprovalIssueTable.vue b/frontend/src/components/Issue/table/WaitingForMyApprovalIssueTable.vuedeleted file mode 100644index c645d4baeb..0000000000--- a/frontend/src/components/Issue/table/WaitingForMyApprovalIssueTable.vue+++ /dev/null@@ -1,44 +0,0 @@-<template>- <PagedIssueTable :page-size="20">- <template #table="{ issueList, loading }">- <slot name="table" :issue-list="filter(issueList)" :loading="loading" />- </template>- </PagedIssueTable>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import {- extractIssueReviewContext,- useWrappedReviewSteps,-} from "@/plugins/issue/logic";-import { useAuthStore } from "@/store";-import type { Issue as LegacyIssue } from "@/types";-import { Issue } from "@/types/proto/v1/issue_service";--const currentUserName = computed(() => useAuthStore().currentUser.name);--const filter = (issueList: LegacyIssue[]) => {- return issueList.filter((legacyIssue) => {- const issue = computed(() => {- try {- return Issue.fromJSON(legacyIssue.payload.approval);- } catch {- return Issue.fromJSON({});- }- });- const context = extractIssueReviewContext(- computed(() => legacyIssue),- issue- );- const steps = useWrappedReviewSteps(legacyIssue, context);- const currentStep = steps.value?.find((step) => step.status === "CURRENT");- if (!currentStep) return false;- return (- currentStep.candidates.findIndex(- (user) => user.name === currentUserName.value- ) >= 0- );- });-};-</script>diff --git a/frontend/src/components/Issue/table/index.ts b/frontend/src/components/Issue/table/index.tsdeleted file mode 100644index 3caadfd615..0000000000--- a/frontend/src/components/Issue/table/index.ts+++ /dev/null@@ -1,5 +0,0 @@-import IssueTable from "./IssueTable.vue";-import PagedIssueTable from "./PagedIssueTable.vue";-import WaitingForMyApprovalIssueTable from "./WaitingForMyApprovalIssueTable.vue";--export { IssueTable, PagedIssueTable, WaitingForMyApprovalIssueTable };diff --git a/frontend/src/components/IssueV1/components/CurrentApproverV1.vue b/frontend/src/components/IssueV1/components/CurrentApproverV1.vueindex 8e38e788b1..53d38d04e2 100644--- a/frontend/src/components/IssueV1/components/CurrentApproverV1.vue+++ b/frontend/src/components/IssueV1/components/CurrentApproverV1.vue@@ -27,10 +27,7 @@ const props = defineProps<{issue: ComposedIssue;}>();-const context = extractIssueReviewContext(- computed(() => undefined),- computed(() => props.issue)-);+const context = extractIssueReviewContext(computed(() => props.issue));const { ready, done } = context;const currentUserName = computed(() => useAuthStore().currentUser.name);diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vueindex fb2b11b19c..5a62cb6c2f 100644--- a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vue+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vue@@ -38,12 +38,6 @@ const syncNow = async () => {syncing.value = true;try {- // await useIssueV1Store().fetchIssueByLegacyIssue(- // issue.value,- // true /* force */- // );- // TODO-synced.value = true;// Show 'synced' status for several seconds to avoid user clicking sync// button too frequently.diff --git a/frontend/src/components/IssueV1/components/Panel/TaskRolloutActionPanel.vue b/frontend/src/components/IssueV1/components/Panel/TaskRolloutActionPanel.vueindex 635c19c025..e6799a9087 100644--- a/frontend/src/components/IssueV1/components/Panel/TaskRolloutActionPanel.vue+++ b/frontend/src/components/IssueV1/components/Panel/TaskRolloutActionPanel.vue@@ -265,21 +265,6 @@ const handleConfirm = async (state.loading = false;emit("close");}-- // Trying to avoid some kind of concurrency and race condition, we fetch the- // latest snapshot of issue from the server-side and check whether this- // transition is applicable again.- // const latestIssue = await useIssueStore().fetchIssueById(issue.value.id);-- // const { action: transition } = props;- // const applicableList = getApplicableIssueStatusTransitionList(latestIssue);- // if (!isApplicableTransition(transition, applicableList)) {- // return cleanup();- // }-- // changeIssueStatus(transition.to, comment);- // isTransiting.value = false;- // emit("updated");};const resetState = () => {diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vueindex f33ec592f1..e3a13810d4 100644--- a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vue+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vue@@ -112,7 +112,7 @@ const allowPreviewRollback = computed(() => {});const taskRollbackBy = computed((): TaskRollbackBy | undefined => {- const activityList = useActivityV1Store().getActivityListByIssue(+ const activityList = useActivityV1Store().getActivityListByIssueV1(issue.value.uid);// Find the latest comment activity with TaskRollbackBy struct if possible.diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vueindex 86532559ca..db44f7c004 100644--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue@@ -173,7 +173,6 @@ import {specForTask,createEmptyLocalSheet,notifyNotEditableLegacyIssue,- patchLegacyIssueTasksStatement,isDeploymentConfigChangeTaskV1,} from "@/components/IssueV1/logic";import MonacoEditor from "@/components/MonacoEditor";@@ -590,18 +589,7 @@ const updateStatement = async (statement: string) => {const planPatch = cloneDeep(issue.value.planEntity);if (!planPatch) {- // notifyNotEditableLegacyIssue();- try {- await patchLegacyIssueTasksStatement(issue.value, tasks, statement);- events.emit("status-changed", { eager: true });- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } finally {- // nothing- }+ notifyNotEditableLegacyIssue();return;}diff --git a/frontend/src/components/IssueV1/logic/index.ts b/frontend/src/components/IssueV1/logic/index.tsindex cb263a090d..bf024b59b5 100644--- a/frontend/src/components/IssueV1/logic/index.ts+++ b/frontend/src/components/IssueV1/logic/index.ts@@ -13,4 +13,3 @@ export * from "./plan-check";export * from "./task-run";export * from "./poll";export * from "./subscriber";-export * from "./legacy-issue-compatibility";diff --git a/frontend/src/components/IssueV1/logic/legacy-issue-compatibility.ts b/frontend/src/components/IssueV1/logic/legacy-issue-compatibility.tsdeleted file mode 100644index 91fe393dc0..0000000000--- a/frontend/src/components/IssueV1/logic/legacy-issue-compatibility.ts+++ /dev/null@@ -1,37 +0,0 @@-import { useIssueStore, useSheetV1Store, useTaskStore } from "@/store";-import { ComposedIssue, TaskPatch } from "@/types";-import { Task } from "@/types/proto/v1/rollout_service";-import { extractSheetUID, setSheetStatement } from "@/utils";-import { createEmptyLocalSheet } from "./sheet";--export const patchLegacyIssueTasksStatement = async (- issue: ComposedIssue,- tasks: Task[],- statement: string-) => {- const sheetCreate = {- ...createEmptyLocalSheet(),- title: issue.title,- };- setSheetStatement(sheetCreate, statement);- const createdSheet = await useSheetV1Store().createSheet(- issue.project,- sheetCreate- );-- const legacyIssue = await useIssueStore().getOrFetchIssueById(- Number(issue.uid)- );- for (let i = 0; i < tasks.length; i++) {- const task = tasks[i];- const taskPatch: TaskPatch = {- sheetId: Number(extractSheetUID(createdSheet.name)),- };- await useTaskStore().patchTask({- issueId: legacyIssue.id,- pipelineId: legacyIssue.pipeline!.id,- taskId: Number(task.uid),- taskPatch,- });- }-};diff --git a/frontend/src/components/IssueV1/logic/transition.ts b/frontend/src/components/IssueV1/logic/transition.tsindex efcb182a83..9ec7564bde 100644--- a/frontend/src/components/IssueV1/logic/transition.ts+++ b/frontend/src/components/IssueV1/logic/transition.ts@@ -133,9 +133,6 @@ const allowUserToApplyIssueStatusTransition = (};function isIssueReviewDone(issue: ComposedIssue) {- const context = extractIssueReviewContext(- computed(() => undefined),- computed(() => issue)- );+ const context = extractIssueReviewContext(computed(() => issue));return context.done.value;}diff --git a/frontend/src/plugins/issue/logic/common.ts b/frontend/src/plugins/issue/logic/common.tsdeleted file mode 100644index a7fcef390c..0000000000--- a/frontend/src/plugins/issue/logic/common.ts+++ /dev/null@@ -1,63 +0,0 @@-import { Ref } from "vue";-import { useRoute } from "vue-router";-import { IssueTemplate } from "@/plugins";-import { useDatabaseV1Store, useProjectV1Store } from "@/store";-import { ComposedDatabase, unknownProject, UNKNOWN_ID } from "@/types";-import { Project } from "@/types/proto/v1/project_service";--// validateOnly: true doesn't support empty SQL-// so we use a fake sql to validate and then set it back to empty if needed-export const VALIDATE_ONLY_SQL = "/* YOUR_SQL_HERE */";--export const ESTABLISH_BASELINE_SQL =- "/* Establish baseline using current schema */";--export type BuildNewIssueContext = {- template: Ref<IssueTemplate>;- route: ReturnType<typeof useRoute>;-};--export const findProject = async (- context: BuildNewIssueContext-): Promise<Project> => {- const { route } = context;-- const projectId = route.query.project- ? (route.query.project as string)- : String(UNKNOWN_ID);- let project = unknownProject();-- if (projectId !== String(UNKNOWN_ID)) {- const projectStore = useProjectV1Store();- project = await projectStore.getOrFetchProjectByUID(projectId);- }-- return project;-};--export const findDatabaseListByQuery = (- context: BuildNewIssueContext-): ComposedDatabase[] => {- // route.query.databaseList is comma-splitted databaseId list- // e.g. databaseList=7002,7006,7014- const { route } = context;- const idList = route.query.databaseList as string;- if (!idList) {- return [];- }-- const databaseList: ComposedDatabase[] = [];- const databaseIdList = idList.split(",");- const databaseStore = useDatabaseV1Store();- for (const databaseId of databaseIdList) {- databaseList.push(databaseStore.getDatabaseByUID(databaseId));- }- return databaseList;-};--export const findDatabaseGroupNameByQuery = (- context: BuildNewIssueContext-): string | undefined => {- const { route } = context;- return (route.query.databaseGroupName as string) || undefined;-};diff --git a/frontend/src/plugins/issue/logic/index.ts b/frontend/src/plugins/issue/logic/index.tsindex 1e924110f3..0dd206ddcd 100644--- a/frontend/src/plugins/issue/logic/index.ts+++ b/frontend/src/plugins/issue/logic/index.ts@@ -1,3 +1 @@-export * from "./initialize";-export * from "./poll";export * from "./review";diff --git a/frontend/src/plugins/issue/logic/initialize/assignee.ts b/frontend/src/plugins/issue/logic/initialize/assignee.tsdeleted file mode 100644index 1f991b0d6e..0000000000--- a/frontend/src/plugins/issue/logic/initialize/assignee.ts+++ /dev/null@@ -1,101 +0,0 @@-import { extractRollOutPolicyValue } from "@/components/Issue/logic";-import { useInstanceV1Store, useProjectV1Store, useUserStore } from "@/store";-import { usePolicyV1Store } from "@/store/modules/v1/policy";-import { IssueCreate, PresetRoleType } from "@/types";-import { UserRole } from "@/types/proto/v1/auth_service";-import {- PolicyType,- ApprovalStrategy,- ApprovalGroup,-} from "@/types/proto/v1/org_policy_service";-import {- extractUserUID,- hasWorkspacePermissionV1,- memberListInProjectV1,-} from "@/utils";--export const tryGetDefaultAssignee = async (issueCreate: IssueCreate) => {- const firstTask = issueCreate.pipeline?.stageList[0]?.taskList[0];- // The pipeline is accidentally empty, so we won't go further- if (!firstTask) return;-- const instance = await useInstanceV1Store().getOrFetchInstanceByUID(- String(firstTask.instanceId)- );-- const policy = await usePolicyV1Store().getOrFetchPolicyByParentAndType({- parentPath: instance.environment,- policyType: PolicyType.DEPLOYMENT_APPROVAL,- });-- const rollOutPolicy = extractRollOutPolicyValue(policy, issueCreate.type);-- if (rollOutPolicy.policy === ApprovalStrategy.AUTOMATIC) {- // We don't need to approve manually.- // But we still set the workspace owner or DBA as the default assignee.- // Just to notify the project owner.- assignToWorkspaceOwnerOrDBA(issueCreate);- return;- }- if (rollOutPolicy.policy === ApprovalStrategy.MANUAL) {- const { assigneeGroup } = rollOutPolicy;-- if (assigneeGroup === ApprovalGroup.APPROVAL_GROUP_PROJECT_OWNER) {- // Assign to the project owner if needed.- assignToProjectOwner(issueCreate);- return;- }-- // If we don't find an assignee group for this issue type- // or its value is WORKSPACE_OWNER_OR_DBA.- assignToWorkspaceOwnerOrDBA(issueCreate);- return;- }-};--// Since we are assigning a project owner, we try to find a more dedicated project owner wearing a-// developer hat to offload DBA workload, thus the searching order is:-// 1. Project owner who is a workspace Developer.-// 2. Project owner who is not a workspace Developer.-const assignToProjectOwner = (issueCreate: IssueCreate) => {- const project = useProjectV1Store().getProjectByUID(- String(issueCreate.projectId)- );- const memberList = memberListInProjectV1(project, project.iamPolicy);- const projectOwnerList = memberList.filter((member) => {- return member.roleList.includes(PresetRoleType.OWNER);- });-- const workspaceMemberList = useUserStore().userList;-- for (const member of projectOwnerList) {- for (const wm of workspaceMemberList) {- if (wm.name === member.user.name && wm.userRole === UserRole.DEVELOPER) {- issueCreate.assigneeId = parseInt(extractUserUID(wm.name), 10);- return;- }- }- }-- for (const member of projectOwnerList) {- for (const wm of workspaceMemberList) {- if (wm.name == member.user.name) {- issueCreate.assigneeId = parseInt(extractUserUID(wm.name), 10);- return;- }- }- }-};-const assignToWorkspaceOwnerOrDBA = (issueCreate: IssueCreate) => {- const memberList = useUserStore().userList;- // Find the workspace owner or DBA, the first one we found is okay.- const ownerOrDBA = memberList.find((user) => {- return hasWorkspacePermissionV1(- "bb.permission.workspace.manage-issue",- user.userRole- );- });- if (ownerOrDBA) {- issueCreate.assigneeId = parseInt(extractUserUID(ownerOrDBA.name), 10);- }-};diff --git a/frontend/src/plugins/issue/logic/initialize/ghost.ts b/frontend/src/plugins/issue/logic/initialize/ghost.tsdeleted file mode 100644index 11a0c11369..0000000000--- a/frontend/src/plugins/issue/logic/initialize/ghost.ts+++ /dev/null@@ -1,64 +0,0 @@-import { IssueCreate, IssueType, MigrationContext, UNKNOWN_ID } from "@/types";-import {- findDatabaseListByQuery,- BuildNewIssueContext,- VALIDATE_ONLY_SQL,-} from "../common";-import { IssueCreateHelper } from "./helper";--export const maybeBuildGhostIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate | undefined> => {- const { route } = context;-- if (parseInt(route.query.ghost as string, 10) !== 1) {- return undefined;- }- const issueType = route.query.template as IssueType;- if (issueType !== "bb.issue.database.schema.update") {- // Only available for schema updates.- return undefined;- }- return buildNewGhostIssue(context);-};--const buildNewGhostIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate> => {- const helper = new IssueCreateHelper(context);- await helper.prepare();-- helper.issueCreate!.type = "bb.issue.database.schema.update.ghost";-- const databaseList = findDatabaseListByQuery(context);- const createContext: MigrationContext = {- detailList: [],- };- if (databaseList.length > 0) {- // For multi-selection pipeline, pass databaseId accordingly.- createContext.detailList = databaseList.map((db) => {- return {- migrationType: "MIGRATE",- databaseId: Number(db.uid),- statement: VALIDATE_ONLY_SQL,- earliestAllowedTs: 0,- sheetId: UNKNOWN_ID,- };- });- } else {- // For tenant deployment config pipeline, omit databaseId- createContext.detailList = [- {- migrationType: "MIGRATE",- statement: VALIDATE_ONLY_SQL,- earliestAllowedTs: 0,- sheetId: UNKNOWN_ID,- },- ];- }- helper.issueCreate!.createContext = createContext;-- await helper.validate();-- return helper.generate();-};diff --git a/frontend/src/plugins/issue/logic/initialize/grantRequest.ts b/frontend/src/plugins/issue/logic/initialize/grantRequest.tsdeleted file mode 100644index 5e6ad63d65..0000000000--- a/frontend/src/plugins/issue/logic/initialize/grantRequest.ts+++ /dev/null@@ -1,59 +0,0 @@-import { head } from "lodash-es";-import {- GrantRequestContext,- IssueCreate,- IssueType,- PresetRoleType,-} from "@/types";-import { extractRoleResourceName } from "@/utils";-import { BuildNewIssueContext, findDatabaseListByQuery } from "../common";-import { IssueCreateHelper } from "./helper";--export const maybeBuildGrantRequestIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate | undefined> => {- const { route } = context;- const issueType = route.query.template as IssueType;- const role = route.query.role;- if (issueType !== "bb.issue.grant.request") {- return undefined;- }- // We only allow to create grant request issue for exporter and querier roles.- const exporterRole = extractRoleResourceName(PresetRoleType.EXPORTER);- const querierRole = extractRoleResourceName(PresetRoleType.QUERIER);- if (role !== exporterRole && role !== querierRole) {- return undefined;- }-- return buildNewGrantRequestIssue(context);-};--const buildNewGrantRequestIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate> => {- const { route } = context;- const helper = new IssueCreateHelper(context);- await helper.prepare();- const issueCreate = await helper.generate();- const role = route.query.role as string;- (issueCreate.createContext as GrantRequestContext).role = role as any;- const project = route.query.project as string;- if (project) {- issueCreate.projectId = Number(project);- }- if (role === "EXPORTER") {- const createContext = issueCreate.createContext as GrantRequestContext;- const statement = (route.query.sql as string) || "";- createContext.statement = statement;- const databaseList = findDatabaseListByQuery(context);- const database = head(databaseList);- if (database) {- createContext.databaseResources = [- {- databaseName: database.name,- },- ];- }- }- return issueCreate;-};diff --git a/frontend/src/plugins/issue/logic/initialize/helper.ts b/frontend/src/plugins/issue/logic/initialize/helper.tsdeleted file mode 100644index 0146ecdf28..0000000000--- a/frontend/src/plugins/issue/logic/initialize/helper.ts+++ /dev/null@@ -1,161 +0,0 @@-import { Ref } from "vue";-import { TemplateType } from "@/plugins";-import { useActuatorV1Store, useCurrentUser, useIssueStore } from "@/store";-import {- Issue,- IssueCreate,- Principal,- SYSTEM_BOT_ID,- Task,- TaskDatabaseSchemaUpdatePayload,- UNKNOWN_ID,-} from "@/types";-import { isDatabaseRelatedIssueType } from "@/utils";-import {- BuildNewIssueContext,- ESTABLISH_BASELINE_SQL,- VALIDATE_ONLY_SQL,-} from "../common";--export class IssueCreateHelper {- issueCreate: IssueCreate | null;- issue: Issue | null;- context: BuildNewIssueContext;- issueStore: ReturnType<typeof useIssueStore>;- currentUser: Ref<Principal>;-- constructor(context: BuildNewIssueContext) {- this.issueCreate = null;- this.issue = null;- this.context = context;- this.issueStore = useIssueStore();- this.currentUser = useCurrentUser();- }-- async prepare(): Promise<IssueCreate> {- const { context, currentUser } = this;- const { route } = context;- const actuatorStore = useActuatorV1Store();-- const baseTemplate = context.template.value.buildIssue({- environmentList: [],- approvalPolicyList: [],- databaseList: [],- currentUser: currentUser.value,- });-- const templateType = route.query.template as TemplateType;-- const issueCreate: IssueCreate = {- projectId: parseInt(route.query.project as string) || UNKNOWN_ID,- name: (route.query.name as string) || baseTemplate.name,- type:- templateType === "bb.issue.database.schema.baseline"- ? "bb.issue.database.schema.update" // use schema.update to establish baseline- : templateType,- description: baseTemplate.description,- // validateOnly does not support assigneeId=-1- // so we need to specify here- // but will reset this to -1 if route.query.assignee is empty- assigneeId: SYSTEM_BOT_ID,- createContext: {},- payload: {},- };-- // For demo mode, we assign the issue to the current user, so it can also experience the assignee user flow.- if (actuatorStore.isDemo) {- issueCreate.assigneeId = currentUser.value.id;- }- if (route.query.name) {- issueCreate.name = route.query.name as string;- }- if (route.query.description) {- issueCreate.description = route.query.description as string;- }- if (route.query.assignee) {- issueCreate.assigneeId = parseInt(route.query.assignee as string);- }-- this.issueCreate = issueCreate;-- return issueCreate;- }-- async validate(): Promise<[IssueCreate, Issue]> {- const { issueStore } = this;- const issue = await issueStore.validateIssue(this.issueCreate!);-- this.issue = issue;-- return [this.issueCreate!, this.issue];- }-- async generate(): Promise<IssueCreate> {- const { route, template } = this.context;- const issueCreate = this.issueCreate!;- const issue = this.issue!;-- if (!route.query.assignee) {- issueCreate.assigneeId =- parseInt(route.query.assignee as string) || UNKNOWN_ID;- }-- // Only generate pipeline for database related issues.- if (isDatabaseRelatedIssueType(issueCreate.type)) {- // copy the generated pipeline to issueCreate- // issueCreate is an editable object for the whole issue UI- issueCreate.pipeline = {- name: issue.pipeline.name,- stageList: issue.pipeline.stageList.map((stage) => ({- name: stage.name,- environmentId: stage.environment.id,- taskList: stage.taskList.map((task) => {- const statement = defaultStatementOfTask(task);- return {- name: task.name,- status: task.status,- type: task.type,- instanceId: task.instance.id,- databaseId: task.database?.id,- databaseName: task.database?.name,- statement,- sheetId: UNKNOWN_ID,- earliestAllowedTs: task.earliestAllowedTs,- payload: task.payload,- };- }),- })),- };- }-- // cleanup input fields, not used yet.- for (const field of template.value.inputFieldList) {- const value = route.query[field.slug] as string;- if (value) {- if (field.type == "Boolean") {- // false if "0" or "false", true otherwise- const bool = value !== "0" && value.toLowerCase() !== "false";- issueCreate.payload[field.id] = bool;- } else {- issueCreate.payload[field.id] = value;- }- }- }-- return issueCreate;- }-}--const defaultStatementOfTask = (task: Task) => {- if (task.type === "bb.task.database.schema.baseline") {- return ESTABLISH_BASELINE_SQL;- }- if (task.statement && task.statement !== VALIDATE_ONLY_SQL) {- return task.statement;- }-- // if we are using VALIDATE_ONLY_SQL, set it back to empty- // otherwise keep it as-is- const payload = task.payload as TaskDatabaseSchemaUpdatePayload;- return payload.statement === VALIDATE_ONLY_SQL ? "" : payload.statement;-};diff --git a/frontend/src/plugins/issue/logic/initialize/index.ts b/frontend/src/plugins/issue/logic/initialize/index.tsdeleted file mode 100644index 06329c946b..0000000000--- a/frontend/src/plugins/issue/logic/initialize/index.ts+++ /dev/null@@ -1,144 +0,0 @@-import { computed, ref, Ref, watch } from "vue";-import { type LocationQuery, useRoute, useRouter } from "vue-router";-import { defaultTemplate, templateForType } from "@/plugins";-import {- pushNotification,- useDatabaseV1Store,- useIssueStore,- useProjectV1Store,-} from "@/store";-import { EMPTY_ID, Issue, IssueCreate, IssueType } from "@/types";-import { SYSTEM_BOT_ID, UNKNOWN_ID } from "@/types";-import { idFromSlug } from "@/utils";-import { BuildNewIssueContext } from "../common";-import { tryGetDefaultAssignee } from "./assignee";-import { maybeBuildGhostIssue } from "./ghost";-import { maybeBuildGrantRequestIssue } from "./grantRequest";-import { buildNewStandardIssue } from "./standard";-import { maybeBuildTenantDeployIssue } from "./tenant";--export function useInitializeIssue(issueSlug: Ref<string>) {- const issueStore = useIssueStore();- const create = computed(() => issueSlug.value.toLowerCase() == "new");- const route = useRoute();- const router = useRouter();-- const issueCreate = ref<IssueCreate | undefined>();- const issue = computed((): Issue | IssueCreate | undefined => {- if (create.value) {- return issueCreate.value;- } else {- const id = idFromSlug(issueSlug.value);- const issueEntity = issueStore.getIssueById(id);- if (issueEntity.id === EMPTY_ID || issueEntity.id === UNKNOWN_ID) {- return undefined;- }- return issueEntity;- }- });-- const template = computed(() => {- // Find proper IssueTemplate from route.query.template- const issueType = route.query.template as IssueType;- if (issueType) {- const tpl = templateForType(issueType);- if (tpl) {- return tpl;- }- pushNotification({- module: "bytebase",- style: "WARN",- title: `Unknown template '${issueType}'.`,- description: "Fallback to the default template",- });- }-- // fallback- return defaultTemplate();- });-- watch(- [issueSlug, create],- async ([issueSlug, create]) => {- try {- if (create) {- issueCreate.value = undefined;-- await prepareDatabaseListForIssueCreation(route.query);-- issueCreate.value = await buildNewIssue({ template, route });- if (- issueCreate.value.assigneeId === UNKNOWN_ID ||- issueCreate.value.assigneeId === SYSTEM_BOT_ID- ) {- // Try to find a default assignee of the first task automatically.- await tryGetDefaultAssignee(issueCreate.value);- }- } else {- const id = idFromSlug(issueSlug);- await issueStore.fetchIssueById(id);- }- } catch (error) {- router.push({ name: "error.404" });- throw error;- }- },- { immediate: true }- );-- return { create, issue };-}--const buildNewIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate> => {- const grantRequest = await maybeBuildGrantRequestIssue(context);- if (grantRequest) {- return grantRequest;- }-- const ghost = await maybeBuildGhostIssue(context);- if (ghost) {- return ghost;- }-- const tenant = await maybeBuildTenantDeployIssue(context);- if (tenant) {- return tenant;- }-- return buildNewStandardIssue(context);-};--const prepareDatabaseListForIssueCreation = async (query: LocationQuery) => {- const databaseStore = useDatabaseV1Store();- // For preparing the database if user visits creating issue url directly.- // It's horrible to fetchDatabaseByUID one-by-one when query.databaseList- // is big (100+ sometimes)- // So we are fetching databaseList by project since that's better cached.- if (query.project) {- // If we found query.project, we can directly search database list by project- const projectId = query.project as string;- const project = await useProjectV1Store().getOrFetchProjectByUID(projectId);- await databaseStore.searchDatabaseList({- parent: `instances/-`,- filter: `project == "${project.name}"`,- });- } else if (query.databaseList) {- // Otherwise, we don't have the projectId (very rare to see, theoretically)- // so we need to fetch the first database in databaseList by id,- // and see what project it belongs.- const databaseIdList = (query.databaseList as string).split(",");- if (databaseIdList.length > 0) {- const firstDB = await databaseStore.getDatabaseByUID(databaseIdList[0]);- if (databaseIdList.length > 1) {- // If we have more than one databases in the list- // fetch the rest of databases by projectId- await databaseStore.searchDatabaseList({- parent: `instances/-`,- filter: `project == "${firstDB.project}"`,- });- }- }- }-};diff --git a/frontend/src/plugins/issue/logic/initialize/standard.ts b/frontend/src/plugins/issue/logic/initialize/standard.tsdeleted file mode 100644index b515806c14..0000000000--- a/frontend/src/plugins/issue/logic/initialize/standard.ts+++ /dev/null@@ -1,112 +0,0 @@-import { TemplateType } from "@/plugins";-import {- DatabaseId,- IssueCreate,- MigrationContext,- MigrationDetail,- MigrationType,- RollbackDetail,- UNKNOWN_ID,-} from "@/types";-import {- findDatabaseListByQuery,- BuildNewIssueContext,- ESTABLISH_BASELINE_SQL,- VALIDATE_ONLY_SQL,-} from "../common";-import { IssueCreateHelper } from "./helper";--export const buildNewStandardIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate> => {- const helper = new IssueCreateHelper(context);-- await helper.prepare();-- // standard single-stage or multi-stage issue is generated by specifying- // databaseId for each stage- const databaseList = findDatabaseListByQuery(context);- const templateType = context.route.query.template as TemplateType;- let migrationType: MigrationType = "MIGRATE";- if (templateType === "bb.issue.database.data.update") {- migrationType = "DATA";- }- if (templateType === "bb.issue.database.schema.baseline") {- migrationType = "BASELINE";- }- const statement =- migrationType === "BASELINE" ? ESTABLISH_BASELINE_SQL : VALIDATE_ONLY_SQL;- const createContext: MigrationContext = {- detailList: databaseList.map((db, index) => {- const detail: MigrationDetail = {- migrationType: migrationType,- databaseId: Number(db.uid),- statement,- sheetId: UNKNOWN_ID,- earliestAllowedTs: 0,- };- return detail;- }),- };- maybeApplyRollbackParams(createContext, context.route);-- helper.issueCreate!.createContext = createContext;- await helper.validate();-- // clean up createContext for standard issues- helper.issueCreate!.createContext = {};-- return helper.generate();-};--// Try to find out the relationship between databaseId and rollback issue/task-// Id from the URL query.-export const getRollbackTaskMappingFromQuery = (- route: BuildNewIssueContext["route"]-) => {- const mapping = new Map<DatabaseId, RollbackDetail>();-- const { query } = route;- const databaseIdListInQuery = (query.databaseList as string) || "";- const databaseIdList = databaseIdListInQuery- .split(",")- .map<DatabaseId>((maybeId) => parseInt(maybeId, 10));-- const rollbackIssueIdInQuery = (query.rollbackIssueId as string) || "";- const issueId = parseInt(rollbackIssueIdInQuery, 10) || UNKNOWN_ID;- if (issueId === UNKNOWN_ID) {- return mapping;- }-- const rollbackTaskIdListInQuery = (query.rollbackTaskIdList as string) || "";- const taskIdList = rollbackTaskIdListInQuery- .split(",")- .map((maybeId) => parseInt(maybeId, 10) || UNKNOWN_ID);-- databaseIdList.forEach((databaseId, index) => {- const taskId = taskIdList[index] || UNKNOWN_ID;- if (taskId !== UNKNOWN_ID) {- mapping.set(databaseId, {- issueId,- taskId,- });- }- });- return mapping;-};--export const maybeApplyRollbackParams = (- migrationContext: MigrationContext,- route: BuildNewIssueContext["route"]-) => {- const mapping = getRollbackTaskMappingFromQuery(route);- migrationContext.detailList.forEach((detail) => {- const { databaseId } = detail;- if (!databaseId || databaseId === UNKNOWN_ID) return;-- const rollbackDetail = mapping.get(databaseId);- if (!rollbackDetail) return;-- detail.rollbackDetail = rollbackDetail;- });-};diff --git a/frontend/src/plugins/issue/logic/initialize/tenant.ts b/frontend/src/plugins/issue/logic/initialize/tenant.tsdeleted file mode 100644index 73f67def34..0000000000--- a/frontend/src/plugins/issue/logic/initialize/tenant.ts+++ /dev/null@@ -1,104 +0,0 @@-import { TemplateType } from "@/plugins";-import {- IssueCreate,- IssueType,- MigrationType,- MigrationContext,-} from "@/types";-import { TenantMode } from "@/types/proto/v1/project_service";-import {- findProject,- BuildNewIssueContext,- VALIDATE_ONLY_SQL,- findDatabaseListByQuery,- findDatabaseGroupNameByQuery,-} from "../common";-import { IssueCreateHelper } from "./helper";--export const maybeBuildTenantDeployIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate | undefined> => {- const { route } = context;- if (route.query.mode !== "tenant") {- return undefined;- }-- const project = await findProject(context);- const issueType = route.query.template as IssueType;- const isMigrate =- issueType === "bb.issue.database.schema.update" ||- issueType === "bb.issue.database.data.update";- if (project.tenantMode === TenantMode.TENANT_MODE_ENABLED && isMigrate) {- // Only to build tenant issue when:- // 1. Project is tenant mode.- // 2. Is schema update or data update (no to establish baseline).- return buildNewTenantSchemaUpdateIssue(context);- }- return undefined;-};--const buildNewTenantSchemaUpdateIssue = async (- context: BuildNewIssueContext-): Promise<IssueCreate> => {- const { route } = context;- const helper = new IssueCreateHelper(context);-- await helper.prepare();- // tenant issue is generated by specifying databaseName- const templateType = route.query.template as TemplateType;- let migrationType: MigrationType = "MIGRATE";- if (templateType === "bb.issue.database.data.update") {- migrationType = "DATA";- }-- const databaseGroupName = findDatabaseGroupNameByQuery(context);- const databaseList = findDatabaseListByQuery(context);- if (databaseGroupName) {- const sql = route.query.sql as string;- helper.issueCreate!.createContext = {- detailList: [- {- migrationType: migrationType,- databaseGroupName: databaseGroupName,- statement: sql || VALIDATE_ONLY_SQL,- earliestAllowedTs: 0,- },- ],- };- } else if (databaseList.length > 0) {- // For multi-selection pipeline, pass databaseId accordingly.- helper.issueCreate!.createContext = {- detailList: databaseList.map((db) => {- return {- migrationType: migrationType,- databaseId: Number(db.uid),- statement: VALIDATE_ONLY_SQL,- earliestAllowedTs: 0,- };- }),- };- } else {- // For tenant deployment config pipeline, omit databaseId- helper.issueCreate!.createContext = {- detailList: [- {- migrationType: migrationType,- statement: VALIDATE_ONLY_SQL,- earliestAllowedTs: 0,- },- ],- };- }- await helper.validate();-- // we are setting SQL statement to "" because showing /* YOUR_SQL_HERE */- // is not that friendly to users- // setting it to empty can provide a placeholder to user, along with an- // exclamation mark indicating "No SQL statement"- const createContext = helper.issueCreate!.createContext as MigrationContext;- for (const detail of createContext.detailList) {- detail.statement = "";- }-- return helper.generate();-};diff --git a/frontend/src/plugins/issue/logic/poll/index.ts b/frontend/src/plugins/issue/logic/poll/index.tsdeleted file mode 100644index cab9b95a42..0000000000--- a/frontend/src/plugins/issue/logic/poll/index.ts+++ /dev/null@@ -1,92 +0,0 @@-import { computed, onUnmounted, reactive, Ref, watch } from "vue";-import { useIssueStore } from "@/store";-import {- Issue,- IssueCreate,- IssueType,- NORMAL_POLL_INTERVAL,- POLL_JITTER,- MINIMUM_POLL_INTERVAL,-} from "@/types";-import { idFromSlug } from "@/utils";--type LocalPollState = {- // Timer tracking the issue poller, we need this to cancel the outstanding one when needed.- timer: ReturnType<typeof setTimeout> | undefined;-};--export const usePollIssue = (- issueSlug: Ref<string>,- issue: Ref<Issue | IssueCreate | undefined>-) => {- const state = reactive<LocalPollState>({- timer: undefined,- });- const create = computed(() => issueSlug.value.toLowerCase() == "new");- const issueStore = useIssueStore();-- const stopPolling = () => {- if (!state.timer) {- return;- }- clearTimeout(state.timer);- };-- // pollIssue invalidates the current timer and schedule a new timer in <<interval>> microseconds- const pollIssue = (interval: number) => {- stopPolling();-- const int = Math.max(- MINIMUM_POLL_INTERVAL,- Math.min(interval, NORMAL_POLL_INTERVAL) +- (Math.random() * 2 - 1) * POLL_JITTER- );-- state.timer = setTimeout(() => {- issueStore.fetchIssueById(idFromSlug(issueSlug.value));-- pollIssue(Math.min(interval * 2, NORMAL_POLL_INTERVAL));- }, int);- };-- const pollOnCreateStateChange = () => {- if (!issue.value) {- return;- }-- let interval = NORMAL_POLL_INTERVAL;- // We will poll faster if meets either of the condition- // 1. Created the database create issue, expect creation result quickly.- // 2. Update the database schema, will do connection and syntax check.- const isNearNow =- Date.now() - (issue.value as Issue).updatedTs * 1000 < 5000;- const { type } = issue.value;- if (FASTER_TYPES.includes(type) && isNearNow) {- interval = MINIMUM_POLL_INTERVAL;- }- pollIssue(interval);- };-- watch(- create,- () => {- if (create.value) {- stopPolling();- } else {- pollOnCreateStateChange();- }- },- { immediate: true }- );-- onUnmounted(stopPolling);-- return pollIssue;-};--const FASTER_TYPES: IssueType[] = [- "bb.issue.database.create",- "bb.issue.database.schema.update",- "bb.issue.database.data.update",- "bb.issue.database.schema.update.ghost",-];diff --git a/frontend/src/plugins/issue/logic/review/index.ts b/frontend/src/plugins/issue/logic/review/index.tsindex 8b937f9df3..3b55d7b6d7 100644--- a/frontend/src/plugins/issue/logic/review/index.ts+++ b/frontend/src/plugins/issue/logic/review/index.ts@@ -1,32 +1,17 @@-import type Emittery from "emittery";-import { computed, watch, type ComputedRef, unref } from "vue";-import { useProgressivePoll } from "@/composables/useProgressivePoll";-import {- candidatesOfApprovalStep,- useAuthStore,- useIssueV1Store,- useUserStore,-} from "@/store";-import type {- Issue as LegacyIssue,- MaybeRef,- ReviewFlow,- WrappedReviewStep,-} from "@/types";+import { computed, type ComputedRef } from "vue";+import type { ReviewFlow } from "@/types";import {ApprovalTemplate,Issue,Issue_Approver_Status,} from "@/types/proto/v1/issue_service";-import { extractUserResourceName } from "@/utils";-import { IssueReviewContext, provideIssueReviewContext } from "./context";+import { IssueReviewContext } from "./context";export type ReviewEvents = {"issue-status-changed": boolean;};export const extractIssueReviewContext = (- legacyIssue: ComputedRef<LegacyIssue | undefined>,issue: ComputedRef<Issue>): IssueReviewContext => {const ready = computed(() => {@@ -90,7 +75,7 @@ export const extractIssueReviewContext = (});return {- issue: issue,+ issue,ready,flow,status,@@ -99,111 +84,6 @@ export const extractIssueReviewContext = (};};-export const provideIssueReview = (- legacyIssue: ComputedRef<LegacyIssue | undefined>,- events: Emittery<ReviewEvents>-) => {- const store = useIssueV1Store();- const issue = computed(() => {- return legacyIssue.value- ? store.getIssueByIssue(legacyIssue.value)- : Issue.fromJSON({});- });-- const update = () => {- if (legacyIssue.value) {- store.fetchIssueByLegacyIssue(legacyIssue.value);- }- };-- const poller = useProgressivePoll(update, {- interval: {- min: 500,- max: 10000,- growth: 2,- jitter: 500,- },- });-- watch(- () => legacyIssue.value?.id,- () => {- if (legacyIssue.value) poller.start();- else poller.stop();- },- {- immediate: true,- }- );- events.on("issue-status-changed", () => {- update();- });-- const context = extractIssueReviewContext(legacyIssue, issue);-- provideIssueReviewContext(context);-};--export const useWrappedReviewSteps = (- issue: MaybeRef<LegacyIssue>,- context: IssueReviewContext-) => {- const userStore = useUserStore();- const currentUserName = computed(() => useAuthStore().currentUser.name);- return computed(() => {- const { flow, done } = context;- const steps = flow.value.template.flow?.steps;- const approvers = flow.value.approvers;- const currentStepIndex = flow.value.currentStepIndex ?? -1;-- const statusOfStep = (index: number) => {- if (done.value) {- return "APPROVED";- }- if (index >= (steps?.length ?? 0)) {- // Out of index- return "PENDING";- }- const approval = approvers[index];- if (approval && approval.status === Issue_Approver_Status.REJECTED) {- return "REJECTED";- }- if (index < currentStepIndex) {- return "APPROVED";- }- if (index === currentStepIndex) {- return "CURRENT";- }- return "PENDING";- };- const approverOfStep = (index: number) => {- const principal = approvers[index]?.principal;- if (!principal) return undefined;- const email = extractUserResourceName(principal);- return userStore.getUserByEmail(email);- };- const candidatesOfStep = (index: number) => {- const step = steps?.[index];- if (!step) return [];- const users = candidatesOfApprovalStep(unref(issue), step);- const idx = users.indexOf(currentUserName.value);- if (idx > 0) {- users.splice(idx, 1);- users.unshift(currentUserName.value);- }- return users.map((user) => userStore.getUserByName(user)!);- };-- return steps?.map<WrappedReviewStep>((step, index) => ({- index,- step,- status: statusOfStep(index),- approver: approverOfStep(index),- candidates: candidatesOfStep(index),- }));- });-};-const emptyFlow = (): ReviewFlow => {return {template: ApprovalTemplate.fromJSON({}),diff --git a/frontend/src/plugins/pitr/index.ts b/frontend/src/plugins/pitr/index.tsindex 5c5dc72823..a3fd9b031a 100644--- a/frontend/src/plugins/pitr/index.ts+++ b/frontend/src/plugins/pitr/index.ts@@ -1,22 +1,12 @@import { head } from "lodash-es";import { computed, Ref, watch } from "vue";import { useI18n } from "vue-i18n";-import {- useBackupListByDatabaseName,- useChangeHistoryStore,- useCurrentUserV1,- useIssueStore,-} from "@/store";-import {- CreateDatabaseContext,- ComposedDatabase,- IssueCreate,- PITRContext,-} from "@/types";+import { useBackupListByDatabaseName, useChangeHistoryStore } from "@/store";+import { ComposedDatabase } from "@/types";import { Engine } from "@/types/proto/v1/common";import { Backup_BackupState } from "@/types/proto/v1/database_service";import { Instance } from "@/types/proto/v1/instance_service";-import { extractUserUID, semverCompare } from "@/utils";+import { semverCompare } from "@/utils";export const MIN_PITR_SUPPORT_MYSQL_VERSION = "8.0.0";@@ -30,7 +20,6 @@ export const isPITRAvailableOnInstanceV1 = (instance: Instance): boolean => {export const usePITRLogic = (database: Ref<ComposedDatabase>) => {const { t } = useI18n();- const currentUserV1 = useCurrentUserV1();const changeHistoryStore = useChangeHistoryStore();const backupList = useBackupListByDatabaseName(@@ -83,41 +72,11 @@ export const usePITRLogic = (database: Ref<ComposedDatabase>) => {return head(changeHistoryList.value);});- const createPITRIssue = async (- pointTimeTs: number,- createDatabaseContext: CreateDatabaseContext | undefined = undefined,- params: Partial<IssueCreate> = {}- ) => {- const issueStore = useIssueStore();- const createContext: PITRContext = {- databaseId: Number(database.value.uid),- pointInTimeTs: pointTimeTs,- createDatabaseContext,- };- const issueCreate: IssueCreate = {- name: `Restore database [${database.value.name}]`,- type: "bb.issue.database.restore.pitr",- description: "",- assigneeId: Number(extractUserUID(currentUserV1.value.name)),- projectId: Number(database.value.projectEntity.uid),- payload: {},- createContext,- ...params,- };-- await issueStore.validateIssue(issueCreate);-- const issue = await issueStore.createIssue(issueCreate);-- return issue;- };-return {backupList,doneBackupList,pitrAvailable,changeHistoryList,lastChangeHistory,- createPITRIssue,};};diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.tsindex 5f7f15d566..46c3ff9547 100644--- a/frontend/src/store/modules/index.ts+++ b/frontend/src/store/modules/index.ts@@ -5,7 +5,6 @@ export * from "./dataSource";export * from "./environment";export * from "./help";export * from "./issue";-export * from "./issueSubscriber";export * from "./instance";export * from "./notification";export * from "./pipeline";diff --git a/frontend/src/store/modules/issue.ts b/frontend/src/store/modules/issue.tsindex f7b5dfaf39..3834f09346 100644--- a/frontend/src/store/modules/issue.ts+++ b/frontend/src/store/modules/issue.ts@@ -1,139 +1,6 @@-import axios from "axios";import { defineStore } from "pinia";-import { computed, ref, unref, watch, WatchCallback, watchEffect } from "vue";-import {- empty,- EMPTY_ID,- isPagedResponse,- Issue,- IssueCreate,- IssueFind,- IssueId,- IssuePatch,- IssueState,- IssueStatusPatch,- MaybeRef,- Pipeline,- Principal,- Project,- ResourceIdentifier,- ResourceObject,- unknown,- UNKNOWN_ID,-} from "@/types";-import { isDatabaseRelatedIssueType } from "@/utils";-import { useLegacyDatabaseStore } from "./database";-import { usePipelineStore } from "./pipeline";-import { getPrincipalFromIncludedList } from "./principal";-import { useLegacyProjectStore } from "./project";-import { convertEntityList } from "./utils";-import {- useDatabaseV1Store,- useInstanceV1Store,- useActivityV1Store,-} from "./v1";--function convert(issue: ResourceObject, includedList: ResourceObject[]): Issue {- const result: Issue = {- ...(issue.attributes as Omit<- Issue,- "id" | "project" | "creator" | "updater" | "assignee" | "subscriberList"- >),- id: parseInt(issue.id),- creator: getPrincipalFromIncludedList(- issue.relationships!.creator.data,- includedList- ),- updater: getPrincipalFromIncludedList(- issue.relationships!.updater.data,- includedList- ),- assignee: getPrincipalFromIncludedList(- issue.relationships!.assignee.data,- includedList- ),- project: unknown("PROJECT") as Project,- pipeline: undefined,- subscriberList: [],- };-- try {- result.payload = JSON.parse(issue.attributes.payload as string);- } catch {- result.payload = {};- }- const projectStore = useLegacyProjectStore();-- // Compose issue pipeline.- if (isDatabaseRelatedIssueType(result.type)) {- let pipeline = unknown("PIPELINE") as Pipeline;- if (issue.relationships?.pipeline?.data) {- const pipelineStore = usePipelineStore();- const pipelineId = (- issue.relationships!.pipeline.data as ResourceIdentifier- ).id;- pipeline.id = parseInt(pipelineId);-- for (const item of includedList || []) {- if (- item.type == "pipeline" &&- issue.relationships!.pipeline.data &&- (issue.relationships!.pipeline.data as ResourceIdentifier).id ==- item.id- ) {- pipeline = pipelineStore.convert(item, includedList);- }- }- }- result.pipeline = pipeline;- }-- // Compose issue project.- for (const item of includedList || []) {- if (- item.type == "project" &&- (issue.relationships!.project.data as ResourceIdentifier).id == item.id- ) {- result.project = projectStore.convert(item, includedList || []);- }- }-- // Compose issue subscriberList.- const subscriberList = [] as Principal[];- if (issue.relationships!.subscriberList.data) {- for (const subscriberData of issue.relationships!.subscriberList- .data as ResourceIdentifier[]) {- subscriberList.push(- getPrincipalFromIncludedList(subscriberData, includedList)- );- }- }-- result.subscriberList = subscriberList;-- return result;-}--function getIssueFromIncludedList(- data:- | ResourceIdentifier<ResourceObject>- | ResourceIdentifier<ResourceObject>[]- | undefined,- includedList: ResourceObject[]-): Issue {- if (data == null) {- return empty("ISSUE");- }- for (const item of includedList || []) {- if (item.type !== "issue") {- continue;- }- if (item.id == (data as ResourceIdentifier).id) {- return convert(item, includedList);- }- }- return empty("ISSUE");-}+import { ref, watch, WatchCallback } from "vue";+import { IssueState } from "@/types";export const useIssueStore = defineStore("issue", {state: (): IssueState => ({@@ -145,233 +12,9 @@ export const useIssueStore = defineStore("issue", {return [...state.issueById.values()];},},- actions: {- getIssueById(issueId: IssueId): Issue {- if (issueId == EMPTY_ID) {- return empty("ISSUE") as Issue;- }-- return this.issueById.get(issueId) || (unknown("ISSUE") as Issue);- },- setIssueById({ issueId, issue }: { issueId: IssueId; issue: Issue }) {- this.issueById.set(issueId, issue);- },- async fetchPagedIssueList(params: IssueFind & { token?: string }) {- const queryList = buildQueryListByIssueFind(params);-- let url = "/api/issue";- if (queryList.length > 0) {- url += `?${queryList.join("&")}`;- }- const responseData = (await axios.get(url)).data;- const issueList = convertEntityList(- responseData,- "issues",- convert,- getIssueFromIncludedList- );-- // The issue list API returns incomplete issue entities (without- // task.instance and task.database compositions)- // So we shouldn't store the incomplete cache items in issueById set here.-- const nextToken = isPagedResponse(responseData, "issues")- ? responseData.data.attributes.nextToken- : "";- return {- nextToken,- issueList,- };- },- async fetchIssueList(params: IssueFind) {- const result = await this.fetchPagedIssueList(params);- return result.issueList;- },- async fetchIssueById(issueId: IssueId) {- const data = (await axios.get(`/api/issue/${issueId}`)).data;- const issue = convert(data.data, data.included);- this.setIssueById({- issueId,- issue,- });-- // It might be the first time the particular instance/database objects are returned,- // so that we should also update instance/database store, otherwise, we may get- // unknown instance/database when navigating to other UI from the issue detail page- // since other UIs are getting instance/database by id from the store.- if (isDatabaseRelatedIssueType(issue.type)) {- const databaseStore = useLegacyDatabaseStore();- const instanceV1Store = useInstanceV1Store();- const databaseV1Store = useDatabaseV1Store();- for (const stage of issue.pipeline!.stageList) {- for (const task of stage.taskList) {- instanceV1Store.getOrFetchInstanceByUID(String(task.instance.id));-- if (task.database) {- databaseV1Store.getOrFetchDatabaseByUID(String(task.database.id));-- // Legacy compatibility- databaseStore.upsertDatabaseList({- databaseList: [task.database],- });- }- }- }- }- return issue;- },- async getOrFetchIssueById(issueId: IssueId) {- if (issueId === EMPTY_ID) return empty("ISSUE");- if (issueId === UNKNOWN_ID) return unknown("ISSUE");- if (!this.issueById.has(issueId)) {- await this.fetchIssueById(issueId);- }- return this.getIssueById(issueId);- },- async createIssue(newIssue: IssueCreate) {- try {- this.isCreatingIssue = true;- const data = (- await axios.post(`/api/issue`, {- data: {- type: "IssueCreate",- attributes: {- ...newIssue,- // Server expects payload as string, so we stringify first.- createContext: JSON.stringify(newIssue.createContext),- payload: JSON.stringify(newIssue.payload),- },- },- })- ).data;- const createdIssue = convert(data.data, data.included);-- this.setIssueById({- issueId: createdIssue.id,- issue: createdIssue,- });-- return createdIssue;- } finally {- this.isCreatingIssue = false;- }- },- async validateIssue(newIssue: IssueCreate) {- const data = (- await axios.post(`/api/issue`, {- data: {- type: "IssueCreate",- attributes: {- ...newIssue,- // Server expects payload as string, so we stringify first.- createContext: JSON.stringify(newIssue.createContext),- payload: JSON.stringify(newIssue.payload),- validateOnly: true,- },- },- })- ).data;- const createdIssue = convert(data.data, data.included);- return createdIssue;- },- async patchIssue({- issueId,- issuePatch,- }: {- issueId: IssueId;- issuePatch: IssuePatch;- }) {- const data = (- await axios.patch(`/api/issue/${issueId}`, {- data: {- type: "issuePatch",- attributes: issuePatch,- },- })- ).data;- const updatedIssue = convert(data.data, data.included);-- this.setIssueById({- issueId: issueId,- issue: updatedIssue,- });-- useActivityV1Store().fetchActivityListByIssueId(issueId);-- return updatedIssue;- },- async updateIssueStatus({- issueId,- issueStatusPatch,- }: {- issueId: IssueId;- issueStatusPatch: IssueStatusPatch;- }) {- const data = (- await axios.patch(`/api/issue/${issueId}/status`, {- data: {- type: "issueStatusPatch",- attributes: issueStatusPatch,- },- })- ).data;- const updatedIssue = convert(data.data, data.included);-- this.setIssueById({- issueId: issueId,- issue: updatedIssue,- });-- useActivityV1Store().fetchActivityListByIssueId(issueId);-- return updatedIssue;- },- },+ actions: {},});-export const buildQueryListByIssueFind = (- params: IssueFind & { token?: string }-): string[] => {- const {- projectId,- principalId,- creatorId,- assigneeId,- subscriberId,- statusList,- limit,- token,- } = params;-- const queryList = [];- if (statusList && statusList.length > 0) {- queryList.push(`status=${statusList.join(",")}`);- }- if (principalId) {- queryList.push(`user=${principalId}`);- }- if (creatorId) {- queryList.push(`creator=${creatorId}`);- }- if (assigneeId) {- queryList.push(`assignee=${assigneeId}`);- }- if (subscriberId) {- queryList.push(`subscriber=${subscriberId}`);- }- if (projectId) {- queryList.push(`project=${projectId}`);- }- if (limit) {- queryList.push(`limit=${limit}`);- }- if (token) {- queryList.push(`token=${token}`);- }-- return queryList;-};-// expose global list refresh featuresconst REFRESH_ISSUE_LIST = ref(Math.random());export const refreshIssueList = () => {@@ -380,23 +23,3 @@ export const refreshIssueList = () => {export const useRefreshIssueList = (callback: WatchCallback) => {watch(REFRESH_ISSUE_LIST, callback);};--export const useIssueById = (issueId: MaybeRef<IssueId>, lazy = false) => {- const store = useIssueStore();-- watchEffect(() => {- const id = unref(issueId);- if (id !== UNKNOWN_ID) {- if (lazy && store.issueById.has(id)) {- // Don't fetch again if we have a local copy- // when lazy === true- return;- }- store.fetchIssueById(id);- }- });-- return computed(() => {- return store.getIssueById(unref(issueId));- });-};diff --git a/frontend/src/store/modules/issueSubscriber.ts b/frontend/src/store/modules/issueSubscriber.tsdeleted file mode 100644index 6b04d26dbb..0000000000--- a/frontend/src/store/modules/issueSubscriber.ts+++ /dev/null@@ -1,137 +0,0 @@-import axios from "axios";-import { defineStore } from "pinia";-import {- PrincipalId,- IssueSubscriber,- IssueSubscriberState,- ResourceObject,- IssueId,-} from "@/types";-import { getPrincipalFromIncludedList } from "./principal";--function convert(- issueSubscriber: ResourceObject,- includedList: ResourceObject[]-): IssueSubscriber {- return {- issueId: issueSubscriber.attributes.issueId as IssueId,- subscriber: getPrincipalFromIncludedList(- issueSubscriber.relationships!.subscriber.data,- includedList- ),- };-}--export const useIssueSubscriberStore = defineStore("issueSubscriber", {- state: (): IssueSubscriberState => ({- subscriberList: new Map(),- }),-- actions: {- subscriberListByIssue(issueId: IssueId): IssueSubscriber[] {- return this.subscriberList.get(issueId) || [];- },- async fetchSubscriberListByIssue(issueId: IssueId) {- const data = (await axios.get(`/api/issue/${issueId}/subscriber`)).data;- const subscriberList = data.data.map(- (issueSubscriber: ResourceObject) => {- return convert(issueSubscriber, data.included);- }- );- this.setSubscriberListByIssueId({- issueId,- subscriberList,- });- return subscriberList;- },-- async createSubscriber({- issueId,- subscriberId,- }: {- issueId: IssueId;- subscriberId: PrincipalId;- }) {- const data = (- await axios.post(`/api/issue/${issueId}/subscriber`, {- data: {- type: "issueSubscriber",- attributes: {- subscriberId,- },- },- })- ).data;- const createdIssueSubscriber = convert(data.data, data.included);-- this.upsertSubsriberListByIssueId({- issueId,- subscriber: createdIssueSubscriber,- });-- return createdIssueSubscriber;- },-- async deleteSubscriber({- issueId,- subscriberId,- }: {- issueId: IssueId;- subscriberId: PrincipalId;- }) {- await axios.delete(`/api/issue/${issueId}/subscriber/${subscriberId}`);-- this.deleteIssueSubscriberByIssueId({ issueId, subscriberId });- },- setSubscriberListByIssueId({- issueId,- subscriberList,- }: {- issueId: IssueId;- subscriberList: IssueSubscriber[];- }) {- this.subscriberList.set(issueId, subscriberList);- },-- upsertSubsriberListByIssueId({- issueId,- subscriber,- }: {- issueId: IssueId;- subscriber: IssueSubscriber;- }) {- const list = this.subscriberList.get(issueId);- if (list) {- const i = list.findIndex(- (item: IssueSubscriber) =>- item.subscriber.id == subscriber.subscriber.id- );- if (i != -1) {- list[i] = subscriber;- } else {- list.push(subscriber);- }- } else {- this.subscriberList.set(issueId, [subscriber]);- }- },-- deleteIssueSubscriberByIssueId({- issueId,- subscriberId,- }: {- issueId: IssueId;- subscriberId: PrincipalId;- }) {- const list = this.subscriberList.get(issueId);- if (list) {- const i = list.findIndex(- (item: IssueSubscriber) => item.subscriber.id == subscriberId- );- if (i != -1) {- list.splice(i, 1);- }- }- },- },-});diff --git a/frontend/src/store/modules/task.ts b/frontend/src/store/modules/task.tsindex 68aa196383..aafb400eb5 100644--- a/frontend/src/store/modules/task.ts+++ b/frontend/src/store/modules/task.ts@@ -1,30 +1,22 @@-import axios from "axios";import { defineStore } from "pinia";import {empty,Instance,- Issue,- IssueId,Pipeline,PipelineId,ResourceIdentifier,ResourceObject,Stage,- StageAllTaskStatusPatch,StageId,Task,TaskCheckRun,- TaskId,- TaskPatch,TaskProgress,TaskRun,TaskState,- TaskStatusPatch,unknown,} from "@/types";import { useLegacyDatabaseStore } from "./database";import { useLegacyInstanceStore } from "./instance";-import { useIssueStore } from "./issue";import { getPrincipalFromIncludedList } from "./principal";function convertTaskRun(@@ -225,113 +217,5 @@ export const useTaskStore = defineStore("task", {stage,} as Task;},- async updateStatus({- issueId,- pipelineId,- taskId,- taskStatusPatch,- }: {- issueId: IssueId;- pipelineId: PipelineId;- taskId: TaskId;- taskStatusPatch: TaskStatusPatch;- }) {- const data = (- await axios.patch(`/api/pipeline/${pipelineId}/task/${taskId}/status`, {- data: {- type: "taskStatusPatch",- attributes: taskStatusPatch,- },- })- ).data;- const task = this.convertPartial(data.data, data.included);-- useIssueStore().fetchIssueById(issueId);-- return task;- },- async updateStageAllTaskStatus({- issue,- stage,- patch,- }: {- issue: Issue;- stage: Stage;- patch: StageAllTaskStatusPatch;- }) {- const { pipeline } = stage;- await axios.patch(- `/api/pipeline/${pipeline.id}/stage/${stage.id}/status`,- {- data: {- type: "stageAllTaskStatusPatch",- attributes: patch,- },- }- );-- useIssueStore().fetchIssueById(issue.id);- },- async patchTask({- issueId,- pipelineId,- taskId,- taskPatch,- }: {- issueId: IssueId;- pipelineId: PipelineId;- taskId: TaskId;- taskPatch: TaskPatch;- }) {- const data = (- await axios.patch(`/api/pipeline/${pipelineId}/task/${taskId}`, {- data: {- type: "taskPatch",- attributes: taskPatch,- },- })- ).data;- const task = this.convertPartial(data.data, data.included);-- useIssueStore().fetchIssueById(issueId);-- return task;- },- async patchAllTasksInIssue({- issueId,- pipelineId,- taskPatch,- }: {- issueId: IssueId;- pipelineId: PipelineId;- taskPatch: TaskPatch;- }) {- await axios.patch(`/api/pipeline/${pipelineId}/task/all`, {- data: {- type: "taskPatch",- attributes: taskPatch,- },- });-- useIssueStore().fetchIssueById(issueId);- },- async runChecks({- issueId,- pipelineId,- taskId,- }: {- issueId: IssueId;- pipelineId: PipelineId;- taskId: TaskId;- }) {- const data = (- await axios.post(`/api/pipeline/${pipelineId}/task/${taskId}/check`)- ).data;- const task = this.convertPartial(data.data, data.included);-- useIssueStore().fetchIssueById(issueId);-- return task;- },},});diff --git a/frontend/src/store/modules/v1/activity.ts b/frontend/src/store/modules/v1/activity.tsindex ea4a4a5b09..e653128426 100644--- a/frontend/src/store/modules/v1/activity.ts+++ b/frontend/src/store/modules/v1/activity.ts@@ -6,7 +6,6 @@ import { loggingServiceClient } from "@/grpcweb";import {IdType,FindActivityMessage,- Issue as LegacyIssue,UNKNOWN_ID,EMPTY_ID,ComposedIssue,@@ -19,14 +18,10 @@ import {logEntity_ActionToJSON,logEntity_LevelToJSON,} from "@/types/proto/v1/logging_service";-import {- isDatabaseRelatedIssue,- isDatabaseRelatedIssueType,- extractRolloutUID,-} from "@/utils";+import { isDatabaseRelatedIssue, extractRolloutUID } from "@/utils";import { useCurrentUserV1 } from "../auth";-import { useIssueStore } from "../issue";import { userNamePrefix, getLogId, logNamePrefix } from "./common";+import { experimentalFetchIssueByUID } from "./experimental-issue";dayjs.extend(utc);@@ -64,7 +59,6 @@ const buildFilter = (find: FindActivityMessage): string => {};export const useActivityV1Store = defineStore("activity_v1", () => {- const activityListByIssue = reactive(new Map<IdType, LogEntity[]>());const activityListByIssueV1 = reactive(new Map<string, LogEntity[]>());const fetchActivityList = async (find: FindActivityMessage) => {@@ -78,40 +72,6 @@ export const useActivityV1Store = defineStore("activity_v1", () => {return resp;};- const getActivityListByIssue = (issueId: IdType): LogEntity[] => {- return activityListByIssue.get(issueId) || [];- };-- const fetchActivityListForIssue = async (issue: LegacyIssue) => {- const requests = [- fetchActivityList({- resource: `issues/${issue.id}`,- order: "asc",- pageSize: 1000,- }).then((resp) => resp.logEntities),- ];- if (isDatabaseRelatedIssueType(issue.type) && issue.pipeline) {- requests.push(- fetchActivityList({- resource: `pipelines/${issue.pipeline.id}`,- order: "asc",- pageSize: 1000,- }).then((resp) => resp.logEntities)- );- } else {- requests.push(Promise.resolve([]));- }-- const [listForIssue, listForPipeline] = await Promise.all(requests);- const mergedList = [...listForIssue, ...listForPipeline];- mergedList.sort((a, b) => {- return getLogId(a.name) - getLogId(b.name);- });-- activityListByIssue.set(issue.id, mergedList);- return mergedList;- };-const getActivityListByIssueV1 = (uid: string): LogEntity[] => {return activityListByIssueV1.get(uid) || [];};@@ -145,12 +105,9 @@ export const useActivityV1Store = defineStore("activity_v1", () => {return mergedList;};- const fetchActivityListByIssueId = async (issueId: IdType) => {- const issue = useIssueStore().getIssueById(issueId);- if (issue.id === UNKNOWN_ID) {- return;- }- return fetchActivityListForIssue(issue);+ const fetchActivityListByIssueUID = async (uid: string) => {+ const issue = await experimentalFetchIssueByUID(uid);+ return fetchActivityListForIssueV1(issue);};const fetchActivityListForQueryHistory = async ({@@ -202,12 +159,10 @@ export const useActivityV1Store = defineStore("activity_v1", () => {return {fetchActivityList,- fetchActivityListForIssue,fetchActivityListForIssueV1,- fetchActivityListByIssueId,+ fetchActivityListByIssueUID,fetchActivityListForQueryHistory,fetchActivityByUID,- getActivityListByIssue,getActivityListByIssueV1,getResourceId,exportData,diff --git a/frontend/src/store/modules/v1/issue.ts b/frontend/src/store/modules/v1/issue.tsindex 240dd9223a..d02f0fae9f 100644--- a/frontend/src/store/modules/v1/issue.ts+++ b/frontend/src/store/modules/v1/issue.ts@@ -1,42 +1,26 @@import dayjs from "dayjs";-import { uniq, uniqBy } from "lodash-es";+import { uniq } from "lodash-es";import { defineStore } from "pinia";-import { ref } from "vue";import { issueServiceClient } from "@/grpcweb";import {- IdType,ActivityIssueCommentCreatePayload,- Issue as LegacyIssue,PresetRoleType,ComposedIssue,IssueFilter,} from "@/types";-import { User, UserRole, UserType } from "@/types/proto/v1/auth_service";+import { UserRole, UserType } from "@/types/proto/v1/auth_service";import {- Issue,issueStatusToJSON,ApprovalStep,ApprovalNode_Type,ApprovalNode_GroupValue,} from "@/types/proto/v1/issue_service";-import { extractUserResourceName, memberListInProjectV1 } from "@/utils";-import { useProjectV1Store } from ".";+import { memberListInProjectV1 } from "@/utils";import { useUserStore } from "../user";import { useActivityV1Store } from "./activity";import { projectNamePrefix, issueNamePrefix } from "./common";import { shallowComposeIssue } from "./experimental-issue";-const issueName = (legacyIssue: LegacyIssue) => {- return `projects/${legacyIssue.project.id}/issues/${legacyIssue.id}`;-};--const emptyIssue = (legacyIssue: LegacyIssue) => {- return Issue.fromJSON({- name: issueName(legacyIssue),- approvalFindingDone: false,- });-};-export type ListIssueParams = {find: IssueFilter;pageSize?: number;@@ -84,70 +68,6 @@ export const buildIssueFilter = (find: IssueFilter): string => {};export const useIssueV1Store = defineStore("issue_v1", () => {- const issuesByName = ref(new Map<string, Issue>());-- const getIssueByIssue = (issue: LegacyIssue) => {- return issuesByName.value.get(issueName(issue)) ?? emptyIssue(issue);- };-- const setIssueIssue = async (legacyIssue: LegacyIssue, issue: Issue) => {- await fetchReviewApproversAndCandidates(legacyIssue, issue);- issuesByName.value.set(issueName(legacyIssue), issue);- };-- const fetchIssueByLegacyIssue = async (- legacyIssue: LegacyIssue,- force = false- ) => {- const name = issueName(legacyIssue);-- try {- const issue = await issueServiceClient.getIssue({- name,- force,- });- await setIssueIssue(legacyIssue, issue);- return issue;- } catch (error) {- return Issue.fromJSON({});- }- };-- const approveIssue = async (legacyIssue: LegacyIssue, comment?: string) => {- const issue = await issueServiceClient.approveIssue({- name: issueName(legacyIssue),- comment,- });- await setIssueIssue(legacyIssue, issue);- };-- const rejectIssue = async (legacyIssue: LegacyIssue, comment?: string) => {- const issue = await issueServiceClient.rejectIssue({- name: issueName(legacyIssue),- comment,- });- await setIssueIssue(legacyIssue, issue);- };-- const requestIssue = async (legacyIssue: LegacyIssue, comment?: string) => {- const issue = await issueServiceClient.requestIssue({- name: issueName(legacyIssue),- comment,- });- await setIssueIssue(legacyIssue, issue);- };-- const regenerateReview = async (legacyIssue: LegacyIssue) => {- const issue = await issueServiceClient.updateIssue({- issue: {- name: issueName(legacyIssue),- approvalFindingDone: false,- },- updateMask: ["approval_finding_done"],- });- await setIssueIssue(legacyIssue, issue);- };-const regenerateReviewV1 = async (name: string) => {await issueServiceClient.updateIssue({issue: {@@ -163,7 +83,7 @@ export const useIssueV1Store = defineStore("issue_v1", () => {comment,payload,}: {- issueId: IdType;+ issueId: string;comment: string;payload?: ActivityIssueCommentCreatePayload;}) => {@@ -174,7 +94,7 @@ export const useIssueV1Store = defineStore("issue_v1", () => {payload: JSON.stringify(payload ?? {}),},});- await useActivityV1Store().fetchActivityListByIssueId(issueId);+ await useActivityV1Store().fetchActivityListByIssueUID(issueId);};const updateIssueComment = async ({@@ -183,7 +103,7 @@ export const useIssueV1Store = defineStore("issue_v1", () => {comment,}: {commentId: string;- issueId: IdType;+ issueId: string;comment: string;}) => {await issueServiceClient.updateIssueComment({@@ -194,7 +114,7 @@ export const useIssueV1Store = defineStore("issue_v1", () => {},updateMask: ["comment"],});- await useActivityV1Store().fetchActivityListByIssueId(issueId);+ await useActivityV1Store().fetchActivityListByIssueUID(issueId);};const listIssues = async ({ find, pageSize, pageToken }: ListIssueParams) => {@@ -237,117 +157,14 @@ export const useIssueV1Store = defineStore("issue_v1", () => {};return {- getIssueByIssue,- fetchIssueByLegacyIssue: fetchIssueByLegacyIssue,- approveIssue,- rejectIssue,- requestIssue,listIssues,searchIssues,- regenerateReview,regenerateReviewV1,createIssueComment,updateIssueComment,};});-const fetchReviewApproversAndCandidates = async (- legacyIssue: LegacyIssue,- issue: Issue-) => {- const userStore = useUserStore();- const approvers = issue.approvers.map((approver) => {- return userStore.getUserByEmail(- extractUserResourceName(approver.principal)- );- });- const candidates = issue.approvalTemplates- .flatMap((template) => {- const steps = template.flow?.steps ?? [];- return steps.flatMap((step) =>- candidatesOfApprovalStep(legacyIssue, step)- );- })- .map((user) => userStore.getUserByName(user));- const users = [...approvers, ...candidates].filter(- (user) => user !== undefined- ) as User[];- return uniqBy(users, "name");-};--export const candidatesOfApprovalStep = (- legacyIssue: LegacyIssue,- step: ApprovalStep-) => {- const workspaceMemberList = useUserStore().activeUserList.filter(- (user) => user.userType === UserType.USER- );- const project = useProjectV1Store().getProjectByUID(- String(legacyIssue.project.id)- );- const projectMemberList = memberListInProjectV1(project, project.iamPolicy)- .filter((member) => member.user.userType === UserType.USER)- .map((member) => ({- ...member,- user: member.user,- }));-- const candidates = step.nodes.flatMap((node) => {- const {- type,- groupValue = ApprovalNode_GroupValue.UNRECOGNIZED,- role,- } = node;- if (type !== ApprovalNode_Type.ANY_IN_GROUP) return [];-- const candidatesForSystemRoles = (groupValue: ApprovalNode_GroupValue) => {- if (groupValue === ApprovalNode_GroupValue.PROJECT_MEMBER) {- return projectMemberList- .filter((member) =>- member.roleList.includes(PresetRoleType.DEVELOPER)- )- .map((member) => member.user);- }- if (groupValue === ApprovalNode_GroupValue.PROJECT_OWNER) {- return projectMemberList- .filter((member) => member.roleList.includes(PresetRoleType.OWNER))- .map((member) => member.user);- }- if (groupValue === ApprovalNode_GroupValue.WORKSPACE_DBA) {- return workspaceMemberList.filter(- (member) => member.userRole === UserRole.DBA- );- }- if (groupValue === ApprovalNode_GroupValue.WORKSPACE_OWNER) {- return workspaceMemberList.filter(- (member) => member.userRole === UserRole.OWNER- );- }- return [];- };- const candidatesForCustomRoles = (role: string) => {- const project = useProjectV1Store().getProjectByUID(- String(legacyIssue.project.id)- );- const memberList = memberListInProjectV1(project, project.iamPolicy);- return memberList- .filter((member) => member.user.userType === UserType.USER)- .filter((member) => member.roleList.includes(role))- .map((member) => member.user);- };-- if (groupValue !== ApprovalNode_GroupValue.UNRECOGNIZED) {- return candidatesForSystemRoles(groupValue);- }- if (role) {- return candidatesForCustomRoles(role);- }- return [];- });-- return uniq(candidates.map((user) => user.name));-};-export const candidatesOfApprovalStepV1 = (issue: ComposedIssue,step: ApprovalStepdiff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex d53358143d..9fe32603bc 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -15,7 +15,6 @@ export * from "./help";export * from "./id";export * from "./instance";export * from "./issue";-export * from "./issueSubscriber";export * from "./jsonapi";export * from "./member";export * from "./notification";diff --git a/frontend/src/types/issueSubscriber.ts b/frontend/src/types/issueSubscriber.tsdeleted file mode 100644index 3feac03b53..0000000000--- a/frontend/src/types/issueSubscriber.ts+++ /dev/null@@ -1,8 +0,0 @@-import { IssueId } from "./id";-import { Principal } from "./principal";--export type IssueSubscriber = {- // Domain specific fields- issueId: IssueId;- subscriber: Principal;-};diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.tsindex 2db12afb9c..79941a053b 100644--- a/frontend/src/types/store.ts+++ b/frontend/src/types/store.ts@@ -15,7 +15,6 @@ import {} from "./id";import { Instance, MigrationHistory } from "./instance";import { Issue } from "./issue";-import { IssueSubscriber } from "./issueSubscriber";import { Label } from "./label";import { Notification } from "./notification";import { Principal } from "./principal";@@ -33,10 +32,6 @@ export interface IssueState {isCreatingIssue: boolean;}-export interface IssueSubscriberState {- subscriberList: Map<IssueId, IssueSubscriber[]>;-}-// eslint-disable-next-line @typescript-eslint/no-empty-interfaceexport interface PipelineState {}diff --git a/frontend/src/views/IssueDetail.vue b/frontend/src/views/IssueDetail.vuedeleted file mode 100644index f86ca15b75..0000000000--- a/frontend/src/views/IssueDetail.vue+++ /dev/null@@ -1,168 +0,0 @@-<template>- <div class="w-full h-full relative">- <template v-if="issue">- <DatabaseRelatedDetail- v-if="isDatabaseRelatedIssue"- :issue="issue"- :create="create"- @status-changed="onStatusChanged"- />- <GrantRequestDetail- v-if="isGrantRequestIssue"- :issue="issue"- :create="create"- @status-changed="onStatusChanged"- />- </template>- <div- v-if="showLoading"- class="w-full h-full fixed md:absolute inset-0 flex justify-center items-center bg-white/50"- >- <NSpin />- </div>- </div>- <FeatureModal- feature="bb.feature.multi-tenancy"- :open="state.showFeatureModal"- @cancel="state.showFeatureModal = false"- />-</template>--<script lang="ts" setup>-import { useTitle } from "@vueuse/core";-import Emittery from "emittery";-import { NSpin } from "naive-ui";-import { onMounted, computed, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute, _RouteLocationBase } from "vue-router";-import DatabaseRelatedDetail from "@/components/Issue/layout/DatabaseRelatedDetail.vue";-import GrantRequestDetail from "@/components/Issue/layout/GrantRequestDetail.vue";-import {- useInitializeIssue,- provideIssueReview,- usePollIssue,- ReviewEvents,-} from "@/plugins/issue/logic";-import {- hasFeature,- useIssueStore,- useProjectV1Store,- useUIStateStore,-} from "@/store";-import {- IssueType,- NORMAL_POLL_INTERVAL,- MINIMUM_POLL_INTERVAL,- UNKNOWN_ID,- Issue,- unknownProject,-} from "@/types";-import { Project, TenantMode } from "@/types/proto/v1/project_service";-import { isDatabaseRelatedIssueType, isGrantRequestIssueType } from "@/utils";--interface LocalState {- showFeatureModal: boolean;-}--const props = defineProps({- issueSlug: {- required: true,- type: String,- },-});--const uiStateStore = useUIStateStore();-const route = useRoute();-const { t } = useI18n();--const state = reactive<LocalState>({- showFeatureModal: false,-});-const issueStore = useIssueStore();--const issueSlug = computed(() => props.issueSlug);--const { create, issue } = useInitializeIssue(issueSlug);--const showLoading = computed(() => {- if (!issue.value) return true;- return issueStore.isCreatingIssue;-});--const pollIssue = usePollIssue(issueSlug, issue);--const reviewEvents = new Emittery<ReviewEvents>();--provideIssueReview(- computed(() => {- return create.value ? undefined : (issue.value as Issue);- }),- reviewEvents-);--const isGrantRequestIssue = computed(() => {- return !!issue.value && isGrantRequestIssueType(issue.value.type);-});--const isDatabaseRelatedIssue = computed(() => {- return !!issue.value && isDatabaseRelatedIssueType(issue.value.type);-});--onMounted(() => {- if (!uiStateStore.getIntroStateByKey("issue.visit")) {- uiStateStore.saveIntroStateByKey({- key: "issue.visit",- newState: true,- });- }-});--watch(issueSlug, async () => {- if (!create.value) return;- const type = route.query.template as IssueType;- const tenantIssueTypes: IssueType[] = [- "bb.issue.database.schema.update",- "bb.issue.database.data.update",- ];- if (tenantIssueTypes.includes(type)) {- const project = await findProject();- if (- project.tenantMode === TenantMode.TENANT_MODE_ENABLED &&- !hasFeature("bb.feature.multi-tenancy")- ) {- state.showFeatureModal = true;- }- }-});--const onStatusChanged = (eager: boolean) => {- pollIssue(eager ? MINIMUM_POLL_INTERVAL : NORMAL_POLL_INTERVAL);- reviewEvents.emit("issue-status-changed", eager);-};--const findProject = async (): Promise<Project> => {- const projectId = route.query.project- ? (route.query.project as string)- : String(UNKNOWN_ID);- if (projectId !== String(UNKNOWN_ID)) {- const projectV1Store = useProjectV1Store();- const project = await projectV1Store.getOrFetchProjectByUID(projectId);- return project;- }- return unknownProject();-};--const documentTitle = computed(() => {- if (create.value) {- return t("issue.new-issue");- } else {- const issueEntity = issue.value as Issue | undefined;-- if (issueEntity) {- return issueEntity.name;- }- return t("common.loading");- }-});-useTitle(documentTitle);-</script>