Skip to content

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

Introduce message model and use it for Inbox

天舟1789a9a67b63
diff --git a/frontend/src/components/ProvideContext.vue b/frontend/src/components/ProvideContext.vue
index ff9c8f632c..8285c24b56 100644
--- a/frontend/src/components/ProvideContext.vue
+++ b/frontend/src/components/ProvideContext.vue
@@ -4,6 +4,7 @@
<script lang="ts">
import { useStore } from "vuex";
+import { Principal } from "../types";
export default {
name: "ProvideContext",
@@ -37,8 +38,11 @@ export default {
]);
// Refresh the user after fetchRoleMappingList / fetchPrincipalList.
- // The user info may change remoted and thus we need to refresh both in-memory and local cache state.
- store.dispatch("auth/refreshUser");
+ // The user info may change remotely and thus we need to refresh both in-memory and local cache state.
+ store.dispatch("auth/refreshUser").then((currentUser: Principal) => {
+ // In order to display the empty/non-empty inbox icon on the sidebar properly.
+ store.dispatch("message/fetchMessageListByUser", currentUser.id);
+ });
},
};
</script>
diff --git a/frontend/src/miragejs/factories/index.js b/frontend/src/miragejs/factories/index.js
index 8997dd9b85..d7e92ab50a 100644
--- a/frontend/src/miragejs/factories/index.js
+++ b/frontend/src/miragejs/factories/index.js
@@ -10,6 +10,8 @@ import task from "./task";
import taskPatch from "./taskPatch";
import activity from "./activity";
import activityPatch from "./activityPatch";
+import message from "./message";
+import messagePatch from "./messagePatch";
import workspace from "./workspace";
import roleMapping from "./roleMapping";
@@ -32,6 +34,8 @@ export default {
...dataSourceMember,
...database,
...databasePatch,
+ ...message,
+ ...messagePatch,
...task,
...taskPatch,
...activity,
diff --git a/frontend/src/miragejs/factories/message.js b/frontend/src/miragejs/factories/message.js
new file mode 100644
index 0000000000..e1214c6e64
--- /dev/null
+++ b/frontend/src/miragejs/factories/message.js
@@ -0,0 +1,37 @@
+import { Factory } from "miragejs";
+import faker from "faker";
+
+export default {
+ message: Factory.extend({
+ createdTs(i) {
+ return Date.now() - (10 - i) * 1800 * 1000;
+ },
+ lastUpdatedTs(i) {
+ return Date.now() - (10 - i) * 1800 * 1000;
+ },
+ type() {
+ return "bb.msg.task.assign";
+ },
+ status(i) {
+ return i % 2 == 0 ? "DELIVERED" : "CONSUMED";
+ },
+ containerId() {
+ return "0";
+ },
+ creatorId() {
+ return "100";
+ },
+ receiverId() {
+ return "200";
+ },
+ name() {
+ return faker.fake("{{lorem.sentence}}");
+ },
+ description(i) {
+ return i % 3 == 0 ? "" : faker.fake("{{lorem.sentences}}");
+ },
+ payload() {
+ return {};
+ },
+ }),
+};
diff --git a/frontend/src/miragejs/factories/messagePatch.js b/frontend/src/miragejs/factories/messagePatch.js
new file mode 100644
index 0000000000..69fe14097a
--- /dev/null
+++ b/frontend/src/miragejs/factories/messagePatch.js
@@ -0,0 +1,9 @@
+import { Factory } from "miragejs";
+
+export default {
+ messagePatch: Factory.extend({
+ status() {
+ return "CONSUMED";
+ },
+ }),
+};
diff --git a/frontend/src/miragejs/models/index.js b/frontend/src/miragejs/models/index.js
index 938725b2af..23eb1f8340 100644
--- a/frontend/src/miragejs/models/index.js
+++ b/frontend/src/miragejs/models/index.js
@@ -17,6 +17,7 @@ export default {
workspace: Model.extend({
roleMapping: hasMany(),
activity: hasMany(),
+ message: hasMany(),
task: hasMany(),
environment: hasMany(),
instance: hasMany(),
@@ -36,6 +37,12 @@ export default {
activityPatch: Model,
+ message: Model.extend({
+ workspace: belongsTo(),
+ }),
+
+ messagePatch: Model,
+
task: Model.extend({
workspace: belongsTo(),
}),
diff --git a/frontend/src/miragejs/routes/index.js b/frontend/src/miragejs/routes/index.js
index 9856109dd6..95ac10773b 100644
--- a/frontend/src/miragejs/routes/index.js
+++ b/frontend/src/miragejs/routes/index.js
@@ -5,6 +5,7 @@ import configureUser from "./user";
import configureAuth from "./auth";
import configureRoleMapping from "./roleMapping";
import configureActivity from "./activity";
+import configureMessage from "./message";
import configureBookmark from "./bookmark";
import configureTask from "./task";
import configureEnvironment from "./environment";
@@ -33,6 +34,9 @@ export default function routes() {
// Activity
configureActivity(this);
+ // message
+ configureMessage(this);
+
// Bookmark
configureBookmark(this);
diff --git a/frontend/src/miragejs/routes/message.js b/frontend/src/miragejs/routes/message.js
new file mode 100644
index 0000000000..f0911fda23
--- /dev/null
+++ b/frontend/src/miragejs/routes/message.js
@@ -0,0 +1,29 @@
+import { WORKSPACE_ID } from "./index";
+
+export default function configureMessage(route) {
+ route.get("/message", function (schema, request) {
+ const {
+ queryParams: { user: userId },
+ } = request;
+ return schema.messages
+ .where((message) => {
+ return (
+ message.workspaceId == WORKSPACE_ID && message.receiverId == userId
+ );
+ })
+ .sort((a, b) => a.createdTs - b.createdTs);
+ });
+
+ route.patch("/message/:messageId", function (schema, request) {
+ const attrs = this.normalizedRequestAttrs("message-patch");
+ const message = schema.messages.find(request.params.messageId);
+ if (message) {
+ return message.update({ ...attrs, lastUpdatedTs: Date.now() });
+ }
+ return new Response(
+ 404,
+ {},
+ { errors: "Message " + request.params.messageId + " not found" }
+ );
+ });
+}
diff --git a/frontend/src/miragejs/seeds/index.ts b/frontend/src/miragejs/seeds/index.ts
index 3c46f11efe..81462f9432 100644
--- a/frontend/src/miragejs/seeds/index.ts
+++ b/frontend/src/miragejs/seeds/index.ts
@@ -142,6 +142,46 @@ const workspacesSeeder = (server: any) => {
workspace: workspace1,
});
+ for (let i = 0; i < 5; i++) {
+ server.create("message", {
+ type: "bb.msg.task.assign",
+ containerId: task.id,
+ creatorId: ws1UserList[Math.floor(Math.random() * ws1UserList.length)].id,
+ receiverId: ws1Owner.id,
+ workspace: workspace1,
+ });
+ }
+
+ for (let i = 0; i < 5; i++) {
+ server.create("message", {
+ type: "bb.msg.task.assign",
+ containerId: task.id,
+ creatorId: ws1UserList[Math.floor(Math.random() * ws1UserList.length)].id,
+ receiverId: ws1DBA.id,
+ workspace: workspace1,
+ });
+ }
+
+ for (let i = 0; i < 5; i++) {
+ server.create("message", {
+ type: "bb.msg.task.assign",
+ containerId: task.id,
+ creatorId: ws1UserList[Math.floor(Math.random() * ws1UserList.length)].id,
+ receiverId: ws1Dev1.id,
+ workspace: workspace1,
+ });
+ }
+
+ for (let i = 0; i < 5; i++) {
+ server.create("message", {
+ type: "bb.msg.task.assign",
+ containerId: task.id,
+ creatorId: ws2DBA.id,
+ receiverId: ws2Dev.id,
+ workspace: workspace2,
+ });
+ }
+
for (let i = 0; i < 3; i++) {
const user = ws1UserList[Math.floor(Math.random() * ws1UserList.length)];
server.create("activity", {
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 7b8ff4c451..8c9bd49bea 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -2,6 +2,7 @@ import { createStore, Store } from "vuex";
// Following states are persisted in database
import activity from "./modules/activity";
+import message from "./modules/message";
import bookmark from "./modules/bookmark";
import roleMapping from "./modules/roleMapping";
import environment from "./modules/environment";
@@ -26,6 +27,7 @@ const debug = import.meta.env.NODE_ENV !== "production";
export const store: Store<any> = createStore({
modules: {
activity,
+ message,
bookmark,
roleMapping,
environment,
diff --git a/frontend/src/store/modules/message.ts b/frontend/src/store/modules/message.ts
new file mode 100644
index 0000000000..3536597adb
--- /dev/null
+++ b/frontend/src/store/modules/message.ts
@@ -0,0 +1,115 @@
+import axios from "axios";
+import {
+ UserId,
+ MessageId,
+ Message,
+ MessageNew,
+ MessageState,
+ ResourceObject,
+ MessageStatus,
+} from "../../types";
+
+function convert(message: ResourceObject, rootGetters: any): Message {
+ const creator = rootGetters["principal/principalById"](
+ message.attributes.creatorId
+ );
+ const receiver = rootGetters["principal/principalById"](
+ message.attributes.receiverId
+ );
+ return {
+ id: message.id,
+ creator,
+ receiver,
+ ...(message.attributes as Omit<Message, "id" | "creator" | "receiver">),
+ };
+}
+
+const state: () => MessageState = () => ({
+ messageListByUser: new Map(),
+});
+
+const getters = {
+ messageListByUser: (state: MessageState) => (userId: UserId): Message[] => {
+ return state.messageListByUser.get(userId) || [];
+ },
+};
+
+const actions = {
+ async fetchMessageListByUser({ commit, rootGetters }: any, userId: UserId) {
+ const messageList = (
+ await axios.get(`/api/message?user=${userId}`)
+ ).data.data.map((message: ResourceObject) => {
+ return convert(message, rootGetters);
+ });
+
+ commit("setMessageListByUser", { userId, messageList });
+ return messageList;
+ },
+
+ async updateStatus(
+ { commit, rootGetters }: any,
+ {
+ messageId,
+ updatedStatus,
+ }: { messageId: MessageId; updatedStatus: MessageStatus }
+ ) {
+ const updatedMessage = convert(
+ (
+ await axios.patch(`/api/message/${messageId}`, {
+ data: {
+ type: "messagepatch",
+ attributes: {
+ status: updatedStatus,
+ },
+ },
+ })
+ ).data.data,
+ rootGetters
+ );
+
+ commit("updateMessageById", { messageId, message: updatedMessage });
+
+ return updatedMessage;
+ },
+};
+
+const mutations = {
+ setMessageListByUser(
+ state: MessageState,
+ {
+ userId,
+ messageList,
+ }: {
+ userId: UserId;
+ messageList: Message[];
+ }
+ ) {
+ state.messageListByUser.set(userId, messageList);
+ },
+
+ updateMessageById(
+ state: MessageState,
+ {
+ messageId,
+ message,
+ }: {
+ messageId: MessageId;
+ message: Message;
+ }
+ ) {
+ for (let [_, messageList] of state.messageListByUser) {
+ const i = messageList.findIndex((item: Message) => item.id == messageId);
+ if (i >= 0) {
+ messageList[i] = message;
+ }
+ }
+ },
+};
+
+export default {
+ namespaced: true,
+ state,
+ getters,
+ actions,
+ mutations,
+};
diff --git a/frontend/src/types/bytebase.ts b/frontend/src/types/bytebase.ts
index 7f51db6c5f..8f247af35f 100644
--- a/frontend/src/types/bytebase.ts
+++ b/frontend/src/types/bytebase.ts
@@ -15,6 +15,7 @@ export type ResourceType =
| "DATA_SOURCE"
| "TASK"
| "ACTIVITY"
+ | "MESSAGE"
| "BOOKMARK";
// Returns as function to avoid caller accidentally mutate it.
@@ -31,6 +32,7 @@ export const unknown = (
| DataSource
| Task
| Activity
+ | Message
| Bookmark => {
const UNKNOWN_EXECUTION: Execution = {
id: UNKNOWN_ID,
@@ -123,6 +125,19 @@ export const unknown = (
comment: "<<Unknown comment>>",
};
+ const UNKNOWN_MESSAGE: Message = {
+ id: UNKNOWN_ID,
+ containerId: UNKNOWN_ID,
+ createdTs: 0,
+ lastUpdatedTs: 0,
+ type: "bb.msg.task.assign",
+ status: "DELIVERED",
+ creator: UNKNOWN_PRINCIPAL,
+ receiver: UNKNOWN_PRINCIPAL,
+ name: "<<Unknown message>>",
+ description: "",
+ };
+
const UNKNOWN_BOOKMARK: Bookmark = {
id: UNKNOWN_ID,
name: "",
@@ -151,6 +166,8 @@ export const unknown = (
return UNKNOWN_TASK;
case "ACTIVITY":
return UNKNOWN_ACTIVITY;
+ case "MESSAGE":
+ return UNKNOWN_MESSAGE;
case "BOOKMARK":
return UNKNOWN_BOOKMARK;
}
@@ -176,6 +193,8 @@ export type TaskId = string;
export type ActivityId = string;
+export type MessageId = string;
+
export type EnvironmentId = string;
export type InstanceId = string;
@@ -191,6 +210,11 @@ export const ALL_DATABASE_NAME: string = "*";
export type CommandId = string;
export type CommandRegisterId = string;
+// This references to the object id, which can be used as a container.
+// Currently, only task can be used a container.
+// The type is used by Activity and Message
+export type ContainerId = TaskId;
+
// Persistent State Models
export type ExecutionStatus = "PENDING" | "RUNNING" | "DONE" | "FAILED";
@@ -464,7 +488,7 @@ export type Activity = {
id: ActivityId;
// The object where this activity belongs
// e.g if actionType is "bytebase.task.xxx", then this field refers to the corresponding task's id.
- containerId: TaskId;
+ containerId: ContainerId;
createdTs: number;
lastUpdatedTs: number;
actionType: ActionType;
@@ -478,6 +502,33 @@ export type ActivityPatch = {
payload: any;
};
+// Message
+export type MessageType = "bb.msg.task.assign";
+
+export type MessagePayload = {};
+
+export type MessageStatus = "DELIVERED" | "CONSUMED";
+
+export type Message = {
+ id: MessageId;
+ // The object where this message belongs
+ containerId: ContainerId;
+ createdTs: number;
+ lastUpdatedTs: number;
+ type: MessageType;
+ status: MessageStatus;
+ creator: Principal;
+ receiver: Principal;
+ name: string;
+ description: string;
+ payload?: MessagePayload;
+};
+export type MessageNew = Omit<Message, "id" | "createdTs" | "lastUpdatedTs">;
+
+export type MessagePatch = {
+ status: MessageStatus;
+};
+
// Environment
export type Environment = {
id: EnvironmentId;
@@ -691,6 +742,10 @@ export interface ActivityState {
activityListByTask: Map<TaskId, Activity[]>;
}
+export interface MessageState {
+ messageListByUser: Map<UserId, Message[]>;
+}
+
export interface TaskState {
// [NOTE] This is only used by the task list view. We don't
// update the entry here if any task is changed (the updated task only gets updated in taskById).
diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vue
index f12da5194c..5293d120ae 100644
--- a/frontend/src/views/DashboardHeader.vue
+++ b/frontend/src/views/DashboardHeader.vue
@@ -91,30 +91,6 @@
Developer
</div>
</div>
- <router-link
- v-if="false"
- to="/inbox"
- class="icon-link p-1 rounded-full"
- >
- <span class="sr-only">View Inbox</span>
- <!-- Heroicon name: bell -->
- <svg
- class="h-6 w-6"
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- aria-hidden="true"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
- />
- </svg>
- </router-link>
-
<div class="ml-2">
<ProfileDropdown />
</div>
diff --git a/frontend/src/views/DashboardSidebar.vue b/frontend/src/views/DashboardSidebar.vue
index 23dbfa64f9..fbfdca4c41 100644
--- a/frontend/src/views/DashboardSidebar.vue
+++ b/frontend/src/views/DashboardSidebar.vue
@@ -28,7 +28,16 @@
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
+ <template v-if="hasUnreadMessage">
+ <path
+ d="M8.707 7.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l2-2a1 1 0 00-1.414-1.414L11 7.586V3a1 1 0 10-2 0v4.586l-.293-.293z"
+ ></path>
+ <path
+ d="M3 5a2 2 0 012-2h1a1 1 0 010 2H5v7h2l1 2h4l1-2h2V5h-1a1 1 0 110-2h1a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V5z"
+ ></path>
+ </template>
<path
+ v-else
fill-rule="evenodd"
d="M5 3a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2V5a2 2 0 00-2-2H5zm0 2h10v7h-2l-1 2H8l-1-2H5V5z"
clip-rule="evenodd"
@@ -50,9 +59,11 @@
</template>
<script lang="ts">
-import { reactive } from "vue";
+import { computed } from "vue";
+import { useStore } from "vuex";
import BookmarkListSidePanel from "../components/BookmarkListSidePanel.vue";
import DatabaseListSidePanel from "../components/DatabaseListSidePanel.vue";
+import { Message } from "../types";
interface LocalState {
hasUnreadMessage: boolean;
@@ -66,12 +77,21 @@ export default {
DatabaseListSidePanel,
},
setup(props, ctx) {
- const state = reactive<LocalState>({
- hasUnreadMessage: Math.random() > 0.5,
+ const store = useStore();
+
+ const currentUser = computed(() => store.getters["auth/currentUser"]());
+
+ const hasUnreadMessage = computed(() => {
+ const list = store.getters["message/messageListByUser"](
+ currentUser.value.id
+ );
+ return list.find((item: Message) => {
+ return item.status == "DELIVERED";
+ });
});
return {
- state,
+ hasUnreadMessage,
};
},
};
diff --git a/frontend/src/views/Inbox.vue b/frontend/src/views/Inbox.vue
index ee9fdb2ba5..4a54a3b958 100644
--- a/frontend/src/views/Inbox.vue
+++ b/frontend/src/views/Inbox.vue
@@ -1,11 +1,160 @@
<template>
- <h1>Inbox</h1>
+ <!-- This example requires Tailwind CSS v2.0+ -->
+ <div class="mx-4">
+ <div class="px-4 py-2 flex justify-between">
+ <BBSwitch
+ :label="'Display all messages'"
+ :value="state.showAll"
+ @toggle="
+ (on) => {
+ showAll(on);
+ }
+ "
+ />
+ <button type="button" class="btn-normal" @click.prevent="markAllAsRead">
+ <!-- Heroicon name: solid/pencil -->
+ <svg
+ class="-ml-1 mr-2 h-5 w-5 text-control-light"
+ fill="currentColor"
+ viewBox="0 0 20 20"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"
+ ></path>
+ </svg>
+ <span>Mark all as read</span>
+ </button>
+ </div>
+ <ul class="divide-y divide-block-border">
+ <li
+ v-for="(message, index) in effectiveMessageList"
+ :key="index"
+ class="p-4 hover:bg-control-bg-hover cursor-pointer"
+ @click.prevent="clickItem(message)"
+ >
+ <div class="flex items-top space-x-3">
+ <BBAvatar :username="message.creator.name" />
+ <div class="flex-1 space-y-1">
+ <div class="flex items-center justify-between">
+ <h3 class="text-sm text-control flex flex-row">
+ {{ message.creator.name }}
+ <span class="text-sm font-medium text-main ml-1">{{
+ message.name
+ }}</span>
+ <span
+ v-if="message.status == 'DELIVERED'"
+ class="ml-2 mt-1 h-3 w-3 rounded-full bg-accent"
+ ></span>
+ </h3>
+ <p class="text-sm text-control">
+ {{ humanizeTs(message.createdTs) }}
+ </p>
+ </div>
+ <div class="text-sm text-control">
+ {{ message.description }}
+ </div>
+ </div>
+ </div>
+ </li>
+ <!-- More items... -->
+ </ul>
+ </div>
</template>
<script lang="ts">
+import { computed, onMounted, reactive, watchEffect } from "vue";
+import { useStore } from "vuex";
+import { Message } from "../types";
+
+interface LocalState {
+ showAll: boolean;
+ messageList: Message[];
+ // To maintain a stable view when user clicks an item.
+ // When user clicks an item, we will set the item as "CONSUMED".
+ // Without this logic, if the user stays on the display unread item view,
+ // that item will suddenly be removed from the list, which is not ideal for UX.
+ whitelist: Message[];
+}
+
export default {
name: "Inbox",
components: {},
- setup(props, ctx) {},
+ setup(props, ctx) {
+ const store = useStore();
+
+ const state = reactive<LocalState>({
+ showAll: false,
+ messageList: [],
+ whitelist: [],
+ });
+
+ const currentUser = computed(() => store.getters["auth/currentUser"]());
+
+ const prepareMessageList = () => {
+ store
+ .dispatch("message/fetchMessageListByUser", currentUser.value.id)
+ .then((list: Message[]) => {
+ state.messageList = list;
+ })
+ .catch((error) => {
+ console.log(error);
+ });
+ };
+
+ watchEffect(prepareMessageList);
+
+ onMounted(() => {
+ state.whitelist = [];
+ });
+
+ const effectiveMessageList = computed(() => {
+ return state.showAll
+ ? state.messageList
+ : state.messageList.filter((message: Message) => {
+ return (
+ message.status == "DELIVERED" ||
+ state.whitelist.find((item: Message) => {
+ return item.id == message.id;
+ })
+ );
+ });
+ });
+
+ const clickItem = (item: Message) => {
+ if (item.status == "DELIVERED") {
+ state.whitelist.push(item);
+ store.dispatch("message/updateStatus", {
+ messageId: item.id,
+ updatedStatus: "CONSUMED",
+ });
+ }
+ };
+
+ const showAll = (show: boolean) => {
+ state.whitelist = [];
+ state.showAll = show;
+ };
+
+ const markAllAsRead = () => {
+ state.messageList.forEach((item: Message) => {
+ if (item.status == "DELIVERED") {
+ state.whitelist.push(item);
+ store.dispatch("message/updateStatus", {
+ messageId: item.id,
+ updatedStatus: "CONSUMED",
+ });
+ }
+ });
+ };
+
+ return {
+ state,
+ effectiveMessageList,
+ clickItem,
+ showAll,
+ markAllAsRead,
+ };
+ },
};
</script>