Skip to content

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

feat(frontend): issue v1 detail page (#6961)

Liu Ji30df3e1eda98
diff --git a/frontend/src/components/BookmarkListSidePanel.vue b/frontend/src/components/BookmarkListSidePanel.vue
index 5a85a3b274..111fcc644d 100644
--- a/frontend/src/components/BookmarkListSidePanel.vue
+++ b/frontend/src/components/BookmarkListSidePanel.vue
@@ -4,7 +4,11 @@
:title="$t('common.bookmarks')"
:item-list="
bookmarkList.map((item) => {
- return { id: item.name, name: item.title, link: item.link };
+ return {
+ id: item.name,
+ name: item.title,
+ link: item.link,
+ };
})
"
:allow-delete="true"
diff --git a/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue b/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue
index 253d7cc1ab..775f79697e 100644
--- a/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue
+++ b/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue
@@ -74,13 +74,13 @@
>
</BBTableCell>
<BBTableCell>
- <template v-if="extractIssueId(history.issue)">
+ <template v-if="extractIssueUID(history.issue)">
<!--Short circuit the click event to prevent propagating to row click-->
<router-link
- :to="`/issue/${extractIssueId(history.issue)}`"
+ :to="`/issue/${extractIssueUID(history.issue)}`"
class="normal-link"
@click.stop=""
- >{{ extractIssueId(history.issue) }}
+ >{{ extractIssueUID(history.issue) }}
</router-link>
</template>
</BBTableCell>
@@ -124,7 +124,7 @@ import { NCheckbox } from "naive-ui";
import { ComposedDatabase } from "@/types";
import { BBTableSectionDataSource } from "@/bbkit/types";
import {
- extractIssueId,
+ extractIssueUID,
humanizeDate,
extractUserResourceName,
changeHistoryLink,
diff --git a/frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue b/frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue
index 33f5901435..a78c604b00 100644
--- a/frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue
+++ b/frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue
@@ -21,11 +21,11 @@
</label>
<div class="flex-1">
<a
- :href="`/issue/${extractIssueId(changeHistory.issue)}`"
+ :href="`/issue/${extractIssueUID(changeHistory.issue)}`"
target="__BLANK"
class="normal-link flex items-center gap-x-1"
>
- {{ extractIssueId(changeHistory.issue) }}
+ {{ extractIssueUID(changeHistory.issue) }}
</a>
</div>
</div>
@@ -83,7 +83,7 @@ import { computed, PropType } from "vue";
import dayjs from "dayjs";
import {
extractUserResourceName,
- extractIssueId,
+ extractIssueUID,
changeHistoryLink as makeChangeHistoryLink,
} from "@/utils";
import { ComposedDatabase } from "@/types";
diff --git a/frontend/src/components/IssueV1/IssueDetailPage.vue b/frontend/src/components/IssueV1/IssueDetailPage.vue
new file mode 100644
index 0000000000..ee189c7b67
--- /dev/null
+++ b/frontend/src/components/IssueV1/IssueDetailPage.vue
@@ -0,0 +1,105 @@
+<template>
+ <div class="divide-y">
+ <div class="issue-debug">phase: {{ phase }}</div>
+
+ <BannerSection v-if="!isCreating" />
+
+ <HeaderSection class="!border-t-0" />
+
+ <StageSection />
+
+ <TaskListSection />
+
+ <TaskRunSection v-if="!isCreating" />
+
+ <PlanCheckSection v-if="!isCreating" />
+
+ <StatementSection />
+
+ <DescriptionSection />
+
+ <ActivitySection v-if="!isCreating" />
+
+ <IssueReviewActionDialog
+ v-if="ongoingIssueReviewAction"
+ :action="ongoingIssueReviewAction.action"
+ @close="ongoingIssueReviewAction = undefined"
+ />
+ <IssueStatusActionDialog
+ v-if="ongoingIssueStatusAction"
+ :action="ongoingIssueStatusAction.action"
+ @close="ongoingIssueStatusAction = undefined"
+ />
+ <TaskRolloutActionDialog
+ v-if="ongoingTaskRolloutAction"
+ :action="ongoingTaskRolloutAction.action"
+ :task-list="ongoingTaskRolloutAction.taskList"
+ @close="ongoingTaskRolloutAction = undefined"
+ />
+ </div>
+
+ <div class="issue-debug">
+ <pre class="text-xs">{{ JSON.stringify(issue, null, " ") }}</pre>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { ref } from "vue";
+
+import {
+ IssueReviewAction,
+ IssueStatusAction,
+ TaskRolloutAction,
+ useIssueContext,
+ usePollIssue,
+} from "./logic";
+import {
+ BannerSection,
+ HeaderSection,
+ StageSection,
+ TaskListSection,
+ TaskRunSection,
+ PlanCheckSection,
+ StatementSection,
+ DescriptionSection,
+ ActivitySection,
+ IssueReviewActionDialog,
+ IssueStatusActionDialog,
+ TaskRolloutActionDialog,
+} from "./components";
+import { Task } from "@/types/proto/v1/rollout_service";
+
+const { isCreating, phase, issue, events } = useIssueContext();
+
+const ongoingIssueReviewAction = ref<{
+ action: IssueReviewAction;
+}>();
+const ongoingIssueStatusAction = ref<{
+ action: IssueStatusAction;
+}>();
+const ongoingTaskRolloutAction = ref<{
+ action: TaskRolloutAction;
+ taskList: Task[];
+}>();
+
+usePollIssue();
+
+events.on("perform-issue-review-action", ({ action }) => {
+ ongoingIssueReviewAction.value = {
+ action,
+ };
+});
+
+events.on("perform-issue-status-action", ({ action }) => {
+ ongoingIssueStatusAction.value = {
+ action,
+ };
+});
+
+events.on("perform-task-rollout-action", async ({ action, tasks }) => {
+ ongoingTaskRolloutAction.value = {
+ action,
+ taskList: tasks,
+ };
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionCreator.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionCreator.vue
new file mode 100644
index 0000000000..fe1283f815
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionCreator.vue
@@ -0,0 +1,44 @@
+<template>
+ <router-link
+ v-if="userEmail !== SYSTEM_BOT_EMAIL"
+ :to="`/u/${userId}`"
+ class="font-medium text-main whitespace-nowrap hover:underline"
+ exact-active-class=""
+ >{{ user?.title }}</router-link
+ >
+ <div v-else class="inline-flex items-center">
+ <span class="font-medium text-main whitespace-nowrap">
+ {{ user?.title }}
+ </span>
+ <span
+ class="ml-0.5 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>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { SYSTEM_BOT_EMAIL } from "@/types";
+import { LogEntity } from "@/types/proto/v1/logging_service";
+import { extractUserResourceName, extractUserUID } from "@/utils";
+import { useUserStore } from "@/store";
+
+const props = defineProps<{
+ activity: LogEntity;
+}>();
+
+const userEmail = computed(() => {
+ return extractUserResourceName(props.activity.creator);
+});
+
+const user = computed(() => {
+ return useUserStore().getUserByEmail(userEmail.value);
+});
+
+const userId = computed(() => {
+ const username = user.value?.name ?? "";
+ return extractUserUID(username);
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionIcon.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionIcon.vue
new file mode 100644
index 0000000000..fa81ffcc89
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionIcon.vue
@@ -0,0 +1,233 @@
+<template>
+ <div class="relative">
+ <div v-if="icon == 'system'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <img class="mt-1" src="@/assets/logo-icon.svg" alt="Bytebase" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'avatar'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-white rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <PrincipalAvatar
+ :username="user?.title"
+ override-class="w-7 h-7 font-medium"
+ override-text-size="0.8rem"
+ />
+ </div>
+ </div>
+ <div v-else-if="icon == 'create'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-solid:plus-sm class="w-5 h-5 text-control" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'update'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-solid:pencil class="w-4 h-4 text-control" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'run' || icon == 'rollout'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-outline:play class="w-6 h-6 text-control" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'approve-review'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-outline:thumb-up class="w-5 h-5 text-control" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'reject-review'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-warning rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons:pause-solid class="w-5 h-5 text-white" />
+ </div>
+ </div>
+ <div v-else-if="icon == 're-request-review'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-white rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <PrincipalAvatar
+ :username="user?.title"
+ override-class="w-7 h-7 font-medium"
+ override-text-size="0.8rem"
+ />
+ </div>
+ </div>
+ <div v-else-if="icon == 'cancel'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-outline:minus class="w-5 h-5 text-control" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'fail'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-white rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-outline:exclamation-circle class="w-6 h-6 text-error" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'complete'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-white rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-outline:check-circle class="w-6 h-6 text-success" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'skip'" class="relative pl-1">
+ <div
+ class="w-6 h-6 bg-gray-200 rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <SkipIcon class="w-5 h-5 text-gray-500" />
+ </div>
+ </div>
+ <div v-else-if="icon == 'commit'" class="relative pl-0.5">
+ <div
+ class="w-7 h-7 bg-control-bg rounded-full ring-4 ring-white flex items-center justify-center"
+ >
+ <heroicons-outline:code class="w-5 h-5 text-control" />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import {
+ ActivityIssueCommentCreatePayload,
+ ActivityStageStatusUpdatePayload,
+ ActivityTaskStatusUpdatePayload,
+ SYSTEM_BOT_EMAIL,
+} from "@/types";
+import PrincipalAvatar from "@/components/PrincipalAvatar.vue";
+import { SkipIcon } from "@/components/Icon";
+import { LogEntity, LogEntity_Action } from "@/types/proto/v1/logging_service";
+import { extractUserResourceName } from "@/utils";
+import { useUserStore } from "@/store";
+
+type ActionIconType =
+ | "avatar"
+ | "system"
+ | "create"
+ | "update"
+ | "run"
+ | "approve-review"
+ | "reject-review"
+ | "re-request-review"
+ | "rollout"
+ | "cancel"
+ | "fail"
+ | "complete"
+ | "skip"
+ | "commit";
+
+const props = defineProps<{
+ activity: LogEntity;
+}>();
+
+const user = computed(() => {
+ const email = extractUserResourceName(props.activity.creator);
+ return useUserStore().getUserByEmail(email);
+});
+
+const icon = computed((): ActionIconType => {
+ const { activity } = props;
+ if (activity.action == LogEntity_Action.ACTION_ISSUE_CREATE) {
+ return "create";
+ } else if (activity.action == LogEntity_Action.ACTION_ISSUE_FIELD_UPDATE) {
+ return "update";
+ } else if (
+ activity.action == LogEntity_Action.ACTION_PIPELINE_TASK_STATUS_UPDATE
+ ) {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityTaskStatusUpdatePayload;
+ switch (payload.newStatus) {
+ case "PENDING": {
+ if (payload.oldStatus == "RUNNING") {
+ return "cancel";
+ } else if (payload.oldStatus == "PENDING_APPROVAL") {
+ return "rollout";
+ }
+ break;
+ }
+ case "CANCELED": {
+ return "cancel";
+ }
+ case "RUNNING": {
+ return "run";
+ }
+ case "DONE": {
+ if (payload.oldStatus === "RUNNING") {
+ return "complete";
+ } else {
+ return "skip";
+ }
+ }
+ case "FAILED": {
+ return "fail";
+ }
+ case "PENDING_APPROVAL": {
+ return "avatar"; // stale approval dismissed.
+ }
+ }
+ } else if (
+ activity.action == LogEntity_Action.ACTION_PIPELINE_STAGE_STATUS_UPDATE
+ ) {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityStageStatusUpdatePayload;
+ switch (payload.stageStatusUpdateType) {
+ case "BEGIN": {
+ return "run";
+ }
+ case "END": {
+ return "complete";
+ }
+ }
+ } else if (
+ activity.action == LogEntity_Action.ACTION_PIPELINE_TASK_FILE_COMMIT
+ ) {
+ return "commit";
+ } else if (
+ activity.action == LogEntity_Action.ACTION_PIPELINE_TASK_STATEMENT_UPDATE
+ ) {
+ return "update";
+ } else if (
+ activity.action ==
+ LogEntity_Action.ACTION_PIPELINE_TASK_EARLIEST_ALLOWED_TIME_UPDATE
+ ) {
+ return "update";
+ } else if (activity.action === LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE) {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityIssueCommentCreatePayload;
+ if (payload.approvalEvent) {
+ const { status } = payload.approvalEvent;
+ switch (status) {
+ case "APPROVED":
+ return "approve-review";
+ case "REJECTED":
+ return "reject-review";
+ case "PENDING":
+ return "re-request-review";
+ }
+ }
+ }
+
+ return extractUserResourceName(activity.creator) == SYSTEM_BOT_EMAIL
+ ? "system"
+ : "avatar";
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionSentence.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionSentence.vue
new file mode 100644
index 0000000000..d9000904f4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActionSentence.vue
@@ -0,0 +1,314 @@
+<template>
+ <Renderer />
+</template>
+
+<script lang="ts" setup>
+import { defineComponent, h, watch } from "vue";
+import dayjs from "dayjs";
+import { Translation, useI18n } from "vue-i18n";
+
+import {
+ ActivityIssueCommentCreatePayload,
+ ActivityStageStatusUpdatePayload,
+ ActivityTaskEarliestAllowedTimeUpdatePayload,
+ ActivityTaskFileCommitPayload,
+ ActivityTaskStatementUpdatePayload,
+ ActivityTaskStatusUpdatePayload,
+ ComposedIssue,
+ SYSTEM_BOT_EMAIL,
+ UNKNOWN_ID,
+} from "@/types";
+import {
+ findStageByUID,
+ findTaskByUID,
+ issueActivityActionSentence,
+} from "@/utils";
+import { useSheetV1Store, useSheetStatementByUID } from "@/store";
+import TaskName from "./TaskName.vue";
+import TextOverflowPopover from "@/components/misc/TextOverflowPopover.vue";
+import StageName from "./StageName.vue";
+import { LogEntity, LogEntity_Action } from "@/types/proto/v1/logging_service";
+import { extractUserResourceName } from "@/utils";
+
+type RenderedContent = string | ReturnType<typeof h>;
+
+const props = defineProps<{
+ activity: LogEntity;
+ issue: ComposedIssue;
+}>();
+
+const { t } = useI18n();
+const sheetV1Store = useSheetV1Store();
+
+const renderActionSentence = () => {
+ const renderSpan = (content: string, props?: object) => {
+ return h("span", props, content);
+ };
+
+ const { activity, issue } = props;
+ if (activity.resource.startsWith("issues")) {
+ if (activity.action === LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE) {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityIssueCommentCreatePayload;
+ if (payload.externalApprovalEvent) {
+ if (payload.externalApprovalEvent.action == "REJECT") {
+ let imName = "";
+ switch (payload.externalApprovalEvent.type) {
+ case "bb.plugin.app.feishu":
+ imName = t("common.feishu");
+ break;
+ }
+ return renderSpan(
+ t("activity.sentence.external-approval-rejected", {
+ stageName: payload.externalApprovalEvent.stageName,
+ imName: imName,
+ })
+ );
+ }
+ }
+ if (payload.approvalEvent) {
+ if (payload.approvalEvent) {
+ const { status } = payload.approvalEvent;
+ const dict: Record<typeof status, string> = {
+ APPROVED: t("custom-approval.issue-review.approved-issue"),
+ REJECTED: t("custom-approval.issue-review.sent-back-issue"),
+ PENDING: t("custom-approval.issue-review.re-requested-review"),
+ };
+ const verb = dict[status];
+ if (verb) {
+ return renderSpan(maybeAutomaticallyVerb(activity, verb));
+ }
+ }
+ }
+ }
+
+ const [tid, params] = issueActivityActionSentence(activity);
+ return renderSpan(t(tid, params));
+ }
+ switch (activity.action) {
+ case LogEntity_Action.ACTION_PIPELINE_TASK_STATUS_UPDATE: {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityTaskStatusUpdatePayload;
+ if (payload.newStatus === "PENDING_APPROVAL") {
+ // stale approval dismissed.
+
+ const task = findTaskByUID(issue.rolloutEntity, String(payload.taskId));
+ const taskName = t("activity.sentence.task-name", {
+ name: task.title,
+ });
+ return t("activity.sentence.dismissed-stale-approval", {
+ task: taskName,
+ });
+ }
+ const params: VerbTypeTarget = {
+ activity,
+ verb: "",
+ type: t("common.task"),
+ target: "",
+ };
+ switch (payload.newStatus) {
+ case "PENDING": {
+ if (payload.oldStatus == "RUNNING") {
+ params.verb = t("activity.sentence.canceled");
+ } else if (payload.oldStatus == "PENDING_APPROVAL") {
+ params.verb = maybeAutomaticallyVerb(
+ activity,
+ t("activity.sentence.rolled-out")
+ );
+ }
+ break;
+ }
+ case "RUNNING": {
+ params.verb = t("activity.sentence.started");
+ break;
+ }
+ case "DONE": {
+ if (payload.oldStatus === "RUNNING") {
+ params.verb = t("activity.sentence.completed");
+ } else {
+ params.verb = t("activity.sentence.skipped");
+ }
+ break;
+ }
+ case "FAILED": {
+ params.verb = t("activity.sentence.failed");
+ break;
+ }
+ case "CANCELED": {
+ params.verb = t("activity.sentence.canceled");
+ break;
+ }
+ default:
+ params.verb = t("activity.sentence.changed");
+ }
+ const task = findTaskByUID(issue.rolloutEntity, String(payload.taskId));
+ if (task) {
+ params.target = h(TaskName, { issue, task });
+ }
+ return renderVerbTypeTarget(params, {
+ tag: "span",
+ });
+ }
+ case LogEntity_Action.ACTION_PIPELINE_STAGE_STATUS_UPDATE: {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityStageStatusUpdatePayload;
+ const stage = findStageByUID(
+ issue.rolloutEntity,
+ String(payload.stageId)
+ );
+ const params: VerbTypeTarget = {
+ activity,
+ verb: "",
+ type: t("common.stage"),
+ target: h(StageName, { stage, issue }),
+ };
+ switch (payload.stageStatusUpdateType) {
+ case "BEGIN":
+ params.verb = maybeAutomaticallyVerb(
+ activity,
+ t("activity.sentence.started")
+ );
+ break;
+ case "END":
+ params.verb = t("activity.sentence.completed");
+ break;
+ default:
+ params.verb = t("activity.sentence.changed");
+ break;
+ }
+ return renderVerbTypeTarget(params, {
+ tag: "span",
+ });
+ }
+ case LogEntity_Action.ACTION_PIPELINE_TASK_FILE_COMMIT: {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityTaskFileCommitPayload;
+ // return `committed ${payload.filePath} to ${payload.branch}@${payload.repositoryFullPath}`;
+ return t("activity.sentence.committed-to-at", {
+ file: payload.filePath,
+ branch: payload.branch,
+ repo: payload.repositoryFullPath,
+ });
+ }
+ case LogEntity_Action.ACTION_PIPELINE_TASK_STATEMENT_UPDATE: {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityTaskStatementUpdatePayload;
+ const oldStatement =
+ useSheetStatementByUID(String(payload.oldSheetId || UNKNOWN_ID))
+ .value || payload.oldStatement;
+ const newStatement =
+ useSheetStatementByUID(String(payload.newSheetId || UNKNOWN_ID))
+ .value || payload.newStatement;
+ return h(
+ "span",
+ {},
+ h(
+ Translation,
+ {
+ keypath: "activity.sentence.changed-from-to",
+ },
+ {
+ name: () => "SQL",
+ oldValue: () => renderStatement(oldStatement),
+ newValue: () => renderStatement(newStatement),
+ }
+ )
+ );
+ }
+ case LogEntity_Action.ACTION_PIPELINE_TASK_EARLIEST_ALLOWED_TIME_UPDATE: {
+ const payload = JSON.parse(
+ activity.payload
+ ) as ActivityTaskEarliestAllowedTimeUpdatePayload;
+ const newVal = payload.newEarliestAllowedTs;
+ const oldVal = payload.oldEarliestAllowedTs;
+ return t("activity.sentence.changed-from-to", {
+ name: "earliest allowed time",
+ oldValue: oldVal ? dayjs(oldVal * 1000) : "Unset",
+ newValue: newVal ? dayjs(newVal * 1000) : "Unset",
+ });
+ }
+ }
+ return "";
+};
+
+const maybeAutomaticallyVerb = (activity: LogEntity, verb: string): string => {
+ if (extractUserResourceName(activity.creator) !== SYSTEM_BOT_EMAIL) {
+ return verb;
+ }
+ return t("activity.sentence.xxx-automatically", {
+ verb,
+ });
+};
+
+type VerbTypeTarget = {
+ activity: LogEntity;
+ verb: RenderedContent;
+ type: RenderedContent;
+ target?: RenderedContent;
+};
+
+const renderVerbTypeTarget = (params: VerbTypeTarget, props: object = {}) => {
+ const keypath =
+ extractUserResourceName(params.activity.creator) === SYSTEM_BOT_EMAIL
+ ? "activity.sentence.verb-type-target-by-system-bot"
+ : "activity.sentence.verb-type-target-by-people";
+ return h(
+ Translation,
+ {
+ ...props,
+ keypath,
+ },
+ {
+ verb: () => params.verb,
+ type: () => params.type,
+ target: () => params.target,
+ }
+ );
+};
+
+const Renderer = defineComponent({
+ name: "ActionSentenceRenderer",
+ render: renderActionSentence,
+});
+
+const renderStatement = (content: string) => {
+ return h(TextOverflowPopover, {
+ statement: content,
+ maxLength: 50,
+ width: 400,
+ contentClass: "text-main",
+ });
+};
+
+watch(
+ () => props.activity,
+ async () => {
+ const activity = props.activity;
+ // Prepare sheet data for rendering.
+ if (
+ activity.action === LogEntity_Action.ACTION_PIPELINE_TASK_STATEMENT_UPDATE
+ ) {
+ sheetV1Store.getOrFetchSheetByUID(
+ String(
+ (JSON.parse(activity.payload) as ActivityTaskStatementUpdatePayload)
+ .newSheetId || UNKNOWN_ID
+ )
+ );
+ sheetV1Store.getOrFetchSheetByUID(
+ String(
+ (JSON.parse(activity.payload) as ActivityTaskStatementUpdatePayload)
+ .oldSheetId || UNKNOWN_ID
+ )
+ );
+ }
+ },
+ {
+ immediate: true,
+ }
+);
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActivityAction.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActivityAction.vue
new file mode 100644
index 0000000000..cc900bc7d4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActivityAction.vue
@@ -0,0 +1,92 @@
+<template>
+ <div class="ml-3 min-w-0 flex-1">
+ <div class="min-w-0 flex-1 pt-1 flex justify-between">
+ <div class="text-sm text-control-light space-x-1">
+ <ActionCreator
+ v-if="
+ extractUserResourceName(activity.creator) !== SYSTEM_BOT_EMAIL ||
+ activity.action === LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE
+ "
+ :activity="activity"
+ />
+
+ <ActionSentence :issue="issue" :activity="activity" />
+
+ <HumanizeTs
+ :ts="(activity.createTime?.getTime() ?? 0) / 1000"
+ class="ml-1"
+ />
+
+ <span
+ v-if="
+ activity.createTime?.getTime() !== activity.updateTime?.getTime() &&
+ activity.action == LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE
+ "
+ >
+ <span>({{ $t("common.edited") }}</span>
+ <HumanizeTs
+ :ts="(activity.updateTime?.getTime() ?? 0) / 1000"
+ class="ml-1"
+ />)
+ </span>
+
+ <span
+ v-if="similar.length > 0"
+ class="text-sm font-normal text-gray-400 ml-1"
+ >
+ {{
+ $t("activity.n-similar-activities", {
+ count: similar.length + 1,
+ })
+ }}
+ </span>
+ </div>
+
+ <slot name="subject-suffix"></slot>
+ </div>
+ <div class="mt-2 text-sm text-control whitespace-pre-wrap">
+ <slot name="comment" />
+
+ <template
+ v-if="
+ activity.action == LogEntity_Action.ACTION_PIPELINE_TASK_FILE_COMMIT
+ "
+ >
+ <a
+ :href="fileCommitActivityUrl(activity)"
+ target="__blank"
+ class="normal-link flex flex-row items-center"
+ >
+ {{ $t("issue.view-commit") }}
+ <heroicons-outline:external-link class="w-4 h-4" />
+ </a>
+ </template>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import {
+ ComposedIssue,
+ ActivityTaskFileCommitPayload,
+ SYSTEM_BOT_EMAIL,
+} from "@/types";
+import ActionCreator from "./ActionCreator.vue";
+import ActionSentence from "./ActionSentence.vue";
+import { LogEntity, LogEntity_Action } from "@/types/proto/v1/logging_service";
+import { extractUserResourceName } from "@/utils";
+
+defineProps<{
+ issue: ComposedIssue;
+ index: number;
+ activity: LogEntity;
+ similar: LogEntity[];
+}>();
+
+const fileCommitActivityUrl = (activity: LogEntity) => {
+ const payload = JSON.parse(activity.payload) as ActivityTaskFileCommitPayload;
+ if (payload.vcsInstanceUrl.includes("https://github.com"))
+ return `${payload.vcsInstanceUrl}/${payload.repositoryFullPath}/commit/${payload.commitId}`;
+ return `${payload.vcsInstanceUrl}/${payload.repositoryFullPath}/-/commit/${payload.commitId}`;
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActivityItem.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActivityItem.vue
new file mode 100644
index 0000000000..243c6be3a4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/ActivityItem.vue
@@ -0,0 +1,45 @@
+<template>
+ <li>
+ <div :id="`#${activity.name}`" class="relative pb-4">
+ <span
+ v-if="index !== activityList.length - 1"
+ class="absolute left-4 -ml-px h-full w-0.5 bg-block-border"
+ aria-hidden="true"
+ ></span>
+ <div class="relative flex items-start">
+ <ActionIcon :activity="activity" />
+
+ <ActivityAction
+ :issue="issue"
+ :index="index"
+ :activity="activity"
+ :similar="similar"
+ >
+ <template #subject-suffix>
+ <slot name="subject-suffix" />
+ </template>
+
+ <template #comment>
+ <slot name="comment" />
+ </template>
+ </ActivityAction>
+ </div>
+ </div>
+ </li>
+</template>
+
+<script lang="ts" setup>
+import { ComposedIssue } from "@/types";
+import ActionIcon from "./ActionIcon.vue";
+import ActivityAction from "./ActivityAction.vue";
+import { DistinctActivity } from "./common";
+import { LogEntity } from "@/types/proto/v1/logging_service";
+
+defineProps<{
+ issue: ComposedIssue;
+ activityList: DistinctActivity[];
+ index: number;
+ activity: LogEntity;
+ similar: LogEntity[];
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/StageName.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/StageName.vue
new file mode 100644
index 0000000000..ba2b08b530
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/StageName.vue
@@ -0,0 +1,15 @@
+<template>
+ <span class="font-medium text-main">
+ {{ stage.title }}
+ </span>
+</template>
+
+<script lang="ts" setup>
+import { ComposedIssue } from "@/types";
+import { Stage } from "@/types/proto/v1/rollout_service";
+
+defineProps<{
+ issue: ComposedIssue;
+ stage: Stage;
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/TaskName.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/TaskName.vue
new file mode 100644
index 0000000000..1e3576fabe
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/TaskName.vue
@@ -0,0 +1,63 @@
+<template>
+ <router-link
+ :to="link"
+ exact-active-class=""
+ class="font-medium text-main hover:border-b hover:border-b-main"
+ @click="toTop"
+ >
+ <span>{{ task.title }}</span>
+ <template v-if="schemaVersion">
+ <span class="ml-1 text-control-placeholder">(</span>
+ <span class="lowercase text-control-placeholder">{{
+ $t("common.schema-version")
+ }}</span>
+ <span class="ml-1 text-control-placeholder">{{ schemaVersion }}</span>
+ <span class="text-control-placeholder">)</span>
+ </template>
+ </router-link>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import scrollIntoView from "scroll-into-view-if-needed";
+import { ComposedIssue } from "@/types";
+import { Task } from "@/types/proto/v1/rollout_service";
+import { extractSchemaVersionFromTask } from "@/utils";
+import { stageForTask } from "@/components/IssueV1/logic";
+
+const props = defineProps<{
+ issue: ComposedIssue;
+ task: Task;
+}>();
+
+const schemaVersion = computed(() => {
+ return extractSchemaVersionFromTask(props.task);
+});
+
+const link = computed(() => {
+ const { issue, task } = props;
+
+ const query: Record<string, any> = {
+ task: task.uid,
+ };
+
+ const stage = stageForTask(issue, task);
+ if (stage) {
+ query.stage = stage.uid;
+ }
+
+ return {
+ path: `/issue/${issue.uid}`,
+ query,
+ };
+});
+
+const toTop = (e: Event) => {
+ const taskElem = document.querySelector(`[data-task-id="${props.task.uid}"]`);
+ if (taskElem) {
+ scrollIntoView(taskElem, {
+ scrollMode: "if-needed",
+ });
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/common.ts b/frontend/src/components/IssueV1/components/ActivitySection/Activity/common.ts
new file mode 100644
index 0000000000..3372d58712
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/common.ts
@@ -0,0 +1,51 @@
+import type {
+ ActivityTaskStatementUpdatePayload,
+ ActivityTaskStatusUpdatePayload,
+} from "@/types";
+import { LogEntity, LogEntity_Action } from "@/types/proto/v1/logging_service";
+
+export type DistinctActivity = {
+ activity: LogEntity;
+ similar: LogEntity[];
+};
+
+export const isSimilarActivity = (a: LogEntity, b: LogEntity): boolean => {
+ // Now, we recognize two "Change SQL from .... to ...." activities are similar
+ // when they have the same "from" and "to" values.
+ if (
+ a.action === LogEntity_Action.ACTION_PIPELINE_TASK_STATEMENT_UPDATE &&
+ a.action === b.action &&
+ a.resource === b.resource
+ ) {
+ const payloadA = JSON.parse(
+ a.payload
+ ) as ActivityTaskStatementUpdatePayload;
+ const payloadB = JSON.parse(
+ b.payload
+ ) as ActivityTaskStatementUpdatePayload;
+ if (
+ payloadA.oldStatement === payloadB.oldStatement &&
+ payloadB.newStatement === payloadB.newStatement
+ ) {
+ return true;
+ }
+ }
+
+ if (
+ a.action === LogEntity_Action.ACTION_PIPELINE_TASK_STATUS_UPDATE &&
+ a.action === b.action &&
+ a.resource === b.resource &&
+ a.creator === b.creator
+ ) {
+ const payloadA = JSON.parse(a.payload) as ActivityTaskStatusUpdatePayload;
+ const payloadB = JSON.parse(b.payload) as ActivityTaskStatusUpdatePayload;
+ if (
+ payloadA.oldStatus === payloadB.oldStatus &&
+ payloadB.newStatus === payloadB.newStatus
+ ) {
+ return true;
+ }
+ }
+
+ return false;
+};
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/index.ts b/frontend/src/components/IssueV1/components/ActivitySection/Activity/index.ts
new file mode 100644
index 0000000000..7b5f21c5ed
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/index.ts
@@ -0,0 +1,4 @@
+import ActivityItem from "./ActivityItem.vue";
+
+export * from "./common";
+export { ActivityItem };
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue b/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue
new file mode 100644
index 0000000000..e9db173957
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue
@@ -0,0 +1,290 @@
+<template>
+ <div class="flex flex-col gap-y-4">
+ <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="[]"
+ @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="currentUser" />
+ <span
+ class="absolute -bottom-0.5 -right-1 bg-white rounded-tl px-0.5 py-px"
+ >
+ <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="[]"
+ @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>
+</template>
+
+<script setup lang="ts">
+import { computed, onMounted, reactive, watch, watchEffect } from "vue";
+import { useRoute } from "vue-router";
+
+import { useActivityV1Store, useCurrentUserV1, useIssueV1Store } from "@/store";
+import { doSubscribeIssue, useIssueContext } from "../../logic";
+import { LogEntity, LogEntity_Action } from "@/types/proto/v1/logging_service";
+import {
+ DistinctActivity,
+ isSimilarActivity,
+} from "@/components/Issue/activity";
+import {
+ ActivityIssueCommentCreatePayload,
+ ActivityIssueFieldUpdatePayload,
+} from "@/types";
+import { IssueBuiltinFieldId } from "@/plugins";
+import { extractUserResourceName } from "@/utils";
+import { getLogId } from "@/store/modules/v1/common";
+import MarkdownEditor from "@/components/MarkdownEditor.vue";
+import { ActivityItem } from "./Activity";
+
+interface LocalState {
+ editCommentMode: boolean;
+ activeActivity?: LogEntity;
+ editComment: string;
+ newComment: string;
+}
+
+const activityV1Store = useActivityV1Store();
+const route = useRoute();
+
+const { issue } = useIssueContext();
+
+const state = reactive<LocalState>({
+ editCommentMode: false,
+ editComment: "",
+ newComment: "",
+});
+
+const currentUser = useCurrentUserV1();
+const issueV1Store = useIssueV1Store();
+
+const prepareActivityList = async () => {
+ await Promise.all([activityV1Store.fetchActivityListForIssueV1(issue.value)]);
+ // todo fetch issue list for markdown editing.
+};
+
+watchEffect(prepareActivityList);
+
+// Need to use computed to make list reactive to activity list changes.
+const activityList = computed((): DistinctActivity[] => {
+ const list = activityV1Store
+ .getActivityListByIssueV1(issue.value.uid)
+ .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 cancelEditComment = () => {
+ state.activeActivity = undefined;
+ state.editCommentMode = false;
+ state.editComment = "";
+};
+
+const doCreateComment = async (comment: string) => {
+ await issueV1Store.createIssueComment({
+ issueId: issue.value.uid,
+ comment,
+ });
+ state.newComment = "";
+
+ await prepareActivityList();
+
+ // // 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
+ try {
+ await doSubscribeIssue(issue.value, currentUser.value);
+ } catch {
+ // Nothing
+ }
+};
+
+const allowEditActivity = (activity: LogEntity) => {
+ if (activity.action !== LogEntity_Action.ACTION_ISSUE_COMMENT_CREATE) {
+ return false;
+ }
+ if (currentUser.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.uid,
+ 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/IssueV1/components/ActivitySection/ActivitySection.vue b/frontend/src/components/IssueV1/components/ActivitySection/ActivitySection.vue
new file mode 100644
index 0000000000..e6d4c4088b
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/ActivitySection.vue
@@ -0,0 +1,18 @@
+<template>
+ <div class="px-4 py-2 flex flex-col gap-y-4">
+ <div class="flex items-center justify-between">
+ <span class="textlabel">
+ {{ $t("common.activity") }}
+ </span>
+
+ <Subscribers />
+ </div>
+
+ <ActivityList />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import ActivityList from "./ActivityList.vue";
+import Subscribers from "./Subscribers";
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscribeButton.vue b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscribeButton.vue
new file mode 100644
index 0000000000..b6667e6aaa
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscribeButton.vue
@@ -0,0 +1,34 @@
+<template>
+ <NButton text :disabled="isLoading" @click="handleClick">
+ <BBSpin v-if="isLoading" class="w-4 h-4 mr-1" />
+ <span>
+ {{ isSubscribed ? $t("issue.unsubscribe") : $t("issue.subscribe") }}
+ </span>
+ </NButton>
+</template>
+
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { NButton } from "naive-ui";
+
+import { useCurrentUserV1 } from "@/store";
+import { useIssueContext, toggleSubscribeIssue } from "@/components/IssueV1";
+
+const { issue } = useIssueContext();
+const currentUser = useCurrentUserV1();
+const isLoading = ref(false);
+
+const isSubscribed = computed(() => {
+ return issue.value.subscribers.includes(`users/${currentUser.value.email}`);
+});
+
+const handleClick = async () => {
+ // TODO
+ try {
+ isLoading.value = true;
+ await toggleSubscribeIssue(issue.value, currentUser.value);
+ } finally {
+ isLoading.value = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscriberList.vue b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscriberList.vue
new file mode 100644
index 0000000000..c6bbec3ff6
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscriberList.vue
@@ -0,0 +1,147 @@
+<template>
+ <NPopselect
+ :multiple="true"
+ :value="issue.subscribers"
+ :options="options"
+ :render-label="renderLabel"
+ :scrollable="true"
+ trigger="click"
+ placement="left"
+ @update:show="onUpdateShow"
+ @update:value="onUpdateSubscribers"
+ >
+ <NButton
+ quaternary
+ :style="{
+ '--n-padding':
+ subscriberList.length === 0 ? '0 8px 0 8px' : '0 8px 0 12px',
+ }"
+ >
+ <div class="flex items-center gap-x-1">
+ <UserAvatar
+ v-for="user in subscriberList"
+ :key="user.name"
+ :user="user"
+ size="SMALL"
+ class="ml-[-18px] first:ml-0"
+ />
+ <heroicons:ellipsis-horizontal class="w-5 h-5" />
+ </div>
+ </NButton>
+
+ <template v-if="false" #action>
+ <NInput
+ ref="filterInputRef"
+ v-model:value="keyword"
+ :placeholder="$t('common.search-user')"
+ />
+ </template>
+ </NPopselect>
+</template>
+
+<script setup lang="ts">
+import { computed, h, nextTick, ref } from "vue";
+import {
+ NButton,
+ NPopselect,
+ NInput,
+ SelectOption,
+ SelectGroupOption,
+} from "naive-ui";
+
+import { updateIssueSubscribers, useIssueContext } from "@/components/IssueV1";
+import { useUserStore } from "@/store";
+import { unknownUser } from "@/types";
+import { extractUserResourceName } from "@/utils";
+import UserAvatar from "@/components/User/UserAvatar.vue";
+import { User, UserType } from "@/types/proto/v1/auth_service";
+import SubscriberListItem from "./SubscriberListItem.vue";
+
+type UserSelectOption = SelectOption & {
+ user: User;
+ value: string;
+};
+
+const userStore = useUserStore();
+const { issue } = useIssueContext();
+const keyword = ref("");
+const filterInputRef = ref<InstanceType<typeof NInput>>();
+
+const subscriberList = computed(() => {
+ return issue.value.subscribers.map((subscriber) => {
+ const email = extractUserResourceName(subscriber);
+ return userStore.getUserByEmail(email) ?? unknownUser();
+ });
+});
+
+const options = computed(() => {
+ const subscribers = new Set(issue.value.subscribers);
+ const options = userStore.userList
+ .filter((user) => user.userType === UserType.USER)
+ .map<UserSelectOption>((user) => ({
+ user,
+ value: `users/${user.email}`,
+ label: user.title,
+ }));
+
+ const subscribersOptions = options.filter((option) =>
+ subscribers.has(option.value)
+ );
+ const nonsubscribersOptions = options.filter(
+ (option) => !subscribers.has(option.value)
+ );
+ const groups: SelectGroupOption[] = [];
+ if (subscribersOptions.length > 0) {
+ groups.push({
+ type: "group",
+ key: "subscribers",
+ children: subscribersOptions,
+ render() {
+ return null;
+ },
+ });
+ }
+ if (nonsubscribersOptions.length > 0) {
+ groups.push({
+ type: "group",
+ key: "nonsubscribers",
+ children: nonsubscribersOptions,
+ render() {
+ if (subscribersOptions.length > 0) {
+ return h("hr", { class: "my-1" });
+ }
+ return null;
+ },
+ });
+ }
+
+ return groups;
+});
+
+const renderLabel = (option: SelectOption | SelectGroupOption) => {
+ if (option.type === "group") {
+ return null;
+ }
+
+ const { user } = option as UserSelectOption;
+
+ return h(SubscriberListItem, { user });
+};
+
+const onUpdateSubscribers = async (subscribers: string[]) => {
+ try {
+ await updateIssueSubscribers(issue.value, subscribers);
+ keyword.value = "";
+ } finally {
+ // Nothing
+ }
+};
+
+const onUpdateShow = (show: boolean) => {
+ if (show) {
+ nextTick(() => {
+ filterInputRef.value?.focus();
+ });
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscriberListItem.vue b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscriberListItem.vue
new file mode 100644
index 0000000000..c2cab18d89
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/SubscriberListItem.vue
@@ -0,0 +1,18 @@
+<template>
+ <div class="flex items-center gap-x-2 py-1">
+ <UserAvatar :user="user" size="NORMAL" />
+ <div class="flex flex-col w-[10rem]">
+ <span class="truncate">{{ user.title }}</span>
+ <span class="truncate text-control-light text-xs">{{ user.email }}</span>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import UserAvatar from "@/components/User/UserAvatar.vue";
+import { User } from "@/types/proto/v1/auth_service";
+
+defineProps<{
+ user: User;
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/Subscribers.vue b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/Subscribers.vue
new file mode 100644
index 0000000000..9e51b7acb9
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/Subscribers.vue
@@ -0,0 +1,11 @@
+<template>
+ <div class="flex items-center gap-x-2">
+ <SubscribeButton />
+ <SubscriberList />
+ </div>
+</template>
+
+<script setup lang="ts">
+import SubscribeButton from "./SubscribeButton.vue";
+import SubscriberList from "./SubscriberList.vue";
+</script>
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/index.ts b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/index.ts
new file mode 100644
index 0000000000..2df6c45abc
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/Subscribers/index.ts
@@ -0,0 +1,3 @@
+import Subscribers from "./Subscribers.vue";
+
+export default Subscribers;
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/index.ts b/frontend/src/components/IssueV1/components/ActivitySection/index.ts
new file mode 100644
index 0000000000..0fddb8247e
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/ActivitySection/index.ts
@@ -0,0 +1,3 @@
+import ActivitySection from "./ActivitySection.vue";
+
+export default ActivitySection;
diff --git a/frontend/src/components/IssueV1/components/BannerSection.vue b/frontend/src/components/IssueV1/components/BannerSection.vue
new file mode 100644
index 0000000000..9fa6dfc3cc
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/BannerSection.vue
@@ -0,0 +1,116 @@
+<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 { computed } from "vue";
+import dayjs from "dayjs";
+
+import { activeTaskInRollout, isDatabaseRelatedIssue } from "@/utils";
+import {
+ IssueStatus,
+ Issue_Approver_Status,
+} from "@/types/proto/v1/issue_service";
+import { useIssueContext } from "../logic";
+import { Task_Status } from "@/types/proto/v1/rollout_service";
+
+const { isCreating, issue, reviewContext } = useIssueContext();
+const { status: reviewStatus } = reviewContext;
+
+const showPendingReview = computed(() => {
+ if (isCreating.value) return false;
+ if (issue.value.status !== IssueStatus.OPEN) return false;
+ return reviewStatus.value === Issue_Approver_Status.PENDING;
+});
+
+const showRejectedReview = computed(() => {
+ if (isCreating.value) return false;
+ if (issue.value.status !== IssueStatus.OPEN) return false;
+ return reviewStatus.value === Issue_Approver_Status.REJECTED;
+});
+
+const showCancelBanner = computed(() => {
+ return issue.value.status === IssueStatus.CANCELED;
+});
+
+const showSuccessBanner = computed(() => {
+ return issue.value.status === IssueStatus.DONE;
+});
+
+const showPendingRollout = computed(() => {
+ if (issue.value.status !== IssueStatus.OPEN) return false;
+ if (!isDatabaseRelatedIssue(issue.value)) {
+ return false;
+ }
+
+ const task = activeTaskInRollout(issue.value.rolloutEntity);
+ return task.status === Task_Status.NOT_STARTED;
+});
+
+const showEarliestAllowedTimeBanner = computed(() => {
+ if (issue.value.status !== IssueStatus.OPEN) return false;
+ if (!isDatabaseRelatedIssue(issue.value)) {
+ return false;
+ }
+
+ const task = activeTaskInRollout(issue.value.rolloutEntity);
+
+ if (task.status !== Task_Status.PENDING) {
+ return false;
+ }
+
+ // const now = Math.floor(Date.now() / 1000);
+ // return task.earliestAllowedTs > now;
+ return false; // todo
+});
+
+const earliestAllowedTime = computed(() => {
+ // const task = activeTaskInRollout(issue.value.rolloutEntity);
+ const tz = "UTC" + dayjs().format("ZZ");
+ return dayjs().format(`YYYY-MM-DD HH:mm:ss ${tz}`);
+ // return dayjs(task.earliestAllowedTs * 1000).format(
+ // `YYYY-MM-DD HH:mm:ss ${tz}`
+ // );
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue b/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue
new file mode 100644
index 0000000000..10c1b35b40
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue
@@ -0,0 +1,187 @@
+<template>
+ <div class="px-4 py-2 flex flex-col gap-y-2">
+ <div class="flex items-center justify-between">
+ <span class="textlabel">
+ {{ title }}
+ </span>
+
+ <div v-if="!isCreating && allowEdit" class="flex items-center gap-x-2">
+ <NButton v-if="!state.isEditing" size="tiny" @click.prevent="beginEdit">
+ {{ $t("common.edit") }}
+ </NButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ :disabled="state.description === issue.description"
+ :loading="state.isUpdating"
+ @click.prevent="saveEdit"
+ >
+ {{ $t("common.save") }}
+ </NButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ quaternary
+ @click.prevent="cancelEdit"
+ >
+ {{ $t("common.cancel") }}
+ </NButton>
+ </div>
+ </div>
+
+ <div class="text-sm">
+ <NInput
+ v-if="isCreating || state.isEditing"
+ ref="inputRef"
+ v-model:value="state.description"
+ :placeholder="$t('issue.add-some-description')"
+ :autosize="{ minRows: 3, maxRows: 10 }"
+ :disabled="state.isUpdating"
+ :loading="state.isUpdating"
+ style="
+ width: 100%;
+ --n-placeholder-color: var(--color-control-placeholder);
+ "
+ type="textarea"
+ size="small"
+ @update:value="onDescriptionChange"
+ />
+ <div
+ v-else
+ class="min-h-[3rem] max-h-[12rem] whitespace-pre-wrap px-[10px] py-[4.5px] text-sm"
+ >
+ <template v-if="issue.description">
+ {{ issue.description }}
+ </template>
+ <span v-else class="text-control-placeholder">
+ {{ $t("issue.add-some-description") }}
+ </span>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, nextTick, reactive, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { NInput, NButton } from "naive-ui";
+
+import { useIssueContext } from "../../logic";
+import {
+ extractUserResourceName,
+ hasWorkspacePermissionV1,
+ isGrantRequestIssue,
+} from "@/utils";
+import { Issue, IssueStatus } from "@/types/proto/v1/issue_service";
+import { pushNotification, useCurrentUserV1 } from "@/store";
+import { issueServiceClient } from "@/grpcweb";
+
+type LocalState = {
+ isEditing: boolean;
+ isUpdating: boolean;
+ description: string;
+};
+
+const { t } = useI18n();
+const { isCreating, issue } = useIssueContext();
+const currentUser = useCurrentUserV1();
+
+const state = reactive<LocalState>({
+ isEditing: false,
+ isUpdating: false,
+ description: issue.value.description,
+});
+
+const inputRef = ref<InstanceType<typeof NInput>>();
+
+const title = computed(() => {
+ return isGrantRequestIssue(issue.value)
+ ? t("common.reason")
+ : t("common.description");
+});
+
+const allowEdit = computed(() => {
+ if (isCreating.value) {
+ return true;
+ }
+ if (issue.value.status !== IssueStatus.OPEN) {
+ return false;
+ }
+
+ if (
+ extractUserResourceName(issue.value.assignee) === currentUser.value.email ||
+ extractUserResourceName(issue.value.creator) === currentUser.value.email
+ ) {
+ // Allowed if current user is the assignee or creator.
+ return true;
+ }
+
+ if (
+ hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-issue",
+ currentUser.value.userRole
+ )
+ ) {
+ // Allowed if RBAC is enabled and current is DBA or workspace owner.
+ return true;
+ }
+ return false;
+});
+
+const onDescriptionChange = (description: string) => {
+ if (isCreating.value) {
+ issue.value.description = description;
+ }
+};
+
+const beginEdit = () => {
+ state.description = issue.value.description;
+ state.isEditing = true;
+ nextTick(() => {
+ inputRef.value?.focus();
+ });
+};
+
+const saveEdit = async () => {
+ try {
+ state.isUpdating = true;
+ const issuePatch = Issue.fromJSON({
+ ...issue.value,
+ description: state.description,
+ });
+ const updated = await issueServiceClient.updateIssue({
+ issue: issuePatch,
+ updateMask: ["description"],
+ });
+ Object.assign(issue.value, updated);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ state.isEditing = false;
+ } finally {
+ state.isUpdating = false;
+ }
+};
+
+const cancelEdit = () => {
+ state.description = issue.value.description;
+ state.isEditing = false;
+};
+
+// Reset the edit state after creating the issue.
+watch(isCreating, (curr, prev) => {
+ if (!curr && prev) {
+ state.isEditing = false;
+ }
+});
+
+watch(
+ () => issue.value,
+ (issue) => {
+ state.description = issue.description;
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/IssueV1/components/DescriptionSection/index.ts b/frontend/src/components/IssueV1/components/DescriptionSection/index.ts
new file mode 100644
index 0000000000..4652881be2
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/DescriptionSection/index.ts
@@ -0,0 +1,3 @@
+import DescriptionSection from "./DescriptionSection.vue";
+
+export default DescriptionSection;
diff --git a/frontend/src/components/IssueV1/components/Dialog/CommonDialog.vue b/frontend/src/components/IssueV1/components/Dialog/CommonDialog.vue
new file mode 100644
index 0000000000..e91ef881d9
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/CommonDialog.vue
@@ -0,0 +1,29 @@
+<template>
+ <BBModal
+ :title="title"
+ class="relative overflow-hidden !w-[30rem] !max-w-[30rem]"
+ header-class="overflow-hidden"
+ @close="$emit('close')"
+ >
+ <slot />
+ <div
+ v-if="loading"
+ class="absolute inset-0 flex items-center justify-center bg-white/50"
+ >
+ <BBSpin />
+ </div>
+ </BBModal>
+</template>
+
+<script setup lang="ts">
+import { BBModal, BBSpin } from "@/bbkit";
+
+defineProps<{
+ title: string;
+ loading: boolean;
+}>();
+
+defineEmits<{
+ (event: "close"): void;
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/ReviewDialog.vue b/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/ReviewDialog.vue
new file mode 100644
index 0000000000..d7cdd8dcaf
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/ReviewDialog.vue
@@ -0,0 +1,92 @@
+<template>
+ <CommonDialog :title="title" :loading="state.loading" @close="$emit('close')">
+ <ReviewForm
+ :action="action"
+ @cancel="$emit('close')"
+ @confirm="handleConfirm"
+ />
+ </CommonDialog>
+</template>
+
+<script setup lang="ts">
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { Issue_Approver_Status } from "@/types/proto/v1/issue_service";
+import {
+ IssueReviewAction,
+ targetReviewStatusForReviewAction,
+ useIssueContext,
+} from "@/components/IssueV1";
+import CommonDialog from "../CommonDialog.vue";
+import ReviewForm from "./ReviewForm.vue";
+import { issueServiceClient } from "@/grpcweb";
+
+type LocalState = {
+ loading: boolean;
+};
+
+const props = defineProps<{
+ action: IssueReviewAction;
+}>();
+
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { t } = useI18n();
+const state = reactive<LocalState>({
+ loading: false,
+});
+
+const { issue, events } = useIssueContext();
+
+const title = computed(() => {
+ switch (props.action) {
+ case "APPROVE":
+ return t("custom-approval.issue-review.approve-issue");
+ case "SEND_BACK":
+ return t("custom-approval.issue-review.send-back-issue");
+ case "RE_REQUEST":
+ return t("custom-approval.issue-review.re-request-review-issue");
+ }
+ return ""; // Make linter happy
+});
+
+const handleConfirm = async (
+ params: {
+ action: IssueReviewAction;
+ comment?: string;
+ },
+ onSuccess: () => void
+) => {
+ state.loading = true;
+ try {
+ const { action, comment = "" } = params;
+ const status = targetReviewStatusForReviewAction(action);
+ if (status === Issue_Approver_Status.APPROVED) {
+ await issueServiceClient.approveIssue({
+ name: issue.value.name,
+ comment,
+ });
+ onSuccess();
+ } else if (status === Issue_Approver_Status.PENDING) {
+ await issueServiceClient.requestIssue({
+ name: issue.value.name,
+ comment,
+ });
+ } else if (status === Issue_Approver_Status.REJECTED) {
+ await issueServiceClient.rejectIssue({
+ name: issue.value.name,
+ comment,
+ });
+ }
+
+ // notify the issue logic to update issue status
+ events.emit("status-changed", { eager: true });
+ } finally {
+ state.loading = false;
+ emit("close");
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/ReviewForm.vue b/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/ReviewForm.vue
new file mode 100644
index 0000000000..7f67abddb4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/ReviewForm.vue
@@ -0,0 +1,106 @@
+<template>
+ <div class="mt-2 flex flex-col gap-y-4">
+ <div class="text-sm">
+ {{ issue.title }}
+ </div>
+ <div class="flex flex-col gap-y-1">
+ <p class="textlabel">
+ {{ $t("common.comment") }}
+ <RequiredStar v-show="props.action === 'SEND_BACK'" />
+ </p>
+ <NInput
+ v-model:value="comment"
+ type="textarea"
+ :placeholder="$t('issue.leave-a-comment')"
+ :autosize="{
+ minRows: 3,
+ maxRows: 10,
+ }"
+ />
+ </div>
+ <div class="py-1 flex justify-end gap-x-3">
+ <NButton @click="$emit('cancel')">
+ {{ $t("common.cancel") }}
+ </NButton>
+ <NButton
+ :disabled="!allowConfirm"
+ v-bind="issueReviewActionButtonProps(action)"
+ @click="handleConfirm"
+ >
+ {{ issueReviewActionDisplayName(action) }}
+ </NButton>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+import { NButton, NInput } from "naive-ui";
+
+import RequiredStar from "@/components/RequiredStar.vue";
+import {
+ IssueReviewAction,
+ issueReviewActionButtonProps,
+ issueReviewActionDisplayName,
+ useIssueContext,
+} from "@/components/IssueV1";
+
+const props = defineProps<{
+ action: IssueReviewAction;
+}>();
+
+const emit = defineEmits<{
+ (event: "cancel"): void;
+ (
+ event: "confirm",
+ params: {
+ action: IssueReviewAction;
+ comment?: string;
+ },
+ onSuccess: () => void
+ ): void;
+}>();
+
+const { issue } = useIssueContext();
+const comment = ref("");
+
+const allowConfirm = computed(() => {
+ if (props.action === "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.action !== "APPROVE") {
+ 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",
+ {
+ action: props.action,
+ comment: comment.value,
+ },
+ onSuccess
+ );
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/index.ts b/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/index.ts
new file mode 100644
index 0000000000..970b1c5fb0
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/IssueReviewActionDialog/index.ts
@@ -0,0 +1,3 @@
+import IssueReviewActionDialog from "./ReviewDialog.vue";
+
+export default IssueReviewActionDialog;
diff --git a/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/Dialog.vue b/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/Dialog.vue
new file mode 100644
index 0000000000..e6086cc559
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/Dialog.vue
@@ -0,0 +1,77 @@
+<template>
+ <CommonDialog :title="title" :loading="state.loading" @close="$emit('close')">
+ <Form :action="action" @cancel="$emit('close')" @confirm="handleConfirm" />
+ </CommonDialog>
+</template>
+
+<script setup lang="ts">
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { IssueStatusAction, useIssueContext } from "@/components/IssueV1/logic";
+import CommonDialog from "../CommonDialog.vue";
+import Form from "./Form.vue";
+
+type LocalState = {
+ loading: boolean;
+};
+
+const props = defineProps<{
+ action: IssueStatusAction;
+}>();
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { t } = useI18n();
+const state = reactive<LocalState>({
+ loading: false,
+});
+const { events } = useIssueContext();
+
+const title = computed(() => {
+ const { action } = props;
+
+ switch (action) {
+ 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 handleConfirm = async (
+ action: IssueStatusAction,
+ comment: string | undefined
+) => {
+ state.loading = true;
+ // TODO
+ try {
+ await new Promise((r) => setTimeout(r, 1000));
+
+ // notify the issue logic to update issue status
+ events.emit("status-changed", { eager: true });
+ } finally {
+ 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");
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/Form.vue b/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/Form.vue
new file mode 100644
index 0000000000..78b559aaf5
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/Form.vue
@@ -0,0 +1,54 @@
+<template>
+ <div class="mt-2 flex flex-col gap-y-4">
+ <div class="text-sm">
+ {{ issue.title }}
+ </div>
+ <div class="flex flex-col gap-y-1">
+ <p class="textlabel">
+ {{ $t("common.comment") }}
+ </p>
+ <NInput
+ v-model:value="comment"
+ type="textarea"
+ :placeholder="$t('issue.leave-a-comment')"
+ :autosize="{
+ minRows: 3,
+ maxRows: 10,
+ }"
+ />
+ </div>
+ <div class="py-1 flex justify-end gap-x-3">
+ <NButton @click="$emit('cancel')">
+ {{ $t("common.cancel") }}
+ </NButton>
+ <NButton
+ v-bind="issueStatusActionButtonProps(action)"
+ @click="$emit('confirm', action, comment)"
+ >
+ {{ issueStatusActionDisplayName(action) }}
+ </NButton>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { ref } from "vue";
+import {
+ IssueStatusAction,
+ issueStatusActionButtonProps,
+ issueStatusActionDisplayName,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+
+defineProps<{
+ action: IssueStatusAction;
+}>();
+
+defineEmits<{
+ (event: "cancel"): void;
+ (event: "confirm", action: IssueStatusAction, comment?: string): void;
+}>();
+
+const { issue } = useIssueContext();
+const comment = ref("");
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/index.ts b/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/index.ts
new file mode 100644
index 0000000000..730b42ef1f
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/IssueStatusActionDialog/index.ts
@@ -0,0 +1,3 @@
+import IssueStatusActionDialog from "./Dialog.vue";
+
+export default IssueStatusActionDialog;
diff --git a/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/Dialog.vue b/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/Dialog.vue
new file mode 100644
index 0000000000..6129e909fd
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/Dialog.vue
@@ -0,0 +1,122 @@
+<template>
+ <CommonDialog :title="title" :loading="state.loading" @close="$emit('close')">
+ <Form
+ :action="action"
+ :task-list="taskList"
+ @cancel="$emit('close')"
+ @confirm="handleConfirm"
+ />
+ </CommonDialog>
+</template>
+
+<script setup lang="ts">
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+
+import {
+ TaskRolloutAction,
+ stageForTask,
+ taskRolloutActionDisplayName,
+ taskRunListForTask,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import CommonDialog from "../CommonDialog.vue";
+import Form from "./Form.vue";
+import {
+ Task,
+ TaskRun,
+ TaskRun_Status,
+} from "@/types/proto/v1/rollout_service";
+import { rolloutServiceClient } from "@/grpcweb";
+import { pushNotification } from "@/store";
+
+type LocalState = {
+ loading: boolean;
+};
+
+const props = defineProps<{
+ action: TaskRolloutAction;
+ taskList: Task[];
+}>();
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { t } = useI18n();
+const state = reactive<LocalState>({
+ loading: false,
+});
+const { issue, events } = useIssueContext();
+
+const title = computed(() => {
+ const action = taskRolloutActionDisplayName(props.action);
+ if (props.taskList.length > 1) {
+ return t("task.action-all-tasks-in-current-stage", { action });
+ }
+ return action;
+});
+
+const handleConfirm = async (
+ action: TaskRolloutAction,
+ comment: string | undefined
+) => {
+ state.loading = true;
+ try {
+ const stage = stageForTask(issue.value, props.taskList[0]);
+ if (!stage) return;
+ if (action === "ROLLOUT" || action === "RETRY" || action === "RESTART") {
+ await rolloutServiceClient.batchRunTasks({
+ parent: stage.name,
+ tasks: props.taskList.map((task) => task.name),
+ });
+ } else if (action === "SKIP") {
+ await rolloutServiceClient.batchSkipTasks({
+ parent: stage.name,
+ tasks: props.taskList.map((task) => task.name),
+ });
+ } else if (action === "CANCEL") {
+ const taskRunListToCancel = props.taskList
+ .map((task) => {
+ const taskRunList = taskRunListForTask(issue.value, task);
+ const currentRunningTaskRun = taskRunList.find(
+ (taskRun) => taskRun.status === TaskRun_Status.RUNNING
+ );
+ return currentRunningTaskRun;
+ })
+ .filter((taskRun) => taskRun !== undefined) as TaskRun[];
+ if (taskRunListToCancel.length > 0) {
+ await rolloutServiceClient.batchCancelTaskRuns({
+ parent: `${stage.name}/tasks/-`,
+ taskRuns: taskRunListToCancel.map((taskRun) => taskRun.name),
+ });
+ }
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: title.value,
+ });
+
+ // notify the issue logic to update issue status
+ events.emit("status-changed", { eager: true });
+ } finally {
+ 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");
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/Form.vue b/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/Form.vue
new file mode 100644
index 0000000000..c56fc71157
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/Form.vue
@@ -0,0 +1,92 @@
+<template>
+ <div class="mt-2 flex flex-col gap-y-4">
+ <div class="text-sm">
+ <label v-if="taskList.length > 1" 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.uid"
+ class="text-sm textinfolabel"
+ >
+ <span class="textinfolabel">
+ {{ item.task.title }}
+ </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>
+ <PlanCheckBar
+ v-if="taskList.length === 1 && action === 'ROLLOUT'"
+ :allow-run-checks="false"
+ :task="taskList[0]"
+ class="pt-2"
+ />
+ </div>
+ <div class="flex flex-col gap-y-1">
+ <p class="textlabel">
+ {{ $t("common.comment") }}
+ </p>
+ <NInput
+ v-model:value="comment"
+ type="textarea"
+ :placeholder="$t('issue.leave-a-comment')"
+ :autosize="{
+ minRows: 3,
+ maxRows: 10,
+ }"
+ />
+ </div>
+ <div class="py-1 flex justify-end gap-x-3">
+ <NButton @click="$emit('cancel')">
+ {{ $t("common.cancel") }}
+ </NButton>
+ <NButton
+ v-bind="taskRolloutActionButtonProps(action)"
+ @click="$emit('confirm', action, comment)"
+ >
+ {{ taskRolloutActionDialogButtonName(action, taskList) }}
+ </NButton>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+import { groupBy } from "lodash-es";
+import { Task } from "@/types/proto/v1/rollout_service";
+import {
+ TaskRolloutAction,
+ taskRolloutActionButtonProps,
+ taskRolloutActionDialogButtonName,
+} from "@/components/IssueV1/logic";
+import { PlanCheckBar } from "@/components/IssueV1/components/PlanCheckSection";
+
+const props = defineProps<{
+ action: TaskRolloutAction;
+ taskList: Task[];
+}>();
+
+defineEmits<{
+ (event: "cancel"): void;
+ (event: "confirm", action: TaskRolloutAction, comment?: string): void;
+}>();
+
+const comment = ref("");
+
+const distinctTaskList = computed(() => {
+ type DistinctTaskList = { task: Task; similar: Task[] };
+ const groups = groupBy(props.taskList, (task) => task.title);
+
+ return Object.keys(groups).map<DistinctTaskList>((taskName) => {
+ const [task, ...similar] = groups[taskName];
+ return { task, similar };
+ });
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/index.ts b/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/index.ts
new file mode 100644
index 0000000000..a48f196b60
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/TaskRolloutActionDialog/index.ts
@@ -0,0 +1,3 @@
+import TaskRolloutActionDialog from "./Dialog.vue";
+
+export default TaskRolloutActionDialog;
diff --git a/frontend/src/components/IssueV1/components/Dialog/index.ts b/frontend/src/components/IssueV1/components/Dialog/index.ts
new file mode 100644
index 0000000000..13ceb5f29c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/Dialog/index.ts
@@ -0,0 +1,9 @@
+import IssueReviewActionDialog from "./IssueReviewActionDialog";
+import IssueStatusActionDialog from "./IssueStatusActionDialog";
+import TaskRolloutActionDialog from "./TaskRolloutActionDialog";
+
+export {
+ IssueReviewActionDialog,
+ IssueStatusActionDialog,
+ TaskRolloutActionDialog,
+};
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/Actions.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/Actions.vue
new file mode 100644
index 0000000000..55b8641290
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/Actions.vue
@@ -0,0 +1,73 @@
+<template>
+ <div class="flex flex-col items-end">
+ <CreateButton v-if="actionType === 'CREATE'" />
+
+ <ExportCenterButton v-if="actionType === 'EXPORT-CENTER'" />
+
+ <SQLEditorButton v-if="actionType === 'SQL-EDITOR'" />
+
+ <IssueReviewButtonGroup v-if="actionType === 'REVIEW'" />
+
+ <CombinedRolloutButtonGroup v-if="actionType === 'ROLLOUT'" />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import { useCurrentUserV1 } from "@/store";
+import { isGrantRequestIssue } from "@/utils";
+import { useIssueContext } from "../../../logic";
+import { CreateButton } from "./create";
+import { IssueReviewButtonGroup } from "./review";
+import { CombinedRolloutButtonGroup } from "./rollout";
+import { ExportCenterButton, SQLEditorButton } from "./request";
+
+type ActionType =
+ | "CREATE"
+ | "EXPORT-CENTER"
+ | "SQL-EDITOR"
+ | "REVIEW"
+ | "ROLLOUT";
+
+const currentUser = useCurrentUserV1();
+const { isCreating, issue, reviewContext } = useIssueContext();
+const { done: reviewDone } = reviewContext;
+
+const isFinishedGrantRequestIssueByCurrentUser = computed(() => {
+ if (isCreating.value) return false;
+ if (issue.value.status !== IssueStatus.DONE) return false;
+ if (!isGrantRequestIssue(issue.value)) return false;
+
+ if (issue.value.creator !== currentUser.value.name) {
+ return false;
+ }
+ return true;
+});
+
+const actionType = computed((): ActionType => {
+ if (isCreating.value) {
+ return "CREATE";
+ }
+ if (isGrantRequestIssue(issue.value)) {
+ if (isFinishedGrantRequestIssueByCurrentUser.value) {
+ // eslint-disable-next-line
+ if (false) {
+ // TODO: check request export payload
+ // return issue.value.pa.payload.grantRequest?.role === PresetRoleType.EXPORTER;
+ return "EXPORT-CENTER";
+ }
+ // eslint-disable-next-line
+ if (false) {
+ // TODO: check request query payload
+ // return issue.value.payload.grantRequest?.role === PresetRoleType.QUERIER;
+ return "SQL-EDITOR";
+ }
+ }
+ return "REVIEW";
+ }
+
+ return reviewDone.value ? "ROLLOUT" : "REVIEW";
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/ExtraActionDropdownItem.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/ExtraActionDropdownItem.vue
new file mode 100644
index 0000000000..6212dafc7e
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/ExtraActionDropdownItem.vue
@@ -0,0 +1,48 @@
+<template>
+ <NTooltip :disabled="errors.length === 0" placement="left">
+ <template #trigger>
+ {{ option.label }}
+ </template>
+ <template #default>
+ <ErrorList :errors="errors" />
+ </template>
+ </NTooltip>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { NTooltip } from "naive-ui";
+
+import { ExtraActionOption } from "../types";
+import {
+ IssueStatusAction,
+ allowUserToApplyIssueStatusAction,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { ErrorList } from "@/components/IssueV1/components/common";
+import { useCurrentUserV1 } from "@/store";
+
+const props = defineProps<{
+ option: ExtraActionOption;
+}>();
+
+const { issue } = useIssueContext();
+const currentUser = useCurrentUserV1();
+
+const errors = computed(() => {
+ const errors: string[] = [];
+ const { type, action } = props.option;
+ if (type === "ISSUE") {
+ if (
+ !allowUserToApplyIssueStatusAction(
+ issue.value,
+ currentUser.value,
+ action as IssueStatusAction
+ )
+ ) {
+ errors.push("You are not allowed to perform this action");
+ }
+ }
+ return errors;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/IssueStatusActionButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/IssueStatusActionButton.vue
new file mode 100644
index 0000000000..fecee9b3cf
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/IssueStatusActionButton.vue
@@ -0,0 +1,59 @@
+<template>
+ <NTooltip :disabled="errors.length === 0" placement="top">
+ <template #trigger>
+ <NButton
+ :disabled="errors.length > 0"
+ size="large"
+ tag="div"
+ v-bind="issueStatusActionButtonProps(action)"
+ @click.prevent="$emit('perform-action', action)"
+ >
+ {{ issueStatusActionDisplayName(action) }}
+ </NButton>
+ </template>
+
+ <template #default>
+ <ErrorList :errors="errors" />
+ </template>
+ </NTooltip>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { NTooltip, NButton } from "naive-ui";
+
+import {
+ IssueStatusAction,
+ allowUserToApplyIssueStatusAction,
+ issueStatusActionButtonProps,
+ issueStatusActionDisplayName,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { ErrorList } from "@/components/IssueV1/components/common";
+import { useCurrentUserV1 } from "@/store";
+
+const props = defineProps<{
+ action: IssueStatusAction;
+}>();
+
+defineEmits<{
+ (event: "perform-action", action: IssueStatusAction): void;
+}>();
+
+const { issue } = useIssueContext();
+const currentUser = useCurrentUserV1();
+
+const errors = computed(() => {
+ const errors: string[] = [];
+ if (
+ !allowUserToApplyIssueStatusAction(
+ issue.value,
+ currentUser.value,
+ props.action
+ )
+ ) {
+ errors.push("You are not allowed to perform this action.");
+ }
+ return errors;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/IssueStatusActionButtonGroup.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/IssueStatusActionButtonGroup.vue
new file mode 100644
index 0000000000..e8b3663f87
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/IssueStatusActionButtonGroup.vue
@@ -0,0 +1,136 @@
+<template>
+ <div v-if="displayMode === 'BUTTON'" class="flex items-center gap-x-2">
+ <IssueStatusActionButton
+ v-for="(action, index) in issueStatusActionList"
+ :key="index"
+ :action="action"
+ @perform-action="
+ (action) => events.emit('perform-issue-status-action', { action })
+ "
+ />
+
+ <NDropdown
+ v-if="extraActionList.length > 0"
+ trigger="click"
+ placement="bottom-end"
+ :options="extraActionList"
+ :render-option="renderDropdownOption"
+ @select="handleDropdownSelect"
+ >
+ <NButton :quaternary="true" size="large" style="--n-padding: 0 4px">
+ <heroicons:ellipsis-vertical class="w-6 h-6" />
+ </NButton>
+ </NDropdown>
+ </div>
+
+ <NDropdown
+ v-if="displayMode === 'DROPDOWN' && mergedDropdownActionList.length > 0"
+ trigger="click"
+ placement="bottom-end"
+ :options="mergedDropdownActionList"
+ :render-option="renderDropdownOption"
+ @select="handleDropdownSelect"
+ >
+ <NButton :quaternary="true" size="large" style="--n-padding: 0 4px">
+ <heroicons:ellipsis-vertical class="w-6 h-6" />
+ </NButton>
+ </NDropdown>
+</template>
+
+<script setup lang="ts">
+import { VNode, computed, h } from "vue";
+import { NButton, NDropdown, DropdownOption } from "naive-ui";
+
+import { Task } from "@/types/proto/v1/rollout_service";
+import { ExtraActionOption } from "../types";
+import {
+ IssueStatusAction,
+ TaskRolloutAction,
+ allowUserToApplyIssueStatusAction,
+ issueStatusActionDisplayName,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import IssueStatusActionButton from "./IssueStatusActionButton.vue";
+import { useCurrentUserV1 } from "@/store";
+import { DropdownItemWithErrorList } from "@/components/IssueV1/components/common";
+
+const props = defineProps<{
+ displayMode: "BUTTON" | "DROPDOWN";
+ issueStatusActionList: IssueStatusAction[];
+ extraActionList: ExtraActionOption[];
+}>();
+
+const { issue, events } = useIssueContext();
+const currentUser = useCurrentUserV1();
+
+const issueStatusActionDropdownOptions = computed(() => {
+ return props.issueStatusActionList.map<ExtraActionOption>((action) => {
+ return {
+ key: action,
+ label: issueStatusActionDisplayName(action),
+ type: "ISSUE",
+ action: action,
+ target: issue.value,
+ disabled: !allowUserToApplyIssueStatusAction(
+ issue.value,
+ currentUser.value,
+ action
+ ),
+ };
+ });
+});
+
+const mergedDropdownActionList = computed(() => {
+ if (issueStatusActionDropdownOptions.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 [
+ ...issueStatusActionDropdownOptions.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 renderDropdownOption = ({
+ node,
+ option,
+}: {
+ node: VNode;
+ option: DropdownOption;
+}) => {
+ const errors = option.disabled
+ ? ["You are not allowed to perform this action"]
+ : [];
+ return h(
+ DropdownItemWithErrorList,
+ {
+ errors,
+ placement: "left",
+ },
+ {
+ default: () => node,
+ }
+ );
+};
+
+const handleDropdownSelect = (key: string, dropdownOption: DropdownOption) => {
+ const option = dropdownOption as ExtraActionOption;
+ if (option.type === "ISSUE") {
+ events.emit("perform-issue-status-action", {
+ action: option.action as IssueStatusAction,
+ });
+ }
+ if (option.type === "TASK-BATCH") {
+ events.emit("perform-task-rollout-action", {
+ action: option.action as TaskRolloutAction,
+ tasks: option.target as Task[],
+ });
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/index.ts
new file mode 100644
index 0000000000..543cf7568b
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/IssueStatusActionButtonGroup/index.ts
@@ -0,0 +1,3 @@
+import IssueStatusActionButtonGroup from "./IssueStatusActionButtonGroup.vue";
+
+export default IssueStatusActionButtonGroup;
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/index.ts
new file mode 100644
index 0000000000..0f556f0e6a
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/index.ts
@@ -0,0 +1,4 @@
+import IssueStatusActionButtonGroup from "./IssueStatusActionButtonGroup";
+
+export * from "./types";
+export { IssueStatusActionButtonGroup };
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/types.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/types.ts
new file mode 100644
index 0000000000..48d300ada4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/common/types.ts
@@ -0,0 +1,22 @@
+import { DropdownOption } from "naive-ui";
+import { Task } from "@/types/proto/v1/rollout_service";
+import { ComposedIssue } from "@/types";
+import {
+ IssueStatusAction,
+ TaskRolloutAction,
+} from "@/components/IssueV1/logic";
+
+export type ExtraAction<T extends "ISSUE" | "TASK" | "TASK-BATCH"> = {
+ type: T;
+ action: T extends "ISSUE" ? IssueStatusAction : TaskRolloutAction;
+ target: T extends "ISSUE"
+ ? ComposedIssue
+ : 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/IssueV1/components/HeaderSection/Actions/create/CreateButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/create/CreateButton.vue
new file mode 100644
index 0000000000..06cde22021
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/create/CreateButton.vue
@@ -0,0 +1,140 @@
+<template>
+ <NTooltip :disabled="issueCreateErrorList.length === 0" placement="top">
+ <template #trigger>
+ <NButton
+ type="primary"
+ size="large"
+ tag="div"
+ :disabled="issueCreateErrorList.length > 0"
+ @click="doCreateIssue"
+ >
+ {{ $t("common.create") }}
+ </NButton>
+ </template>
+
+ <template #default>
+ <ErrorList :errors="issueCreateErrorList" />
+ </template>
+ </NTooltip>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { NTooltip, NButton } from "naive-ui";
+
+import { Plan_ChangeDatabaseConfig } from "@/types/proto/v1/rollout_service";
+import { Sheet } from "@/types/proto/v1/sheet_service";
+import { useSheetV1Store } from "@/store";
+import {
+ getLocalSheetByName,
+ isValidStage,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { ErrorList } from "@/components/IssueV1/components/common";
+import { issueServiceClient, rolloutServiceClient } from "@/grpcweb";
+import { extractSheetUID } from "@/utils";
+import { ComposedIssue } from "@/types";
+import { useRouter } from "vue-router";
+
+const router = useRouter();
+const { issue } = useIssueContext();
+
+const issueCreateErrorList = computed(() => {
+ const errorList: string[] = [];
+ if (!issue.value.title.trim()) {
+ errorList.push("Missing issue title");
+ }
+ if (issue.value.rolloutEntity.stages.some((stage) => !isValidStage(stage))) {
+ errorList.push("Missing SQL statement in some stages");
+ }
+ if (!issue.value.assignee) {
+ errorList.push("Assignee is required");
+ }
+ return errorList;
+});
+
+const doCreateIssue = async () => {
+ await createSheets();
+ const createdPlan = await createPlan();
+ if (!createdPlan) return;
+
+ issue.value.plan = createdPlan.name;
+ issue.value.planEntity = createdPlan;
+
+ const createdIssue = await issueServiceClient.createIssue({
+ parent: issue.value.project,
+ issue: issue.value,
+ });
+
+ const createdRollout = await rolloutServiceClient.createRollout({
+ parent: issue.value.project,
+ plan: createdPlan.name,
+ });
+
+ createdIssue.rollout = createdRollout.name;
+
+ const composedIssue: ComposedIssue = {
+ ...issue.value,
+ ...createdIssue,
+ planEntity: createdPlan,
+ rolloutEntity: createdRollout,
+ };
+
+ router.push(`/issue/${composedIssue.uid}`);
+
+ return composedIssue;
+};
+
+// Create sheets for spec configs and update their resource names.
+const createSheets = async () => {
+ const steps = issue.value.planEntity?.steps ?? [];
+ const flattenSpecList = steps.flatMap((step) => {
+ return step.specs;
+ });
+
+ const configWithSheetList: Plan_ChangeDatabaseConfig[] = [];
+ const pendingCreateSheetMap = new Map<string, Sheet>();
+
+ for (let i = 0; i < flattenSpecList.length; i++) {
+ const spec = flattenSpecList[i];
+ const config = spec.changeDatabaseConfig;
+ if (!config) continue;
+ configWithSheetList.push(config);
+ if (pendingCreateSheetMap.has(config.sheet)) continue;
+ const uid = extractSheetUID(config.sheet);
+ if (uid.startsWith("-")) {
+ // The sheet is pending create
+ const sheet = getLocalSheetByName(config.sheet);
+ sheet.database = config.target;
+ pendingCreateSheetMap.set(sheet.name, sheet);
+ }
+ }
+ const pendingCreateSheetList = Array.from(pendingCreateSheetMap.values());
+ const sheetNameMap = new Map<string, string>();
+ for (let i = 0; i < pendingCreateSheetList.length; i++) {
+ const sheet = pendingCreateSheetList[i];
+ sheet.title = issue.value.title;
+ const createdSheet = await useSheetV1Store().createSheet(
+ issue.value.project,
+ sheet
+ );
+ sheetNameMap.set(sheet.name, createdSheet.name);
+ }
+ configWithSheetList.forEach((config) => {
+ const uid = extractSheetUID(config.sheet);
+ if (uid.startsWith("-")) {
+ config.sheet = sheetNameMap.get(config.sheet) ?? "";
+ }
+ });
+};
+
+const createPlan = async () => {
+ const plan = issue.value.planEntity;
+ if (!plan) return;
+ const createdPlan = await rolloutServiceClient.createPlan({
+ parent: issue.value.project,
+ plan,
+ });
+ return createdPlan;
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/create/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/create/index.ts
new file mode 100644
index 0000000000..b30ba24e7e
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/create/index.ts
@@ -0,0 +1,3 @@
+import CreateButton from "./CreateButton.vue";
+
+export { CreateButton };
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/index.ts
new file mode 100644
index 0000000000..9793717924
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/index.ts
@@ -0,0 +1,3 @@
+import Actions from "./Actions.vue";
+
+export default Actions;
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportCenterButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportCenterButton.vue
new file mode 100644
index 0000000000..c89ab3fdeb
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportCenterButton.vue
@@ -0,0 +1,25 @@
+<template>
+ <NButton type="primary" size="large" @click="toExportCenter">
+ <template #icon>
+ <heroicons-outline:download class="w-5 h-5" />
+ </template>
+
+ {{ $t("export-center.self") }}
+ </NButton>
+</template>
+
+<script setup lang="ts">
+import { useRouter } from "vue-router";
+
+import { useIssueContext } from "@/components/IssueV1";
+
+const router = useRouter();
+const { issue } = useIssueContext();
+
+const toExportCenter = () => {
+ router.push({
+ name: "workspace.export-center",
+ hash: `#${issue.value.uid}`,
+ });
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/SQLEditorButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/SQLEditorButton.vue
new file mode 100644
index 0000000000..6e31984fd3
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/SQLEditorButton.vue
@@ -0,0 +1,45 @@
+<template>
+ <NButton type="primary" size="large" @click="gotoSQLEditor">
+ <template #icon>
+ <heroicons-solid:terminal class="w-5 h-5" />
+ </template>
+ {{ $t("sql-editor.self") }}
+ </NButton>
+</template>
+
+<script setup lang="ts">
+import { NButton } from "naive-ui";
+
+const gotoSQLEditor = async () => {
+ alert("gogogo sql editor");
+ // 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/IssueV1/components/HeaderSection/Actions/request/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/index.ts
new file mode 100644
index 0000000000..bc69a8b39c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/index.ts
@@ -0,0 +1,4 @@
+import SQLEditorButton from "./SQLEditorButton.vue";
+import ExportCenterButton from "./ExportCenterButton.vue";
+
+export { SQLEditorButton, ExportCenterButton };
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/IssueReviewButtonGroup.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/IssueReviewButtonGroup.vue
new file mode 100644
index 0000000000..f0e5e7f96c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/IssueReviewButtonGroup.vue
@@ -0,0 +1,81 @@
+<template>
+ <div class="flex items-stretch gap-x-3">
+ <ReviewActionButton
+ v-for="action in issueReviewActionList"
+ :key="action"
+ :action="action"
+ @perform-action="
+ (action) => events.emit('perform-issue-review-action', { action })
+ "
+ />
+
+ <IssueStatusActionButtonGroup
+ :display-mode="issueReviewActionList.length > 0 ? 'DROPDOWN' : 'BUTTON'"
+ :issue-status-action-list="issueStatusActionList"
+ :extra-action-list="[]"
+ />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import { useCurrentUserV1 } from "@/store";
+import { Issue_Approver_Status } from "@/types/proto/v1/issue_service";
+import { extractUserResourceName } from "@/utils";
+import {
+ IssueReviewAction,
+ getApplicableIssueStatusActionList,
+ useIssueContext,
+} from "@/components/IssueV1";
+import { IssueStatusActionButtonGroup } from "../common";
+import ReviewActionButton from "./ReviewActionButton.vue";
+
+const currentUser = useCurrentUserV1();
+const { issue, phase, reviewContext, events } = useIssueContext();
+const { ready, status, done } = reviewContext;
+
+const shouldShowApproveOrReject = computed(() => {
+ if (phase.value !== "REVIEW") {
+ return false;
+ }
+
+ if (!ready.value) return false;
+ if (done.value) return false;
+
+ return true;
+});
+const shouldShowApprove = computed(() => {
+ if (!shouldShowApproveOrReject.value) return false;
+
+ return status.value === Issue_Approver_Status.PENDING;
+});
+const shouldShowReject = computed(() => {
+ if (!shouldShowApproveOrReject.value) return false;
+ return status.value === Issue_Approver_Status.PENDING;
+});
+const shouldShowReRequestReview = computed(() => {
+ return (
+ extractUserResourceName(issue.value.creator) === currentUser.value.email &&
+ status.value === Issue_Approver_Status.REJECTED
+ );
+});
+const issueReviewActionList = computed(() => {
+ const actionList: IssueReviewAction[] = [];
+ if (shouldShowReject.value) {
+ actionList.push("SEND_BACK");
+ }
+ if (shouldShowApprove.value) {
+ actionList.push("APPROVE");
+ }
+ if (shouldShowReRequestReview.value) {
+ actionList.push("RE_REQUEST");
+ }
+
+ return actionList;
+});
+
+const issueStatusActionList = computed(() => {
+ return getApplicableIssueStatusActionList(issue.value);
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/ReviewActionButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/ReviewActionButton.vue
new file mode 100644
index 0000000000..0c95c20ceb
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/ReviewActionButton.vue
@@ -0,0 +1,82 @@
+<template>
+ <NTooltip :disabled="errors.length === 0" placement="top">
+ <template #trigger>
+ <NButton
+ size="large"
+ tag="div"
+ :disabled="errors.length > 0"
+ v-bind="issueReviewActionButtonProps(action)"
+ @click="$emit('perform-action', action)"
+ >
+ {{ issueReviewActionDisplayName(action) }}
+ </NButton>
+ </template>
+ <template #default>
+ <ErrorList :errors="errors" />
+ </template>
+ </NTooltip>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { NButton, NTooltip } from "naive-ui";
+import { useI18n } from "vue-i18n";
+
+import {
+ IssueReviewAction,
+ issueReviewActionDisplayName,
+ issueReviewActionButtonProps,
+ allowUserToApplyReviewAction,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { ErrorList } from "@/components/IssueV1/components/common";
+import { useCurrentUserV1 } from "@/store";
+
+const props = defineProps<{
+ action: IssueReviewAction;
+}>();
+
+defineEmits<{
+ (event: "perform-action", action: IssueReviewAction): void;
+}>();
+
+const { t } = useI18n();
+const { issue, reviewContext } = useIssueContext();
+const currentUser = useCurrentUserV1();
+
+const allTaskChecksPassed = computed(() => {
+ // TODO
+ return true;
+ // 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 errors = computed(() => {
+ const errors: string[] = [];
+
+ if (
+ !allowUserToApplyReviewAction(
+ issue.value,
+ reviewContext,
+ currentUser.value,
+ props.action
+ )
+ ) {
+ errors.push("You are not allowed to perform this action.");
+ }
+ if (props.action === "APPROVE") {
+ if (!allTaskChecksPassed.value) {
+ errors.push(
+ t(
+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"
+ )
+ );
+ }
+ }
+ return errors;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/index.ts
new file mode 100644
index 0000000000..1ad1cd1161
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/review/index.ts
@@ -0,0 +1,3 @@
+import IssueReviewButtonGroup from "./IssueReviewButtonGroup.vue";
+
+export { IssueReviewButtonGroup };
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/CombinedRolloutButtonGroup.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/CombinedRolloutButtonGroup.vue
new file mode 100644
index 0000000000..4f819f13b5
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/CombinedRolloutButtonGroup.vue
@@ -0,0 +1,139 @@
+<template>
+ <div class="flex gap-x-3">
+ <RolloutActionButtonGroup
+ v-if="primaryTaskRolloutActionList.length > 0"
+ :task-rollout-action-list="primaryTaskRolloutActionList"
+ :stage-rollout-action-list="
+ stageRolloutActionList.map((item) => item.action)
+ "
+ @perform-action="performRolloutAction"
+ />
+
+ <IssueStatusActionButtonGroup
+ :display-mode="
+ primaryTaskRolloutActionList.length > 0 ? 'DROPDOWN' : 'BUTTON'
+ "
+ :issue-status-action-list="issueStatusActionList"
+ :extra-action-list="extraActionList"
+ />
+ </div>
+
+ <div class="issue-debug">
+ <div>taskRolloutActionList: {{ taskRolloutActionList }}</div>
+ <div>
+ stageRolloutActionList:
+ {{
+ stageRolloutActionList.map(
+ ({ action, tasks }) => `${action}(${tasks.map((t) => t.uid)})`
+ )
+ }}
+ </div>
+ <div>primaryTaskRolloutActionList: {{ primaryTaskRolloutActionList }}</div>
+ <div>issueStatusActionList: {{ issueStatusActionList }}</div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { asyncComputed } from "@vueuse/core";
+
+import {
+ PrimaryTaskRolloutActionList,
+ TaskRolloutAction,
+ allowUserToApplyTaskRolloutAction,
+ getApplicableIssueStatusActionList,
+ getApplicableStageRolloutActionList,
+ getApplicableTaskRolloutActionList,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { Task } from "@/types/proto/v1/rollout_service";
+import { useCurrentUserV1 } from "@/store";
+import RolloutActionButtonGroup from "./RolloutActionButtonGroup.vue";
+import { ExtraActionOption, IssueStatusActionButtonGroup } from "../common";
+import { RolloutAction } from "./common";
+
+const { t } = useI18n();
+const currentUser = useCurrentUserV1();
+const { issue, activeStage, activeTask, events } = useIssueContext();
+
+const issueStatusActionList = computed(() => {
+ return getApplicableIssueStatusActionList(issue.value);
+});
+
+const taskRolloutActionList = computed(() => {
+ return getApplicableTaskRolloutActionList(issue.value, activeTask.value);
+});
+
+const stageRolloutActionList = computed(() => {
+ return getApplicableStageRolloutActionList(
+ issue.value,
+ activeStage.value,
+ false /* !allowSkipPendingTasks */
+ );
+});
+
+const primaryTaskRolloutActionList = computed(() => {
+ return taskRolloutActionList.value.filter((action) =>
+ PrimaryTaskRolloutActionList.includes(action)
+ );
+});
+
+const allowUserToSkipTask = asyncComputed(async () => {
+ const skip = stageRolloutActionList.value.find(
+ (item) => item.action === "SKIP"
+ );
+ if (!skip) return false;
+ const allowed = await Promise.all(
+ skip.tasks.map((task) =>
+ allowUserToApplyTaskRolloutAction(
+ issue.value,
+ task,
+ currentUser.value,
+ "SKIP"
+ )
+ )
+ );
+ return allowed.every((allow) => allow);
+});
+
+const extraActionList = computed(() => {
+ const list: ExtraActionOption[] = [];
+ const skip = stageRolloutActionList.value.find(
+ (item) => item.action === "SKIP"
+ );
+ if (skip) {
+ list.push({
+ label: t("task.skip-failed-in-current-stage"),
+ key: "skip-failed-tasks-in-current-stage",
+ type: "TASK-BATCH",
+ action: "SKIP",
+ target: skip.tasks,
+ disabled: !allowUserToSkipTask.value,
+ });
+ }
+ return list;
+});
+
+const performRolloutAction = async (params: RolloutAction) => {
+ const { action, target } = params;
+ if (target === "TASK") {
+ return performBatchTaskAction(action, [activeTask.value]);
+ }
+ if (target === "STAGE") {
+ const actionItem = stageRolloutActionList.value.find(
+ (item) => item.action === action
+ );
+ if (actionItem) {
+ return performBatchTaskAction(action, actionItem.tasks);
+ }
+ }
+};
+
+const performBatchTaskAction = async (
+ action: TaskRolloutAction,
+ tasks: Task[]
+) => {
+ events.emit("perform-task-rollout-action", { action, tasks });
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/RolloutActionButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/RolloutActionButton.vue
new file mode 100644
index 0000000000..3e9917cc42
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/RolloutActionButton.vue
@@ -0,0 +1,120 @@
+<template>
+ <NTooltip :disabled="errors.length === 0" placement="top">
+ <template #trigger>
+ <ContextMenuButton
+ :preference-key="`bb-rollout-action-${action}`"
+ :action-list="actionList"
+ :default-action-key="`${action}-STAGE`"
+ @click="$emit('perform-action', ($event as RolloutButtonAction).params)"
+ />
+ </template>
+ <template #default>
+ <ErrorList :errors="errors" />
+ </template>
+ </NTooltip>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { asyncComputed } from "@vueuse/core";
+
+import { useCurrentUserV1 } from "@/store";
+import {
+ StageRolloutAction,
+ TaskRolloutAction,
+ allPlanChecksPassedForTask,
+ allowUserToApplyTaskRolloutAction,
+ taskRolloutActionButtonProps,
+ taskRolloutActionDisplayName,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { ErrorList } from "@/components/IssueV1/components/common";
+import { ContextMenuButton } from "@/components/v2";
+import { RolloutAction, RolloutButtonAction } from "./common";
+
+const props = defineProps<{
+ action: TaskRolloutAction;
+ stageRolloutActionList: StageRolloutAction[];
+}>();
+
+defineEmits<{
+ (event: "perform-action", action: RolloutAction): void;
+}>();
+
+const { t } = useI18n();
+const currentUser = useCurrentUserV1();
+const { issue, activeTask } = useIssueContext();
+
+const errors = asyncComputed(async () => {
+ const errors: string[] = [];
+ if (!allPlanChecksPassedForTask(issue.value, activeTask.value)) {
+ errors.push("Some checks failed");
+ }
+ if (
+ !(await allowUserToApplyTaskRolloutAction(
+ issue.value,
+ activeTask.value,
+ currentUser.value,
+ props.action
+ ))
+ ) {
+ errors.push("You are not the assignee of this issue");
+ }
+ return errors;
+}, []);
+
+// const errors = computed(() => {
+// const errors: string[] = [];
+// if (!allPlanChecksPassedForTask(issue.value, activeTask.value)) {
+// errors.push("Some checks failed.");
+// }
+// if (
+// !isUserAllowedToApplyTaskRolloutAction(
+// issue.value,
+// activeTask.value,
+// currentUser.value,
+// props.action
+// )
+// ) {
+// errors.push("You are not assignee of this issue.");
+// }
+// return errors;
+// });
+
+const actionList = computed(() => {
+ const { action } = props;
+
+ const text = taskRolloutActionDisplayName(action);
+ const actionProps: RolloutButtonAction["props"] = {
+ ...taskRolloutActionButtonProps(action),
+ size: "large",
+ tag: "div",
+ disabled: errors.value.length > 0,
+ };
+ const actionList: RolloutButtonAction[] = [
+ {
+ key: `${action}-TASK`,
+ text,
+ props: actionProps,
+ params: {
+ action,
+ target: "TASK",
+ },
+ },
+ ];
+ if (props.stageRolloutActionList.includes(action as any)) {
+ actionList.push({
+ key: `${action}-STAGE`,
+ text: t("issue.action-to-current-stage", { action: text }),
+ props: actionProps,
+ params: {
+ action,
+ target: "STAGE",
+ },
+ });
+ }
+
+ return actionList;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/RolloutActionButtonGroup.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/RolloutActionButtonGroup.vue
new file mode 100644
index 0000000000..6cf835f47d
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/RolloutActionButtonGroup.vue
@@ -0,0 +1,76 @@
+<template>
+ <div class="flex items-center gap-x-3">
+ <RolloutActionButton
+ v-for="action in taskRolloutActionList"
+ :key="action"
+ :action="action"
+ :stage-rollout-action-list="stageRolloutActionList"
+ @perform-action="$emit('perform-action', $event)"
+ />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import {
+ StageRolloutAction,
+ TaskRolloutAction,
+} from "@/components/IssueV1/logic";
+import RolloutActionButton from "./RolloutActionButton.vue";
+import { RolloutAction } from "./common";
+
+defineProps<{
+ taskRolloutActionList: TaskRolloutAction[];
+ stageRolloutActionList: StageRolloutAction[];
+}>();
+
+defineEmits<{
+ (event: "perform-action", action: RolloutAction): void;
+}>();
+
+// 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 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/IssueV1/components/HeaderSection/Actions/rollout/common.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/common.ts
new file mode 100644
index 0000000000..f18d16f35e
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/common.ts
@@ -0,0 +1,12 @@
+import {
+ StageRolloutAction,
+ TaskRolloutAction,
+} from "@/components/IssueV1/logic";
+import { ContextMenuButtonAction } from "@/components/v2";
+
+export type RolloutAction<T = "TASK" | "STAGE"> = {
+ target: T;
+ action: T extends "TASK" ? TaskRolloutAction : StageRolloutAction;
+};
+
+export type RolloutButtonAction = ContextMenuButtonAction<RolloutAction>;
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/index.ts
new file mode 100644
index 0000000000..e2a444895c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/rollout/index.ts
@@ -0,0 +1,3 @@
+import CombinedRolloutButtonGroup from "./CombinedRolloutButtonGroup.vue";
+
+export { CombinedRolloutButtonGroup };
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Assignee/Assignee.vue b/frontend/src/components/IssueV1/components/HeaderSection/Assignee/Assignee.vue
new file mode 100644
index 0000000000..fd75e594cf
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Assignee/Assignee.vue
@@ -0,0 +1,132 @@
+<template>
+ <div class="flex items-center justify-end gap-3">
+ <div class="flex items-center justify-end gap-1">
+ <NTooltip>
+ <template #trigger>
+ <div class="flex items-center gap-x-1 textlabel">
+ <span>{{ $t("common.assignee") }}</span>
+ <span v-if="isCreating" class="text-red-600">*</span>
+ </div>
+ </template>
+ <template #default>
+ <div class="max-w-[12rem]">
+ {{ $t("issue.assignee-tooltip") }}
+ </div>
+ </template>
+ </NTooltip>
+
+ <!-- AssigneeAttentionButton will be now shown until the feature is re-defined -->
+ <AssigneeAttentionButton v-if="false" />
+ </div>
+
+ <NTooltip :disabled="allowChangeAssignee">
+ <template #trigger>
+ <UserSelect
+ :multiple="false"
+ :user="assigneeUID"
+ :disabled="!allowChangeAssignee || isUpdating"
+ :loading="isUpdating"
+ :filter="filterAssignee"
+ style="width: 12rem"
+ @update:user="changeAssigneeUID"
+ />
+ </template>
+ <template #default>
+ <ErrorList :errors="['You are not allowed to change assignee']" />
+ </template>
+ </NTooltip>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { NTooltip } from "naive-ui";
+import { useI18n } from "vue-i18n";
+
+import { User } from "@/types/proto/v1/auth_service";
+import { Issue } from "@/types/proto/v1/issue_service";
+import { issueServiceClient } from "@/grpcweb";
+import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
+import { SYSTEM_BOT_EMAIL, SYSTEM_BOT_ID, UNKNOWN_ID } from "@/types";
+import { extractUserResourceName, extractUserUID } from "@/utils";
+import { UserSelect } from "@/components/v2";
+import {
+ allowUserToChangeAssignee,
+ allowUserToBeAssignee,
+ useCurrentRolloutPolicyForActiveEnvironment,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import AssigneeAttentionButton from "./AssigneeAttentionButton.vue";
+import { ErrorList } from "../../common";
+
+const { t } = useI18n();
+const userStore = useUserStore();
+const { isCreating, issue } = useIssueContext();
+const currentUser = useCurrentUserV1();
+const isUpdating = ref(false);
+
+const assigneeEmail = computed(() => {
+ const assignee = issue.value.assignee;
+ if (!assignee) return undefined;
+ return extractUserResourceName(assignee);
+});
+
+const assigneeUID = computed(() => {
+ if (!assigneeEmail.value) return undefined;
+ if (assigneeEmail.value === SYSTEM_BOT_EMAIL) return String(SYSTEM_BOT_ID);
+ const user = userStore.getUserByEmail(assigneeEmail.value);
+ if (!user) return undefined;
+ return extractUserUID(user.name);
+});
+
+const allowChangeAssignee = computed(() => {
+ if (isCreating.value) {
+ return true;
+ }
+ return allowUserToChangeAssignee(currentUser.value, issue.value);
+});
+
+const changeAssigneeUID = async (uid: string | undefined) => {
+ if (!uid || uid === String(UNKNOWN_ID)) {
+ issue.value.assignee = "";
+ return;
+ }
+ const assignee = userStore.getUserById(uid);
+ if (!assignee) {
+ issue.value.assignee = "";
+ return;
+ }
+ issue.value.assignee = `users/${assignee.email}`;
+
+ if (!isCreating.value) {
+ const issuePatch = Issue.fromJSON(issue.value);
+ isUpdating.value = true;
+ try {
+ const updated = await issueServiceClient.updateIssue({
+ issue: issuePatch,
+ updateMask: ["assignee"],
+ });
+ Object.assign(issue.value, updated);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } finally {
+ isUpdating.value = false;
+ }
+ }
+};
+
+const rollOutPolicy = useCurrentRolloutPolicyForActiveEnvironment();
+const filterAssignee = (user: User): boolean => {
+ const project = issue.value.projectEntity;
+ return allowUserToBeAssignee(
+ user,
+ project,
+ project.iamPolicy,
+ rollOutPolicy.value.policy,
+ rollOutPolicy.value.assigneeGroup
+ );
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Assignee/AssigneeAttentionButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Assignee/AssigneeAttentionButton.vue
new file mode 100644
index 0000000000..c81600f98c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Assignee/AssigneeAttentionButton.vue
@@ -0,0 +1,149 @@
+<template>
+ <NTooltip v-if="showNotifyAssignee">
+ <template #trigger>
+ <button
+ class="p-0.5 rounded"
+ :class="[
+ isAssigneeAttentionOn
+ ? 'cursor-default'
+ : 'cursor-pointer hover:bg-control-bg-hover',
+ ]"
+ :disabled="isUpdating"
+ v-bind="$attrs"
+ @click="notifyAssignee"
+ >
+ <BBSpin v-if="isUpdating" class="w-4 h-4" />
+ <heroicons-outline:bell-alert
+ v-else
+ 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 { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { NTooltip } from "naive-ui";
+
+import { AppIMSetting_IMType } from "@/types/proto/v1/setting_service";
+import { Workflow } from "@/types/proto/v1/project_service";
+import { Issue, IssueStatus } from "@/types/proto/v1/issue_service";
+import { issueServiceClient } from "@/grpcweb";
+import { extractUserResourceName } from "@/utils";
+import {
+ useSettingV1Store,
+ useCurrentUserV1,
+ useUserStore,
+ pushNotification,
+} from "@/store";
+import { useIssueContext } from "@/components/IssueV1/logic";
+
+const { t } = useI18n();
+const currentUserV1 = useCurrentUserV1();
+const settingV1Store = useSettingV1Store();
+const { isCreating, issue } = useIssueContext();
+const project = computed(() => issue.value.projectEntity);
+const isUpdating = ref(false);
+
+const showNotifyAssignee = computed(() => {
+ if (isCreating.value) {
+ return false;
+ }
+ if (project.value.workflow === Workflow.VCS) {
+ return false;
+ }
+
+ if (issue.value.status !== IssueStatus.OPEN) {
+ return false;
+ }
+
+ if (
+ issue.value.assigneeAttention &&
+ currentUserV1.value.email === extractUserResourceName(issue.value.assignee)
+ ) {
+ // Also show the icon for assignee if need attention.
+ return true;
+ }
+
+ return (
+ currentUserV1.value.email === extractUserResourceName(issue.value.creator)
+ );
+});
+
+const isAssigneeAttentionOn = computed(() => {
+ return issue.value.assigneeAttention;
+});
+
+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 = async () => {
+ if (!showNotifyAssignee.value) return;
+ if (isAssigneeAttentionOn.value) return;
+
+ try {
+ isUpdating.value = true;
+ const issuePatch = Issue.fromJSON({
+ ...issue.value,
+ assigneeAttention: true,
+ });
+ const updated = await issueServiceClient.updateIssue({
+ issue: issuePatch,
+ updateMask: ["assignee_attention"],
+ });
+ Object.assign(issue.value, updated);
+
+ const email = extractUserResourceName(issue.value.assignee);
+ const assignee = useUserStore().getUserByEmail(email);
+ 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: assignee ? assignee.title : email,
+ });
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: message,
+ });
+ } finally {
+ isUpdating.value = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Assignee/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/Assignee/index.ts
new file mode 100644
index 0000000000..aff6feea9f
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Assignee/index.ts
@@ -0,0 +1,3 @@
+import Assignee from "./Assignee.vue";
+
+export default Assignee;
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Description.vue b/frontend/src/components/IssueV1/components/HeaderSection/Description.vue
new file mode 100644
index 0000000000..a12a1e13dd
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Description.vue
@@ -0,0 +1,45 @@
+<template>
+ <div class="flex items-center gap-x-4">
+ <div class="flex items-center gap-x-1 text-sm">
+ <div class="textlabel">{{ $t("common.project") }}</div>
+ <div>-</div>
+ <ProjectV1Name :project="project" />
+ </div>
+
+ <i18n-t
+ v-if="!isCreating && creator"
+ keypath="issue.opened-by-at"
+ tag="div"
+ class="text-sm text-control-light"
+ >
+ <template #creator>
+ <router-link
+ :to="`/u/${extractUserUID(creator.name)}`"
+ class="font-medium text-control hover:underline"
+ >{{ creator.title }}</router-link
+ >
+ </template>
+ <template #time>
+ <HumanizeDate :date="issue.createTime" />
+ </template>
+ </i18n-t>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+
+import { useIssueContext } from "../../logic";
+import { extractUserResourceName, extractUserUID } from "@/utils";
+import { useUserStore } from "@/store";
+import HumanizeDate from "@/components/misc/HumanizeDate.vue";
+
+const { isCreating, issue } = useIssueContext();
+
+const creator = computed(() => {
+ const email = extractUserResourceName(issue.value.creator);
+ return useUserStore().getUserByEmail(email);
+});
+
+const project = computed(() => issue.value.projectEntity);
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/HeaderSection.vue b/frontend/src/components/IssueV1/components/HeaderSection/HeaderSection.vue
new file mode 100644
index 0000000000..3be0284a53
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/HeaderSection.vue
@@ -0,0 +1,67 @@
+<template>
+ <div class="flex flex-col gap-2 px-4 py-2">
+ <div
+ class="flex flex-col md:flex-row md:items-start md:justify-between gap-2"
+ >
+ <div class="flex-1 flex items-center gap-x-2">
+ <div v-if="!isCreating">
+ <IssueStatusIcon
+ :issue-status="issue.status"
+ :task-status="issueTaskStatus"
+ />
+ </div>
+
+ <Title />
+ </div>
+
+ <Actions />
+ </div>
+ <div
+ class="flex flex-col md:flex-row md:items-stretch md:justify-between gap-2"
+ >
+ <div class="flex-1 flex flex-col gap-x-2">
+ <Description />
+
+ <VCSInfo />
+
+ <RollbackFromTips />
+ </div>
+
+ <div class="flex flex-col items-end gap-y-2">
+ <ReviewSection v-if="!isCreating" />
+ <Assignee v-if="shouldShowAssignee" />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import IssueStatusIcon from "../IssueStatusIcon.vue";
+import { activeTaskInRollout, isDatabaseRelatedIssue } from "@/utils";
+import { useIssueContext } from "../../logic";
+import { Task_Status } from "@/types/proto/v1/rollout_service";
+import Title from "./Title.vue";
+import Description from "./Description.vue";
+import VCSInfo from "./VCSInfo.vue";
+import Actions from "./Actions";
+import ReviewSection from "./ReviewSection";
+import Assignee from "./Assignee";
+import RollbackFromTips from "./RollbackFromTips.vue";
+
+const { isCreating, issue } = useIssueContext();
+
+const issueTaskStatus = computed(() => {
+ // For grant request issue, we always show the status as "NOT_STARTED" as task status.
+ if (!isDatabaseRelatedIssue(issue.value)) {
+ return Task_Status.NOT_STARTED;
+ }
+
+ return activeTaskInRollout(issue.value.rolloutEntity).status;
+});
+
+const shouldShowAssignee = computed(() => {
+ return isDatabaseRelatedIssue(issue.value);
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Approver.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Approver.vue
new file mode 100644
index 0000000000..2e3fdc44e2
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Approver.vue
@@ -0,0 +1,28 @@
+<template>
+ <div
+ 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 === SYSTEM_BOT_USER_NAME"
+ class="ml-1 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>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { useCurrentUserV1 } from "@/store";
+import { SYSTEM_BOT_USER_NAME, WrappedReviewStep } from "@/types";
+
+const currentUser = useCurrentUserV1();
+
+defineProps<{
+ step: WrappedReviewStep;
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Candidates.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Candidates.vue
new file mode 100644
index 0000000000..89c8d5c592
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Candidates.vue
@@ -0,0 +1,43 @@
+<template>
+ <div v-if="candidates.length === 0" class="w-[14rem] text-warning">
+ {{ $t("custom-approval.issue-review.no-one-matches-role") }}
+ </div>
+
+ <div
+ v-else
+ class="min-w-[8rem] max-w-[12rem] max-h-[18rem] flex flex-col text-control-light overflow-y-hidden"
+ >
+ <div class="flex-1 overflow-auto text-xs">
+ <div
+ v-for="user in candidates"
+ :key="user.name"
+ class="flex items-center py-1 gap-x-1"
+ :class="[user.name === currentUser.name && 'font-bold']"
+ >
+ <PrincipalAvatar
+ :principal="convertUserToPrincipal(user)"
+ size="SMALL"
+ />
+ <span class="whitespace-nowrap">{{ user.title }}</span>
+ <span v-if="user.name === currentUser.name">
+ ({{ $t("custom-approval.issue-review.you") }})
+ </span>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import { convertUserToPrincipal, useCurrentUserV1 } from "@/store";
+import { WrappedReviewStep } from "@/types";
+import PrincipalAvatar from "@/components/PrincipalAvatar.vue";
+
+const props = defineProps<{
+ step: WrappedReviewStep;
+}>();
+
+const currentUser = useCurrentUserV1();
+const candidates = computed(() => props.step.candidates);
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vue
new file mode 100644
index 0000000000..8df8d49d48
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ExternalApprovalNodeSyncButton.vue
@@ -0,0 +1,64 @@
+<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 { ref } from "vue";
+import { NButton, NTooltip } from "naive-ui";
+import { useI18n } from "vue-i18n";
+
+import { pushNotification } from "@/store";
+
+const { t } = useI18n();
+const syncing = ref(false);
+const synced = ref(false);
+
+const syncNow = async () => {
+ if (syncing.value || synced.value) return;
+
+ 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.
+ 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/IssueV1/components/HeaderSection/ReviewSection/ReviewSection.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ReviewSection.vue
new file mode 100644
index 0000000000..700c9f456b
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/ReviewSection.vue
@@ -0,0 +1,98 @@
+<template>
+ <div class="flex items-center gap-x-3">
+ <NTooltip :disabled="!showApprovalTooltip">
+ <template #trigger>
+ <div class="textlabel flex items-center gap-x-1">
+ {{ $t("issue.approval-flow.self") }}
+ </div>
+ </template>
+ <template #default>
+ <div class="max-w-[22rem]">
+ {{ $t("issue.approval-flow.tooltip") }}
+ </div>
+ </template>
+ </NTooltip>
+
+ <div class="flex-1 min-w-[12rem]">
+ <div
+ v-if="!ready"
+ class="flex items-center gap-x-2 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">
+ <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>
+ <Timeline
+ v-else-if="wrappedSteps && wrappedSteps.length > 0"
+ :steps="wrappedSteps"
+ />
+ <div
+ v-else
+ class="flex items-center 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>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+import { NTooltip } from "naive-ui";
+
+import { isGrantRequestIssue } from "@/utils";
+import { useIssueV1Store } from "@/store";
+import {
+ databaseForTask,
+ useIssueContext,
+ useWrappedReviewStepsV1,
+} from "@/components/IssueV1";
+import Timeline from "./Timeline.vue";
+
+const { issue, events, reviewContext, selectedTask } = useIssueContext();
+const { ready, error } = reviewContext;
+const selectedDatabase = computed(() =>
+ databaseForTask(issue.value, selectedTask.value)
+);
+
+const wrappedSteps = useWrappedReviewStepsV1(issue, reviewContext);
+
+const retrying = ref(false);
+const retryFindingApprovalFlow = async () => {
+ retrying.value = true;
+ try {
+ await useIssueV1Store().regenerateReviewV1(issue.value.name);
+ events.emit("status-changed", { eager: true });
+ } finally {
+ retrying.value = false;
+ }
+};
+
+const showApprovalTooltip = computed(() => {
+ // Don't show the tooltip if the issue type is grant request.
+ if (isGrantRequestIssue(issue.value)) {
+ return false;
+ }
+ return true;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Timeline.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Timeline.vue
new file mode 100644
index 0000000000..78860ede3d
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/Timeline.vue
@@ -0,0 +1,100 @@
+<template>
+ <NTimeline
+ :horizontal="true"
+ :icon-size="28"
+ class="bb-approval-timeline-horizontal"
+ >
+ <NTimelineItem v-for="step in steps" :key="step.index">
+ <template #icon>
+ <NPopover placement="bottom">
+ <template #trigger>
+ <TimelineIcon :step="step" />
+ </template>
+
+ <template #default>
+ <div class="flex flex-col gap-y-2 text-sm">
+ <div class="whitespace-nowrap textlabel">
+ {{ approvalNodeText(step.step.nodes[0]) }}
+ </div>
+ <hr />
+ <template v-if="!isExternalApprovalStep(step.step)">
+ <Approver v-if="step.status === 'APPROVED'" :step="step" />
+ <Candidates v-else :step="step" />
+ </template>
+ <template v-else>
+ <ExternalApprovalSyncButton />
+ </template>
+ </div>
+ </template>
+ </NPopover>
+ </template>
+
+ <template v-if="false" #default>
+ <div class="flex text-sm whitespace-nowrap" :class="itemClass(step)">
+ {{ approvalNodeText(step.step.nodes[0]) }}
+ </div>
+ </template>
+ </NTimelineItem>
+ </NTimeline>
+</template>
+
+<script lang="ts" setup>
+import { NTimeline, NTimelineItem, NPopover } from "naive-ui";
+
+import { ApprovalStep } from "@/types/proto/v1/issue_service";
+import { WrappedReviewStep } from "@/types";
+import { approvalNodeText } from "@/utils";
+import Candidates from "./Candidates.vue";
+import ExternalApprovalSyncButton from "./ExternalApprovalNodeSyncButton.vue";
+import Approver from "./Approver.vue";
+import TimelineIcon from "./TimelineIcon.vue";
+
+defineProps<{
+ steps: WrappedReviewStep[];
+}>();
+
+const isExternalApprovalStep = (step: ApprovalStep) => {
+ return !!step.nodes[0]?.externalNodeId;
+};
+
+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-horizontal .n-timeline-item {
+ padding-right: 20px !important;
+}
+.bb-approval-timeline-horizontal .n-timeline-item:last-child {
+ padding-right: 0 !important;
+}
+.bb-approval-timeline-horizontal .n-timeline-item .n-timeline-item-timeline {
+ position: static;
+ height: calc(var(--n-icon-size)) !important;
+}
+.bb-approval-timeline-horizontal
+ .n-timeline-item
+ .n-timeline-item-timeline
+ .n-timeline-item-timeline__line {
+ --line-padding: 4px;
+ left: calc(var(--n-icon-size) + var(--line-padding)) !important;
+ right: calc(var(--line-padding)) !important;
+ height: 3px !important;
+}
+.bb-approval-timeline-horizontal .n-timeline-item .n-timeline-item-content {
+ margin-top: 2px !important;
+}
+.bb-approval-timeline-horizontal
+ .n-timeline-item
+ .n-timeline-item-content
+ .n-timeline-item-content__meta {
+ display: none;
+}
+</style>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/TimelineIcon.vue b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/TimelineIcon.vue
new file mode 100644
index 0000000000..8ccaaa6ea0
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/TimelineIcon.vue
@@ -0,0 +1,49 @@
+<template>
+ <div
+ class="w-7 h-7 rounded-full flex items-center justify-center text-sm shrink-0"
+ :class="iconClass"
+ >
+ <heroicons-outline:thumb-up
+ v-if="step.status === 'APPROVED'"
+ class="w-5 h-5 text-white"
+ />
+ <heroicons:pause-solid
+ v-else-if="step.status === 'REJECTED'"
+ class="w-5 h-5 text-white"
+ />
+ <template v-else-if="step.status === 'CURRENT'">
+ <heroicons-outline:external-link
+ v-if="isExternalApprovalStep"
+ class="w-5 h-5"
+ />
+ <heroicons-outline:user v-else class="w-5 h-5" />
+ </template>
+ <template v-else>
+ {{ step.index + 1 }}
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+
+import { WrappedReviewStep } from "@/types";
+
+const props = defineProps<{
+ step: WrappedReviewStep;
+}>();
+
+const isExternalApprovalStep = computed(() => {
+ return !!props.step.step.nodes[0]?.externalNodeId;
+});
+
+const iconClass = computed(() => {
+ const { status } = props.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",
+ ];
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/index.ts
new file mode 100644
index 0000000000..a4590e753c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/ReviewSection/index.ts
@@ -0,0 +1,3 @@
+import ReviewSection from "./ReviewSection.vue";
+
+export default ReviewSection;
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/RollbackFromTips.vue b/frontend/src/components/IssueV1/components/HeaderSection/RollbackFromTips.vue
new file mode 100644
index 0000000000..10a4884638
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/RollbackFromTips.vue
@@ -0,0 +1,137 @@
+<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.uid }}</template>
+ <template #task>[{{ rollbackFromTask.title }}]</template>
+ </i18n-t>
+ </router-link>
+ </template>
+ </i18n-t>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref, watch } from "vue";
+import { useRoute } from "vue-router";
+
+import { RollbackDetail, UNKNOWN_ID, unknownIssue, unknownTask } from "@/types";
+import { Task_Type } from "@/types/proto/v1/rollout_service";
+import {
+ buildIssueV1LinkWithTask,
+ extractIssueUID,
+ extractTaskUID,
+ flattenTaskV1List,
+} from "@/utils";
+import { experimentalFetchIssueByUID } from "@/store";
+import {
+ databaseForTask,
+ getRollbackTaskMappingFromQuery,
+ useIssueContext,
+} from "../../logic";
+
+const { isCreating, issue, selectedTask } = useIssueContext();
+const route = useRoute();
+
+const taskConfig = computed(() => {
+ if (isCreating.value) return undefined;
+
+ const task = selectedTask.value;
+ if (task.type === Task_Type.DATABASE_DATA_UPDATE) {
+ return task.databaseDataUpdate;
+ // return task.payload as TaskDatabaseDataUpdatePayload | undefined;
+ }
+ return undefined;
+});
+
+const rollbackDetail = computed((): RollbackDetail | undefined => {
+ if (!isCreating.value) return undefined;
+ // Try to find out the relationship between databaseId and rollback issue/task
+ // Id from the URL query.
+ const databaseUID = databaseForTask(issue.value, selectedTask.value).uid;
+
+ const mapping = getRollbackTaskMappingFromQuery(route);
+ return mapping.get(databaseUID);
+});
+
+const rollbackFromIssueUID = computed(() => {
+ if (isCreating.value) {
+ return String(rollbackDetail.value?.issueId ?? UNKNOWN_ID);
+ }
+ if (taskConfig.value) {
+ return (
+ extractIssueUID(taskConfig.value.rollbackFromIssue) || String(UNKNOWN_ID)
+ );
+ }
+ return String(UNKNOWN_ID);
+});
+
+const rollbackFromTaskUID = computed(() => {
+ if (isCreating.value) {
+ return String(rollbackDetail.value?.taskId ?? UNKNOWN_ID);
+ }
+ if (taskConfig.value) {
+ return (
+ extractTaskUID(taskConfig.value.rollbackFromTask) || String(UNKNOWN_ID)
+ );
+ }
+ return String(UNKNOWN_ID);
+});
+
+// const rollbackFromIssue = useIssueById(
+// rollbackFromIssueUID,
+// true /* Lazy fetch */
+// );
+const rollbackFromIssue = ref(unknownIssue()); // TODO: useComposedIssueByUID
+
+watch(
+ rollbackFromIssueUID,
+ (uid) => {
+ experimentalFetchIssueByUID(uid).then((issue) => {
+ if (issue.uid === rollbackFromIssueUID.value) {
+ rollbackFromIssue.value = issue;
+ }
+ });
+ },
+ { immediate: true }
+);
+
+const rollbackFromTask = computed(() => {
+ const issue = rollbackFromIssue.value;
+ if (issue.uid === String(UNKNOWN_ID)) return unknownTask();
+
+ const taskUID = rollbackFromTaskUID.value;
+ if (taskUID === String(UNKNOWN_ID)) return unknownTask();
+
+ const task = flattenTaskV1List(issue.rolloutEntity).find(
+ (t) => t.uid === taskUID
+ );
+ if (task) {
+ return task;
+ }
+
+ return unknownTask();
+});
+
+const shouldShowTips = computed(() => {
+ // Show the tips when rollbackFromIssue and rollbackFromTask are both ready.
+ return (
+ rollbackFromIssue.value.uid !== String(UNKNOWN_ID) &&
+ rollbackFromTask.value.uid !== String(UNKNOWN_ID)
+ );
+});
+
+const rollbackIssueLink = computed(() => {
+ if (!shouldShowTips.value) return "";
+ return buildIssueV1LinkWithTask(
+ rollbackFromIssue.value,
+ rollbackFromTask.value
+ );
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Title.vue b/frontend/src/components/IssueV1/components/HeaderSection/Title.vue
new file mode 100644
index 0000000000..d6032f04be
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/Title.vue
@@ -0,0 +1,155 @@
+<template>
+ <div class="flex-1">
+ <NInput
+ :value="state.title"
+ :style="style"
+ :loading="state.isUpdating"
+ :disabled="!allowEdit || state.isUpdating"
+ size="large"
+ required
+ class="bb-issue-title-input"
+ @focus="state.isEditing = true"
+ @blur="onBlur"
+ @keyup.enter="onEnter"
+ @update:value="onUpdateValue"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { CSSProperties, computed, reactive, watch } from "vue";
+import { NInput } from "naive-ui";
+import { useI18n } from "vue-i18n";
+
+import { Issue, IssueStatus } from "@/types/proto/v1/issue_service";
+import { issueServiceClient } from "@/grpcweb";
+import { pushNotification, useCurrentUserV1 } from "@/store";
+import { extractUserResourceName, hasWorkspacePermissionV1 } from "@/utils";
+import { useIssueContext } from "../../logic";
+
+type ViewMode = "EDIT" | "VIEW";
+
+const { t } = useI18n();
+const currentUser = useCurrentUserV1();
+const { isCreating, issue } = useIssueContext();
+
+const state = reactive({
+ isEditing: false,
+ isUpdating: false,
+ title: issue.value.title,
+});
+
+const viewMode = computed((): ViewMode => {
+ if (isCreating.value) return "EDIT";
+ return state.isEditing ? "EDIT" : "VIEW";
+});
+
+const style = computed(() => {
+ const style: CSSProperties = {
+ cursor: "default",
+ "--n-color-disabled": "transparent",
+ "--n-font-size": "18px",
+ "font-weight": "bold",
+ };
+ const border =
+ viewMode.value === "EDIT"
+ ? "1px solid var(--color-control-border)"
+ : "none";
+ style["--n-border"] = border;
+ style["--n-border-disabled"] = border;
+
+ return style;
+});
+
+const allowEdit = computed(() => {
+ if (isCreating.value) {
+ return true;
+ }
+
+ if (issue.value.status !== IssueStatus.OPEN) {
+ return false;
+ }
+
+ if (
+ extractUserResourceName(issue.value.assignee) === currentUser.value.email ||
+ extractUserResourceName(issue.value.creator) === currentUser.value.email
+ ) {
+ // Allowed if current user is the assignee or creator.
+ return true;
+ }
+
+ if (
+ hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-issue",
+ currentUser.value.userRole
+ )
+ ) {
+ // Allowed if RBAC is enabled and current is DBA or workspace owner.
+ return true;
+ }
+ return false;
+});
+
+const onBlur = async () => {
+ const cleanup = () => {
+ state.isEditing = false;
+ state.isUpdating = false;
+ };
+
+ if (isCreating.value) {
+ cleanup();
+ return;
+ }
+ if (state.title === issue.value.title) {
+ cleanup();
+ return;
+ }
+ try {
+ state.isUpdating = true;
+ // TODO update name
+ const issuePatch = Issue.fromJSON({
+ ...issue.value,
+ title: state.title,
+ });
+ const updated = await issueServiceClient.updateIssue({
+ issue: issuePatch,
+ updateMask: ["title"],
+ });
+ Object.assign(issue.value, updated);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } finally {
+ cleanup();
+ }
+};
+
+const onEnter = (e: Event) => {
+ const input = e.target as HTMLInputElement;
+ input.blur();
+};
+
+const onUpdateValue = (title: string) => {
+ state.title = title;
+ if (isCreating.value) {
+ issue.value.title = title;
+ }
+};
+
+watch(
+ () => issue.value.title,
+ (title) => {
+ state.title = title;
+ }
+);
+</script>
+
+<style>
+.bb-issue-title-input input {
+ cursor: text !important;
+ color: var(--n-text-color) !important;
+ text-decoration-color: var(--n-text-color) !important;
+}
+</style>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/VCSInfo.vue b/frontend/src/components/IssueV1/components/HeaderSection/VCSInfo.vue
new file mode 100644
index 0000000000..7c17da2d3b
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/VCSInfo.vue
@@ -0,0 +1,83 @@
+<template>
+ <div class="issue-debug">
+ issue vcs push event info if needed
+ <!-- <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>
+</template>
+
+<script setup lang="ts">
+// 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 "";
+// });
+</script>
diff --git a/frontend/src/components/IssueV1/components/HeaderSection/index.ts b/frontend/src/components/IssueV1/components/HeaderSection/index.ts
new file mode 100644
index 0000000000..3843a93df5
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/HeaderSection/index.ts
@@ -0,0 +1,3 @@
+import HeaderSection from "./HeaderSection.vue";
+
+export default HeaderSection;
diff --git a/frontend/src/components/IssueV1/components/IssueStatusIcon.vue b/frontend/src/components/IssueV1/components/IssueStatusIcon.vue
new file mode 100644
index 0000000000..282b4ecbc8
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/IssueStatusIcon.vue
@@ -0,0 +1,77 @@
+<template>
+ <span
+ class="flex items-center justify-center rounded-full select-none overflow-hidden"
+ :class="issueIconClass()"
+ >
+ <template v-if="issueStatus === IssueStatus.OPEN">
+ <template v-if="taskStatus === Task_Status.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 === Task_Status.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 === IssueStatus.DONE">
+ <heroicons-solid:check class="w-4 h-4" />
+ </template>
+ <template v-else-if="issueStatus === IssueStatus.CANCELED">
+ <heroicons-solid:minus class="w-5 h-5" />
+ </template>
+ </span>
+</template>
+
+<script lang="ts" setup>
+import { PropType } from "vue";
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import { Task_Status } from "@/types/proto/v1/rollout_service";
+
+export type SizeType = "small" | "normal";
+
+const props = defineProps({
+ issueStatus: {
+ required: true,
+ type: Number as PropType<IssueStatus>,
+ },
+ // Specify taskStatus if we want to show the task specific status when issueStatus is OPEN.
+ taskStatus: {
+ type: Number as PropType<Task_Status>,
+ default: undefined,
+ },
+ size: {
+ type: String as PropType<SizeType>,
+ default: "normal",
+ },
+});
+const issueIconClass = () => {
+ const iconClass = props.size === "normal" ? "w-5 h-5" : "w-4 h-4";
+ switch (props.issueStatus) {
+ case IssueStatus.OPEN:
+ if (props.taskStatus && props.taskStatus === Task_Status.FAILED) {
+ return iconClass + " bg-error text-white";
+ }
+ return iconClass + " bg-white border-2 border-info text-info";
+ case IssueStatus.CANCELED:
+ return iconClass + " bg-white border-2 text-gray-400 border-gray-400";
+ case IssueStatus.DONE:
+ return iconClass + " bg-success text-white";
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBadge.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBadge.vue
new file mode 100644
index 0000000000..6939513c0f
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBadge.vue
@@ -0,0 +1,168 @@
+<template>
+ <div class="issue-debug">
+ <div>type: {{ type }}</div>
+ <div>count in type: {{ planCheckRunList.length }}</div>
+ <div>latest: {{ latestPlanCheckRun.name }}</div>
+ </div>
+
+ <button
+ class="inline-flex items-center px-3 py-0.5 rounded-full text-sm border border-control-border"
+ :class="buttonClasses"
+ @click="$emit('click')"
+ >
+ <template v-if="status === PlanCheckRun_Status.RUNNING">
+ <TaskSpinner class="-ml-1 mr-1.5 h-4 w-4 text-info" />
+ </template>
+ <template v-else-if="status === PlanCheckRun_Status.DONE">
+ <template v-if="resultStatus === PlanCheckRun_Result_Status.SUCCESS">
+ <heroicons-outline:check
+ class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-success"
+ />
+ </template>
+ <template v-else-if="resultStatus === PlanCheckRun_Result_Status.WARNING">
+ <heroicons-outline:exclamation
+ class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-warning"
+ />
+ </template>
+ <template v-else-if="resultStatus === PlanCheckRun_Result_Status.ERROR">
+ <span class="mr-1.5 font-medium text-error" aria-hidden="true">
+ !
+ </span>
+ </template>
+ </template>
+ <template v-else-if="status === PlanCheckRun_Status.FAILED">
+ <span class="mr-1.5 font-medium text-error" aria-hidden="true"> ! </span>
+ </template>
+ <template v-else-if="status === PlanCheckRun_Status.CANCELED">
+ <heroicons-outline:ban class="-ml-1 mr-1.5 mt-0.5 h-4 w-4 text-control" />
+ </template>
+
+ <span>{{ name }}</span>
+ </button>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { maxBy } from "lodash-es";
+import { useI18n } from "vue-i18n";
+
+import {
+ PlanCheckRun,
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Status,
+ PlanCheckRun_Type,
+} from "@/types/proto/v1/rollout_service";
+import { planCheckRunResultStatus } from "@/components/IssueV1/logic";
+
+const props = defineProps<{
+ planCheckRunList: PlanCheckRun[];
+ type: PlanCheckRun_Type;
+}>();
+
+defineEmits<{
+ (event: "click"): void;
+}>();
+
+const { t } = useI18n();
+
+const latestPlanCheckRun = computed(() => {
+ return maxBy(props.planCheckRunList, (check) => Number(check.uid))!;
+});
+
+const status = computed(() => {
+ return latestPlanCheckRun.value.status;
+});
+
+const resultStatus = computed(() => {
+ return planCheckRunResultStatus(latestPlanCheckRun.value);
+});
+
+const buttonClasses = computed(() => {
+ let bgColor = "";
+ let bgHoverColor = "";
+ let textColor = "";
+ switch (status.value) {
+ case PlanCheckRun_Status.RUNNING:
+ bgColor = "bg-blue-100";
+ bgHoverColor = "bg-blue-300";
+ textColor = "text-blue-800";
+ break;
+ case PlanCheckRun_Status.FAILED:
+ bgColor = "bg-red-100";
+ bgHoverColor = "bg-red-300";
+ textColor = "text-red-800";
+ break;
+ case PlanCheckRun_Status.CANCELED:
+ bgColor = "bg-yellow-100";
+ bgHoverColor = "bg-yellow-300";
+ textColor = "text-yellow-800";
+ break;
+ case PlanCheckRun_Status.DONE:
+ switch (resultStatus.value) {
+ case PlanCheckRun_Result_Status.SUCCESS:
+ bgColor = "bg-gray-100";
+ bgHoverColor = "bg-gray-300";
+ textColor = "text-gray-800";
+ break;
+ case PlanCheckRun_Result_Status.WARNING:
+ bgColor = "bg-yellow-100";
+ bgHoverColor = "bg-yellow-300";
+ textColor = "text-yellow-800";
+ break;
+ case PlanCheckRun_Result_Status.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");
+ // }
+ styleList.push("cursor-pointer", `hover:${bgHoverColor}`);
+ styleList.push(bgColor);
+
+ return styleList.join(" ");
+});
+
+// Defines the mapping from PlanCheckRun_Type to an i18n resource keypath
+const PlanCheckRunTypeNameDict = new Map<PlanCheckRun_Type, string>([
+ [PlanCheckRun_Type.DATABASE_STATEMENT_FAKE_ADVISE, "task.check-type.fake"],
+ // ["bb.task-check.database.statement.syntax", "task.check-type.syntax"],
+ [
+ PlanCheckRun_Type.DATABASE_STATEMENT_COMPATIBILITY,
+ "task.check-type.compatibility",
+ ],
+ [PlanCheckRun_Type.DATABASE_STATEMENT_ADVISE, "task.check-type.sql-review"],
+ [PlanCheckRun_Type.DATABASE_STATEMENT_TYPE, "task.check-type.statement-type"],
+ [PlanCheckRun_Type.DATABASE_CONNECT, "task.check-type.connection"],
+ [PlanCheckRun_Type.DATABASE_GHOST_SYNC, "task.check-type.ghost-sync"],
+ [PlanCheckRun_Type.DATABASE_PITR_MYSQL, "task.check-type.pitr"],
+ [
+ PlanCheckRun_Type.DATABASE_STATEMENT_SUMMARY_REPORT,
+ "task.check-type.summary-report",
+ ],
+]);
+
+const name = computed(() => {
+ const { type } = latestPlanCheckRun.value;
+ const has = PlanCheckRunTypeNameDict.has(type);
+ console.assert(has, `Missing PlanCheckType name of "${type}"`);
+ if (has) {
+ const key = PlanCheckRunTypeNameDict.get(type)!;
+ return t(key);
+ }
+ return type;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBadgeBar.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBadgeBar.vue
new file mode 100644
index 0000000000..e27b59e1cb
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBadgeBar.vue
@@ -0,0 +1,284 @@
+<template>
+ <div class="flex items-center flex-wrap gap-2 flex-1">
+ <PlanCheckBadge
+ v-for="group in planCheckRunsGroupByType"
+ :key="group.type"
+ :type="group.type"
+ :plan-check-run-list="group.list"
+ @click="$emit('select-type', group.type)"
+ />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import {
+ PlanCheckRun,
+ PlanCheckRun_Type,
+ Task,
+} from "@/types/proto/v1/rollout_service";
+import PlanCheckBadge from "./PlanCheckBadge.vue";
+import { groupBy } from "@/utils/collections";
+import { orderBy } from "lodash-es";
+
+const props = defineProps<{
+ planCheckRunList: PlanCheckRun[];
+ selectedType?: PlanCheckRun_Type;
+ task: Task;
+}>();
+
+defineEmits<{
+ (event: "select-type", type: PlanCheckRun_Type): void;
+}>();
+
+const planCheckRunsGroupByType = computed(() => {
+ const groups = groupBy(props.planCheckRunList, (checkRun) => checkRun.type);
+ const list = Array.from(groups.entries()).map(([type, list]) => ({
+ type,
+ list,
+ }));
+ // Sort by pre-defined orders
+ // If an item's order is not defined, put it behind
+ return orderBy(
+ list,
+ [(group) => PlanCheckTypeOrderDict.get(group.type) ?? 99999],
+ "asc"
+ );
+});
+
+const PlanCheckTypeOrderList: PlanCheckRun_Type[] = [
+ PlanCheckRun_Type.DATABASE_PITR_MYSQL,
+ PlanCheckRun_Type.DATABASE_GHOST_SYNC,
+ PlanCheckRun_Type.DATABASE_STATEMENT_COMPATIBILITY,
+ PlanCheckRun_Type.DATABASE_STATEMENT_TYPE,
+ PlanCheckRun_Type.DATABASE_CONNECT,
+ PlanCheckRun_Type.DATABASE_STATEMENT_ADVISE,
+];
+const PlanCheckTypeOrderDict = new Map<PlanCheckRun_Type, number>(
+ PlanCheckTypeOrderList.map((type, order) => [type, order])
+);
+
+// import { computed, defineComponent, PropType, reactive, watch } from "vue";
+// import { groupBy, maxBy } from "lodash-es";
+// import { useI18n } from "vue-i18n";
+
+// import { HiddenCheckTypes } from "@/utils";
+
+// 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/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBar.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBar.vue
new file mode 100644
index 0000000000..699b65a12a
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckBar.vue
@@ -0,0 +1,127 @@
+<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> -->
+
+ <div class="flex items-start gap-x-4">
+ <div class="textlabel h-[26px] inline-flex items-center">
+ {{ $t("task.task-checks") }}
+ </div>
+
+ <PlanCheckBadgeBar
+ :plan-check-run-list="planCheckRunList"
+ :task="task"
+ @select-type="selectedType = $event"
+ />
+
+ <PlanCheckRunButton
+ v-if="allowRunChecks"
+ :task="task"
+ @run-checks="runChecks"
+ />
+
+ <PlanCheckPanel
+ v-if="planCheckRunList.length > 0 && selectedType"
+ :selected-type="selectedType"
+ :plan-check-run-list="planCheckRunList"
+ :task="task"
+ @close="selectedType = undefined"
+ />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+
+import {
+ notifyNotEditableLegacyIssue,
+ planCheckRunListForTask,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import PlanCheckBadgeBar from "./PlanCheckBadgeBar.vue";
+import PlanCheckRunButton from "./PlanCheckRunButton.vue";
+import { PlanCheckRun_Type, Task } from "@/types/proto/v1/rollout_service";
+import { rolloutServiceClient } from "@/grpcweb";
+import PlanCheckPanel from "./PlanCheckPanel.vue";
+
+const props = defineProps<{
+ allowRunChecks?: boolean;
+ task: Task;
+}>();
+
+const { issue, events } = useIssueContext();
+const selectedType = ref<PlanCheckRun_Type>();
+
+const planCheckRunList = computed(() => {
+ return planCheckRunListForTask(issue.value, props.task);
+});
+
+const runChecks = (taskList: Task[]) => {
+ const { plan } = issue.value;
+ if (!plan) {
+ notifyNotEditableLegacyIssue();
+ return;
+ }
+
+ rolloutServiceClient.runPlanChecks({
+ name: plan,
+ });
+ events.emit("status-changed", { eager: true });
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
new file mode 100644
index 0000000000..aae57a2e72
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckDetail.vue
@@ -0,0 +1,256 @@
+<template>
+ <BBGrid
+ :column-list="COLUMN_LIST"
+ :data-source="tableRows"
+ :show-header="false"
+ :row-clickable="false"
+ class="border"
+ >
+ <template #item="{ item: row }: BBGridRow<TableRow>">
+ <div class="bb-grid-cell">
+ <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 === PlanCheckRun_Result_Status.SUCCESS"
+ >
+ <heroicons-solid:check class="w-4 h-4" />
+ </template>
+ <template
+ v-if="row.checkResult.status === PlanCheckRun_Result_Status.WARNING"
+ >
+ <heroicons-outline:exclamation class="h-4 w-4" />
+ </template>
+ <template
+ v-else-if="
+ row.checkResult.status === PlanCheckRun_Result_Status.ERROR
+ "
+ >
+ <span class="text-white font-medium text-base" aria-hidden="true"
+ >!</span
+ >
+ </template>
+ </div>
+ </div>
+ <div v-if="showCategoryColumn" class="bb-grid-cell">
+ {{ row.category }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ row.title }}
+ </div>
+ <div class="bb-grid-cell">
+ <span>{{ row.checkResult.content }}</span>
+ <template v-if="row.checkResult.sqlReviewReport?.detail">
+ <span
+ class="ml-1 normal-link"
+ @click="selectDetail(row.checkResult.sqlReviewReport)"
+ >{{ $t("sql-review.view-definition") }}</span
+ >
+ <span class="border-r border-control-border ml-1"></span>
+ </template>
+ TODO: details
+ </div>
+ </template>
+ </BBGrid>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { BBGridColumn, BBGridRow, BBGrid } from "@/bbkit";
+import { LocalizedSQLRuleErrorCodes } from "@/components/Issue/const";
+import {
+ GeneralErrorCode,
+ RuleType,
+ SQLReviewPolicyErrorCode,
+ getRuleLocalization,
+ ruleTemplateMap,
+} from "@/types";
+import {
+ PlanCheckRun,
+ PlanCheckRun_Result,
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Status,
+ Task,
+} from "@/types/proto/v1/rollout_service";
+
+interface ErrorCodeLink {
+ title: string;
+ target: string;
+ url: string;
+}
+
+// type PreviewSQLReviewRule = {
+// rule: RuleTemplate;
+// payload: PayloadValueType[];
+// };
+
+type TableRow = {
+ checkResult: PlanCheckRun_Result;
+ category: string;
+ title: string;
+ link: ErrorCodeLink | undefined;
+};
+
+const props = defineProps<{
+ planCheckRun: PlanCheckRun;
+ task: Task;
+}>();
+
+const { t } = useI18n();
+
+const statusIconClass = (status: PlanCheckRun_Result_Status) => {
+ switch (status) {
+ case PlanCheckRun_Result_Status.SUCCESS:
+ return "bg-success text-white";
+ case PlanCheckRun_Result_Status.WARNING:
+ return "bg-warning text-white";
+ case PlanCheckRun_Result_Status.ERROR:
+ return "bg-error text-white";
+ }
+};
+
+const checkResultList = computed((): PlanCheckRun_Result[] => {
+ if (props.planCheckRun.status === PlanCheckRun_Status.DONE) {
+ return props.planCheckRun.results;
+ } else if (props.planCheckRun.status === PlanCheckRun_Status.FAILED) {
+ // return [
+ // {
+ // status: "ERROR",
+ // title: t("common.error"),
+ // code: props.planCheckRun.code,
+ // content: props.planCheckRun.result.detail,
+ // namespace: "bb.core",
+ // line: undefined,
+ // column: undefined,
+ // },
+ // ];
+ return [
+ PlanCheckRun_Result.fromJSON({
+ status: PlanCheckRun_Result_Status.ERROR,
+ title: t("common.error"),
+ }),
+ ];
+ } else if (props.planCheckRun.status === PlanCheckRun_Status.CANCELED) {
+ // return [
+ // {
+ // status: "WARN",
+ // title: t("common.canceled"),
+ // code: props.planCheckRun.code,
+ // content: "",
+ // namespace: "bb.core",
+ // line: undefined,
+ // column: undefined,
+ // },
+ // ];
+ return [
+ PlanCheckRun_Result.fromJSON({
+ status: PlanCheckRun_Result_Status.WARNING,
+ title: t("common.canceled"),
+ }),
+ ];
+ }
+
+ return [];
+});
+
+const categoryAndTitle = (
+ checkResult: PlanCheckRun_Result
+): [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: PlanCheckRun_Result
+): 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}`;
+ const url = "#TODO";
+ 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(() => {
+ const STATUS: BBGridColumn = {
+ title: "Status",
+ width: "auto",
+ };
+ const CATEGORY: BBGridColumn = {
+ title: "Category",
+ width: "minmax(4rem, 6rem)",
+ };
+ const TITLE: BBGridColumn = {
+ title: "Title",
+ width: "12rem",
+ };
+ const CONTENT: BBGridColumn = {
+ title: "Detail",
+ width: "1fr",
+ };
+ if (showCategoryColumn.value) {
+ return [STATUS, CATEGORY, TITLE, CONTENT];
+ }
+ return [STATUS, TITLE, CONTENT];
+});
+
+const selectDetail = (args: any) => {
+ // TODO
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckPanel.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckPanel.vue
new file mode 100644
index 0000000000..73a0047d49
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckPanel.vue
@@ -0,0 +1,96 @@
+<template>
+ <BBModal
+ :title="$t('task.check-result.title', { name: task.title })"
+ class="!w-[56rem]"
+ header-class="whitespace-pre-wrap break-all gap-x-1"
+ @close="$emit('close')"
+ >
+ <div class="space-y-4">
+ <PlanCheckBadgeBar
+ :plan-check-run-list="planCheckRunList"
+ :selected-type="selectedType"
+ :task="task"
+ />
+ <TabFilter
+ v-if="selectedPlanCheckRunUID"
+ v-model:value="selectedPlanCheckRunUID"
+ :items="tabItemList"
+ />
+
+ <PlanCheckDetail
+ v-if="selectedPlanCheckRun"
+ :plan-check-run="selectedPlanCheckRun"
+ :task="task"
+ />
+ </div>
+ </BBModal>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { first, orderBy } from "lodash-es";
+import { useI18n } from "vue-i18n";
+
+import {
+ PlanCheckRun,
+ PlanCheckRun_Type,
+ Task,
+} from "@/types/proto/v1/rollout_service";
+import { TabFilter, TabFilterItem } from "@/components/v2";
+import PlanCheckBadgeBar from "./PlanCheckBadgeBar.vue";
+import PlanCheckDetail from "./PlanCheckDetail.vue";
+import { humanizeDate } from "@/utils";
+
+const props = defineProps<{
+ planCheckRunList: PlanCheckRun[];
+ selectedType: PlanCheckRun_Type;
+ task: Task;
+}>();
+
+defineEmits<{
+ (event: "close"): void;
+}>();
+
+const { t } = useI18n();
+
+const selectedPlanCheckRunList = computed(() => {
+ return orderBy(
+ props.planCheckRunList.filter(
+ (checkRun) => checkRun.type === props.selectedType
+ ),
+ (checkRun) => parseInt(checkRun.uid, 10),
+ "desc"
+ );
+});
+
+const selectedPlanCheckRunUID = ref(first(selectedPlanCheckRunList.value)?.uid);
+
+const selectedPlanCheckRun = computed(() => {
+ const uid = selectedPlanCheckRunUID.value;
+ if (!uid) return undefined;
+ return selectedPlanCheckRunList.value.find(
+ (checkRun) => checkRun.uid === uid
+ );
+});
+
+const tabItemList = computed(() => {
+ return selectedPlanCheckRunList.value.map<TabFilterItem<string>>(
+ (checkRun, i) => {
+ const label =
+ i === 0
+ ? t("common.latest")
+ : checkRun.createTime
+ ? humanizeDate(checkRun.createTime)
+ : `UID(${checkRun.uid})`;
+ return {
+ label,
+ value: checkRun.uid,
+ };
+ }
+ );
+});
+
+watch(selectedPlanCheckRunList, (list) => {
+ selectedPlanCheckRunUID.value = first(list)?.uid;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckRunButton.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckRunButton.vue
new file mode 100644
index 0000000000..39a387cdce
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/PlanCheckRunButton.vue
@@ -0,0 +1,122 @@
+<template>
+ <ContextMenuButton
+ v-if="actionList.length > 0"
+ :action-list="actionList"
+ :disabled="hasRunningPlanCheck"
+ 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="hasRunningPlanCheck" class="w-4 h-4" />
+ <heroicons-outline:play v-else class="w-4 h-4" />
+ </template>
+ <template #default="{ action }">
+ <template v-if="hasRunningPlanCheck">
+ {{ $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 { ContextMenuButton, ContextMenuButtonAction } from "@/components/v2";
+import {
+ PlanCheckRun_Status,
+ Task,
+ Task_Status,
+} from "@/types/proto/v1/rollout_service";
+import {
+ planCheckRunListForTask,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+
+type ButtonAction = ContextMenuButtonAction<{
+ taskList: Task[];
+}>;
+
+const props = defineProps<{
+ task: Task;
+}>();
+
+defineEmits<{
+ (event: "run-checks", taskList: Task[]): void;
+}>();
+
+const { t } = useI18n();
+const { isCreating, issue } = useIssueContext();
+
+const allowRunCheckForIssue = computed(() => {
+ if (isCreating.value) {
+ return false;
+ }
+ if (issue.value.status !== IssueStatus.OPEN) {
+ return false;
+ }
+ return true;
+});
+
+const actionList = computed(() => {
+ if (!allowRunCheckForIssue.value) return [];
+
+ const actionList: ButtonAction[] = [];
+ if (allowRunChecksForTask(props.task)) {
+ actionList.push({
+ key: "RUN-CHECKS",
+ text: t("task.run-checks"),
+ params: {
+ taskList: [props.task],
+ },
+ });
+
+ // TODO: never show 'run checks in current stage' by now
+ // since RolloutService.RunPlanChecks will actually run all plan checks
+ // for the entire plan
+
+ // // Don't only show 'run checks in current stage' if we don't show 'run checks'
+ // // since that might be weird.
+ // const stage = stageForTask(issue.value, props.task);
+ // if (stage) {
+ // const taskListInStage = stage.tasks;
+ // 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 hasRunningPlanCheck = computed((): boolean => {
+ if (isCreating.value) return false;
+
+ const planCheckRunList = planCheckRunListForTask(issue.value, props.task);
+ return planCheckRunList.some(
+ (checkRun) => checkRun.status === PlanCheckRun_Status.RUNNING
+ );
+});
+
+const allowRunChecksForTask = (task: Task) => {
+ return (
+ task.status === Task_Status.NOT_STARTED ||
+ task.status === Task_Status.PENDING ||
+ task.status === Task_Status.RUNNING ||
+ task.status === Task_Status.FAILED
+ );
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/index.ts b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/index.ts
new file mode 100644
index 0000000000..86b498a89c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckBar/index.ts
@@ -0,0 +1,3 @@
+import PlanCheckBar from "./PlanCheckBar.vue";
+
+export default PlanCheckBar;
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckSection.vue b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckSection.vue
new file mode 100644
index 0000000000..aafc714f09
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/PlanCheckSection.vue
@@ -0,0 +1,76 @@
+<template>
+ <div class="issue-debug">
+ <h3>plan check section</h3>
+ <div v-if="!isCreating">
+ <NButton type="primary" @click="runPlanChecks">Run plan checks</NButton>
+ </div>
+ <div>
+ issue.planCheckRunList.length: {{ issue.planCheckRunList.length }}
+ </div>
+ </div>
+
+ <PlanCheckBar
+ v-if="!isCreating"
+ :allow-run-checks="allowRunChecks"
+ :task="selectedTask"
+ class="px-4 py-2"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { NButton } from "naive-ui";
+
+import { rolloutServiceClient } from "@/grpcweb";
+import { useCurrentUserV1 } from "@/store";
+import {
+ extractUserResourceName,
+ hasWorkspacePermissionV1,
+ isOwnerOfProjectV1,
+} from "@/utils";
+import { useIssueContext } from "@/components/IssueV1/logic";
+import PlanCheckBar from "./PlanCheckBar";
+
+const currentUser = useCurrentUserV1();
+const { isCreating, issue, selectedTask } = useIssueContext();
+
+const allowRunChecks = computed(() => {
+ // Allowing below users to run plan checks
+ // - the creator of the issue
+ // - the assignee of the issue
+ // - project owners
+ // - workspace DBAs/owners
+ const me = currentUser.value;
+ if (extractUserResourceName(issue.value.creator) === me.email) {
+ return true;
+ }
+ if (extractUserResourceName(issue.value.assignee) === me.email) {
+ return true;
+ }
+ if (isOwnerOfProjectV1(issue.value.projectEntity.iamPolicy, me)) {
+ return true;
+ }
+ if (
+ hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-issue",
+ me.userRole
+ )
+ ) {
+ return true;
+ }
+ return false;
+});
+
+const runPlanChecks = async () => {
+ const plan = issue.value.planEntity;
+ if (!plan) return;
+
+ try {
+ await rolloutServiceClient.runPlanChecks({
+ name: plan.name,
+ });
+ } catch (ex) {
+ // debugger;
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/PlanCheckSection/index.ts b/frontend/src/components/IssueV1/components/PlanCheckSection/index.ts
new file mode 100644
index 0000000000..fa794844a4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/PlanCheckSection/index.ts
@@ -0,0 +1,6 @@
+import PlanCheckSection from "./PlanCheckSection.vue";
+import PlanCheckBar from "./PlanCheckBar";
+
+export default PlanCheckSection;
+
+export { PlanCheckBar };
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vue
new file mode 100644
index 0000000000..9443f0cd1e
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/Actions.vue
@@ -0,0 +1,12 @@
+<template>
+ <div class="flex flex-col items-end gap-y-2">
+ <EarliestAllowedTime />
+
+ <RollbackSection />
+ </div>
+</template>
+
+<script setup lang="ts">
+import EarliestAllowedTime from "./EarliestAllowedTime.vue";
+import RollbackSection from "./RollbackSection";
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/EarliestAllowedTime.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/EarliestAllowedTime.vue
new file mode 100644
index 0000000000..18301451d8
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/EarliestAllowedTime.vue
@@ -0,0 +1,150 @@
+<template>
+ <div class="flex items-center gap-x-3">
+ <h2 class="flex flex-col items-end">
+ <NTooltip>
+ <template #trigger>
+ <div class="flex gap-x-1 items-center textlabel">
+ {{ $t("common.when") }}
+ </div>
+ </template>
+ <template #default>
+ <div class="w-60">
+ {{ $t("task.earliest-allowed-time-hint") }}
+ </div>
+ </template>
+ </NTooltip>
+
+ <div class="text-gray-600 text-xs">
+ {{ "UTC" + dayjs().format("ZZ") }}
+ </div>
+ </h2>
+ <div class="w-[12rem]">
+ <NTooltip :disabled="allowEditEarliestAllowedTime">
+ <template #trigger>
+ <NDatePicker
+ :value="earliestAllowedTime"
+ :is-date-disabled="isDayPassed"
+ :placeholder="$t('task.earliest-allowed-time-unset')"
+ :disabled="!allowEditEarliestAllowedTime || isUpdating"
+ :loading="isUpdating"
+ :actions="['clear', 'confirm']"
+ type="datetime"
+ clearable
+ @update:value="handleUpdateEarliestAllowedTime"
+ />
+ </template>
+ <template #default>
+ <div class="w-48">
+ {{ $t("task.earliest-allowed-time-no-modify") }}
+ </div>
+ </template>
+ </NTooltip>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { useNow } from "@vueuse/core";
+import { NDatePicker, NTooltip } from "naive-ui";
+import dayjs from "dayjs";
+import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
+import { cloneDeep } from "lodash-es";
+import { useI18n } from "vue-i18n";
+
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import { Task_Status } from "@/types/proto/v1/rollout_service";
+import { rolloutServiceClient } from "@/grpcweb";
+import { pushNotification, useCurrentUserV1 } from "@/store";
+import { extractUserResourceName } from "@/utils";
+import {
+ notifyNotEditableLegacyIssue,
+ specForTask,
+ useIssueContext,
+} from "@/components/IssueV1";
+
+dayjs.extend(isSameOrAfter);
+
+const { t } = useI18n();
+const currentUser = useCurrentUserV1();
+const { isCreating, issue, isTenantMode, selectedTask, events } =
+ useIssueContext();
+const isUpdating = ref(false);
+
+// `null` to "Unset"
+const earliestAllowedTime = computed(() => {
+ const spec = specForTask(issue.value.planEntity, selectedTask.value);
+ return spec?.earliestAllowedTime ? spec.earliestAllowedTime.getTime() : null;
+});
+
+const allowEditEarliestAllowedTime = computed(() => {
+ if (isTenantMode.value) {
+ return false;
+ }
+ if (isCreating.value) {
+ return true;
+ }
+ // only the assignee is allowed to modify EarliestAllowedTime
+ const task = selectedTask.value;
+
+ if (issue.value.status !== IssueStatus.OPEN) {
+ return false;
+ }
+ if (![Task_Status.NOT_STARTED, Task_Status.PENDING].includes(task.status)) {
+ return false;
+ }
+
+ return (
+ extractUserResourceName(issue.value.creator) === currentUser.value.email
+ );
+});
+
+const handleUpdateEarliestAllowedTime = async (timestampMS: number | null) => {
+ if (isCreating.value) {
+ const spec = specForTask(issue.value.planEntity, selectedTask.value);
+ if (!spec) return;
+ if (!timestampMS) {
+ spec.earliestAllowedTime = undefined;
+ } else {
+ spec.earliestAllowedTime = new Date();
+ spec.earliestAllowedTime.setTime(timestampMS);
+ }
+ } else {
+ const planPatch = cloneDeep(issue.value.planEntity);
+ const spec = specForTask(issue.value.planEntity, selectedTask.value);
+ if (!planPatch || !spec) {
+ notifyNotEditableLegacyIssue();
+ return;
+ }
+
+ isUpdating.value = true;
+ try {
+ if (!timestampMS) {
+ spec.earliestAllowedTime = undefined;
+ } else {
+ spec.earliestAllowedTime = new Date();
+ spec.earliestAllowedTime.setTime(timestampMS);
+ }
+
+ const updatedPlan = await rolloutServiceClient.updatePlan({
+ plan: planPatch,
+ updateMask: ["steps"],
+ });
+ issue.value.planEntity = updatedPlan;
+
+ events.emit("status-changed", { eager: true });
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } finally {
+ isUpdating.value = false;
+ }
+ }
+};
+
+const now = useNow();
+const isDayPassed = (ts: number) => !dayjs(ts).isSameOrAfter(now.value, "day");
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/LogButton.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/LogButton.vue
new file mode 100644
index 0000000000..28e2cf2c52
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/LogButton.vue
@@ -0,0 +1,9 @@
+<template>
+ <div class="flex items-center">
+ <RollbackSwitch />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import RollbackSwitch from "./RollbackSwitch.vue";
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/LoggingButton.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/LoggingButton.vue
new file mode 100644
index 0000000000..8b653b44f8
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/LoggingButton.vue
@@ -0,0 +1,32 @@
+<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 { computed } from "vue";
+import { NTooltip } from "naive-ui";
+import { useRollbackContext } from "./common";
+
+const { allowRollback, toggleRollback } = useRollbackContext();
+
+const disabled = computed(() => !allowRollback.value);
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackSection.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackSection.vue
new file mode 100644
index 0000000000..b4d13f046f
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackSection.vue
@@ -0,0 +1,41 @@
+<template>
+ <div v-if="rollbackUIType !== 'NONE'" class="flex items-center gap-x-3">
+ <NTooltip>
+ <template #trigger>
+ <div class="textlabel flex items-center">
+ {{ $t("task.rollback.sql-rollback") }}
+ </div>
+ </template>
+ <template #default>
+ <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>
+ </template>
+ </NTooltip>
+ <div class="w-[12rem]">
+ <RollbackSwitch v-if="rollbackUIType === 'SWITCH'" />
+ <RollbackStatus v-if="rollbackUIType === 'FULL'" />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { NTooltip } from "naive-ui";
+
+import { useRollbackContext } from "./common";
+import RollbackSwitch from "./RollbackSwitch.vue";
+import RollbackStatus from "./RollbackStatus.vue";
+
+const rollbackContext = useRollbackContext();
+
+const { rollbackUIType } = rollbackContext;
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vue
new file mode 100644
index 0000000000..89182a83dc
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackStatus.vue
@@ -0,0 +1,188 @@
+<template>
+ <div class="text-sm font-medium">
+ <template v-if="!config?.rollbackEnabled">
+ <LogButton />
+ </template>
+ <template v-else>
+ <template v-if="config?.rollbackSqlStatus === RollbackSqlStatus.FAILED">
+ <div class="tooltip-wrapper">
+ <NTooltip>
+ <template #trigger>
+ <span class="text-error">{{ $t("task.rollback.failed") }}</span>
+ </template>
+
+ <div v-if="config.rollbackError" class="max-w-[20rem]">
+ {{ config.rollbackError }}
+ </div>
+ </NTooltip>
+ </div>
+ </template>
+ <template
+ v-else-if="config?.rollbackSqlStatus === RollbackSqlStatus.DONE"
+ >
+ <template
+ v-if="taskRollbackBy && rollbackByIssue.uid !== String(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>
+ <NButton
+ v-if="allowPreviewRollback"
+ size="small"
+ @click="tryRollbackTask"
+ >
+ {{ $t("task.rollback.preview-rollback-issue") }}
+ </NButton>
+ <NTooltip v-else :disabled="!!config?.rollbackSheet">
+ <template #trigger>
+ <NButton :disabled="true" size="small" tag="div">
+ {{ $t("task.rollback.preview-rollback-issue") }}
+ </NButton>
+ </template>
+
+ <div v-if="!config?.rollbackSheet" 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 { computed, reactive, ref } from "vue";
+import { useRouter } from "vue-router";
+import { NTooltip } from "naive-ui";
+
+import {
+ ActivityIssueCommentCreatePayload,
+ TaskRollbackBy,
+ UNKNOWN_ID,
+ unknownIssue,
+} from "@/types";
+import { extractSheetUID } from "@/utils";
+import { LogEntity_Action } from "@/types/proto/v1/logging_service";
+import { useActivityV1Store, useSheetV1Store } from "@/store";
+import { Task_DatabaseDataUpdate_RollbackSqlStatus as RollbackSqlStatus } from "@/types/proto/v1/rollout_service";
+import LogButton from "./LogButton.vue";
+import LoggingButton from "./LoggingButton.vue";
+import LearnMoreLink from "@/components/LearnMoreLink.vue";
+import { databaseForTask, useIssueContext } from "@/components/IssueV1";
+import { useRollbackContext } from "./common";
+import IssueStatusIcon from "../../../IssueStatusIcon.vue";
+
+type LocalState = {
+ loading: boolean;
+};
+
+const router = useRouter();
+const sheetV1Store = useSheetV1Store();
+
+const { issue, selectedTask: task } = useIssueContext();
+const { allowRollback } = useRollbackContext();
+
+const config = computed(() => task.value.databaseDataUpdate);
+
+const state = reactive<LocalState>({
+ loading: false,
+});
+
+const allowPreviewRollback = computed(() => {
+ if (!allowRollback.value) {
+ return false;
+ }
+ if (!config.value?.rollbackSheet) {
+ return false;
+ }
+ return true;
+});
+
+const taskRollbackBy = computed((): TaskRollbackBy | undefined => {
+ const activityList = useActivityV1Store().getActivityListByIssue(
+ issue.value.uid
+ );
+ // 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 rollbackByIssue = ref(unknownIssue()); // TODO
+
+const tryRollbackTask = async () => {
+ // const navigateToRollbackIssue = () => {
+ // if (!state.rollbackIssue) return;
+ // router.push(`/issue/${state.rollbackIssue.uid}`);
+ // };
+
+ // if (state.rollbackIssue) {
+ // return navigateToRollbackIssue();
+ // }
+
+ if (!config.value) return;
+ try {
+ state.loading = true;
+
+ const issueName = [
+ `Rollback`,
+ `#${issue.value.uid}`,
+ `${issue.value.title}`,
+ ].join(" ");
+
+ const originalSheet = await sheetV1Store.getOrFetchSheetByName(
+ config.value.sheet
+ );
+ 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.projectEntity.uid,
+ databaseList: [databaseForTask(issue.value, task.value).uid].join(","),
+ rollbackIssueId: issue.value.uid,
+ rollbackTaskIdList: [task.value.uid].join(","),
+ sheetId: extractSheetUID(config.value.rollbackSheet),
+ description,
+ },
+ });
+ } finally {
+ state.loading = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackSwitch.vue b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackSwitch.vue
new file mode 100644
index 0000000000..09aeae9845
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/RollbackSwitch.vue
@@ -0,0 +1,42 @@
+<template>
+ <div class="flex items-center">
+ <NSwitch
+ :disabled="!allowRollback"
+ :value="rollbackEnabled"
+ class="bb-rollback-switch"
+ @update:value="toggleRollback"
+ >
+ <template #checked>
+ <span style="font-size: 10px">{{ $t("common.on") }}</span>
+ </template>
+ <template #unchecked>
+ <span style="font-size: 10px">{{ $t("common.off") }}</span>
+ </template>
+ </NSwitch>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { useRollbackContext } from "./common";
+import { NSwitch } from "naive-ui";
+
+const { allowRollback, rollbackEnabled, toggleRollback } = useRollbackContext();
+</script>
+
+<style>
+.bb-rollback-switch {
+ --n-width: max(
+ var(--n-rail-width),
+ calc(var(--n-rail-width) + var(--n-button-width) - var(--n-rail-height))
+ ) !important;
+}
+.bb-rollback-switch .n-switch__checked {
+ padding-right: calc(var(--n-rail-height) - var(--n-offset) + 1px) !important;
+}
+.bb-rollback-switch .n-switch__unchecked {
+ padding-left: calc(var(--n-rail-height) - var(--n-offset) + 1px) !important;
+}
+.bb-rollback-switch .n-switch__button-placeholder {
+ width: calc(1.25 * var(--n-rail-height)) !important;
+}
+</style>
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/common.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/common.ts
new file mode 100644
index 0000000000..494461054c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/common.ts
@@ -0,0 +1,259 @@
+import { computed } from "vue";
+
+import { ComposedIssue, UNKNOWN_ID } from "@/types";
+import {
+ extractUserResourceName,
+ flattenTaskV1List,
+ hasPermissionInProjectV1,
+ hasWorkspacePermissionV1,
+ semverCompare,
+} from "@/utils";
+import {
+ useCurrentUserV1,
+ experimentalFetchIssueByName,
+ useIssueV1Store,
+ pushNotification,
+} from "@/store";
+import { Engine } from "@/types/proto/v1/common";
+import {
+ databaseForTask,
+ notifyNotEditableLegacyIssue,
+ specForTask,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { Task, Task_Status, Task_Type } from "@/types/proto/v1/rollout_service";
+import { cloneDeep } from "lodash-es";
+import { rolloutServiceClient } from "@/grpcweb";
+import { useI18n } from "vue-i18n";
+
+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 useRollbackContext = () => {
+ const currentUserV1 = useCurrentUserV1();
+ const context = useIssueContext();
+ const { t } = useI18n();
+ const { isCreating, issue, selectedTask: task, events } = context;
+ const project = computed(() => issue.value.projectEntity);
+
+ // Decide with type of UI should be displayed.
+ const rollbackUIType = computed((): RollbackUIType => {
+ if (task.value.type !== Task_Type.DATABASE_DATA_UPDATE) {
+ return "NONE";
+ }
+
+ const database = databaseForTask(issue.value, 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 (isCreating.value) {
+ return "SWITCH";
+ }
+
+ switch (task.value.status) {
+ case Task_Status.SKIPPED:
+ return "NONE";
+ case Task_Status.CANCELED:
+ return "NONE";
+ case Task_Status.DONE:
+ return "FULL";
+ default:
+ return "SWITCH";
+ }
+ });
+
+ // Decide whether current user can operate.
+ const allowRollback = computed((): boolean => {
+ if (rollbackUIType.value === "NONE") {
+ return false;
+ }
+
+ if (isCreating.value) {
+ return true;
+ }
+
+ const user = currentUserV1.value;
+
+ if (user.email === extractUserResourceName(issue.value.creator)) {
+ // Allowed to the issue creator
+ return true;
+ }
+
+ if (user.email === extractUserResourceName(issue.value.assignee)) {
+ // Allowed to the issue assignee
+ return true;
+ }
+
+ if (
+ hasPermissionInProjectV1(
+ project.value.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 (isCreating.value) {
+ const spec = specForTask(issue.value.planEntity, task.value);
+ return spec?.changeDatabaseConfig?.rollbackEnabled ?? false;
+ } else {
+ return task.value.databaseDataUpdate?.rollbackEnabled ?? false;
+ }
+ });
+
+ const toggleRollback = async (on: boolean) => {
+ if (isCreating.value) {
+ const config = task.value.databaseDataUpdate;
+ if (config) {
+ config.rollbackEnabled = on;
+ }
+ const spec = specForTask(issue.value.planEntity, task.value);
+ if (spec && spec.changeDatabaseConfig) {
+ spec.changeDatabaseConfig.rollbackEnabled = on;
+ }
+ } else {
+ // patch plan to reconcile rollout/stages/tasks
+ const planPatch = cloneDeep(issue.value.planEntity);
+ const spec = specForTask(planPatch, task.value);
+ if (!planPatch || !spec || !spec.changeDatabaseConfig) {
+ notifyNotEditableLegacyIssue();
+ return;
+ }
+ spec.changeDatabaseConfig.rollbackEnabled = on;
+ if (task.value.databaseDataUpdate) {
+ task.value.databaseDataUpdate.rollbackEnabled = on;
+ }
+
+ const updatedPlan = await rolloutServiceClient.updatePlan({
+ plan: planPatch,
+ updateMask: ["steps"],
+ });
+ issue.value.planEntity = updatedPlan;
+
+ const action = on ? "Enable" : "Disable";
+ events.emit("status-changed", { eager: true });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+
+ try {
+ await useIssueV1Store().createIssueComment({
+ issueId: issue.value.uid,
+ comment: `${action} SQL rollback log for task [${issue.value.title}].`,
+ payload: {
+ issueName: issue.value.title,
+ },
+ });
+ } catch {
+ // fail to comment won't be too bad
+ }
+ }
+ };
+
+ return {
+ rollbackUIType,
+ allowRollback,
+ rollbackEnabled,
+ toggleRollback,
+ };
+};
+
+export const maybeCreateBackTraceComments = async (newIssue: ComposedIssue) => {
+ const rollbackList = [] as Array<{
+ byTask: Task;
+ fromIssue: string;
+ fromTask: string;
+ }>;
+ const taskList = flattenTaskV1List(newIssue.rolloutEntity);
+ for (let i = 0; i < taskList.length; i++) {
+ const byTask = taskList[i];
+ if (byTask.type !== Task_Type.DATABASE_DATA_UPDATE) {
+ continue;
+ }
+ const config = byTask.databaseDataUpdate;
+ if (!config) {
+ continue;
+ }
+ if (config.rollbackFromIssue && config.rollbackFromTask) {
+ rollbackList.push({
+ byTask,
+ fromIssue: config.rollbackFromIssue,
+ fromTask: config.rollbackFromTask,
+ });
+ }
+ }
+ if (rollbackList.length === 0) return;
+
+ for (let i = 0; i < rollbackList.length; i++) {
+ const {
+ // byTask,
+ fromIssue: fromIssueName,
+ fromTask: fromTaskName,
+ } = rollbackList[i];
+ const fromIssue = await experimentalFetchIssueByName(fromIssueName);
+
+ if (fromIssue.uid === String(UNKNOWN_ID)) continue;
+ const fromTask = flattenTaskV1List(fromIssue.rolloutEntity).find(
+ (task) => task.name === fromTaskName
+ );
+ if (!fromTask || fromTask.uid === String(UNKNOWN_ID)) continue;
+
+ // const comment = [
+ // `Create issue #${newIssue.uid}`,
+ // "to rollback task",
+ // `[${fromTask.title}]`,
+ // ].join(" ");
+ try {
+ // TODO: create comment
+ // await useIssueV1Store().createIssueComment({
+ // issueId: fromIssue.uid,
+ // 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/IssueV1/components/StageSection/Actions/RollbackSection/index.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/index.ts
new file mode 100644
index 0000000000..947da313d6
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/RollbackSection/index.ts
@@ -0,0 +1,3 @@
+import RollbackSection from "./RollbackSection.vue";
+
+export default RollbackSection;
diff --git a/frontend/src/components/IssueV1/components/StageSection/Actions/index.ts b/frontend/src/components/IssueV1/components/StageSection/Actions/index.ts
new file mode 100644
index 0000000000..9793717924
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/Actions/index.ts
@@ -0,0 +1,3 @@
+import Actions from "./Actions.vue";
+
+export default Actions;
diff --git a/frontend/src/components/IssueV1/components/StageSection/StageInfo/DatabaseInfo.vue b/frontend/src/components/IssueV1/components/StageSection/StageInfo/DatabaseInfo.vue
new file mode 100644
index 0000000000..9624fcc7ff
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/StageInfo/DatabaseInfo.vue
@@ -0,0 +1,121 @@
+<template>
+ <div class="flex items-center flex-wrap gap-1">
+ <EnvironmentV1Name
+ :environment="environment"
+ :plain="true"
+ :tooltip="true"
+ class="hover:underline"
+ />
+
+ <heroicons-outline:chevron-right class="text-control-light" />
+
+ <InstanceV1Name
+ :instance="coreDatabaseInfo.instanceEntity"
+ :plain="true"
+ class="hover:underline"
+ />
+
+ <heroicons-outline:chevron-right class="text-control-light" />
+
+ <div class="flex items-center gap-x-1">
+ <heroicons-outline:database />
+
+ <DatabaseV1Name
+ v-if="database"
+ :database="database"
+ :plain="true"
+ class="hover:underline"
+ />
+ <span v-else>
+ {{ coreDatabaseInfo.databaseName }}
+ </span>
+
+ <span
+ v-if="databaseCreationStatus !== 'EXISTED'"
+ class="text-control-light"
+ >
+ {{
+ databaseCreationStatus === "CREATED"
+ ? $t("task.database-create.created")
+ : $t("task.database-create.pending")
+ }}
+ </span>
+
+ <SQLEditorButtonV1 v-if="database" :database="database" />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import { UNKNOWN_ID } from "@/types";
+import { Task_Status, Task_Type } from "@/types/proto/v1/rollout_service";
+import { SQLEditorButtonV1 } from "@/components/DatabaseDetail";
+import { DatabaseV1Name, InstanceV1Name } from "@/components/v2";
+import { useDatabaseV1Store } from "@/store";
+import {
+ databaseForTask,
+ stageForTask,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+
+type DatabaseCreationStatus = "EXISTED" | "PENDING_CREATE" | "CREATED";
+
+const { issue, selectedTask } = useIssueContext();
+const coreDatabaseInfo = computed(() => {
+ return databaseForTask(issue.value, selectedTask.value);
+});
+
+const databaseCreationStatus = computed((): DatabaseCreationStatus => {
+ const task = selectedTask.value;
+
+ // For database create task, see if its task status is "DONE"
+ if (task.type === Task_Type.DATABASE_CREATE) {
+ if (task.status === Task_Status.DONE) return "CREATED";
+ else return "PENDING_CREATE";
+ }
+
+ // For database restore target, find its related database create task
+ // and check its status.
+ if (
+ task.type === Task_Type.DATABASE_RESTORE_RESTORE &&
+ task.databaseRestoreRestore
+ ) {
+ const targetDatabase = task.databaseRestoreRestore.target || task.target;
+ if (
+ useDatabaseV1Store().getDatabaseByName(targetDatabase).uid !==
+ String(UNKNOWN_ID)
+ ) {
+ return "EXISTED";
+ }
+
+ if (!targetDatabase) return "PENDING_CREATE";
+ const stage = stageForTask(issue.value, selectedTask.value);
+ if (!stage) return "PENDING_CREATE";
+
+ const targetDatabaseCreateTask = stage.tasks.find((t) => {
+ return (
+ t.type === Task_Type.DATABASE_CREATE &&
+ t.databaseCreate &&
+ `${t.target}/databases/${t.databaseCreate.database}` === targetDatabase
+ );
+ });
+ if (targetDatabaseCreateTask?.status === Task_Status.DONE) return "CREATED";
+ return "PENDING_CREATE";
+ }
+ return "EXISTED";
+});
+
+const environment = computed(() => {
+ return coreDatabaseInfo.value.instanceEntity.environmentEntity;
+});
+
+const database = computed(() => {
+ const maybeExistedDatabase = coreDatabaseInfo.value;
+ if (maybeExistedDatabase.uid !== String(UNKNOWN_ID)) {
+ return maybeExistedDatabase;
+ }
+ return undefined;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/StageInfo/StageInfo.vue b/frontend/src/components/IssueV1/components/StageSection/StageInfo/StageInfo.vue
new file mode 100644
index 0000000000..32efe311ba
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/StageInfo/StageInfo.vue
@@ -0,0 +1,13 @@
+<template>
+ <div
+ class="flex flex-col lg:flex-row lg:flex-wrap lg:items-center justify-start gap-y-2 gap-x-4 text-sm"
+ >
+ <StageSelect />
+ <DatabaseInfo />
+ </div>
+</template>
+
+<script setup lang="ts">
+import StageSelect from "./StageSelect.vue";
+import DatabaseInfo from "./DatabaseInfo.vue";
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/StageInfo/StageSelect.vue b/frontend/src/components/IssueV1/components/StageSection/StageInfo/StageSelect.vue
new file mode 100644
index 0000000000..3007a451a7
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/StageInfo/StageSelect.vue
@@ -0,0 +1,79 @@
+<template>
+ <div class="flex items-center gap-x-2">
+ <div class="textlabel">
+ {{ $t("common.stage") }}
+ </div>
+ <NSelect
+ :value="selectedStage.name"
+ :options="options"
+ :render-label="renderLabel"
+ style="width: 12rem"
+ @update-value="handleSelectStage"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, h } from "vue";
+import { NSelect, SelectOption } from "naive-ui";
+import { useI18n } from "vue-i18n";
+import { first } from "lodash-es";
+
+import { Stage } from "@/types/proto/v1/rollout_service";
+import { activeTaskInStageV1 } from "@/utils";
+import { EMPTY_TASK_NAME } from "@/types";
+import { useIssueContext } from "../../../logic";
+
+type StageSelectOption = SelectOption & {
+ stage: Stage;
+};
+
+const { t } = useI18n();
+const { isCreating, issue, activeStage, selectedStage, events } =
+ useIssueContext();
+
+const stageList = computed(() => issue.value.rolloutEntity.stages);
+
+const options = computed(() => {
+ return stageList.value.map<StageSelectOption>((stage) => ({
+ value: stage.name,
+ label: stage.title,
+ stage,
+ }));
+});
+
+const renderLabel = (option: SelectOption) => {
+ const { stage } = option as StageSelectOption;
+
+ const text =
+ !isCreating.value && stage === activeStage.value
+ ? t("issue.stage-select.active", { name: stage.title })
+ : stage.title;
+ return h("div", { class: "flex items-center gap-x-1" }, [
+ h("span", {}, text),
+ ]);
+};
+
+const activeOrFirstTaskInStage = (stage: Stage) => {
+ if (isCreating.value) {
+ return first(stage.tasks);
+ }
+ const activeTask = activeTaskInStageV1(stage);
+ if (activeTask.name === EMPTY_TASK_NAME) {
+ return first(stage.tasks);
+ }
+ return activeTask;
+};
+
+const handleSelectStage = (name: string) => {
+ const stage = stageList.value.find((s) => s.name === name);
+ if (stage === selectedStage.value) return;
+
+ if (stage) {
+ const task = activeOrFirstTaskInStage(stage);
+ if (task) {
+ events.emit("select-task", { task });
+ }
+ }
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/StageInfo/index.ts b/frontend/src/components/IssueV1/components/StageSection/StageInfo/index.ts
new file mode 100644
index 0000000000..a45c5c2960
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/StageInfo/index.ts
@@ -0,0 +1,3 @@
+import StageInfo from "./StageInfo.vue";
+
+export default StageInfo;
diff --git a/frontend/src/components/IssueV1/components/StageSection/StageSection.vue b/frontend/src/components/IssueV1/components/StageSection/StageSection.vue
new file mode 100644
index 0000000000..3b12942830
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/StageSection.vue
@@ -0,0 +1,147 @@
+<template>
+ <div v-if="show" class="w-full px-4 py-2 flex flex-col gap-y-2">
+ <div class="stage" :class="stageClass">
+ <TaskStatusIcon
+ :create="isCreating"
+ :active="isActiveStage"
+ :status="activeTaskInStage.status"
+ :ignore-task-check-status="true"
+ />
+
+ <div class="text">
+ <div class="text-sm min-w-32 lg:min-w-fit with-underline space-x-1">
+ <heroicons:arrow-small-right
+ v-if="isActiveStage"
+ class="w-5 h-5 inline-block mb-0.5"
+ />
+ <span>{{ $t("common.stage") }} - {{ stage.title }}</span>
+ </div>
+ <div class="text-xs flex flex-col gap-1 md:flex-row md:items-center">
+ <div class="whitespace-pre-wrap break-all with-underline">
+ {{ taskTitle }}
+ </div>
+ <StageSummary :stage="(stage as Stage)" />
+ </div>
+ </div>
+
+ <NTooltip v-if="isCreating && !isValid" trigger="hover" placement="top">
+ <template #trigger>
+ <heroicons:exclamation-circle-solid
+ class="w-6 h-6 ml-2 text-error hover:text-error-hover"
+ />
+ </template>
+ <span>Missing SQL statement</span>
+ </NTooltip>
+ </div>
+
+ <div class="lg:flex items-start justify-between">
+ <StageInfo />
+
+ <Actions />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { NTooltip } from "naive-ui";
+import { first } from "lodash-es";
+
+import { Stage, task_StatusToJSON } from "@/types/proto/v1/rollout_service";
+import { EMPTY_STAGE_NAME, emptyTask } from "@/types";
+import { activeTaskInStageV1 } from "@/utils";
+import {
+ isTaskFinished,
+ isValidStage,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import TaskStatusIcon from "../TaskStatusIcon.vue";
+import StageSummary from "./StageSummary.vue";
+import StageInfo from "./StageInfo";
+import Actions from "./Actions";
+
+const { isCreating, activeTask, selectedStage: stage } = useIssueContext();
+
+const show = computed(() => {
+ return stage.value.name !== EMPTY_STAGE_NAME;
+});
+
+const activeTaskInStage = computed(() => {
+ return activeTaskInStageV1(stage.value);
+});
+
+const isValid = computed(() => {
+ return isValidStage(stage.value);
+});
+
+const isActiveStage = computed(() => {
+ if (isCreating.value) {
+ // In create mode we don't have an ActiveStage
+ return false;
+ }
+
+ const taskFound = stage.value.tasks.find(
+ (t) => t.uid === activeTask.value.uid
+ );
+ if (taskFound && !isTaskFinished(taskFound)) {
+ // A stage is "Active" if the ActiveTaskOfPipeline is inside this stage
+ return true;
+ }
+
+ return false;
+});
+
+const stageClass = computed(() => {
+ const classList: string[] = [];
+ if (isCreating.value) {
+ classList.push("create");
+ if (!isValid.value) {
+ classList.push("invalid");
+ }
+ }
+ if (isActiveStage.value) classList.push("active");
+ const task = activeTaskInStage.value;
+ classList.push(`status_${task_StatusToJSON(task.status).toLowerCase()}`);
+
+ return classList;
+});
+
+const taskTitle = computed(() => {
+ const task = isCreating ? first(stage.value.tasks) : activeTaskInStage.value;
+ return (task ?? emptyTask()).title;
+});
+</script>
+
+<style scoped lang="postcss">
+.stage {
+ @apply cursor-default flex items-center justify-start w-full text-sm font-medium relative;
+ @apply lg:w-auto lg:flex-1;
+}
+.stage.invalid {
+ @apply pr-10;
+}
+
+.stage .text {
+ @apply cursor-pointer ml-4 flex flex-col gap-y-0.5;
+}
+.stage.active .text {
+ @apply font-bold;
+}
+.stage.status_done .text {
+ @apply text-control;
+}
+.stage.status_pending .text,
+.stage.status_pending_approval .text {
+ @apply text-control;
+}
+.stage.active.status_pending .text,
+.stage.active.status_pending_approval .text {
+ @apply text-info;
+}
+.stage.status_running .text {
+ @apply text-info;
+}
+.stage.status_failed .text {
+ @apply text-red-500;
+}
+</style>
diff --git a/frontend/src/components/IssueV1/components/StageSection/StageSummary.vue b/frontend/src/components/IssueV1/components/StageSection/StageSummary.vue
new file mode 100644
index 0000000000..f02e027f6c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/StageSummary.vue
@@ -0,0 +1,46 @@
+<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 { Stage, Task_Status } from "@/types/proto/v1/rollout_service";
+import { computed } from "vue";
+
+const props = defineProps<{
+ stage: Stage;
+}>();
+
+const summary = computed(() => {
+ const tasks = props.stage.tasks;
+ const summary = {
+ done: 0,
+ failed: 0,
+ canceled: 0,
+ running: 0,
+ total: tasks.length,
+ };
+ tasks.forEach((task) => {
+ switch (task.status) {
+ case Task_Status.DONE:
+ summary.done++;
+ break;
+ case Task_Status.FAILED:
+ summary.failed++;
+ break;
+ case Task_Status.CANCELED:
+ summary.canceled++;
+ break;
+ case Task_Status.RUNNING:
+ summary.running++;
+ break;
+ }
+ });
+ return summary;
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/StageSection/index.ts b/frontend/src/components/IssueV1/components/StageSection/index.ts
new file mode 100644
index 0000000000..0c240e16c6
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StageSection/index.ts
@@ -0,0 +1,3 @@
+import StageSection from "./StageSection.vue";
+
+export default StageSection;
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
new file mode 100644
index 0000000000..3b64eee881
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
@@ -0,0 +1,635 @@
+<template>
+ <div class="flex flex-col gap-y-2">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-x-4">
+ <div class="flex items-center gap-x-1 text-sm font-medium">
+ <span
+ :class="isEmpty(state.statement) ? 'text-red-600' : 'text-control'"
+ >
+ {{ statementTitle }}
+ </span>
+ <span v-if="isCreating" class="text-red-600">*</span>
+ <NButton
+ v-if="!isCreating && !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="isCreating && allowApplyTaskStateToOthers"
+ :disabled="isEmpty(state.statement)"
+ size="tiny"
+ @click.prevent="applyTaskStateToOthers"
+ >
+ {{ $t("issue.apply-to-other-tasks") }}
+ </NButton>
+ </div>
+
+ <div
+ v-if="selectedTask.type !== Task_Type.DATABASE_SCHEMA_BASELINE"
+ class="flex items-center justify-end gap-x-2"
+ >
+ <template v-if="isCreating">
+ <template v-if="allowEditStatementWhenCreating">
+ <FormatOnSaveCheckbox
+ v-model:value="formatOnSave"
+ :language="language"
+ />
+ <UploadProgressButton :upload="handleUploadFile" size="tiny">
+ {{ $t("issue.upload-sql") }}
+ </UploadProgressButton>
+ </template>
+ </template>
+
+ <template v-else>
+ <template v-if="!state.isEditing">
+ <template v-if="shouldShowEditButton">
+ <!-- for small size sheets, show full featured UI editing button group -->
+ <NTooltip :disabled="denyEditTaskReasons.length === 0">
+ <template #trigger>
+ <NButton
+ v-if="!isTaskSheetOversize"
+ size="tiny"
+ tag="div"
+ :disabled="denyEditTaskReasons.length > 0"
+ @click.prevent="beginEdit"
+ >
+ {{ $t("common.edit") }}
+ </NButton>
+ <!-- for oversized sheets, only allow to upload and overwrite the sheet -->
+ <UploadProgressButton
+ v-else
+ :upload="handleUploadAndOverwrite"
+ :disabled="denyEditTaskReasons.length > 0"
+ size="tiny"
+ >
+ {{ $t("issue.upload-sql") }}
+ </UploadProgressButton>
+ </template>
+ <template #default>
+ <ErrorList :errors="denyEditTaskReasons" />
+ </template>
+ </NTooltip>
+ </template>
+ </template>
+ <template v-else>
+ <FormatOnSaveCheckbox
+ v-model:value="formatOnSave"
+ :language="language"
+ />
+ <UploadProgressButton :upload="handleUploadFile" size="tiny">
+ {{ $t("issue.upload-sql") }}
+ </UploadProgressButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ :disabled="!allowSaveSQL"
+ @click.prevent="saveEdit"
+ >
+ {{ $t("common.save") }}
+ </NButton>
+ <NButton
+ v-if="state.isEditing"
+ size="tiny"
+ quaternary
+ @click.prevent="cancelEdit"
+ >
+ {{ $t("common.cancel") }}
+ </NButton>
+ </template>
+ </template>
+ </div>
+ </div>
+
+ <BBAttention
+ v-if="isTaskSheetOversize"
+ :style="`WARN`"
+ :title="$t('issue.statement-from-sheet-warning')"
+ >
+ <template #action>
+ <DownloadSheetButton v-if="sheetName" :sheet="sheetName" size="small" />
+ </template>
+ </BBAttention>
+
+ <div class="whitespace-pre-wrap overflow-hidden border">
+ <MonacoEditor
+ ref="editorRef"
+ class="w-full h-auto max-h-[360px] min-h-[120px]"
+ data-label="bb-issue-sql-editor"
+ :value="state.statement"
+ :readonly="isEditorReadonly"
+ :auto-focus="false"
+ :language="language"
+ :dialect="dialect"
+ :advices="isEditorReadonly ? markers : []"
+ @change="handleStatementChange"
+ @ready="handleMonacoEditorReady"
+ />
+ </div>
+ </div>
+
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.sql-review"
+ @cancel="state.showFeatureModal = false"
+ />
+
+ <div class="issue-debug">
+ <div>task: {{ selectedTask }}</div>
+ <div>sheetName: {{ sheetName }}</div>
+ <div>sheetReady: {{ sheetReady }}</div>
+ <div>sheetStatement.length: {{ sheetStatement.length }}</div>
+ <div>sheet.source: {{ sheet?.source }}</div>
+ <div>sheet.type: {{ sheet?.type }}</div>
+ <div>sheet.visibility: {{ sheet?.visibility }}</div>
+ <div>sheet.title: {{ sheet?.title }}</div>
+ <div>sheet.content.length: {{ sheet?.content?.length }}</div>
+ <div>isTaskSheetOversize: {{ isTaskSheetOversize }}</div>
+ <div>isEditorReadonly: {{ isEditorReadonly }}</div>
+ <div>state.isEditing: {{ state.isEditing }}</div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, h, reactive, watch } from "vue";
+import { NButton, NTooltip, useDialog } from "naive-ui";
+import { useRoute } from "vue-router";
+import { useI18n } from "vue-i18n";
+import { cloneDeep } from "lodash-es";
+
+import {
+ SQLDialect,
+ TaskTypeListWithStatement,
+ dialectOfEngineV1,
+} from "@/types";
+import { TenantMode } from "@/types/proto/v1/project_service";
+import { Plan_Spec, Task, Task_Type } from "@/types/proto/v1/rollout_service";
+import {
+ defer,
+ flattenTaskV1List,
+ getSheetStatement,
+ setSheetStatement,
+ sheetNameOfTaskV1,
+ useInstanceV1EditorLanguage,
+} from "@/utils";
+import {
+ databaseForTask,
+ getLocalSheetByName,
+ useIssueContext,
+ allowUserToEditStatementForTask,
+ stageForTask,
+ isTaskEditable,
+ specForTask,
+ createEmptyLocalSheet,
+ notifyNotEditableLegacyIssue,
+} from "@/components/IssueV1/logic";
+import { ErrorList } from "@/components/IssueV1/components/common";
+import {
+ hasFeature,
+ pushNotification,
+ useCurrentUserV1,
+ useSheetV1Store,
+ useUIStateStore,
+} from "@/store";
+import { rolloutServiceClient } from "@/grpcweb";
+import UploadProgressButton from "@/components/misc/UploadProgressButton.vue";
+import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";
+import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";
+import { EditState, useTempEditState } from "./useTempEditState";
+import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";
+import { useAutoEditorHeight } from "./useAutoEditorHeight";
+import { readFileAsync } from "./utils";
+
+type LocalState = EditState & {
+ showFeatureModal: boolean;
+ isUploadingFile: boolean;
+};
+
+const { t } = useI18n();
+const uiStateStore = useUIStateStore();
+const route = useRoute();
+const currentUser = useCurrentUserV1();
+const { events, isCreating, issue, selectedTask } = useIssueContext();
+const project = computed(() => issue.value.projectEntity);
+const dialog = useDialog();
+
+const state = reactive<LocalState>({
+ isEditing: false,
+ statement: "",
+ showFeatureModal: false,
+ isUploadingFile: false,
+});
+
+const { editorRef, updateEditorHeight } = useAutoEditorHeight();
+
+const selectedDatabase = computed(() => {
+ return databaseForTask(issue.value, selectedTask.value);
+});
+
+const language = useInstanceV1EditorLanguage(
+ computed(() => selectedDatabase.value.instanceEntity)
+);
+const dialect = computed((): SQLDialect => {
+ const db = selectedDatabase.value;
+ return dialectOfEngineV1(db.instanceEntity.engine);
+});
+const statementTitle = computed(() => {
+ return language.value === "sql" ? t("common.sql") : t("common.statement");
+});
+const { markers } = useSQLAdviceMarkers();
+
+const allowEditStatementWhenCreating = computed(() => {
+ if (route.query.sheetId) {
+ return false;
+ }
+ if (selectedTask.value.type === Task_Type.DATABASE_SCHEMA_BASELINE) {
+ return false;
+ }
+ return true;
+});
+
+/**
+ * to set the MonacoEditor as readonly
+ * This happens when
+ * - BASELINE issue
+ * - Not in edit mode
+ * - Disallowed to edit statement
+ */
+const isEditorReadonly = computed(() => {
+ if (selectedTask.value.type === Task_Type.DATABASE_SCHEMA_BASELINE) {
+ return true;
+ }
+ if (isCreating.value) {
+ return !allowEditStatementWhenCreating.value;
+ }
+ return (
+ !state.isEditing ||
+ // !allowEditStatement.value || // TODO
+ isTaskSheetOversize.value ||
+ // isGroupingChangeIssue(issue.value as Issue) || // TODO
+ false // TODO
+ );
+});
+
+const formatOnSave = computed({
+ get: () => uiStateStore.issueFormatStatementOnSave,
+ set: (value: boolean) => uiStateStore.setIssueFormatStatementOnSave(value),
+});
+
+const {
+ sheet,
+ sheetName,
+ sheetReady,
+ sheetStatement,
+ reset: resetTempEditState,
+} = useTempEditState(state);
+
+const isTaskSheetOversize = computed(() => {
+ if (isCreating.value) return false;
+ if (state.isEditing) return false;
+ if (!sheetReady.value) return false;
+ if (!sheet.value) return false;
+ return getSheetStatement(sheet.value).length < sheet.value.contentSize;
+});
+
+const denyEditTaskReasons = computed(() => {
+ return allowUserToEditStatementForTask(
+ issue.value,
+ selectedTask.value,
+ currentUser.value
+ );
+});
+
+const shouldShowEditButton = computed(() => {
+ // Need not to show "Edit" while the issue is still pending create.
+ if (isCreating.value) {
+ return false;
+ }
+ // Will show another button group as [Upload][Cancel][Save]
+ // while editing
+ if (state.isEditing) {
+ return false;
+ }
+
+ return true;
+});
+
+const allowApplyTaskStateToOthers = computed(() => {
+ if (!isCreating.value) {
+ return false;
+ }
+ if (project.value.tenantMode === TenantMode.TENANT_MODE_ENABLED) {
+ return false;
+ }
+
+ const taskList = flattenTaskV1List(issue.value.rolloutEntity);
+ // Allowed when more than one tasks need SQL statement or sheet.
+ const count = taskList.filter((task) =>
+ TaskTypeListWithStatement.includes(task.type)
+ ).length;
+
+ return count > 1;
+});
+
+const allowSaveSQL = computed((): boolean => {
+ if (state.statement === "") {
+ // Not allowed if the statement is empty.
+ return false;
+ }
+ if (!sheetReady.value) {
+ return false;
+ }
+ if (state.statement === sheetStatement.value) {
+ // Not allowed if the statement is not modified.
+ return false;
+ }
+
+ // Allowed to save otherwise
+ return true;
+});
+
+const beginEdit = () => {
+ state.isEditing = true;
+};
+
+const saveEdit = async () => {
+ try {
+ // TODO
+ await updateStatement(state.statement);
+ resetTempEditState();
+ await new Promise((r) => setTimeout(r, 500));
+ } finally {
+ state.isEditing = false;
+ }
+};
+
+const cancelEdit = () => {
+ state.statement = sheetStatement.value;
+ state.isEditing = false;
+};
+
+const chooseUpdateStatementTarget = () => {
+ type Target = "TASK" | "STAGE" | "ALL";
+ const d = defer<{ target: Target; tasks: Task[] }>();
+
+ const targets: Record<Target, Task[]> = {
+ TASK: [selectedTask.value],
+ STAGE: (stageForTask(issue.value, selectedTask.value)?.tasks ?? []).filter(
+ (task) => {
+ return (
+ TaskTypeListWithStatement.includes(task.type) &&
+ isTaskEditable(issue.value, task).length === 0
+ );
+ }
+ ),
+ ALL: flattenTaskV1List(issue.value.rolloutEntity).filter((task) => {
+ return (
+ TaskTypeListWithStatement.includes(task.type) &&
+ isTaskEditable(issue.value, task).length === 0
+ );
+ }),
+ };
+
+ if (targets.STAGE.length === 1 && targets.ALL.length === 1) {
+ d.resolve({ target: "TASK", tasks: targets.TASK });
+ return d.promise;
+ }
+
+ const $d = dialog.create({
+ title: t("issue.update-statement.self", { type: statementTitle.value }),
+ content: t("issue.update-statement.apply-current-change-to"),
+ type: "info",
+ autoFocus: false,
+ closable: false,
+ maskClosable: false,
+ closeOnEsc: false,
+ showIcon: false,
+ action: () => {
+ const finish = (target: Target) => {
+ d.resolve({ target, tasks: targets[target] });
+ $d.destroy();
+ };
+
+ const TASK = h(
+ NButton,
+ { size: "small", onClick: () => finish("TASK") },
+ {
+ default: () => t("issue.update-statement.target.selected-task"),
+ }
+ );
+ const buttons = [TASK];
+ if (targets.STAGE.length > 1) {
+ // More than one editable tasks in stage
+ // Add "Selected stage" option
+ const STAGE = h(
+ NButton,
+ { size: "small", onClick: () => finish("STAGE") },
+ {
+ default: () => t("issue.update-statement.target.selected-stage"),
+ }
+ );
+ buttons.push(STAGE);
+ }
+ if (targets.ALL.length > targets.STAGE.length) {
+ // More editable tasks in other stages
+ // Add "All tasks" option
+ const ALL = h(
+ NButton,
+ { size: "small", onClick: () => finish("ALL") },
+ {
+ default: () => t("issue.update-statement.target.all-tasks"),
+ }
+ );
+ buttons.push(ALL);
+ }
+
+ return h(
+ "div",
+ { class: "flex items-center justify-end gap-x-2" },
+ buttons
+ );
+ },
+ });
+
+ return d.promise;
+};
+
+const showOverwriteConfirmDialog = () => {
+ return new Promise((resolve, reject) => {
+ // Show a confirm dialog before replacing if the editing statement is not empty.
+ dialog.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 handleUploadAndOverwrite = async (event: Event) => {
+ if (state.isUploadingFile) {
+ return;
+ }
+ try {
+ state.isUploadingFile = true;
+ await showOverwriteConfirmDialog();
+ const { filename, content: statement } = await readFileAsync(event, 100);
+ state.isEditing = true;
+ state.statement = statement;
+ handleStatementChange(statement);
+ if (sheet.value) {
+ sheet.value.title = filename;
+ }
+
+ resetTempEditState();
+ updateEditorHeight();
+ } finally {
+ state.isUploadingFile = false;
+ }
+};
+
+const handleUploadFile = async (event: Event) => {
+ try {
+ state.isUploadingFile = true;
+ const { filename, content: statement } = await readFileAsync(event, 100);
+ handleStatementChange(statement);
+ if (sheet.value) {
+ sheet.value.title = filename;
+ }
+
+ resetTempEditState();
+ updateEditorHeight();
+ } finally {
+ state.isUploadingFile = false;
+ }
+};
+
+const applyTaskStateToOthers = async () => {
+ const taskList = flattenTaskV1List(issue.value.rolloutEntity).filter((task) =>
+ TaskTypeListWithStatement.includes(task.type)
+ );
+ for (let i = 0; i < taskList.length; i++) {
+ const task = taskList[i];
+ const sheetName = sheetNameOfTaskV1(task);
+ if (!sheetName) continue;
+ const sheet = getLocalSheetByName(sheetName);
+ setSheetStatement(sheet, state.statement);
+ }
+};
+
+const updateStatement = async (statement: string) => {
+ // - find the task related plan/step/spec
+ // - create a new sheet
+ // - update sheet id in the spec
+
+ // Find the target editing task(s)
+ // default to selectedTask
+ // also ask whether to apply the change to all tasks in the stage.
+ const { tasks } = await chooseUpdateStatementTarget();
+
+ const planPatch = cloneDeep(issue.value.planEntity);
+ if (!planPatch) {
+ notifyNotEditableLegacyIssue();
+ return;
+ }
+
+ const specs: Plan_Spec[] = [];
+ tasks.forEach((task) => {
+ const spec = specForTask(planPatch, task);
+ if (spec) {
+ specs.push(spec);
+ }
+ });
+ const distinctSpecIds = new Set(specs.map((s) => s.id));
+ if (distinctSpecIds.size === 0) {
+ notifyNotEditableLegacyIssue();
+ return;
+ }
+
+ const specsToPatch = planPatch.steps
+ .flatMap((step) => step.specs)
+ .filter((spec) => distinctSpecIds.has(spec.id));
+
+ const sheet = {
+ ...createEmptyLocalSheet(),
+ title: issue.value.title,
+ };
+ setSheetStatement(sheet, statement);
+ const createdSheet = await useSheetV1Store().createSheet(
+ issue.value.project,
+ sheet
+ );
+
+ for (let i = 0; i < specsToPatch.length; i++) {
+ const spec = specsToPatch[i];
+ const config = spec.changeDatabaseConfig;
+ if (!config) continue;
+ config.sheet = createdSheet.name;
+ }
+
+ const updatedPlan = await rolloutServiceClient.updatePlan({
+ plan: planPatch,
+ updateMask: ["steps"],
+ });
+
+ issue.value.planEntity = updatedPlan;
+
+ events.emit("status-changed", { eager: true });
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+};
+
+const handleStatementChange = (value: string) => {
+ if (isEditorReadonly.value) {
+ return;
+ }
+
+ state.statement = value;
+ if (isCreating.value) {
+ // When creating an issue, update the local sheet directly.
+ if (!sheet.value) return;
+ setSheetStatement(sheet.value, value);
+ }
+};
+
+const handleMonacoEditorReady = () => {
+ // TODO
+ // handleUpdateEditorAutoCompletionContext();
+ updateEditorHeight();
+};
+
+watch(
+ sheetStatement,
+ (statement) => {
+ state.statement = statement;
+ },
+ { immediate: true }
+);
+
+watch(isCreating, (curr, prev) => {
+ // Reset the edit state after creating the issue.
+ if (!curr && prev) {
+ state.isEditing = false;
+ updateEditorHeight();
+ }
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue
new file mode 100644
index 0000000000..6f6420a4d8
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/FormatOnSaveCheckbox.vue
@@ -0,0 +1,28 @@
+<template>
+ <NCheckbox
+ v-if="allowFormatOnSave"
+ :checked="value"
+ size="small"
+ @update:checked="$emit('update:value', $event)"
+ >
+ {{ $t("issue.format-on-save") }}
+ </NCheckbox>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { NCheckbox } from "naive-ui";
+
+import { Language } from "@/types";
+
+const props = defineProps<{
+ language: Language;
+ value: boolean;
+}>();
+
+defineEmits<{
+ (event: "update:value", on: boolean): void;
+}>();
+
+const allowFormatOnSave = computed(() => props.language === "sql");
+</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/index.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/index.ts
new file mode 100644
index 0000000000..8a654810d1
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/index.ts
@@ -0,0 +1,3 @@
+import EditorView from "./EditorView.vue";
+
+export default EditorView;
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/useAutoEditorHeight.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/useAutoEditorHeight.ts
new file mode 100644
index 0000000000..6c42e73375
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/useAutoEditorHeight.ts
@@ -0,0 +1,24 @@
+import MonacoEditor from "@/components/MonacoEditor";
+import { ref } from "vue";
+
+const EDITOR_MIN_HEIGHT = 120; // ~= 6 lines, a reasonable size to start writing SQL
+
+export const useAutoEditorHeight = () => {
+ const editorRef = ref<InstanceType<typeof MonacoEditor>>();
+ 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);
+ });
+ };
+
+ return {
+ editorRef,
+ updateEditorHeight,
+ };
+};
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/useTempEditState.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/useTempEditState.ts
new file mode 100644
index 0000000000..426b126cb2
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/useTempEditState.ts
@@ -0,0 +1,117 @@
+import { computed, nextTick, ref, watch } from "vue";
+
+import { UNKNOWN_ID } from "@/types";
+import { useIssueContext } from "../../../logic";
+import { useTaskSheet } from "../useTaskSheet";
+
+export type EditState = {
+ isEditing: boolean;
+ statement: string;
+};
+
+export const useTempEditState = (state: EditState) => {
+ const { isCreating, selectedTask } = useIssueContext();
+ const { sheet, sheetName, sheetReady, sheetStatement } = useTaskSheet();
+
+ let stopWatching = () => {
+ // noop
+ };
+
+ const startWatching = () => {
+ const tempEditStateMap = new Map<string, EditState>();
+ 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 selectedTaskUID = computed((): string => {
+ if (isCreating.value) return String(UNKNOWN_ID);
+ return selectedTask.value.uid;
+ });
+
+ watch(selectedTaskUID, () => {
+ // When switching task id, set the switch flag to true
+ // to temporarily disable change listeners.
+ 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(selectedTaskUID.value, {
+ isEditing: state.isEditing,
+ statement: state.statement,
+ });
+ };
+
+ const afterTaskUIDChange = (uid: string) => {
+ // Try to restore the saved temp edit state after switching task.
+ const storedState = tempEditStateMap.get(uid);
+ 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.isEditing = false;
+ state.statement = sheetStatement.value;
+ }
+ };
+
+ // Save the temp editing state before switching tasks
+ const stopWatchBeforeChange = watch(
+ [() => state.isEditing, () => state.statement],
+ handleEditChange,
+ { immediate: true }
+ );
+ const stopWatchAfterChange = watch(
+ selectedTaskUID,
+ afterTaskUIDChange,
+ { flush: "post" } // Listen to the event AFTER selectedTaskId changed
+ );
+
+ return () => {
+ tempEditStateMap.clear();
+ stopWatchBeforeChange();
+ stopWatchAfterChange();
+ };
+ };
+
+ watch(
+ isCreating,
+ () => {
+ if (!isCreating.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();
+
+ if (!isCreating.value) {
+ stopWatching = startWatching();
+ }
+ };
+
+ return {
+ reset,
+ sheet,
+ sheetName,
+ sheetReady,
+ sheetStatement,
+ };
+};
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/utils.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/utils.ts
new file mode 100644
index 0000000000..404c00bb55
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/utils.ts
@@ -0,0 +1,65 @@
+import { t } from "@/plugins/i18n";
+import { pushNotification } from "@/store";
+
+export const readFileAsync = (
+ 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();
+ });
+};
diff --git a/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vue b/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vue
new file mode 100644
index 0000000000..ca7ce97f28
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vue
@@ -0,0 +1,141 @@
+<template>
+ <div class="flex flex-col gap-y-2">
+ <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="issue-debug">
+ <div>SDLView</div>
+ <pre>sdlState: {{ sdlState }}</pre>
+ </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 :disabled="!!sdlState.detail.error">
+ <template #trigger>
+ <heroicons-outline: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>
+ </div>
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.sql-review"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { reactive, ref } from "vue";
+import { NTabs, NTab, NTooltip } from "naive-ui";
+import { CodeDiff } from "v-code-diff";
+
+import LearnMoreLink from "@/components/LearnMoreLink.vue";
+import { hasFeature, pushNotification } from "@/store";
+import MonacoEditor from "@/components/MonacoEditor";
+import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";
+import { useSDLState } from "./useSDLState";
+
+type TabView = "DIFF" | "STATEMENT" | "SCHEMA";
+
+interface LocalState {
+ showFeatureModal: boolean;
+ tab: TabView;
+}
+
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+ tab: "DIFF",
+});
+const editorRef = ref<InstanceType<typeof MonacoEditor>>();
+
+const { state: sdlState, events: sdlEvents } = useSDLState();
+
+const updateEditorHeight = () => {
+ const contentHeight =
+ editorRef.value?.editorInstance?.getContentHeight() as number;
+ editorRef.value?.setEditorContentHeight(contentHeight);
+};
+
+const handleMonacoEditorReady = () => {
+ updateEditorHeight();
+};
+
+const { markers } = useSQLAdviceMarkers();
+
+sdlEvents.on("error", ({ message }) => {
+ state.tab = "SCHEMA";
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: message,
+ });
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/SDLView/index.ts b/frontend/src/components/IssueV1/components/StatementSection/SDLView/index.ts
new file mode 100644
index 0000000000..b1e4ba40ed
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/SDLView/index.ts
@@ -0,0 +1,3 @@
+import SDLView from "./SDLView.vue";
+
+export default SDLView;
diff --git a/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.ts b/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.ts
new file mode 100644
index 0000000000..1e42d01178
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.ts
@@ -0,0 +1,192 @@
+import { computed, reactive, watch } from "vue";
+import axios from "axios";
+
+import {
+ Task,
+ TaskRun_Status,
+ Task_Status,
+} from "@/types/proto/v1/rollout_service";
+import { useIssueContext } from "../../../logic";
+import { useTaskSheet } from "../useTaskSheet";
+import { useChangeHistoryStore, useDatabaseV1Store } from "@/store";
+import { sqlServiceClient } from "@/grpcweb";
+import { useSilentRequest } from "@/plugins/silent-request";
+import { engineToJSON } from "@/types/proto/v1/common";
+import Emittery from "emittery";
+import { extractTaskUID } from "@/utils";
+
+export type SDLDetail = {
+ error: string;
+ previousSDL: string;
+ prettyExpectedSDL: string;
+ expectedSDL: string;
+ diffDDL: string;
+};
+
+export type SDLState = {
+ task: Task;
+ loading: boolean;
+ detail: SDLDetail | undefined;
+};
+
+export type SDLEvents = Emittery<{
+ error: { message: string };
+}>;
+
+export const useSDLState = () => {
+ const { issue, selectedTask } = useIssueContext();
+ const { sheetStatement } = useTaskSheet();
+ const databaseStore = useDatabaseV1Store();
+ const events: SDLEvents = new Emittery();
+
+ const emptyState = (task: Task): SDLState => {
+ return {
+ task,
+ loading: true,
+ detail: undefined,
+ };
+ };
+
+ const map = reactive(new Map<string, SDLState>());
+
+ const findLatestChangeHistoryName = (task: Task) => {
+ if (task.status !== Task_Status.DONE) return undefined;
+ const taskRunList = issue.value.rolloutTaskRunList.filter((taskRun) => {
+ return extractTaskUID(taskRun.name) === task.uid;
+ });
+ for (let i = taskRunList.length - 1; i >= 0; i--) {
+ const taskRun = taskRunList[i];
+ if (taskRun.status === TaskRun_Status.DONE) {
+ return taskRun.changeHistory;
+ }
+ }
+ return undefined;
+ };
+
+ const changeHistoryName = computed(() => {
+ const task = selectedTask.value;
+ return findLatestChangeHistoryName(task);
+ });
+
+ const fetchOngoingSDLDetail = async (
+ task: Task,
+ statement: string
+ ): Promise<SDLDetail | undefined> => {
+ if (!task.target) return undefined;
+ const database = await databaseStore.getOrFetchDatabaseByName(task.target);
+ const previousSDL = (
+ await databaseStore.fetchDatabaseSchema(
+ `${database.name}/schema`,
+ true // fetch SDL format
+ )
+ ).schema;
+ const expectedSDL = statement;
+
+ const getSchemaDiff = async () => {
+ const { data } = await axios.post("/v1/sql/schema/diff", {
+ engineType: engineToJSON(database.instanceEntity.engine),
+ sourceSchema: previousSDL ?? "",
+ targetSchema: expectedSDL ?? "",
+ });
+ return data ?? "";
+ };
+ const diffDDL = await useSilentRequest(getSchemaDiff);
+
+ const { currentSchema, expectedSchema } = await sqlServiceClient.pretty({
+ engine: database.instanceEntity.engine,
+ currentSchema: previousSDL ?? "",
+ expectedSchema: expectedSDL ?? "",
+ });
+
+ if (task.status === Task_Status.DONE) {
+ throw new Error();
+ }
+
+ return {
+ error: "",
+ previousSDL: currentSchema,
+ prettyExpectedSDL: expectedSchema,
+ expectedSDL,
+ diffDDL,
+ };
+ };
+
+ const fetchSDLDetailFromChangeHistory = async (
+ task: Task,
+ changeHistoryName: string | undefined
+ ): Promise<SDLDetail | undefined> => {
+ if (!changeHistoryName) {
+ return undefined;
+ }
+ const history = await useChangeHistoryStore().fetchChangeHistory({
+ name: changeHistoryName,
+ sdlFormat: true,
+ });
+ // The latestChangeHistoryName might change during fetching the
+ // ChangeHistory.
+ // Should give up the result.
+ const latestChangeHistoryName = findLatestChangeHistoryName(task);
+ if (history.name !== latestChangeHistoryName) {
+ throw new Error();
+ }
+ return {
+ error: "",
+ previousSDL: history.prevSchema,
+ prettyExpectedSDL: history.schema,
+ expectedSDL: history.schema,
+ diffDDL: history.statement,
+ };
+ };
+
+ watch(
+ [() => selectedTask.value.name, sheetStatement, changeHistoryName],
+ async ([taskName, statement, changeHistoryName]) => {
+ const task = selectedTask.value;
+ if (!map.has(taskName)) {
+ map.set(taskName, emptyState(task));
+ }
+ const finish = (detail?: SDLState["detail"]) => {
+ const state = map.get(taskName);
+ if (!state) return;
+ state.loading = false;
+ state.detail = detail;
+ };
+ try {
+ if (task.status === Task_Status.DONE) {
+ const detail = await fetchSDLDetailFromChangeHistory(
+ task,
+ changeHistoryName
+ );
+ finish(detail);
+ } else {
+ const detail = await fetchOngoingSDLDetail(task, statement);
+ finish(detail);
+ }
+ } catch (error: any) {
+ // The task has been changed during the fetch
+ // The result is meaningless.
+ const message =
+ error.response?.data?.message ??
+ error.details ??
+ "Internal server error";
+
+ events.emit("error", { message });
+ finish({
+ error: message,
+ diffDDL: "",
+ expectedSDL: statement,
+ previousSDL: "",
+ prettyExpectedSDL: "",
+ });
+ }
+ },
+ { immediate: true }
+ );
+
+ const state = computed(() => {
+ const task = selectedTask.value as Task;
+ return map.get(task.name) ?? emptyState(task);
+ });
+
+ return { state, events };
+};
diff --git a/frontend/src/components/IssueV1/components/StatementSection/StatementSection.vue b/frontend/src/components/IssueV1/components/StatementSection/StatementSection.vue
new file mode 100644
index 0000000000..aabe9b7835
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/StatementSection.vue
@@ -0,0 +1,35 @@
+<template>
+ <div v-if="viewMode !== 'NONE'" class="px-4 py-2 flex flex-col gap-y-2">
+ <EditorView v-if="viewMode === 'EDITOR'" />
+ <SDLView v-if="viewMode === 'SDL'" />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useIssueContext } from "../../logic";
+import { Task_Type } from "@/types/proto/v1/rollout_service";
+import { TaskTypeListWithStatement } from "@/types";
+import EditorView from "./EditorView";
+import SDLView from "./SDLView";
+
+const { isCreating, selectedTask } = useIssueContext();
+
+type ViewMode = "NONE" | "EDITOR" | "SDL";
+
+const viewMode = computed((): ViewMode => {
+ const task = selectedTask.value;
+ const { type } = task;
+ if (type === Task_Type.DATABASE_SCHEMA_UPDATE_SDL) {
+ return "SDL";
+ }
+ if (type === Task_Type.DATABASE_SCHEMA_BASELINE) {
+ return isCreating.value ? "EDITOR" : "NONE";
+ }
+ if (TaskTypeListWithStatement.includes(type)) {
+ return "EDITOR";
+ }
+
+ return "NONE";
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/index.ts b/frontend/src/components/IssueV1/components/StatementSection/index.ts
new file mode 100644
index 0000000000..2895e1f4a0
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/index.ts
@@ -0,0 +1,3 @@
+import StatementSection from "./StatementSection.vue";
+
+export default StatementSection;
diff --git a/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.ts b/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.ts
new file mode 100644
index 0000000000..2412104b56
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.ts
@@ -0,0 +1,67 @@
+import { computed } from "vue";
+import { maxBy } from "lodash-es";
+
+import {
+ PlanCheckRun,
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Type,
+} from "@/types/proto/v1/rollout_service";
+import { AdviceOption } from "@/components/MonacoEditor";
+import { useIssueContext } from "../../logic";
+
+export const useSQLAdviceMarkers = () => {
+ const { isCreating, issue, selectedTask } = useIssueContext();
+ const markers = computed(() => {
+ if (isCreating.value) return [];
+
+ const task = selectedTask.value;
+ const planCheckRunList = issue.value.planCheckRunList.filter((checkRun) => {
+ task; // TODO: match task and plan
+ return true;
+ });
+
+ const types: PlanCheckRun_Type[] = [
+ PlanCheckRun_Type.DATABASE_STATEMENT_ADVISE,
+ PlanCheckRun_Type.DATABASE_STATEMENT_SYNTAX,
+ ];
+ return types.flatMap((type) => {
+ return getLatestAdviceOptions(
+ planCheckRunList.filter((checkRun) => checkRun.type === type)
+ );
+ });
+ });
+ return { markers };
+};
+
+const getLatestAdviceOptions = (planCheckRunList: PlanCheckRun[]) => {
+ const latest = maxBy(planCheckRunList, (checkRun) =>
+ parseInt(checkRun.uid, 10)
+ );
+ if (!latest) {
+ return [];
+ }
+ const resultList = latest.results;
+ return resultList
+ .filter(
+ (result) =>
+ result.status === PlanCheckRun_Result_Status.ERROR ||
+ result.status === PlanCheckRun_Result_Status.WARNING
+ )
+ .filter((result) => result.line !== undefined)
+ .map<AdviceOption>((result) => {
+ return {
+ severity:
+ result.status === PlanCheckRun_Result_Status.ERROR
+ ? "ERROR"
+ : "WARNING",
+ message: result.content,
+ source: `${result.title} (${result.code})`,
+ startLineNumber: result.line!,
+ // We don't know the actual column yet, so we show the marker at then end of the line
+ startColumn: Number.MAX_SAFE_INTEGER,
+ endLineNumber: result.line!,
+ // We don't know the actual column yet, so we show the marker at then end of the line
+ endColumn: Number.MAX_SAFE_INTEGER,
+ };
+ });
+};
diff --git a/frontend/src/components/IssueV1/components/StatementSection/useTaskSheet.ts b/frontend/src/components/IssueV1/components/StatementSection/useTaskSheet.ts
new file mode 100644
index 0000000000..522129556d
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/StatementSection/useTaskSheet.ts
@@ -0,0 +1,67 @@
+import { computed, ref, watch } from "vue";
+import { useSheetV1Store } from "@/store";
+import {
+ extractSheetUID,
+ getSheetStatement,
+ setSheetStatement,
+ sheetNameOfTaskV1,
+} from "@/utils";
+import { getLocalSheetByName, useIssueContext } from "../../logic";
+import { ESTABLISH_BASELINE_SQL } from "@/types";
+import { Task_Type } from "@/types/proto/v1/rollout_service";
+
+export const useTaskSheet = () => {
+ const sheetStore = useSheetV1Store();
+ const { selectedTask } = useIssueContext();
+
+ const sheetName = computed(() => {
+ return sheetNameOfTaskV1(selectedTask.value);
+ });
+ const sheetReady = ref(false);
+ const sheet = computed(() => {
+ const name = sheetName.value;
+ const uid = extractSheetUID(name);
+ if (uid.startsWith("-")) {
+ return getLocalSheetByName(name);
+ }
+ return sheetStore.getSheetByName(name);
+ });
+ watch(
+ sheetName,
+ (sheetName) => {
+ const uid = extractSheetUID(sheetName);
+ if (!uid) return;
+ if (uid.startsWith("-")) {
+ // The sheet is not created yet (uid starts with "-")
+ sheetReady.value = true;
+ } else {
+ sheetReady.value = false;
+ sheetStore.getOrFetchSheetByName(sheetName).finally(() => {
+ sheetReady.value = true;
+ });
+ }
+ },
+ { immediate: true }
+ );
+ const sheetStatement = computed({
+ get() {
+ if (selectedTask.value.type === Task_Type.DATABASE_SCHEMA_BASELINE) {
+ return ESTABLISH_BASELINE_SQL;
+ }
+
+ if (!sheetReady.value || !sheet.value) return "";
+ return getSheetStatement(sheet.value);
+ },
+ set(statement) {
+ if (!sheetReady.value || !sheet.value) return;
+ setSheetStatement(sheet.value, statement);
+ },
+ });
+
+ return {
+ sheet,
+ sheetName,
+ sheetReady,
+ sheetStatement,
+ };
+};
diff --git a/frontend/src/components/IssueV1/components/TaskListSection/TaskCard.vue b/frontend/src/components/IssueV1/components/TaskListSection/TaskCard.vue
new file mode 100644
index 0000000000..00677ec167
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskListSection/TaskCard.vue
@@ -0,0 +1,178 @@
+<template>
+ <div
+ class="task px-2 py-1 cursor-pointer border rounded lg:flex-1 flex justify-between items-stretch overflow-hidden gap-x-1"
+ :class="taskClass"
+ :data-task-uid="isCreating ? '-creating-' : task.uid"
+ @click="onClickTask(task)"
+ >
+ <div class="flex-1 flex flex-col gap-y-1">
+ <div class="flex items-start">
+ <div class="flex items-center flex-1 gap-x-1">
+ <TaskStatusIcon
+ :create="isCreating"
+ :active="active"
+ :status="task.status"
+ :task="task"
+ class="transform scale-75"
+ />
+ <div class="name flex-1 space-x-1 overflow-x-hidden">
+ <heroicons:arrow-small-right
+ v-if="active"
+ class="w-5 h-5 inline-block mb-0.5"
+ />
+ <span>{{ databaseForTask(issue, task).databaseName }}</span>
+ <span v-if="schemaVersion" class="schema-version">
+ ({{ schemaVersion }})
+ </span>
+ </div>
+ </div>
+ <TaskExtraActionsButton :task="task" />
+ </div>
+ <div class="flex items-center justify-between px-1 text-sm">
+ <div
+ v-if="secondaryViewMode === 'INSTANCE'"
+ class="flex flex-1 items-center whitespace-pre-wrap"
+ >
+ <InstanceV1Name
+ :instance="databaseForTask(issue, task).instanceEntity"
+ :link="false"
+ class="!gap-x-2"
+ />
+ </div>
+ <div
+ v-if="secondaryViewMode === 'TASK_TITLE'"
+ class="flex flex-1 items-center whitespace-pre-wrap break-all"
+ >
+ {{ taskTitle }}
+ </div>
+ </div>
+ </div>
+ <div v-if="shouldShowTaskProgress" class="flex flex-col justify-center">
+ <TaskProgress :task="task" />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { TaskTypeListWithProgress } from "@/types";
+import {
+ Task,
+ Task_Type,
+ task_StatusToJSON,
+} from "@/types/proto/v1/rollout_service";
+import { databaseForTask, isTaskFinished, useIssueContext } from "../../logic";
+import { TenantMode, Workflow } from "@/types/proto/v1/project_service";
+import { InstanceV1Name } from "@/components/v2";
+import TaskStatusIcon from "../TaskStatusIcon.vue";
+import TaskExtraActionsButton from "./TaskExtraActionsButton.vue";
+import TaskProgress from "./TaskProgress.vue";
+import { extractSchemaVersionFromTask } from "@/utils";
+
+type SecondaryViewMode = "INSTANCE" | "TASK_TITLE";
+
+const props = defineProps<{
+ task: Task;
+}>();
+
+const { t } = useI18n();
+const { isCreating, issue, activeTask, selectedTask, events } =
+ useIssueContext();
+const project = computed(() => issue.value.projectEntity);
+const active = computed(
+ () =>
+ !isCreating.value &&
+ props.task === activeTask.value &&
+ !isTaskFinished(props.task)
+);
+const selected = computed(() => props.task === selectedTask.value);
+
+const secondaryViewMode = computed((): SecondaryViewMode => {
+ if (
+ [
+ Task_Type.DATABASE_CREATE,
+ Task_Type.DATABASE_RESTORE_RESTORE,
+ Task_Type.DATABASE_RESTORE_CUTOVER,
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC,
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER,
+ ].includes(props.task.type)
+ ) {
+ return "TASK_TITLE";
+ }
+ return "INSTANCE";
+});
+
+const schemaVersion = computed(() => {
+ // show the schema version for a task if
+ // the project is standard mode and VCS workflow
+ if (isCreating.value) return "";
+ if (project.value.tenantMode === TenantMode.TENANT_MODE_ENABLED) return "";
+ if (project.value.workflow === Workflow.UI) return "";
+
+ return extractSchemaVersionFromTask(props.task);
+});
+
+const taskClass = computed(() => {
+ const { task } = props;
+
+ const classes: string[] = [];
+ if (selected.value) classes.push("selected");
+ if (active.value) classes.push("active");
+ if (isCreating.value) classes.push("create");
+ classes.push(`status_${task_StatusToJSON(task.status).toLowerCase()}`);
+ return classes;
+});
+
+const shouldShowTaskProgress = computed(() => {
+ return TaskTypeListWithProgress.includes(props.task.type);
+});
+
+const taskTitle = computed(() => {
+ const type = props.task.type;
+ if (type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC) {
+ return t("task.type.bb-task-database-schema-update-ghost-sync");
+ }
+ if (type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER) {
+ return t("task.type.bb-task-database-schema-update-ghost-cutover");
+ }
+ return props.task.title;
+});
+
+const onClickTask = (task: Task) => {
+ events.emit("select-task", { task });
+};
+</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_not_started .name {
+ @apply text-control;
+}
+.task.active.status_pending .name,
+.task.active.status_not_started .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/IssueV1/components/TaskListSection/TaskExtraActionsButton.vue b/frontend/src/components/IssueV1/components/TaskListSection/TaskExtraActionsButton.vue
new file mode 100644
index 0000000000..081163159b
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskListSection/TaskExtraActionsButton.vue
@@ -0,0 +1,119 @@
+<template>
+ <NDropdown
+ v-if="options.length > 0"
+ trigger="click"
+ placement="bottom-end"
+ :options="options"
+ :render-option="renderOption"
+ @select="handleSelect"
+ >
+ <NButton
+ quaternary
+ size="tiny"
+ style="--n-padding: 0 1px; --n-icon-size: 20px"
+ >
+ <template #icon>
+ <heroicons:ellipsis-vertical-solid class="w-5 h-5" />
+ </template>
+ </NButton>
+ </NDropdown>
+</template>
+
+<script setup lang="ts">
+import { VNode, computed, h } from "vue";
+import { DropdownOption, NDropdown, NButton } from "naive-ui";
+import { useI18n } from "vue-i18n";
+
+import { Task } from "@/types/proto/v1/rollout_service";
+import {
+ TaskRolloutAction,
+ allowUserToApplyTaskRolloutAction,
+ getApplicableTaskRolloutActionList,
+ useIssueContext,
+} from "@/components/IssueV1/logic";
+import { useCurrentUserV1 } from "@/store";
+import { asyncComputed } from "@vueuse/core";
+import { DropdownItemWithErrorList } from "../common";
+
+type ExtraTaskRolloutActionDropdownOption = DropdownOption & {
+ action: TaskRolloutAction;
+ tasks: Task[];
+};
+
+const props = defineProps<{
+ task: Task;
+}>();
+
+const { t } = useI18n();
+const currentUser = useCurrentUserV1();
+const { events, isCreating, activeTask, issue } = useIssueContext();
+
+const actionList = computed(() => {
+ return getApplicableTaskRolloutActionList(
+ issue.value,
+ props.task,
+ true /* allowSkipPendingTask */
+ );
+});
+
+const allowUserToSkipTask = asyncComputed(() => {
+ return allowUserToApplyTaskRolloutAction(
+ issue.value,
+ props.task,
+ currentUser.value,
+ "SKIP"
+ );
+});
+
+const options = computed((): ExtraTaskRolloutActionDropdownOption[] => {
+ if (isCreating.value) {
+ return [];
+ }
+ const { task } = props;
+ if (task.uid !== activeTask.value.uid) {
+ return [];
+ }
+ const SKIP = actionList.value.includes("SKIP");
+ if (!SKIP) {
+ return [];
+ }
+ return [
+ {
+ key: "skip",
+ label: t("task.skip"),
+ action: "SKIP",
+ tasks: [task],
+ disabled: !allowUserToSkipTask.value,
+ },
+ ];
+});
+
+const renderOption = ({
+ node,
+ option,
+}: {
+ node: VNode;
+ option: DropdownOption;
+}) => {
+ const errors = option.disabled
+ ? ["You are not allowed to perform this action"]
+ : [];
+ return h(
+ DropdownItemWithErrorList,
+ { errors },
+ {
+ default: () => node,
+ }
+ );
+};
+
+const handleSelect = (key: string) => {
+ const option = options.value.find((opt) => opt.key === key);
+ if (!option) return;
+ const { action, tasks } = option;
+ events.emit("perform-task-rollout-action", {
+ action,
+ tasks,
+ });
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/TaskListSection/TaskListSection.vue b/frontend/src/components/IssueV1/components/TaskListSection/TaskListSection.vue
new file mode 100644
index 0000000000..fc5bf6080c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskListSection/TaskListSection.vue
@@ -0,0 +1,53 @@
+<template>
+ <div v-if="shouldShowTaskBar" class="relative">
+ <div
+ ref="taskBar"
+ class="task-list gap-2 py-2 px-4 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,
+ }"
+ >
+ <TaskCard v-for="(task, i) in taskList" :key="i" :task="task" />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+
+import { useVerticalScrollState } from "@/composables/useScrollState";
+import { useIssueContext } from "../../logic";
+import TaskCard from "./TaskCard.vue";
+
+const { issue, selectedStage } = useIssueContext();
+const taskBar = ref<HTMLDivElement>();
+const taskBarScrollState = useVerticalScrollState(taskBar, 192);
+
+const rollout = computed(() => issue.value.rolloutEntity);
+const taskList = computed(() => selectedStage.value.tasks);
+
+// Show the task bar when some of the stages have more than one tasks.
+const shouldShowTaskBar = computed(() => {
+ return rollout.value.stages.some((stage) => stage.tasks.length > 1);
+});
+</script>
+
+<style scoped lang="postcss">
+.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/IssueV1/components/TaskListSection/TaskProgress.vue b/frontend/src/components/IssueV1/components/TaskListSection/TaskProgress.vue
new file mode 100644
index 0000000000..f3ecc96628
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskListSection/TaskProgress.vue
@@ -0,0 +1,33 @@
+<template>
+ <BBProgressPie
+ :percent="percent"
+ class="w-10 h-10 issue-debug"
+ :class="task.status === Task_Status.DONE ? 'text-success' : 'text-info'"
+ :thickness="3"
+ >
+ <!-- eslint-disable vue/no-template-shadow -->
+ <template #default="{ percent }">
+ <span v-if="task.status !== Task_Status.DONE" class="text-xs">
+ {{ percent }}%
+ </span>
+ <span v-else>
+ <heroicons-outline:check class="w-8 h-8" />
+ </span>
+ </template>
+ </BBProgressPie>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+
+import { BBProgressPie } from "@/bbkit";
+import { Task, Task_Status } from "@/types/proto/v1/rollout_service";
+
+defineProps<{
+ task: Task;
+}>();
+
+const percent = computed(() => {
+ return 0; // TODO
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/TaskListSection/index.ts b/frontend/src/components/IssueV1/components/TaskListSection/index.ts
new file mode 100644
index 0000000000..a3894328e7
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskListSection/index.ts
@@ -0,0 +1,3 @@
+import TaskListSection from "./TaskListSection.vue";
+
+export default TaskListSection;
diff --git a/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue
new file mode 100644
index 0000000000..b9c28f3663
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunComment.vue
@@ -0,0 +1,93 @@
+<template>
+ {{ taskRun.detail }}
+
+ <template v-if="commentLink.link">
+ <router-link
+ class="bb-comment-link ml-1 normal-link"
+ :to="commentLink.link"
+ >
+ {{ commentLink.title }}
+ </router-link>
+ </template>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+
+import {
+ TaskRun,
+ TaskRun_Status,
+ Task_Type,
+} from "@/types/proto/v1/rollout_service";
+import { unknownTask } from "@/types";
+import {
+ changeHistorySlug,
+ extractChangeHistoryUID,
+ extractTaskUID,
+ flattenTaskV1List,
+} from "@/utils";
+import { databaseForTask, useIssueContext } from "../../logic";
+
+export type CommentLink = {
+ title: string;
+ link: string;
+};
+
+const props = defineProps<{
+ taskRun: TaskRun;
+}>();
+
+const { issue } = useIssueContext();
+const { t } = useI18n();
+
+const commentLink = computed((): CommentLink => {
+ const { taskRun } = props;
+ const taskUID = extractTaskUID(taskRun.name);
+ const task =
+ flattenTaskV1List(issue.value.rolloutEntity).find(
+ (task) => task.uid === taskUID
+ ) ?? unknownTask();
+ if (taskRun.status === TaskRun_Status.DONE) {
+ switch (task.type) {
+ case Task_Type.DATABASE_SCHEMA_BASELINE:
+ case Task_Type.DATABASE_SCHEMA_UPDATE:
+ case Task_Type.DATABASE_SCHEMA_UPDATE_SDL:
+ case Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC:
+ case Task_Type.DATABASE_DATA_UPDATE: {
+ const db = databaseForTask(issue.value, task);
+ const link = `/${db.name}/changeHistories/${changeHistorySlug(
+ extractChangeHistoryUID(taskRun.changeHistory),
+ taskRun.schemaVersion
+ )}`;
+ return {
+ title: t("task.view-change"),
+ link,
+ };
+ }
+ }
+ } else if (taskRun.status === TaskRun_Status.FAILED) {
+ // TBD: taskRun.code is not available
+ // 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/IssueV1/components/TaskRunSection/TaskRunSection.vue b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunSection.vue
new file mode 100644
index 0000000000..767355994c
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunSection.vue
@@ -0,0 +1,46 @@
+<template>
+ <div class="issue-debug">
+ <div>task run section</div>
+ <div>mode: {{ mode }}</div>
+ <div>flattenTaskRunList.length: {{ flattenTaskRunList.length }}</div>
+ </div>
+ <div v-if="flattenTaskRunList.length > 0" class="px-4 py-2 space-y-4">
+ <TaskRunTable :task-run-list="flattenTaskRunList" />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import {
+ useIssueContext,
+ taskRunListForTask,
+} from "@/components/IssueV1/logic";
+import TaskRunTable from "./TaskRunTable.vue";
+
+type ViewMode = "SINGLE" | "MERGED";
+
+const { issue, selectedTask, isGhostMode, isPITRMode, isTenantMode } =
+ useIssueContext();
+
+/**
+ * MERGED mode: merge all tasks' activities into one table
+ * SINGLE mode: show only selected task's activities
+ */
+const mode = computed((): ViewMode => {
+ 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 taskRunListForTask(issue.value, selectedTask.value);
+ }
+ if (mode.value === "MERGED") {
+ return issue.value.rolloutTaskRunList;
+ }
+ return [];
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunStatusIcon.vue b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunStatusIcon.vue
new file mode 100644
index 0000000000..897f7264bb
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunStatusIcon.vue
@@ -0,0 +1,55 @@
+<template>
+ <div
+ class="relative w-5 h-5 flex flex-shrink-0 items-center justify-center rounded-full select-none"
+ :class="classes"
+ >
+ <template v-if="status === 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="status === TaskRun_Status.DONE">
+ <heroicons-outline:check class="w-5 h-5" />
+ </template>
+ <template v-else-if="status === TaskRun_Status.FAILED">
+ <span class="text-white font-medium text-base" aria-hidden="true">!</span>
+ </template>
+ <template v-else-if="status === TaskRun_Status.CANCELED">
+ <heroicons-outline:minus-sm class="w-5 h-5" />
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import {
+ TaskRun_Status,
+ taskRun_StatusToJSON,
+} from "@/types/proto/v1/rollout_service";
+import { computed } from "vue";
+
+const props = defineProps<{
+ status: TaskRun_Status;
+}>();
+
+const classes = computed(() => {
+ switch (props.status) {
+ case TaskRun_Status.RUNNING:
+ return "bg-white border-2 border-info text-info";
+ case TaskRun_Status.DONE:
+ return "bg-success text-white";
+ case TaskRun_Status.FAILED:
+ return "bg-error text-white";
+ case TaskRun_Status.CANCELED:
+ return "bg-white border-2 border-gray-400 text-gray-400";
+ }
+ console.assert(
+ false,
+ `should never reach this line. status=${
+ props.status
+ } ${taskRun_StatusToJSON(props.status)}`
+ );
+ return "";
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunTable.vue b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunTable.vue
new file mode 100644
index 0000000000..84ba5d4881
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskRunSection/TaskRunTable.vue
@@ -0,0 +1,81 @@
+<template>
+ <BBGrid
+ :column-list="columnList"
+ :data-source="taskRunList"
+ :row-clickable="false"
+ row-key="uid"
+ class="border"
+ >
+ <template #item="{ item: taskRun }: TaskRunGridRow">
+ <div class="bb-grid-cell">
+ <TaskRunStatusIcon :status="taskRun.status" />
+ </div>
+ <div class="bb-grid-cell whitespace-pre-wrap break-words">
+ <TaskRunComment :task-run="taskRun" />
+ </div>
+ <div class="bb-grid-cell">
+ <HumanizeDate :date="taskRun.createTime" />
+ </div>
+ <div class="bb-grid-cell">
+ {{ humanizeDurationV1(executionDurationOfTaskRun(taskRun)) }}
+ </div>
+ </template>
+ </BBGrid>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { Task, TaskRun } from "@/types/proto/v1/rollout_service";
+import { Duration } from "@/types/proto/google/protobuf/duration";
+import { BBGrid, BBGridColumn, BBGridRow } from "@/bbkit";
+import HumanizeDate from "@/components/misc/HumanizeDate.vue";
+import TaskRunStatusIcon from "./TaskRunStatusIcon.vue";
+import TaskRunComment from "./TaskRunComment.vue";
+
+export type MergedTaskRunItem = {
+ task: Task;
+ taskRun: TaskRun;
+};
+export type TaskRunGridRow = BBGridRow<TaskRun>;
+
+defineProps<{
+ taskRunList: TaskRun[];
+}>();
+
+const { t } = useI18n();
+
+const columnList = computed((): BBGridColumn[] => {
+ return [
+ {
+ title: "",
+ width: "auto",
+ },
+ {
+ title: t("task.comment"),
+ width: "1fr",
+ },
+ {
+ title: t("task.started"),
+ width: "auto",
+ },
+ {
+ title: t("task.execution-time"),
+ width: "auto",
+ },
+ ];
+});
+
+const executionDurationOfTaskRun = (taskRun: TaskRun): Duration => {
+ const { createTime, updateTime } = taskRun;
+ if (!createTime || !updateTime) return { seconds: 0, nanos: 0 };
+ const createMS = createTime.getTime();
+ const updateMS = updateTime.getTime();
+ const elapsedMS = updateMS - createMS;
+ return {
+ seconds: Math.floor(elapsedMS / 1000),
+ nanos: (elapsedMS % 1000) * 1e6,
+ };
+};
+</script>
diff --git a/frontend/src/components/IssueV1/components/TaskRunSection/index.ts b/frontend/src/components/IssueV1/components/TaskRunSection/index.ts
new file mode 100644
index 0000000000..86345305d4
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskRunSection/index.ts
@@ -0,0 +1,3 @@
+import TaskRunSection from "./TaskRunSection.vue";
+
+export default TaskRunSection;
diff --git a/frontend/src/components/IssueV1/components/TaskStatusIcon.vue b/frontend/src/components/IssueV1/components/TaskStatusIcon.vue
new file mode 100644
index 0000000000..d00f286dda
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/TaskStatusIcon.vue
@@ -0,0 +1,122 @@
+<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="planCheckStatus === PlanCheckRun_Result_Status.ERROR">
+ <heroicons:exclamation-circle class="w-7 h-7 text-error" />
+ </template>
+ <template
+ v-else-if="planCheckStatus === PlanCheckRun_Result_Status.WARNING"
+ >
+ <heroicons:exclamation-triangle class="w-7 h-7 text-warning" />
+ </template>
+ <template v-else-if="status === Task_Status.NOT_STARTED">
+ <heroicons-outline:user class="w-4 h-4" />
+ </template>
+ <template v-else-if="status === Task_Status.PENDING">
+ <span
+ v-if="active"
+ class="h-2 w-2 bg-info rounded-full"
+ aria-hidden="true"
+ />
+ <span
+ v-else
+ class="h-1.5 w-1.5 bg-control rounded-full"
+ aria-hidden="true"
+ />
+ </template>
+ <template v-else-if="status === Task_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
+ class="w-full h-full rounded-full z-[1] bg-info"
+ aria-hidden="true"
+ />
+ </div>
+ </template>
+ <template v-else-if="status === Task_Status.SKIPPED">
+ <SkipIcon class="w-5 h-5" />
+ </template>
+ <template v-else-if="status === Task_Status.DONE">
+ <heroicons-solid:check class="w-5 h-5" />
+ </template>
+ <template v-else-if="status === Task_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 === Task_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 { SkipIcon } from "@/components/Icon";
+import { planCheckStatusForTask, useIssueContext } from "../logic";
+import {
+ PlanCheckRun_Result_Status,
+ Task,
+ Task_Status,
+} from "@/types/proto/v1/rollout_service";
+
+const props = defineProps<{
+ active: boolean;
+ status: Task_Status;
+ task?: Task;
+ ignorePlanCheckStatus?: boolean;
+}>();
+
+const { isCreating, issue } = useIssueContext();
+
+const planCheckStatus = computed(() => {
+ if (props.ignorePlanCheckStatus) return undefined;
+ if (isCreating.value) return undefined;
+ if (!props.task) return undefined;
+
+ return planCheckStatusForTask(issue.value, props.task);
+});
+
+const classes = computed((): string => {
+ if (planCheckStatus.value === PlanCheckRun_Result_Status.ERROR) {
+ return "bg-white text-error !w-7";
+ }
+ if (planCheckStatus.value === PlanCheckRun_Result_Status.WARNING) {
+ return "bg-white text-warning !w-7";
+ }
+
+ switch (props.status) {
+ case Task_Status.NOT_STARTED:
+ if (!isCreating.value && props.active) {
+ return "bg-white border-2 border-info text-info";
+ }
+ return "bg-white border-2 border-control";
+ case Task_Status.PENDING:
+ if (!isCreating.value && props.active) {
+ return "bg-white border-2 border-info text-info ";
+ }
+ return "bg-white border-2 border-control";
+ case Task_Status.RUNNING:
+ return "bg-white border-2 border-info text-info";
+ case Task_Status.SKIPPED:
+ return "bg-gray-200 text-gray-500";
+ case Task_Status.DONE:
+ return "bg-success text-white";
+ case Task_Status.FAILED:
+ return "bg-error text-white";
+ default:
+ return "";
+ }
+});
+</script>
diff --git a/frontend/src/components/IssueV1/components/common/DropdownItemWithErrorList.vue b/frontend/src/components/IssueV1/components/common/DropdownItemWithErrorList.vue
new file mode 100644
index 0000000000..3de4e2e66e
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/common/DropdownItemWithErrorList.vue
@@ -0,0 +1,23 @@
+<template>
+ <NTooltip
+ :disabled="errors.length === 0"
+ :keep-alive-on-hover="false"
+ style="width: max-content"
+ >
+ <template #trigger>
+ <slot />
+ </template>
+ <template #default>
+ <ErrorList :errors="errors" />
+ </template>
+ </NTooltip>
+</template>
+
+<script lang="ts" setup>
+import { NTooltip } from "naive-ui";
+import ErrorList from "./ErrorList.vue";
+
+defineProps<{
+ errors: string[];
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/common/ErrorList.vue b/frontend/src/components/IssueV1/components/common/ErrorList.vue
new file mode 100644
index 0000000000..8e7b0aecb0
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/common/ErrorList.vue
@@ -0,0 +1,16 @@
+<template>
+ <ul
+ class="flex flex-col whitespace-nowrap"
+ :class="[errors.length > 1 && 'list-disc pl-4']"
+ >
+ <li v-for="(error, i) in errors" :key="i">
+ {{ error }}
+ </li>
+ </ul>
+</template>
+
+<script setup lang="ts">
+defineProps<{
+ errors: string[];
+}>();
+</script>
diff --git a/frontend/src/components/IssueV1/components/common/index.ts b/frontend/src/components/IssueV1/components/common/index.ts
new file mode 100644
index 0000000000..312cd0760f
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/common/index.ts
@@ -0,0 +1,4 @@
+import ErrorList from "./ErrorList.vue";
+import DropdownItemWithErrorList from "./DropdownItemWithErrorList.vue";
+
+export { ErrorList, DropdownItemWithErrorList };
diff --git a/frontend/src/components/IssueV1/components/index.ts b/frontend/src/components/IssueV1/components/index.ts
new file mode 100644
index 0000000000..7fa5c8ca63
--- /dev/null
+++ b/frontend/src/components/IssueV1/components/index.ts
@@ -0,0 +1,22 @@
+import BannerSection from "./BannerSection.vue";
+import HeaderSection from "./HeaderSection";
+import StageSection from "./StageSection";
+import TaskListSection from "./TaskListSection";
+import TaskRunSection from "./TaskRunSection";
+import PlanCheckSection from "./PlanCheckSection";
+import StatementSection from "./StatementSection";
+import DescriptionSection from "./DescriptionSection";
+import ActivitySection from "./ActivitySection";
+
+export * from "./Dialog";
+export {
+ BannerSection,
+ HeaderSection,
+ StageSection,
+ TaskListSection,
+ TaskRunSection,
+ PlanCheckSection,
+ StatementSection,
+ DescriptionSection,
+ ActivitySection,
+};
diff --git a/frontend/src/components/IssueV1/index.ts b/frontend/src/components/IssueV1/index.ts
new file mode 100644
index 0000000000..e065f3225b
--- /dev/null
+++ b/frontend/src/components/IssueV1/index.ts
@@ -0,0 +1,5 @@
+import IssueDetailPage from "./IssueDetailPage.vue";
+
+export * from "./logic";
+
+export { IssueDetailPage };
diff --git a/frontend/src/components/IssueV1/logic/action/index.ts b/frontend/src/components/IssueV1/logic/action/index.ts
new file mode 100644
index 0000000000..7ff80e105b
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/action/index.ts
@@ -0,0 +1,4 @@
+export * from "./review";
+export * from "./issue";
+export * from "./task";
+export * from "./stage";
diff --git a/frontend/src/components/IssueV1/logic/action/issue.ts b/frontend/src/components/IssueV1/logic/action/issue.ts
new file mode 100644
index 0000000000..401dd87c4c
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/action/issue.ts
@@ -0,0 +1,110 @@
+import { ButtonProps } from "naive-ui";
+import { t } from "@/plugins/i18n";
+
+import { ComposedIssue } from "@/types";
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import {
+ extractUserResourceName,
+ flattenTaskV1List,
+ hasWorkspacePermissionV1,
+ isDatabaseRelatedIssue,
+ isGrantRequestIssue,
+ isOwnerOfProjectV1,
+} from "@/utils";
+import { isTaskFinished } from "..";
+import { User } from "@/types/proto/v1/auth_service";
+
+export type IssueStatusAction = "RESOLVE" | "CANCEL" | "REOPEN";
+
+export const IssueStatusActionMap: Record<IssueStatus, IssueStatusAction[]> = {
+ [IssueStatus.OPEN]: ["RESOLVE", "CANCEL"],
+ [IssueStatus.DONE]: ["REOPEN"],
+ [IssueStatus.CANCELED]: ["REOPEN"],
+
+ // Only to make TypeScript compiler happy
+ [IssueStatus.ISSUE_STATUS_UNSPECIFIED]: [],
+ [IssueStatus.UNRECOGNIZED]: [],
+};
+
+export const getApplicableIssueStatusActionList = (
+ issue: ComposedIssue
+): IssueStatusAction[] => {
+ const list = IssueStatusActionMap[issue.status];
+ return list.filter((action) => {
+ if (isGrantRequestIssue(issue)) {
+ // Don't show RESOLVE or REOPEN for request granting issues.
+ if (action === "RESOLVE" || action === "REOPEN") {
+ return false;
+ }
+ }
+ if (isDatabaseRelatedIssue(issue) && action === "RESOLVE") {
+ const tasks = flattenTaskV1List(issue.rolloutEntity);
+ // Ths issue cannot be resolved if some tasks are not finished yet.
+ if (tasks.some((task) => !isTaskFinished(task))) {
+ return false;
+ }
+ }
+ return true;
+ });
+};
+
+export const issueStatusActionDisplayName = (action: IssueStatusAction) => {
+ switch (action) {
+ case "RESOLVE":
+ return t("issue.status-transition.dropdown.resolve");
+ case "CANCEL":
+ return t("issue.status-transition.dropdown.cancel");
+ case "REOPEN":
+ return t("issue.status-transition.dropdown.reopen");
+ }
+};
+
+export const issueStatusActionButtonProps = (
+ action: IssueStatusAction
+): ButtonProps => {
+ switch (action) {
+ case "RESOLVE":
+ return {
+ type: "success",
+ };
+ case "CANCEL":
+ return {
+ type: "default",
+ };
+ case "REOPEN":
+ return {
+ type: "default",
+ };
+ }
+};
+export const allowUserToApplyIssueStatusAction = (
+ issue: ComposedIssue,
+ user: User,
+ action: IssueStatusAction
+) => {
+ // 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 project = issue.projectEntity;
+ if (isOwnerOfProjectV1(project.iamPolicy, user)) {
+ return true;
+ }
+
+ // The creator and the assignee are allowed.
+ if (extractUserResourceName(issue.creator) === user.email) {
+ return true;
+ }
+ if (extractUserResourceName(issue.assignee) === user.email) {
+ return true;
+ }
+
+ return false;
+};
diff --git a/frontend/src/components/IssueV1/logic/action/review.ts b/frontend/src/components/IssueV1/logic/action/review.ts
new file mode 100644
index 0000000000..27b707c035
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/action/review.ts
@@ -0,0 +1,87 @@
+import { t } from "@/plugins/i18n";
+import { candidatesOfApprovalStepV1 } from "@/store";
+import { ComposedIssue } from "@/types";
+import { User } from "@/types/proto/v1/auth_service";
+import {
+ IssueStatus,
+ Issue_Approver_Status,
+} from "@/types/proto/v1/issue_service";
+import { extractUserResourceName } from "@/utils";
+import { ButtonProps } from "naive-ui";
+import { ReviewContext } from "../context";
+
+export type IssueReviewAction = "APPROVE" | "SEND_BACK" | "RE_REQUEST";
+
+export const targetReviewStatusForReviewAction = (
+ action: IssueReviewAction
+) => {
+ switch (action) {
+ case "APPROVE":
+ return Issue_Approver_Status.APPROVED;
+ case "SEND_BACK":
+ return Issue_Approver_Status.REJECTED;
+ case "RE_REQUEST":
+ return Issue_Approver_Status.PENDING;
+ }
+};
+
+export const issueReviewActionDisplayName = (action: IssueReviewAction) => {
+ switch (action) {
+ case "APPROVE":
+ return t("common.approve");
+ case "SEND_BACK":
+ return t("custom-approval.issue-review.send-back");
+ case "RE_REQUEST":
+ return t("custom-approval.issue-review.re-request-review");
+ }
+};
+
+export const issueReviewActionButtonProps = (
+ action: IssueReviewAction
+): ButtonProps => {
+ switch (action) {
+ case "APPROVE":
+ return {
+ type: "primary",
+ };
+ case "SEND_BACK":
+ return {
+ type: "default",
+ };
+ case "RE_REQUEST":
+ return {
+ type: "primary",
+ };
+ }
+};
+
+export const allowUserToApplyReviewAction = async (
+ issue: ComposedIssue,
+ context: ReviewContext,
+ user: User,
+ action: IssueReviewAction
+) => {
+ const { ready, done, flow } = context;
+
+ if (
+ issue.status === IssueStatus.CANCELED ||
+ issue.status === IssueStatus.DONE
+ ) {
+ return false;
+ }
+
+ if (!ready.value) return false;
+ if (done.value) return false;
+
+ if (action === "APPROVE" || action === "SEND_BACK") {
+ const index = flow.value.currentStepIndex;
+ const steps = flow.value.template.flow?.steps ?? [];
+ const step = steps[index];
+ if (!step) return false;
+ const candidates = candidatesOfApprovalStepV1(issue, step);
+ return candidates.includes(user.name);
+ }
+
+ // action === 'RE_REQUEST'
+ return user.email === extractUserResourceName(issue.creator);
+};
diff --git a/frontend/src/components/IssueV1/logic/action/stage.ts b/frontend/src/components/IssueV1/logic/action/stage.ts
new file mode 100644
index 0000000000..0cbb08ec64
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/action/stage.ts
@@ -0,0 +1,58 @@
+import { ComposedIssue } from "@/types";
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import { Stage, Task } from "@/types/proto/v1/rollout_service";
+import { getApplicableTaskRolloutActionList, TaskRolloutAction } from "./task";
+
+export type StageRolloutAction = Extract<
+ TaskRolloutAction,
+ "ROLLOUT" | "CANCEL" | "RETRY" | "SKIP" | "RESTART"
+>;
+export const StageRolloutActionList: StageRolloutAction[] = [
+ "ROLLOUT",
+ "CANCEL",
+ "RETRY",
+ "SKIP",
+ "RESTART",
+];
+
+export const getApplicableStageRolloutActionList = (
+ issue: ComposedIssue,
+ stage: Stage,
+ allowSkipPendingTasks = false // If set to true, only FAILED tasks can be skipped
+) => {
+ if (issue.status !== IssueStatus.OPEN) {
+ return [];
+ }
+
+ const applicableActionsMap: Record<StageRolloutAction, Task[]> = {
+ ROLLOUT: [],
+ CANCEL: [],
+ RETRY: [],
+ SKIP: [],
+ RESTART: [],
+ };
+ stage.tasks.forEach((task) => {
+ const actions = getApplicableTaskRolloutActionList(
+ issue,
+ task,
+ allowSkipPendingTasks
+ );
+ StageRolloutActionList.forEach((action) => {
+ if (actions.includes(action)) {
+ applicableActionsMap[action].push(task);
+ }
+ });
+ });
+
+ const actions: { action: StageRolloutAction; tasks: Task[] }[] = [];
+ StageRolloutActionList.forEach((action) => {
+ const tasks = applicableActionsMap[action];
+ if (tasks.length > 1) {
+ actions.push({
+ action,
+ tasks,
+ });
+ }
+ });
+ return actions;
+};
diff --git a/frontend/src/components/IssueV1/logic/action/task.ts b/frontend/src/components/IssueV1/logic/action/task.ts
new file mode 100644
index 0000000000..12275721fa
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/action/task.ts
@@ -0,0 +1,155 @@
+import { t } from "@/plugins/i18n";
+import { ComposedIssue } from "@/types";
+import { User } from "@/types/proto/v1/auth_service";
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import { Task, Task_Status, Task_Type } from "@/types/proto/v1/rollout_service";
+import { extractUserResourceName } from "@/utils";
+import { ButtonProps } from "naive-ui";
+import {
+ allowUserToBeAssignee,
+ getCurrentRolloutPolicyForTask,
+} from "../assignee";
+
+export type TaskRolloutAction =
+ | "ROLLOUT" // NOT_STARTED -> PENDING
+ | "RETRY" // FAILED -> NOT_STARTED
+ | "CANCEL" // ? -> CANCELLED
+ | "SKIP" // ? -> SKIPPED
+ | "RESTART"; // ? -> NOT_STARTED
+
+// Primary actions will be displayed as big buttons.
+export const PrimaryTaskRolloutActionList: TaskRolloutAction[] = [
+ "ROLLOUT",
+ "CANCEL",
+ "RETRY",
+ "RESTART",
+];
+
+// Secondary actions will be folded in the context menu.
+export const SecondaryTaskRolloutActionList: TaskRolloutAction[] = ["SKIP"];
+
+export const CancelableTaskTypeList: Task_Type[] = [
+ Task_Type.DATABASE_DATA_UPDATE,
+ Task_Type.DATABASE_SCHEMA_UPDATE,
+ Task_Type.DATABASE_SCHEMA_UPDATE_SDL,
+ // Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC, // on the way
+];
+
+export const TaskRolloutActionMap: Record<Task_Status, TaskRolloutAction[]> = {
+ [Task_Status.NOT_STARTED]: ["ROLLOUT", "SKIP"],
+ [Task_Status.PENDING]: ["CANCEL"], // Only DDL/DML can be cancelled
+ [Task_Status.RUNNING]: ["CANCEL"], // Only DDL/DML can be cancelled
+ [Task_Status.SKIPPED]: [],
+ [Task_Status.DONE]: [],
+ [Task_Status.FAILED]: ["RETRY", "SKIP"],
+ [Task_Status.CANCELED]: ["RESTART", "SKIP"],
+
+ // Only to make TypeScript compiler happy
+ [Task_Status.STATUS_UNSPECIFIED]: [],
+ [Task_Status.UNRECOGNIZED]: [],
+};
+
+export const getApplicableTaskRolloutActionList = (
+ issue: ComposedIssue,
+ task: Task,
+ allowSkipPendingTask = false // If set to true, only FAILED tasks can be skipped
+): TaskRolloutAction[] => {
+ if (issue.status !== IssueStatus.OPEN) {
+ return [];
+ }
+ const list = TaskRolloutActionMap[task.status];
+ return list.filter((action) => {
+ if (action === "CANCEL") {
+ return CancelableTaskTypeList.includes(task.type);
+ return task.type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC;
+ }
+ if (action === "RETRY") {
+ // RETRYing gh-ost cut-over task is not allowed (yet).
+ if (task.type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER) {
+ return false;
+ }
+ }
+ if (action === "SKIP") {
+ if (task.status !== Task_Status.FAILED && !allowSkipPendingTask) {
+ return false;
+ }
+ }
+
+ return true;
+ });
+};
+
+export const taskRolloutActionDisplayName = (action: TaskRolloutAction) => {
+ switch (action) {
+ case "ROLLOUT":
+ return t("common.rollout");
+ case "CANCEL":
+ return t("common.cancel");
+ case "RETRY":
+ return t("common.retry");
+ case "RESTART":
+ return t("common.restart");
+ case "SKIP":
+ return t("common.skip");
+ }
+};
+
+export const taskRolloutActionDialogButtonName = (
+ action: TaskRolloutAction,
+ tasks: Task[]
+) => {
+ if (action === "CANCEL") {
+ // Avoiding [Cancel] [Cancel] button group scene
+ return t("task.cancel-task", tasks.length);
+ }
+ return taskRolloutActionDisplayName(action);
+};
+
+export const taskRolloutActionButtonProps = (
+ action: TaskRolloutAction
+): ButtonProps => {
+ switch (action) {
+ case "ROLLOUT":
+ return {
+ type: "primary",
+ };
+ case "RESTART":
+ return {
+ type: "primary",
+ };
+ case "RETRY":
+ return {
+ type: "primary",
+ };
+ }
+ return {
+ type: "default",
+ };
+};
+
+export const allowUserToApplyTaskRolloutAction = async (
+ issue: ComposedIssue,
+ task: Task,
+ user: User,
+ action: TaskRolloutAction
+) => {
+ if (extractUserResourceName(issue.assignee) === user.email) {
+ return true;
+ }
+
+ const project = issue.projectEntity;
+ const rolloutPolicy = await getCurrentRolloutPolicyForTask(issue, task);
+ if (
+ allowUserToBeAssignee(
+ user,
+ project,
+ project.iamPolicy,
+ rolloutPolicy.policy,
+ rolloutPolicy.assigneeGroup
+ )
+ ) {
+ return true;
+ }
+
+ return false;
+};
diff --git a/frontend/src/components/IssueV1/logic/assignee.ts b/frontend/src/components/IssueV1/logic/assignee.ts
new file mode 100644
index 0000000000..d1ec42cd2a
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/assignee.ts
@@ -0,0 +1,251 @@
+import { computed, unref } from "vue";
+import { first } from "lodash-es";
+
+import {
+ ComposedIssue,
+ emptyStage,
+ emptyTask,
+ MaybeRef,
+ SYSTEM_BOT_EMAIL,
+ unknownEnvironment,
+} from "@/types";
+import {
+ isDatabaseRelatedIssue,
+ isOwnerOfProjectV1,
+ hasWorkspacePermissionV1,
+ extractUserResourceName,
+ activeTaskInRollout,
+} from "@/utils";
+import {
+ Policy,
+ PolicyType,
+ ApprovalStrategy,
+ ApprovalGroup,
+} from "@/types/proto/v1/org_policy_service";
+import { DeploymentType } from "@/types/proto/v1/deployment";
+import {
+ usePolicyByParentAndType,
+ defaultApprovalStrategy,
+ usePolicyV1Store,
+} from "@/store/modules/v1/policy";
+import { Project } from "@/types/proto/v1/project_service";
+import { User } from "@/types/proto/v1/auth_service";
+import { IamPolicy } from "@/types/proto/v1/iam_policy";
+import { Task, Task_Type } from "@/types/proto/v1/rollout_service";
+import { IssueStatus } from "@/types/proto/v1/issue_service";
+import { useEnvironmentV1Store } from "@/store";
+import { useIssueContext } from "./context";
+import { stageForTask } from "./utils";
+
+export const getCurrentRolloutPolicyForTask = async (
+ issue: ComposedIssue,
+ task: Task
+) => {
+ if (!isDatabaseRelatedIssue(issue)) {
+ return {
+ policy: ApprovalStrategy.MANUAL,
+ assigneeGroup: undefined,
+ };
+ }
+
+ const stage = stageForTask(issue, task);
+ const environment = stage
+ ? useEnvironmentV1Store().getEnvironmentByName(stage.environment)
+ : undefined;
+
+ if (!environment) {
+ return extractRollOutPolicyValue(undefined, task.type);
+ }
+
+ const approvalPolicy =
+ await usePolicyV1Store().getOrFetchPolicyByParentAndType({
+ parentPath: environment.name,
+ policyType: PolicyType.DEPLOYMENT_APPROVAL,
+ });
+ return extractRollOutPolicyValue(approvalPolicy, task.type);
+};
+
+export const useCurrentRolloutPolicyForTask = (task: MaybeRef<Task>) => {
+ const { issue } = useIssueContext();
+ if (!isDatabaseRelatedIssue(issue.value)) {
+ return computed(() => ({
+ policy: ApprovalStrategy.MANUAL,
+ assigneeGroup: undefined,
+ }));
+ }
+
+ const environment = computed(() => {
+ const stage = stageForTask(issue.value, unref(task));
+ if (!stage) return unknownEnvironment();
+ return (
+ useEnvironmentV1Store().getEnvironmentByName(stage.environment) ??
+ unknownEnvironment()
+ );
+ });
+
+ const approvalPolicy = usePolicyByParentAndType(
+ computed(() => ({
+ parentPath: environment.value.name,
+ policyType: PolicyType.DEPLOYMENT_APPROVAL,
+ }))
+ );
+
+ return computed(() => {
+ const policy = approvalPolicy.value;
+ return extractRollOutPolicyValue(policy, unref(task).type);
+ });
+};
+
+export const useCurrentRolloutPolicyForActiveEnvironment = () => {
+ const { isCreating, issue } = useIssueContext();
+
+ const activeTask = computed(() => {
+ const rollout = issue.value.rolloutEntity;
+ if (isCreating.value) {
+ const firstStage = first(rollout.stages) ?? emptyStage();
+ return first(firstStage.tasks) ?? emptyTask();
+ }
+ return activeTaskInRollout(rollout);
+ });
+
+ return useCurrentRolloutPolicyForTask(activeTask);
+};
+
+export const extractRollOutPolicyValue = (
+ policy: Policy | undefined,
+ taskType: Task_Type
+): {
+ 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 = taskTypeToDeploymentType(taskType);
+ 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: ComposedIssue) => {
+ if (issue.status !== IssueStatus.OPEN) {
+ return false;
+ }
+ if (
+ hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-issue",
+ user.userRole
+ )
+ ) {
+ return true;
+ }
+
+ const currentUserEmail = user.email;
+ const assigneeEmail = extractUserResourceName(issue.assignee);
+ const creatorEmail = extractUserResourceName(issue.creator);
+ if (assigneeEmail === SYSTEM_BOT_EMAIL) {
+ return currentUserEmail === creatorEmail;
+ }
+ return currentUserEmail === assigneeEmail;
+};
+
+export const allowProjectOwnerToApprove = (
+ policy: Policy,
+ taskType: Task_Type
+): boolean => {
+ const strategy =
+ policy.deploymentApprovalPolicy?.defaultStrategy ?? defaultApprovalStrategy;
+ if (strategy === ApprovalStrategy.AUTOMATIC) {
+ return false;
+ }
+
+ const deploymentType = taskTypeToDeploymentType(taskType);
+ const assigneeGroup = (
+ policy.deploymentApprovalPolicy?.deploymentApprovalStrategies ?? []
+ ).find((group) => group.deploymentType === deploymentType);
+
+ if (!assigneeGroup) {
+ return false;
+ }
+
+ return (
+ assigneeGroup.approvalGroup === ApprovalGroup.APPROVAL_GROUP_PROJECT_OWNER
+ );
+};
+
+const taskTypeToDeploymentType = (taskType: Task_Type): DeploymentType => {
+ switch (taskType) {
+ case Task_Type.DATABASE_CREATE:
+ return DeploymentType.DATABASE_CREATE;
+ case Task_Type.DATABASE_SCHEMA_UPDATE:
+ return DeploymentType.DATABASE_DDL;
+ case Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER:
+ case Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC:
+ return DeploymentType.DATABASE_DDL_GHOST;
+ case Task_Type.DATABASE_DATA_UPDATE:
+ return DeploymentType.DATABASE_DML;
+ case Task_Type.DATABASE_RESTORE_RESTORE:
+ case Task_Type.DATABASE_RESTORE_CUTOVER:
+ return DeploymentType.DATABASE_RESTORE_PITR;
+ default:
+ return DeploymentType.DEPLOYMENT_TYPE_UNSPECIFIED;
+ }
+};
diff --git a/frontend/src/components/IssueV1/logic/base.ts b/frontend/src/components/IssueV1/logic/base.ts
new file mode 100644
index 0000000000..936c0b181c
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/base.ts
@@ -0,0 +1,190 @@
+import { computed } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { first } from "lodash-es";
+
+import { IssueContext, IssueEvents, IssuePhase } from "./context";
+import { Stage, Task, Task_Type } from "@/types/proto/v1/rollout_service";
+import {
+ activeStageInRollout,
+ activeTaskInRollout,
+ activeTaskInStageV1,
+ flattenTaskV1List,
+ idFromSlug,
+ indexOrUIDFromSlug,
+ stageV1Slug,
+ taskV1Slug,
+} from "@/utils";
+import { emptyStage, emptyTask, TaskTypeListWithStatement } from "@/types";
+import { extractReviewContext } from "./review";
+import { TenantMode } from "@/types/proto/v1/project_service";
+import { stageForTask } from "./utils";
+import Emittery from "emittery";
+
+const state = {
+ uid: -101,
+};
+export const nextUID = () => {
+ return String(state.uid--);
+};
+
+export const useBaseIssueContext = (
+ context: Pick<IssueContext, "isCreating" | "ready" | "issue">
+): Partial<IssueContext> => {
+ const { isCreating, issue } = context;
+ const route = useRoute();
+ const router = useRouter();
+
+ const events: IssueEvents = new Emittery();
+
+ const rollout = computed(() => issue.value.rolloutEntity);
+ const project = computed(() => issue.value.projectEntity);
+
+ const activeStage = computed((): Stage => {
+ return activeStageInRollout(rollout.value);
+ });
+ const activeTask = computed((): Task => {
+ return activeTaskInRollout(rollout.value);
+ });
+
+ const selectedStage = computed((): Stage => {
+ const stageSlug = route.query.stage as string;
+ const taskSlug = route.query.task as string;
+ const stageList = rollout.value.stages;
+
+ // Index is used when `isCreating === true`
+ // UID is used when otherwise
+ if (stageSlug) {
+ const indexOrUID = indexOrUIDFromSlug(stageSlug);
+ if (isCreating.value) {
+ if (indexOrUID < stageList.length) {
+ return stageList[indexOrUID];
+ }
+ } else {
+ const stageFound = stageList.find(
+ (stage) => stage.uid === String(indexOrUID)
+ );
+ if (stageFound) {
+ return stageFound;
+ }
+ }
+ } else if (!isCreating.value && taskSlug) {
+ const taskUID = String(idFromSlug(taskSlug));
+ for (const stage of stageList) {
+ if (stage.tasks.findIndex((task) => task.uid === taskUID)) {
+ return stage;
+ }
+ }
+ }
+ // fallback
+ if (isCreating.value) {
+ return first(stageList) ?? emptyStage();
+ }
+
+ return activeStageInRollout(rollout.value);
+ });
+ const selectedTask = computed((): Task => {
+ const taskSlug = route.query.task as string;
+ const { tasks } = selectedStage.value;
+ // Index is used when `isCreating === true`
+ // UID is used when otherwise
+ if (taskSlug) {
+ const indexOrUID = indexOrUIDFromSlug(taskSlug);
+ if (isCreating.value) {
+ if (indexOrUID < tasks.length) {
+ return tasks[indexOrUID];
+ }
+ } else {
+ const taskFound = tasks.find((task) => task.uid === String(indexOrUID));
+ if (taskFound) {
+ return taskFound;
+ }
+ }
+ }
+
+ // fallback
+ if (isCreating.value) {
+ return first(tasks) ?? emptyTask();
+ }
+ return activeTaskInStageV1(selectedStage.value);
+ });
+
+ events.on("select-task", ({ task }) => {
+ const stages = rollout.value.stages;
+ const stage = stageForTask(issue.value, task);
+ if (!stage) return;
+ const stageParam = isCreating.value
+ ? String(stages.indexOf(stage))
+ : stageV1Slug(stage);
+ const taskParam = isCreating.value
+ ? String(stage.tasks.indexOf(task))
+ : taskV1Slug(task);
+
+ router.replace({
+ name: "workspace.issue.detail",
+ query: {
+ ...route.query,
+ stage: stageParam,
+ task: taskParam,
+ },
+ hash: route.hash,
+ });
+ });
+
+ const reviewContext = extractReviewContext(issue);
+
+ const phase = computed((): IssuePhase => {
+ if (isCreating.value) return "CREATE";
+
+ return reviewContext.done.value ? "ROLLOUT" : "REVIEW";
+ });
+
+ const isGhostMode = computed(() => {
+ return flattenTaskV1List(rollout.value).some((task) => {
+ return [
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC,
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER,
+ ].includes(task.type);
+ });
+ });
+ const isPITRMode = computed(() => {
+ return flattenTaskV1List(rollout.value).some((task) => {
+ return [
+ Task_Type.DATABASE_RESTORE_RESTORE,
+ Task_Type.DATABASE_RESTORE_CUTOVER,
+ Task_Type.DATABASE_CREATE,
+ ].includes(task.type);
+ });
+ });
+ const isTenantMode = computed((): boolean => {
+ // To sync databases schema in tenant mode, we use normal project logic to create issue.
+ if (isCreating.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 (
+ flattenTaskV1List(rollout.value).filter((task) =>
+ TaskTypeListWithStatement.includes(task.type)
+ ).length > 1
+ );
+ });
+ const isLegacyIssue = computed(() => {
+ return !issue.value.plan && !issue.value.planEntity;
+ });
+
+ return {
+ phase,
+ isGhostMode,
+ isPITRMode,
+ isTenantMode,
+ isLegacyIssue,
+ events,
+ reviewContext,
+ activeStage,
+ activeTask,
+ selectedStage,
+ selectedTask,
+ };
+};
diff --git a/frontend/src/components/IssueV1/logic/common.ts b/frontend/src/components/IssueV1/logic/common.ts
new file mode 100644
index 0000000000..74acaa62c1
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/common.ts
@@ -0,0 +1,35 @@
+import { RouteLocation } from "vue-router";
+
+import { RollbackDetail, UNKNOWN_ID } from "@/types";
+
+// Try to find out the relationship between databaseId and rollback issue/task
+// Id from the URL query.
+export const getRollbackTaskMappingFromQuery = (route: RouteLocation) => {
+ const mapping = new Map<string, RollbackDetail>();
+
+ const { query } = route;
+ const databaseUIDListInQuery = (query.databaseList as string) || "";
+ const databaseUIDList = databaseUIDListInQuery.split(",");
+
+ const rollbackIssueUIDInQuery = (query.rollbackIssueId as string) || "";
+ const issueUID = rollbackIssueUIDInQuery || String(UNKNOWN_ID);
+ if (issueUID === String(UNKNOWN_ID)) {
+ return mapping;
+ }
+
+ const rollbackTaskIdListInQuery = (query.rollbackTaskIdList as string) || "";
+ const taskIdList = rollbackTaskIdListInQuery
+ .split(",")
+ .map((maybeUID) => maybeUID || String(UNKNOWN_ID));
+
+ databaseUIDList.forEach((databaseId, index) => {
+ const taskUID = taskIdList[index] || String(UNKNOWN_ID);
+ if (taskUID !== String(UNKNOWN_ID)) {
+ mapping.set(databaseId, {
+ issueId: issueUID,
+ taskId: taskUID,
+ });
+ }
+ });
+ return mapping;
+};
diff --git a/frontend/src/components/IssueV1/logic/context.ts b/frontend/src/components/IssueV1/logic/context.ts
new file mode 100644
index 0000000000..72231708ac
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/context.ts
@@ -0,0 +1,86 @@
+import { InjectionKey, Ref, inject, provide } from "vue";
+import { useDialog } from "naive-ui";
+import Emittery from "emittery";
+
+import { ComposedIssue, ReviewFlow } from "@/types";
+import { Stage, Task } from "@/types/proto/v1/rollout_service";
+import { Issue_Approver_Status } from "@/types/proto/v1/issue_service";
+import {
+ IssueReviewAction,
+ IssueStatusAction,
+ TaskRolloutAction,
+} from "./action";
+
+export type IssuePhase = "CREATE" | "REVIEW" | "ROLLOUT";
+
+export type IssueEvents = Emittery<{
+ "status-changed": { eager: boolean };
+ "select-task": { task: Task };
+ "perform-issue-review-action": { action: IssueReviewAction };
+ "perform-issue-status-action": { action: IssueStatusAction };
+ "perform-task-rollout-action": { action: TaskRolloutAction; tasks: Task[] };
+}>;
+
+export type ReviewContext = {
+ // true if the approval flow is generated
+ ready: Ref<boolean>;
+ // The review flow.
+ // Now we have only one flow in an issue
+ flow: Ref<ReviewFlow>;
+ // The overall status of the entire review flow
+ status: Ref<Issue_Approver_Status>;
+ // Whether the review flow is finished successfully.
+ // A shortcut to `status === Review_Approver_Status.APPROVED`
+ done: Ref<boolean>;
+ // Whether the review finding has error.
+ error: Ref<string | undefined>;
+};
+
+export type IssueContext = {
+ // Basic fields
+ isCreating: Ref<boolean>;
+ ready: Ref<boolean>;
+ issue: Ref<ComposedIssue>;
+ phase: Ref<IssuePhase>;
+ isGhostMode: Ref<boolean>;
+ isPITRMode: Ref<boolean>;
+ isTenantMode: Ref<boolean>;
+ isLegacyIssue: Ref<boolean>;
+
+ // review status
+ reviewContext: ReviewContext;
+
+ // rollout status
+ activeStage: Ref<Stage>;
+ activeTask: Ref<Task>;
+
+ // UI status
+ selectedStage: Ref<Stage>;
+ selectedTask: Ref<Task>;
+
+ // UI events
+ events: IssueEvents;
+
+ // misc
+ dialog: ReturnType<typeof useDialog>;
+};
+
+const KEY = Symbol("bb.issue.context") as InjectionKey<IssueContext>;
+
+export const useIssueContext = () => {
+ return inject(KEY)!;
+};
+
+export const provideIssueContext = (
+ context: Partial<IssueContext>,
+ root = false
+) => {
+ if (!root) {
+ const parent = useIssueContext();
+ context = {
+ ...parent,
+ ...context,
+ };
+ }
+ provide(KEY, context as IssueContext);
+};
diff --git a/frontend/src/components/IssueV1/logic/index.ts b/frontend/src/components/IssueV1/logic/index.ts
new file mode 100644
index 0000000000..bf024b59b5
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/index.ts
@@ -0,0 +1,15 @@
+export * from "./context";
+export * from "./base";
+export * from "./common";
+export * from "./assignee";
+export * from "./plan";
+export * from "./review";
+export * from "./rollout";
+export * from "./utils";
+export * from "./initialize";
+export * from "./action";
+export * from "./sheet";
+export * from "./plan-check";
+export * from "./task-run";
+export * from "./poll";
+export * from "./subscriber";
diff --git a/frontend/src/components/IssueV1/logic/initialize/assignee.ts b/frontend/src/components/IssueV1/logic/initialize/assignee.ts
new file mode 100644
index 0000000000..87a20d350d
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/initialize/assignee.ts
@@ -0,0 +1,98 @@
+import { usePolicyV1Store, useUserStore } from "@/store";
+import { ComposedIssue, PresetRoleType } from "@/types";
+import { UserRole } from "@/types/proto/v1/auth_service";
+import {
+ ApprovalGroup,
+ ApprovalStrategy,
+ PolicyType,
+} from "@/types/proto/v1/org_policy_service";
+import {
+ flattenTaskV1List,
+ hasWorkspacePermissionV1,
+ memberListInProjectV1,
+} from "@/utils";
+import { first } from "lodash-es";
+import { extractRollOutPolicyValue } from "../assignee";
+import { databaseForTask } from "../utils";
+
+export const trySetDefaultAssignee = async (issue: ComposedIssue) => {
+ const firstTask = first(flattenTaskV1List(issue.rolloutEntity));
+ // The pipeline is accidentally empty, so we won't go further
+ if (!firstTask) return;
+
+ const database = databaseForTask(issue, firstTask);
+
+ const policy = await usePolicyV1Store().getOrFetchPolicyByParentAndType({
+ parentPath: database.instanceEntity.environment,
+ policyType: PolicyType.DEPLOYMENT_APPROVAL,
+ });
+
+ const rollOutPolicy = extractRollOutPolicyValue(policy, firstTask.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(issue);
+ return;
+ }
+ if (rollOutPolicy.policy === ApprovalStrategy.MANUAL) {
+ const { assigneeGroup } = rollOutPolicy;
+
+ if (assigneeGroup === ApprovalGroup.APPROVAL_GROUP_PROJECT_OWNER) {
+ // Assign to the project owner if needed.
+ assignToProjectOwner(issue);
+ return;
+ }
+
+ // If we don't find an assignee group for this issue type
+ // or its value is WORKSPACE_OWNER_OR_DBA.
+ assignToWorkspaceOwnerOrDBA(issue);
+ 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 = (issue: ComposedIssue) => {
+ const project = issue.projectEntity;
+ 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) {
+ issue.assignee = `users/${wm.email}`;
+ return;
+ }
+ }
+ }
+
+ for (const member of projectOwnerList) {
+ for (const wm of workspaceMemberList) {
+ if (wm.name == member.user.name) {
+ issue.assignee = `users/${wm.email}`;
+ return;
+ }
+ }
+ }
+};
+const assignToWorkspaceOwnerOrDBA = (issue: ComposedIssue) => {
+ 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) {
+ issue.assignee = `users/${ownerOrDBA.email}`;
+ }
+};
diff --git a/frontend/src/components/IssueV1/logic/initialize/create.ts b/frontend/src/components/IssueV1/logic/initialize/create.ts
new file mode 100644
index 0000000000..e3b4e238ea
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/initialize/create.ts
@@ -0,0 +1,402 @@
+import { type _RouteLocationBase } from "vue-router";
+import { v4 as uuidv4 } from "uuid";
+import { groupBy, orderBy } from "lodash-es";
+import { reactive } from "vue";
+
+import {
+ useDatabaseV1Store,
+ useDeploymentConfigV1Store,
+ useEnvironmentV1Store,
+ useProjectV1Store,
+ useSheetV1Store,
+} from "@/store";
+import {
+ ComposedProject,
+ emptyIssue,
+ TaskTypeListWithStatement,
+ UNKNOWN_ID,
+} from "@/types";
+import {
+ Plan,
+ Plan_ChangeDatabaseConfig,
+ Plan_ChangeDatabaseConfig_Type,
+ Plan_Spec,
+ Plan_Step,
+ Stage,
+ Task_Type,
+} from "@/types/proto/v1/rollout_service";
+import { IssueStatus, Issue_Type } from "@/types/proto/v1/issue_service";
+import { rolloutServiceClient } from "@/grpcweb";
+import { TemplateType } from "@/plugins";
+import { nextUID } from "../base";
+import {
+ extractSheetUID,
+ getPipelineFromDeploymentScheduleV1,
+ getSheetStatement,
+ instanceV1HasAlterSchema,
+ setSheetStatement,
+ sheetNameOfTaskV1,
+} from "@/utils";
+import { getLocalSheetByName } from "../sheet";
+import { trySetDefaultAssignee } from "./assignee";
+import { sheetNameForSpec } from "../plan";
+
+type CreateIssueParams = {
+ databaseUIDList: string[];
+ project: ComposedProject;
+ route: _RouteLocationBase;
+ initialSQL: {
+ sqlList?: string[];
+ sql?: string;
+ };
+};
+
+export const createIssueSkeleton = async (route: _RouteLocationBase) => {
+ const issue = emptyIssue();
+
+ const project = await useProjectV1Store().getOrFetchProjectByUID(
+ route.query.project as string
+ );
+ issue.project = project.name;
+ issue.projectEntity = project;
+ issue.uid = nextUID();
+ issue.name = `${project.name}/issues/${issue.uid}`;
+ issue.title = route.query.name as string;
+ issue.type = Issue_Type.DATABASE_CHANGE;
+ issue.status = IssueStatus.OPEN;
+
+ const databaseUIDList = ((route.query.databaseList as string) || "")
+ .split(",")
+ .filter((uid) => uid && uid !== String(UNKNOWN_ID));
+ await prepareDatabaseList(databaseUIDList, project.uid);
+
+ const params: CreateIssueParams = {
+ databaseUIDList,
+ project,
+ route,
+ initialSQL: extractInitialSQLListFromQuery(route),
+ };
+
+ const plan = await buildPlan(params);
+ issue.plan = plan.name;
+ issue.planEntity = plan;
+
+ const rollout = await previewPlan(plan, params);
+ issue.rollout = rollout.name;
+ issue.rolloutEntity = rollout;
+
+ await trySetDefaultAssignee(issue);
+
+ const description = route.query.description as string;
+ if (description) {
+ issue.description = description;
+ }
+
+ return issue;
+};
+
+export const buildPlan = async (params: CreateIssueParams) => {
+ const { databaseUIDList, project, route } = params;
+
+ const plan = Plan.fromJSON({
+ uid: nextUID(),
+ });
+ plan.name = `${project.name}/plans/${plan.uid}`;
+ if (route.query.mode === "tenant") {
+ // in tenant mode, all specs share a unique sheet
+ const sheetUID = nextUID();
+ // build tenant plan
+ if (databaseUIDList.length === 0) {
+ // evaluate DeploymentConfig and generate steps/specs
+ if (route.query.databaseGroupName) {
+ alert("databaseGroup not implemented yet");
+ } else {
+ plan.steps = await buildStepsViaDeploymentConfig(params, sheetUID);
+ }
+ } else {
+ plan.steps = await buildSteps(databaseUIDList, params, sheetUID);
+ }
+ } else {
+ // build standard plan
+ plan.steps = await buildSteps(
+ databaseUIDList,
+ params,
+ undefined // each spec should has an independent sheet
+ );
+ }
+ return plan;
+};
+
+export const buildSteps = async (
+ databaseUIDList: string[],
+ params: CreateIssueParams,
+ sheetUID?: string // if specified, all tasks will share the same sheet
+) => {
+ const databaseList = databaseUIDList.map((uid) =>
+ useDatabaseV1Store().getDatabaseByUID(uid)
+ );
+
+ const databaseListGroupByEnvironment = groupBy(
+ databaseList,
+ (db) => db.instanceEntity.environment
+ );
+ const stageList = orderBy(
+ Object.keys(databaseListGroupByEnvironment).map((env) => {
+ const environment = useEnvironmentV1Store().getEnvironmentByName(env);
+ const databases = databaseListGroupByEnvironment[env];
+ return {
+ environment,
+ databases,
+ };
+ }),
+ [(stage) => stage.environment?.order],
+ ["asc"]
+ );
+
+ const steps: Plan_Step[] = [];
+ let index = 0;
+ for (let i = 0; i < stageList.length; i++) {
+ const step = Plan_Step.fromJSON({});
+ const { databases } = stageList[i];
+ for (let j = 0; j < databases.length; j++) {
+ const db = databases[j];
+ const spec = await buildSpecForTarget(db.name, params, sheetUID);
+ step.specs.push(spec);
+ maybeSetInitialSQLForSpec(spec, index, params);
+ index++;
+ }
+ steps.push(step);
+ }
+ return steps;
+};
+
+export const buildStepsViaDeploymentConfig = async (
+ params: CreateIssueParams,
+ sheetUID: string
+) => {
+ const { route, project } = params;
+ const deploymentConfig =
+ await useDeploymentConfigV1Store().fetchDeploymentConfigByProjectName(
+ project.name
+ );
+ let databaseList = useDatabaseV1Store().databaseListByProject(project.name);
+ const template = route.query.template as TemplateType;
+
+ if (
+ template === "bb.issue.database.schema.update" ||
+ template === "bb.issue.database.schema.update.ghost"
+ ) {
+ databaseList = databaseList.filter((db) =>
+ instanceV1HasAlterSchema(db.instanceEntity)
+ );
+ }
+ const stages = getPipelineFromDeploymentScheduleV1(
+ databaseList,
+ deploymentConfig?.schedule
+ ).filter((stage) => stage.length > 0);
+ const steps: Plan_Step[] = [];
+ let index = 0;
+ for (let i = 0; i < stages.length; i++) {
+ const step = Plan_Step.fromJSON({});
+ const databases = stages[i];
+ for (let j = 0; j < databases.length; j++) {
+ const db = databases[j];
+ const spec = await buildSpecForTarget(db.name, params, sheetUID);
+ step.specs.push(spec);
+ maybeSetInitialSQLForSpec(spec, index, params);
+
+ index++;
+ }
+ steps.push(step);
+ }
+ return steps;
+};
+
+export const buildSpecForDatabaseGroup = async (params: CreateIssueParams) => {
+ const group = (params.route.query.databaseGroupName as string) || "";
+ const target = group ? group : `${params.project.name}/deploymentConfig`;
+ return buildSpecForTarget(target, params);
+};
+
+export const buildSpecForTarget = async (
+ target: string,
+ { project, route }: CreateIssueParams,
+ sheetUID?: string
+) => {
+ const sheet = `${project.name}/sheets/${sheetUID ?? nextUID()}`;
+ const template = route.query.template as TemplateType;
+ const spec = Plan_Spec.fromJSON({
+ id: uuidv4(),
+ });
+ if (template === "bb.issue.database.data.update") {
+ spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({
+ target,
+ type: Plan_ChangeDatabaseConfig_Type.DATA,
+ });
+ if (route.query.sheetId) {
+ const sheet = await useSheetV1Store().getOrFetchSheetByUID(
+ route.query.sheetId as string
+ );
+ if (sheet) {
+ spec.changeDatabaseConfig.sheet = sheet.name;
+ }
+ }
+ if (!spec.changeDatabaseConfig.sheet) {
+ spec.changeDatabaseConfig.sheet = sheet;
+ }
+ }
+ if (template === "bb.issue.database.schema.update") {
+ const type =
+ route.query.ghost === "1"
+ ? Plan_ChangeDatabaseConfig_Type.MIGRATE_GHOST
+ : Plan_ChangeDatabaseConfig_Type.MIGRATE;
+ spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({
+ target,
+ type,
+ sheet,
+ });
+ }
+ if (template === "bb.issue.database.schema.baseline") {
+ spec.changeDatabaseConfig = Plan_ChangeDatabaseConfig.fromJSON({
+ target,
+ type: Plan_ChangeDatabaseConfig_Type.BASELINE,
+ });
+ }
+
+ return spec;
+};
+
+export const previewPlan = async (plan: Plan, params: CreateIssueParams) => {
+ const rollout = await rolloutServiceClient.previewRollout({
+ project: params.project.name,
+ plan,
+ });
+ // Touch UIDs for each object for local referencing
+ rollout.plan = plan.name;
+ rollout.uid = nextUID();
+ rollout.name = `${params.project.name}/rollouts/${rollout.uid}`;
+ rollout.stages.forEach((stage) => {
+ stage.uid = nextUID();
+ stage.name = `${rollout.name}/stages/${stage.uid}`;
+ stage.tasks.forEach((task) => {
+ task.uid = nextUID();
+ task.name = `${stage.name}/tasks/${task.uid}`;
+ });
+ });
+
+ return reactive(rollout);
+};
+
+const maybeSetInitialSQLForSpec = (
+ spec: Plan_Spec,
+ index: number,
+ params: CreateIssueParams
+) => {
+ const sheet = sheetNameForSpec(spec);
+ if (!sheet) return;
+ const uid = extractSheetUID(sheet);
+ if (!uid.startsWith("-")) {
+ // If the sheet is a remote sheet, ignore initial SQL in URL query
+ return;
+ }
+ // Priority: sqlList[index] -> sql -> nothing
+ const sql = params.initialSQL.sqlList?.[index] ?? params.initialSQL.sql ?? "";
+ if (sql) {
+ const sheetEntity = getLocalSheetByName(sheet);
+ setSheetStatement(sheetEntity, sql);
+ }
+};
+
+const extractInitialSQLListFromQuery = (
+ route: _RouteLocationBase
+): {
+ sqlList?: string[];
+ sql?: string;
+} => {
+ const sqlListJSON = route.query.sqlList as string;
+ if (sqlListJSON && sqlListJSON.startsWith("[") && sqlListJSON.endsWith("]")) {
+ try {
+ const sqlList = JSON.parse(sqlListJSON) as string[];
+ if (Array.isArray(sqlList)) {
+ if (sqlList.every((maybeSQL) => typeof maybeSQL === "string")) {
+ return {
+ sqlList,
+ };
+ }
+ }
+ } catch {
+ // Nothing
+ }
+ }
+ const sql = route.query.sql;
+ if (sql && typeof sql === "string") {
+ return {
+ sql,
+ };
+ }
+ return {};
+};
+
+export const prepareDatabaseList = async (
+ databaseUIDList: string[],
+ projectUID: string
+) => {
+ const databaseStore = useDatabaseV1Store();
+ if (projectUID && projectUID !== String(UNKNOWN_ID)) {
+ // 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.
+ const project = await useProjectV1Store().getOrFetchProjectByUID(
+ projectUID
+ );
+ await prepareDatabaseListByProject(project.name);
+ } else {
+ // Otherwise, we don't have the projectUID (very rare to see, theoretically)
+ // so we need to fetch the first database in databaseList by id,
+ // and see what project it belongs.
+ if (databaseUIDList.length > 0) {
+ const firstDB = await databaseStore.getOrFetchDatabaseByUID(
+ databaseUIDList[0]
+ );
+ if (databaseUIDList.length > 1) {
+ await prepareDatabaseListByProject(firstDB.project);
+ }
+ }
+ }
+};
+
+const prepareDatabaseListByProject = async (project: string) => {
+ await useDatabaseV1Store().searchDatabaseList({
+ parent: `instances/-`,
+ filter: `project == "${project}"`,
+ });
+};
+
+export const isValidStage = (stage: Stage): boolean => {
+ for (const task of stage.tasks) {
+ if (task.type === Task_Type.DATABASE_SCHEMA_BASELINE) {
+ continue;
+ }
+
+ if (TaskTypeListWithStatement.includes(task.type)) {
+ const sheetName = sheetNameOfTaskV1(task);
+ const uid = extractSheetUID(sheetName);
+ if (uid.startsWith("-")) {
+ const sheet = getLocalSheetByName(sheetName);
+ if (getSheetStatement(sheet).length === 0) {
+ return false;
+ }
+ } else {
+ const sheet = useSheetV1Store().getSheetByName(sheetName);
+ if (!sheet) {
+ return false;
+ }
+ if (getSheetStatement(sheet).length === 0) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+};
diff --git a/frontend/src/components/IssueV1/logic/initialize/index.ts b/frontend/src/components/IssueV1/logic/initialize/index.ts
new file mode 100644
index 0000000000..6ec90788a4
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/initialize/index.ts
@@ -0,0 +1,59 @@
+import { computed, ref, Ref, watch } from "vue";
+import { useRoute, useRouter, _RouteLocationBase } from "vue-router";
+
+import { ComposedIssue, emptyIssue, EMPTY_ID, UNKNOWN_ID } from "@/types";
+import { experimentalFetchIssueByUID } from "@/store";
+import { idFromSlug } from "@/utils";
+import { createIssueSkeleton } from "./create";
+
+export * from "./create";
+
+export function useInitializeIssue(issueSlug: Ref<string>) {
+ const isCreating = computed(() => issueSlug.value.toLowerCase() == "new");
+ const uid = computed(() => {
+ const slug = issueSlug.value;
+ if (slug.toLowerCase() === "new") return String(EMPTY_ID);
+ const uid = Number(idFromSlug(slug));
+ if (uid > 0) return String(uid);
+ return String(UNKNOWN_ID);
+ });
+ const route = useRoute();
+ const router = useRouter();
+ const isInitializing = ref(false);
+
+ const issue = ref<ComposedIssue>(emptyIssue());
+
+ const runner = async (uid: string, url: string) => {
+ const issue =
+ uid === String(EMPTY_ID)
+ ? await createIssueSkeleton(router.resolve(url))
+ : await experimentalFetchIssueByUID(uid);
+ return {
+ issue,
+ url,
+ };
+ };
+
+ watch(
+ uid,
+ (uid) => {
+ if (uid === String(UNKNOWN_ID)) {
+ router.push({ name: "error.404" });
+ return;
+ }
+ const url = route.fullPath;
+ isInitializing.value = true;
+ runner(uid, url).then((result) => {
+ if (result.url !== route.fullPath) {
+ // the url changed, drop the outdated result
+ return;
+ }
+ issue.value = result.issue;
+ isInitializing.value = false;
+ });
+ },
+ { immediate: true }
+ );
+
+ return { isCreating, issue, isInitializing };
+}
diff --git a/frontend/src/components/IssueV1/logic/plan-check.ts b/frontend/src/components/IssueV1/logic/plan-check.ts
new file mode 100644
index 0000000000..d73ee64c8f
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/plan-check.ts
@@ -0,0 +1,230 @@
+import { ComposedIssue } from "@/types";
+import {
+ PlanCheckRun,
+ PlanCheckRun_Result_Status,
+ PlanCheckRun_Status,
+ PlanCheckRun_Type,
+ Task,
+ Task_Status,
+} from "@/types/proto/v1/rollout_service";
+import { groupBy, maxBy } from "lodash-es";
+import { databaseForTask } from ".";
+
+export const planCheckRunListForTask = (issue: ComposedIssue, task: Task) => {
+ const database = databaseForTask(issue, task);
+ return issue.planCheckRunList.filter(
+ (check) => check.target === database.name
+ );
+};
+
+export const allPlanChecksPassedForTask = (
+ issue: ComposedIssue,
+ task: Task
+) => {
+ const planCheckRunList = planCheckRunListForTask(issue, task);
+ if (planCheckRunList.length === 0) {
+ return true;
+ }
+ const summary = planCheckRunSummaryForCheckRunList(planCheckRunList);
+ return summary.errorCount === 0;
+};
+
+export const HiddenPlanCheckTypes = new Set<PlanCheckRun_Type>([
+ PlanCheckRun_Type.DATABASE_STATEMENT_SUMMARY_REPORT,
+]);
+
+export const planCheckRunResultStatus = (checkRun: PlanCheckRun) => {
+ let status = PlanCheckRun_Result_Status.SUCCESS;
+
+ for (const result of checkRun.results) {
+ if (result.status === PlanCheckRun_Result_Status.ERROR) {
+ return PlanCheckRun_Result_Status.ERROR;
+ }
+ if (result.status === PlanCheckRun_Result_Status.WARNING) {
+ status = PlanCheckRun_Result_Status.WARNING;
+ }
+ }
+ return status;
+};
+
+export const planCheckStatusForTask = (issue: ComposedIssue, task: Task) => {
+ if (
+ task.status === Task_Status.PENDING ||
+ task.status === Task_Status.NOT_STARTED
+ ) {
+ const summary = planCheckRunSummaryForTask(issue, task);
+ if (summary.errorCount > 0) return PlanCheckRun_Result_Status.ERROR;
+ if (summary.warnCount > 0) return PlanCheckRun_Result_Status.WARNING;
+ }
+ return undefined;
+};
+
+export type PlanCheckRunSummary = {
+ runningCount: number;
+ successCount: number;
+ warnCount: number;
+ errorCount: number;
+};
+
+export const planCheckRunSummaryForCheckRunList = (
+ planCheckRunList: PlanCheckRun[]
+) => {
+ const summary: PlanCheckRunSummary = {
+ runningCount: 0,
+ successCount: 0,
+ warnCount: 0,
+ errorCount: 0,
+ };
+
+ planCheckRunList = planCheckRunList.filter(
+ (check) => !HiddenPlanCheckTypes.has(check.type)
+ );
+
+ const listGroupByType = groupBy(
+ planCheckRunList,
+ (checkRun) => checkRun.type
+ );
+
+ const latestCheckRunOfEachType = Object.keys(listGroupByType).map((type) => {
+ const listOfType = listGroupByType[type];
+ const latest = maxBy(listOfType, (checkRun) => Number(checkRun.uid))!;
+ return latest;
+ });
+
+ for (const checkRun of latestCheckRunOfEachType) {
+ switch (checkRun.status) {
+ case PlanCheckRun_Status.CANCELED:
+ // nothing todo
+ break;
+ case PlanCheckRun_Status.FAILED:
+ summary.errorCount++;
+ break;
+ case PlanCheckRun_Status.RUNNING:
+ summary.runningCount++;
+ break;
+ case PlanCheckRun_Status.DONE:
+ switch (planCheckRunResultStatus(checkRun)) {
+ case PlanCheckRun_Result_Status.SUCCESS:
+ summary.successCount++;
+ break;
+ case PlanCheckRun_Result_Status.WARNING:
+ summary.warnCount++;
+ break;
+ case PlanCheckRun_Result_Status.ERROR:
+ summary.errorCount++;
+ }
+ }
+ }
+
+ return summary;
+};
+
+export const planCheckRunSummaryForIssue = (issue: ComposedIssue) => {
+ return planCheckRunSummaryForCheckRunList(issue.planCheckRunList);
+};
+
+export const planCheckRunSummaryForTask = (
+ issue: ComposedIssue,
+ task: Task
+) => {
+ const planCheckRunList = planCheckRunListForTask(issue, task);
+ return planCheckRunSummaryForCheckRunList(planCheckRunList);
+};
+
+// export const isTaskSkipped = (task: Task): boolean => {
+// if (task.status === "DONE") {
+// const payload = task.payload as any;
+// return payload?.skipped === true;
+// }
+// return false;
+// };
+
+// export const isTaskTriggeredByVCS = (task: Task): boolean => {
+// const taskTypesWithPushEvent: TaskType[] = [
+// "bb.task.database.data.update",
+// "bb.task.database.schema.update",
+// "bb.task.database.schema.update-sdl",
+// "bb.task.database.schema.update.ghost.sync",
+// "bb.task.database.schema.baseline",
+// ];
+
+// type PayloadTypesWithPushEvent =
+// | TaskDatabaseDataUpdatePayload
+// | TaskDatabaseSchemaUpdatePayload
+// | TaskDatabaseSchemaUpdateSDLPayload
+// | TaskDatabaseSchemaUpdateGhostSyncPayload
+// | TaskDatabaseSchemaBaselinePayload;
+
+// if (taskTypesWithPushEvent.includes(task.type)) {
+// const payload = task.payload as PayloadTypesWithPushEvent | undefined;
+
+// if (payload && payload.pushEvent) {
+// return true;
+// }
+// }
+
+// return false;
+// };
+
+// export const isTaskEntity = (task: Task | TaskCreate): task is Task => {
+// const obj = task as any;
+// return typeof obj["id"] === "number";
+// };
+
+// export const isTaskCreate = (task: Task | TaskCreate): task is TaskCreate => {
+// return !isTaskEntity(task);
+// };
+
+// /**
+// *
+// * @param task
+// * @param issue
+// * @param activeOnly if true, only "Active Task" can be skipped
+// * @returns
+// */
+// export const canSkipTask = (
+// task: Task,
+// issue: Issue,
+// activeOnly = false,
+// failedOnly = false
+// ) => {
+// const pipeline = issue.pipeline;
+// const isActiveTask = task.id === activeTask(pipeline!).id;
+// if (activeOnly && !isActiveTask) {
+// return false;
+// }
+
+// const applicableStatusList: TaskStatus[] = failedOnly
+// ? ["FAILED"]
+// : ["PENDING_APPROVAL", "FAILED"];
+
+// if (!applicableStatusList.includes(task.status)) {
+// return false;
+// }
+
+// const currentUserV1 = useCurrentUserV1();
+
+// if (
+// hasWorkspacePermissionV1(
+// "bb.permission.workspace.manage-issue",
+// currentUserV1.value.userRole
+// )
+// ) {
+// return true;
+// }
+
+// if (extractUserUID(currentUserV1.value.name) === String(issue.assignee.id)) {
+// return true;
+// }
+
+// return false;
+// };
+
+// export const checkStatusOfTask = (task: Task): TaskCheckStatus | undefined => {
+// if (task.status === "PENDING" || task.status === "PENDING_APPROVAL") {
+// const summary = taskCheckRunSummary(task);
+// if (summary.errorCount > 0) return "ERROR";
+// if (summary.warnCount > 0) return "WARN";
+// }
+// return undefined;
+// };
diff --git a/frontend/src/components/IssueV1/logic/plan.ts b/frontend/src/components/IssueV1/logic/plan.ts
new file mode 100644
index 0000000000..13e7288976
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/plan.ts
@@ -0,0 +1,5 @@
+import { Plan_Spec } from "@/types/proto/v1/rollout_service";
+
+export const sheetNameForSpec = (spec: Plan_Spec): string => {
+ return spec.changeDatabaseConfig?.sheet ?? "";
+};
diff --git a/frontend/src/components/IssueV1/logic/poll.ts b/frontend/src/components/IssueV1/logic/poll.ts
new file mode 100644
index 0000000000..af77c3613e
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/poll.ts
@@ -0,0 +1,58 @@
+import { useProgressivePoll } from "@/composables/useProgressivePoll";
+import { experimentalFetchIssueByUID } from "@/store";
+import { UNKNOWN_ID } from "@/types";
+import { computed, watch } from "vue";
+import { useIssueContext } from "./context";
+
+export const usePollIssue = () => {
+ const { isCreating, ready, issue, events, activeTask } = useIssueContext();
+
+ const shouldPollIssue = computed(() => {
+ return !isCreating.value && ready.value;
+ });
+
+ const refreshIssue = () => {
+ if (!shouldPollIssue.value) return;
+
+ experimentalFetchIssueByUID(issue.value.uid).then(
+ (updatedIssue) => (issue.value = updatedIssue)
+ );
+ };
+
+ const poller = useProgressivePoll(refreshIssue, {
+ interval: {
+ min: 500,
+ max: 10000,
+ growth: 2,
+ jitter: 500,
+ },
+ });
+
+ watch(
+ shouldPollIssue,
+ () => {
+ if (shouldPollIssue.value) {
+ poller.start();
+ } else {
+ poller.stop();
+ }
+ },
+ {
+ immediate: true,
+ }
+ );
+
+ events.on("status-changed", ({ eager }) => {
+ if (eager) {
+ refreshIssue();
+ poller.restart();
+ }
+ });
+
+ watch(activeTask, (curr, prev) => {
+ if (curr.uid === String(UNKNOWN_ID)) return;
+ if (curr.uid !== prev.uid) {
+ events.emit("select-task", { task: curr });
+ }
+ });
+};
diff --git a/frontend/src/components/IssueV1/logic/review.ts b/frontend/src/components/IssueV1/logic/review.ts
new file mode 100644
index 0000000000..f25c65492f
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/review.ts
@@ -0,0 +1,147 @@
+import { Ref, computed, unref } from "vue";
+
+import {
+ ReviewFlow,
+ emptyFlow,
+ MaybeRef,
+ ComposedIssue,
+ WrappedReviewStep,
+} from "@/types";
+import { Issue, Issue_Approver_Status } from "@/types/proto/v1/issue_service";
+import { ReviewContext } from "./context";
+import {
+ candidatesOfApprovalStepV1,
+ useAuthStore,
+ useUserStore,
+} from "@/store";
+import { extractUserResourceName } from "@/utils";
+
+export const extractReviewContext = (issue: Ref<Issue>): ReviewContext => {
+ const ready = computed(() => {
+ return issue.value.approvalFindingDone ?? false;
+ });
+ const flow = computed((): ReviewFlow => {
+ if (!ready.value) return emptyFlow();
+ const { approvalTemplates, approvers } = issue.value;
+ if (approvalTemplates.length === 0) return emptyFlow();
+
+ const rejectedIndex = approvers.findIndex(
+ (ap) => ap.status === Issue_Approver_Status.REJECTED
+ );
+ const currentStepIndex =
+ rejectedIndex >= 0 ? rejectedIndex : approvers.length;
+
+ return {
+ template: approvalTemplates[0],
+ approvers,
+ currentStepIndex,
+ };
+ });
+ const status = computed(() => {
+ if (!ready.value) {
+ return Issue_Approver_Status.PENDING;
+ }
+ if (issue.value.approvalFindingError) {
+ return Issue_Approver_Status.PENDING;
+ }
+
+ const { template, approvers } = flow.value;
+ const steps = template.flow?.steps ?? [];
+
+ if (steps.length === 0) {
+ // No review flow steps. That means need not manual review.
+ return Issue_Approver_Status.APPROVED;
+ }
+
+ if (
+ approvers.some((app) => app.status === Issue_Approver_Status.REJECTED)
+ ) {
+ // If any of the approvers down voted, the overall status should be 'REJECTED'
+ return Issue_Approver_Status.REJECTED;
+ }
+
+ // For an N-steps approval flow, we need exactly N upvote approvals to
+ // pass the entire flow.
+ const upVotes = approvers.filter(
+ (app) => app.status === Issue_Approver_Status.APPROVED
+ );
+ if (upVotes.length === steps.length) {
+ return Issue_Approver_Status.APPROVED;
+ }
+ return Issue_Approver_Status.PENDING;
+ });
+ const done = computed(() => {
+ return status.value === Issue_Approver_Status.APPROVED;
+ });
+ const error = computed(() => {
+ return issue.value.approvalFindingError;
+ });
+
+ return {
+ ready,
+ flow,
+ status,
+ done,
+ error,
+ };
+};
+
+export const useWrappedReviewStepsV1 = (
+ issue: MaybeRef<ComposedIssue>,
+ context: ReviewContext
+) => {
+ 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 = candidatesOfApprovalStepV1(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),
+ }));
+ });
+};
diff --git a/frontend/src/components/IssueV1/logic/rollout.ts b/frontend/src/components/IssueV1/logic/rollout.ts
new file mode 100644
index 0000000000..229a6b3059
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/rollout.ts
@@ -0,0 +1,119 @@
+import { ComposedIssue } from "@/types";
+import { User } from "@/types/proto/v1/auth_service";
+import { IssueStatus, Issue_Type } from "@/types/proto/v1/issue_service";
+import { TenantMode } from "@/types/proto/v1/project_service";
+import {
+ Task,
+ Task_Status,
+ task_StatusToJSON,
+ Task_Type,
+} from "@/types/proto/v1/rollout_service";
+import {
+ extractUserResourceName,
+ flattenTaskV1List,
+ hasWorkspacePermissionV1,
+} from "@/utils";
+import { planCheckRunSummaryForTask } from ".";
+
+export const isGroupingChangeTaskV1 = (issue: ComposedIssue, task: Task) => {
+ return false; // TODO
+};
+
+export const allowUserToEditStatementForTask = (
+ issue: ComposedIssue,
+ task: Task,
+ user: User
+): string[] => {
+ const denyReasons: string[] = [];
+
+ if (isGroupingChangeTaskV1(issue, task)) {
+ denyReasons.push("Cannot edit database group change issue");
+ }
+
+ if (isTaskV1TriggeredByVCS(issue, 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 [];
+ }
+
+ if (issue.type !== Issue_Type.DATABASE_CHANGE) {
+ denyReasons.push("Only database change issue type can be changed");
+ }
+ if (issue.status !== IssueStatus.OPEN) {
+ denyReasons.push("The issue is not open");
+ }
+
+ if (task.type === Task_Type.DATABASE_CREATE) {
+ // For standard mode projects, we are not allowed to edit the database
+ // creation SQL statement.
+ if (issue.projectEntity.tenantMode !== TenantMode.TENANT_MODE_ENABLED) {
+ denyReasons.push("Cannot edit database creation statement");
+ }
+
+ // 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 (issue.projectEntity.tenantMode === TenantMode.TENANT_MODE_ENABLED) {
+ const tasks = flattenTaskV1List(issue.rolloutEntity);
+ if (!tasks.every((task) => isTaskEditable(issue, task).length === 0)) {
+ denyReasons.push("Some of the tasks are not editable in batch mode");
+ }
+ }
+
+ // if not creating, we are allowed to edit sql statement only when:
+ // - user is the creator
+ // - OR user is Workspace DBA or Owner
+
+ denyReasons.push(...isTaskEditable(issue, task));
+
+ if (extractUserResourceName(issue.creator) !== user.email) {
+ if (
+ !hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-issue",
+ user.userRole
+ )
+ ) {
+ denyReasons.push("You don't have the privilege to edit this issue");
+ }
+ }
+ return denyReasons;
+};
+
+export const isTaskEditable = (issue: ComposedIssue, task: Task): string[] => {
+ if (
+ task.status === Task_Status.NOT_STARTED ||
+ task.status === Task_Status.FAILED ||
+ task.status === Task_Status.CANCELED
+ ) {
+ return [];
+ }
+ if (task.status === 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 = planCheckRunSummaryForTask(issue, task);
+ if (summary.errorCount > 0) {
+ return [];
+ }
+ return [`Task is pending to run`];
+ }
+
+ return [`${task_StatusToJSON(task.status)} task is not editable`];
+};
+
+export const isTaskFinished = (task: Task): boolean => {
+ return [Task_Status.DONE, Task_Status.SKIPPED].includes(task.status);
+};
+
+export const isTaskV1TriggeredByVCS = (
+ issue: ComposedIssue,
+ task: Task
+): boolean => {
+ return false; // TODO
+};
diff --git a/frontend/src/components/IssueV1/logic/sheet.ts b/frontend/src/components/IssueV1/logic/sheet.ts
new file mode 100644
index 0000000000..3feca1996d
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/sheet.ts
@@ -0,0 +1,32 @@
+import { reactive } from "vue";
+import {
+ Sheet,
+ Sheet_Source,
+ Sheet_Type,
+ Sheet_Visibility,
+} from "@/types/proto/v1/sheet_service";
+
+const sheetsByName = reactive(new Map<string, Sheet>());
+
+export const createEmptyLocalSheet = () => {
+ return reactive(
+ Sheet.fromJSON({
+ source: Sheet_Source.SOURCE_BYTEBASE_ARTIFACT,
+ visibility: Sheet_Visibility.VISIBILITY_PROJECT,
+ type: Sheet_Type.TYPE_SQL,
+ })
+ );
+};
+
+export const getLocalSheetByName = (name: string) => {
+ const existed = sheetsByName.get(name);
+ if (existed) {
+ return existed;
+ }
+ const sheet = reactive({
+ ...createEmptyLocalSheet(),
+ name,
+ });
+ sheetsByName.set(name, sheet);
+ return sheet;
+};
diff --git a/frontend/src/components/IssueV1/logic/subscriber.ts b/frontend/src/components/IssueV1/logic/subscriber.ts
new file mode 100644
index 0000000000..586d75b7d1
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/subscriber.ts
@@ -0,0 +1,49 @@
+import { Issue } from "@/types/proto/v1/issue_service";
+import { issueServiceClient } from "@/grpcweb";
+import { pushNotification } from "@/store";
+import { t } from "@/plugins/i18n";
+import { User } from "@/types/proto/v1/auth_service";
+import { pull } from "lodash-es";
+
+export const updateIssueSubscribers = async (
+ issue: Issue,
+ subscribers: string[]
+) => {
+ const issuePatch = Issue.fromJSON({
+ ...issue,
+ subscribers,
+ });
+ const updated = await issueServiceClient.updateIssue({
+ issue: issuePatch,
+ updateMask: ["subscribers"],
+ });
+ Object.assign(issue, updated);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+};
+
+export const toggleSubscribeIssue = async (issue: Issue, user: User) => {
+ const subscribers = [...issue.subscribers];
+ const userTag = `users/${user.email}`;
+ const isSubscribed = subscribers.includes(userTag);
+ if (isSubscribed) {
+ pull(subscribers, userTag);
+ } else {
+ subscribers.push(userTag);
+ }
+ return await updateIssueSubscribers(issue, subscribers);
+};
+
+export const doSubscribeIssue = async (issue: Issue, user: User) => {
+ const subscribers = [...issue.subscribers];
+ const userTag = `users/${user.email}`;
+ const isSubscribed = subscribers.includes(userTag);
+ if (isSubscribed) {
+ return;
+ }
+ subscribers.push(userTag);
+ return await updateIssueSubscribers(issue, subscribers);
+};
diff --git a/frontend/src/components/IssueV1/logic/task-run.ts b/frontend/src/components/IssueV1/logic/task-run.ts
new file mode 100644
index 0000000000..7f9be1352d
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/task-run.ts
@@ -0,0 +1,9 @@
+import { ComposedIssue } from "@/types";
+import { Task } from "@/types/proto/v1/rollout_service";
+import { extractTaskUID } from "@/utils";
+
+export const taskRunListForTask = (issue: ComposedIssue, task: Task) => {
+ return issue.rolloutTaskRunList.filter(
+ (taskRun) => extractTaskUID(taskRun.name) === task.uid
+ );
+};
diff --git a/frontend/src/components/IssueV1/logic/utils.ts b/frontend/src/components/IssueV1/logic/utils.ts
new file mode 100644
index 0000000000..a681ebadaf
--- /dev/null
+++ b/frontend/src/components/IssueV1/logic/utils.ts
@@ -0,0 +1,107 @@
+import { t } from "@/plugins/i18n";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useInstanceV1Store,
+} from "@/store";
+import {
+ ComposedIssue,
+ ComposedProject,
+ unknownDatabase,
+ UNKNOWN_ID,
+} from "@/types";
+import { Plan, Task, Task_Type } from "@/types/proto/v1/rollout_service";
+import { extractDatabaseResourceName, flattenSpecList } from "@/utils";
+
+export const databaseForTask = (issue: ComposedIssue, task: Task) => {
+ if (
+ task.type === Task_Type.DATABASE_CREATE ||
+ task.type === Task_Type.DATABASE_RESTORE_RESTORE ||
+ task.type === Task_Type.DATABASE_RESTORE_CUTOVER
+ ) {
+ // The database is not created yet.
+ // extract database info from the task's and payload's properties.
+ return extractCoreDatabaseInfoFromDatabaseCreateTask(
+ issue.projectEntity,
+ task
+ );
+ } else {
+ if (
+ task.databaseDataUpdate ||
+ task.databaseSchemaUpdate ||
+ task.databaseRestoreRestore ||
+ task.type === Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER ||
+ task.type === Task_Type.DATABASE_SCHEMA_BASELINE
+ ) {
+ return useDatabaseV1Store().getDatabaseByName(task.target);
+ }
+ }
+ return unknownDatabase();
+};
+
+const extractCoreDatabaseInfoFromDatabaseCreateTask = (
+ project: ComposedProject,
+ task: Task
+) => {
+ const coreDatabaseInfo = (instance: string, databaseName: string) => {
+ const name = `${instance}/databases/${databaseName}`;
+ const maybeExistedDatabase = useDatabaseV1Store().getDatabaseByName(name);
+ if (maybeExistedDatabase.uid !== String(UNKNOWN_ID)) {
+ return maybeExistedDatabase;
+ }
+
+ const instanceEntity = useInstanceV1Store().getInstanceByName(instance);
+ return {
+ ...unknownDatabase(),
+ name,
+ uid: String(UNKNOWN_ID),
+ databaseName,
+ instance,
+ instanceEntity,
+ project: project.name,
+ projectEntity: project,
+ };
+ };
+
+ if (task.databaseCreate) {
+ const databaseName = task.databaseCreate.database;
+ const instance = task.target;
+ return coreDatabaseInfo(instance, databaseName);
+ }
+ if (task.databaseRestoreRestore) {
+ const db = extractDatabaseResourceName(
+ task.databaseRestoreRestore.target || task.target
+ );
+ const databaseName = db.database;
+ const instance = `instances/${db.instance}`;
+ return coreDatabaseInfo(instance, databaseName);
+ }
+ if (task.type === Task_Type.DATABASE_RESTORE_CUTOVER) {
+ const db = extractDatabaseResourceName(task.target);
+ const databaseName = db.database;
+ const instance = `instances/${db.instance}`;
+ return coreDatabaseInfo(instance, databaseName);
+ }
+
+ return unknownDatabase();
+};
+
+export const specForTask = (plan: Plan | undefined, task: Task) => {
+ if (!plan) return undefined;
+ return flattenSpecList(plan).find((spec) => spec.id === task.specId);
+};
+
+export const stageForTask = (issue: ComposedIssue, task: Task) => {
+ const rollout = issue.rolloutEntity;
+ return rollout.stages.find(
+ (stage) => stage.tasks.findIndex((t) => t.name === task.name) >= 0
+ );
+};
+
+export const notifyNotEditableLegacyIssue = () => {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("issue.not-editable-legacy-issue"),
+ });
+};
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index ef32c6e27f..860c849292 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -1,9 +1,12 @@
<template>
- <div ref="editorContainerRef" v-bind="$attrs"></div>
- <BBSpin
- v-if="!isEditorLoaded"
- class="h-full w-full flex items-center justify-center"
- />
+ <div ref="editorContainerRef" v-bind="$attrs" class="relative">
+ <div
+ v-if="!isEditorLoaded"
+ class="absolute inset-0 flex flex-col items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </div>
</template>
<script lang="ts" setup>
diff --git a/frontend/src/components/misc/UploadProgressButton.vue b/frontend/src/components/misc/UploadProgressButton.vue
index dfa9a04763..56db503f8f 100644
--- a/frontend/src/components/misc/UploadProgressButton.vue
+++ b/frontend/src/components/misc/UploadProgressButton.vue
@@ -1,6 +1,7 @@
<template>
<NButton
:disabled="disabled"
+ tag="div"
style="--n-icon-margin: 3px"
@click="handleClick"
>
diff --git a/frontend/src/components/v2/Button/ContextMenuButton.vue b/frontend/src/components/v2/Button/ContextMenuButton.vue
index 3c7d3fa4c0..96654fa35e 100644
--- a/frontend/src/components/v2/Button/ContextMenuButton.vue
+++ b/frontend/src/components/v2/Button/ContextMenuButton.vue
@@ -1,15 +1,14 @@
<template>
- <NButtonGroup size="small">
+ <NButtonGroup v-if="currentAction" size="small">
<NButton
- v-if="currentAction"
v-bind="currentAction.props"
@click="$emit('click', currentAction)"
>
<template #icon>
- <slot name="icon" :action="currentAction!" />
+ <slot name="icon" :action="currentAction" />
</template>
- <slot name="default" :action="currentAction!">
- {{ currentAction?.text }}
+ <slot name="default" :action="currentAction">
+ {{ currentAction.text }}
</slot>
</NButton>
@@ -21,7 +20,10 @@
trigger="click"
@update:value="changeActionKey"
>
- <NButton style="--n-padding: 0 6px" v-bind="currentAction?.props">
+ <NButton
+ :style="dropdownButtonStyle(currentAction)"
+ v-bind="currentAction.props"
+ >
<heroicons-outline:chevron-down />
</NButton>
</NPopselect>
@@ -101,4 +103,15 @@ const changeActionKey = (key: string) => {
}
currentActionKey.value = key;
};
+
+const dropdownButtonStyle = (action: ContextMenuButtonAction) => {
+ const style: Record<string, any> = {
+ "--n-padding": "0 6px",
+ };
+ if (action.props?.type === "primary") {
+ style["--n-padding"] = "0 8px";
+ style["border-left"] = "0.5px solid var(--color-accent-hover)";
+ }
+ return style;
+};
</script>
diff --git a/frontend/src/components/v2/Button/TooltipButton.vue b/frontend/src/components/v2/Button/TooltipButton.vue
new file mode 100644
index 0000000000..3ad3ac4be0
--- /dev/null
+++ b/frontend/src/components/v2/Button/TooltipButton.vue
@@ -0,0 +1,60 @@
+<template>
+ <NTooltip v-bind="tooltipProps" :disabled="!tooltipDisabled">
+ <template #trigger>
+ <NButton
+ v-bind="$attrs"
+ tag="div"
+ :disabled="disabled"
+ @click="$emit('click')"
+ >
+ <template #icon>
+ <slot name="icon" />
+ </template>
+ <template #default>
+ <slot />
+ </template>
+ </NButton>
+ </template>
+ <template #default>
+ <slot name="tooltip" />
+ </template>
+ </NTooltip>
+</template>
+
+<script lang="ts">
+export default {
+ name: "BBTooltipButton",
+ inheritAttrs: false,
+};
+</script>
+
+<script lang="ts" setup>
+import { withDefaults, computed, useSlots } from "vue";
+import { NTooltip, type TooltipProps } from "naive-ui";
+import { TooltipMode } from "./types";
+
+const props = withDefaults(
+ defineProps<{
+ disabled: boolean;
+ tooltipMode: TooltipMode;
+ tooltipProps?: TooltipProps;
+ }>(),
+ {
+ disabled: false,
+ tooltipMode: "ALWAYS",
+ tooltipProps: undefined,
+ }
+);
+
+defineEmits<{
+ (event: "click"): void;
+}>();
+
+const slots = useSlots();
+
+const tooltipDisabled = computed(() => {
+ if (props.tooltipMode === "ALWAYS") return false;
+ if (!slots.tooltip) return true;
+ return props.disabled;
+});
+</script>
diff --git a/frontend/src/components/v2/Button/index.ts b/frontend/src/components/v2/Button/index.ts
index 6dcf5c1f58..de2632a09c 100644
--- a/frontend/src/components/v2/Button/index.ts
+++ b/frontend/src/components/v2/Button/index.ts
@@ -1,4 +1,5 @@
import ContextMenuButton from "./ContextMenuButton.vue";
+import TooltipButton from "./TooltipButton.vue";
-export { ContextMenuButton };
+export { ContextMenuButton, TooltipButton };
export * from "./types";
diff --git a/frontend/src/components/v2/Button/types.ts b/frontend/src/components/v2/Button/types.ts
index 013c2bb899..7de0afacf5 100644
--- a/frontend/src/components/v2/Button/types.ts
+++ b/frontend/src/components/v2/Button/types.ts
@@ -6,3 +6,5 @@ export type ContextMenuButtonAction<T = unknown> = {
props?: ButtonProps;
params: T;
};
+
+export type TooltipMode = "ALWAYS" | "DISABLED-ONLY";
diff --git a/frontend/src/components/v2/Model/EnvironmentV1Name.vue b/frontend/src/components/v2/Model/EnvironmentV1Name.vue
index bf232b28bd..bf7cafb465 100644
--- a/frontend/src/components/v2/Model/EnvironmentV1Name.vue
+++ b/frontend/src/components/v2/Model/EnvironmentV1Name.vue
@@ -9,6 +9,7 @@
<ProductionEnvironmentV1Icon
:environment="environment"
:class="iconClass ?? '!text-current'"
+ :tooltip="tooltip"
/>
</component>
</template>
@@ -27,12 +28,14 @@ const props = withDefaults(
link?: boolean;
plain?: boolean;
iconClass?: VueClass;
+ tooltip?: boolean;
}>(),
{
tag: "span",
link: true,
plain: false,
iconClass: undefined,
+ tooltip: false,
}
);
diff --git a/frontend/src/components/v2/Model/Instance/InstanceV1Name.vue b/frontend/src/components/v2/Model/Instance/InstanceV1Name.vue
index 89ba87543d..45c272a8f9 100644
--- a/frontend/src/components/v2/Model/Instance/InstanceV1Name.vue
+++ b/frontend/src/components/v2/Model/Instance/InstanceV1Name.vue
@@ -3,7 +3,7 @@
:is="link ? 'router-link' : tag"
v-bind="bindings"
class="inline-flex items-center gap-x-1"
- :class="link && 'normal-link'"
+ :class="link && !plain && 'normal-link'"
>
<InstanceV1EngineIcon
v-if="icon && iconPosition === 'prefix'"
@@ -32,12 +32,14 @@ const props = withDefaults(
tag?: string;
link?: boolean;
icon?: boolean;
+ plain?: boolean;
iconPosition?: "prefix" | "suffix";
}>(),
{
tag: "span",
link: true,
icon: true,
+ plain: false,
iconPosition: "prefix",
}
);
diff --git a/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue b/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue
index b8f29f22be..6dc436514c 100644
--- a/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue
+++ b/frontend/src/components/v2/Model/ProductionEnvironmentV1Icon.vue
@@ -1,12 +1,5 @@
<template>
- <NTooltip
- v-if="enabled"
- :disabled="!tooltip"
- :delay="0"
- :show-arrow="false"
- :animated="false"
- placement="top-start"
- >
+ <NTooltip v-if="enabled" :disabled="!tooltip" placement="top">
<template #trigger>
<heroicons-solid:shield-exclamation
class="text-control inline-block"
diff --git a/frontend/src/grpcweb/index.ts b/frontend/src/grpcweb/index.ts
index 5e78fc36fd..18b511ee54 100644
--- a/frontend/src/grpcweb/index.ts
+++ b/frontend/src/grpcweb/index.ts
@@ -30,6 +30,7 @@ import { LoggingServiceDefinition } from "@/types/proto/v1/logging_service";
import { BookmarkServiceDefinition } from "@/types/proto/v1/bookmark_service";
import { InboxServiceDefinition } from "@/types/proto/v1/inbox_service";
import { AnomalyServiceDefinition } from "@/types/proto/v1/anomaly_service";
+import { RolloutServiceDefinition } from "@/types/proto/v1/rollout_service";
import { SchemaDesignServiceDefinition } from "@/types/proto/v1/schema_design_service";
// Create each grpc service client.
@@ -127,6 +128,11 @@ export const issueServiceClient = clientFactory.create(
channel
);
+export const rolloutServiceClient = clientFactory.create(
+ RolloutServiceDefinition,
+ channel
+);
+
export const sqlServiceClient = clientFactory.create(
SQLServiceDefinition,
channel
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 623f05f82a..5f034cf450 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -261,7 +261,8 @@
"warehouse": "Warehouse",
"schedule": "Schedule",
"state": "State",
- "condition": "Condition"
+ "condition": "Condition",
+ "search-user": "Search user"
},
"error-page": {
"go-back-home": "Go back home"
@@ -358,7 +359,13 @@
"execution-time": "Execution time",
"run-checks": "Run checks",
"run-checks-in-current-stage": "Run checks in current stage",
- "action-failed-in-current-stage": "{action} failed tasks in current stage"
+ "database-create": {
+ "pending": "(pending create)",
+ "created": "(created)"
+ },
+ "action-failed-in-current-stage": "{action} failed tasks in current stage",
+ "action-all-tasks-in-current-stage": "{action} all tasks in current stage",
+ "cancel-task": "Cancel task | Cancel tasks"
},
"banner": {
"update-license": "Update license",
@@ -822,7 +829,17 @@
"export-method": "Export method",
"please-select-database-first": "Please select database first"
},
- "review-sent-back": "Review sent back"
+ "review-sent-back": "Review sent back",
+ "update-statement": {
+ "self": "Update {type}",
+ "apply-current-change-to": "Apply current change to",
+ "target": {
+ "selected-task": "Selected task",
+ "selected-stage": "Selected stage",
+ "all-tasks": "All tasks"
+ }
+ },
+ "not-editable-legacy-issue": "This issue is not editable because it was created in an old version of Bytebase"
},
"alter-schema": {
"vcs-enabled": "This project has enabled VCS based version control and selecting database below will navigate you to the corresponding Git repository to initiate the change process.",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index ccc32a52f5..30c244bc03 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -260,7 +260,8 @@
"warehouse": "Almacén",
"schedule": "Horario",
"state": "Estado",
- "condition": "Condición"
+ "condition": "Condición",
+ "search-user": "Buscar usuario"
},
"error-page": {
"go-back-home": "Volver al inicio"
@@ -357,7 +358,13 @@
"execution-time": "Tiempo de ejecución",
"run-checks": "Ejecutar comprobaciones",
"run-checks-in-current-stage": "Ejecutar comprobaciones en la etapa actual",
- "action-failed-in-current-stage": "{action} tareas fallidas en la etapa actual"
+ "database-create": {
+ "pending": "(pendiente de crear)",
+ "created": "(creado)"
+ },
+ "action-failed-in-current-stage": "{action} tareas fallidas en la etapa actual",
+ "action-all-tasks-in-current-stage": "{action} todas las tareas en la etapa actual",
+ "cancel-task": "Cancelar tarea | Cancelar tareas"
},
"banner": {
"update-license": "Actualizar licencia",
@@ -820,7 +827,17 @@
"export-method": "Método de exportación",
"please-select-database-first": "Por favor, seleccione primero la base de datos"
},
- "review-sent-back": "Revisión devuelta"
+ "review-sent-back": "Revisión devuelta",
+ "update-statement": {
+ "self": "Actualizar {type}",
+ "apply-current-change-to": "Aplicar el cambio actual a",
+ "target": {
+ "selected-task": "Tarea seleccionada",
+ "selected-stage": "Etapa seleccionada",
+ "all-tasks": "Todas las tareas"
+ }
+ },
+ "not-editable-legacy-issue": "Este problema no es editable porque se creó en una versión anterior de Bytebase"
},
"alter-schema": {
"vcs-enabled": "Este proyecto ha habilitado el control de versiones basado en VCS y seleccionar la base de datos a continuación lo llevará al repositorio Git correspondiente para iniciar el proceso de cambio.",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index a37a1f2cca..8b07d0f49b 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -257,7 +257,8 @@
"warehouse": "仓库",
"schedule": "计划",
"state": "状态",
- "condition": "条件"
+ "condition": "条件",
+ "search-user": "搜索用户"
},
"error-page": {
"go-back-home": "回到主页"
@@ -354,7 +355,13 @@
"execution-time": "执行时间",
"run-checks": "运行检查",
"run-checks-in-current-stage": "运行当前阶段的所有检查",
- "action-failed-in-current-stage": "{action}当前阶段失败的任务"
+ "database-create": {
+ "pending": "(待创建)",
+ "created": "(已创建)"
+ },
+ "action-failed-in-current-stage": "{action}当前阶段失败的任务",
+ "action-all-tasks-in-current-stage": "{action}当前阶段的所有任务",
+ "cancel-task": "取消任务"
},
"banner": {
"update-license": "更新证书",
@@ -693,7 +700,7 @@
"action-to-stage": "{action}阶段({n}个任务)"
},
"dropdown": {
- "resolve": "解决",
+ "resolve": "解决工单",
"cancel": "取消工单",
"reopen": "重开"
},
@@ -818,7 +825,17 @@
"export-method": "导出方式",
"please-select-database-first": "请先选择数据库"
},
- "review-sent-back": "审核被退回"
+ "review-sent-back": "审核被退回",
+ "update-statement": {
+ "self": "更新{type}",
+ "apply-current-change-to": "应用当前修改到",
+ "target": {
+ "selected-task": "选中的任务",
+ "selected-stage": "选中的阶段",
+ "all-tasks": "所有任务"
+ }
+ },
+ "not-editable-legacy-issue": "这个工单不可编辑,因为它是在旧版本的 Bytebase 中创建的。"
},
"alter-schema": {
"vcs-enabled": "该项目开启了基于 VCS 的版本管理,选择下面的数据库会将您导航到相应的 Git 仓库以发起变更流程。",
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 97fbe0cbef..88720e6ec7 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -29,7 +29,7 @@ import {
idFromSlug,
sheetNameFromSlug,
isOwnerOfProjectV1,
- extractChangeHistoryUID,
+ uidFromSlug,
} from "@/utils";
import Signin from "@/views/auth/Signin.vue";
import Signup from "@/views/auth/Signup.vue";
@@ -901,7 +901,7 @@ const routes: Array<RouteRecordRaw> = [
meta: {
title: (route) => {
const parent = `instances/${route.params.instance}/databases/${route.params.database}`;
- const uid = extractChangeHistoryUID(
+ const uid = uidFromSlug(
route.params.changeHistorySlug as string
);
const name = `${parent}/changeHistories/${uid}`;
@@ -952,7 +952,8 @@ const routes: Array<RouteRecordRaw> = [
overrideTitle: true,
},
components: {
- content: () => import("../views/IssueDetail.vue"),
+ content: () =>
+ import("../views/IssueDetailCompatibilityLayer.vue"),
leftSidebar: DashboardSidebar,
},
props: { content: true },
@@ -1329,7 +1330,7 @@ router.beforeEach((to, from, next) => {
if (to.name === "workspace.database.history.detail") {
const parent = `instances/${to.params.instance}/databases/${to.params.database}`;
- const uid = extractChangeHistoryUID(to.params.changeHistorySlug as string);
+ const uid = uidFromSlug(to.params.changeHistorySlug as string);
Promise.all([
useDatabaseV1Store().getOrFetchDatabaseByName(parent),
useChangeHistoryStore().fetchChangeHistory({
diff --git a/frontend/src/store/modules/v1/activity.ts b/frontend/src/store/modules/v1/activity.ts
index e7ef84cdf1..f33575d0ec 100644
--- a/frontend/src/store/modules/v1/activity.ts
+++ b/frontend/src/store/modules/v1/activity.ts
@@ -7,9 +7,10 @@ import { loggingServiceClient } from "@/grpcweb";
import {
IdType,
FindActivityMessage,
- Issue,
+ Issue as LegacyIssue,
UNKNOWN_ID,
EMPTY_ID,
+ ComposedIssue,
} from "@/types";
import { userNamePrefix, getLogId, logNamePrefix } from "./common";
import {
@@ -19,7 +20,11 @@ import {
logEntity_ActionToJSON,
logEntity_LevelToJSON,
} from "@/types/proto/v1/logging_service";
-import { isDatabaseRelatedIssueType } from "@/utils";
+import {
+ isDatabaseRelatedIssue,
+ isDatabaseRelatedIssueType,
+ extractRolloutUID,
+} from "@/utils";
import { useIssueStore } from "../issue";
import { useCurrentUserV1 } from "../auth";
@@ -60,6 +65,7 @@ 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) => {
const resp = await loggingServiceClient.listLogs({
@@ -76,7 +82,7 @@ export const useActivityV1Store = defineStore("activity_v1", () => {
return activityListByIssue.get(issueId) || [];
};
- const fetchActivityListForIssue = async (issue: Issue) => {
+ const fetchActivityListForIssue = async (issue: LegacyIssue) => {
const requests = [
fetchActivityList({
resource: `issues/${issue.id}`,
@@ -110,6 +116,42 @@ export const useActivityV1Store = defineStore("activity_v1", () => {
return mergedList;
};
+ const getActivityListByIssueV1 = (uid: string): LogEntity[] => {
+ return activityListByIssueV1.get(uid) || [];
+ };
+ const fetchActivityListForIssueV1 = async (issue: ComposedIssue) => {
+ const requests = [
+ fetchActivityList({
+ resource: `issues/${issue.uid}`,
+ order: "asc",
+ }).then((resp) => resp.logEntities),
+ ];
+ if (isDatabaseRelatedIssue(issue) && issue.rollout) {
+ const pipelineUID = extractRolloutUID(issue.rollout);
+ requests.push(
+ fetchActivityList({
+ resource: `pipelines/${pipelineUID}`,
+ order: "asc",
+ }).then((resp) => resp.logEntities)
+ );
+ } else {
+ requests.push(Promise.resolve([]));
+ }
+
+ const [listForIssue, listForPipeline] = await Promise.all(requests);
+ const mergedList = [...listForIssue, ...listForPipeline];
+ mergedList.sort((a, b) => {
+ if (a.createTime !== b.createTime) {
+ return (a.createTime?.getTime() ?? 0) - (b.createTime?.getTime() ?? 0);
+ }
+
+ return getLogId(a.name) - getLogId(b.name);
+ });
+
+ activityListByIssueV1.set(issue.uid, mergedList);
+ return mergedList;
+ };
+
const fetchActivityListByIssueId = async (issueId: IdType) => {
const issue = useIssueStore().getIssueById(issueId);
if (issue.id === UNKNOWN_ID) {
@@ -153,10 +195,12 @@ export const useActivityV1Store = defineStore("activity_v1", () => {
return {
fetchActivityList,
fetchActivityListForIssue,
+ fetchActivityListForIssueV1,
fetchActivityListByIssueId,
fetchActivityListForQueryHistory,
fetchActivityByUID,
getActivityListByIssue,
+ getActivityListByIssueV1,
getResourceId,
};
});
diff --git a/frontend/src/store/modules/v1/experimental-issue.ts b/frontend/src/store/modules/v1/experimental-issue.ts
new file mode 100644
index 0000000000..e58ec9244c
--- /dev/null
+++ b/frontend/src/store/modules/v1/experimental-issue.ts
@@ -0,0 +1,118 @@
+import { issueServiceClient, rolloutServiceClient } from "@/grpcweb";
+import {
+ ComposedIssue,
+ emptyIssue,
+ emptyRollout,
+ EMPTY_ID,
+ EMPTY_ISSUE_NAME,
+ EMPTY_ROLLOUT_NAME,
+ unknownIssue,
+ UNKNOWN_ID,
+ UNKNOWN_ISSUE_NAME,
+} from "@/types";
+import { extractProjectResourceName } from "@/utils";
+import { useProjectV1Store } from "./project";
+
+export const experimentalFetchIssueByUID = async (uid: string) => {
+ if (uid === "undefined") {
+ console.warn("undefined issue uid");
+ return unknownIssue();
+ }
+
+ if (uid === String(EMPTY_ID)) return emptyIssue();
+ if (uid === String(UNKNOWN_ID)) return unknownIssue();
+
+ const rawIssue = await issueServiceClient.getIssue({
+ name: `projects/-/issues/${uid}`,
+ });
+
+ const project = `projects/${extractProjectResourceName(rawIssue.name)}`;
+ const projectEntity = await useProjectV1Store().getOrFetchProjectByName(
+ project
+ );
+
+ const issue: ComposedIssue = {
+ ...rawIssue,
+ planEntity: undefined,
+ planCheckRunList: [],
+ rolloutEntity: emptyRollout(),
+ rolloutTaskRunList: [],
+ project,
+ projectEntity,
+ };
+
+ if (issue.rollout) {
+ issue.rolloutEntity = await rolloutServiceClient.getRollout({
+ name: issue.rollout,
+ });
+ const { taskRuns } = await rolloutServiceClient.listTaskRuns({
+ parent: `${issue.rollout}/stages/-/tasks/-`,
+ pageSize: 1000, // MAX
+ });
+ issue.rolloutTaskRunList = taskRuns;
+ }
+ if (issue.plan) {
+ const plan = await rolloutServiceClient.getPlan({
+ name: issue.plan,
+ });
+ issue.planEntity = plan;
+ const { planCheckRuns } = await rolloutServiceClient.listPlanCheckRuns({
+ parent: plan.name,
+ });
+ issue.planCheckRunList = planCheckRuns;
+ }
+
+ await new Promise((r) => setTimeout(r, 500));
+
+ return issue;
+};
+
+export const experimentalFetchIssueByName = async (name: string) => {
+ if (name === EMPTY_ISSUE_NAME) return emptyIssue();
+ if (name === UNKNOWN_ISSUE_NAME) return unknownIssue();
+
+ const rawIssue = await issueServiceClient.getIssue({
+ name,
+ });
+
+ const project = `projects/${extractProjectResourceName(rawIssue.name)}`;
+ const projectEntity = await useProjectV1Store().getOrFetchProjectByName(
+ project
+ );
+
+ const issue: ComposedIssue = {
+ ...rawIssue,
+ planEntity: undefined,
+ planCheckRunList: [],
+ rollout: EMPTY_ROLLOUT_NAME,
+ rolloutEntity: emptyRollout(),
+ rolloutTaskRunList: [],
+ project,
+ projectEntity,
+ };
+
+ if (issue.rollout) {
+ issue.rolloutEntity = await rolloutServiceClient.getRollout({
+ name: issue.rollout,
+ });
+ const { taskRuns } = await rolloutServiceClient.listTaskRuns({
+ parent: `${issue.rollout}/stages/-/tasks/-`,
+ pageSize: 1000, // MAX
+ });
+ issue.rolloutTaskRunList = taskRuns;
+ }
+ if (issue.plan) {
+ const plan = await rolloutServiceClient.getPlan({
+ name: issue.plan,
+ });
+ issue.planEntity = plan;
+ const { planCheckRuns } = await rolloutServiceClient.listPlanCheckRuns({
+ parent: plan.name,
+ });
+ issue.planCheckRunList = planCheckRuns;
+ }
+
+ await new Promise((r) => setTimeout(r, 500));
+
+ return issue;
+};
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index 91204d3e8b..2da9b50b7c 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -11,6 +11,7 @@ export * from "./policy";
export * from "./setting";
export * from "./instance";
export * from "./issue";
+export * from "./experimental-issue";
export * from "./subscription";
export * from "./actuator";
export * from "./sql";
diff --git a/frontend/src/store/modules/v1/issue.ts b/frontend/src/store/modules/v1/issue.ts
index 0646ea3ece..33f0b0d6b7 100644
--- a/frontend/src/store/modules/v1/issue.ts
+++ b/frontend/src/store/modules/v1/issue.ts
@@ -9,6 +9,7 @@ import {
ActivityIssueCommentCreatePayload,
Issue as LegacyIssue,
PresetRoleType,
+ ComposedIssue,
} from "@/types";
import {
Issue,
@@ -98,6 +99,16 @@ export const useIssueV1Store = defineStore("issue_v1", () => {
await setIssueIssue(legacyIssue, issue);
};
+ const regenerateReviewV1 = async (name: string) => {
+ await issueServiceClient.updateIssue({
+ issue: {
+ name,
+ approvalFindingDone: false,
+ },
+ updateMask: ["approval_finding_done"],
+ });
+ };
+
const createIssueComment = async ({
issueId,
comment,
@@ -144,6 +155,7 @@ export const useIssueV1Store = defineStore("issue_v1", () => {
rejectIssue,
requestIssue,
regenerateReview,
+ regenerateReviewV1,
createIssueComment,
updateIssueComment,
};
@@ -245,3 +257,71 @@ export const candidatesOfApprovalStep = (
return uniq(candidates.map((user) => user.name));
};
+
+export const candidatesOfApprovalStepV1 = (
+ issue: ComposedIssue,
+ step: ApprovalStep
+) => {
+ const workspaceMemberList = useUserStore().activeUserList.filter(
+ (user) => user.userType === UserType.USER
+ );
+ const project = issue.projectEntity;
+ 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 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));
+};
diff --git a/frontend/src/store/modules/v1/sheet.ts b/frontend/src/store/modules/v1/sheet.ts
index 563776b6ff..3bae628e4a 100644
--- a/frontend/src/store/modules/v1/sheet.ts
+++ b/frontend/src/store/modules/v1/sheet.ts
@@ -1,18 +1,18 @@
import { defineStore } from "pinia";
-import { computed, ref, unref, watchEffect } from "vue";
+import { computed, ref, unref, watch, watchEffect } from "vue";
import { isEqual, isUndefined } from "lodash-es";
import { sheetServiceClient } from "@/grpcweb";
+import { getUserEmailFromIdentifier } from "./common";
+import { extractSheetUID, getSheetStatement, isSheetReadableV1 } from "@/utils";
import {
Sheet,
SheetOrganizer,
Sheet_Source,
} from "@/types/proto/v1/sheet_service";
-import { extractSheetUID, getSheetStatement, isSheetReadableV1 } from "@/utils";
import { UNKNOWN_ID, MaybeRef } from "@/types";
import { useCurrentUserV1 } from "../auth";
import { useTabStore } from "../tab";
-import { getUserEmailFromIdentifier } from "./common";
const REQUEST_CACHE_BY_UID = new Map<
string /* uid */,
@@ -85,6 +85,7 @@ export const useSheetV1Store = defineStore("sheet_v1", () => {
const sheet = await sheetServiceClient.getSheet({
name,
});
+
setSheetList([sheet]);
return sheet;
} catch {
@@ -346,3 +347,23 @@ export const useSheetStatementByUID = (uid: MaybeRef<string>) => {
return getSheetStatement(sheet);
});
};
+
+export const useSheetByName = (name: MaybeRef<string>) => {
+ const store = useSheetV1Store();
+ const ready = ref(false);
+ const sheet = computed(() => store.getSheetByName(unref(name)));
+ watch(
+ () => unref(name),
+ (name) => {
+ if (!name) return;
+ if (extractSheetUID(name) === String(UNKNOWN_ID)) return;
+
+ ready.value = false;
+ store.getOrFetchSheetByName(name).finally(() => {
+ ready.value = true;
+ });
+ },
+ { immediate: true }
+ );
+ return { ready, sheet };
+};
diff --git a/frontend/src/types/review.ts b/frontend/src/types/review.ts
index 2a8cd2536a..c244bb81c1 100644
--- a/frontend/src/types/review.ts
+++ b/frontend/src/types/review.ts
@@ -1,5 +1,5 @@
import type { User } from "./proto/v1/auth_service";
-import type {
+import {
ApprovalStep,
ApprovalTemplate,
Issue_Approver,
@@ -22,3 +22,11 @@ export type WrappedReviewStep = {
approver: User | undefined;
candidates: User[];
};
+
+export const emptyFlow = (): ReviewFlow => {
+ return {
+ template: ApprovalTemplate.fromJSON({}),
+ approvers: [],
+ currentStepIndex: -1,
+ };
+};
diff --git a/frontend/src/types/v1/index.ts b/frontend/src/types/v1/index.ts
index 463d461287..b94a79778e 100644
--- a/frontend/src/types/v1/index.ts
+++ b/frontend/src/types/v1/index.ts
@@ -9,3 +9,4 @@ export * from "./user";
export * from "./repository";
export * from "./sql";
export * from "./webTerminal";
+export * from "./issue";
diff --git a/frontend/src/types/v1/issue/index.ts b/frontend/src/types/v1/issue/index.ts
new file mode 100644
index 0000000000..d85c62674e
--- /dev/null
+++ b/frontend/src/types/v1/issue/index.ts
@@ -0,0 +1,2 @@
+export * from "./issue";
+export * from "./rollout";
diff --git a/frontend/src/types/v1/issue/issue.ts b/frontend/src/types/v1/issue/issue.ts
new file mode 100644
index 0000000000..b6df55b6b5
--- /dev/null
+++ b/frontend/src/types/v1/issue/issue.ts
@@ -0,0 +1,70 @@
+import { EMPTY_ID, UNKNOWN_ID } from "../../const";
+import { Issue, Issue_Type } from "../../proto/v1/issue_service";
+import {
+ Plan,
+ PlanCheckRun,
+ Rollout,
+ TaskRun,
+} from "../../proto/v1/rollout_service";
+import {
+ ComposedProject,
+ EMPTY_PROJECT_NAME,
+ UNKNOWN_PROJECT_NAME,
+ emptyProject,
+ unknownProject,
+} from "../project";
+import {
+ EMPTY_ROLLOUT_NAME,
+ UNKNOWN_ROLLOUT_NAME,
+ emptyRollout,
+ unknownRollout,
+} from "./rollout";
+
+export interface ComposedIssue extends Issue {
+ planEntity: Plan | undefined;
+ planCheckRunList: PlanCheckRun[];
+ rolloutEntity: Rollout;
+ rolloutTaskRunList: TaskRun[];
+ project: string;
+ projectEntity: ComposedProject;
+}
+
+export const ESTABLISH_BASELINE_SQL =
+ "/* Establish baseline using current schema. This SQL won't be applied to the database. */";
+
+export const EMPTY_ISSUE_NAME = `projects/${EMPTY_ID}/issues/${EMPTY_ID}`;
+export const UNKNOWN_ISSUE_NAME = `projects/${UNKNOWN_ID}/issues/${UNKNOWN_ID}`;
+
+export const emptyIssue = (): ComposedIssue => {
+ return {
+ ...Issue.fromJSON({
+ name: EMPTY_ISSUE_NAME,
+ rollout: EMPTY_ROLLOUT_NAME,
+ uid: String(EMPTY_ID),
+ type: Issue_Type.DATABASE_CHANGE,
+ }),
+ planEntity: undefined,
+ planCheckRunList: [],
+ rolloutEntity: emptyRollout(),
+ rolloutTaskRunList: [],
+ project: EMPTY_PROJECT_NAME,
+ projectEntity: emptyProject(),
+ };
+};
+
+export const unknownIssue = (): ComposedIssue => {
+ return {
+ ...Issue.fromJSON({
+ name: UNKNOWN_ISSUE_NAME,
+ rollout: UNKNOWN_ROLLOUT_NAME,
+ uid: String(UNKNOWN_ID),
+ type: Issue_Type.DATABASE_CHANGE,
+ }),
+ planEntity: undefined,
+ planCheckRunList: [],
+ rolloutEntity: unknownRollout(),
+ rolloutTaskRunList: [],
+ project: UNKNOWN_PROJECT_NAME,
+ projectEntity: unknownProject(),
+ };
+};
diff --git a/frontend/src/types/v1/issue/rollout.ts b/frontend/src/types/v1/issue/rollout.ts
new file mode 100644
index 0000000000..c2e7c63798
--- /dev/null
+++ b/frontend/src/types/v1/issue/rollout.ts
@@ -0,0 +1,77 @@
+import { EMPTY_ID, UNKNOWN_ID } from "@/types/const";
+import {
+ Rollout,
+ Stage,
+ Task,
+ Task_Type,
+} from "@/types/proto/v1/rollout_service";
+import {
+ EMPTY_ENVIRONMENT_NAME,
+ UNKNOWN_ENVIRONMENT_NAME,
+} from "../environment";
+
+export const EMPTY_ROLLOUT_NAME = `projects/${EMPTY_ID}/rollouts/${EMPTY_ID}`;
+export const UNKNOWN_ROLLOUT_NAME = `projects/${UNKNOWN_ID}/rollouts/${UNKNOWN_ID}`;
+export const emptyRollout = () => {
+ return Rollout.fromJSON({
+ name: EMPTY_ROLLOUT_NAME,
+ uid: String(EMPTY_ID),
+ });
+};
+export const unknownRollout = () => {
+ return Rollout.fromJSON({
+ name: UNKNOWN_ROLLOUT_NAME,
+ uid: String(UNKNOWN_ID),
+ });
+};
+
+export const EMPTY_STAGE_NAME = `${EMPTY_ROLLOUT_NAME}/stages/${EMPTY_ID}`;
+export const UNKNOWN_STAGE_NAME = `${UNKNOWN_ROLLOUT_NAME}/stages/${UNKNOWN_ID}`;
+export const emptyStage = () => {
+ return Stage.fromJSON({
+ name: EMPTY_STAGE_NAME,
+ uid: String(EMPTY_ID),
+ environment: EMPTY_ENVIRONMENT_NAME,
+ title: "",
+ });
+};
+export const unknownStage = () => {
+ return Stage.fromJSON({
+ name: UNKNOWN_STAGE_NAME,
+ uid: String(UNKNOWN_ID),
+ environment: UNKNOWN_ENVIRONMENT_NAME,
+ title: "<<Unknown stage>>",
+ });
+};
+
+export const EMPTY_TASK_NAME = `${EMPTY_STAGE_NAME}/tasks/${EMPTY_ID}`;
+export const UNKNOWN_TASK_NAME = `${UNKNOWN_STAGE_NAME}/tasks/${UNKNOWN_ID}`;
+export const emptyTask = () => {
+ return Task.fromJSON({
+ name: EMPTY_TASK_NAME,
+ uid: String(EMPTY_ID),
+ title: "",
+ });
+};
+export const unknownTask = () => {
+ return Task.fromJSON({
+ name: UNKNOWN_TASK_NAME,
+ uid: String(UNKNOWN_ID),
+ title: "<<Unknown task>>",
+ });
+};
+
+export const TaskTypeListWithStatement: Task_Type[] = [
+ Task_Type.GENERAL,
+ Task_Type.DATABASE_CREATE,
+ Task_Type.DATABASE_DATA_UPDATE,
+ Task_Type.DATABASE_SCHEMA_BASELINE,
+ Task_Type.DATABASE_SCHEMA_UPDATE,
+ Task_Type.DATABASE_SCHEMA_UPDATE_SDL,
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC,
+];
+
+export const TaskTypeListWithProgress: Task_Type[] = [
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC,
+ Task_Type.DATABASE_RESTORE_RESTORE,
+];
diff --git a/frontend/src/utils/activity.ts b/frontend/src/utils/activity.ts
index 5ee1cfe571..2949d01d25 100644
--- a/frontend/src/utils/activity.ts
+++ b/frontend/src/utils/activity.ts
@@ -39,10 +39,10 @@ export function issueActivityActionSentence(
if (update.oldValue && update.newValue) {
const oldName = (
userStore.getUserById(String(update.oldValue)) ?? unknownUser()
- ).name;
+ ).title;
const newName = (
userStore.getUserById(String(update.newValue)) ?? unknownUser()
- ).name;
+ ).title;
return [
"activity.sentence.reassigned-issue",
{
@@ -53,7 +53,7 @@ export function issueActivityActionSentence(
} else if (!update.oldValue && update.newValue) {
const newName = (
userStore.getUserById(String(update.newValue)) ?? unknownUser()
- ).name;
+ ).title;
return [
"activity.sentence.assigned-issue",
{
@@ -63,7 +63,7 @@ export function issueActivityActionSentence(
} else if (update.oldValue && !update.newValue) {
const oldName = (
userStore.getUserById(String(update.oldValue)) ?? unknownUser()
- ).name;
+ ).title;
return [
"activity.sentence.unassigned-issue",
{
diff --git a/frontend/src/utils/collections.ts b/frontend/src/utils/collections.ts
new file mode 100644
index 0000000000..1e69384466
--- /dev/null
+++ b/frontend/src/utils/collections.ts
@@ -0,0 +1,12 @@
+export const groupBy = <T, K>(
+ array: T[],
+ keyOf: (item: T) => K
+): Map<K, T[]> => {
+ return array.reduce((map, item) => {
+ const key = keyOf(item);
+ const list = map.get(key) ?? map.set(key, []).get(key)!;
+ list.push(item);
+
+ return map;
+ }, new Map<K, T[]>());
+};
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 367d268b1b..8b823b5aa3 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -1,3 +1,4 @@
+export * from "./collections";
export * from "./activity";
export * from "./database";
export * from "./environment";
diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.ts
index de8b6c863a..deb4d68b4b 100644
--- a/frontend/src/utils/slug.ts
+++ b/frontend/src/utils/slug.ts
@@ -20,11 +20,25 @@ import {
getVCSUid,
} from "@/store/modules/v1/common";
+export const indexOrUIDFromSlug = (slug: string): number => {
+ const parts = slug.split("-");
+ const indexOrUID = parseInt(parts[parts.length - 1], 10);
+ if (Number.isNaN(indexOrUID) || indexOrUID < 0) {
+ return -1;
+ }
+ return indexOrUID;
+};
+
export function idFromSlug(slug: string): IdType {
const parts = slug.split("-");
return parseInt(parts[parts.length - 1]);
}
+export const uidFromSlug = (slug: string): string => {
+ const parts = slug.split("-");
+ return parts[parts.length - 1];
+};
+
export function sheetNameFromSlug(slug: string): string {
const parts = slug.split("-");
return `${projectNamePrefix}${parts
diff --git a/frontend/src/utils/v1/changeHistory.ts b/frontend/src/utils/v1/changeHistory.ts
index d305241977..96e25035ae 100644
--- a/frontend/src/utils/v1/changeHistory.ts
+++ b/frontend/src/utils/v1/changeHistory.ts
@@ -1,14 +1,14 @@
import slug from "slug";
-import { UNKNOWN_ID } from "@/types";
import { ChangeHistory } from "@/types/proto/v1/database_service";
import { extractDatabaseResourceName } from "./database";
import { useDBSchemaV1Store, useDatabaseV1Store } from "@/store";
import { isUndefined, orderBy } from "lodash-es";
import { AffectedTable } from "@/types/changeHistory";
-export const extractChangeHistoryUID = (changeHistorySlug: string) => {
- const parts = changeHistorySlug.split("-");
- return parts[parts.length - 1] ?? String(UNKNOWN_ID);
+export const extractChangeHistoryUID = (name: string) => {
+ const pattern = /(?:^|\/)(?:changeHistories|migrations)\/([^/]+)(?:$|\/)/;
+ const matches = name.match(pattern);
+ return matches?.[1] ?? "";
};
export const extractDatabaseNameAndChangeHistoryUID = (
diff --git a/frontend/src/utils/v1/issue.ts b/frontend/src/utils/v1/issue.ts
deleted file mode 100644
index 7ab37fa3c3..0000000000
--- a/frontend/src/utils/v1/issue.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export const extractIssueId = (name: string) => {
- const pattern = /(?:^|\/)issues\/(\d+)(?:$|\/)/;
- const matches = name.match(pattern);
- return matches?.[1] ?? "";
-};
diff --git a/frontend/src/utils/v1/issue/index.ts b/frontend/src/utils/v1/issue/index.ts
new file mode 100644
index 0000000000..d85c62674e
--- /dev/null
+++ b/frontend/src/utils/v1/issue/index.ts
@@ -0,0 +1,2 @@
+export * from "./issue";
+export * from "./rollout";
diff --git a/frontend/src/utils/v1/issue/issue.ts b/frontend/src/utils/v1/issue/issue.ts
new file mode 100644
index 0000000000..f7a450859d
--- /dev/null
+++ b/frontend/src/utils/v1/issue/issue.ts
@@ -0,0 +1,43 @@
+import slug from "slug";
+
+import { ComposedIssue, EMPTY_ROLLOUT_NAME } from "@/types";
+import { Plan, Rollout, Task_Type } from "@/types/proto/v1/rollout_service";
+
+export const issueV1Slug = (issue: ComposedIssue) => {
+ return [slug(issue.title), issue.uid].join("-");
+};
+
+export const extractIssueUID = (name: string) => {
+ const pattern = /(?:^|\/)issues\/(\d+)(?:$|\/)/;
+ const matches = name.match(pattern);
+ return matches?.[1] ?? "";
+};
+
+export const isGrantRequestIssue = (issue: ComposedIssue): boolean => {
+ return !issue.rollout || issue.rollout === EMPTY_ROLLOUT_NAME; // TODO
+ // return issueType === "bb.issue.grant.request";
+};
+
+export const flattenTaskV1List = (rollout: Rollout) => {
+ return rollout.stages.flatMap((stage) => stage.tasks);
+};
+
+export const flattenSpecList = (plan: Plan) => {
+ return plan.steps.flatMap((step) => step.specs);
+};
+
+export const isDatabaseRelatedIssue = (issue: ComposedIssue): boolean => {
+ return flattenTaskV1List(issue.rolloutEntity).some((task) => {
+ const DATABASE_RELATED_TASK_TYPE_LIST = [
+ Task_Type.DATABASE_CREATE,
+ Task_Type.DATABASE_SCHEMA_BASELINE,
+ Task_Type.DATABASE_SCHEMA_UPDATE,
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_SYNC,
+ Task_Type.DATABASE_SCHEMA_UPDATE_GHOST_CUTOVER,
+ Task_Type.DATABASE_SCHEMA_UPDATE_SDL,
+ Task_Type.DATABASE_DATA_UPDATE,
+ Task_Type.DATABASE_BACKUP,
+ ];
+ return DATABASE_RELATED_TASK_TYPE_LIST.includes(task.type);
+ });
+};
diff --git a/frontend/src/utils/v1/issue/rollout.ts b/frontend/src/utils/v1/issue/rollout.ts
new file mode 100644
index 0000000000..c5d4bce2a1
--- /dev/null
+++ b/frontend/src/utils/v1/issue/rollout.ts
@@ -0,0 +1,144 @@
+import slug from "slug";
+import { last } from "lodash-es";
+import { stringify } from "qs";
+
+import {
+ EMPTY_TASK_NAME,
+ emptyStage,
+ emptyTask,
+ unknownTask,
+ unknownStage,
+ ComposedIssue,
+} from "@/types";
+import {
+ Rollout,
+ Stage,
+ Task,
+ Task_Status,
+} from "@/types/proto/v1/rollout_service";
+import { flattenTaskV1List, issueV1Slug } from "./issue";
+
+export const extractRolloutUID = (name: string) => {
+ const pattern = /(?:^|\/)rollouts\/([^/]+)(?:$|\/)/;
+ const matches = name.match(pattern);
+ return matches?.[1] ?? "";
+};
+
+export const extractTaskUID = (name: string) => {
+ const pattern = /(?:^|\/)tasks\/([^/]+)(?:$|\/)/;
+ const matches = name.match(pattern);
+ return matches?.[1] ?? "";
+};
+
+export const stageV1Slug = (stage: Stage): string => {
+ return [slug(stage.title), stage.uid].join("-");
+};
+
+export const taskV1Slug = (task: Task): string => {
+ return [slug(task.title), task.uid].join("-");
+};
+
+export const activeTaskInTaskList = (tasks: Task[]): Task => {
+ for (const task of tasks) {
+ if (
+ task.status === Task_Status.NOT_STARTED ||
+ task.status === Task_Status.PENDING ||
+ task.status === Task_Status.RUNNING ||
+ // "FAILED" is also a transient task status, which requires user
+ // to take further action (e.g. Skip, Retry)
+ task.status === Task_Status.FAILED ||
+ // "CANCELED" tasks can be "RESTART"ed
+ // So it should be an "active" task
+ task.status === Task_Status.CANCELED
+ ) {
+ return task;
+ }
+ }
+
+ return last(tasks) ?? emptyTask();
+};
+
+export const activeTaskInStageV1 = (stage: Stage): Task => {
+ return activeTaskInTaskList(stage.tasks);
+};
+
+export const activeTaskInRollout = (rollout: Rollout): Task => {
+ return activeTaskInTaskList(flattenTaskV1List(rollout));
+};
+
+export const activeStageInRollout = (rollout: Rollout): Stage => {
+ const activeTask = activeTaskInRollout(rollout);
+ if (activeTask.name !== EMPTY_TASK_NAME) {
+ const stage = rollout.stages.find((stage) =>
+ stage.tasks.includes(activeTask)
+ );
+ if (stage) {
+ return stage;
+ }
+ }
+ return emptyStage();
+};
+
+export const findTaskByUID = (
+ rollout: Rollout | undefined,
+ uid: string
+): Task => {
+ for (const stage of rollout?.stages ?? []) {
+ for (const task of stage.tasks) {
+ if (task.uid == uid) {
+ return task;
+ }
+ }
+ }
+ return unknownTask();
+};
+
+export const findStageByUID = (
+ rollout: Rollout | undefined,
+ uid: string
+): Stage => {
+ return (rollout?.stages ?? []).find((s) => s.uid === uid) ?? unknownStage();
+};
+
+export const extractSchemaVersionFromTask = (task: Task): string => {
+ // 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.
+ return (
+ task.databaseDataUpdate?.schemaVersion ??
+ task.databaseSchemaBaseline?.schemaVersion ??
+ task.databaseSchemaUpdate?.schemaVersion ??
+ ""
+ );
+};
+
+export const sheetNameOfTaskV1 = (task: Task): string => {
+ return (
+ task.databaseCreate?.sheet ??
+ task.databaseDataUpdate?.sheet ??
+ task.databaseSchemaUpdate?.sheet ??
+ ""
+ );
+};
+
+export const buildIssueV1LinkWithTask = (
+ issue: ComposedIssue,
+ task: Task,
+ simple = false
+) => {
+ const stage = issue.rolloutEntity.stages.find(
+ (s) => s.tasks.findIndex((t) => t.uid === task.uid) >= 0
+ );
+
+ const issueSlug = simple ? issue.uid : issueV1Slug(issue);
+ const query: Record<string, string> = {};
+ if (stage) {
+ query.stage = simple ? stage.uid : stageV1Slug(stage);
+ }
+ query.task = simple ? task.uid : taskV1Slug(task);
+
+ const querystring = stringify(query);
+ const url = `/issue/${issueSlug}?${querystring}`;
+
+ return url;
+};
diff --git a/frontend/src/views/ChangeHistoryDetail.vue b/frontend/src/views/ChangeHistoryDetail.vue
index fa635af506..0cd478e57f 100644
--- a/frontend/src/views/ChangeHistoryDetail.vue
+++ b/frontend/src/views/ChangeHistoryDetail.vue
@@ -27,10 +27,10 @@
>{{ $t("common.issue") }}&nbsp;-&nbsp;</span
>
<router-link
- :to="`/issue/${extractIssueId(changeHistory.issue)}`"
+ :to="`/issue/${extractIssueUID(changeHistory.issue)}`"
class="normal-link"
>
- {{ extractIssueId(changeHistory.issue) }}
+ {{ extractIssueUID(changeHistory.issue) }}
</router-link>
</dd>
<dt class="sr-only">{{ $t("common.duration") }}</dt>
@@ -277,9 +277,9 @@ import { toClipboard } from "@soerenmartius/vue3-clipboard";
import { CodeDiff } from "v-code-diff";
import {
changeHistoryLink,
- extractChangeHistoryUID,
- extractIssueId,
+ extractIssueUID,
extractUserResourceName,
+ uidFromSlug,
getAffectedTablesOfChangeHistory,
} from "@/utils";
import {
@@ -323,7 +323,7 @@ const changeHistoryParent = computed(() => {
return `instances/${props.instance}/databases/${props.database}`;
});
const changeHistoryUID = computed(() => {
- return extractChangeHistoryUID(props.changeHistorySlug);
+ return uidFromSlug(props.changeHistorySlug);
});
const changeHistoryName = computed(() => {
return `${changeHistoryParent.value}/changeHistories/${changeHistoryUID.value}`;
diff --git a/frontend/src/views/IssueDetailCompatibilityLayer.vue b/frontend/src/views/IssueDetailCompatibilityLayer.vue
new file mode 100644
index 0000000000..7644260472
--- /dev/null
+++ b/frontend/src/views/IssueDetailCompatibilityLayer.vue
@@ -0,0 +1,84 @@
+<template>
+ <div class="w-full h-full relative">
+ <div
+ v-if="state.loading"
+ class="w-full h-full fixed md:absolute inset-0 flex justify-center items-center bg-white/50"
+ >
+ <NSpin />
+ </div>
+ <template v-else>
+ <IssueDetail v-if="state.view === 'OLD'" :issue-slug="issueSlug" />
+ <IssueDetailV1 v-if="state.view === 'NEW'" :issue-slug="issueSlug" />
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, reactive, watch } from "vue";
+import { useRouter } from "vue-router";
+import { useTitle } from "@vueuse/core";
+import { useI18n } from "vue-i18n";
+import { NSpin } from "naive-ui";
+
+import { useActuatorV1Store, useIssueStore } from "@/store";
+import { UNKNOWN_ID } from "@/types";
+import { idFromSlug, isGrantRequestIssueType } from "@/utils";
+import IssueDetail from "./IssueDetail.vue";
+import IssueDetailV1 from "./IssueDetailV1.vue";
+
+const props = defineProps({
+ issueSlug: {
+ required: true,
+ type: String,
+ },
+});
+
+const { t } = useI18n();
+const router = useRouter();
+const actuatorStore = useActuatorV1Store();
+
+const state = reactive({
+ view: "OLD" as "OLD" | "NEW",
+ loading: true,
+});
+const enableNewIssueUI = computed(() => {
+ return !!actuatorStore.serverInfo?.developmentUseV2Scheduler;
+});
+
+watch(
+ [enableNewIssueUI, () => props.issueSlug],
+ async ([enableNewIssueUI, slug]) => {
+ if (!enableNewIssueUI) {
+ state.view = "OLD";
+ state.loading = false;
+ return;
+ }
+
+ if (slug === "new") {
+ state.view = "NEW";
+ state.loading = false;
+ return;
+ } else {
+ const legacyIssue = await useIssueStore().getOrFetchIssueById(
+ idFromSlug(slug)
+ );
+ if (String(legacyIssue.id) === String(UNKNOWN_ID)) {
+ router.replace({
+ name: "error.404",
+ });
+ return;
+ }
+ if (isGrantRequestIssueType(legacyIssue.type)) {
+ state.view = "OLD";
+ state.loading = false;
+ return;
+ }
+ state.view = "NEW";
+ state.loading = false;
+ }
+ },
+ { immediate: true }
+);
+
+useTitle(computed(() => t("common.loading")));
+</script>
diff --git a/frontend/src/views/IssueDetailV1.vue b/frontend/src/views/IssueDetailV1.vue
new file mode 100644
index 0000000000..fa20dccc52
--- /dev/null
+++ b/frontend/src/views/IssueDetailV1.vue
@@ -0,0 +1,84 @@
+<template>
+ <div class="w-full h-full relative">
+ <IssueDetailPage v-if="ready" />
+ <div v-else class="w-full h-full flex flex-col items-center justify-center">
+ <NSpin />
+ </div>
+ </div>
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.multi-tenancy"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+import { useTitle } from "@vueuse/core";
+import { NSpin } from "naive-ui";
+
+import { UNKNOWN_ID } from "@/types";
+import {
+ IssueDetailPage,
+ provideIssueContext,
+ useBaseIssueContext,
+ useInitializeIssue,
+} from "@/components/IssueV1";
+
+interface LocalState {
+ showFeatureModal: boolean;
+}
+
+const props = defineProps({
+ issueSlug: {
+ required: true,
+ type: String,
+ },
+});
+
+const { t } = useI18n();
+
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+});
+
+const issueSlug = computed(() => props.issueSlug);
+
+const { isCreating, issue, isInitializing } = useInitializeIssue(issueSlug);
+const ready = computed(() => {
+ return !isInitializing.value && !!issue.value;
+});
+
+provideIssueContext(
+ {
+ isCreating,
+ issue,
+ ready,
+ ...useBaseIssueContext({
+ isCreating,
+ ready,
+ issue,
+ }),
+ },
+ true /* root */
+);
+
+const documentTitle = computed(() => {
+ if (isCreating.value) {
+ return t("issue.new-issue");
+ } else {
+ if (ready.value && issue.value.uid !== String(UNKNOWN_ID)) {
+ return issue.value.title;
+ }
+ }
+ return t("common.loading");
+});
+useTitle(documentTitle);
+</script>
+
+<style lang="postcss">
+.issue-debug {
+ @apply hidden bg-red-200/50 font-mono text-xs;
+}
+</style>