refactor(frontend): 按需加载页面并清理未使用代码
- 将业务页面路由统一改为动态导入,拆分首屏入口与各功能模块构建产物。 - 将网页端和桌面端布局改为异步组件,避免两套平台布局同时进入初始包。 - 新增 Element Plus 按需安装入口,并通过全局配置组件统一注入中文语言包。 - 提取 API 运行时钩子,在应用启动时注入项目清理、令牌续期和认证失效退出能力。 - 将权限监控面板及地图资源改为延迟加载,补充地图加载状态、失败提示和切换竞态保护。 - 删除已被现有工作流替代的项目成员、接口权限、中心绑定、培训表单及旧项目首页等页面。 - 清理废弃的快捷操作、项目选择、用户选择、FAQ 表单、风险占位组件和旧地图辅助模块。 - 移除未使用的 API 方法、类型、字典、状态机、展示工具、样式和项目详情编辑逻辑。 - 开启 TypeScript 未使用变量与参数检查,并同步收紧相关测试和组件暴露类型。 - 移除未使用的 updater、date-fns 和 Sass 前端依赖,更新锁文件并删除旧 CSS 清洗插件。 - 更新路由、Axios、ETMF、通知、权限监控和桌面布局测试以覆盖重构后的边界。
This commit is contained in:
Generated
-898
File diff suppressed because it is too large
Load Diff
@@ -34,9 +34,7 @@
|
||||
"@tauri-apps/plugin-fs": "^2.4.0",
|
||||
"@tauri-apps/plugin-notification": "^2.3.0",
|
||||
"@tauri-apps/plugin-opener": "^2.5.0",
|
||||
"@tauri-apps/plugin-updater": "^2.9.0",
|
||||
"axios": "^1.6.8",
|
||||
"date-fns": "^3.6.0",
|
||||
"echarts": "^6.0.0",
|
||||
"element-plus": "^2.4.4",
|
||||
"pdfjs-dist": "6.1.200",
|
||||
@@ -51,7 +49,6 @@
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
"jsdom": "^26.1.0",
|
||||
"sass-embedded": "^1.77.0",
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^7.3.1",
|
||||
"vitest": "^3.2.4",
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<template>
|
||||
<el-config-provider :locale="zhCn">
|
||||
<div class="app-shell">
|
||||
<router-view />
|
||||
<SessionTimeoutPrompt />
|
||||
</div>
|
||||
</el-config-provider>
|
||||
<!-- TODO: 预留聚合接口页面:/study/{id}/overview /subjects/{id}/detail /sites/{id}/summary -->
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import zhCn from "element-plus/es/locale/lang/zh-cn";
|
||||
import { initSessionManager } from "./session/sessionManager";
|
||||
import { initDesktopNotificationManager } from "./session/desktopNotificationManager";
|
||||
import { initDesktopUpdateManager } from "./session/desktopUpdateManager";
|
||||
|
||||
@@ -39,12 +39,6 @@ export type SessionHeartbeatResponse = {
|
||||
client_ip: string | null;
|
||||
};
|
||||
|
||||
export type EncryptedPasswordRequest = {
|
||||
key_id: string;
|
||||
challenge: string;
|
||||
ciphertext: string;
|
||||
};
|
||||
|
||||
export const extendToken = (token: string): Promise<AxiosResponse<ExtendResponse>> =>
|
||||
authClient.post<ExtendResponse>(
|
||||
"/api/v1/auth/extend",
|
||||
|
||||
@@ -9,28 +9,10 @@ vi.mock("element-plus", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../router", () => ({
|
||||
default: {
|
||||
push: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils/auth", () => ({
|
||||
getToken: vi.fn(() => undefined),
|
||||
}));
|
||||
|
||||
vi.mock("../store/study", () => ({
|
||||
useStudyStore: vi.fn(() => ({
|
||||
clearCurrentStudy: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../session/sessionManager", () => ({
|
||||
extendAccessToken: vi.fn(),
|
||||
forceLogout: vi.fn(),
|
||||
LOGOUT_REASON_AUTH_EXPIRED: "auth-expired",
|
||||
}));
|
||||
|
||||
describe("api axios retry", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
@@ -4,6 +4,11 @@ import { getToken } from "../utils/auth";
|
||||
import type { ApiError } from "../types/api";
|
||||
import { TEXT } from "../locales";
|
||||
import { clientRuntime, DESKTOP_SERVER_URL_CHANGED_EVENT, getAppMetadataHeaders } from "../runtime";
|
||||
import {
|
||||
clearInvalidStudyAndNavigate,
|
||||
extendAccessTokenAfterUnauthorized,
|
||||
forceAuthExpiredLogout,
|
||||
} from "./runtimeHooks";
|
||||
|
||||
const instance: AxiosInstance = axios.create({
|
||||
baseURL: clientRuntime.apiBaseUrl(),
|
||||
@@ -204,24 +209,6 @@ if (typeof window !== "undefined") {
|
||||
});
|
||||
}
|
||||
|
||||
const clearInvalidStudyAndNavigate = async () => {
|
||||
try {
|
||||
const [{ useStudyStore }, { default: router }] = await Promise.all([
|
||||
import("../store/study"),
|
||||
import("../router"),
|
||||
]);
|
||||
useStudyStore().clearCurrentStudy();
|
||||
router.push("/admin/projects");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const forceAuthExpiredLogout = async () => {
|
||||
const { forceLogout, LOGOUT_REASON_AUTH_EXPIRED } = await import("../session/sessionManager");
|
||||
await forceLogout(LOGOUT_REASON_AUTH_EXPIRED);
|
||||
};
|
||||
|
||||
instance.interceptors.request.use((config: InternalAxiosRequestConfig & ApiRequestConfig) => {
|
||||
config.headers = config.headers || {};
|
||||
Object.assign(config.headers, getAppMetadataHeaders());
|
||||
@@ -265,8 +252,7 @@ instance.interceptors.response.use(
|
||||
const config = error.config as ApiRequestConfig;
|
||||
let clearedCacheForAuthFailure = false;
|
||||
if (config && !config._retry) {
|
||||
const { extendAccessToken } = await import("../session/sessionManager");
|
||||
const result = await extendAccessToken("response-401");
|
||||
const result = await extendAccessTokenAfterUnauthorized();
|
||||
if (result.token) {
|
||||
config._retry = true;
|
||||
config.headers = config.headers || {};
|
||||
@@ -276,7 +262,6 @@ instance.interceptors.response.use(
|
||||
if (result.authFailed) {
|
||||
clearApiResponseCache();
|
||||
clearedCacheForAuthFailure = true;
|
||||
await forceAuthExpiredLogout();
|
||||
}
|
||||
}
|
||||
if (!clearedCacheForAuthFailure) {
|
||||
|
||||
@@ -39,15 +39,6 @@ describe("collaboration API", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("records a completed Save As operation for audit", async () => {
|
||||
const { recordCollaborationExport } = await import("./collaboration");
|
||||
recordCollaborationExport("study-1", "file-1", "xlsx");
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
"/api/v1/studies/study-1/collaboration/files/file-1/exports",
|
||||
{ file_type: "xlsx" },
|
||||
);
|
||||
});
|
||||
|
||||
it("records a completed local download separately from workspace Save As", async () => {
|
||||
const { recordCollaborationDownload } = await import("./collaboration");
|
||||
recordCollaborationDownload("study-1", "file-1", "xlsx");
|
||||
|
||||
@@ -161,9 +161,6 @@ export const fetchCollaborationEditorConfig = (studyId: string, fileId: string)
|
||||
suppressErrorMessage: true,
|
||||
});
|
||||
|
||||
export const recordCollaborationExport = (studyId: string, fileId: string, fileType: string) =>
|
||||
apiPost(`${baseUrl(studyId)}/files/${fileId}/exports`, { file_type: fileType });
|
||||
|
||||
export const recordCollaborationDownload = (studyId: string, fileId: string, fileType: string) =>
|
||||
apiPost(`${baseUrl(studyId)}/files/${fileId}/downloads`, { file_type: fileType });
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import { apiGet } from "./axios";
|
||||
import type { ApiListResponse } from "../types/api";
|
||||
|
||||
import { VisitLostItem } from "../types/visits";
|
||||
|
||||
export interface CenterSummaryItem {
|
||||
id: string;
|
||||
name: string;
|
||||
stage: string;
|
||||
stage_status?: string;
|
||||
actual_enrolled: number;
|
||||
planned_enrolled: number;
|
||||
}
|
||||
|
||||
export const fetchProgress = (studyId: string) =>
|
||||
apiGet(`/api/v1/studies/${studyId}/dashboard/progress`, {
|
||||
cache: { ttlMs: 30_000, tags: [`study:${studyId}`, `study:${studyId}:dashboard`] },
|
||||
});
|
||||
|
||||
export const fetchFinanceSummary = (studyId: string) =>
|
||||
apiGet(`/api/v1/studies/${studyId}/finance/summary`, {
|
||||
cache: { ttlMs: 30_000, tags: [`study:${studyId}`, `study:${studyId}:dashboard`, `study:${studyId}:finance`] },
|
||||
});
|
||||
|
||||
export const fetchOverdueAesCount = (studyId: string) =>
|
||||
apiGet<ApiListResponse<any>>(`/api/v1/studies/${studyId}/aes/`, {
|
||||
params: { overdue: true, limit: 1 },
|
||||
cache: { ttlMs: 30_000, tags: [`study:${studyId}`, `study:${studyId}:dashboard`, `study:${studyId}:aes`] },
|
||||
});
|
||||
|
||||
export const fetchLostVisits = (studyId: string, params?: Record<string, any>) =>
|
||||
apiGet<VisitLostItem[]>(`/api/v1/studies/${studyId}/dashboard/lost-visits`, {
|
||||
params,
|
||||
cache: { ttlMs: 30_000, tags: [`study:${studyId}`, `study:${studyId}:dashboard`, `study:${studyId}:visits`] },
|
||||
});
|
||||
|
||||
export const fetchCenterSummary = (studyId: string) =>
|
||||
apiGet<CenterSummaryItem[]>(`/api/v1/studies/${studyId}/dashboard/center-summary`, {
|
||||
cache: { ttlMs: 30_000, tags: [`study:${studyId}`, `study:${studyId}:dashboard`, `study:${studyId}:sites`] },
|
||||
});
|
||||
@@ -37,9 +37,3 @@ export const acknowledgeDesktopNotifications = (claimToken: string, deliveredIds
|
||||
suppressErrorMessage: true,
|
||||
disableNetworkRetry: true,
|
||||
});
|
||||
|
||||
export const markDesktopNotificationRead = (distributionId: string) =>
|
||||
apiPost<void>(`/api/v1/desktop-notifications/${distributionId}/read`, undefined, {
|
||||
suppressErrorMessage: true,
|
||||
disableNetworkRetry: true,
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { apiDelete, apiGet, apiPatch, apiPost } from "./axios";
|
||||
import type { ApiListResponse } from "../types/api";
|
||||
import type {
|
||||
Acknowledgement,
|
||||
Distribution,
|
||||
DocumentDetail,
|
||||
DocumentSummary,
|
||||
|
||||
@@ -2,12 +2,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiGet = vi.fn();
|
||||
const apiPost = vi.fn();
|
||||
const apiPatch = vi.fn();
|
||||
|
||||
vi.mock("./axios", () => ({
|
||||
apiGet,
|
||||
apiPost,
|
||||
apiPatch,
|
||||
}));
|
||||
|
||||
describe("etmf api", () => {
|
||||
@@ -16,12 +14,11 @@ describe("etmf api", () => {
|
||||
});
|
||||
|
||||
it("uses canonical eTMF URLs", async () => {
|
||||
const { fetchEtmfTree, fetchEtmfNodeDocuments, createEtmfNode, updateEtmfNode, createEtmfDocument } = await import("./etmf");
|
||||
const { fetchEtmfTree, fetchEtmfNodeDocuments, createEtmfNode, createEtmfDocument } = await import("./etmf");
|
||||
|
||||
fetchEtmfTree("study-1");
|
||||
fetchEtmfNodeDocuments("node-1", { site_id: "site-1" });
|
||||
createEtmfNode({ study_id: "study-1", code: "01", name: "项目管理" });
|
||||
updateEtmfNode("node-1", { name: "项目管理文件" });
|
||||
createEtmfDocument("node-1", {
|
||||
trial_id: "study-1",
|
||||
doc_no: "DOC-001",
|
||||
@@ -33,7 +30,6 @@ describe("etmf api", () => {
|
||||
expect(apiGet).toHaveBeenCalledWith("/api/v1/etmf/tree", { params: { study_id: "study-1" } });
|
||||
expect(apiGet).toHaveBeenCalledWith("/api/v1/etmf/nodes/node-1/documents", { params: { site_id: "site-1" } });
|
||||
expect(apiPost).toHaveBeenCalledWith("/api/v1/etmf/nodes", { study_id: "study-1", code: "01", name: "项目管理" });
|
||||
expect(apiPatch).toHaveBeenCalledWith("/api/v1/etmf/nodes/node-1", { name: "项目管理文件" });
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
"/api/v1/etmf/nodes/node-1/documents",
|
||||
expect.objectContaining({ doc_no: "DOC-001" })
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { apiGet, apiPatch, apiPost } from "./axios";
|
||||
import { apiGet, apiPost } from "./axios";
|
||||
import type { DocumentSummary } from "../types/documents";
|
||||
import type { EtmfDocumentCreatePayload, EtmfNodeCreatePayload, EtmfNodeUpdatePayload, EtmfTreeNode } from "../types/etmf";
|
||||
import type { EtmfDocumentCreatePayload, EtmfNodeCreatePayload, EtmfTreeNode } from "../types/etmf";
|
||||
|
||||
export const fetchEtmfTree = (studyId: string) =>
|
||||
apiGet<EtmfTreeNode[]>("/api/v1/etmf/tree", { params: { study_id: studyId } });
|
||||
@@ -11,8 +11,5 @@ export const fetchEtmfNodeDocuments = (nodeId: string, params: Record<string, an
|
||||
export const createEtmfNode = (payload: EtmfNodeCreatePayload) =>
|
||||
apiPost<EtmfTreeNode>("/api/v1/etmf/nodes", payload);
|
||||
|
||||
export const updateEtmfNode = (nodeId: string, payload: EtmfNodeUpdatePayload) =>
|
||||
apiPatch<EtmfTreeNode>(`/api/v1/etmf/nodes/${nodeId}`, payload);
|
||||
|
||||
export const createEtmfDocument = (nodeId: string, payload: EtmfDocumentCreatePayload) =>
|
||||
apiPost<DocumentSummary>(`/api/v1/etmf/nodes/${nodeId}/documents`, payload);
|
||||
|
||||
@@ -11,13 +11,11 @@ describe("general notification API", () => {
|
||||
it("loads an uncached recipient feed and updates read state", async () => {
|
||||
const {
|
||||
listGeneralNotifications,
|
||||
markAllGeneralNotificationsRead,
|
||||
markGeneralNotificationRead,
|
||||
} = await import("./notifications");
|
||||
|
||||
listGeneralNotifications("study-1", 8);
|
||||
markGeneralNotificationRead("study-1", "notification-1");
|
||||
markAllGeneralNotificationsRead("study-1");
|
||||
|
||||
expect(apiGet).toHaveBeenCalledWith(
|
||||
"/api/v1/studies/study-1/notifications/feed",
|
||||
@@ -26,8 +24,5 @@ describe("general notification API", () => {
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
"/api/v1/studies/study-1/notifications/notification-1/read",
|
||||
);
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
"/api/v1/studies/study-1/notifications/read-all",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { apiGet, apiPost } from "./axios";
|
||||
import type { GeneralNotificationFeed, GeneralNotificationItem, NotificationItem } from "../types/notifications";
|
||||
|
||||
export const listNotifications = (studyId: string, params?: Record<string, any>) =>
|
||||
apiGet<NotificationItem[]>(`/api/v1/studies/${studyId}/notifications`, { params });
|
||||
import type { GeneralNotificationFeed, GeneralNotificationItem } from "../types/notifications";
|
||||
|
||||
export const listGeneralNotifications = (studyId: string, limit = 10) =>
|
||||
apiGet<GeneralNotificationFeed>(`/api/v1/studies/${studyId}/notifications/feed`, {
|
||||
@@ -15,6 +12,3 @@ export const markGeneralNotificationRead = (studyId: string, notificationId: str
|
||||
apiPost<GeneralNotificationItem>(
|
||||
`/api/v1/studies/${studyId}/notifications/${notificationId}/read`,
|
||||
);
|
||||
|
||||
export const markAllGeneralNotificationsRead = (studyId: string) =>
|
||||
apiPost<void>(`/api/v1/studies/${studyId}/notifications/read-all`);
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
ApiEndpointPermissionsUpdate,
|
||||
ApiOperation,
|
||||
PermissionMetricsResponse,
|
||||
CacheStatsResponse,
|
||||
AlertsResponse,
|
||||
HealthResponse,
|
||||
AccessLogsResponse,
|
||||
@@ -48,11 +47,6 @@ export const fetchPermissionMetrics = () =>
|
||||
cache: { ttlMs: 30_000, tags: ["permission-monitoring"] },
|
||||
});
|
||||
|
||||
export const fetchCacheStats = () =>
|
||||
apiGet<CacheStatsResponse>(`/api/v1/permission-monitoring/cache-stats`, {
|
||||
cache: { ttlMs: 30_000, tags: ["permission-monitoring"] },
|
||||
});
|
||||
|
||||
export const fetchPermissionAlerts = (level?: string, limit?: number) =>
|
||||
apiGet<AlertsResponse>(`/api/v1/permission-monitoring/alerts`, {
|
||||
params: { level, limit },
|
||||
@@ -63,12 +57,6 @@ export const fetchPermissionHealth = () =>
|
||||
cache: { ttlMs: 30_000, tags: ["permission-monitoring"] },
|
||||
});
|
||||
|
||||
export const resetPermissionMetrics = () =>
|
||||
apiPost<void>(`/api/v1/permission-monitoring/reset-metrics`);
|
||||
|
||||
export const clearPermissionAlerts = () =>
|
||||
apiPost<void>(`/api/v1/permission-monitoring/clear-alerts`);
|
||||
|
||||
// 系统监测 - 新增API
|
||||
export const fetchAccessLogs = (params: {
|
||||
study_id?: string;
|
||||
@@ -143,29 +131,12 @@ export interface PermissionTemplateCreate {
|
||||
recommended_roles?: string;
|
||||
}
|
||||
|
||||
export interface ApplyTemplateRequest {
|
||||
template_id: string;
|
||||
roles?: string[];
|
||||
override?: boolean;
|
||||
}
|
||||
|
||||
export interface ApplyTemplateResponse {
|
||||
study_id: string;
|
||||
applied_roles: string[];
|
||||
permissions: Record<string, Record<string, { allowed: boolean }>>;
|
||||
}
|
||||
|
||||
export const fetchPermissionTemplates = (params?: { template_type?: string; category?: string }) =>
|
||||
apiGet<PermissionTemplate[]>(`/api/v1/permission-templates`, {
|
||||
params,
|
||||
cache: { ttlMs: 5 * 60_000, tags: ["permission-templates"] },
|
||||
});
|
||||
|
||||
export const fetchPermissionTemplate = (templateId: string) =>
|
||||
apiGet<PermissionTemplate>(`/api/v1/permission-templates/${templateId}`, {
|
||||
cache: { ttlMs: 5 * 60_000, tags: ["permission-templates", `permission-template:${templateId}`] },
|
||||
});
|
||||
|
||||
export const createPermissionTemplate = (payload: PermissionTemplateCreate) =>
|
||||
apiPost<PermissionTemplate>(`/api/v1/permission-templates`, payload);
|
||||
|
||||
@@ -175,12 +146,6 @@ export const updatePermissionTemplate = (templateId: string, payload: Partial<Pe
|
||||
export const deletePermissionTemplate = (templateId: string) =>
|
||||
apiDelete<void>(`/api/v1/permission-templates/${templateId}`);
|
||||
|
||||
export const applyPermissionTemplate = (studyId: string, payload: ApplyTemplateRequest) =>
|
||||
apiPost<ApplyTemplateResponse>(
|
||||
`/api/v1/studies/${studyId}/permission-templates/${payload.template_id}/apply`,
|
||||
payload,
|
||||
);
|
||||
|
||||
// 系统级权限
|
||||
export interface SystemPermissionItem {
|
||||
permission_key: string;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
export type AccessTokenExtensionResult = {
|
||||
token: string | null;
|
||||
authFailed: boolean;
|
||||
};
|
||||
|
||||
export interface ApiRuntimeHooks {
|
||||
clearInvalidStudyAndNavigate: () => void | Promise<unknown>;
|
||||
extendAccessToken: (reason: "response-401") => Promise<AccessTokenExtensionResult>;
|
||||
forceAuthExpiredLogout: () => void | Promise<unknown>;
|
||||
}
|
||||
|
||||
let runtimeHooks: ApiRuntimeHooks | null = null;
|
||||
|
||||
export const configureApiRuntimeHooks = (hooks: ApiRuntimeHooks): void => {
|
||||
runtimeHooks = hooks;
|
||||
};
|
||||
|
||||
export const clearInvalidStudyAndNavigate = async (): Promise<void> => {
|
||||
await runtimeHooks?.clearInvalidStudyAndNavigate();
|
||||
};
|
||||
|
||||
export const extendAccessTokenAfterUnauthorized = (): Promise<AccessTokenExtensionResult> =>
|
||||
runtimeHooks?.extendAccessToken("response-401")
|
||||
?? Promise.resolve({ token: null, authFailed: false });
|
||||
|
||||
export const forceAuthExpiredLogout = async (): Promise<void> => {
|
||||
await runtimeHooks?.forceAuthExpiredLogout();
|
||||
};
|
||||
@@ -3,9 +3,6 @@ import { apiDelete, apiGet, apiPatch, apiPost } from "./axios";
|
||||
export const listSubjectHistories = (studyId: string, subjectId: string, params?: Record<string, any>) =>
|
||||
apiGet(`/api/v1/studies/${studyId}/subjects/${subjectId}/histories`, { params });
|
||||
|
||||
export const getSubjectHistory = (studyId: string, subjectId: string, historyId: string) =>
|
||||
apiGet(`/api/v1/studies/${studyId}/subjects/${subjectId}/histories/${historyId}`);
|
||||
|
||||
export const createSubjectHistory = (studyId: string, subjectId: string, payload: Record<string, any>) =>
|
||||
apiPost(`/api/v1/studies/${studyId}/subjects/${subjectId}/histories`, payload);
|
||||
|
||||
|
||||
@@ -764,10 +764,3 @@ export const normalizeAuditEvent = (raw: any, userMap: Record<string, string>):
|
||||
clientSourceLabel: resolveAuditClientSourceLabel(raw),
|
||||
};
|
||||
};
|
||||
|
||||
// Deprecated: keep API-compatible no-op to avoid accidental reliance on browser local storage.
|
||||
export const logAudit = async (eventType: string, payload: Record<string, any>) => {
|
||||
void eventType;
|
||||
void payload;
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
@@ -526,7 +526,6 @@ import {
|
||||
Key,
|
||||
Monitor,
|
||||
Notebook,
|
||||
Refresh,
|
||||
Search,
|
||||
Setting,
|
||||
Star,
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-if="modelValue"
|
||||
:model-value="modelValue"
|
||||
direction="rtl"
|
||||
size="520px"
|
||||
:close-on-click-modal="true"
|
||||
:show-close="false"
|
||||
class="faq-category-editor-drawer"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
@close="close"
|
||||
>
|
||||
<template #header>
|
||||
<div class="editor-header">
|
||||
<div class="editor-title">{{ isEdit ? TEXT.modules.knowledgeMedicalConsult.editCategory : TEXT.modules.knowledgeMedicalConsult.newCategory }}</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="faq-category-form">
|
||||
<div class="form-group">
|
||||
<div class="form-group-title">
|
||||
<span class="group-dot group-dot-basic"></span>
|
||||
{{ TEXT.modules.knowledgeMedicalConsult.title }}
|
||||
</div>
|
||||
<el-form-item :label="TEXT.modules.knowledgeMedicalConsult.categoryName" prop="name">
|
||||
<el-input v-model="form.name" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.description">
|
||||
<el-input v-model="form.description" type="textarea" :rows="2" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.sortOrder">
|
||||
<el-input-number v-model="form.sort_order" :min="0" :step="1" />
|
||||
</el-form-item>
|
||||
<el-form-item label="图标">
|
||||
<div class="icon-picker">
|
||||
<span
|
||||
v-for="icon in iconOptions"
|
||||
:key="icon.cls"
|
||||
:title="icon.label"
|
||||
:class="['icon-option', {
|
||||
'icon-option--selected': form.icon === icon.cls,
|
||||
'icon-option--used': isIconUsedByOther(icon.cls),
|
||||
}]"
|
||||
@click="selectIcon(icon.cls)"
|
||||
><FaqIcon :icon="icon.cls" /></span>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="drawer-footer" :class="{ 'drawer-footer--edit': isEdit }">
|
||||
<el-button v-if="isEdit && canDelete" type="danger" plain :loading="deleting" @click="onDelete">
|
||||
{{ TEXT.common.actions.delete }}
|
||||
</el-button>
|
||||
<div class="drawer-footer-spacer" v-if="isEdit"></div>
|
||||
<el-button @click="close">{{ TEXT.common.actions.cancel }}</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="onSubmit">{{ TEXT.common.actions.save }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
|
||||
import FaqIcon from "./FaqIcon.vue";
|
||||
import { createFaqCategory, updateFaqCategory, deleteFaqCategory } from "../api/faqs";
|
||||
import { useStudyStore } from "../store/study";
|
||||
import { TEXT, requiredMessage } from "../locales";
|
||||
|
||||
const props = defineProps<{ modelValue: boolean; category?: any; isAdmin: boolean; canDelete?: boolean; existingIcons?: string[] }>();
|
||||
const emit = defineEmits(["update:modelValue", "success"]);
|
||||
|
||||
const study = useStudyStore();
|
||||
const formRef = ref<FormInstance>();
|
||||
const submitting = ref(false);
|
||||
const deleting = ref(false);
|
||||
|
||||
const form = reactive({
|
||||
study_id: "",
|
||||
name: "",
|
||||
description: "",
|
||||
sort_order: 0,
|
||||
icon: "",
|
||||
});
|
||||
|
||||
const iconOptions = [
|
||||
{ cls: "fa-th-large", label: "全部" },
|
||||
{ cls: "fa-ruler-combined", label: "入排标准" },
|
||||
{ cls: "fa-calendar-check", label: "访视" },
|
||||
{ cls: "fa-filter", label: "筛选" },
|
||||
{ cls: "fa-flag-checkered", label: "启动会" },
|
||||
{ cls: "fa-capsules", label: "试验药物" },
|
||||
{ cls: "fa-prescription-bottle", label: "药品" },
|
||||
{ cls: "fa-vial", label: "实验室" },
|
||||
{ cls: "fa-heartbeat", label: "AE" },
|
||||
{ cls: "fa-pills", label: "合并用药" },
|
||||
{ cls: "fa-file-medical", label: "门诊病历" },
|
||||
{ cls: "fa-camera", label: "拍照" },
|
||||
{ cls: "fa-notes-medical", label: "医疗记录" },
|
||||
{ cls: "fa-clipboard-list", label: "检查表" },
|
||||
{ cls: "fa-syringe", label: "注射" },
|
||||
{ cls: "fa-flask", label: "研究" },
|
||||
{ cls: "fa-book-medical", label: "医学书籍" },
|
||||
{ cls: "fa-user-md", label: "医生" },
|
||||
{ cls: "fa-hospital", label: "医院" },
|
||||
{ cls: "fa-ellipsis-h", label: "其他" },
|
||||
];
|
||||
|
||||
const rules: FormRules = {
|
||||
name: [{ required: true, message: requiredMessage(TEXT.modules.knowledgeMedicalConsult.categoryName), trigger: "blur" }],
|
||||
};
|
||||
|
||||
const isEdit = computed(() => !!props.category);
|
||||
|
||||
const isIconUsedByOther = (icon: string) => {
|
||||
if (form.icon === icon) return false;
|
||||
return (props.existingIcons || []).includes(icon);
|
||||
};
|
||||
|
||||
const selectIcon = (icon: string) => {
|
||||
if (isIconUsedByOther(icon)) return;
|
||||
form.icon = form.icon === icon ? "" : icon;
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
form.name = "";
|
||||
form.description = "";
|
||||
form.sort_order = 0;
|
||||
form.icon = "";
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.category,
|
||||
(val) => {
|
||||
if (val) {
|
||||
form.name = val.name;
|
||||
form.description = val.description || "";
|
||||
form.sort_order = val.sort_order || 0;
|
||||
form.icon = val.icon || "";
|
||||
} else {
|
||||
reset();
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(val) => {
|
||||
if (val && !props.category) {
|
||||
reset();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const close = () => emit("update:modelValue", false);
|
||||
|
||||
const onSubmit = async () => {
|
||||
if (!formRef.value) return;
|
||||
|
||||
// 验证当前项目存在
|
||||
if (!study.currentStudy?.id) {
|
||||
ElMessage.warning(TEXT.common.empty.selectProject);
|
||||
return;
|
||||
}
|
||||
|
||||
await formRef.value.validate();
|
||||
submitting.value = true;
|
||||
try {
|
||||
const payload: Record<string, any> = {
|
||||
study_id: study.currentStudy.id,
|
||||
name: form.name,
|
||||
description: form.description || null,
|
||||
sort_order: form.sort_order,
|
||||
icon: form.icon || null,
|
||||
};
|
||||
if (isEdit.value && props.category) {
|
||||
await updateFaqCategory(props.category.id, payload);
|
||||
} else {
|
||||
await createFaqCategory(payload);
|
||||
}
|
||||
ElMessage.success(TEXT.common.messages.saveSuccess);
|
||||
emit("success");
|
||||
close();
|
||||
} catch (e: any) {
|
||||
const errorMsg = e?.response?.data?.message || e?.response?.data?.detail || TEXT.common.messages.saveFailed;
|
||||
ElMessage.error(typeof errorMsg === 'string' ? errorMsg : TEXT.common.messages.saveFailed);
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const onDelete = async () => {
|
||||
if (!props.category) return;
|
||||
const ok = await ElMessageBox.confirm(
|
||||
TEXT.modules.knowledgeMedicalConsult.confirmDeleteCategory.replace("{name}", props.category.name),
|
||||
TEXT.common.labels.tips,
|
||||
).catch(() => null);
|
||||
if (!ok) return;
|
||||
deleting.value = true;
|
||||
try {
|
||||
await deleteFaqCategory(props.category.id, study.currentStudy?.id);
|
||||
ElMessage.success(TEXT.common.messages.deleteSuccess);
|
||||
emit("success");
|
||||
close();
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
|
||||
} finally {
|
||||
deleting.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.editor-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.editor-title {
|
||||
color: var(--ctms-text-main);
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.faq-category-form {
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
padding: 16px 0;
|
||||
}
|
||||
|
||||
.form-group-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
color: var(--ctms-text-main);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.group-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.group-dot-basic {
|
||||
background: var(--ctms-primary);
|
||||
}
|
||||
|
||||
.drawer-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.drawer-footer--edit {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.drawer-footer-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.icon-picker {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.icon-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border: 2px solid #e8eef6;
|
||||
border-radius: 10px;
|
||||
font-size: 18px;
|
||||
color: #697982;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.icon-option:hover {
|
||||
border-color: #93c5fd;
|
||||
background: #eff6ff;
|
||||
transform: scale(1.08);
|
||||
}
|
||||
|
||||
.icon-option--selected {
|
||||
border-color: #3b82f6;
|
||||
background: #dbeafe;
|
||||
color: #1e40af;
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
.icon-option--used {
|
||||
opacity: 0.3;
|
||||
pointer-events: none;
|
||||
cursor: not-allowed;
|
||||
border-color: #e8eef6;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
</style>
|
||||
@@ -97,7 +97,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { ArrowDown, ArrowUp, Delete, Plus } from "@element-plus/icons-vue";
|
||||
import FaqIcon from "./FaqIcon.vue";
|
||||
import { createFaqCategory, updateFaqCategory, deleteFaqCategory } from "../api/faqs";
|
||||
|
||||
@@ -35,6 +35,8 @@ describe("desktop layout shell", () => {
|
||||
const app = readAppSource();
|
||||
|
||||
expect(source).toContain("const isDesktop = isTauriRuntime()");
|
||||
expect(source).toContain('defineAsyncComponent(() => import("./DesktopLayout.vue"))');
|
||||
expect(source).toContain('defineAsyncComponent(() => import("./WebLayout.vue"))');
|
||||
expect(source).toContain("<DesktopLayout v-if=\"isDesktop\" />");
|
||||
expect(source).toContain("<WebLayout v-else />");
|
||||
expect(app).toContain("const isDesktopRuntime = isTauriRuntime();");
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import { isTauriRuntime } from "../runtime";
|
||||
import DesktopLayout from "./DesktopLayout.vue";
|
||||
import WebLayout from "./WebLayout.vue";
|
||||
|
||||
const DesktopLayout = defineAsyncComponent(() => import("./DesktopLayout.vue"));
|
||||
const WebLayout = defineAsyncComponent(() => import("./WebLayout.vue"));
|
||||
|
||||
const isDesktop = isTauriRuntime();
|
||||
</script>
|
||||
|
||||
@@ -29,7 +29,7 @@ describe("PermissionAccessLogs", () => {
|
||||
expect(source).toContain("IP访问排行");
|
||||
expect(source).toContain("ipRankingDialogVisible");
|
||||
expect(source).toContain("openIpRankingDialog");
|
||||
expect(source).toContain("ipRankingPeriodOptions");
|
||||
expect(source).toContain('<TimeRangeSelector v-model="ipRankingPeriod"');
|
||||
expect(source).toContain('class="access-toolbar"');
|
||||
expect(source).toContain('class="access-toolbar-actions"');
|
||||
expect(source).toContain('@click="loadData">刷新');
|
||||
@@ -320,8 +320,7 @@ describe("PermissionAccessLogs", () => {
|
||||
const source = readSource();
|
||||
|
||||
expect(source).toContain('placeholder="搜索账号、IP、属地、接口或来源"');
|
||||
expect(source).toContain("filter-time-presets");
|
||||
expect(source).toContain("timeRangePresetOptions");
|
||||
expect(source).toContain('<TimeRangeSelector v-model="timeRangePreset"');
|
||||
expect(source).toContain("onTimePresetChange");
|
||||
expect(source).toContain("buildTimeRangeFromPreset");
|
||||
expect(source).toContain("全部");
|
||||
@@ -341,7 +340,8 @@ describe("PermissionAccessLogs", () => {
|
||||
|
||||
expect(source).toContain("--filter-control-height: 26px");
|
||||
expect(source).toContain("--filter-font-size: 12px");
|
||||
expect(source).toContain(".filter-time-presets :deep(.el-radio-button__inner)");
|
||||
expect(source).toContain('import TimeRangeSelector from "./TimeRangeSelector.vue"');
|
||||
expect(source).not.toContain(".filter-time-presets :deep(.el-radio-button__inner)");
|
||||
expect(source).toContain(".audit-filters :deep(.el-select__wrapper)");
|
||||
expect(source).toContain(".audit-filters :deep(.el-input__wrapper)");
|
||||
expect(source).toContain('class="filter-reset"');
|
||||
|
||||
@@ -432,8 +432,6 @@ const filters = reactive({
|
||||
|
||||
const ROLE_FILTER_KEYS = ["ADMIN", "PM", "CRA", "PV", "QA", "CTA"];
|
||||
const roleFilterOptions = computed(() => roleOptionsFor(ROLE_FILTER_KEYS));
|
||||
const timeRangePresetOptions = TIME_RANGE_PRESETS;
|
||||
const ipRankingPeriodOptions = TIME_RANGE_PRESETS;
|
||||
const selectedIpRankingPeriod = computed(() => TIME_RANGE_PRESETS.find((period) => period.value === ipRankingPeriod.value) || TIME_RANGE_PRESETS[1]);
|
||||
const clientSourceOptions = [
|
||||
{ value: "web", label: "网页端" },
|
||||
@@ -1168,31 +1166,6 @@ defineExpose({ refresh, applyTrendFilter });
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.filter-time-presets {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.filter-time-presets :deep(.el-radio-button__inner) {
|
||||
height: var(--filter-control-height);
|
||||
padding: 0 12px;
|
||||
border-radius: 0;
|
||||
font-size: var(--filter-font-size);
|
||||
font-weight: 500;
|
||||
line-height: calc(var(--filter-control-height) - 2px);
|
||||
}
|
||||
|
||||
.filter-time-presets :deep(.el-radio-button:first-child .el-radio-button__inner) {
|
||||
border-radius: 7px 0 0 7px;
|
||||
}
|
||||
|
||||
.filter-time-presets :deep(.el-radio-button:last-child .el-radio-button__inner) {
|
||||
border-radius: 0 7px 7px 0;
|
||||
}
|
||||
|
||||
.filter-time-presets :deep(.el-radio-button.is-active .el-radio-button__inner) {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.filter-role {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
@@ -73,7 +73,9 @@ describe("PermissionIpLocations", () => {
|
||||
it("uses backend coordinates and keeps unmapped locations in the ranking", () => {
|
||||
const source = readSource();
|
||||
|
||||
expect(source).toContain('const mapView = ref<"china" | "flow">("flow");');
|
||||
expect(source).toContain('const mapView = ref<MapView>("flow");');
|
||||
expect(source).toContain('load: () => import("../assets/china.json")');
|
||||
expect(source).toContain('load: () => import("../assets/world.json")');
|
||||
expect(source).toContain("item.longitude");
|
||||
expect(source).toContain("item.latitude");
|
||||
expect(source).toContain("external_fallback_ip_count");
|
||||
|
||||
@@ -56,8 +56,9 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="source-map-wrap">
|
||||
<template v-if="!fullscreenVisible">
|
||||
<v-chart
|
||||
v-if="!fullscreenVisible"
|
||||
v-if="mapReady"
|
||||
ref="sourceChartRef"
|
||||
:key="mapView"
|
||||
:option="sourceMapOption"
|
||||
@@ -66,6 +67,9 @@
|
||||
:autoresize="chartAutoresize"
|
||||
class="source-map"
|
||||
/>
|
||||
<el-empty v-else-if="mapLoadError" :description="mapLoadError" :image-size="72" />
|
||||
<div v-else v-loading="true" class="source-map" aria-label="地图加载中" />
|
||||
</template>
|
||||
<div class="flow-legend map-legend" aria-label="访问链路图例">
|
||||
<span v-if="serverLocation" class="legend-item"><i class="legend-dot server"></i>服务器</span>
|
||||
<template v-if="mapMetric === 'traffic'">
|
||||
@@ -125,7 +129,7 @@
|
||||
</template>
|
||||
<div class="fullscreen-map-wrap">
|
||||
<v-chart
|
||||
v-if="fullscreenChartMounted"
|
||||
v-if="fullscreenChartMounted && mapReady"
|
||||
ref="fullscreenChartRef"
|
||||
:key="fullscreenMapKey"
|
||||
:option="fullscreenSourceMapOption"
|
||||
@@ -152,21 +156,26 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, h, nextTick, onMounted, ref } from "vue";
|
||||
import { computed, h, nextTick, onMounted, ref, watch } from "vue";
|
||||
import VChart from "vue-echarts";
|
||||
import { registerMap, use } from "echarts/core";
|
||||
import { CanvasRenderer } from "echarts/renderers";
|
||||
import { EffectScatterChart, LinesChart, ScatterChart } from "echarts/charts";
|
||||
import { GeoComponent, TooltipComponent } from "echarts/components";
|
||||
import chinaMapGeoJson from "../assets/china.json";
|
||||
import worldMapGeoJson from "../assets/world.json";
|
||||
import { fetchIpLocations } from "../api/projectPermissions";
|
||||
import type { IpLocationsResponse, IpLocationStatItem } from "../types/api";
|
||||
import TimeRangeSelector from "./TimeRangeSelector.vue";
|
||||
|
||||
use([CanvasRenderer, LinesChart, ScatterChart, EffectScatterChart, GeoComponent, TooltipComponent]);
|
||||
registerMap("ctms-china", chinaMapGeoJson as any);
|
||||
registerMap("ctms-world", worldMapGeoJson as any);
|
||||
|
||||
type MapView = "china" | "flow";
|
||||
|
||||
const mapDefinitions: Record<MapView, { name: string; load: () => Promise<{ default: unknown }> }> = {
|
||||
china: { name: "ctms-china", load: () => import("../assets/china.json") },
|
||||
flow: { name: "ctms-world", load: () => import("../assets/world.json") },
|
||||
};
|
||||
|
||||
const registeredMaps = new Set<string>();
|
||||
|
||||
const IconGlobe = () => h("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2" }, [
|
||||
h("circle", { cx: "12", cy: "12", r: "10" }),
|
||||
@@ -192,12 +201,6 @@ const IconShield = () => h("svg", { viewBox: "0 0 24 24", fill: "none", stroke:
|
||||
const loading = ref(false);
|
||||
type TimeRangePreset = "all" | "24h" | "7d" | "30d";
|
||||
const timeRangePreset = ref<TimeRangePreset>("30d");
|
||||
const timeRangeOptions = [
|
||||
{ value: "all", label: "全部" },
|
||||
{ value: "24h", label: "24小时" },
|
||||
{ value: "7d", label: "7天" },
|
||||
{ value: "30d", label: "30天" },
|
||||
] as const;
|
||||
|
||||
const getIpLocationsDays = (preset: TimeRangePreset): number | undefined => {
|
||||
const map: Record<TimeRangePreset, number | undefined> = {
|
||||
@@ -208,7 +211,7 @@ const getIpLocationsDays = (preset: TimeRangePreset): number | undefined => {
|
||||
};
|
||||
return map[preset];
|
||||
};
|
||||
const mapView = ref<"china" | "flow">("flow");
|
||||
const mapView = ref<MapView>("flow");
|
||||
const mapMetric = ref<"traffic" | "risk">("traffic");
|
||||
const items = ref<IpLocationStatItem[]>([]);
|
||||
const summary = ref<IpLocationsResponse["summary"] | null>(null);
|
||||
@@ -216,6 +219,8 @@ const periodMetadata = ref<IpLocationsResponse["period"] | null>(null);
|
||||
const dataQuality = ref<IpLocationsResponse["data_quality"] | null>(null);
|
||||
const serverLocation = ref<IpLocationsResponse["server_location"]>(null);
|
||||
const loadError = ref("");
|
||||
const mapLoadError = ref("");
|
||||
const mapReady = ref(false);
|
||||
const lastUpdatedAt = ref<Date | null>(null);
|
||||
const getDevicePixelRatio = () => (typeof window === "undefined" ? 1 : window.devicePixelRatio || 1);
|
||||
const chartInitOptions = { devicePixelRatio: Math.min(getDevicePixelRatio(), 2), useDirtyRect: true };
|
||||
@@ -270,6 +275,31 @@ const resizeSourceCharts = async () => {
|
||||
sourceChartRef.value?.resize?.();
|
||||
};
|
||||
|
||||
let mapLoadSequence = 0;
|
||||
|
||||
const loadMap = async (view: MapView) => {
|
||||
const sequence = ++mapLoadSequence;
|
||||
const definition = mapDefinitions[view];
|
||||
mapReady.value = false;
|
||||
mapLoadError.value = "";
|
||||
|
||||
try {
|
||||
if (!registeredMaps.has(definition.name)) {
|
||||
const geoJson = await definition.load();
|
||||
registerMap(definition.name, geoJson.default as any);
|
||||
registeredMaps.add(definition.name);
|
||||
}
|
||||
if (sequence !== mapLoadSequence) return;
|
||||
mapReady.value = true;
|
||||
await resizeSourceCharts();
|
||||
} catch {
|
||||
if (sequence !== mapLoadSequence) return;
|
||||
mapLoadError.value = "地图资源加载失败,请刷新后重试";
|
||||
}
|
||||
};
|
||||
|
||||
watch(mapView, (view) => void loadMap(view), { immediate: true });
|
||||
|
||||
const formatNumber = (value: number) => new Intl.NumberFormat("zh-CN").format(value || 0);
|
||||
const formatLastUpdated = (value: Date) => {
|
||||
return `${value.getFullYear()}/${value.getMonth() + 1}/${value.getDate()} ${String(value.getHours()).padStart(2, "0")}:${String(value.getMinutes()).padStart(2, "0")}:${String(value.getSeconds()).padStart(2, "0")}`;
|
||||
|
||||
@@ -267,7 +267,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, h, nextTick, onMounted, onUnmounted } from "vue";
|
||||
import { computed, defineAsyncComponent, h, nextTick, onMounted, onUnmounted, ref } from "vue";
|
||||
import type {
|
||||
PermissionMetricsResponse,
|
||||
AlertsResponse,
|
||||
@@ -282,12 +282,13 @@ import {
|
||||
fetchTopDenied,
|
||||
fetchStatsSummary,
|
||||
} from "@/api/projectPermissions";
|
||||
import PermissionTrendCharts from "./PermissionTrendCharts.vue";
|
||||
import PermissionAccessLogs from "./PermissionAccessLogs.vue";
|
||||
import PermissionIpLocations from "./PermissionIpLocations.vue";
|
||||
import SecurityCenter from "./SecurityCenter.vue";
|
||||
import TimeRangeSelector from "./TimeRangeSelector.vue";
|
||||
|
||||
const PermissionTrendCharts = defineAsyncComponent(() => import("./PermissionTrendCharts.vue"));
|
||||
const PermissionAccessLogs = defineAsyncComponent(() => import("./PermissionAccessLogs.vue"));
|
||||
const PermissionIpLocations = defineAsyncComponent(() => import("./PermissionIpLocations.vue"));
|
||||
const SecurityCenter = defineAsyncComponent(() => import("./SecurityCenter.vue"));
|
||||
|
||||
const IconCheck = () => h("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2" }, [
|
||||
h("polyline", { points: "20 6 9 17 4 12" }),
|
||||
]);
|
||||
@@ -328,12 +329,6 @@ const lastUpdatedAt = ref<Date | null>(null);
|
||||
|
||||
type TimeRangePreset = "all" | "24h" | "7d" | "30d";
|
||||
const timeRangePreset = ref<TimeRangePreset>("7d");
|
||||
const timeRangeOptions = [
|
||||
{ value: "all", label: "全部" },
|
||||
{ value: "24h", label: "24小时" },
|
||||
{ value: "7d", label: "7天" },
|
||||
{ value: "30d", label: "30天" },
|
||||
] as const;
|
||||
|
||||
const getTopDeniedDays = (preset: TimeRangePreset): number => {
|
||||
const map: Record<TimeRangePreset, number> = {
|
||||
@@ -355,15 +350,6 @@ const currentDeniedPeriodLabel = computed(() => {
|
||||
return map[timeRangePreset.value];
|
||||
});
|
||||
|
||||
const trendChartsRef = ref<InstanceType<typeof PermissionTrendCharts>>();
|
||||
const accessLogsRef = ref<InstanceType<typeof PermissionAccessLogs>>();
|
||||
type IpLocationsExpose = {
|
||||
refresh: () => void | Promise<void>;
|
||||
resize: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
const ipLocationsRef = ref<IpLocationsExpose>();
|
||||
|
||||
interface TrendDrilldownPayload {
|
||||
preset?: "24h" | "7d" | "30d";
|
||||
startAt?: string;
|
||||
@@ -374,13 +360,28 @@ interface TrendDrilldownPayload {
|
||||
keyword?: string;
|
||||
}
|
||||
|
||||
type RefreshablePanel = {
|
||||
refresh: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
type AccessLogsExpose = RefreshablePanel & {
|
||||
applyTrendFilter: (payload: TrendDrilldownPayload) => void | Promise<void>;
|
||||
};
|
||||
|
||||
type IpLocationsExpose = RefreshablePanel & {
|
||||
resize: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
const trendChartsRef = ref<RefreshablePanel>();
|
||||
const accessLogsRef = ref<AccessLogsExpose>();
|
||||
const ipLocationsRef = ref<IpLocationsExpose>();
|
||||
const securityCenterRef = ref<RefreshablePanel>();
|
||||
|
||||
const openTrendDrilldown = async (payload: TrendDrilldownPayload) => {
|
||||
activeTab.value = "logs";
|
||||
await nextTick();
|
||||
await accessLogsRef.value?.applyTrendFilter(payload);
|
||||
};
|
||||
const securityCenterRef = ref<InstanceType<typeof SecurityCenter>>();
|
||||
|
||||
const formatTime = (timestamp: number): string => {
|
||||
return new Date(timestamp * 1000).toLocaleString("zh-CN");
|
||||
};
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
<template>
|
||||
<div class="quick-actions-section">
|
||||
<div class="section-header">
|
||||
<el-icon class="header-icon"><Pointer /></el-icon>
|
||||
<span class="header-title">{{ TEXT.common.labels.quickActions }}</span>
|
||||
</div>
|
||||
<div class="actions-grid">
|
||||
<div
|
||||
v-for="item in visibleActions"
|
||||
:key="item.path"
|
||||
class="action-item"
|
||||
@click="go(item.path)"
|
||||
>
|
||||
<div class="action-icon-wrapper">
|
||||
<el-icon><component :is="item.icon" /></el-icon>
|
||||
</div>
|
||||
<span class="action-label">{{ item.label }}</span>
|
||||
<el-icon class="action-arrow"><ArrowRight /></el-icon>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import {
|
||||
Pointer, ArrowRight, Timer, UserFilled,
|
||||
Management, Money, Collection
|
||||
} from "@element-plus/icons-vue";
|
||||
import { TEXT } from "../locales";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useStudyStore } from "../store/study";
|
||||
import { isSystemAdmin } from "../utils/roles";
|
||||
import { getProjectRoutePermission, hasProjectPermission } from "../utils/projectRoutePermissions";
|
||||
|
||||
const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const study = useStudyStore();
|
||||
|
||||
const actions = [
|
||||
{ label: TEXT.menu.startupFeasibilityEthics, path: "/startup/feasibility-ethics", icon: Timer },
|
||||
{ label: TEXT.menu.startupMeetingAuth, path: "/startup/meeting-auth", icon: Timer },
|
||||
{ label: TEXT.menu.subjects, path: "/subjects", icon: UserFilled },
|
||||
{ label: TEXT.menu.drugShipments, path: "/drug/shipments", icon: Management },
|
||||
{ label: TEXT.menu.finance, path: "/fees/contracts", icon: Money },
|
||||
{ label: TEXT.menu.knowledgeMedicalConsult, path: "/knowledge/medical-consult", icon: Collection },
|
||||
];
|
||||
|
||||
const projectRole = computed(() => study.currentStudyRole || (study.currentStudy as any)?.role_in_study || "");
|
||||
const visibleActions = computed(() =>
|
||||
actions.filter((item) =>
|
||||
hasProjectPermission(
|
||||
study.currentPermissions,
|
||||
projectRole.value,
|
||||
getProjectRoutePermission(item.path),
|
||||
isSystemAdmin(auth.user),
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const go = (path: string) => router.push(path);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.quick-actions-section {
|
||||
background-color: #fff;
|
||||
border-radius: var(--ctms-radius);
|
||||
padding: 24px;
|
||||
border: 1px solid var(--ctms-border-color);
|
||||
}
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.header-icon {
|
||||
font-size: 16px;
|
||||
color: var(--ctms-text-secondary);
|
||||
}
|
||||
|
||||
.header-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--ctms-text-main);
|
||||
}
|
||||
|
||||
.actions-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.action-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background-color: #ffffff;
|
||||
border: 1px solid var(--ctms-border-color);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: var(--ctms-transition);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.action-item:hover {
|
||||
background-color: #ffffff;
|
||||
border-color: var(--ctms-border-color-hover);
|
||||
}
|
||||
|
||||
.action-icon-wrapper {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
margin-right: 12px;
|
||||
color: var(--ctms-text-secondary);
|
||||
background-color: var(--ctms-bg-muted);
|
||||
}
|
||||
|
||||
.action-label {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--ctms-text-main);
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.action-arrow {
|
||||
font-size: 14px;
|
||||
color: var(--ctms-text-disabled);
|
||||
opacity: 1;
|
||||
transition: var(--ctms-transition);
|
||||
}
|
||||
|
||||
.action-item:hover .action-arrow {
|
||||
color: var(--ctms-text-secondary);
|
||||
}
|
||||
</style>
|
||||
@@ -429,8 +429,6 @@ const formatLastUpdated = (value: Date) => {
|
||||
return `${value.getFullYear()}/${value.getMonth() + 1}/${value.getDate()} ${String(value.getHours()).padStart(2, "0")}:${String(value.getMinutes()).padStart(2, "0")}:${String(value.getSeconds()).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const isHighRisk = (event: SecurityAccessLogItem) => event.severity === "CRITICAL" || event.severity === "HIGH";
|
||||
|
||||
const fallbackIpLocation = (ip: string | null) => {
|
||||
if (!ip) return "未知位置";
|
||||
if (ip === "127.0.0.1" || ip === "::1") return "本机访问";
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
<template>
|
||||
<el-dropdown trigger="click" class="study-selector-dropdown" @command="onCommand">
|
||||
<div class="selector-trigger">
|
||||
<el-icon class="trigger-icon"><OfficeBuilding /></el-icon>
|
||||
<span class="current-study-name">{{ study.currentStudy?.name || TEXT.common.empty.selectProject }}</span>
|
||||
<el-icon class="arrow-icon"><ArrowDown /></el-icon>
|
||||
</div>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu class="study-dropdown">
|
||||
<el-dropdown-item command="workbench">
|
||||
<el-icon><OfficeBuilding /></el-icon>返回工作台选择项目
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useRouter } from "vue-router";
|
||||
import { useStudyStore } from "../store/study";
|
||||
import { OfficeBuilding, ArrowDown } from "@element-plus/icons-vue";
|
||||
import { TEXT } from "../locales";
|
||||
|
||||
const router = useRouter();
|
||||
const study = useStudyStore();
|
||||
|
||||
const onCommand = async (cmd: any) => {
|
||||
if (cmd === "workbench") {
|
||||
study.clearCurrentStudy();
|
||||
await router.push("/workbench");
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.selector-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 12px;
|
||||
background-color: #fafafa;
|
||||
border: 1px solid var(--ctms-border-color);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.selector-trigger:hover {
|
||||
background-color: var(--ctms-primary-light);
|
||||
border-color: var(--ctms-primary-hover);
|
||||
}
|
||||
|
||||
.trigger-icon {
|
||||
color: var(--ctms-primary);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.current-study-name {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--ctms-text-main);
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.arrow-icon {
|
||||
font-size: 12px;
|
||||
color: var(--ctms-text-secondary);
|
||||
}
|
||||
|
||||
.study-dropdown {
|
||||
max-height: 320px;
|
||||
overflow-y: auto;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -408,7 +408,7 @@ import { TEXT } from "../locales";
|
||||
import {
|
||||
User, Suitcase, House, Calendar, Flag,
|
||||
CircleCheck, Box, Coin, Notebook, Document, ArrowDown, SwitchButton, Files, Key, DataAnalysis, UserFilled, Bell, Setting,
|
||||
Search, Star, StarFilled, Clock, Monitor, FullScreen, ScaleToOriginal
|
||||
Search, Star, StarFilled, Monitor, FullScreen, ScaleToOriginal
|
||||
} from "@element-plus/icons-vue";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { getProjectRoutePermission, hasProjectPermission, projectRouteLandingPaths } from "../utils/projectRoutePermissions";
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// 地图数据来源:https://geojson.cn/api/china/1.6.3/china.json
|
||||
// 组件直接导入本地缓存的 GeoJSON,避免运行时依赖外部网络。
|
||||
|
||||
export const normalizeProvinceName = (value?: string | null) => {
|
||||
return String(value || "")
|
||||
.trim()
|
||||
.replace(/特别行政区$/u, "")
|
||||
.replace(/维吾尔自治区$/u, "")
|
||||
.replace(/壮族自治区$/u, "")
|
||||
.replace(/回族自治区$/u, "")
|
||||
.replace(/自治区$/u, "")
|
||||
.replace(/省$/u, "")
|
||||
.replace(/市$/u, "");
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
<template>
|
||||
<el-select
|
||||
:model-value="modelValue"
|
||||
:multiple="multiple"
|
||||
:placeholder="placeholder || TEXT.common.placeholders.select"
|
||||
:filterable="filterable"
|
||||
:clearable="clearable"
|
||||
:loading="loading"
|
||||
style="width: 100%"
|
||||
@update:model-value="onUpdate"
|
||||
>
|
||||
<el-option v-for="opt in options" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
|
||||
<slot />
|
||||
</el-select>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { TEXT } from "../../locales";
|
||||
|
||||
type OptionItem = {
|
||||
label: string;
|
||||
value: string | number;
|
||||
};
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: string | number | Array<string | number> | null;
|
||||
options?: OptionItem[];
|
||||
multiple?: boolean;
|
||||
placeholder?: string;
|
||||
filterable?: boolean;
|
||||
clearable?: boolean;
|
||||
loading?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: "update:modelValue", value: string | number | Array<string | number> | null): void;
|
||||
}>();
|
||||
|
||||
const onUpdate = (value: string | number | Array<string | number> | null) => {
|
||||
emit("update:modelValue", value);
|
||||
};
|
||||
|
||||
const options = computed(() => props.options ?? []);
|
||||
const multiple = computed(() => props.multiple ?? false);
|
||||
const filterable = computed(() => props.filterable ?? true);
|
||||
const clearable = computed(() => props.clearable ?? true);
|
||||
const loading = computed(() => props.loading ?? false);
|
||||
</script>
|
||||
@@ -8,8 +8,4 @@ export const createDict = (items: DictItem[]): Dict => {
|
||||
return { items: normalized, get, list };
|
||||
};
|
||||
|
||||
export const getDictItem = (dict: Dict, value?: string | null) => dict.get(value);
|
||||
export const getDictLabel = (dict: Dict, value?: string | null) => dict.get(value)?.label || value || "";
|
||||
export const getDictColor = (dict: Dict, value?: string | null) => dict.get(value)?.color;
|
||||
export const getDictOptions = (dict: Dict) =>
|
||||
dict.list().map((i) => ({ label: i.label, value: i.value, disabled: false }));
|
||||
|
||||
@@ -2,18 +2,4 @@ import { TEXT } from "./zh-CN";
|
||||
|
||||
export { TEXT };
|
||||
|
||||
export const formatEnum = (
|
||||
value: string | number | null | undefined,
|
||||
map: Record<string, string>,
|
||||
fallback: string = TEXT.common.fallback
|
||||
) => {
|
||||
if (value === null || value === undefined || value === "") return fallback;
|
||||
return map[String(value)] || fallback;
|
||||
};
|
||||
|
||||
export const formatBool = (value: boolean | null | undefined) => {
|
||||
if (value === null || value === undefined) return TEXT.common.fallback;
|
||||
return value ? TEXT.common.boolean.yes : TEXT.common.boolean.no;
|
||||
};
|
||||
|
||||
export const requiredMessage = (label: string) => `${label}${TEXT.common.validation.requiredSuffix}`;
|
||||
|
||||
+12
-3
@@ -1,7 +1,5 @@
|
||||
import { createApp } from "vue";
|
||||
import { createPinia } from "pinia";
|
||||
import ElementPlus from "element-plus";
|
||||
import zhCn from "element-plus/es/locale/lang/zh-cn";
|
||||
import dayjs from "dayjs";
|
||||
import "dayjs/locale/zh-cn";
|
||||
import "element-plus/dist/index.css";
|
||||
@@ -10,8 +8,11 @@ import "./styles/unified-page.css";
|
||||
|
||||
import App from "./App.vue";
|
||||
import router from "./router";
|
||||
import { configureApiRuntimeHooks } from "./api/runtimeHooks";
|
||||
import { installElementPlus } from "./plugins/elementPlus";
|
||||
import { getToken } from "./utils/auth";
|
||||
import { useStudyStore } from "./store/study";
|
||||
import { extendAccessToken, forceLogout, LOGOUT_REASON_AUTH_EXPIRED } from "./session/sessionManager";
|
||||
import { cleanupTemporaryFiles, initializeSecureSessionStorage, isTauriRuntime, shouldRequireDesktopServerUrl } from "./runtime";
|
||||
|
||||
const bootstrap = async () => {
|
||||
@@ -25,7 +26,15 @@ const bootstrap = async () => {
|
||||
const pinia = createPinia();
|
||||
app.use(pinia);
|
||||
dayjs.locale("zh-cn");
|
||||
app.use(ElementPlus, { locale: zhCn });
|
||||
installElementPlus(app);
|
||||
configureApiRuntimeHooks({
|
||||
clearInvalidStudyAndNavigate: async () => {
|
||||
useStudyStore().clearCurrentStudy();
|
||||
await router.push("/admin/projects");
|
||||
},
|
||||
extendAccessToken,
|
||||
forceAuthExpiredLogout: () => forceLogout(LOGOUT_REASON_AUTH_EXPIRED),
|
||||
});
|
||||
|
||||
// 初始化项目上下文
|
||||
const studyStore = useStudyStore();
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { App } from "vue";
|
||||
import {
|
||||
ElAlert,
|
||||
ElAside,
|
||||
ElAutocomplete,
|
||||
ElAvatar,
|
||||
ElBadge,
|
||||
ElButton,
|
||||
ElCard,
|
||||
ElCheckbox,
|
||||
ElCol,
|
||||
ElCollapse,
|
||||
ElCollapseItem,
|
||||
ElConfigProvider,
|
||||
ElContainer,
|
||||
ElDatePicker,
|
||||
ElDescriptions,
|
||||
ElDescriptionsItem,
|
||||
ElDialog,
|
||||
ElDivider,
|
||||
ElDrawer,
|
||||
ElDropdown,
|
||||
ElDropdownItem,
|
||||
ElDropdownMenu,
|
||||
ElEmpty,
|
||||
ElForm,
|
||||
ElFormItem,
|
||||
ElHeader,
|
||||
ElIcon,
|
||||
ElImage,
|
||||
ElInput,
|
||||
ElInputNumber,
|
||||
ElLink,
|
||||
ElLoading,
|
||||
ElMain,
|
||||
ElMenu,
|
||||
ElMenuItem,
|
||||
ElMenuItemGroup,
|
||||
ElOption,
|
||||
ElOptionGroup,
|
||||
ElPagination,
|
||||
ElPopover,
|
||||
ElProgress,
|
||||
ElRadioButton,
|
||||
ElRadioGroup,
|
||||
ElRow,
|
||||
ElScrollbar,
|
||||
ElSegmented,
|
||||
ElSelect,
|
||||
ElSkeleton,
|
||||
ElSkeletonItem,
|
||||
ElSubMenu,
|
||||
ElSwitch,
|
||||
ElTabPane,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
ElTabs,
|
||||
ElTag,
|
||||
ElTimeline,
|
||||
ElTimelineItem,
|
||||
ElTooltip,
|
||||
ElTree,
|
||||
ElUpload,
|
||||
} from "element-plus";
|
||||
|
||||
const components = [
|
||||
ElAlert,
|
||||
ElAside,
|
||||
ElAutocomplete,
|
||||
ElAvatar,
|
||||
ElBadge,
|
||||
ElButton,
|
||||
ElCard,
|
||||
ElCheckbox,
|
||||
ElCol,
|
||||
ElCollapse,
|
||||
ElCollapseItem,
|
||||
ElConfigProvider,
|
||||
ElContainer,
|
||||
ElDatePicker,
|
||||
ElDescriptions,
|
||||
ElDescriptionsItem,
|
||||
ElDialog,
|
||||
ElDivider,
|
||||
ElDrawer,
|
||||
ElDropdown,
|
||||
ElDropdownItem,
|
||||
ElDropdownMenu,
|
||||
ElEmpty,
|
||||
ElForm,
|
||||
ElFormItem,
|
||||
ElHeader,
|
||||
ElIcon,
|
||||
ElImage,
|
||||
ElInput,
|
||||
ElInputNumber,
|
||||
ElLink,
|
||||
ElMain,
|
||||
ElMenu,
|
||||
ElMenuItem,
|
||||
ElMenuItemGroup,
|
||||
ElOption,
|
||||
ElOptionGroup,
|
||||
ElPagination,
|
||||
ElPopover,
|
||||
ElProgress,
|
||||
ElRadioButton,
|
||||
ElRadioGroup,
|
||||
ElRow,
|
||||
ElScrollbar,
|
||||
ElSegmented,
|
||||
ElSelect,
|
||||
ElSkeleton,
|
||||
ElSkeletonItem,
|
||||
ElSubMenu,
|
||||
ElSwitch,
|
||||
ElTabPane,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
ElTabs,
|
||||
ElTag,
|
||||
ElTimeline,
|
||||
ElTimelineItem,
|
||||
ElTooltip,
|
||||
ElTree,
|
||||
ElUpload,
|
||||
];
|
||||
|
||||
export const installElementPlus = (app: App): void => {
|
||||
for (const component of components) app.use(component);
|
||||
app.use(ElLoading);
|
||||
};
|
||||
@@ -103,7 +103,7 @@ describe("admin project route permissions", () => {
|
||||
const monitoringRouteEnd = source.indexOf("],", monitoringRouteStart);
|
||||
const monitoringRoute = source.slice(monitoringRouteStart, monitoringRouteEnd);
|
||||
|
||||
expect(source).toContain('import SystemMonitoringPage from "../views/admin/SystemMonitoringPage.vue";');
|
||||
expect(source).toContain('const SystemMonitoringPage = () => import("../views/admin/SystemMonitoringPage.vue");');
|
||||
expect(source).toContain('path: "system-monitoring"');
|
||||
expect(monitoringRoute).toContain("component: SystemMonitoringPage");
|
||||
expect(monitoringRoute).toContain("requiresAdmin: true");
|
||||
@@ -123,7 +123,7 @@ describe("admin project route permissions", () => {
|
||||
expect(source).toContain('const DESKTOP_PROJECT_ENTRY_PATH = "/desktop/project-entry";');
|
||||
expect(source).toContain("const resolveWorkbenchEntryPath = (isDesktopRuntime: boolean)");
|
||||
expect(source).toContain("const isWorkbenchEntryPath = (path: string)");
|
||||
expect(source).toContain('import WebWorkbenchEntry from "../views/WebWorkbenchEntry.vue";');
|
||||
expect(source).toContain('const WebWorkbenchEntry = () => import("../views/WebWorkbenchEntry.vue");');
|
||||
expect(source).toContain("path: WEB_WORKBENCH_ENTRY_PATH");
|
||||
expect(source).toContain('name: "WorkbenchEntry"');
|
||||
expect(source).toContain("component: WebWorkbenchEntry");
|
||||
|
||||
@@ -7,65 +7,65 @@ import { findFirstAccessibleProjectPath, getProjectRoutePermission, hasProjectPe
|
||||
import { fetchStudies, fetchStudyDetail } from "../api/studies";
|
||||
import { fetchApiEndpointPermissions } from "../api/projectPermissions";
|
||||
import Layout from "../components/Layout.vue";
|
||||
import Login from "../views/Login.vue";
|
||||
import Register from "../views/Register.vue";
|
||||
import ForgotPassword from "../views/ForgotPassword.vue";
|
||||
import DesktopServerSettings from "../views/DesktopServerSettings.vue";
|
||||
import DesktopProjectEntry from "../views/DesktopProjectEntry.vue";
|
||||
import DesktopSessionRestore from "../views/DesktopSessionRestore.vue";
|
||||
import WebWorkbenchEntry from "../views/WebWorkbenchEntry.vue";
|
||||
import StudyHome from "../views/StudyHome.vue";
|
||||
import FaqDetail from "../views/FaqDetail.vue";
|
||||
import AuditLogs from "../views/admin/AuditLogs.vue";
|
||||
import AdminUsers from "../views/admin/Users.vue";
|
||||
import AdminProjects from "../views/admin/Projects.vue";
|
||||
import AdminSites from "../views/admin/Sites.vue";
|
||||
import PermissionManagement from "../views/admin/PermissionManagement.vue";
|
||||
import SystemMonitoringPage from "../views/admin/SystemMonitoringPage.vue";
|
||||
import EmailSettings from "../views/admin/EmailSettings.vue";
|
||||
import ProjectDetail from "../views/admin/ProjectDetail.vue";
|
||||
import ProfileSettings from "../views/ProfileSettings.vue";
|
||||
import ProjectOverview from "../views/ia/ProjectOverview.vue";
|
||||
import ProjectMilestones from "../views/ia/ProjectMilestones.vue";
|
||||
import FeeContracts from "../views/fees/ContractFees.vue";
|
||||
import FeeContractDetail from "../views/fees/ContractFeeDetail.vue";
|
||||
import DrugShipments from "../views/ia/DrugShipments.vue";
|
||||
import ShipmentDetail from "../views/drug/ShipmentDetail.vue";
|
||||
import MaterialEquipment from "../views/ia/MaterialEquipment.vue";
|
||||
import MaterialEquipmentDetail from "../views/materials/MaterialEquipmentDetail.vue";
|
||||
import DocumentList from "../views/documents/DocumentList.vue";
|
||||
import DocumentDetail from "../views/documents/DocumentDetail.vue";
|
||||
import OfficePreviewWorkspace from "../views/OfficePreviewWorkspace.vue";
|
||||
import StartupFeasibilityEthics from "../views/ia/StartupFeasibilityEthics.vue";
|
||||
import StartupMeetingAuth from "../views/ia/StartupMeetingAuth.vue";
|
||||
import SubjectManagement from "../views/ia/SubjectManagement.vue";
|
||||
import RiskIssueSae from "../views/ia/RiskIssueSae.vue";
|
||||
import RiskIssuePd from "../views/ia/RiskIssuePd.vue";
|
||||
import RiskIssueMonitoringVisits from "../views/ia/RiskIssueMonitoringVisits.vue";
|
||||
import EtmfPlaceholder from "../views/ia/EtmfPlaceholder.vue";
|
||||
import KnowledgeMedicalConsult from "../views/ia/KnowledgeMedicalConsult.vue";
|
||||
import Precautions from "../views/ia/Precautions.vue";
|
||||
import KnowledgeSupportFiles from "../views/ia/KnowledgeSupportFiles.vue";
|
||||
import KnowledgeInstructionFiles from "../views/ia/KnowledgeInstructionFiles.vue";
|
||||
import CollaborationLibrary from "../views/knowledge/CollaborationLibrary.vue";
|
||||
import CollaborationWorkspace from "../views/knowledge/CollaborationWorkspace.vue";
|
||||
import CollaborationShareWorkspace from "../views/knowledge/CollaborationShareWorkspace.vue";
|
||||
import FeasibilityForm from "../views/startup/FeasibilityForm.vue";
|
||||
import FeasibilityDetail from "../views/startup/FeasibilityDetail.vue";
|
||||
import EthicsForm from "../views/startup/EthicsForm.vue";
|
||||
import EthicsDetail from "../views/startup/EthicsDetail.vue";
|
||||
import KickoffForm from "../views/startup/KickoffForm.vue";
|
||||
import KickoffDetail from "../views/startup/KickoffDetail.vue";
|
||||
import TrainingDetail from "../views/startup/TrainingDetail.vue";
|
||||
import PrecautionForm from "../views/knowledge/PrecautionForm.vue";
|
||||
import PrecautionDetail from "../views/knowledge/PrecautionDetail.vue";
|
||||
import SubjectForm from "../views/subjects/SubjectForm.vue";
|
||||
import SubjectDetail from "../views/subjects/SubjectDetail.vue";
|
||||
import { TEXT } from "../locales";
|
||||
import { resolveDesktopRouteRedirect } from "./desktopGuard";
|
||||
import { isTauriRuntime } from "../runtime";
|
||||
import { DESKTOP_SESSION_RESTORE_PATH, shouldPreserveDesktopSessionOnAuthCheckFailure } from "../session/authRecovery";
|
||||
|
||||
const Login = () => import("../views/Login.vue");
|
||||
const Register = () => import("../views/Register.vue");
|
||||
const ForgotPassword = () => import("../views/ForgotPassword.vue");
|
||||
const DesktopServerSettings = () => import("../views/DesktopServerSettings.vue");
|
||||
const DesktopProjectEntry = () => import("../views/DesktopProjectEntry.vue");
|
||||
const DesktopSessionRestore = () => import("../views/DesktopSessionRestore.vue");
|
||||
const WebWorkbenchEntry = () => import("../views/WebWorkbenchEntry.vue");
|
||||
const FaqDetail = () => import("../views/FaqDetail.vue");
|
||||
const AuditLogs = () => import("../views/admin/AuditLogs.vue");
|
||||
const AdminUsers = () => import("../views/admin/Users.vue");
|
||||
const AdminProjects = () => import("../views/admin/Projects.vue");
|
||||
const AdminSites = () => import("../views/admin/Sites.vue");
|
||||
const PermissionManagement = () => import("../views/admin/PermissionManagement.vue");
|
||||
const SystemMonitoringPage = () => import("../views/admin/SystemMonitoringPage.vue");
|
||||
const EmailSettings = () => import("../views/admin/EmailSettings.vue");
|
||||
const ProjectDetail = () => import("../views/admin/ProjectDetail.vue");
|
||||
const ProjectOverview = () => import("../views/ia/ProjectOverview.vue");
|
||||
const ProjectMilestones = () => import("../views/ia/ProjectMilestones.vue");
|
||||
const FeeContracts = () => import("../views/fees/ContractFees.vue");
|
||||
const FeeContractDetail = () => import("../views/fees/ContractFeeDetail.vue");
|
||||
const DrugShipments = () => import("../views/ia/DrugShipments.vue");
|
||||
const ShipmentDetail = () => import("../views/drug/ShipmentDetail.vue");
|
||||
const MaterialEquipment = () => import("../views/ia/MaterialEquipment.vue");
|
||||
const MaterialEquipmentDetail = () => import("../views/materials/MaterialEquipmentDetail.vue");
|
||||
const DocumentList = () => import("../views/documents/DocumentList.vue");
|
||||
const DocumentDetail = () => import("../views/documents/DocumentDetail.vue");
|
||||
const OfficePreviewWorkspace = () => import("../views/OfficePreviewWorkspace.vue");
|
||||
const StartupFeasibilityEthics = () => import("../views/ia/StartupFeasibilityEthics.vue");
|
||||
const StartupMeetingAuth = () => import("../views/ia/StartupMeetingAuth.vue");
|
||||
const SubjectManagement = () => import("../views/ia/SubjectManagement.vue");
|
||||
const RiskIssueSae = () => import("../views/ia/RiskIssueSae.vue");
|
||||
const RiskIssuePd = () => import("../views/ia/RiskIssuePd.vue");
|
||||
const RiskIssueMonitoringVisits = () => import("../views/ia/RiskIssueMonitoringVisits.vue");
|
||||
const EtmfPlaceholder = () => import("../views/ia/EtmfPlaceholder.vue");
|
||||
const KnowledgeMedicalConsult = () => import("../views/ia/KnowledgeMedicalConsult.vue");
|
||||
const Precautions = () => import("../views/ia/Precautions.vue");
|
||||
const KnowledgeSupportFiles = () => import("../views/ia/KnowledgeSupportFiles.vue");
|
||||
const KnowledgeInstructionFiles = () => import("../views/ia/KnowledgeInstructionFiles.vue");
|
||||
const CollaborationLibrary = () => import("../views/knowledge/CollaborationLibrary.vue");
|
||||
const CollaborationWorkspace = () => import("../views/knowledge/CollaborationWorkspace.vue");
|
||||
const CollaborationShareWorkspace = () => import("../views/knowledge/CollaborationShareWorkspace.vue");
|
||||
const FeasibilityForm = () => import("../views/startup/FeasibilityForm.vue");
|
||||
const FeasibilityDetail = () => import("../views/startup/FeasibilityDetail.vue");
|
||||
const EthicsForm = () => import("../views/startup/EthicsForm.vue");
|
||||
const EthicsDetail = () => import("../views/startup/EthicsDetail.vue");
|
||||
const KickoffForm = () => import("../views/startup/KickoffForm.vue");
|
||||
const KickoffDetail = () => import("../views/startup/KickoffDetail.vue");
|
||||
const TrainingDetail = () => import("../views/startup/TrainingDetail.vue");
|
||||
const PrecautionForm = () => import("../views/knowledge/PrecautionForm.vue");
|
||||
const PrecautionDetail = () => import("../views/knowledge/PrecautionDetail.vue");
|
||||
const SubjectForm = () => import("../views/subjects/SubjectForm.vue");
|
||||
const SubjectDetail = () => import("../views/subjects/SubjectDetail.vue");
|
||||
|
||||
const SYSTEM_PERMISSION_READ = "system:permissions:read";
|
||||
const SYSTEM_PERMISSION_PROJECT_CONFIG = "system:permissions:project_config";
|
||||
const WEB_WORKBENCH_ENTRY_PATH = "/workbench";
|
||||
|
||||
@@ -1,20 +1,5 @@
|
||||
import type { StateMachine } from "./types";
|
||||
|
||||
export const getStateLabel = (machine: StateMachine, stateValue?: string | null) => {
|
||||
if (!stateValue) return "";
|
||||
return machine.states[stateValue]?.label || stateValue;
|
||||
};
|
||||
|
||||
export const getStateColor = (machine: StateMachine, stateValue?: string | null) => {
|
||||
if (!stateValue) return undefined;
|
||||
return machine.states[stateValue]?.color;
|
||||
};
|
||||
|
||||
export const getAvailableActions = (machine: StateMachine, currentState?: string | null) => {
|
||||
if (!currentState) return [];
|
||||
return Object.values(machine.actions).filter((a) => a.from.includes(currentState));
|
||||
};
|
||||
|
||||
export const canDoAction = (machine: StateMachine, actionKey: string, currentState?: string | null) => {
|
||||
if (!currentState) return false;
|
||||
const action = machine.actions[actionKey];
|
||||
|
||||
@@ -149,11 +149,6 @@ export interface PasswordResetTokenRequest {
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AdminUserListResponse {
|
||||
items: UserInfo[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface Study {
|
||||
id: string;
|
||||
code: string;
|
||||
|
||||
@@ -59,27 +59,6 @@ export interface DocumentVersion {
|
||||
can_actions?: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowNode {
|
||||
id: string;
|
||||
node_order: number;
|
||||
role: string;
|
||||
name?: string | null;
|
||||
is_required: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface WorkflowTemplate {
|
||||
id: string;
|
||||
trial_id?: string | null;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
is_active: boolean;
|
||||
created_by?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
nodes?: WorkflowNode[];
|
||||
}
|
||||
|
||||
export interface DistributionStats {
|
||||
total: number;
|
||||
received: number;
|
||||
@@ -104,18 +83,6 @@ export interface Distribution {
|
||||
stats?: DistributionStats;
|
||||
}
|
||||
|
||||
export interface Acknowledgement {
|
||||
id: string;
|
||||
distribution_id: string;
|
||||
user_id: string;
|
||||
site_id?: string | null;
|
||||
ack_type: "RECEIVED" | "READ" | "TRAINED";
|
||||
due_at?: string | null;
|
||||
acked_at?: string | null;
|
||||
note?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface DocumentDetail extends DocumentSummary {
|
||||
description?: string | null;
|
||||
version_timeline: DocumentVersion[];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { DocumentScopeType, DocumentSummary } from "./documents";
|
||||
import type { DocumentScopeType } from "./documents";
|
||||
|
||||
export type EtmfNodeStatus = "NOT_REQUIRED" | "MISSING" | "UPLOADED" | "EFFECTIVE" | "INACTIVE";
|
||||
|
||||
@@ -35,18 +35,6 @@ export interface EtmfNodeCreatePayload {
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export interface EtmfNodeUpdatePayload {
|
||||
parent_id?: string | null;
|
||||
code?: string;
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
scope_type?: DocumentScopeType;
|
||||
required?: boolean;
|
||||
expected_doc_type?: string | null;
|
||||
sort_order?: number;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export type EtmfDocumentCreatePayload = {
|
||||
trial_id: string;
|
||||
site_id?: string | null;
|
||||
@@ -57,7 +45,3 @@ export type EtmfDocumentCreatePayload = {
|
||||
owner_id?: string | null;
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
export interface EtmfNodeDocumentList {
|
||||
documents: DocumentSummary[];
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
export interface VisitLostItem {
|
||||
visit_id: string;
|
||||
subject_id: string;
|
||||
subject_no: string;
|
||||
site_id?: string | null;
|
||||
visit_code: string;
|
||||
status: string;
|
||||
updated_at: string;
|
||||
}
|
||||
@@ -41,11 +41,6 @@ export const displayUser = (
|
||||
return (name as string) || displayFallback;
|
||||
};
|
||||
|
||||
export const displayEntity = (entityMap: Record<string, string>, id?: string | null) => {
|
||||
if (!id) return displayFallback;
|
||||
return entityMap[id] || displayFallback;
|
||||
};
|
||||
|
||||
export const displayDate = (value?: string | number | Date | null) => {
|
||||
if (!value) return displayFallback;
|
||||
const date = new Date(value);
|
||||
|
||||
@@ -5,59 +5,6 @@ import { TEXT } from "../locales";
|
||||
import { getProjectRole, isSystemAdmin } from "./roles";
|
||||
import { isApiPermissionAllowed } from "./apiPermissionValue";
|
||||
|
||||
const PERMISSIONS: Record<string, string[]> = {
|
||||
"subject.create": ["ADMIN"],
|
||||
"subject.enroll": ["ADMIN"],
|
||||
"subject.complete": ["ADMIN"],
|
||||
"subject.drop": ["ADMIN"],
|
||||
"subject.delete": ["ADMIN"],
|
||||
"ae.create": ["ADMIN"],
|
||||
"ae.close": ["ADMIN"],
|
||||
"faq.edit": ["ADMIN"],
|
||||
"faq.update": ["ADMIN"],
|
||||
"faq.delete": ["ADMIN"],
|
||||
"faq.create": ["ADMIN"],
|
||||
"faq.reply": ["ADMIN"],
|
||||
"faq.reply.delete": ["ADMIN"],
|
||||
"faq.category.read": ["ADMIN"],
|
||||
"faq.category.create": ["ADMIN"],
|
||||
"faq.category.update": ["ADMIN"],
|
||||
"faq.category.delete": ["ADMIN"],
|
||||
"precautions.create": ["ADMIN"],
|
||||
"precautions.update": ["ADMIN"],
|
||||
"precautions.delete": ["ADMIN"],
|
||||
"startup.initiation.create": ["ADMIN"],
|
||||
"startup.initiation.update": ["ADMIN"],
|
||||
"startup.initiation.delete": ["ADMIN"],
|
||||
"startup.ethics.create": ["ADMIN"],
|
||||
"startup.ethics.update": ["ADMIN"],
|
||||
"startup.ethics.delete": ["ADMIN"],
|
||||
"startup.auth.create": ["ADMIN"],
|
||||
"startup.auth.update": ["ADMIN"],
|
||||
"startup.auth.delete": ["ADMIN"],
|
||||
"project.milestones.update": ["ADMIN"],
|
||||
"project.members.list": ["ADMIN"],
|
||||
"project.members.candidates": ["ADMIN"],
|
||||
"project.members.create": ["ADMIN"],
|
||||
"project.members.update": ["ADMIN"],
|
||||
"project.members.delete": ["ADMIN"],
|
||||
"site.manage": ["ADMIN"],
|
||||
"site.cra.bind": ["ADMIN"],
|
||||
"fees.contract.create": ["ADMIN"],
|
||||
"fees.contract.update": ["ADMIN"],
|
||||
"fees.contract.delete": ["ADMIN"],
|
||||
"documents.read": ["ADMIN"],
|
||||
"documents.create": ["ADMIN"],
|
||||
"documents.update": ["ADMIN"],
|
||||
"documents.delete": ["ADMIN"],
|
||||
"collaboration.read": ["ADMIN"],
|
||||
"collaboration.create": ["ADMIN"],
|
||||
"collaboration.edit": ["ADMIN"],
|
||||
"collaboration.manage": ["ADMIN"],
|
||||
"collaboration.export": ["ADMIN"],
|
||||
"collaboration.delete": ["ADMIN"],
|
||||
};
|
||||
|
||||
const REASONS: Record<string, string> = {
|
||||
"subject.enroll": TEXT.modules.permissions.subjectEnroll,
|
||||
"subject.complete": TEXT.modules.permissions.subjectComplete,
|
||||
|
||||
@@ -174,9 +174,6 @@ const userDisplayName = computed(
|
||||
() => auth.user?.full_name || auth.user?.username || auth.user?.email || TEXT.common.labels.userFallback,
|
||||
);
|
||||
const userInitial = computed(() => userDisplayName.value.charAt(0).toUpperCase() || TEXT.common.labels.userInitialFallback);
|
||||
const entrySubtitle = computed(() =>
|
||||
canEnterManagement.value ? "进入系统管理,或选择一个项目开始桌面工作。" : "请选择本次要进入的项目。",
|
||||
);
|
||||
|
||||
const statusLabel = (status: string | undefined) =>
|
||||
status ? TEXT.enums.projectStatus[status as keyof typeof TEXT.enums.projectStatus] || status : "未知";
|
||||
|
||||
@@ -368,7 +368,7 @@ import {
|
||||
sendRegisterEmailCode,
|
||||
verifyRegisterEmailCode,
|
||||
} from "../api/auth";
|
||||
import type { ApiError, RegisterRequest } from "../types/api";
|
||||
import type { ApiError } from "../types/api";
|
||||
import { TEXT, requiredMessage } from "../locales";
|
||||
import { privacyPolicySections, serviceTermsSections } from "../content/authProtocol";
|
||||
|
||||
|
||||
@@ -1,371 +0,0 @@
|
||||
<template>
|
||||
<div class="study-home-container unified-shell" v-if="study.currentStudy">
|
||||
<!-- 概览头部 -->
|
||||
<div class="home-header">
|
||||
<div class="header-content">
|
||||
<h1 class="welcome-title">{{ TEXT.modules.projectOverview.title }}</h1>
|
||||
<p class="page-subtitle">{{ TEXT.modules.projectOverview.subtitle }}</p>
|
||||
<p class="study-info">
|
||||
<span class="study-name">{{ study.currentStudy.name }}</span>
|
||||
<span class="study-divider">/</span>
|
||||
<span class="study-code">{{ study.currentStudy.code }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="header-meta">
|
||||
<el-tag effect="plain" class="role-tag">{{ TEXT.common.labels.role }}: {{ roleLabel }}</el-tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据指标网格 -->
|
||||
<div class="stats-grid">
|
||||
<div class="stats-item">
|
||||
<KpiCard
|
||||
:title="TEXT.modules.projectOverview.kpiProgress"
|
||||
:value="progress?.milestones_done ?? 0"
|
||||
:unit="` / ${progress?.milestones_total ?? 0}`"
|
||||
:subtext="milestoneCompletionRate"
|
||||
:loading="loading.progress"
|
||||
:icon="List"
|
||||
/>
|
||||
</div>
|
||||
<div class="stats-item">
|
||||
<KpiCard
|
||||
:title="TEXT.modules.projectOverview.kpiOverdueAes"
|
||||
:value="overdueAes"
|
||||
:unit="TEXT.common.units.case"
|
||||
:subtext="TEXT.modules.projectOverview.kpiOverdueAesHint"
|
||||
:loading="loading.overdueAes"
|
||||
:icon="Warning"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="canReadFinanceContracts" class="stats-item">
|
||||
<KpiCard
|
||||
:title="TEXT.modules.projectOverview.kpiFinanceTotal"
|
||||
:value="formatAmount(financeSummary?.total_amount ?? 0)"
|
||||
:subtext="`${TEXT.modules.projectOverview.kpiFinancePaid}:¥${formatAmount(financeSummary?.paid_amount ?? 0)}`"
|
||||
:loading="loading.finance"
|
||||
:icon="Money"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 通知/警告 -->
|
||||
<el-alert
|
||||
v-if="overdueAes > 0"
|
||||
type="warning"
|
||||
:title="TEXT.modules.projectOverview.alertWarning"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="home-alert"
|
||||
/>
|
||||
<el-alert
|
||||
v-else
|
||||
type="success"
|
||||
:title="TEXT.modules.projectOverview.alertOk"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="home-alert"
|
||||
/>
|
||||
|
||||
<!-- 通知 -->
|
||||
<el-card class="notifications-card unified-shell">
|
||||
<div class="notifications-header">
|
||||
<span class="notifications-title">{{ TEXT.modules.projectOverview.notificationsTitle }}</span>
|
||||
<span class="notifications-subtitle">{{ TEXT.modules.projectOverview.notificationsSubtitle }}</span>
|
||||
</div>
|
||||
<el-skeleton v-if="loading.notifications" :rows="3" animated />
|
||||
<StateEmpty v-else-if="!notifications.length" :description="TEXT.modules.projectOverview.notificationsEmpty" />
|
||||
<div v-else class="notification-list">
|
||||
<div class="notification-item" :class="{ 'is-unread': !item.read_at }" v-for="item in notifications" :key="item.id">
|
||||
<div class="notification-main">
|
||||
<div class="notification-title">
|
||||
<span class="notification-doc">{{ item.document_title }}</span>
|
||||
<span class="notification-version">V{{ item.version_no }}</span>
|
||||
</div>
|
||||
<div class="notification-meta">
|
||||
<span class="notification-time">{{ formatDate(item.effective_at || item.created_at) }}</span>
|
||||
<span v-if="item.change_summary" class="notification-summary">{{ item.change_summary }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<el-button link type="primary" @click="openDocument(item)">
|
||||
{{ TEXT.common.actions.view }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<!-- 快捷模块 -->
|
||||
<div class="quick-nav-section">
|
||||
<QuickActions />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="empty-state-container">
|
||||
<StateEmpty :description="TEXT.common.empty.selectProject" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useStudyStore } from "../store/study";
|
||||
import { fetchFinanceSummary, fetchOverdueAesCount, fetchProgress } from "../api/dashboard";
|
||||
import { listNotifications } from "../api/notifications";
|
||||
import { markDesktopNotificationRead } from "../api/desktopNotifications";
|
||||
import KpiCard from "../components/KpiCard.vue";
|
||||
import QuickActions from "../components/QuickActions.vue";
|
||||
import { List, Warning, Money } from "@element-plus/icons-vue";
|
||||
import StateEmpty from "../components/StateEmpty.vue";
|
||||
import { getProjectRole, isSystemAdmin } from "../utils/roles";
|
||||
import { isApiPermissionAllowed } from "../utils/apiPermissionValue";
|
||||
import { useRoleTemplateMeta } from "../composables/useRoleTemplateMeta";
|
||||
import { TEXT } from "../locales";
|
||||
import type { NotificationItem } from "../types/notifications";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const study = useStudyStore();
|
||||
const router = useRouter();
|
||||
const { roleLabel: displayRoleLabel, loadRoleTemplates } = useRoleTemplateMeta();
|
||||
|
||||
const progress = ref<any>(null);
|
||||
const financeSummary = ref<any>(null);
|
||||
const overdueAes = ref<number>(0);
|
||||
const notifications = ref<NotificationItem[]>([]);
|
||||
|
||||
const loading = ref({
|
||||
progress: false,
|
||||
finance: false,
|
||||
overdueAes: false,
|
||||
notifications: false,
|
||||
});
|
||||
|
||||
const milestoneCompletionRate = computed(() => {
|
||||
const total = progress.value?.milestones_total ?? 0;
|
||||
if (!total) return TEXT.modules.projectOverview.noMilestones;
|
||||
const rate = (progress.value?.milestones_done ?? 0) / total;
|
||||
return TEXT.modules.projectOverview.progressLabel.replace("{rate}", `${(rate * 100).toFixed(0)}%`);
|
||||
});
|
||||
|
||||
const projectRole = computed(() => {
|
||||
if (isSystemAdmin(auth.user)) return "ADMIN";
|
||||
return getProjectRole(study.currentStudy, study.currentStudyRole);
|
||||
});
|
||||
const roleLabel = computed(() => displayRoleLabel(projectRole.value));
|
||||
const canReadFinanceContracts = computed(() => {
|
||||
if (isSystemAdmin(auth.user)) return true;
|
||||
const role = projectRole.value;
|
||||
if (!role) return false;
|
||||
return isApiPermissionAllowed(study.currentPermissions?.[role]?.["fees_contracts:read"]);
|
||||
});
|
||||
|
||||
const formatAmount = (val: number) => {
|
||||
return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2 }).format(val);
|
||||
};
|
||||
|
||||
const loadData = async () => {
|
||||
const studyId = study.currentStudy?.id;
|
||||
if (!studyId) return;
|
||||
|
||||
loading.value.progress = true;
|
||||
loading.value.finance = canReadFinanceContracts.value;
|
||||
loading.value.overdueAes = true;
|
||||
loading.value.notifications = true;
|
||||
try {
|
||||
const [pRes, fRes, aesRes, nRes] = await Promise.allSettled([
|
||||
fetchProgress(studyId),
|
||||
canReadFinanceContracts.value ? fetchFinanceSummary(studyId) : Promise.resolve(null),
|
||||
fetchOverdueAesCount(studyId),
|
||||
listNotifications(studyId, { limit: 5 }),
|
||||
]);
|
||||
|
||||
if (pRes.status === "fulfilled") progress.value = pRes.value.data;
|
||||
if (fRes.status === "fulfilled" && fRes.value) financeSummary.value = fRes.value.data;
|
||||
if (aesRes.status === "fulfilled") overdueAes.value = aesRes.value.data?.total ?? 0;
|
||||
if (nRes.status === "fulfilled") notifications.value = nRes.value.data || [];
|
||||
} finally {
|
||||
loading.value.progress = false;
|
||||
loading.value.finance = false;
|
||||
loading.value.overdueAes = false;
|
||||
loading.value.notifications = false;
|
||||
}
|
||||
};
|
||||
|
||||
const resetData = () => {
|
||||
progress.value = null;
|
||||
financeSummary.value = null;
|
||||
overdueAes.value = 0;
|
||||
notifications.value = [];
|
||||
};
|
||||
|
||||
const formatDate = (value?: string | null) => {
|
||||
if (!value) return TEXT.common.fallback;
|
||||
return value.replace("T", " ").replace("Z", "").split(".")[0];
|
||||
};
|
||||
|
||||
const openDocument = async (item: NotificationItem) => {
|
||||
await markDesktopNotificationRead(item.id).catch(() => {});
|
||||
item.read_at = new Date().toISOString();
|
||||
router.push(`/documents/${item.document_id}`);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadRoleTemplates();
|
||||
loadData();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => study.currentStudy?.id,
|
||||
() => {
|
||||
resetData();
|
||||
loadData();
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.study-home-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.home-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.welcome-title {
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
color: var(--ctms-text-main);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-subtitle {
|
||||
font-size: 13px;
|
||||
color: var(--ctms-text-secondary);
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
|
||||
.study-info {
|
||||
margin: 6px 0 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--ctms-text-secondary);
|
||||
}
|
||||
|
||||
.study-divider {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.role-tag {
|
||||
background-color: #ffffff;
|
||||
border-color: var(--ctms-border-color);
|
||||
color: var(--ctms-text-regular);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.home-alert {
|
||||
border: 1px solid var(--ctms-border-color);
|
||||
border-radius: var(--ctms-radius);
|
||||
}
|
||||
|
||||
.notifications-card {
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.notifications-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.notifications-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--ctms-text-main);
|
||||
}
|
||||
|
||||
.notifications-subtitle {
|
||||
font-size: 12px;
|
||||
color: var(--ctms-text-secondary);
|
||||
}
|
||||
|
||||
.notification-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.notification-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
background: var(--ctms-bg-muted);
|
||||
}
|
||||
|
||||
.notification-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.notification-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 500;
|
||||
color: var(--ctms-text-main);
|
||||
}
|
||||
|
||||
.notification-version {
|
||||
font-size: 12px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 10px;
|
||||
background: var(--ctms-primary-light);
|
||||
color: var(--ctms-primary);
|
||||
}
|
||||
|
||||
.notification-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--ctms-text-secondary);
|
||||
}
|
||||
|
||||
.notification-summary {
|
||||
max-width: 360px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.quick-nav-section {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.empty-state-container {
|
||||
padding-top: 100px;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.stats-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,71 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import ApiPermissions from "@/views/admin/ApiPermissions.vue";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
||||
vi.mock("vue-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("vue-router")>("vue-router");
|
||||
return {
|
||||
...actual,
|
||||
useRoute: () => ({ params: { id: "study-1" } }),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/api/projectPermissions", () => ({
|
||||
fetchApiEndpointPermissions: vi.fn().mockResolvedValue({ data: {} }),
|
||||
updateApiEndpointPermissions: vi.fn().mockResolvedValue({ data: {} }),
|
||||
fetchPermissionMetrics: vi.fn().mockResolvedValue({ data: {} }),
|
||||
fetchCacheStats: vi.fn().mockResolvedValue({ data: {} }),
|
||||
fetchPermissionAlerts: vi.fn().mockResolvedValue({ data: { total: 0, alerts: [] } }),
|
||||
fetchPermissionHealth: vi.fn().mockResolvedValue({ data: {} }),
|
||||
resetPermissionMetrics: vi.fn().mockResolvedValue({ data: undefined }),
|
||||
}));
|
||||
|
||||
describe("ApiPermissions.vue", () => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, "localStorage", {
|
||||
value: {
|
||||
getItem: vi.fn(() => null),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
value: window.localStorage,
|
||||
configurable: true,
|
||||
});
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("renders permission management page", () => {
|
||||
const wrapper = mount(ApiPermissions, {
|
||||
global: {
|
||||
stubs: {
|
||||
ApiEndpointPermissions: true,
|
||||
PermissionMonitoring: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.find(".permission-page").exists()).toBe(true);
|
||||
expect(wrapper.find(".permission-title h2").text()).toBe("权限管理");
|
||||
});
|
||||
|
||||
it("renders tabs", () => {
|
||||
const source = readFileSync(resolve(__dirname, "./ApiPermissions.vue"), "utf8");
|
||||
|
||||
expect(source).toContain('label="角色权限"');
|
||||
expect(source).not.toContain('label="权限监控"');
|
||||
expect(source).not.toContain("<PermissionMonitoring");
|
||||
});
|
||||
|
||||
it("has save button disabled when not dirty", () => {
|
||||
const source = readFileSync(resolve(__dirname, "./ApiPermissions.vue"), "utf8");
|
||||
|
||||
expect(source).toContain(':disabled="!dirty"');
|
||||
});
|
||||
});
|
||||
@@ -1,229 +0,0 @@
|
||||
<template>
|
||||
<div class="permission-page">
|
||||
<div class="permission-shell unified-shell" v-loading="loading">
|
||||
<!-- 顶部操作栏 -->
|
||||
<div class="permission-header unified-action-bar">
|
||||
<div class="permission-title">
|
||||
<el-icon><Key /></el-icon>
|
||||
<h2>权限管理</h2>
|
||||
</div>
|
||||
<div class="permission-project-meta">
|
||||
<span class="meta-item">
|
||||
<span class="meta-label">项目编号</span>
|
||||
<strong>{{ project?.code || "-" }}</strong>
|
||||
</span>
|
||||
<span class="meta-separator" />
|
||||
<span class="meta-item">
|
||||
<span class="meta-label">项目名称</span>
|
||||
<strong>{{ project?.name || "-" }}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<div class="permission-actions">
|
||||
<el-button type="primary" :loading="saving" :disabled="!dirty" @click="save">
|
||||
<el-icon><Check /></el-icon>
|
||||
保存
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 标签页 -->
|
||||
<el-tabs v-model="activeTab">
|
||||
<!-- 接口级权限 -->
|
||||
<el-tab-pane label="角色权限" name="api">
|
||||
<PermissionTemplateSelector
|
||||
:study-id="studyId"
|
||||
:current-permissions="currentPermissionsForTemplate"
|
||||
@applied="onTemplateApplied"
|
||||
/>
|
||||
<el-divider />
|
||||
<ApiEndpointPermissions
|
||||
:project="project"
|
||||
:matrix="apiMatrix"
|
||||
@update="onApiMatrixUpdate"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { Key, Check } from "@element-plus/icons-vue";
|
||||
import type {
|
||||
ApiEndpointPermissionsResponse,
|
||||
} from "@/types/api";
|
||||
import {
|
||||
fetchApiEndpointPermissions,
|
||||
updateApiEndpointPermissions,
|
||||
} from "@/api/projectPermissions";
|
||||
import { useStudyStore } from "@/store/study";
|
||||
import ApiEndpointPermissions from "@/components/ApiEndpointPermissions.vue";
|
||||
import PermissionTemplateSelector from "@/components/PermissionTemplateSelector.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const studyStore = useStudyStore();
|
||||
|
||||
const activeTab = ref<"api">("api");
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
|
||||
const project = computed(() => studyStore.currentStudy);
|
||||
const studyId = computed(() => {
|
||||
const id = route.params.id;
|
||||
return typeof id === "string" ? id : (id as string[])[0];
|
||||
});
|
||||
|
||||
// 权限数据
|
||||
const apiMatrix = ref<ApiEndpointPermissionsResponse | null>(null);
|
||||
|
||||
// 脏值检测
|
||||
const dirty = ref(false);
|
||||
|
||||
const loadPermissionData = async () => {
|
||||
if (!studyId.value) return;
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
const apiRes = await fetchApiEndpointPermissions(studyId.value);
|
||||
apiMatrix.value = apiRes.data;
|
||||
dirty.value = false;
|
||||
} catch (error) {
|
||||
ElMessage.error("加载权限数据失败");
|
||||
console.error(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const onApiMatrixUpdate = (newMatrix: ApiEndpointPermissionsResponse) => {
|
||||
apiMatrix.value = newMatrix;
|
||||
dirty.value = true;
|
||||
};
|
||||
|
||||
// 将当前 apiMatrix 转换为模板所需的 {role: {endpoint_key: bool}} 格式
|
||||
const currentPermissionsForTemplate = computed(() => {
|
||||
if (!apiMatrix.value) return undefined;
|
||||
const result: Record<string, Record<string, boolean>> = {};
|
||||
for (const [role, endpoints] of Object.entries(apiMatrix.value)) {
|
||||
result[role] = {};
|
||||
for (const [key, val] of Object.entries(endpoints)) {
|
||||
result[role][key] = typeof val === "boolean" ? val : val.allowed;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
const onTemplateApplied = async (permissions: Record<string, Record<string, { allowed: boolean }>>) => {
|
||||
// 模板应用后刷新权限矩阵
|
||||
await loadPermissionData();
|
||||
ElMessage.success("权限已更新");
|
||||
};
|
||||
|
||||
const flattenMatrix = (matrix: ApiEndpointPermissionsResponse): Record<string, Record<string, boolean>> => {
|
||||
const result: Record<string, Record<string, boolean>> = {};
|
||||
for (const [role, endpoints] of Object.entries(matrix)) {
|
||||
result[role] = {};
|
||||
for (const [key, val] of Object.entries(endpoints)) {
|
||||
result[role][key] = typeof val === "boolean" ? val : val.allowed;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!studyId.value || !dirty.value) return;
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
if (apiMatrix.value) {
|
||||
const res = await updateApiEndpointPermissions(studyId.value, flattenMatrix(apiMatrix.value));
|
||||
apiMatrix.value = res.data;
|
||||
}
|
||||
|
||||
dirty.value = false;
|
||||
ElMessage.success("权限已保存");
|
||||
|
||||
await loadPermissionData();
|
||||
} catch (error) {
|
||||
ElMessage.error("保存权限失败");
|
||||
console.error(error);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadPermissionData();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.permission-page {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.permission-shell {
|
||||
background: #fff;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.permission-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 20px;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.permission-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.permission-project-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
flex: 1;
|
||||
font-size: 14px;
|
||||
color: #606266;
|
||||
}
|
||||
|
||||
.meta-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.meta-label {
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.meta-separator {
|
||||
width: 1px;
|
||||
height: 20px;
|
||||
background: #dcdfe6;
|
||||
}
|
||||
|
||||
.permission-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
:deep(.el-tabs) {
|
||||
padding: 20px;
|
||||
}
|
||||
</style>
|
||||
@@ -56,7 +56,8 @@ describe("permission management custom roles", () => {
|
||||
expect(source).toContain("const roleDisplayName = (row: PermissionTemplate) => row.name;");
|
||||
expect(source).toContain("await loadPermissionData();");
|
||||
expect(source).toContain('Object.keys(assignableRoleLabels.value)[0] || ""');
|
||||
expect(source).toContain('role === "ADMIN"');
|
||||
expect(source).toContain("const canAssignProjectRole");
|
||||
expect(source).toContain("(ROLE_RANK[role] ?? 0) < ROLE_RANK.PM");
|
||||
expect(source).not.toContain("const ALL_ROLES = [");
|
||||
expect(source).not.toContain("const ROLE_LABELS");
|
||||
});
|
||||
|
||||
@@ -655,7 +655,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch, reactive, nextTick } from "vue";
|
||||
import { ref, computed, onMounted, watch, reactive } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { Files, Search, ArrowRight } from "@element-plus/icons-vue";
|
||||
@@ -817,23 +817,6 @@ const onStudyChange = async (id: string) => {
|
||||
|
||||
const activeRolesInStudy = computed(() => activeRolesDraft.value);
|
||||
|
||||
// 把 apiMatrix(可能混有 { allowed: boolean } 或 boolean)展平为 boolean 格式
|
||||
const flattenMatrix = (
|
||||
matrix: ApiEndpointPermissionsResponse,
|
||||
{ includePm = true }: { includePm?: boolean } = {}
|
||||
): Record<string, Record<string, boolean>> => {
|
||||
const result: Record<string, Record<string, boolean>> = {};
|
||||
for (const [role, endpoints] of Object.entries(matrix as Record<string, Record<string, any>>)) {
|
||||
if (role === "ADMIN") continue;
|
||||
if (role === "PM" && !includePm) continue;
|
||||
result[role] = {};
|
||||
for (const [key, val] of Object.entries(endpoints)) {
|
||||
result[role][key] = typeof val === "boolean" ? val : val.allowed;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const flattenRolePermissions = (
|
||||
role: string,
|
||||
permissions: Record<string, boolean>
|
||||
|
||||
@@ -1833,77 +1833,6 @@
|
||||
</template>
|
||||
</el-drawer>
|
||||
|
||||
<el-drawer
|
||||
v-if="siteEnrollmentEditorVisible"
|
||||
v-model="siteEnrollmentEditorVisible"
|
||||
direction="rtl"
|
||||
size="480px"
|
||||
:close-on-click-modal="true"
|
||||
:before-close="siteEnrollmentEditorDirtyGuard.beforeClose"
|
||||
:show-close="false"
|
||||
class="setup-milestone-editor-drawer"
|
||||
>
|
||||
<template #header>
|
||||
<div class="sme-header">
|
||||
<div class="sme-header-title">编辑中心入组计划</div>
|
||||
<div class="sme-header-subtitle">配置中心入组目标与时间范围</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" class="sme-form">
|
||||
<!-- 中心选择 -->
|
||||
<div class="sme-group">
|
||||
<div class="sme-group-title"><span class="sme-dot sme-dot-blue"></span>中心选择</div>
|
||||
<el-row :gutter="12">
|
||||
<el-col :span="12">
|
||||
<el-form-item label="中心">
|
||||
<el-select v-model="siteEnrollmentEditorForm.siteId" filterable clearable placeholder="选择中心" class="w-full">
|
||||
<el-option
|
||||
v-for="site in siteSelectOptions"
|
||||
:key="site.id"
|
||||
:label="site.label"
|
||||
:value="site.id"
|
||||
:disabled="isSiteEnrollmentSiteTaken(site.id)"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-form-item label="计划例数">
|
||||
<el-input-number v-model="siteEnrollmentEditorForm.target" :min="0" controls-position="right" class="w-full" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
<!-- 时间计划 -->
|
||||
<div class="sme-group">
|
||||
<div class="sme-group-title"><span class="sme-dot sme-dot-amber"></span>时间计划</div>
|
||||
<el-row :gutter="12">
|
||||
<el-col :span="12">
|
||||
<el-form-item label="启动日期">
|
||||
<el-date-picker v-model="siteEnrollmentEditorForm.startDate" type="date" value-format="YYYY-MM-DD" class="w-full" placeholder="选择日期" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-form-item label="完成日期">
|
||||
<el-date-picker v-model="siteEnrollmentEditorForm.endDate" type="date" value-format="YYYY-MM-DD" class="w-full" placeholder="选择日期" />
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
<!-- 备注 -->
|
||||
<div class="sme-group">
|
||||
<div class="sme-group-title"><span class="sme-dot sme-dot-gray"></span>备注</div>
|
||||
<el-input v-model="siteEnrollmentEditorForm.note" type="textarea" :rows="3" placeholder="请输入备注信息" />
|
||||
</div>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="sme-footer">
|
||||
<el-button @click="siteEnrollmentEditorVisible = false">取消</el-button>
|
||||
<el-button type="primary" @click="saveSiteEnrollmentEditor">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-drawer>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1920,7 +1849,6 @@ import { listMembers } from "../../api/members";
|
||||
import { fetchSites } from "../../api/sites";
|
||||
import type { Site, Study } from "../../types/api";
|
||||
import type {
|
||||
CenterConfirmDraft,
|
||||
ProjectPublishSnapshot,
|
||||
ProjectMilestoneDraft,
|
||||
SetupConfigDraft,
|
||||
@@ -2117,8 +2045,6 @@ const projectMilestoneEditorVisible = ref(false);
|
||||
const projectMilestoneEditingIndex = ref<number>(-1);
|
||||
const siteMilestoneEditorVisible = ref(false);
|
||||
const siteMilestoneEditingIndex = ref<number>(-1);
|
||||
const siteEnrollmentEditorVisible = ref(false);
|
||||
const siteEnrollmentEditingIndex = ref<number>(-1);
|
||||
|
||||
type IndexedEditorController = {
|
||||
visible: Ref<boolean>;
|
||||
@@ -2132,10 +2058,6 @@ const siteMilestoneEditor: IndexedEditorController = {
|
||||
visible: siteMilestoneEditorVisible,
|
||||
index: siteMilestoneEditingIndex,
|
||||
};
|
||||
const siteEnrollmentEditor: IndexedEditorController = {
|
||||
visible: siteEnrollmentEditorVisible,
|
||||
index: siteEnrollmentEditingIndex,
|
||||
};
|
||||
|
||||
const projectMilestoneEditorForm = reactive<ProjectMilestoneDraft>({
|
||||
id: "",
|
||||
@@ -2156,19 +2078,8 @@ const siteMilestoneEditorForm = reactive<SiteMilestoneDraft>({
|
||||
remark: "",
|
||||
status: "未开始",
|
||||
});
|
||||
const siteEnrollmentEditorForm = reactive<SiteEnrollmentPlanDraft>({
|
||||
id: "",
|
||||
siteId: "",
|
||||
siteName: "",
|
||||
target: 0,
|
||||
startDate: "",
|
||||
endDate: "",
|
||||
note: "",
|
||||
stageBreakdown: "",
|
||||
});
|
||||
const projectMilestoneEditorDirtyGuard = useDrawerDirtyGuard(() => projectMilestoneEditorForm);
|
||||
const siteMilestoneEditorDirtyGuard = useDrawerDirtyGuard(() => siteMilestoneEditorForm);
|
||||
const siteEnrollmentEditorDirtyGuard = useDrawerDirtyGuard(() => siteEnrollmentEditorForm);
|
||||
|
||||
|
||||
type EnrollmentCycle = "month" | "quarter";
|
||||
@@ -2494,7 +2405,6 @@ const currentStepTitle = computed(() => `第${activeStep.value + 1}步:${steps
|
||||
const setupPublishedVersionText = computed(() => {
|
||||
return setupPublishedVersion.value || "v0";
|
||||
});
|
||||
const hasProjectPendingChanges = computed(() => hasFormUnsavedChanges.value);
|
||||
const draftSyncStatus = computed<DraftSyncStatus>(() => {
|
||||
const formDirty = Boolean(formBaselineSnapshot.value && serializeFormForCompare() !== formBaselineSnapshot.value);
|
||||
if (formDirty || setupDirtySinceLastPersist.value || Boolean(autoSaveTimer.value)) {
|
||||
@@ -2623,7 +2533,6 @@ const buildProjectPublishSnapshot = (): ProjectPublishSnapshot =>
|
||||
status: form.value.status,
|
||||
visit_schedule: normalizeVisitSchedule(form.value.visit_schedule),
|
||||
});
|
||||
const serializeProjectForPublishCompare = (): string => JSON.stringify(buildProjectPublishSnapshot());
|
||||
const hasFormUnsavedChanges = computed(() => Boolean(formBaselineSnapshot.value && serializeFormForCompare() !== formBaselineSnapshot.value));
|
||||
const hasSetupDiffFromServer = (): boolean =>
|
||||
Boolean(setupServerSnapshot.value && serializeSetupForCompare() !== setupServerSnapshot.value);
|
||||
@@ -2654,9 +2563,6 @@ const reconcileDraftSyncStateBeforePublish = () => {
|
||||
clearLocalProjectDraft();
|
||||
}
|
||||
};
|
||||
const hasUnsavedChanges = computed(
|
||||
() => hasFormUnsavedChanges.value || setupDirtySinceLastPersist.value || Boolean(autoSaveTimer.value)
|
||||
);
|
||||
const hasSetupDraftUnsavedChanges = computed(() => setupDirtySinceLastPersist.value || Boolean(autoSaveTimer.value));
|
||||
const hasLeaveGuardChanges = computed(
|
||||
() => hasFormUnsavedChanges.value || hasSetupDraftUnsavedChanges.value || draftSyncStatus.value !== "SYNCED"
|
||||
@@ -3088,7 +2994,6 @@ const toDateOnly = (value: string | null | undefined): Date | null => {
|
||||
}
|
||||
return date;
|
||||
};
|
||||
const pad2 = (value: number): string => String(value).padStart(2, "0");
|
||||
const getQuarter = (month: number): number => Math.floor((month - 1) / 3) + 1;
|
||||
const toYearMonthIndex = (year: number, month: number): number => year * 12 + (month - 1);
|
||||
const buildYearMonthKey = (year: number, month: number): string => `${year}-${String(month).padStart(2, "0")}`;
|
||||
@@ -3324,20 +3229,6 @@ const centerConfiguredSiteCount = computed(() => {
|
||||
const centerPlannedCount = computed(() => {
|
||||
return Array.from(centerEnrollmentTargetMap.value.values()).reduce((sum, target) => sum + target, 0);
|
||||
});
|
||||
const centerPendingCount = computed(() => {
|
||||
const totalTarget = normalizeEnrollmentTarget(currentSetupDraft.value.enrollmentPlan.totalTarget);
|
||||
return Math.max(totalTarget - centerPlannedCount.value, 0);
|
||||
});
|
||||
const centerOverflowCount = computed(() => {
|
||||
const totalTarget = normalizeEnrollmentTarget(currentSetupDraft.value.enrollmentPlan.totalTarget);
|
||||
return Math.max(centerPlannedCount.value - totalTarget, 0);
|
||||
});
|
||||
const centerUnplannedSiteCount = computed(() => {
|
||||
const activeSites = siteOptions.value.filter((site) => site.is_active !== false);
|
||||
if (!activeSites.length) return 0;
|
||||
const plannedSiteIds = centerEnrollmentTargetMap.value;
|
||||
return activeSites.filter((site) => !plannedSiteIds.has(site.id)).length;
|
||||
});
|
||||
const getSiteEnrollmentTargetsByCycle = (row: SiteEnrollmentPlanDraft): Record<EnrollmentCycle, Record<string, number>> => {
|
||||
const parsed = parseSiteEnrollmentStageBreakdown(row.stageBreakdown);
|
||||
return {
|
||||
@@ -3601,14 +3492,6 @@ const getSiteOptionLabel = (site: Partial<Site> | null | undefined): string => {
|
||||
if (siteId) return `中心-${siteId.slice(0, 8)}`;
|
||||
return "未命名中心";
|
||||
};
|
||||
const siteSelectOptions = computed(() =>
|
||||
siteOptions.value
|
||||
.map((site) => ({
|
||||
id: normalizeSiteId(String(site.id || "")),
|
||||
label: getSiteOptionLabel(site),
|
||||
}))
|
||||
.filter((site) => Boolean(site.id))
|
||||
);
|
||||
const getSiteName = (siteId: string): string => {
|
||||
const normalizedSiteId = normalizeSiteId(siteId);
|
||||
const matched = siteOptions.value.find((s) => normalizeSiteId(String(s.id || "")) === normalizedSiteId);
|
||||
@@ -3760,18 +3643,6 @@ const createSelectedSiteEnrollmentPlan = () => {
|
||||
stageBreakdown: "",
|
||||
});
|
||||
};
|
||||
const getSiteEnrollmentEditorIndex = () => getEditingIndex(siteEnrollmentEditor, setupDraft.siteEnrollmentPlans.length);
|
||||
const isSiteEnrollmentDuplicate = (siteId: string, excludeIndex: number): boolean => {
|
||||
const normalizedSiteId = normalizeSiteId(siteId);
|
||||
if (!normalizedSiteId) return false;
|
||||
return setupDraft.siteEnrollmentPlans.some(
|
||||
(row, rowIndex) => rowIndex !== excludeIndex && normalizeSiteId(row.siteId) === normalizedSiteId
|
||||
);
|
||||
};
|
||||
const isSiteEnrollmentSiteTaken = (siteId: string): boolean => {
|
||||
const editingIndex = getSiteEnrollmentEditorIndex();
|
||||
return isSiteEnrollmentDuplicate(siteId, editingIndex);
|
||||
};
|
||||
watch(
|
||||
[siteOptions, () => currentSetupDraft.value.siteEnrollmentPlans.map((row) => normalizeSiteId(row.siteId)).join("|")],
|
||||
syncSelectedSiteEnrollmentPlanSiteId,
|
||||
@@ -5841,80 +5712,6 @@ const removeSiteEnrollment = (index: number) => {
|
||||
if (!canMutateDraft()) return;
|
||||
setupDraft.siteEnrollmentPlans.splice(index, 1);
|
||||
};
|
||||
const openSiteEnrollmentEditor = (index: number) => {
|
||||
const opened = openIndexedEditor(setupDraft.siteEnrollmentPlans, index, siteEnrollmentEditor, (row) => {
|
||||
siteEnrollmentEditorForm.id = row.id || "";
|
||||
siteEnrollmentEditorForm.siteId = row.siteId || "";
|
||||
siteEnrollmentEditorForm.siteName = row.siteName || "";
|
||||
siteEnrollmentEditorForm.target = row.target ?? 0;
|
||||
siteEnrollmentEditorForm.startDate = row.startDate || "";
|
||||
siteEnrollmentEditorForm.endDate = row.endDate || "";
|
||||
siteEnrollmentEditorForm.note = row.note || "";
|
||||
siteEnrollmentEditorForm.stageBreakdown = row.stageBreakdown || "";
|
||||
});
|
||||
if (opened) siteEnrollmentEditorDirtyGuard.syncBaseline();
|
||||
};
|
||||
const saveSiteEnrollmentEditor = () => {
|
||||
if (!canMutateDraft()) return;
|
||||
const index = getEditingIndex(siteEnrollmentEditor, setupDraft.siteEnrollmentPlans.length);
|
||||
if (index < 0) return;
|
||||
if (!siteEnrollmentEditorForm.siteId) {
|
||||
ElMessage.warning("请选择中心");
|
||||
return;
|
||||
}
|
||||
if (isSiteEnrollmentDuplicate(siteEnrollmentEditorForm.siteId, index)) {
|
||||
ElMessage.warning("该中心已配置入组计划,请勿重复配置");
|
||||
return;
|
||||
}
|
||||
if (!siteEnrollmentEditorForm.startDate || !siteEnrollmentEditorForm.endDate) {
|
||||
ElMessage.warning("请填写启动日期和完成日期");
|
||||
return;
|
||||
}
|
||||
if (siteEnrollmentEditorForm.startDate > siteEnrollmentEditorForm.endDate) {
|
||||
ElMessage.warning("完成日期不能早于启动日期");
|
||||
return;
|
||||
}
|
||||
const { start: planStart, end: planEnd } = getProjectPlanWindow();
|
||||
const startDate = normalizePlanDate(siteEnrollmentEditorForm.startDate);
|
||||
const endDate = normalizePlanDate(siteEnrollmentEditorForm.endDate);
|
||||
if (planStart && startDate < planStart) {
|
||||
ElMessage.warning("中心启动日期不能早于项目计划开始日期");
|
||||
return;
|
||||
}
|
||||
if (planEnd && startDate > planEnd) {
|
||||
ElMessage.warning("中心启动日期不能晚于项目计划结束日期");
|
||||
return;
|
||||
}
|
||||
if (planStart && endDate < planStart) {
|
||||
ElMessage.warning("中心完成日期不能早于项目计划开始日期");
|
||||
return;
|
||||
}
|
||||
if (planEnd && endDate > planEnd) {
|
||||
ElMessage.warning("中心完成日期不能晚于项目计划结束日期");
|
||||
return;
|
||||
}
|
||||
setupDraft.siteEnrollmentPlans[index] = {
|
||||
id: siteEnrollmentEditorForm.id || makeId(),
|
||||
siteId: siteEnrollmentEditorForm.siteId,
|
||||
siteName: getSiteName(siteEnrollmentEditorForm.siteId),
|
||||
target: Math.max(0, Number(siteEnrollmentEditorForm.target || 0)),
|
||||
startDate: siteEnrollmentEditorForm.startDate,
|
||||
endDate: siteEnrollmentEditorForm.endDate,
|
||||
note: (siteEnrollmentEditorForm.note || "").trim(),
|
||||
stageBreakdown: siteEnrollmentEditorForm.stageBreakdown || "",
|
||||
};
|
||||
closeIndexedEditor(siteEnrollmentEditor, "中心入组计划已更新");
|
||||
};
|
||||
|
||||
const addCenterConfirm = () => {
|
||||
if (!canMutateDraft()) return;
|
||||
setupDraft.centerConfirm.push({ id: makeId(), siteId: "", siteName: "", confirmer: "", confirmStatus: "待确认", confirmDate: "", note: "" });
|
||||
};
|
||||
const removeCenterConfirm = (index: number) => {
|
||||
if (!canMutateDraft()) return;
|
||||
setupDraft.centerConfirm.splice(index, 1);
|
||||
};
|
||||
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!hasLeaveGuardChanges.value) return;
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1,419 +0,0 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="main-content-flat unified-shell">
|
||||
<div class="unified-action-bar actions-only-bar">
|
||||
<div class="filter-spacer"></div>
|
||||
<el-button v-if="canAddMember" type="primary" @click="openAdd">
|
||||
{{ TEXT.common.actions.add }}{{ TEXT.modules.adminProjectMembers.memberLabel }}
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="unified-section member-table-section">
|
||||
<el-table :data="memberRows" v-loading="loading" stripe class="member-table">
|
||||
<el-table-column prop="full_name" :label="TEXT.modules.adminProjectMembers.username" min-width="160" />
|
||||
<el-table-column prop="role_in_study" :label="TEXT.modules.adminProjectMembers.projectRole" min-width="140">
|
||||
<template #default="scope">
|
||||
<el-tag>{{ roleLabel(scope.row.role_in_study) }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="TEXT.common.fields.status" width="100">
|
||||
<template #default="scope">
|
||||
<el-tooltip
|
||||
v-if="scope.row.effectiveStatus === 'DISABLED_GLOBAL'"
|
||||
:content="TEXT.modules.adminProjectMembers.disabledGlobalHint"
|
||||
placement="top"
|
||||
>
|
||||
<el-tag type="danger">{{ TEXT.modules.adminProjectMembers.disabledGlobal }}</el-tag>
|
||||
</el-tooltip>
|
||||
<el-tag v-else :type="scope.row.is_active ? 'success' : 'danger'">
|
||||
{{ scope.row.is_active ? TEXT.common.actions.enable : TEXT.modules.adminProjectMembers.disabled }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="added_at" :label="TEXT.modules.adminProjectMembers.addedAt" min-width="180">
|
||||
<template #default="scope">{{ displayDateTime(scope.row.added_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="TEXT.common.labels.actions" width="300" align="center" class-name="action-column">
|
||||
<template #default="scope">
|
||||
<el-select
|
||||
v-model="scope.row.role_in_study"
|
||||
size="small"
|
||||
style="width: 120px"
|
||||
@change="(val: string) => updateRole(scope.row.id, val)"
|
||||
:disabled="!canEditMember(scope.row) || !scope.row.is_active || scope.row.effectiveStatus === 'DISABLED_GLOBAL'"
|
||||
>
|
||||
<el-option
|
||||
v-for="role in roleOptions"
|
||||
:key="role.value"
|
||||
:label="role.label"
|
||||
:value="role.value"
|
||||
:disabled="!canAssignRole(role.value)"
|
||||
/>
|
||||
</el-select>
|
||||
<span v-if="scope.row.effectiveStatus === 'DISABLED_GLOBAL'" class="hint">{{ TEXT.modules.adminProjectMembers.disabledGlobalDesc }}</span>
|
||||
<el-button link type="danger" size="small" :disabled="!canDeleteProjectMember(scope.row)" @click="onDelete(scope.row)">{{ TEXT.common.actions.delete }}</el-button>
|
||||
<el-button
|
||||
link
|
||||
:type="scope.row.is_active ? 'danger' : 'primary'"
|
||||
size="small"
|
||||
:disabled="!canEditMember(scope.row) || scope.row.effectiveStatus === 'DISABLED_GLOBAL'"
|
||||
@click="toggleActive(scope.row)"
|
||||
>
|
||||
{{ scope.row.is_active ? TEXT.common.actions.disable : TEXT.common.actions.enable }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog v-if="addVisible" append-to=".layout-main .content-wrapper" :title="TEXT.modules.adminProjectMembers.newTitle" width="520px" v-model="addVisible" :close-on-click-modal="false">
|
||||
<el-form :model="newMember" label-width="120px" ref="addFormRef" :rules="addRules">
|
||||
<el-form-item :label="TEXT.modules.adminProjectMembers.user" prop="user_id">
|
||||
<el-select v-model="newMember.user_id" filterable :placeholder="TEXT.modules.adminProjectMembers.userPlaceholder">
|
||||
<el-option
|
||||
v-for="user in availableUsers"
|
||||
:key="user.id"
|
||||
:label="user.full_name || TEXT.common.fallback"
|
||||
:value="user.id"
|
||||
:disabled="!user.is_active"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.modules.adminProjectMembers.projectRole" prop="role_in_study">
|
||||
<el-select v-model="newMember.role_in_study" :placeholder="TEXT.modules.adminProjectMembers.rolePlaceholder">
|
||||
<el-option
|
||||
v-for="role in roleOptions"
|
||||
:key="role.value"
|
||||
:label="role.label"
|
||||
:value="role.value"
|
||||
:disabled="!canAssignRole(role.value)"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="addVisible = false">{{ TEXT.common.actions.cancel }}</el-button>
|
||||
<el-button type="primary" :loading="adding" @click="submitAdd">{{ TEXT.common.actions.save }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
|
||||
import { addMember, listMemberCandidates, listMembers, removeMember, updateMember } from "../../api/members";
|
||||
import { fetchStudyDetail } from "../../api/studies";
|
||||
import type { Study, StudyMember, UserInfo } from "../../types/api";
|
||||
import { useAuthStore } from "../../store/auth";
|
||||
import { evaluateAction } from "../../guards/actionGuard";
|
||||
import { usePermission } from "../../utils/permission";
|
||||
import { displayDateTime } from "../../utils/display";
|
||||
import { TEXT, requiredMessage } from "../../locales";
|
||||
import { useRoleTemplateMeta } from "../../composables/useRoleTemplateMeta";
|
||||
|
||||
const route = useRoute();
|
||||
const projectId = computed(() => route.params.projectId as string);
|
||||
const auth = useAuthStore();
|
||||
const permission = usePermission();
|
||||
const { roleLabel, roleOptionsFor, loadRoleTemplates } = useRoleTemplateMeta();
|
||||
|
||||
const project = ref<Study | null>(null);
|
||||
const members = ref<StudyMember[]>([]);
|
||||
const users = ref<UserInfo[]>([]);
|
||||
const loading = ref(false);
|
||||
const addVisible = ref(false);
|
||||
const adding = ref(false);
|
||||
const addFormRef = ref<FormInstance>();
|
||||
const newMember = reactive({
|
||||
user_id: "",
|
||||
role_in_study: "PM",
|
||||
});
|
||||
const canListMembers = computed(() => permission.can("project.members.list"));
|
||||
const canListMemberCandidates = computed(() => permission.can("project.members.candidates"));
|
||||
const canCreateMember = computed(() => permission.can("project.members.create"));
|
||||
const canUpdateMember = computed(() => permission.can("project.members.update"));
|
||||
const canDeleteMember = computed(() => permission.can("project.members.delete"));
|
||||
const canAddMember = computed(() => canCreateMember.value && canListMemberCandidates.value);
|
||||
const projectRole = computed(() => project.value?.role_in_study || "");
|
||||
const ROLE_KEYS = ["PM", "CRA", "PV", "QA", "CTA", "ADMIN"];
|
||||
const roleOptions = computed(() => roleOptionsFor(ROLE_KEYS));
|
||||
const roleRank: Record<string, number> = {
|
||||
ADMIN: 100,
|
||||
PM: 80,
|
||||
PV: 50,
|
||||
QA: 60,
|
||||
CRA: 40,
|
||||
CTA: 40,
|
||||
};
|
||||
const currentRoleRank = computed(() => auth.user?.is_admin ? Number.POSITIVE_INFINITY : roleRank[projectRole.value] || 0);
|
||||
const canAssignRole = (role: string) => (auth.user?.is_admin ? true : (roleRank[role] || 0) <= currentRoleRank.value);
|
||||
const canMutateProjectMember = (row: StudyMember) => {
|
||||
if (row.user?.is_admin) return false;
|
||||
if (auth.user?.is_admin) return true;
|
||||
if (row.user_id === auth.user?.id) return false;
|
||||
return (roleRank[row.role_in_study] || 0) <= currentRoleRank.value;
|
||||
};
|
||||
const canEditMember = (row: StudyMember) => canUpdateMember.value && canMutateProjectMember(row);
|
||||
const canDeleteProjectMember = (row: StudyMember) => canDeleteMember.value && canMutateProjectMember(row);
|
||||
|
||||
const addRules = reactive<FormRules>({
|
||||
user_id: [{ required: true, message: requiredMessage(TEXT.modules.adminProjectMembers.user), trigger: "change" }],
|
||||
role_in_study: [{ required: true, message: requiredMessage(TEXT.modules.adminProjectMembers.projectRole), trigger: "change" }],
|
||||
});
|
||||
|
||||
const loadProject = async () => {
|
||||
if (!projectId.value) return;
|
||||
try {
|
||||
const { data } = await fetchStudyDetail(projectId.value);
|
||||
project.value = data;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const loadMembers = async () => {
|
||||
if (!canListMembers.value || !projectId.value) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await listMembers(projectId.value, { limit: 500, include_inactive: true });
|
||||
members.value = Array.isArray(data) ? data : data.items || [];
|
||||
if (!canListMemberCandidates.value) syncUsersFromMembers();
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.modules.adminProjectMembers.loadFailed);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const syncUsersFromMembers = () => {
|
||||
users.value = members.value
|
||||
.map((member) => member.user)
|
||||
.filter((user): user is UserInfo => Boolean(user?.id)) as UserInfo[];
|
||||
};
|
||||
|
||||
const loadUsers = async () => {
|
||||
if (!canListMemberCandidates.value || !projectId.value) {
|
||||
syncUsersFromMembers();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { data } = await listMemberCandidates(projectId.value, { limit: 500 });
|
||||
users.value = data || [];
|
||||
} catch {
|
||||
users.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const memberRows = computed(() =>
|
||||
members.value.map((m) => {
|
||||
const user = users.value.find((u) => u.id === m.user_id) || m.user;
|
||||
const effectiveStatus = user && user.is_active === false ? "DISABLED_GLOBAL" : m.is_active ? "ACTIVE" : "DISABLED";
|
||||
return {
|
||||
...m,
|
||||
full_name: user?.full_name || user?.username || m.user_id,
|
||||
effectiveStatus,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const openAdd = () => {
|
||||
if (!canAddMember.value) return;
|
||||
newMember.user_id = "";
|
||||
newMember.role_in_study = canAssignRole("PM") ? "PM" : "CRA";
|
||||
addVisible.value = true;
|
||||
};
|
||||
|
||||
const submitAdd = async () => {
|
||||
if (!projectId.value) return;
|
||||
if (!canAddMember.value) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
const decision = evaluateAction({
|
||||
actorRole: auth.user?.is_admin ? "ADMIN" : null,
|
||||
requiredPermission: "project.members.create",
|
||||
target: { projectId: projectId.value },
|
||||
});
|
||||
if (!decision.allowed) {
|
||||
ElMessage.warning(decision.reason || TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
if (!canAssignRole(newMember.role_in_study)) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
await addFormRef.value?.validate();
|
||||
adding.value = true;
|
||||
try {
|
||||
await addMember(projectId.value, newMember);
|
||||
ElMessage.success(TEXT.modules.adminProjectMembers.addSuccess);
|
||||
addVisible.value = false;
|
||||
await Promise.all([loadMembers(), loadUsers()]);
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.modules.adminProjectMembers.addFailed);
|
||||
} finally {
|
||||
adding.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const updateRole = async (memberId: string, role: string) => {
|
||||
if (!projectId.value) return;
|
||||
const row = members.value.find((member) => member.id === memberId);
|
||||
if (!row || !canEditMember(row) || !canAssignRole(role)) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
loadMembers();
|
||||
return;
|
||||
}
|
||||
const decision = evaluateAction({
|
||||
actorRole: auth.user?.is_admin ? "ADMIN" : null,
|
||||
requiredPermission: "project.members.update",
|
||||
target: { projectId: projectId.value, memberId },
|
||||
});
|
||||
if (!decision.allowed) {
|
||||
ElMessage.warning(decision.reason || TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateMember(projectId.value, memberId, { role_in_study: role });
|
||||
ElMessage.success(TEXT.modules.adminProjectMembers.roleUpdated);
|
||||
loadMembers();
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.updateFailed);
|
||||
loadMembers();
|
||||
}
|
||||
};
|
||||
|
||||
const toggleActive = async (row: StudyMember) => {
|
||||
if (!projectId.value) return;
|
||||
if (!canEditMember(row)) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
const decision = evaluateAction({
|
||||
actorRole: auth.user?.is_admin ? "ADMIN" : null,
|
||||
requiredPermission: "project.members.update",
|
||||
target: { projectId: projectId.value, memberId: row.id },
|
||||
});
|
||||
if (!decision.allowed) {
|
||||
ElMessage.warning(decision.reason || TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
if (row.is_active) {
|
||||
const ok = await ElMessageBox.confirm(TEXT.modules.adminProjectMembers.disableConfirm, TEXT.modules.adminProjectMembers.disableTitle, {
|
||||
type: "warning",
|
||||
confirmButtonText: TEXT.common.actions.confirm,
|
||||
}).catch(() => null);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await updateMember(projectId.value, row.id, { is_active: false });
|
||||
ElMessage.success(TEXT.modules.adminProjectMembers.disableSuccess);
|
||||
loadMembers();
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.actionFailed);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
await updateMember(projectId.value, row.id, { is_active: true });
|
||||
ElMessage.success(TEXT.modules.adminProjectMembers.enableSuccess);
|
||||
loadMembers();
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.actionFailed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onDelete = async (row: StudyMember) => {
|
||||
if (!projectId.value) return;
|
||||
if (!canDeleteProjectMember(row)) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
const decision = evaluateAction({
|
||||
actorRole: auth.user?.is_admin ? "ADMIN" : null,
|
||||
requiredPermission: "project.members.delete",
|
||||
target: { projectId: projectId.value, memberId: row.id },
|
||||
});
|
||||
if (!decision.allowed) {
|
||||
ElMessage.warning(decision.reason || TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
const ok = await ElMessageBox.confirm(TEXT.modules.adminProjectMembers.removeConfirm, TEXT.modules.adminProjectMembers.removeTitle, {
|
||||
type: "warning",
|
||||
confirmButtonText: TEXT.common.actions.confirm,
|
||||
cancelButtonText: TEXT.common.actions.cancel,
|
||||
}).catch(() => null);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await removeMember(projectId.value, row.id);
|
||||
members.value = members.value.filter((m) => m.id !== row.id);
|
||||
await loadUsers();
|
||||
ElMessage.success(TEXT.modules.adminProjectMembers.removeSuccess);
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
|
||||
}
|
||||
};
|
||||
|
||||
const availableUsers = computed(() => {
|
||||
const memberUserIds = new Set(members.value.map((m) => m.user_id));
|
||||
return users.value.filter((u) => !memberUserIds.has(u.id));
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadRoleTemplates(), loadProject(), loadMembers()]);
|
||||
loadUsers();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.main-content-flat {
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.main-content-flat :deep(.el-card__body) {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.actions-only-bar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.member-table-section {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.member-table :deep(.el-table__inner-wrapper::before) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: #999;
|
||||
margin: 0 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
.el-table .action-column .cell {
|
||||
padding-left: 8px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
.action-column .el-select {
|
||||
margin-right: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,115 +0,0 @@
|
||||
<template>
|
||||
<el-dialog v-if="visibleProxy" append-to=".layout-main .content-wrapper" :title="TEXT.modules.adminSites.craBindTitle" width="520px" v-model="visibleProxy" :close-on-click-modal="false">
|
||||
<div class="tip">{{ TEXT.modules.adminSites.sitePrefix }}{{ site?.name }}</div>
|
||||
<el-form label-width="120px">
|
||||
<el-form-item :label="TEXT.modules.adminSites.craSelect">
|
||||
<el-select v-model="selectedCras" multiple filterable :placeholder="TEXT.modules.adminSites.craSelectPlaceholder" style="width: 100%">
|
||||
<el-option v-for="user in craUsers" :key="user.id" :label="user.username" :value="user.id" />
|
||||
</el-select>
|
||||
<div class="hint">{{ TEXT.modules.adminSites.craHint }}</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="visibleProxy = false">{{ TEXT.common.actions.cancel }}</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="onSave">{{ TEXT.modules.adminSites.craSave }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { updateSite } from "../../api/sites";
|
||||
import type { Site, UserInfo } from "../../types/api";
|
||||
import { useAuthStore } from "../../store/auth";
|
||||
import { evaluateAction } from "../../guards/actionGuard";
|
||||
import { TEXT } from "../../locales";
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
studyId: string;
|
||||
site: Site | null;
|
||||
craUsers: UserInfo[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "update:visible", value: boolean): void;
|
||||
(e: "saved"): void;
|
||||
}>();
|
||||
|
||||
const auth = useAuthStore();
|
||||
const visibleProxy = computed({
|
||||
get: () => props.visible,
|
||||
set: (val: boolean) => emit("update:visible", val),
|
||||
});
|
||||
|
||||
const selectedCras = ref<string[]>([]);
|
||||
const saving = ref(false);
|
||||
|
||||
const loadSelected = () => {
|
||||
if (!props.site) {
|
||||
selectedCras.value = [];
|
||||
return;
|
||||
}
|
||||
const raw = props.site.contact || "";
|
||||
const tokens = raw
|
||||
.split(",")
|
||||
.map((i) => i.trim())
|
||||
.filter(Boolean);
|
||||
selectedCras.value = tokens
|
||||
.map((token) => {
|
||||
const byId = props.craUsers.find((u) => u.id === token);
|
||||
if (byId) return byId.id;
|
||||
const byName = props.craUsers.find((u) => u.username === token);
|
||||
return byName?.id;
|
||||
})
|
||||
.filter((v): v is string => !!v);
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(val) => {
|
||||
if (val) {
|
||||
loadSelected();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const onSave = async () => {
|
||||
if (!props.site) return;
|
||||
const decision = evaluateAction({
|
||||
actorRole: auth.user?.is_admin ? "ADMIN" : null,
|
||||
requiredPermission: "site.cra.bind",
|
||||
target: { siteId: props.site.id, studyId: props.studyId },
|
||||
});
|
||||
if (!decision.allowed) {
|
||||
ElMessage.warning(decision.reason || TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const names = selectedCras.value
|
||||
.map((id) => props.craUsers.find((u) => u.id === id)?.username || id)
|
||||
.filter(Boolean);
|
||||
await updateSite(props.studyId, props.site.id, { contact: names.join(",") });
|
||||
ElMessage.success(TEXT.modules.adminSites.craSaveSuccess);
|
||||
emit("saved");
|
||||
visibleProxy.value = false;
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.tip {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.hint {
|
||||
color: #888;
|
||||
font-size: 12px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
</style>
|
||||
@@ -231,7 +231,6 @@ import { Plus } from "@element-plus/icons-vue";
|
||||
import { fetchDocuments, createDocument, deleteDocument, updateDocument } from "../../api/documents";
|
||||
import { fetchSites } from "../../api/sites";
|
||||
import { useStudyStore } from "../../store/study";
|
||||
import { useAuthStore } from "../../store/auth";
|
||||
import { usePermission } from "../../utils/permission";
|
||||
import { useDrawerDirtyGuard } from "../../utils/drawerDirtyGuard";
|
||||
import type { DocumentSummary } from "../../types/documents";
|
||||
@@ -244,7 +243,6 @@ import { isTauriRuntime } from "../../runtime";
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const study = useStudyStore();
|
||||
const auth = useAuthStore();
|
||||
const { can } = usePermission();
|
||||
const loading = ref(false);
|
||||
const items = ref<DocumentSummary[]>([]);
|
||||
@@ -284,9 +282,6 @@ const siteActiveMap = computed(() => {
|
||||
});
|
||||
return map;
|
||||
});
|
||||
const isAdmin = computed(() => {
|
||||
return !!auth.user?.is_admin;
|
||||
});
|
||||
const canCreate = computed(() => can("documents.create"));
|
||||
const canUpdate = computed(() => can("documents.update"));
|
||||
const canDelete = computed(() => can("documents.delete"));
|
||||
|
||||
@@ -395,12 +395,6 @@ const selectNode = async (node: EtmfTreeNode) => {
|
||||
await loadNodeDocuments();
|
||||
};
|
||||
|
||||
const resetFilters = () => {
|
||||
filters.siteId = "";
|
||||
filters.status = "";
|
||||
loadNodeDocuments();
|
||||
};
|
||||
|
||||
const openNodeDialog = () => {
|
||||
if (!canCreate.value) {
|
||||
ElMessage.warning("权限不足");
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
<template>
|
||||
<ModulePlaceholder
|
||||
:title="TEXT.modules.riskIssues.title"
|
||||
:subtitle="TEXT.modules.riskIssues.subtitle"
|
||||
:list-title="TEXT.modules.riskIssues.listTitle"
|
||||
:empty-description="TEXT.modules.riskIssues.emptyDescription"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import ModulePlaceholder from "../../components/ModulePlaceholder.vue";
|
||||
import { TEXT } from "../../locales";
|
||||
</script>
|
||||
@@ -1,192 +0,0 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="unified-shell">
|
||||
<section class="unified-section">
|
||||
<div class="unified-section-header">
|
||||
<div class="ctms-section-title">{{ isEdit ? TEXT.modules.startupMeetingAuth.trainingEditTitle : TEXT.modules.startupMeetingAuth.trainingNewTitle }}</div>
|
||||
<div class="ctms-section-actions">
|
||||
<el-button @click="goBack">{{ TEXT.common.actions.back }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<el-form :model="form" label-width="120px">
|
||||
<el-form-item :label="TEXT.common.fields.name" required>
|
||||
<el-input v-model="form.name" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.name" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.labels.role">
|
||||
<el-input v-model="form.role" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.input + TEXT.common.labels.role" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.site">
|
||||
<el-input v-model="form.site_name" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.site" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.trained">
|
||||
<el-switch v-model="form.trained" :disabled="isReadOnly" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.trainedDate">
|
||||
<el-date-picker v-model="form.trained_date" :disabled="isReadOnly" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.authorized">
|
||||
<el-switch v-model="form.authorized" :disabled="isReadOnly" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.authorizedDate">
|
||||
<el-date-picker v-model="form.authorized_date" :disabled="isReadOnly" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="TEXT.common.fields.remark">
|
||||
<el-input v-model="form.remark" :disabled="isReadOnly" type="textarea" :rows="3" :placeholder="TEXT.common.placeholders.input" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="saving" :disabled="isReadOnly" @click="submit">{{ TEXT.common.actions.save }}</el-button>
|
||||
<el-button @click="goBack">{{ TEXT.common.actions.cancel }}</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</section>
|
||||
<section class="unified-section">
|
||||
<div class="ctms-section-header">
|
||||
<div class="ctms-section-title">{{ TEXT.common.labels.attachments }}</div>
|
||||
</div>
|
||||
<AttachmentList
|
||||
ref="attachmentPanelRef"
|
||||
:study-id="studyId"
|
||||
entity-type="training_authorization"
|
||||
:entity-id="recordId || ''"
|
||||
:readonly="isReadOnly"
|
||||
:mode="'upload'"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { useStudyStore } from "../../store/study";
|
||||
import { createTrainingAuthorization, getTrainingAuthorization, updateTrainingAuthorization } from "../../api/startup";
|
||||
import { fetchSites } from "../../api/sites";
|
||||
import AttachmentList from "../../components/attachments/AttachmentList.vue";
|
||||
import { TEXT } from "../../locales";
|
||||
import { usePermission } from "../../utils/permission";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const study = useStudyStore();
|
||||
const { can } = usePermission();
|
||||
const saving = ref(false);
|
||||
const attachmentPanelRef = ref<InstanceType<typeof AttachmentList> | null>(null);
|
||||
const sites = ref<any[]>([]);
|
||||
|
||||
const recordId = computed(() => route.params.recordId as string | undefined);
|
||||
const isEdit = computed(() => !!recordId.value);
|
||||
const studyId = computed(() => study.currentStudy?.id || "");
|
||||
|
||||
const form = reactive({
|
||||
name: "",
|
||||
role: "",
|
||||
site_name: "",
|
||||
trained: false,
|
||||
authorized: false,
|
||||
trained_date: "",
|
||||
authorized_date: "",
|
||||
remark: "",
|
||||
});
|
||||
|
||||
const siteActiveMap = computed(() => {
|
||||
const map: Record<string, boolean> = {};
|
||||
sites.value.forEach((site) => {
|
||||
if (site?.name) map[site.name] = !!site.is_active;
|
||||
});
|
||||
return map;
|
||||
});
|
||||
const canCreateAuth = computed(() => can("startup.auth.create"));
|
||||
const canUpdateAuth = computed(() => can("startup.auth.update"));
|
||||
const canSaveAuth = computed(() => (isEdit.value ? canUpdateAuth.value : canCreateAuth.value));
|
||||
const isInactiveSite = computed(() => isEdit.value && !!form.site_name && siteActiveMap.value[form.site_name] === false);
|
||||
const isReadOnly = computed(() => !canSaveAuth.value || isInactiveSite.value);
|
||||
|
||||
const loadSites = async () => {
|
||||
if (!studyId.value) return;
|
||||
try {
|
||||
const { data } = await fetchSites(studyId.value, { limit: 500 });
|
||||
sites.value = Array.isArray(data) ? data : data.items || [];
|
||||
} catch {
|
||||
sites.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
if (!isEdit.value || !studyId.value || !recordId.value) return;
|
||||
try {
|
||||
const { data } = await getTrainingAuthorization(studyId.value, recordId.value);
|
||||
Object.assign(form, {
|
||||
name: data.name || "",
|
||||
role: data.role || "",
|
||||
site_name: data.site_name || "",
|
||||
trained: !!data.trained,
|
||||
authorized: !!data.authorized,
|
||||
trained_date: data.trained_date || "",
|
||||
authorized_date: data.authorized_date || "",
|
||||
remark: data.remark || "",
|
||||
});
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
if (!studyId.value) return;
|
||||
if (!canSaveAuth.value) {
|
||||
ElMessage.warning("权限不足");
|
||||
return;
|
||||
}
|
||||
if (isInactiveSite.value) {
|
||||
ElMessage.warning("中心已停用");
|
||||
return;
|
||||
}
|
||||
if (form.site_name && siteActiveMap.value[form.site_name] === false) {
|
||||
ElMessage.warning("中心已停用");
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const payload = {
|
||||
name: form.name,
|
||||
role: form.role || null,
|
||||
site_name: form.site_name || null,
|
||||
trained: form.trained,
|
||||
authorized: form.authorized,
|
||||
trained_date: form.trained_date || null,
|
||||
authorized_date: form.authorized_date || null,
|
||||
remark: form.remark || null,
|
||||
};
|
||||
let savedId = recordId.value || "";
|
||||
if (isEdit.value && recordId.value) {
|
||||
await updateTrainingAuthorization(studyId.value, recordId.value, payload);
|
||||
} else {
|
||||
const { data } = await createTrainingAuthorization(studyId.value, payload);
|
||||
savedId = data.id;
|
||||
}
|
||||
await attachmentPanelRef.value?.uploadPending(savedId);
|
||||
ElMessage.success(isEdit.value ? TEXT.common.messages.saveSuccess : TEXT.common.messages.createSuccess);
|
||||
router.push(`/startup/training/${savedId}`);
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const goBack = () => router.push("/startup/meeting-auth");
|
||||
|
||||
onMounted(async () => {
|
||||
await loadSites();
|
||||
load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -16,7 +16,7 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-form ref="formRef" :model="form" label-position="top" class="visit-editor-form">
|
||||
<el-form :model="form" label-position="top" class="visit-editor-form">
|
||||
<div class="form-group">
|
||||
<div class="form-group-title">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:#3b82f6;flex-shrink:0"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
|
||||
@@ -99,7 +99,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
import { ElMessage, type FormInstance } from "element-plus";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { createVisit, updateVisit } from "../../api/visits";
|
||||
import { useDrawerDirtyGuard } from "../../utils/drawerDirtyGuard";
|
||||
import { TEXT } from "../../locales";
|
||||
@@ -121,8 +121,6 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const saving = ref(false);
|
||||
const formRef = ref<FormInstance>();
|
||||
|
||||
|
||||
const form = reactive({
|
||||
visit_code: "",
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"skipLibCheck": true,
|
||||
"lib": ["ESNext", "DOM"],
|
||||
"types": ["node", "vite/client"],
|
||||
|
||||
+1
-18
@@ -12,24 +12,7 @@ const tauriDebug = process.env.TAURI_ENV_DEBUG === "true";
|
||||
export default defineConfig({
|
||||
clearScreen: false,
|
||||
envPrefix: ["VITE_", "TAURI_ENV_"],
|
||||
plugins: [
|
||||
vue(),
|
||||
{
|
||||
name: "sanitize-legacy-css",
|
||||
generateBundle(_, bundle) {
|
||||
for (const asset of Object.values(bundle)) {
|
||||
if (asset.type !== "asset" || !asset.fileName.endsWith(".css") || typeof asset.source !== "string") {
|
||||
continue;
|
||||
}
|
||||
asset.source = asset.source
|
||||
.replace(/\.el-button::\-moz-focus-inner\{border:0\}/g, "")
|
||||
.replace(/\.el-input__inner\[type=password\]::\-ms-reveal\{display:none\}/g, "")
|
||||
.replace(/filter:alpha\(opacity=0\);/g, "")
|
||||
.replace(/[^{}]*::\-webkit-scrollbar[^{}]*\{[^{}]*\}/g, "");
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": fileURLToPath(new URL("./src", import.meta.url)),
|
||||
|
||||
Reference in New Issue
Block a user