Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support advanced issue search (#7830)
ecmadaod61c237e372d
diff --git a/frontend/src/bbkit/BBStepBar.vue b/frontend/src/bbkit/BBStepBar.vueindex f10a8086c4..f106a7d0d7 100644--- a/frontend/src/bbkit/BBStepBar.vue+++ b/frontend/src/bbkit/BBStepBar.vue@@ -79,6 +79,7 @@ defineEmits<{const stepClass = (status: BBStepStatus) => {switch (status) {case "PENDING":+ case "NOT_STARTED":return "bg-white border-2 border-control hover:border-control-hover";case "PENDING_ACTIVE":return "bg-white border-2 border-blue-600 text-blue-600 hover:text-blue-700 hover:border-blue-700";diff --git a/frontend/src/bbkit/types.ts b/frontend/src/bbkit/types.tsindex c11349c0cc..57f1db225c 100644--- a/frontend/src/bbkit/types.ts+++ b/frontend/src/bbkit/types.ts@@ -54,6 +54,7 @@ export type BBTabFilterItem = {};export type BBStepStatus =+ | "NOT_STARTED"| "PENDING"| "PENDING_ACTIVE"| "PENDING_APPROVAL"diff --git a/frontend/src/components/AdvancedSearch.vue b/frontend/src/components/AdvancedSearch.vuenew file mode 100644index 0000000000..ffd6d2cad3--- /dev/null+++ b/frontend/src/components/AdvancedSearch.vue@@ -0,0 +1,272 @@+<template>+ <div class="relative" :class="customClass">+ <NInput+ ref="inputRef"+ :value="state.searchText"+ :clearable="!!state.searchText"+ :placeholder="$t('issue.advanced-search')"+ style="width: 100%"+ @update:value="onUpdate($event)"+ @focus="state.showSearchItems = true"+ @blur="onClear"+ @keyup="onKeydown"+ >+ <template #prefix>+ <heroicons-outline:search class="h-4 w-4 text-control-placeholder" />+ </template>+ </NInput>+ <div+ v-if="state.showSearchItems"+ class="absolute z-50 top-full w-full divide-y divide-block-border bg-white shadow-md"+ >+ <div+ v-for="item in searchItems"+ :key="item.keyword"+ class="flex gap-x-3 p-3 items-center cursor-pointer hover:bg-gray-100"+ @mousedown.prevent.stop="+ () => {+ state.showSearchItems = false;+ state.searchKeyword = item.keyword;+ }+ "+ >+ <heroicons-outline:filter class="h-4 w-4 text-control" />+ <span class="text-accent">{{ item.keyword }}</span>+ <span class="text-control-light">{{ item.description }}</span>+ </div>+ </div>+ <div+ v-if="state.searchKeyword && searchOptions.length > 0"+ class="absolute z-50 top-full w-full divide-y divide-block-border bg-white shadow-md"+ >+ <div class="p-3 text-lg text-control-light">+ {{ searchKeyword }}+ </div>+ <div class="max-h-60 overflow-y-auto divide-y divide-block-border">+ <div+ v-for="option in searchOptions"+ :key="option.id"+ class="flex gap-x-3 p-3 items-baseline cursor-pointer hover:bg-gray-100"+ @mousedown.prevent.stop="+ onOptionSelect(state.searchKeyword, option.id)+ "+ >+ <component :is="option.label" class="text-control text-sm" />+ <span class="text-control-light text-xs">{{ option.id }}</span>+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { debounce } from "lodash-es";+import { NInput } from "naive-ui";+import { reactive, computed, h, VNode, onMounted, ref } from "vue";+import GitIcon from "@/components/GitIcon.vue";+import { useProjectV1ListByCurrentUser } from "@/store";+import { Workflow } from "@/types/proto/v1/project_service";+import { projectV1Name } from "@/utils";++type SearchKeyword = "project";++export interface SearchParams {+ query: string;+ scopes: {+ id: SearchKeyword;+ value: string;+ }[];+}++const props = withDefaults(+ defineProps<{+ customClass?: string;+ params?: SearchParams;+ autofocus?: boolean;+ }>(),+ {+ customClass: "",+ params: undefined,+ autofocus: false,+ }+);++const emit = defineEmits<{+ (event: "update", params: SearchParams): void;+}>();++interface LocalState {+ searchText: string;+ showSearchItems: boolean;+ searchKeyword?: SearchKeyword;+}++interface SearchOption {+ id: string;+ label: VNode;+}++interface SearchItem {+ keyword: SearchKeyword;+ description: string;+ options: SearchOption[];+}++const buildSearchTextByParams = (params: SearchParams | undefined): string => {+ const prefix = (params?.scopes ?? [])+ .map((scope) => `${scope.id}:${scope.value}`)+ .join(" ");+ const query = params?.query ?? "";+ if (!prefix && !query) {+ return "";+ }+ return `${prefix} ${query}`;+};++const state = reactive<LocalState>({+ searchText: buildSearchTextByParams(props.params),+ showSearchItems: false,+});+const inputRef = ref<InstanceType<typeof NInput>>();++const { projectList } = useProjectV1ListByCurrentUser();++const searchItems = computed((): SearchItem[] => {+ return [+ {+ keyword: "project",+ description: "Include only issues from this project",+ options: projectList.value.map((proj) => {+ const children: VNode[] = [+ h("span", { innerHTML: projectV1Name(proj) }),+ ];+ if (proj.workflow === Workflow.VCS) {+ children.push(h(GitIcon, { class: "w-5" }));+ }+ return {+ id: proj.name,+ label: h("div", { class: "flex gap-x-2" }, children),+ };+ }),+ },+ ];+});++const searchOptions = computed((): SearchOption[] => {+ const item = searchItems.value.find(+ (item) => item.keyword === state.searchKeyword+ );+ return item?.options ?? [];+});++const searchKeyword = computed(() => {+ if (!state.searchKeyword) {+ return "";+ }+ return `${state.searchKeyword[0].toUpperCase()}${state.searchKeyword.slice(+ 1+ )}`;+});++const onOptionSelect = (keyword: SearchKeyword, id: string) => {+ const search = `${keyword}:${id} ${query.value}`;+ state.searchText = search;+ debouncedUpdate();+ onClear();+};++const onClear = () => {+ state.showSearchItems = false;+ state.searchKeyword = undefined;+};++const debouncedUpdate = debounce(() => {+ emit("update", getSearchParamsByText(state.searchText));+}, 500);++const onUpdate = (value: string) => {+ state.searchText = value;+ debouncedUpdate();+};++const query = computed(() => {+ const sections = state.searchText.split(" ");+ let i = 0;+ while (i < sections.length) {+ const section = sections[i];+ const keyword = section.split(":")[0];+ const exist =+ searchItems.value.findIndex((item) => item.keyword === keyword) >= 0;+ if (!exist) {+ break;+ }+ i++;+ }+ return sections.slice(i).join(" ");+});++const getSearchParamsByText = (text: string): SearchParams => {+ const plainQuery = query.value;+ const scopeText = text.split(` ${plainQuery}`)[0] || "";+ return {+ query: plainQuery,+ scopes: scopeText.split(" ").map((scope) => {+ return {+ id: scope.split(":")[0] as SearchKeyword,+ value: scope.split(":")[1],+ };+ }),+ };+};++onMounted(() => {+ if (props.autofocus) {+ inputRef.value?.inputElRef?.focus();+ }+});++const onKeydown = (e: KeyboardEvent) => {+ if (!inputRef.value || !inputRef.value.inputElRef) {+ return;+ }+ if (!state.searchText) {+ state.showSearchItems = true;+ return;+ }++ const start = inputRef.value.inputElRef.selectionStart ?? -1;+ const end = inputRef.value.inputElRef.selectionEnd ?? -1;+ if (start !== end) {+ onClear();+ return;+ }++ const sections = state.searchText.split(" ");+ let i = 0;+ let len = 0;+ while (i < sections.length) {+ len += sections[i].length;+ if (i < sections.length - 1) {+ len += 1;+ }+ if (len >= start) {+ break;+ }+ i++;+ }+ if (i >= sections.length) {+ onClear();+ return;+ }++ const keyword = sections[i].split(":")[0] as SearchKeyword;+ const existed =+ searchItems.value.findIndex((item) => item.keyword === keyword) >= 0;+ if (!existed) {+ onClear();+ return;+ }++ state.searchKeyword = keyword;+};+</script>diff --git a/frontend/src/components/IssueV1/components/BatchIssueActionsV1.vue b/frontend/src/components/IssueV1/components/BatchIssueActionsV1.vuenew file mode 100644index 0000000000..6227e97192--- /dev/null+++ b/frontend/src/components/IssueV1/components/BatchIssueActionsV1.vue@@ -0,0 +1,254 @@+<template>+ <BBTooltipButton+ type="primary"+ :disabled="!isTransitionApplicableForAllIssues('RESOLVE')"+ tooltip-mode="DISABLED-ONLY"+ @click="startBatchIssueTransition('RESOLVE')"+ >+ {{ $t("issue.batch-transition.resolve") }}+ <template #tooltip>+ <div class="whitespace-nowrap">+ {{+ $t("issue.batch-transition.not-allowed-tips", {+ operation: $t("issue.batch-transition.resolved"),+ })+ }}+ </div>+ </template>+ </BBTooltipButton>++ <BBTooltipButton+ type="normal"+ :disabled="!isTransitionApplicableForAllIssues('CANCEL')"+ tooltip-mode="DISABLED-ONLY"+ @click="startBatchIssueTransition('CANCEL')"+ >+ {{ $t("issue.batch-transition.cancel") }}+ <template #tooltip>+ <div class="whitespace-nowrap">+ {{+ $t("issue.batch-transition.not-allowed-tips", {+ operation: $t("issue.batch-transition.cancelled"),+ })+ }}+ </div>+ </template>+ </BBTooltipButton>++ <BBTooltipButton+ type="normal"+ :disabled="!isTransitionApplicableForAllIssues('REOPEN')"+ tooltip-mode="DISABLED-ONLY"+ @click="startBatchIssueTransition('REOPEN')"+ >+ {{ $t("issue.batch-transition.reopen") }}+ <template #tooltip>+ <div class="whitespace-nowrap">+ {{+ $t("issue.batch-transition.not-allowed-tips", {+ operation: $t("issue.batch-transition.reopened"),+ })+ }}+ </div>+ </template>+ </BBTooltipButton>++ <BBModal+ v-if="state.modal.show"+ :title="state.modal.title"+ class="relative overflow-hidden"+ @close="state.modal.show = false"+ >+ <div+ v-if="state.isRequesting"+ class="absolute inset-0 flex flex-col items-center justify-center bg-white/70"+ >+ <BBSpin />+ <div class="flex items-center textlabel">+ <span>{{ $t("common.updating") }}</span>+ <span v-if="state.stats"+ >({{ state.stats.success }} / {{ state.stats.total }})</span+ >+ </div>+ </div>++ <div>+ <div class="sm:col-span-4 w-112 min-w-full">+ <label for="about" class="textlabel">+ {{ $t("issue.status-transition.form.note") }}+ </label>+ <div class="mt-1">+ <textarea+ ref="commentTextArea"+ v-model="state.modal.comment"+ rows="3"+ class="textarea block w-full resize-none mt-1 text-sm text-control rounded-md whitespace-pre-wrap"+ :placeholder="$t('issue.status-transition.form.placeholder')"+ @input="+ (e) => {+ sizeToFit(e.target as HTMLTextAreaElement);+ }+ "+ @focus="+ (e) => {+ sizeToFit(e.target as HTMLTextAreaElement);+ }+ "+ ></textarea>+ </div>+ </div>+ </div>++ <!-- Update button group -->+ <div class="flex justify-end items-center pt-5">+ <button+ type="button"+ class="btn-normal mt-3 px-4 py-2 sm:mt-0 sm:w-auto"+ @click.prevent="state.modal.show = false"+ >+ {{ $t("common.cancel") }}+ </button>+ <button+ type="button"+ class="ml-3 px-4 py-2"+ :class="state.modal.okButtonClass"+ @click="doBatchIssueTransition(state.modal.transition!)"+ >+ {{ state.modal.okButtonText }}+ </button>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { computed, PropType, reactive } from "vue";+import { useI18n } from "vue-i18n";+import { pushNotification, refreshIssueList, useIssueStore } from "@/store";+import type {+ ComposedIssue,+ IssueStatusPatch,+ IssueStatusTransition,+ IssueStatusTransitionType,+} from "@/types";+import { ISSUE_STATUS_TRANSITION_LIST } from "@/types";+import { extractIssueUID } from "@/utils";+import { calcApplicableIssueStatusTransitionList } from "../logic/transition";++type RequestStats = {+ total: number;+ success: number;+ failed: number;+};++type ModalProps = {+ show: boolean;+ title: string;+ comment: string;+ transition?: IssueStatusTransition;+ okButtonText: string;+ okButtonClass?: string;+};++type LocalState = {+ isRequesting: boolean;+ modal: ModalProps;+ stats?: RequestStats;+};++const props = defineProps({+ issueList: {+ type: Array as PropType<ComposedIssue[]>,+ default: () => [],+ },+});++const state = reactive<LocalState>({+ isRequesting: false,+ modal: {+ show: false,+ title: "",+ comment: "",+ okButtonText: "",+ },+});++const issueStore = useIssueStore();+const { t } = useI18n();++const issueTransitionList = computed(() => {+ return props.issueList.map((issue) => {+ const transitions = calcApplicableIssueStatusTransitionList(issue);+ return { issue, transitions };+ });+});++const isTransitionApplicableForAllIssues = (+ type: IssueStatusTransitionType+): boolean => {+ return issueTransitionList.value.every((item) => {+ return (+ item.transitions.findIndex((transition) => transition.type === type) >= 0+ );+ });+};++const startBatchIssueTransition = (type: IssueStatusTransitionType) => {+ const { modal } = state;+ modal.show = true;+ const transition = ISSUE_STATUS_TRANSITION_LIST.get(type)!;+ modal.transition = transition;+ modal.comment = "";+ modal.okButtonClass = transition.buttonClass;+ modal.okButtonText = t(transition.buttonName);+ modal.title = t("issue.batch-transition.action-n-issues", {+ action: t(`issue.batch-transition.${type.toLowerCase()}`),+ n: props.issueList.length,+ });+};++const doBatchIssueTransition = async (transition: IssueStatusTransition) => {+ const issueStatusPatch: IssueStatusPatch = {+ status: transition.to,+ comment: state.modal.comment,+ };++ const stats = reactive<RequestStats>({+ total: props.issueList.length,+ success: 0,+ failed: 0,+ });++ const doSingleIssueTransition = async (+ issue: ComposedIssue,+ index: number+ ) => {+ const request = issueStore.updateIssueStatus({+ issueId: extractIssueUID(issue.name),+ issueStatusPatch,+ });+ request.then(+ () => stats.success++,+ () => stats.failed+++ );++ return request;+ };++ state.isRequesting = true;+ state.stats = stats;+ try {+ const requestList = props.issueList.map(doSingleIssueTransition);+ await Promise.allSettled(requestList);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("issue.batch-transition.successfully-updated-n-issues", {+ n: stats.success,+ }),+ });+ } finally {+ state.isRequesting = false;+ refreshIssueList();+ }+};+</script>diff --git a/frontend/src/components/IssueV1/components/CurrentApproverV1.vue b/frontend/src/components/IssueV1/components/CurrentApproverV1.vuenew file mode 100644index 0000000000..8e38e788b1--- /dev/null+++ b/frontend/src/components/IssueV1/components/CurrentApproverV1.vue@@ -0,0 +1,53 @@+<template>+ <div class="flex flex-row items-center">+ <template v-if="issue.status !== IssueStatus.OPEN || done">+ <span>-</span>+ </template>+ <template v-else-if="!ready">+ <BBSpin />+ </template>+ <template v-else-if="currentApprover">+ <BBAvatar :size="'SMALL'" :username="currentApprover.title" />+ <span class="ml-2">+ {{ currentApprover.title }}+ </span>+ </template>+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { useWrappedReviewStepsV1 } from "@/components/IssueV1";+import { extractIssueReviewContext } from "@/plugins/issue/logic";+import { useAuthStore } from "@/store";+import { ComposedIssue } from "@/types";+import { IssueStatus } from "@/types/proto/v1/issue_service";++const props = defineProps<{+ issue: ComposedIssue;+}>();++const context = extractIssueReviewContext(+ computed(() => undefined),+ computed(() => props.issue)+);+const { ready, done } = context;+const currentUserName = computed(() => useAuthStore().currentUser.name);++const wrappedSteps = useWrappedReviewStepsV1(props.issue, context);++const currentStep = computed(() => {+ return wrappedSteps.value?.find((step) => step.status === "CURRENT");+});++const currentApprover = computed(() => {+ if (!currentStep.value) return undefined;+ const me = currentStep.value.candidates.find(+ (user) => user.name === currentUserName.value+ );+ // Show currentUser if currentUser is one of the validate approver candidates.+ if (me) return me;+ // Show the first approver candidate otherwise.+ return currentStep.value.candidates[0];+});+</script>diff --git a/frontend/src/components/IssueV1/components/IssueTableV1.vue b/frontend/src/components/IssueV1/components/IssueTableV1.vuenew file mode 100644index 0000000000..5f094a0e66--- /dev/null+++ b/frontend/src/components/IssueV1/components/IssueTableV1.vue@@ -0,0 +1,467 @@+<template>+ <BBTable+ ref="tableRef"+ :column-list="columnList"+ :section-data-source="issueSectionList"+ :show-header="true"+ :custom-header="true"+ :left-bordered="leftBordered"+ :right-bordered="rightBordered"+ :top-bordered="topBordered"+ :bottom-bordered="bottomBordered"+ v-bind="$attrs"+ @click-row="clickIssue"+ >+ <template #header>+ <th+ v-for="(column, index) in columnList"+ :key="index"+ scope="col"+ class="pl-2 first:pl-4 py-2 text-left text-xs font-medium text-gray-500 tracking-wider capitalize"+ :class="[column.center && 'text-center pr-2']"+ >+ <template v-if="index === 0">+ <input+ v-if="issueList.length > 0"+ type="checkbox"+ class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"+ :checked="allSelectionState.checked"+ :indeterminate="allSelectionState.indeterminate"+ @input="+ setAllIssuesSelection(($event.target as HTMLInputElement).checked)+ "+ />+ </template>+ <template v-else>{{ $t(column.title) }}</template>+ </th>+ </template>+ <template #body="{ rowData: issue }: { rowData: ComposedIssue }">+ <BBTableCell+ class="w-[1%]"+ @click.stop="setIssueSelection(issue, !isIssueSelected(issue))"+ >+ <!-- width: 1% means as narrow as possible -->+ <input+ type="checkbox"+ class="ml-2 h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"+ :checked="isIssueSelected(issue)"+ />+ </BBTableCell>+ <BBTableCell class="table-cell w-12">+ <IssueStatusIcon+ :issue-status="issue.status"+ :task-status="issueTaskStatus(issue)"+ />+ </BBTableCell>+ <BBTableCell class="table-cell">+ <div class="flex items-center">+ <div class="whitespace-nowrap mr-2 text-control">+ <template v-if="mode == 'ALL'">+ {{ issue.projectEntity.key }}-{{ issue.uid }}+ </template>+ <template v-else> #{{ issue.uid }} </template>+ </div>+ <div+ class="flex truncate"+ :class="{+ 'font-semibold': isAssigneeAttentionOn(issue),+ }"+ >+ <span+ v-for="(item, index) in issueNameSections(issue.title)"+ :key="index"+ :class="['whitespace-pre', item.highlight ? 'bg-yellow-100' : '']"+ >+ {{ item.text }}+ </span>+ </div>+ <NTooltip v-if="isAssigneeAttentionOn(issue)">+ <template #trigger>+ <span>+ <heroicons-outline:bell-alert+ class="w-4 h-4 text-accent ml-1"+ />+ </span>+ </template>+ <span class="whitespace-nowrap">+ {{ $t("issue.assignee-attention.needs-attention") }}+ </span>+ </NTooltip>+ </div>+ </BBTableCell>+ <BBTableCell class="table-cell w-36">+ <div v-if="isDatabaseRelatedIssue(issue)" class="flex items-center">+ {{ activeEnvironmentForIssue(issue)?.title }}+ <ProductionEnvironmentV1Icon+ class="ml-1"+ :environment="activeEnvironmentForIssue(issue)"+ />+ </div>+ <div v-else>-</div>+ </BBTableCell>+ <BBTableCell class="hidden sm:table-cell w-36">+ <BBStepBar+ :step-list="taskStepList(issue)"+ @click-step="+ (step: any) => {+ clickIssueStep(issue, step);+ }+ "+ />+ </BBTableCell>+ <BBTableCell class="hidden md:table-cell w-36">+ {{ humanizeTs((issue.updateTime?.getTime() ?? 0) / 1000) }}+ </BBTableCell>+ <BBTableCell class="hidden sm:table-cell w-36">+ <CurrentApproverV1 :issue="issue" />+ </BBTableCell>+ <BBTableCell class="hidden sm:table-cell w-36">+ <div class="flex flex-row items-center">+ <BBAvatar+ :size="'SMALL'"+ :username="issue.assigneeEntity?.title ?? $t('common.unassigned')"+ />+ <span class="ml-2">+ {{ issue.assigneeEntity?.title ?? $t("common.unassigned") }}+ </span>+ </div>+ </BBTableCell>+ <BBTableCell class="hidden sm:table-cell w-36">+ <div class="flex flex-row items-center">+ <BBAvatar :size="'SMALL'" :username="issue.creatorEntity.title" />+ <span class="ml-2">+ {{ issue.creatorEntity.title }}+ </span>+ </div>+ </BBTableCell>+ </template>+ </BBTable>++ <div+ v-if="isTableInViewport && selectedIssueList.length > 0"+ class="sticky bottom-0 w-full bg-white flex items-center gap-x-2 px-4 py-2 border border-t-0"+ >+ <BatchIssueActionsV1 :issue-list="selectedIssueList" />+ </div>+</template>++<script lang="ts" setup>+import { reactive, PropType, computed, watch, ref } from "vue";+import { useRouter } from "vue-router";+import type {+ BBTableColumn,+ BBStep,+ BBStepStatus,+ BBTableSectionDataSource,+} from "@/bbkit/types";+import BatchIssueActionsV1 from "@/components/IssueV1/components/BatchIssueActionsV1.vue";+import CurrentApproverV1 from "@/components/IssueV1/components/CurrentApproverV1.vue";+import IssueStatusIcon from "@/components/IssueV1/components/IssueStatusIcon.vue";+import { useElementVisibilityInScrollParent } from "@/composables/useElementVisibilityInScrollParent";+import { useCurrentUserV1, useEnvironmentV1Store } from "@/store";+import type { Task, ComposedIssue } from "@/types";+import { IssueStatus, issueStatusToJSON } from "@/types/proto/v1/issue_service";+import { Workflow } from "@/types/proto/v1/project_service";+import {+ Task_Status,+ task_StatusToJSON,+} from "@/types/proto/v1/rollout_service";+import {+ issueSlug,+ stageSlug,+ activeTaskInStageV1,+ activeEnvironmentInRollout,+} from "@/utils";+import { isDatabaseRelatedIssue, activeTaskInRollout } from "@/utils";++type Mode = "ALL" | "PROJECT";++const columnList: BBTableColumn[] = [+ {+ title: "",+ },+ {+ title: "",+ },+ {+ title: "issue.table.name",+ },+ {+ title: "issue.table.environment",+ },+ {+ title: "issue.table.progress",+ },+ {+ title: "issue.table.updated",+ },+ {+ title: "issue.table.approver",+ },+ {+ title: "issue.table.assignee",+ },+ {+ title: "issue.table.creator",+ },+];++interface LocalState {+ dataSource: any[];+ selectedIssueIdList: Set<string>;+}++const props = defineProps({+ title: {+ type: String,+ required: true,+ },+ issueList: {+ type: Array as PropType<ComposedIssue[]>,+ default: () => [],+ },+ mode: {+ default: "ALL",+ type: String as PropType<Mode>,+ },+ leftBordered: {+ default: true,+ type: Boolean,+ },+ rightBordered: {+ default: true,+ type: Boolean,+ },+ topBordered: {+ default: true,+ type: Boolean,+ },+ bottomBordered: {+ default: true,+ type: Boolean,+ },+ highlightText: {+ default: "",+ required: false,+ type: String,+ },+});+const router = useRouter();++const state = reactive<LocalState>({+ dataSource: [],+ selectedIssueIdList: new Set(),+});+const currentUserV1 = useCurrentUserV1();+const environmentStore = useEnvironmentV1Store();++const tableRef = ref<HTMLTableElement>();+const isTableInViewport = useElementVisibilityInScrollParent(tableRef);++const issueSectionList = computed(+ (): BBTableSectionDataSource<ComposedIssue>[] => {+ return [+ {+ title: props.title,+ list: props.issueList,+ },+ ];+ }+);++const selectedIssueList = computed(() => {+ return props.issueList.filter((issue) =>+ state.selectedIssueIdList.has(issue.uid)+ );+});++const issueTaskStatus = (issue: ComposedIssue) => {+ // For grant request issue, we always show the status as "NOT_STARTED" as task status.+ if (!isDatabaseRelatedIssue(issue)) {+ return Task_Status.NOT_STARTED;+ }++ return activeTaskInRollout(issue.rolloutEntity).status;+};++const activeEnvironmentForIssue = (issue: ComposedIssue) => {+ const environmentName = activeEnvironmentInRollout(issue.rolloutEntity);+ return environmentStore.getEnvironmentByName(environmentName);+};++const taskStepList = function (issue: ComposedIssue): BBStep[] {+ if (!isDatabaseRelatedIssue(issue)) {+ return [+ {+ status:+ issue.status === IssueStatus.OPEN+ ? "PENDING_APPROVAL_ACTIVE"+ : (issueStatusToJSON(issue.status) as BBStepStatus),+ payload: undefined,+ },+ ];+ }++ const res = issue.rolloutEntity.stages.map((stage) => {+ const task = activeTaskInStageV1(stage);+ let status = task_StatusToJSON(task.status) as BBStepStatus;+ if (status == "PENDING" || status == "NOT_STARTED") {+ if (activeTaskInRollout(issue.rolloutEntity).uid == task.uid) {+ status =+ status == "PENDING" ? "PENDING_ACTIVE" : "PENDING_APPROVAL_ACTIVE";+ } else {+ status = "PENDING_APPROVAL";+ }+ }+ return {+ status,+ payload: task,+ };+ });++ return res;+};++const isIssueSelected = (issue: ComposedIssue): boolean => {+ return state.selectedIssueIdList.has(issue.uid);+};++const allSelectionState = computed(() => {+ const set = state.selectedIssueIdList;++ const checked = props.issueList.every((issue) => set.has(issue.uid));+ const indeterminate =+ !checked && props.issueList.some((issue) => set.has(issue.uid));++ return {+ checked,+ indeterminate,+ };+});++const setIssueSelection = (issue: ComposedIssue, selected: boolean) => {+ if (selected) {+ state.selectedIssueIdList.add(issue.uid);+ } else {+ state.selectedIssueIdList.delete(issue.uid);+ }+};+const setAllIssuesSelection = (selected: boolean): void => {+ const set = state.selectedIssueIdList;+ const list = props.issueList;+ if (selected) {+ list.forEach((issue) => {+ set.add(issue.uid);+ });+ } else {+ list.forEach((issue) => {+ set.delete(issue.uid);+ });+ }+};++const isAssigneeAttentionOn = (issue: ComposedIssue) => {+ if (issue.projectEntity.workflow === Workflow.VCS) {+ return false;+ }+ if (issue.status !== IssueStatus.OPEN) {+ return false;+ }+ if (currentUserV1.value.name === issue.assignee) {+ // True if current user is the assignee+ return issue.assigneeAttention;+ }++ return false;+};++const clickIssue = (_: number, row: number, e: MouseEvent) => {+ const issue = props.issueList[row];+ const url = `/issue/${issueSlug(issue.name, issue.uid)}`;+ if (e.ctrlKey || e.metaKey) {+ window.open(url, "_blank");+ } else {+ router.push(url);+ }+};++const clickIssueStep = (issue: ComposedIssue, step: BBStep) => {+ if (!isDatabaseRelatedIssue(issue)) {+ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: issueSlug(issue.name, issue.uid),+ },+ });+ return;+ }++ const task = step.payload as Task;+ const stageIndex = issue.rolloutEntity.stages.findIndex((item) => {+ return item.uid === `${task.stage.id}`;+ });++ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: issueSlug(issue.name, issue.uid),+ },+ query: { stage: stageSlug(task.stage.name, stageIndex) },+ });+};++watch(+ () => props.issueList,+ (list) => {+ const oldIssueIdList = Array.from(state.selectedIssueIdList.values());+ const newIssueIdList = new Set(list.map((issue) => issue.uid));+ oldIssueIdList.forEach((id) => {+ // If a selected issue id doesn't appear in the new IssueList+ // we should cancel its selection state.+ if (!newIssueIdList.has(id)) {+ state.selectedIssueIdList.delete(id);+ }+ });+ }+);++interface IssueNameSection {+ text: string;+ highlight: boolean;+}++const issueNameSections = (issueName: string): IssueNameSection[] => {+ if (!props.highlightText) {+ return [+ {+ text: issueName,+ highlight: false,+ },+ ];+ }++ const resp = [];+ const sections = issueName+ .toLowerCase()+ .split(props.highlightText.toLowerCase());+ let pos = 0;+ for (let i = 0; i < sections.length; i++) {+ const section = sections[i];+ if (section.length) {+ resp.push({+ text: issueName.slice(pos, pos + section.length),+ highlight: false,+ });+ pos += section.length;+ }+ if (i < sections.length - 1) {+ resp.push({+ text: issueName.slice(pos, pos + props.highlightText.length),+ highlight: true,+ });+ pos += props.highlightText.length;+ }+ }+ return resp;+};+</script>diff --git a/frontend/src/components/IssueV1/components/PagedIssueTableV1.vue b/frontend/src/components/IssueV1/components/PagedIssueTableV1.vuenew file mode 100644index 0000000000..a4c2b94311--- /dev/null+++ b/frontend/src/components/IssueV1/components/PagedIssueTableV1.vue@@ -0,0 +1,179 @@+<template>+ <slot name="table" :issue-list="state.issueList" :loading="state.loading" />++ <div+ v-if="state.loading"+ class="flex items-center justify-center py-2 text-gray-400 text-sm"+ >+ <BBSpin />+ </div>++ <slot+ v-if="!state.loading"+ name="more"+ :has-more="state.hasMore"+ :fetch-next-page="fetchNextPage"+ >+ <div+ v-if="!hideLoadMore && pageSize > 0 && state.hasMore"+ class="flex items-center justify-center py-2 text-gray-400 text-sm hover:bg-gray-200 cursor-pointer"+ @click="fetchNextPage"+ >+ {{ $t("common.load-more") }}+ </div>+ </slot>+</template>++<script lang="ts" setup>+import { useSessionStorage } from "@vueuse/core";+import { computed, PropType, reactive, watch } from "vue";+import { useIsLoggedIn, useIssueV1Store, useRefreshIssueList } from "@/store";+import { IssueFilter, ComposedIssue } from "@/types";++type LocalState = {+ loading: boolean;+ issueList: ComposedIssue[];+ paginationToken: string;+ hasMore: boolean;+};++/**+ * It's complex and dangerous to cache the issue list.+ * So we just memorize how many times the user clicks the "load more" button.+ * And load the first N pages in the first fetch.+ * E.g., the user clicked "load more" 4 times, then the first time will set limit+ * to `pageSize * 5`.+ */+type SessionState = {+ // How many times the user clicks the "load more" button.+ page: number;+ // Help us to check if the session is outdated.+ updatedTs: number;+};++const MAX_PAGE_SIZE = 1000;+const SESSION_LIFE = 1 * 60 * 1000; // 1 minute++const props = defineProps({+ // A unique key to identify the session state.+ sessionKey: {+ type: String,+ required: true,+ },+ issueFilter: {+ type: Object as PropType<IssueFilter>,+ required: true,+ },+ pageSize: {+ type: Number,+ default: 10,+ },+ hideLoadMore: {+ type: Boolean,+ default: false,+ },+});++const state = reactive<LocalState>({+ loading: false,+ issueList: [],+ paginationToken: "",+ hasMore: true,+});++const sessionState = useSessionStorage<SessionState>(+ `bb.page-issue-table-v1.${props.sessionKey}`,+ {+ page: 1,+ updatedTs: 0,+ }+);++const issueStore = useIssueV1Store();+const isLoggedIn = useIsLoggedIn();++const limit = computed(() => {+ if (props.pageSize <= 0) return MAX_PAGE_SIZE;+ return props.pageSize;+});++const fetchData = (refresh = false) => {+ if (!isLoggedIn.value) {+ return;+ }++ state.loading = true;++ const isFirstFetch = state.paginationToken === "";+ const expectedRowCount = isFirstFetch+ ? // Load one or more page for the first fetch to restore the session+ limit.value * sessionState.value.page+ : // Always load one page if NOT the first fetch+ limit.value;++ issueStore+ .searchIssues({+ find: props.issueFilter,+ pageSize: props.pageSize,+ pageToken: state.paginationToken,+ })+ .then(({ nextPageToken, issues }) => {+ if (refresh) {+ state.issueList = issues;+ } else {+ state.issueList.push(...issues);+ }++ if (issues.length < expectedRowCount) {+ state.hasMore = false;+ } else if (!isFirstFetch) {+ // If we didn't reach the end, memorize we've clicked the "load more" button.+ sessionState.value.page++;+ }++ sessionState.value.updatedTs = Date.now();+ state.paginationToken = nextPageToken;+ if (!nextPageToken) {+ state.hasMore = false;+ }+ })+ .finally(() => {+ state.loading = false;+ });+};++const resetSession = () => {+ sessionState.value = {+ page: 1,+ updatedTs: 0,+ };+};++const refresh = () => {+ state.paginationToken = "";+ state.hasMore = true;+ resetSession();+ fetchData(true);+};++const fetchNextPage = () => {+ fetchData(false);+};++if (Date.now() - sessionState.value.updatedTs > SESSION_LIFE) {+ // Reset session if it's outdated.+ resetSession();+}+fetchData(true);+watch(() => JSON.stringify(props.issueFilter), refresh);+watch(isLoggedIn, () => {+ // Reset session when logged out.+ if (!isLoggedIn.value) {+ resetSession();+ }+});++useRefreshIssueList(() => {+ refresh();+});+</script>diff --git a/frontend/src/components/IssueV1/logic/transition.ts b/frontend/src/components/IssueV1/logic/transition.tsnew file mode 100644index 0000000000..efcb182a83--- /dev/null+++ b/frontend/src/components/IssueV1/logic/transition.ts@@ -0,0 +1,141 @@+import { computed } from "vue";+import { extractIssueReviewContext } from "@/plugins/issue/logic";+import { useCurrentUserV1, useProjectV1Store } from "@/store";+import {+ ComposedIssue,+ IssueStatusTransitionType,+ ISSUE_STATUS_TRANSITION_LIST,+ IssueStatusTransition,+} from "@/types";+import { User } from "@/types/proto/v1/auth_service";+import { IssueStatus } from "@/types/proto/v1/issue_service";+import { Task_Status } from "@/types/proto/v1/rollout_service";+import {+ StageStatusTransition,+ TaskStatusTransition,+ hasWorkspacePermissionV1,+ isOwnerOfProjectV1,+ isDatabaseRelatedIssue,+ flattenTaskV1List,+ isGrantRequestIssue,+ activeTaskInRollout,+} from "@/utils";++// The first transition in the list is the primary action and the rests are+// the normal action. For now there are at most 1 primary 1 normal action.+const APPLICABLE_ISSUE_ACTION_LIST: Map<+ IssueStatus,+ IssueStatusTransitionType[]+> = new Map([+ [IssueStatus.OPEN, ["RESOLVE", "CANCEL"]],+ [IssueStatus.DONE, ["REOPEN"]],+ [IssueStatus.CANCELED, ["REOPEN"]],+]);++export const calcApplicableIssueStatusTransitionList = (+ issue: ComposedIssue+): IssueStatusTransition[] => {+ const transitionTypeList: IssueStatusTransitionType[] = [];+ const currentUserV1 = useCurrentUserV1();++ if (allowUserToApplyIssueStatusTransition(issue, currentUserV1.value)) {+ const actions = APPLICABLE_ISSUE_ACTION_LIST.get(issue.status);+ if (actions) {+ transitionTypeList.push(...actions);+ }+ }++ const applicableTransitionList: IssueStatusTransition[] = [];+ transitionTypeList.forEach((type) => {+ const transition = ISSUE_STATUS_TRANSITION_LIST.get(type);+ if (!transition) return;++ if (type === "RESOLVE") {+ // If an issue is not "Approved" in review stage+ // it cannot be Resolved.+ if (!isIssueReviewDone(issue)) {+ return;+ }+ } else if (type === "REOPEN") {+ // Don't show the REOPEN button for request granting issues.+ if (isGrantRequestIssue(issue)) {+ return;+ }+ }++ if (isDatabaseRelatedIssue(issue)) {+ const currentTask = activeTaskInRollout(issue.rolloutEntity);+ const flattenTaskList = flattenTaskV1List(issue.rolloutEntity);+ if (flattenTaskList.some((task) => task.status === Task_Status.RUNNING)) {+ // Disallow any issue status transition if some of the tasks are in RUNNING state.+ return;+ }+ if (type === "RESOLVE") {+ if (transition.type === "RESOLVE" && flattenTaskList.length > 0) {+ const lastTask = flattenTaskList[flattenTaskList.length - 1];+ // Don't display the RESOLVE action if the pipeline doesn't reach the+ // last task+ if (lastTask.uid !== currentTask.uid) {+ return;+ }+ // Don't display the RESOLVE action if the last task is not DONE.+ if (currentTask.status !== Task_Status.DONE) {+ return;+ }+ }+ }+ }+ applicableTransitionList.push(transition);+ });+ return applicableTransitionList;+};++export function isApplicableTransition<+ T extends IssueStatusTransition | TaskStatusTransition | StageStatusTransition+>(target: T, list: T[]): boolean {+ return (+ list.findIndex((applicable) => {+ return applicable.to === target.to && applicable.type === target.type;+ }) >= 0+ );+}++const allowUserToApplyIssueStatusTransition = (+ issue: ComposedIssue,+ user: User+) => {+ // Workspace level high-privileged user (DBA/OWNER) are always allowed.+ if (+ hasWorkspacePermissionV1(+ "bb.permission.workspace.manage-issue",+ user.userRole+ )+ ) {+ return true;+ }++ // Project owners are also allowed+ const projectV1 = useProjectV1Store().getProjectByName(issue.project);+ if (isOwnerOfProjectV1(projectV1.iamPolicy, user)) {+ return true;+ }++ // The creator and the assignee can apply issue status transition++ if (user.name === issue.creatorEntity.name) {+ return true;+ }+ if (user.name === issue.assigneeEntity?.name) {+ return true;+ }++ return false;+};++function isIssueReviewDone(issue: ComposedIssue) {+ const context = extractIssueReviewContext(+ computed(() => undefined),+ computed(() => issue)+ );+ return context.done.value;+}diff --git a/frontend/src/components/ProjectOverviewPanel.vue b/frontend/src/components/ProjectOverviewPanel.vueindex 8249989fed..57a38257f5 100644--- a/frontend/src/components/ProjectOverviewPanel.vue+++ b/frontend/src/components/ProjectOverviewPanel.vue@@ -39,9 +39,28 @@</div><div class="space-y-2">- <p class="text-lg font-medium leading-7 text-main">- {{ $t("common.issue") }}- </p>+ <div class="flex items-center gap-x-1">+ <p class="text-lg font-medium leading-7 text-main">+ {{ $t("common.issue") }}+ </p>+ <button+ type="button"+ class="p-1 rounded hover:bg-gray-200"+ @click="+ () => {+ router.replace({+ name: 'workspace.issue',+ query: {+ project: project.uid,+ autofocus: 1,+ },+ });+ }+ "+ >+ <heroicons-outline:search class="h-4 w-4 text-control" />+ </button>+ </div><div><WaitingForMyApprovalIssueTable@@ -119,6 +138,7 @@<script lang="ts" setup>import { reactive, PropType } from "vue";+import { useRouter } from "vue-router";import PagedIssueTable from "@/components/Issue/table/PagedIssueTable.vue";import { featureToRef } from "@/store";import { Project } from "@/types/proto/v1/project_service";@@ -143,5 +163,7 @@ const state = reactive<LocalState>({progressIssueList: [],closedIssueList: [],});+const router = useRouter();+const hasCustomApprovalFeature = featureToRef("bb.feature.custom-approval");</script>diff --git a/frontend/src/store/modules/v1/experimental-issue.ts b/frontend/src/store/modules/v1/experimental-issue.tsindex 9f565424d6..0f4636f16c 100644--- a/frontend/src/store/modules/v1/experimental-issue.ts+++ b/frontend/src/store/modules/v1/experimental-issue.ts@@ -1,39 +1,33 @@import { issueServiceClient, rolloutServiceClient } from "@/grpcweb";+import { useProjectV1Store, useUserStore } from "@/store";import {ComposedIssue,ComposedProject,emptyIssue,emptyRollout,+ unknownUser,EMPTY_ID,EMPTY_ISSUE_NAME,- EMPTY_ROLLOUT_NAME,unknownIssue,UNKNOWN_ID,UNKNOWN_ISSUE_NAME,} from "@/types";import { Issue } from "@/types/proto/v1/issue_service";import { Plan, Rollout } from "@/types/proto/v1/rollout_service";-import { extractProjectResourceName } from "@/utils";-import { useProjectV1Store } from "./project";+import { extractProjectResourceName, extractUserResourceName } from "@/utils";-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}`,- });+export const composeIssue = async (rawIssue: Issue): Promise<ComposedIssue> => {+ const userStore = useUserStore();const project = `projects/${extractProjectResourceName(rawIssue.name)}`;const projectEntity = await useProjectV1Store().getOrFetchProjectByName(project);+ const creatorEntity =+ userStore.getUserByEmail(extractUserResourceName(rawIssue.creator)) ??+ unknownUser();+const issue: ComposedIssue = {...rawIssue,planEntity: undefined,@@ -42,6 +36,7 @@ export const experimentalFetchIssueByUID = async (uid: string) => {rolloutTaskRunList: [],project,projectEntity,+ creatorEntity,};if (issue.rollout) {@@ -65,11 +60,34 @@ export const experimentalFetchIssueByUID = async (uid: string) => {issue.planCheckRunList = planCheckRuns;}+ if (issue.assignee) {+ const assigneeEntity = userStore.getUserByEmail(+ extractUserResourceName(rawIssue.assignee)+ );+ issue.assigneeEntity = assigneeEntity;+ }+await new Promise((r) => setTimeout(r, 500));return issue;};+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}`,+ });++ return composeIssue(rawIssue);+};+export const experimentalFetchIssueByName = async (name: string) => {if (name === EMPTY_ISSUE_NAME) return emptyIssue();if (name === UNKNOWN_ISSUE_NAME) return unknownIssue();@@ -78,46 +96,7 @@ export const experimentalFetchIssueByName = async (name: string) => {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;+ return composeIssue(rawIssue);};export type CreateIssueHooks = {diff --git a/frontend/src/store/modules/v1/issue.ts b/frontend/src/store/modules/v1/issue.tsindex 3931c7cf43..3c8f3a10d9 100644--- a/frontend/src/store/modules/v1/issue.ts+++ b/frontend/src/store/modules/v1/issue.ts@@ -8,10 +8,12 @@ import {Issue as LegacyIssue,PresetRoleType,ComposedIssue,+ IssueFilter,} from "@/types";import { User, UserRole, UserType } from "@/types/proto/v1/auth_service";import {Issue,+ issueStatusToJSON,ApprovalStep,ApprovalNode_Type,ApprovalNode_GroupValue,@@ -21,6 +23,7 @@ import { useProjectV1Store } from ".";import { useUserStore } from "../user";import { useActivityV1Store } from "./activity";import { projectNamePrefix, issueNamePrefix } from "./common";+import { composeIssue } from "./experimental-issue";const issueName = (legacyIssue: LegacyIssue) => {return `projects/${legacyIssue.project.id}/issues/${legacyIssue.id}`;@@ -33,6 +36,30 @@ const emptyIssue = (legacyIssue: LegacyIssue) => {});};+export const buildIssueFilter = (find: IssueFilter): string => {+ const filter: string[] = [];+ if (find.principal) {+ filter.push(`principal = "${find.principal}"`);+ }+ if (find.creator) {+ filter.push(`creator = "${find.creator}"`);+ }+ if (find.assignee) {+ filter.push(`assignee = "${find.assignee}"`);+ }+ if (find.subscriber) {+ filter.push(`subscriber = "${find.subscriber}"`);+ }+ if (find.statusList) {+ filter.push(+ `status = "${find.statusList+ .map((s) => issueStatusToJSON(s))+ .join(" | ")}"`+ );+ }+ return filter.join(" && ");+};+export const useIssueV1Store = defineStore("issue_v1", () => {const issuesByName = ref(new Map<string, Issue>());@@ -147,12 +174,39 @@ export const useIssueV1Store = defineStore("issue_v1", () => {await useActivityV1Store().fetchActivityListByIssueId(issueId);};+ const searchIssues = async ({+ find,+ pageSize,+ pageToken,+ }: {+ find: IssueFilter;+ pageSize?: number;+ pageToken?: string;+ }) => {+ const resp = await issueServiceClient.searchIssues({+ parent: find.project,+ query: find.query,+ filter: buildIssueFilter(find),+ pageSize,+ pageToken,+ });++ const composedIssues = await Promise.all(+ resp.issues.map((issue) => composeIssue(issue))+ );+ return {+ nextPageToken: resp.nextPageToken,+ issues: composedIssues,+ };+ };+return {getIssueByIssue,fetchIssueByLegacyIssue: fetchIssueByLegacyIssue,approveIssue,rejectIssue,requestIssue,+ searchIssues,regenerateReview,regenerateReviewV1,createIssueComment,diff --git a/frontend/src/types/v1/issue/issue.ts b/frontend/src/types/v1/issue/issue.tsindex b6df55b6b5..95ca84aa62 100644--- a/frontend/src/types/v1/issue/issue.ts+++ b/frontend/src/types/v1/issue/issue.ts@@ -1,18 +1,21 @@+import {+ ComposedProject,+ EMPTY_PROJECT_NAME,+ UNKNOWN_PROJECT_NAME,+ emptyProject,+ unknownProject,+ emptyUser,+ unknownUser,+} from "@/types";+import { User } from "@/types/proto/v1/auth_service";import { EMPTY_ID, UNKNOWN_ID } from "../../const";-import { Issue, Issue_Type } from "../../proto/v1/issue_service";+import { Issue, Issue_Type, IssueStatus } 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,@@ -27,6 +30,8 @@ export interface ComposedIssue extends Issue {rolloutTaskRunList: TaskRun[];project: string;projectEntity: ComposedProject;+ assigneeEntity?: User;+ creatorEntity: User;}export const ESTABLISH_BASELINE_SQL =@@ -49,6 +54,7 @@ export const emptyIssue = (): ComposedIssue => {rolloutTaskRunList: [],project: EMPTY_PROJECT_NAME,projectEntity: emptyProject(),+ creatorEntity: emptyUser(),};};@@ -66,5 +72,16 @@ export const unknownIssue = (): ComposedIssue => {rolloutTaskRunList: [],project: UNKNOWN_PROJECT_NAME,projectEntity: unknownProject(),+ creatorEntity: unknownUser(),};};++export interface IssueFilter {+ project: string;+ query: string;+ principal?: string;+ creator?: string;+ assignee?: string;+ subscriber?: string;+ statusList?: IssueStatus[];+}diff --git a/frontend/src/utils/v1/issue/rollout.ts b/frontend/src/utils/v1/issue/rollout.tsindex 12f119c429..079499dd27 100644--- a/frontend/src/utils/v1/issue/rollout.ts+++ b/frontend/src/utils/v1/issue/rollout.ts@@ -78,6 +78,11 @@ export const activeStageInRollout = (rollout: Rollout): Stage => {return emptyStage();};+export const activeEnvironmentInRollout = (rollout: Rollout): string => {+ const stage: Stage = activeStageInRollout(rollout);+ return stage.environment;+};+export const findTaskByUID = (rollout: Rollout | undefined,uid: stringdiff --git a/frontend/src/views/DashboardSidebar.vue b/frontend/src/views/DashboardSidebar.vueindex a64d23c57f..79b1c9f80c 100644--- a/frontend/src/views/DashboardSidebar.vue+++ b/frontend/src/views/DashboardSidebar.vue@@ -30,6 +30,22 @@<heroicons-outline:home class="w-5 h-5 mr-2" />{{ $t("issue.my-issues") }}</div>+ <button+ type="button"+ class="p-1 rounded hover:bg-gray-300 mr-2"+ @click.prevent.stop="+ () => {+ router.replace({+ name: 'workspace.issue',+ query: {+ autofocus: 1,+ },+ });+ }+ "+ >+ <heroicons-outline:search class="h-4 w-4 text-control" />+ </button></router-link><ahref="/sql-editor"@@ -84,6 +100,7 @@<script lang="ts" setup>import { useKBarHandler } from "@bytebase/vue-kbar";import { computed } from "vue";+import { useRouter } from "vue-router";import BookmarkListSidePanel from "@/components/BookmarkListSidePanel.vue";import BytebaseLogo from "@/components/BytebaseLogo.vue";import DatabaseListSidePanel from "@/components/DatabaseListSidePanel.vue";@@ -96,6 +113,7 @@ import {const isMac = navigator.platform.match(/mac/i);const handler = useKBarHandler();+const router = useRouter();// Only show sync schema if the user has permission to alter schema of at least one project.const shouldShowSyncSchemaEntry = computed(() => {diff --git a/frontend/src/views/IssueDashboard.vue b/frontend/src/views/IssueDashboard.vueindex a291d31494..b81151133c 100644--- a/frontend/src/views/IssueDashboard.vue+++ b/frontend/src/views/IssueDashboard.vue@@ -1,5 +1,13 @@<template><div class="flex flex-col">+ <AdvancedSearch+ v-if="isDev()"+ custom-class="m-4"+ :params="initSearchParams"+ :autofocus="autofocus"+ @update="onSearchParamsUpdate($event)"+ />+<div class="px-4 py-2 flex justify-between items-center"><EnvironmentTabFilter:include-all="true"@@ -20,31 +28,27 @@@update:user="changeUserUID"/><SearchBox- :value="state.searchText"- :placeholder="$t('issue.search-issue-name')"- :autofocus="true"- @update:value="changeSearchText($event)"+ :value="state.filterText"+ :placeholder="$t('issue.filter-issue-by-name')"+ :autofocus="false"+ @update:value="state.filterText = $event"/></NInputGroup></div></div><!-- show all OPEN issues with pageSize=10 -->- <PagedIssueTable+ <PagedIssueTableV1v-if="showOpen"session-key="dashboard-open"- :issue-find="{- statusList: ['OPEN'],- principalId:- selectedUserUID && selectedUserUID !== String(UNKNOWN_ID)- ? selectedUserUID- : undefined,- projectId: selectedProjectId,+ :issue-filter="{+ ...issueFilter,+ statusList: [IssueStatus.OPEN],}":page-size="10"><template #table="{ issueList, loading }">- <IssueTable+ <IssueTableV1:left-bordered="false":right-bordered="false":top-bordered="true"@@ -52,26 +56,23 @@:show-placeholder="!loading":title="$t('issue.table.open')":issue-list="issueList.filter(filter)"+ :highlight-text="state.searchParams.query"/></template>- </PagedIssueTable>+ </PagedIssueTableV1><!-- show all DONE and CANCELED issues with pageSize=10 -->- <PagedIssueTable+ <PagedIssueTableV1v-if="showClosed"session-key="dashboard-closed"- :issue-find="{- statusList: ['DONE', 'CANCELED'],- principalId:- selectedUserUID && selectedUserUID !== String(UNKNOWN_ID)- ? selectedUserUID- : undefined,- projectId: selectedProjectId,+ :issue-filter="{+ ...issueFilter,+ statusList: [IssueStatus.DONE, IssueStatus.CANCELED],}":page-size="10"><template #table="{ issueList, loading }">- <IssueTable+ <IssueTableV1class="-mt-px":left-bordered="false":right-bordered="false"@@ -80,36 +81,43 @@:show-placeholder="!loading":title="$t('issue.table.closed')":issue-list="issueList.filter(filter)"+ :highlight-text="state.searchParams.query"/></template>- </PagedIssueTable>+ </PagedIssueTableV1></div></template><script lang="ts" setup>import { NInputGroup, NButton } from "naive-ui";-import { reactive, computed, watchEffect } from "vue";+import { reactive, computed, watchEffect, onMounted } from "vue";import { useRoute, useRouter } from "vue-router";-import PagedIssueTable from "@/components/Issue/table/PagedIssueTable.vue";+import { SearchParams } from "@/components/AdvancedSearch.vue";+import IssueTableV1 from "@/components/IssueV1/components/IssueTableV1.vue";+import PagedIssueTableV1 from "@/components/IssueV1/components/PagedIssueTableV1.vue";import { EnvironmentTabFilter, UserSelect, SearchBox } from "@/components/v2";import {useCurrentUserV1,useEnvironmentV1Store,useProjectV1Store,+ useUserStore,} from "@/store";+import { projectNamePrefix, userNamePrefix } from "@/store/modules/v1/common";+import { UNKNOWN_ID, IssueFilter, ComposedIssue } from "@/types";import { Environment } from "@/types/proto/v1/environment_service";-import { IssueTable } from "../components/Issue";-import { type Issue, UNKNOWN_ID } from "../types";+import { IssueStatus } from "@/types/proto/v1/issue_service";import {- activeEnvironment,+ isDev,extractUserUID,hasWorkspacePermissionV1,- isDatabaseRelatedIssueType,+ isDatabaseRelatedIssue,+ activeEnvironmentInRollout,projectV1Slug,-} from "../utils";+} from "@/utils";interface LocalState {- searchText: string;+ filterText: string;+ searchParams: SearchParams;}const router = useRouter();@@ -123,8 +131,37 @@ const statusList = computed((): string[] =>route.query.status ? (route.query.status as string).split(",") : []);+const autofocus = computed((): boolean => {+ return !!route.query.autofocus;+});++const initSearchParams = computed((): SearchParams => {+ const projectName = project.value?.name ?? "";+ const query = (route.query.query as string) ?? "";++ if (!projectName) {+ return {+ query,+ scopes: [],+ };+ }+ return {+ query,+ scopes: [+ {+ id: "project",+ value: projectName,+ },+ ],+ };+});+const state = reactive<LocalState>({- searchText: "",+ filterText: "",+ searchParams: {+ query: "",+ scopes: [],+ },});const project = computed(() => {@@ -175,6 +212,14 @@ const selectedUserUID = computed((): string => {: extractUserUID(currentUserV1.value.name); // default to current user otherwise});+const selectedUser = computed(() => {+ const uid = selectedUserUID.value;+ if (uid === String(UNKNOWN_ID)) {+ return;+ }+ return useUserStore().getUserById(uid);+});+const selectedEnvironment = computed((): Environment | undefined => {const { environment } = route.query;return environment@@ -187,21 +232,21 @@ const selectedProjectId = computed((): string | undefined => {return project ? (project as string) : undefined;});-const filter = (issue: Issue) => {+const filter = (issue: ComposedIssue) => {if (selectedEnvironment.value) {- if (!isDatabaseRelatedIssueType(issue.type)) {+ if (!isDatabaseRelatedIssue(issue)) {return false;}if (- String(activeEnvironment(issue.pipeline).id) !==- selectedEnvironment.value.uid+ activeEnvironmentInRollout(issue.rolloutEntity) !==+ selectedEnvironment.value.name) {return false;}}- const keyword = state.searchText.trim().toLowerCase();+ const keyword = state.filterText.trim().toLowerCase();if (keyword) {- if (!issue.name.toLowerCase().includes(keyword)) {+ if (!issue.title.toLowerCase().includes(keyword)) {return false;}}@@ -241,10 +286,6 @@ const changeUserUID = (user: string | undefined) => {});};-const changeSearchText = (searchText: string) => {- state.searchText = searchText;-};-const goProject = () => {if (!project.value) return;router.push({@@ -260,4 +301,27 @@ watchEffect(() => {projectV1Store.getOrFetchProjectByUID(selectedProjectId.value);}});++onMounted(() => {+ state.searchParams = initSearchParams.value;+});++const onSearchParamsUpdate = (params: SearchParams) => {+ state.searchParams = params;+};++const issueFilter = computed((): IssueFilter => {+ const { query, scopes } = state.searchParams;+ const projectScope = scopes.find((s) => s.id === "project");+ const project = projectScope?.value ?? `${projectNamePrefix}-`;+ let principal = "";+ if (selectedUser.value) {+ principal = `${userNamePrefix}${selectedUser.value.email}`;+ }+ return {+ project,+ query,+ principal,+ };+});</script>