Skip to content

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

First batch of to add project activity and add a activity tab to the project detail page

天舟6fc36918dc96
diff --git a/api/activity.go b/api/activity.go
index baa5a23776..196b4e0566 100644
--- a/api/activity.go
+++ b/api/activity.go
@@ -3,6 +3,8 @@ package api
import (
"context"
"encoding/json"
+
+ "github.com/bytebase/bytebase/common"
)
// Activity type
@@ -21,6 +23,9 @@ const (
ActivityMemberRoleUpdate ActivityType = "bb.member.role.update"
ActivityMemberActivate ActivityType = "bb.member.activate"
ActivityMemberDeactivate ActivityType = "bb.member.deactivate"
+
+ // Project related
+ ActivityProjectRepositoryPush ActivityType = "bb.project.repository.push"
)
func (e ActivityType) String() string {
@@ -43,6 +48,8 @@ func (e ActivityType) String() string {
return "bb.member.activate"
case ActivityMemberDeactivate:
return "bb.member.deactivate"
+ case ActivityProjectRepositoryPush:
+ return "bb.project.repository.push"
}
return "bb.activity.unknown"
}
@@ -130,6 +137,11 @@ type ActivityMemberActivateDeactivatePayload struct {
Role Role `json:"role"`
}
+type ActivityProjectRepositoryPushPayload struct {
+ VCSPushEvent common.VCSPushEvent `json:"pushEvent"`
+ Error string `json:"error"`
+}
+
type Activity struct {
ID int `jsonapi:"primary,activity"`
@@ -170,6 +182,7 @@ type ActivityFind struct {
// Domain specific fields
ContainerId *int
+ Limit *int
}
func (find *ActivityFind) String() string {
diff --git a/frontend/src/components/ActivityTable.vue b/frontend/src/components/ActivityTable.vue
new file mode 100644
index 0000000000..21bb3d4a54
--- /dev/null
+++ b/frontend/src/components/ActivityTable.vue
@@ -0,0 +1,132 @@
+<template>
+ <BBTable
+ :columnList="COLUMN_LIST"
+ :dataSource="activityList"
+ :showHeader="true"
+ :rowClickable="false"
+ :leftBordered="true"
+ :rightBordered="true"
+ >
+ <template v-slot:body="{ rowData: activity }">
+ <BBTableCell :leftPadding="4" class="w-4">
+ <span
+ class="
+ w-5
+ h-5
+ flex
+ items-center
+ justify-center
+ rounded-full
+ select-none
+ "
+ >
+ <template v-if="activity.level === `INFO`">
+ <svg
+ class="text-info"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
+ ></path>
+ </svg>
+ </template>
+ <template v-else-if="activity.level === `WARNING`">
+ <svg
+ class="text-warning"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
+ ></path>
+ </svg>
+ </template>
+ <template v-else-if="activity.level === `ERROR`">
+ <svg
+ class="text-error"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
+ ></path>
+ </svg>
+ </template>
+ </span>
+ </BBTableCell>
+ <BBTableCell class="w-8">
+ {{ activityName(activity.actionType) }}
+ </BBTableCell>
+ <BBTableCell class="w-24">
+ {{ activity.comment }}
+ </BBTableCell>
+ <BBTableCell class="w-8">
+ {{ humanizeTs(activity.createdTs) }}
+ </BBTableCell>
+ <BBTableCell class="w-8">
+ <div class="flex flex-row items-center">
+ <BBAvatar :size="'SMALL'" :username="activity.creator.name" />
+ <span class="ml-2">{{ activity.creator.name }}</span>
+ </div>
+ </BBTableCell>
+ </template>
+ </BBTable>
+</template>
+
+<script lang="ts">
+import { PropType } from "vue";
+import { BBTableColumn } from "../bbkit/types";
+import { Activity } from "../types";
+import { activityName } from "../utils";
+
+const COLUMN_LIST: BBTableColumn[] = [
+ {
+ title: "",
+ },
+ {
+ title: "Type",
+ },
+ {
+ title: "Comment",
+ },
+ {
+ title: "Created",
+ },
+ {
+ title: "Invoker",
+ },
+];
+
+export default {
+ name: "ActivityTable",
+ components: {},
+ props: {
+ activityList: {
+ required: true,
+ type: Object as PropType<Activity[]>,
+ },
+ },
+ setup(props, ctx) {
+ return {
+ activityName,
+ COLUMN_LIST,
+ };
+ },
+};
+</script>
diff --git a/frontend/src/components/ProjectActivityPanel.vue b/frontend/src/components/ProjectActivityPanel.vue
new file mode 100644
index 0000000000..635071a17f
--- /dev/null
+++ b/frontend/src/components/ProjectActivityPanel.vue
@@ -0,0 +1,53 @@
+<template>
+ <div>
+ <div class="space-y-2">
+ <p class="text-lg font-medium leading-7 text-main">Activity</p>
+ <ActivityTable :activityList="state.activityList" />
+ </div>
+ </div>
+</template>
+
+<script lang="ts">
+import { PropType, reactive, watchEffect } from "vue";
+import { useStore } from "vuex";
+import { Activity, Project } from "../types";
+import ActivityTable from "../components/ActivityTable.vue";
+
+interface LocalState {
+ activityList: Activity[];
+}
+
+export default {
+ name: "ProjectActivityPanel",
+ components: { ActivityTable },
+ props: {
+ project: {
+ required: true,
+ type: Object as PropType<Project>,
+ },
+ },
+ setup(props, ctx) {
+ const store = useStore();
+
+ const state = reactive<LocalState>({
+ activityList: [],
+ });
+
+ const prepareActivityList = () => {
+ store
+ .dispatch("activity/fetchActivityListForProject", {
+ projectId: props.project.id,
+ })
+ .then((list) => {
+ state.activityList = list;
+ });
+ };
+
+ watchEffect(prepareActivityList);
+
+ return {
+ state,
+ };
+ },
+};
+</script>
diff --git a/frontend/src/components/ProjectOverviewPanel.vue b/frontend/src/components/ProjectOverviewPanel.vue
index a6cc4cae37..5555aa4721 100644
--- a/frontend/src/components/ProjectOverviewPanel.vue
+++ b/frontend/src/components/ProjectOverviewPanel.vue
@@ -1,9 +1,22 @@
<template>
<div class="space-y-6">
+ <div class="space-y-2">
+ <p class="text-lg font-medium leading-7 text-main">Recent activities</p>
+ <ActivityTable :activityList="state.activityList" />
+ <router-link
+ :to="`#activity`"
+ class="mt-2 flex justify-end normal-link"
+ exact-active-class=""
+ >
+ View all
+ </router-link>
+ </div>
+
<div class="space-y-2">
<p class="text-lg font-medium leading-7 text-main">Databases</p>
<DatabaseTable :mode="'PROJECT'" :databaseList="databaseList" />
</div>
+
<div class="space-y-2">
<p class="text-lg font-medium leading-7 text-main">Issues</p>
<IssueTable
@@ -32,11 +45,16 @@
<script lang="ts">
import { reactive, watchEffect, PropType } from "vue";
import { useStore } from "vuex";
+import ActivityTable from "../components/ActivityTable.vue";
import DatabaseTable from "../components/DatabaseTable.vue";
import IssueTable from "../components/IssueTable.vue";
-import { Database, Issue, Project } from "../types";
+import { Activity, Database, Issue, Project } from "../types";
+
+// Show at most 5 activity
+const ACTIVITY_LIMIT = 5;
interface LocalState {
+ activityList: Activity[];
progressIssueList: Issue[];
closedIssueList: Issue[];
}
@@ -44,6 +62,7 @@ interface LocalState {
export default {
name: "ProjectOverviewPanel",
components: {
+ ActivityTable,
DatabaseTable,
IssueTable,
},
@@ -61,10 +80,24 @@ export default {
const store = useStore();
const state = reactive<LocalState>({
+ activityList: [],
progressIssueList: [],
closedIssueList: [],
});
+ const prepareActivityList = () => {
+ store
+ .dispatch("activity/fetchActivityListForProject", {
+ projectId: props.project.id,
+ limit: ACTIVITY_LIMIT,
+ })
+ .then((list) => {
+ state.activityList = list;
+ });
+ };
+
+ watchEffect(prepareActivityList);
+
const prepareIssueList = () => {
store
.dispatch("issue/fetchIssueList", {
diff --git a/frontend/src/layouts/ProjectLayout.vue b/frontend/src/layouts/ProjectLayout.vue
index 259fea7bf0..23e2402dbd 100644
--- a/frontend/src/layouts/ProjectLayout.vue
+++ b/frontend/src/layouts/ProjectLayout.vue
@@ -45,6 +45,7 @@ type ProjectTabItem = {
const projectTabItemList: ProjectTabItem[] = [
{ name: "Overview", hash: "overview" },
{ name: "Migration History", hash: "migration-history" },
+ { name: "Activity", hash: "activity" },
{ name: "Version Control", hash: "version-control" },
{ name: "Webhooks", hash: "webhook" },
{ name: "Settings", hash: "setting" },
diff --git a/frontend/src/store/modules/activity.ts b/frontend/src/store/modules/activity.ts
index fe323af660..2e64f8f67c 100644
--- a/frontend/src/store/modules/activity.ts
+++ b/frontend/src/store/modules/activity.ts
@@ -7,6 +7,7 @@ import {
ActivityState,
IssueId,
PrincipalId,
+ ProjectId,
ResourceObject,
} from "../../types";
@@ -77,6 +78,29 @@ const actions = {
return activityList;
},
+ // We do not store the returned list because the caller will specify different limits
+ async fetchActivityListForProject(
+ { rootGetters }: any,
+ {
+ projectId,
+ limit,
+ }: {
+ projectId: ProjectId;
+ limit?: number;
+ }
+ ) {
+ var queryList = [`container=${projectId}`];
+ if (limit) {
+ queryList.push(`limit=${limit}`);
+ }
+ const data = (await axios.get(`/api/activity?${queryList.join("&")}`)).data;
+ const activityList = data.data.map((activity: ResourceObject) => {
+ return convert(activity, data.included, rootGetters);
+ });
+
+ return activityList;
+ },
+
async createActivity(
{ dispatch, rootGetters }: any,
newActivity: ActivityCreate
diff --git a/frontend/src/types/activity.ts b/frontend/src/types/activity.ts
index e799f716aa..adc315633d 100644
--- a/frontend/src/types/activity.ts
+++ b/frontend/src/types/activity.ts
@@ -18,7 +18,12 @@ export type MemberActivityType =
| "bb.member.activate"
| "bb.member.deactivate";
-export type ActivityType = IssueActivityType | MemberActivityType;
+export type ProjectActivityType = "bb.project.repository.push";
+
+export type ActivityType =
+ | IssueActivityType
+ | MemberActivityType
+ | ProjectActivityType;
export type ActivityLevel = "INFO" | "WARNING" | "ERROR";
diff --git a/frontend/src/utils/activity.ts b/frontend/src/utils/activity.ts
index 4dbdc20c29..c35eb688a1 100644
--- a/frontend/src/utils/activity.ts
+++ b/frontend/src/utils/activity.ts
@@ -4,6 +4,7 @@ import {
ActionIssueFieldUpdatePayload,
ActionIssueStatusUpdatePayload,
Activity,
+ ActivityType,
} from "../types";
let store: Store<any>;
@@ -12,6 +13,31 @@ export function registerStoreWithActivityUtil(theStore: Store<any>) {
store = theStore;
}
+export function activityName(type: ActivityType): string {
+ switch (type) {
+ case "bb.issue.create":
+ return "Create issue";
+ case "bb.issue.comment.create":
+ return "Create comment";
+ case "bb.issue.field.update":
+ return "Update issue field";
+ case "bb.issue.status.update":
+ return "Update issue status";
+ case "bb.pipeline.task.status.update":
+ return "Update issue task status";
+ case "bb.member.create":
+ return "Create member";
+ case "bb.member.role.update":
+ return "Update role";
+ case "bb.member.activate":
+ return "Activate member";
+ case "bb.member.deactivate":
+ return "Deactivate member";
+ case "bb.project.repository.push":
+ return "Repository push event";
+ }
+}
+
export function issueActivityActionSentence(activity: Activity): string {
switch (activity.actionType) {
case "bb.issue.create":
diff --git a/frontend/src/views/ProjectDetail.vue b/frontend/src/views/ProjectDetail.vue
index 51833904ad..1b1f742150 100644
--- a/frontend/src/views/ProjectDetail.vue
+++ b/frontend/src/views/ProjectDetail.vue
@@ -13,6 +13,9 @@
:databaseList="databaseList"
/>
</template>
+ <template v-if="selectedTab == ACTIVITY_TAB">
+ <ProjectActivityPanel id="activity" :project="project" />
+ </template>
<template v-else-if="selectedTab == VERSION_CONTROL_TAB">
<ProjectVersionControlPanel
id="version-control"
@@ -39,7 +42,8 @@
<script lang="ts">
import { computed, watchEffect } from "vue";
import { useStore } from "vuex";
-import { idFromSlug, isProjectOwner, sortDatabaseList } from "../utils";
+import { idFromSlug, sortDatabaseList } from "../utils";
+import ProjectActivityPanel from "../components/ProjectActivityPanel.vue";
import ProjectMigrationHistoryPanel from "../components/ProjectMigrationHistoryPanel.vue";
import ProjectOverviewPanel from "../components/ProjectOverviewPanel.vue";
import ProjectVersionControlPanel from "../components/ProjectVersionControlPanel.vue";
@@ -49,13 +53,15 @@ import { cloneDeep } from "lodash";
const OVERVIEW_TAB = 0;
const MIGRATION_HISTORY_TAB = 1;
-const VERSION_CONTROL_TAB = 2;
-const PROJECT_HOOK_TAB = 3;
-const SETTING_TAB = 4;
+const ACTIVITY_TAB = 2;
+const VERSION_CONTROL_TAB = 3;
+const PROJECT_HOOK_TAB = 4;
+const SETTING_TAB = 5;
export default {
name: "ProjectDetail",
components: {
+ ProjectActivityPanel,
ProjectMigrationHistoryPanel,
ProjectOverviewPanel,
ProjectVersionControlPanel,
@@ -105,6 +111,7 @@ export default {
return {
OVERVIEW_TAB,
MIGRATION_HISTORY_TAB,
+ ACTIVITY_TAB,
VERSION_CONTROL_TAB,
PROJECT_HOOK_TAB,
SETTING_TAB,
diff --git a/server/activity.go b/server/activity.go
index 5ae393d535..8010c119eb 100644
--- a/server/activity.go
+++ b/server/activity.go
@@ -65,14 +65,20 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
g.GET("/activity", func(c echo.Context) error {
activityFind := &api.ActivityFind{}
- containerIdStr := c.QueryParams().Get("container")
- if containerIdStr != "" {
+ if containerIdStr := c.QueryParams().Get("container"); containerIdStr != "" {
containerId, err := strconv.Atoi(containerIdStr)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Query parameter container is not a number: %s", containerIdStr)).SetInternal(err)
}
activityFind.ContainerId = &containerId
}
+ if limitStr := c.QueryParam("limit"); limitStr != "" {
+ limit, err := strconv.Atoi(limitStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Query parameter limit is not a number: %s", limitStr)).SetInternal(err)
+ }
+ activityFind.Limit = &limit
+ }
list, err := s.ActivityService.FindActivityList(context.Background(), activityFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch activity list").SetInternal(err)
diff --git a/server/webhook.go b/server/webhook.go
index 318217f339..e615ade473 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -78,9 +78,58 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
continue
}
+ createdTime, err := time.Parse(time.RFC3339, commit.Timestamp)
+ if err != nil {
+ s.l.Warn("Failed to parse timestamp. Skip", zap.String("file", added), zap.Error(err))
+ }
+ vcsPushEvent := common.VCSPushEvent{
+ VCSType: repository.VCS.Type,
+ BaseDirectory: repository.BaseDirectory,
+ Ref: pushEvent.Ref,
+ RepositoryID: strconv.Itoa(pushEvent.Project.ID),
+ RepositoryURL: pushEvent.Project.WebURL,
+ RepositoryFullPath: pushEvent.Project.FullPath,
+ AuthorName: pushEvent.AuthorName,
+ FileCommit: common.VCSFileCommit{
+ ID: commit.ID,
+ Title: commit.Title,
+ Message: commit.Message,
+ CreatedTs: createdTime.Unix(),
+ URL: commit.URL,
+ AuthorName: commit.Author.Name,
+ Added: added,
+ },
+ }
+
mi, err := db.ParseMigrationInfo(added, repository.BaseDirectory)
if err != nil {
s.l.Warn("Invalid migration filename. Skip", zap.String("file", added), zap.Error(err))
+
+ // Create a WARNING project activity if the committed file path doesn't match the expected pattern
+ {
+ bytes, err := json.Marshal(api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: vcsPushEvent,
+ Error: err.Error(),
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
+ }
+
+ activityCreate := &api.ActivityCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ ContainerId: repository.ProjectId,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ACTIVITY_WARNING,
+ Payload: string(bytes),
+ }
+ _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ if err != nil {
+ return echo.NewHTTPError(
+ http.StatusInternalServerError,
+ "Failed to create project activity to record mismatch between committed file and expected pattern.").SetInternal(err)
+ }
+ }
+
continue
}
@@ -184,29 +233,6 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
// Compose the new issue
- createdTime, err := time.Parse(time.RFC3339, commit.Timestamp)
- if err != nil {
- s.l.Warn("Failed to parse timestamp. Skip", zap.String("file", added), zap.Error(err))
- }
- vcsPushEvent := common.VCSPushEvent{
- VCSType: repository.VCS.Type,
- BaseDirectory: repository.BaseDirectory,
- Ref: pushEvent.Ref,
- RepositoryID: strconv.Itoa(pushEvent.Project.ID),
- RepositoryURL: pushEvent.Project.WebURL,
- RepositoryFullPath: pushEvent.Project.FullPath,
- AuthorName: pushEvent.AuthorName,
- FileCommit: common.VCSFileCommit{
- ID: commit.ID,
- Title: commit.Title,
- Message: commit.Message,
- CreatedTs: createdTime.Unix(),
- URL: commit.URL,
- AuthorName: commit.Author.Name,
- Added: added,
- },
- }
-
stageList := []api.StageCreate{}
for _, database := range filterdDatabaseList {
databaseID := database.ID
@@ -248,7 +274,30 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
zap.String("file", added))
continue
}
+
createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue %q on adding %s", issue.Name, added))
+
+ // Create a project activity after sucessfully creating the issue as the result of the push event
+ {
+ bytes, err := json.Marshal(api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: vcsPushEvent,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
+ }
+
+ activityCreate := &api.ActivityCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ ContainerId: repository.ProjectId,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ACTIVITY_INFO,
+ Payload: string(bytes),
+ }
+ _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)
+ }
+ }
}
}
diff --git a/store/activity.go b/store/activity.go
index 05ad7a75ef..5a52064f60 100644
--- a/store/activity.go
+++ b/store/activity.go
@@ -184,7 +184,7 @@ func findActivityList(ctx context.Context, tx *Tx, find *api.ActivityFind) (_ []
where, args = append(where, "container_id = ?"), append(args, *v)
}
- rows, err := tx.QueryContext(ctx, `
+ var query = `
SELECT
id,
creator_id,
@@ -192,12 +192,17 @@ func findActivityList(ctx context.Context, tx *Tx, find *api.ActivityFind) (_ []
updater_id,
updated_ts,
container_id,
- `+"`type`,"+`
- `+"`level`,"+`
+ ` + "`type`," + `
+ ` + "`level`," + `
comment,
payload
FROM activity
- WHERE `+strings.Join(where, " AND "),
+ WHERE ` + strings.Join(where, " AND ")
+ if v := find.Limit; v != nil {
+ query += fmt.Sprintf(" ORDER BY updated_ts DESC LIMIT %d", *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, query,
args...,
)
if err != nil {