feat(v2.7): 接入协作治理前端体验

This commit is contained in:
2026-07-08 16:31:06 +08:00
parent bcbe84bb6e
commit 9ba9449c1a
23 changed files with 987 additions and 2 deletions

View File

@@ -0,0 +1,79 @@
'use client';
import { create } from 'zustand';
import { api } from '@/lib/api';
import type { CommentEntityType } from '@/components/comment/CommentPanel';
export interface CommentRecord {
id: string;
entityType: CommentEntityType;
entityId: string;
entityVersionId?: string | null;
authorId: string;
content: string;
mentionedMemberIds?: string[];
createdAt: string;
deletedAt?: string | null;
}
interface CreateCommentInput {
actorId: string;
entityType: CommentEntityType;
entityId: string;
entityVersionId?: string | null;
productId?: string | null;
projectId?: string | null;
versionId?: string | null;
content: string;
mentionMemberIds?: string[];
}
interface CommentState {
commentsByKey: Record<string, CommentRecord[]>;
loadingKeys: string[];
fetchComments: (entityType: CommentEntityType, entityId: string) => Promise<void>;
createComment: (input: CreateCommentInput) => Promise<void>;
deleteComment: (entityType: CommentEntityType, entityId: string, id: string, actorId: string) => Promise<void>;
}
export function commentKey(entityType: CommentEntityType, entityId: string) {
return `${entityType}:${entityId}`;
}
export const useCommentStore = create<CommentState>((set, get) => ({
commentsByKey: {},
loadingKeys: [],
fetchComments: async (entityType, entityId) => {
const key = commentKey(entityType, entityId);
set({ loadingKeys: [...get().loadingKeys.filter((item) => item !== key), key] });
const params = new URLSearchParams({ entityType, entityId });
const rows = await api.get<CommentRecord[]>(`/comments?${params.toString()}`);
set({
commentsByKey: { ...get().commentsByKey, [key]: rows },
loadingKeys: get().loadingKeys.filter((item) => item !== key),
});
},
createComment: async (input) => {
const row = await api.post<CommentRecord>('/comments', input);
const key = commentKey(input.entityType, input.entityId);
set({
commentsByKey: {
...get().commentsByKey,
[key]: [...(get().commentsByKey[key] ?? []), row],
},
});
},
deleteComment: async (entityType, entityId, id, actorId) => {
const row = await api.deleteWithBody<CommentRecord>(`/comments/${id}`, { actorId });
const key = commentKey(entityType, entityId);
set({
commentsByKey: {
...get().commentsByKey,
[key]: (get().commentsByKey[key] ?? []).map((item) => item.id === id ? row : item).filter((item) => !item.deletedAt),
},
});
},
}));

View File

@@ -0,0 +1,52 @@
'use client';
import { create } from 'zustand';
import { api } from '@/lib/api';
import { countUnreadNotifications, sortNotificationsNewestFirst, type NotificationRecord } from '@/lib/notification';
interface NotificationState {
notifications: NotificationRecord[];
loading: boolean;
loadedFor?: string;
unreadCount: number;
fetchNotifications: (recipientId: string, options?: { unreadOnly?: boolean }) => Promise<void>;
markRead: (id: string, recipientId: string) => Promise<void>;
markAllRead: (recipientId: string) => Promise<void>;
}
export const useNotificationStore = create<NotificationState>((set, get) => ({
notifications: [],
loading: false,
loadedFor: undefined,
unreadCount: 0,
fetchNotifications: async (recipientId, options) => {
if (!recipientId) return;
set({ loading: true });
const params = new URLSearchParams({ recipientId });
if (options?.unreadOnly) params.set('unreadOnly', 'true');
const rows = await api.get<NotificationRecord[]>(`/notifications?${params.toString()}`);
const notifications = sortNotificationsNewestFirst(rows);
set({
notifications,
unreadCount: countUnreadNotifications(notifications),
loadedFor: recipientId,
loading: false,
});
},
markRead: async (id, recipientId) => {
await api.patch(`/notifications/${id}/read`, { recipientId });
const notifications = get().notifications.map((item) =>
item.id === id ? { ...item, readAt: item.readAt ?? new Date().toISOString() } : item,
);
set({ notifications, unreadCount: countUnreadNotifications(notifications) });
},
markAllRead: async (recipientId) => {
await api.patch('/notifications/read-all', { recipientId });
const readAt = new Date().toISOString();
const notifications = get().notifications.map((item) => item.readAt ? item : { ...item, readAt });
set({ notifications, unreadCount: 0 });
},
}));

View File

@@ -1,6 +1,8 @@
'use client';
import { create } from 'zustand';
import { loadServerData, saveServerData, SERVER_DATA_CACHE_MS } from '@/lib/server-data';
import { api } from '@/lib/api';
import { useMemberStore } from './useMemberStore';
import {
mergeDailySnapshotCacheForSave,
mergeInsightCacheForSave,
@@ -74,6 +76,7 @@ export const useXiaobaoRiskStore = create<XiaobaoRiskState>((set, get) => ({
const snapshots = mergeDailySnapshotCacheForSave(get().snapshots, Array.isArray(remote) ? remote : [], item);
set({ snapshots, error: undefined });
await saveServerData('xiaobao-risk-snapshots', snapshots);
void notifyRiskManagers(item).catch(() => {});
});
snapshotSaveQueue = task.catch(() => undefined);
try {
@@ -119,3 +122,32 @@ export const useXiaobaoRiskStore = create<XiaobaoRiskState>((set, get) => ({
set({ pendingInsightKeys: get().pendingInsightKeys.filter((item) => item !== key) });
},
}));
async function notifyRiskManagers(item: XiaobaoRiskSnapshot) {
if (!['at_risk', 'likely_delayed', 'blocked'].includes(item.riskLevel)) return;
const memberStore = useMemberStore.getState();
if (!memberStore.loaded) {
await memberStore.fetchMembers().catch(() => undefined);
}
const state = useMemberStore.getState();
const roleMap = new Map(state.roles.map((role) => [role.id, role]));
const recipients = state.members.filter((member) => {
const permissions = roleMap.get(member.roleId)?.permissions ?? [];
return permissions.includes('*') || permissions.includes('xiaobao.warning:manage');
});
await Promise.all(recipients.map((member) => api.post('/notifications', {
recipientId: member.id,
actorId: 'xiaobao',
type: 'risk_alert',
title: '小宝预警更新',
body: `版本 ${item.versionId} 当前风险 ${item.riskLevel},风险分 ${item.riskScore}`,
resourceType: 'version',
resourceId: item.versionId,
versionId: item.versionId,
metadata: {
riskLevel: item.riskLevel,
riskScore: item.riskScore,
riskSignature: `${item.versionId}:${item.date}:${item.riskScore}:${item.riskLevel}`,
},
}).catch(() => undefined)));
}