优化后台界面与无操作退出体验
This commit is contained in:
@@ -39,15 +39,6 @@ class ExtendResponse(BaseModel):
|
||||
expiresAt: datetime
|
||||
|
||||
|
||||
class UnlockRequest(LoginRequest):
|
||||
pass
|
||||
|
||||
|
||||
class UnlockResponse(BaseModel):
|
||||
accessToken: str
|
||||
expiresAt: datetime
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
AVATAR_ROOT = Path(__file__).resolve().parent.parent.parent / "uploads" / "avatars"
|
||||
AVATAR_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
@@ -197,24 +188,6 @@ async def extend_access_token(
|
||||
return ExtendResponse(accessToken=new_token, expiresAt=expires_at)
|
||||
|
||||
|
||||
@router.post("/unlock", response_model=UnlockResponse)
|
||||
async def unlock_session(
|
||||
payload: UnlockRequest,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
) -> UnlockResponse:
|
||||
db_user = await authenticate_encrypted_password(payload, db)
|
||||
if db_user.status != UserStatus.ACTIVE:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="账号已停用")
|
||||
session_start = datetime.now(timezone.utc)
|
||||
access_token = create_access_token(
|
||||
user_id=str(db_user.id),
|
||||
expires_minutes=None,
|
||||
session_start=session_start,
|
||||
)
|
||||
expires_at = session_start + timedelta(minutes=settings.JWT_EXPIRE_MINUTES)
|
||||
return UnlockResponse(accessToken=access_token, expiresAt=expires_at)
|
||||
|
||||
|
||||
@router.patch("/me", response_model=UserRead)
|
||||
async def update_me(
|
||||
payload: UserSelfUpdate,
|
||||
|
||||
@@ -358,15 +358,3 @@ async def test_login_challenge_cannot_be_reused(client_and_db):
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unlock_requires_encrypted_password(client_and_db):
|
||||
client, _ = client_and_db
|
||||
plaintext = await client.post("/api/v1/auth/unlock", json={"email": "admin@test.com", "password": "admin123"})
|
||||
encrypted = await client.post(
|
||||
"/api/v1/auth/unlock",
|
||||
json=await encrypted_auth_payload(client, "admin@test.com", "admin123"),
|
||||
)
|
||||
|
||||
assert plaintext.status_code == 422
|
||||
assert encrypted.status_code == 200
|
||||
|
||||
@@ -15,21 +15,17 @@ Last Updated: `2026-03-30`
|
||||
- 同时触发 10 个 API 请求
|
||||
- 仅出现 1 次 /auth/extend,其余请求自动重放成功
|
||||
|
||||
4) Idle lock at 30 minutes
|
||||
4) Idle auto logout at 30 minutes
|
||||
- 30 分钟无鼠标/键盘/触摸/滚动且无任何请求
|
||||
- 出现锁屏,背景虚化,原页面状态保留
|
||||
- 自动退出登录并跳转登录页
|
||||
|
||||
5) Unlock success
|
||||
- 锁屏输入正确密码,解锁成功并继续原页面
|
||||
5) Login notice after idle logout
|
||||
- 登录页展示 30 分钟无操作自动退出提示
|
||||
|
||||
6) Unlock failure threshold
|
||||
- 连续错误密码 >= 5 次
|
||||
- 强制登出并跳登录页
|
||||
|
||||
7) Extend failure to lock
|
||||
6) Extend failure logout
|
||||
- 人为让 token 彻底过期,/auth/extend 返回 401
|
||||
- 不跳登录,进入锁屏并要求密码解锁
|
||||
- 强制登出并跳登录页,提示登录状态失效
|
||||
|
||||
8) 403 permission vs disabled
|
||||
7) 403 permission vs disabled
|
||||
- 权限不足接口返回 403 时不跳登录
|
||||
- /auth/extend 或 /auth/unlock 返回 403 时强制登出跳登录
|
||||
- /auth/extend 返回 403 时强制登出跳登录
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
| high | business-draft | `frontend/src/views/admin/ProjectDetail.vue` | 2984 | `localStorage.removeItem` | `storageKey.value` | 立项配置草稿本地兜底,需显式提示未落库 |
|
||||
| low | ui-preference | `frontend/src/components/Layout.vue` | 227 | `localStorage.getItem` | `"ctms_sidebar_collapsed"` | UI偏好/上下文缓存 |
|
||||
| low | ui-preference | `frontend/src/components/Layout.vue` | 390 | `localStorage.setItem` | `"ctms_sidebar_collapsed"` | UI偏好/上下文缓存 |
|
||||
| low | auth-session | `frontend/src/components/LockScreenModal.vue` | 92 | `localStorage.getItem` | `"ctms_last_login_email"` | 认证/会话数据(非业务主数据) |
|
||||
| low | auth-session | `frontend/src/components/ThreadList.vue` | 72 | `localStorage.getItem` | `"ctms_token"` | 认证/会话数据(非业务主数据) |
|
||||
| low | auth-session | `frontend/src/components/attachments/AttachmentList.vue` | 132 | `localStorage.getItem` | `"ctms_token"` | 认证/会话数据(非业务主数据) |
|
||||
| low | auth-session | `frontend/src/components/attachments/AttachmentList.vue` | 137 | `localStorage.getItem` | `"ctms_token"` | 认证/会话数据(非业务主数据) |
|
||||
|
||||
+3
-10
@@ -1,18 +1,16 @@
|
||||
<template>
|
||||
<div class="app-shell" :class="{ 'app-locked': session.locked }">
|
||||
<div class="app-shell">
|
||||
<router-view />
|
||||
<LockScreenModal v-if="session.locked" />
|
||||
<SessionTimeoutPrompt />
|
||||
</div>
|
||||
<!-- TODO: 预留聚合接口页面:/study/{id}/overview /subjects/{id}/detail /sites/{id}/summary -->
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useSessionStore } from "./store/session";
|
||||
import { initSessionManager } from "./session/sessionManager";
|
||||
import LockScreenModal from "./components/LockScreenModal.vue";
|
||||
import SessionTimeoutPrompt from "./components/SessionTimeoutPrompt.vue";
|
||||
|
||||
initSessionManager();
|
||||
const session = useSessionStore();
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -20,9 +18,4 @@ const session = useSessionStore();
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
.app-locked {
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -11,11 +11,6 @@ export type ExtendResponse = {
|
||||
expiresAt: string;
|
||||
};
|
||||
|
||||
export type UnlockResponse = {
|
||||
accessToken: string;
|
||||
expiresAt: string;
|
||||
};
|
||||
|
||||
export type LoginKeyResponse = {
|
||||
key_id: string;
|
||||
public_key: string;
|
||||
@@ -43,7 +38,4 @@ export const extendToken = (token: string): Promise<AxiosResponse<ExtendResponse
|
||||
export const getLoginKey = (): Promise<AxiosResponse<LoginKeyResponse>> =>
|
||||
authClient.get<LoginKeyResponse>("/api/v1/auth/login-key");
|
||||
|
||||
export const unlockSession = (payload: EncryptedPasswordRequest): Promise<AxiosResponse<UnlockResponse>> =>
|
||||
authClient.post<UnlockResponse>("/api/v1/auth/unlock", payload);
|
||||
|
||||
export default authClient;
|
||||
|
||||
@@ -5,8 +5,7 @@ import { getToken } from "../utils/auth";
|
||||
import type { ApiError } from "../types/api";
|
||||
import { useStudyStore } from "../store/study";
|
||||
import { TEXT } from "../locales";
|
||||
import { extendAccessToken, forceLogout, lockSession, markNetworkActive } from "../session/sessionManager";
|
||||
import { useSessionStore } from "../store/session";
|
||||
import { extendAccessToken, forceLogout, LOGOUT_REASON_AUTH_EXPIRED } from "../session/sessionManager";
|
||||
|
||||
const instance: AxiosInstance = axios.create({
|
||||
baseURL: "/",
|
||||
@@ -14,59 +13,29 @@ const instance: AxiosInstance = axios.create({
|
||||
});
|
||||
|
||||
export type ApiRequestConfig = AxiosRequestConfig & {
|
||||
ignoreIdle?: boolean;
|
||||
allowWhileLocked?: boolean;
|
||||
suppressErrorMessage?: boolean;
|
||||
_retry?: boolean;
|
||||
};
|
||||
|
||||
class LockedError extends Error {
|
||||
constructor() {
|
||||
super("LOCKED");
|
||||
this.name = "LockedError";
|
||||
}
|
||||
}
|
||||
|
||||
instance.interceptors.request.use((config: InternalAxiosRequestConfig & ApiRequestConfig) => {
|
||||
const session = useSessionStore();
|
||||
const reqUrl = config.url || "";
|
||||
const allowWhileLocked =
|
||||
config.allowWhileLocked ||
|
||||
reqUrl.includes("/api/v1/auth/login") ||
|
||||
reqUrl.includes("/api/v1/auth/register") ||
|
||||
reqUrl.includes("/api/v1/auth/unlock");
|
||||
if (session.locked && !allowWhileLocked) {
|
||||
return Promise.reject(new LockedError());
|
||||
}
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
config.headers = config.headers || {};
|
||||
(config.headers as Record<string, string>).Authorization = `Bearer ${token}`;
|
||||
}
|
||||
if (!config.ignoreIdle) {
|
||||
markNetworkActive();
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
instance.interceptors.response.use(
|
||||
(response: AxiosResponse) => response,
|
||||
async (error: AxiosError<ApiError>) => {
|
||||
if (error instanceof LockedError) {
|
||||
const lockedConfig = error.config as ApiRequestConfig | undefined;
|
||||
if (!lockedConfig?.suppressErrorMessage) {
|
||||
ElMessage.warning(TEXT.common.messages.sessionLocked || "请解锁后继续操作");
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
const status = error.response?.status;
|
||||
const data = error.response?.data;
|
||||
const reqUrl = error.config?.url || "";
|
||||
const isAuthEndpoint =
|
||||
reqUrl.includes("/api/v1/auth/login") ||
|
||||
reqUrl.includes("/api/v1/auth/register") ||
|
||||
reqUrl.includes("/api/v1/auth/extend") ||
|
||||
reqUrl.includes("/api/v1/auth/unlock");
|
||||
reqUrl.includes("/api/v1/auth/extend");
|
||||
if (isAuthEndpoint) {
|
||||
// 认证相关的错误由具体页面自行处理,避免重复提示
|
||||
return Promise.reject(error);
|
||||
@@ -92,11 +61,11 @@ instance.interceptors.response.use(
|
||||
return instance(config);
|
||||
}
|
||||
if (result.authFailed) {
|
||||
lockSession("token_invalid");
|
||||
forceLogout(LOGOUT_REASON_AUTH_EXPIRED);
|
||||
}
|
||||
}
|
||||
} else if (status === 403 && (data as any)?.detail === "账号已停用") {
|
||||
forceLogout();
|
||||
forceLogout(LOGOUT_REASON_AUTH_EXPIRED);
|
||||
} else {
|
||||
const suppressErrorMessage = (error.config as ApiRequestConfig | undefined)?.suppressErrorMessage;
|
||||
if (!suppressErrorMessage) {
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
>
|
||||
<template #header>
|
||||
<div class="editor-header">
|
||||
<div class="editor-title-row">
|
||||
<div class="editor-title">分类管理</div>
|
||||
<el-button size="small" class="header-add-btn" @click="addCategory">
|
||||
<div class="editor-title-row">
|
||||
<div class="editor-title">分类管理</div>
|
||||
<el-button v-if="canCreate" size="small" class="header-add-btn" @click="addCategory">
|
||||
<el-icon><Plus /></el-icon> 新增
|
||||
</el-button>
|
||||
</div>
|
||||
@@ -69,11 +69,13 @@
|
||||
size="small"
|
||||
placeholder="分类名称"
|
||||
class="row-name-input"
|
||||
:disabled="!cat._isNew && !canUpdate"
|
||||
@input="cat._dirty = true"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="cat._isNew ? canCreate : canDelete"
|
||||
class="row-delete"
|
||||
type="button"
|
||||
@click.stop="removeCategory(cat)"
|
||||
@@ -120,6 +122,9 @@ const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
categories: FaqCategory[];
|
||||
faqs?: any[];
|
||||
canCreate?: boolean;
|
||||
canUpdate?: boolean;
|
||||
canDelete?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -130,6 +135,9 @@ const emit = defineEmits<{
|
||||
const study = useStudyStore();
|
||||
const saving = ref(false);
|
||||
let keyCounter = 0;
|
||||
const canCreate = computed(() => props.canCreate !== false);
|
||||
const canUpdate = computed(() => props.canUpdate !== false);
|
||||
const canDelete = computed(() => props.canDelete !== false);
|
||||
|
||||
const editableCategories = ref<EditableCategory[]>([]);
|
||||
|
||||
@@ -174,6 +182,10 @@ const loadFromProps = () => {
|
||||
};
|
||||
|
||||
const addCategory = () => {
|
||||
if (!canCreate.value) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
editableCategories.value.push({
|
||||
_key: `new-${++keyCounter}`,
|
||||
_dirty: true,
|
||||
@@ -219,6 +231,11 @@ const moveDown = (idx: number) => {
|
||||
};
|
||||
|
||||
const removeCategory = (cat: EditableCategory) => {
|
||||
const allowed = cat._isNew ? canCreate.value : canDelete.value;
|
||||
if (!allowed) {
|
||||
ElMessage.warning(TEXT.common.messages.noPermission);
|
||||
return;
|
||||
}
|
||||
if (!cat._isNew) {
|
||||
const count = (props.faqs || []).filter((f: any) => f.category_id === cat.id).length;
|
||||
if (count > 0) {
|
||||
@@ -250,6 +267,7 @@ const saveAll = async () => {
|
||||
const existingIds = all.filter((c) => !c._isNew && c.id).map((c) => c.id);
|
||||
for (const orig of props.categories) {
|
||||
if (!existingIds.includes(orig.id)) {
|
||||
if (!canDelete.value) continue;
|
||||
await deleteFaqCategory(orig.id, studyId);
|
||||
}
|
||||
}
|
||||
@@ -270,9 +288,11 @@ const saveAll = async () => {
|
||||
};
|
||||
|
||||
if (cat._isNew) {
|
||||
if (!canCreate.value) continue;
|
||||
if (!cat.name.trim()) continue;
|
||||
await createFaqCategory(payload);
|
||||
} else if (cat._dirty) {
|
||||
if (!canUpdate.value) continue;
|
||||
await updateFaqCategory(cat.id, payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<aside class="panel unified-shell faq-category-panel">
|
||||
<div class="header">
|
||||
<span>{{ TEXT.common.labels.category }}</span>
|
||||
<div v-if="canCreateCategory">
|
||||
<div v-if="canManageCategories">
|
||||
<el-button type="primary" size="small" class="category-create-btn" @click="openManager()">编辑</el-button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -21,7 +21,15 @@
|
||||
<span class="cat-count">{{ categoryCounts[c.id] || 0 }}</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
<FaqCategoryManager v-model="showForm" :categories="props.categories" :faqs="props.faqs" @success="emit('refresh')" />
|
||||
<FaqCategoryManager
|
||||
v-model="showForm"
|
||||
:categories="props.categories"
|
||||
:faqs="props.faqs"
|
||||
:can-create="canCreateCategory"
|
||||
:can-update="canUpdateCategory"
|
||||
:can-delete="canDeleteCategory"
|
||||
@success="emit('refresh')"
|
||||
/>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
@@ -44,6 +52,9 @@ const showForm = ref(false);
|
||||
|
||||
const { can } = usePermission();
|
||||
const canCreateCategory = computed(() => can("faq.category.create"));
|
||||
const canUpdateCategory = computed(() => can("faq.category.update"));
|
||||
const canDeleteCategory = computed(() => can("faq.category.delete"));
|
||||
const canManageCategories = computed(() => canCreateCategory.value || canUpdateCategory.value || canDeleteCategory.value);
|
||||
const sortedCategories = computed(() =>
|
||||
[...props.categories].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
|
||||
);
|
||||
|
||||
@@ -180,9 +180,9 @@
|
||||
<el-icon><User /></el-icon>
|
||||
<span>{{ TEXT.menu.profile }}</span>
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item command="logout">
|
||||
<el-dropdown-item command="logout" :disabled="loggingOut" divided>
|
||||
<el-icon><SwitchButton /></el-icon>
|
||||
<span>{{ TEXT.menu.logout }}</span>
|
||||
<span>{{ loggingOut ? "正在退出..." : TEXT.menu.logout }}</span>
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
@@ -218,8 +218,9 @@ import {
|
||||
User, Suitcase, House, Calendar, Flag,
|
||||
CircleCheck, Box, Coin, Notebook, Document, ArrowDown, SwitchButton, Files, Key
|
||||
} from "@element-plus/icons-vue";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { getProjectRoutePermission, hasProjectPermission, projectRouteLandingPaths } from "../utils/projectRoutePermissions";
|
||||
import { forceLogout, LOGOUT_REASON_MANUAL } from "../session/sessionManager";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const study = useStudyStore();
|
||||
@@ -233,6 +234,7 @@ const canAccessProjectPath = (path: string) =>
|
||||
hasProjectPermission(study.currentPermissions, projectRole.value, getProjectRoutePermission(path), isAdmin.value);
|
||||
const canAccessAnyProjectPath = (paths: string[]) => paths.some((path) => canAccessProjectPath(path));
|
||||
const hasAnyProjectModuleAccess = computed(() => canAccessAnyProjectPath(projectRouteLandingPaths));
|
||||
const loggingOut = ref(false);
|
||||
|
||||
/* 动态设置 body 上的侧边栏宽度 CSS 变量,用于全局弹窗定位偏移 */
|
||||
const hasSidebar = computed(() => isAdmin.value || !!study.currentStudy);
|
||||
@@ -433,18 +435,41 @@ const toggleCollapse = () => {
|
||||
localStorage.setItem("ctms_sidebar_collapsed", isCollapsed.value ? "1" : "0");
|
||||
};
|
||||
|
||||
const onLogout = () => {
|
||||
const logoutImmediately = () => {
|
||||
auth.logout();
|
||||
study.clearCurrentStudy();
|
||||
router.replace("/login");
|
||||
};
|
||||
|
||||
const onLogout = async () => {
|
||||
if (loggingOut.value) return;
|
||||
const confirmed = await ElMessageBox.confirm(
|
||||
"退出后需要重新登录才能继续访问项目数据。",
|
||||
"确认退出登录",
|
||||
{
|
||||
type: "warning",
|
||||
confirmButtonText: "退出登录",
|
||||
cancelButtonText: TEXT.common.actions.cancel,
|
||||
distinguishCancelAndClose: true,
|
||||
},
|
||||
).catch(() => null);
|
||||
if (!confirmed) return;
|
||||
loggingOut.value = true;
|
||||
try {
|
||||
forceLogout(LOGOUT_REASON_MANUAL);
|
||||
} finally {
|
||||
window.setTimeout(() => {
|
||||
loggingOut.value = false;
|
||||
}, 300);
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
if (auth.token && !auth.user) {
|
||||
try {
|
||||
await auth.fetchMe();
|
||||
} catch {
|
||||
onLogout();
|
||||
logoutImmediately();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,4 +41,15 @@ describe("Layout breadcrumbs", () => {
|
||||
|
||||
expect(source).toContain('<component v-if="Component" :is="Component" />');
|
||||
});
|
||||
|
||||
it("confirms manual logout and records the logout reason", () => {
|
||||
const source = readLayout();
|
||||
|
||||
expect(source).toContain('command="logout" :disabled="loggingOut" divided');
|
||||
expect(source).toContain("ElMessageBox.confirm(");
|
||||
expect(source).toContain("确认退出登录");
|
||||
expect(source).toContain("退出后需要重新登录才能继续访问项目数据。");
|
||||
expect(source).toContain("forceLogout(LOGOUT_REASON_MANUAL)");
|
||||
expect(source).toContain('loggingOut ? "正在退出..." : TEXT.menu.logout');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
<template>
|
||||
<teleport to="body">
|
||||
<div class="lock-screen" role="dialog" aria-modal="true">
|
||||
<div class="lock-backdrop" />
|
||||
<div class="lock-panel">
|
||||
<h2 class="lock-title">已锁定</h2>
|
||||
<p class="lock-desc">30 分钟无操作将锁定,2 小时无操作将自动退出登录</p>
|
||||
<p class="lock-countdown">剩余自动登出:{{ autoLogoutCountdown }}</p>
|
||||
<el-input
|
||||
ref="passwordInput"
|
||||
v-model="password"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
name="lock-password"
|
||||
placeholder="请输入登录密码"
|
||||
show-password
|
||||
@keyup.enter="onUnlock"
|
||||
/>
|
||||
<div class="lock-actions">
|
||||
<el-button type="primary" :loading="loading" @click="onUnlock">解锁</el-button>
|
||||
<el-button @click="onLogout">退出登录</el-button>
|
||||
</div>
|
||||
<p v-if="errorMessage" class="lock-error">{{ errorMessage }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useSessionStore } from "../store/session";
|
||||
import {
|
||||
AUTO_LOGOUT_TIMEOUT_HOURS,
|
||||
UNLOCK_MAX_ATTEMPTS,
|
||||
unlockWithPassword,
|
||||
forceLogout,
|
||||
} from "../session/sessionManager";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const session = useSessionStore();
|
||||
const password = ref("");
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref("");
|
||||
const passwordInput = ref<{ focus?: () => void } | null>(null);
|
||||
const nowTs = ref(Date.now());
|
||||
let countdownTimer: number | null = null;
|
||||
|
||||
const pad2 = (value: number) => String(value).padStart(2, "0");
|
||||
|
||||
const autoLogoutCountdown = computed(() => {
|
||||
const fallbackDeadlineAt =
|
||||
Math.max(session.lastUserActiveAt, session.lastNetworkActiveAt) + AUTO_LOGOUT_TIMEOUT_HOURS * 60 * 60 * 1000;
|
||||
const deadlineAt = session.lockAutoLogoutDeadlineAt || fallbackDeadlineAt;
|
||||
const remainMs = Math.max(0, deadlineAt - nowTs.value);
|
||||
const remainSec = Math.floor(remainMs / 1000);
|
||||
const hours = Math.floor(remainSec / 3600);
|
||||
const minutes = Math.floor((remainSec % 3600) / 60);
|
||||
const seconds = remainSec % 60;
|
||||
if (hours > 0) {
|
||||
return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}`;
|
||||
}
|
||||
return `${pad2(minutes)}:${pad2(seconds)}`;
|
||||
});
|
||||
|
||||
const startCountdown = () => {
|
||||
if (countdownTimer) {
|
||||
window.clearInterval(countdownTimer);
|
||||
}
|
||||
nowTs.value = Date.now();
|
||||
countdownTimer = window.setInterval(() => {
|
||||
nowTs.value = Date.now();
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const stopCountdown = () => {
|
||||
if (!countdownTimer) return;
|
||||
window.clearInterval(countdownTimer);
|
||||
countdownTimer = null;
|
||||
};
|
||||
|
||||
const focusPassword = () => {
|
||||
nextTick(() => {
|
||||
passwordInput.value?.focus?.();
|
||||
});
|
||||
};
|
||||
|
||||
const resolveUnlockEmail = async () => {
|
||||
if (session.lockEmail) return session.lockEmail;
|
||||
if (auth.user?.email) return auth.user.email;
|
||||
const cachedEmail = localStorage.getItem("ctms_last_login_email");
|
||||
if (cachedEmail) return cachedEmail;
|
||||
try {
|
||||
const me = await auth.fetchMe();
|
||||
return me?.email || "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const onUnlock = async () => {
|
||||
if (loading.value) return;
|
||||
errorMessage.value = "";
|
||||
const email = await resolveUnlockEmail();
|
||||
if (!email) {
|
||||
ElMessage.error("无法获取用户信息,请重新登录");
|
||||
forceLogout();
|
||||
return;
|
||||
}
|
||||
if (!password.value) {
|
||||
errorMessage.value = "请输入密码";
|
||||
focusPassword();
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
await unlockWithPassword(email, password.value);
|
||||
password.value = "";
|
||||
} catch (err: any) {
|
||||
session.incrementUnlockAttempt();
|
||||
const message = err?.response?.data?.detail || err?.response?.data?.message || err?.message || "密码错误";
|
||||
errorMessage.value = message;
|
||||
if (session.unlockAttempts >= UNLOCK_MAX_ATTEMPTS) {
|
||||
ElMessage.error("错误次数过多,请重新登录");
|
||||
forceLogout();
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
focusPassword();
|
||||
}
|
||||
};
|
||||
|
||||
const onLogout = () => {
|
||||
forceLogout();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
password.value = "";
|
||||
errorMessage.value = "";
|
||||
focusPassword();
|
||||
if (session.locked) {
|
||||
startCountdown();
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => session.locked,
|
||||
(value) => {
|
||||
if (value) {
|
||||
password.value = "";
|
||||
errorMessage.value = "";
|
||||
focusPassword();
|
||||
startCountdown();
|
||||
return;
|
||||
}
|
||||
password.value = "";
|
||||
errorMessage.value = "";
|
||||
stopCountdown();
|
||||
}
|
||||
);
|
||||
|
||||
onUnmounted(() => {
|
||||
stopCountdown();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.lock-screen {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2000;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.lock-backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(7, 10, 20, 0.35);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.lock-panel {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
width: min(420px, 92vw);
|
||||
background: #ffffff;
|
||||
border-radius: 16px;
|
||||
padding: 28px;
|
||||
box-shadow: 0 18px 48px rgba(15, 20, 35, 0.2);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.lock-title {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.lock-desc {
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.lock-countdown {
|
||||
margin: -4px 0 0;
|
||||
color: #1d4ed8;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.lock-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.lock-error {
|
||||
margin: 0;
|
||||
color: #d8342c;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,98 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useSessionStore } from "../store/session";
|
||||
import SessionTimeoutPrompt from "./SessionTimeoutPrompt.vue";
|
||||
|
||||
const sessionManagerMock = vi.hoisted(() => ({
|
||||
forceLogout: vi.fn(),
|
||||
markUserActive: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../session/sessionManager", () => ({
|
||||
forceLogout: sessionManagerMock.forceLogout,
|
||||
markUserActive: sessionManagerMock.markUserActive,
|
||||
LOGOUT_REASON_MANUAL: "manual",
|
||||
TIMEOUT_WARNING_SECONDS: 60,
|
||||
}));
|
||||
|
||||
const mountPrompt = () =>
|
||||
mount(SessionTimeoutPrompt, {
|
||||
global: {
|
||||
stubs: {
|
||||
transition: false,
|
||||
"el-button": {
|
||||
inheritAttrs: false,
|
||||
template: '<button type="button" @click="$emit(\'click\')"><slot /></button>',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createStorage = () => {
|
||||
const data = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key: string) => data.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
data.set(key, String(value));
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
data.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
data.clear();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
describe("SessionTimeoutPrompt", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-03-31T12:00:00.000Z"));
|
||||
setActivePinia(createPinia());
|
||||
sessionManagerMock.forceLogout.mockClear();
|
||||
sessionManagerMock.markUserActive.mockClear();
|
||||
Object.defineProperty(window, "localStorage", {
|
||||
value: createStorage(),
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the remaining time before automatic logout", () => {
|
||||
const auth = useAuthStore();
|
||||
const session = useSessionStore();
|
||||
auth.setToken("token");
|
||||
session.showTimeoutWarning(Date.now() + 60_000);
|
||||
|
||||
const wrapper = mountPrompt();
|
||||
|
||||
expect(wrapper.text()).toContain("即将自动退出");
|
||||
expect(wrapper.text()).toContain("60 秒");
|
||||
expect(wrapper.find(".timeout-progress span").attributes("style")).toContain("width: 100%");
|
||||
});
|
||||
|
||||
it("continues the session from the warning action", async () => {
|
||||
const auth = useAuthStore();
|
||||
const session = useSessionStore();
|
||||
auth.setToken("token");
|
||||
session.showTimeoutWarning(Date.now() + 60_000);
|
||||
|
||||
const wrapper = mountPrompt();
|
||||
await wrapper.findAll("button")[1].trigger("click");
|
||||
|
||||
expect(sessionManagerMock.markUserActive).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("logs out immediately from the warning action", async () => {
|
||||
const auth = useAuthStore();
|
||||
const session = useSessionStore();
|
||||
auth.setToken("token");
|
||||
session.showTimeoutWarning(Date.now() + 60_000);
|
||||
|
||||
const wrapper = mountPrompt();
|
||||
await wrapper.findAll("button")[0].trigger("click");
|
||||
|
||||
expect(sessionManagerMock.forceLogout).toHaveBeenCalledWith("manual");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
<template>
|
||||
<transition name="session-timeout-fade">
|
||||
<div v-if="visible" class="session-timeout-prompt" role="status" aria-live="polite">
|
||||
<div class="timeout-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<circle cx="12" cy="12" r="9"></circle>
|
||||
<path d="M12 7v5l3 2"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="timeout-copy">
|
||||
<strong>即将自动退出</strong>
|
||||
<span>{{ countdownText }} 后将退出登录,以保护项目数据。</span>
|
||||
</div>
|
||||
<div class="timeout-actions">
|
||||
<el-button size="small" @click="logoutNow">立即退出</el-button>
|
||||
<el-button size="small" type="primary" @click="continueSession">继续使用</el-button>
|
||||
</div>
|
||||
<div class="timeout-progress" aria-hidden="true">
|
||||
<span :style="{ width: progressWidth }"></span>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useSessionStore } from "../store/session";
|
||||
import {
|
||||
forceLogout,
|
||||
LOGOUT_REASON_MANUAL,
|
||||
markUserActive,
|
||||
TIMEOUT_WARNING_SECONDS,
|
||||
} from "../session/sessionManager";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const session = useSessionStore();
|
||||
const nowTs = ref(Date.now());
|
||||
let timer: number | null = null;
|
||||
|
||||
const visible = computed(() => Boolean(auth.token && session.timeoutWarningVisible));
|
||||
|
||||
const countdownText = computed(() => {
|
||||
const remainSeconds = Math.max(0, Math.ceil((session.timeoutAt - nowTs.value) / 1000));
|
||||
return `${remainSeconds} 秒`;
|
||||
});
|
||||
|
||||
const progressWidth = computed(() => {
|
||||
const remainSeconds = Math.max(0, Math.ceil((session.timeoutAt - nowTs.value) / 1000));
|
||||
const ratio = Math.min(1, remainSeconds / TIMEOUT_WARNING_SECONDS);
|
||||
return `${Math.round(ratio * 100)}%`;
|
||||
});
|
||||
|
||||
const stopTimer = () => {
|
||||
if (!timer) return;
|
||||
window.clearInterval(timer);
|
||||
timer = null;
|
||||
};
|
||||
|
||||
const startTimer = () => {
|
||||
stopTimer();
|
||||
nowTs.value = Date.now();
|
||||
timer = window.setInterval(() => {
|
||||
nowTs.value = Date.now();
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const continueSession = () => {
|
||||
markUserActive();
|
||||
};
|
||||
|
||||
const logoutNow = () => {
|
||||
forceLogout(LOGOUT_REASON_MANUAL);
|
||||
};
|
||||
|
||||
watch(
|
||||
visible,
|
||||
(value) => {
|
||||
if (value) {
|
||||
startTimer();
|
||||
return;
|
||||
}
|
||||
stopTimer();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopTimer();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.session-timeout-prompt {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
z-index: 2200;
|
||||
width: min(420px, calc(100vw - 32px));
|
||||
display: grid;
|
||||
grid-template-columns: 38px minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(197, 139, 42, 0.24);
|
||||
background: rgba(255, 252, 246, 0.96);
|
||||
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.14), inset 0 1px 0 rgba(255, 255, 255, 0.72);
|
||||
backdrop-filter: blur(16px);
|
||||
color: #3b2b12;
|
||||
}
|
||||
|
||||
.timeout-progress {
|
||||
grid-column: 1 / -1;
|
||||
height: 3px;
|
||||
overflow: hidden;
|
||||
border-radius: 999px;
|
||||
background: rgba(197, 139, 42, 0.14);
|
||||
}
|
||||
|
||||
.timeout-progress span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(90deg, #d59a35, #f2b84f);
|
||||
box-shadow: 0 0 12px rgba(242, 184, 79, 0.36);
|
||||
transition: width 220ms ease;
|
||||
}
|
||||
|
||||
.timeout-icon {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 11px;
|
||||
color: var(--ctms-warning);
|
||||
background: #fff3dc;
|
||||
box-shadow: inset 0 0 0 1px rgba(197, 139, 42, 0.16);
|
||||
}
|
||||
|
||||
.timeout-icon svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.timeout-copy {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.timeout-copy strong {
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
font-weight: 800;
|
||||
color: #182235;
|
||||
}
|
||||
|
||||
.timeout-copy span {
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
font-weight: 600;
|
||||
color: #7a5a23;
|
||||
}
|
||||
|
||||
.timeout-actions {
|
||||
display: inline-flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.session-timeout-fade-enter-active,
|
||||
.session-timeout-fade-leave-active {
|
||||
transition: opacity 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.session-timeout-fade-enter-from,
|
||||
.session-timeout-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.session-timeout-prompt {
|
||||
left: 16px;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
width: auto;
|
||||
grid-template-columns: 34px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.timeout-actions {
|
||||
grid-column: 1 / -1;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -51,7 +51,6 @@ export const TEXT = {
|
||||
noPermission: "无权限执行该操作",
|
||||
networkError: "网络错误,请稍后重试",
|
||||
fileTooLarge: "文件大小不能超过",
|
||||
sessionLocked: "请解锁后继续操作",
|
||||
sessionExpired: "登录已过期,请重新登录",
|
||||
requestFailed: "请求失败,请稍后重试",
|
||||
invalidStateAction: "当前状态不允许该操作",
|
||||
|
||||
@@ -9,10 +9,9 @@ vi.mock("../router", () => ({
|
||||
|
||||
vi.mock("../api/authClient", () => ({
|
||||
extendToken: vi.fn(),
|
||||
unlockSession: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("session manager idle recovery", () => {
|
||||
describe("session manager idle logout", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.useFakeTimers();
|
||||
@@ -50,37 +49,47 @@ describe("session manager idle recovery", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("locks instead of refreshing activity after long inactivity when user activity resumes", async () => {
|
||||
it("shows a timeout warning one minute before automatic logout", async () => {
|
||||
vi.setSystemTime(new Date("2026-03-10T01:00:00.000Z"));
|
||||
const { useSessionStore } = await import("../store/session");
|
||||
const { IDLE_TIMEOUT_MINUTES, AUTO_LOGOUT_TIMEOUT_HOURS, markUserActive } = await import("./sessionManager");
|
||||
const { IDLE_TIMEOUT_MINUTES, TIMEOUT_WARNING_SECONDS, initSessionManager } = await import("./sessionManager");
|
||||
const session = useSessionStore();
|
||||
const oldTs = Date.now() - ((IDLE_TIMEOUT_MINUTES * 60 - TIMEOUT_WARNING_SECONDS) * 1000);
|
||||
|
||||
session.recordUserActivity(oldTs);
|
||||
initSessionManager();
|
||||
|
||||
expect(session.timeoutWarningVisible).toBe(true);
|
||||
expect(session.timeoutAt).toBe(oldTs + IDLE_TIMEOUT_MINUTES * 60 * 1000);
|
||||
});
|
||||
|
||||
it("logs out after long inactivity when user activity resumes", async () => {
|
||||
vi.setSystemTime(new Date("2026-03-10T01:00:00.000Z"));
|
||||
const { useSessionStore } = await import("../store/session");
|
||||
const router = (await import("../router")).default;
|
||||
const { IDLE_TIMEOUT_MINUTES, LOGOUT_REASON_TIMEOUT, markUserActive } = await import("./sessionManager");
|
||||
const session = useSessionStore();
|
||||
const oldTs = Date.now() - (IDLE_TIMEOUT_MINUTES * 60 * 1000 + 1_000);
|
||||
|
||||
session.recordUserActivity(oldTs);
|
||||
session.recordNetworkActivity(oldTs);
|
||||
|
||||
markUserActive(Date.now());
|
||||
|
||||
expect(session.locked).toBe(true);
|
||||
expect(session.lockReason).toBe("idle");
|
||||
expect(session.lockAutoLogoutDeadlineAt).toBe(oldTs + AUTO_LOGOUT_TIMEOUT_HOURS * 60 * 60 * 1000);
|
||||
expect(window.sessionStorage.getItem("ctms_logout_reason")).toBe(LOGOUT_REASON_TIMEOUT);
|
||||
expect(router.replace).toHaveBeenCalledWith("/login");
|
||||
});
|
||||
|
||||
it("locks instead of refreshing activity after long inactivity when network activity resumes", async () => {
|
||||
it("clears the timeout warning when user activity resumes", async () => {
|
||||
vi.setSystemTime(new Date("2026-03-10T01:00:00.000Z"));
|
||||
const { useSessionStore } = await import("../store/session");
|
||||
const { IDLE_TIMEOUT_MINUTES, AUTO_LOGOUT_TIMEOUT_HOURS, markNetworkActive } = await import("./sessionManager");
|
||||
const { markUserActive } = await import("./sessionManager");
|
||||
const session = useSessionStore();
|
||||
const oldTs = Date.now() - (IDLE_TIMEOUT_MINUTES * 60 * 1000 + 1_000);
|
||||
|
||||
session.recordUserActivity(oldTs);
|
||||
session.recordNetworkActivity(oldTs);
|
||||
session.showTimeoutWarning(Date.now() + 60_000);
|
||||
|
||||
markNetworkActive(Date.now());
|
||||
markUserActive(Date.now());
|
||||
|
||||
expect(session.locked).toBe(true);
|
||||
expect(session.lockReason).toBe("idle");
|
||||
expect(session.lockAutoLogoutDeadlineAt).toBe(oldTs + AUTO_LOGOUT_TIMEOUT_HOURS * 60 * 60 * 1000);
|
||||
expect(session.timeoutWarningVisible).toBe(false);
|
||||
expect(session.timeoutAt).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,22 +2,20 @@ import router from "../router";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useSessionStore } from "../store/session";
|
||||
import { getToken, setToken, clearToken } from "../utils/auth";
|
||||
import { extendToken, getLoginKey, unlockSession } from "../api/authClient";
|
||||
import { encryptLoginPayload } from "../utils/loginCrypto";
|
||||
import { extendToken } from "../api/authClient";
|
||||
import { parseJwtExp } from "./jwt";
|
||||
|
||||
export const IDLE_TIMEOUT_MINUTES = 30;
|
||||
export const AUTO_LOGOUT_TIMEOUT_HOURS = 2;
|
||||
export const TIMEOUT_WARNING_SECONDS = 60;
|
||||
export const EXTEND_EARLY_SECONDS = 120;
|
||||
export const EXTEND_MIN_INTERVAL_SECONDS = 60;
|
||||
export const UNLOCK_MAX_ATTEMPTS = 5;
|
||||
export const LOGOUT_REASON_TIMEOUT = "timeout";
|
||||
export const LOGOUT_REASON_MANUAL = "manual";
|
||||
export const LOGOUT_REASON_AUTH_EXPIRED = "auth_expired";
|
||||
const LOGOUT_REASON_STORAGE_KEY = "ctms_logout_reason";
|
||||
|
||||
type BroadcastMessage =
|
||||
| { type: "ACTIVE"; at: number }
|
||||
| { type: "NETWORK"; at: number }
|
||||
| { type: "LOCK"; reason: string; email?: string; deadlineAt?: number }
|
||||
| { type: "TOKEN_UPDATED"; token: string }
|
||||
| { type: "LOGOUT"; reason?: string };
|
||||
|
||||
@@ -26,23 +24,15 @@ let extendPromise: Promise<{ token: string | null; authFailed: boolean }> | null
|
||||
let initialized = false;
|
||||
const channel = typeof BroadcastChannel !== "undefined" ? new BroadcastChannel("ctms-auth") : null;
|
||||
|
||||
const getLastActiveAt = (session: ReturnType<typeof useSessionStore>) =>
|
||||
Math.max(session.lastUserActiveAt, session.lastNetworkActiveAt);
|
||||
const getTimeoutAt = (session: ReturnType<typeof useSessionStore>) =>
|
||||
session.lastUserActiveAt + IDLE_TIMEOUT_MINUTES * 60 * 1000;
|
||||
|
||||
const reconcileSessionState = (now: number = Date.now()) => {
|
||||
const session = useSessionStore();
|
||||
if (session.locked) return false;
|
||||
const idleTimeoutMs = IDLE_TIMEOUT_MINUTES * 60 * 1000;
|
||||
const autoLogoutMs = AUTO_LOGOUT_TIMEOUT_HOURS * 60 * 60 * 1000;
|
||||
const lastActiveAt = getLastActiveAt(session);
|
||||
if (now - lastActiveAt > autoLogoutMs) {
|
||||
if (now >= getTimeoutAt(session)) {
|
||||
forceLogout(LOGOUT_REASON_TIMEOUT);
|
||||
return false;
|
||||
}
|
||||
if (now - lastActiveAt > idleTimeoutMs) {
|
||||
lockSession("idle");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -61,24 +51,13 @@ const handleBroadcast = (message: BroadcastMessage) => {
|
||||
const session = useSessionStore();
|
||||
const auth = useAuthStore();
|
||||
if (message.type === "ACTIVE") {
|
||||
if (session.locked) return;
|
||||
session.recordUserActivity(message.at);
|
||||
scheduleIdleCheck();
|
||||
}
|
||||
if (message.type === "NETWORK") {
|
||||
if (session.locked) return;
|
||||
session.recordNetworkActivity(message.at);
|
||||
scheduleIdleCheck();
|
||||
}
|
||||
if (message.type === "LOCK") {
|
||||
const reason = message.reason as "idle" | "extend_failed" | "token_invalid";
|
||||
session.lock(reason || "idle", message.email, message.deadlineAt);
|
||||
scheduleIdleCheck();
|
||||
}
|
||||
if (message.type === "TOKEN_UPDATED") {
|
||||
auth.setToken(message.token);
|
||||
setToken(message.token);
|
||||
session.unlock();
|
||||
session.resetActivity();
|
||||
}
|
||||
if (message.type === "LOGOUT") {
|
||||
performLogout(message.reason);
|
||||
@@ -91,39 +70,22 @@ const scheduleIdleCheck = () => {
|
||||
}
|
||||
const session = useSessionStore();
|
||||
const now = Date.now();
|
||||
if (session.locked) {
|
||||
const remain = (session.lockAutoLogoutDeadlineAt || 0) - now;
|
||||
if (remain <= 0) {
|
||||
checkIdle();
|
||||
return;
|
||||
}
|
||||
idleTimer = window.setTimeout(checkIdle, remain);
|
||||
return;
|
||||
}
|
||||
const idleTimeoutMs = IDLE_TIMEOUT_MINUTES * 60 * 1000;
|
||||
const autoLogoutMs = AUTO_LOGOUT_TIMEOUT_HOURS * 60 * 60 * 1000;
|
||||
const lastActiveAt = getLastActiveAt(session);
|
||||
const idleRemain = lastActiveAt + idleTimeoutMs - now;
|
||||
const logoutRemain = lastActiveAt + autoLogoutMs - now;
|
||||
const nextCheck = Math.min(idleRemain, logoutRemain);
|
||||
if (nextCheck <= 0) {
|
||||
const timeoutAt = getTimeoutAt(session);
|
||||
const warningAt = timeoutAt - TIMEOUT_WARNING_SECONDS * 1000;
|
||||
if (timeoutAt <= now) {
|
||||
checkIdle();
|
||||
return;
|
||||
}
|
||||
idleTimer = window.setTimeout(checkIdle, nextCheck);
|
||||
if (warningAt <= now) {
|
||||
session.showTimeoutWarning(timeoutAt);
|
||||
idleTimer = window.setTimeout(checkIdle, timeoutAt - now);
|
||||
return;
|
||||
}
|
||||
session.clearTimeoutWarning();
|
||||
idleTimer = window.setTimeout(checkIdle, warningAt - now);
|
||||
};
|
||||
|
||||
const checkIdle = () => {
|
||||
const session = useSessionStore();
|
||||
if (session.locked) {
|
||||
const deadlineAt = session.lockAutoLogoutDeadlineAt || 0;
|
||||
if (deadlineAt > 0 && Date.now() >= deadlineAt) {
|
||||
forceLogout(LOGOUT_REASON_TIMEOUT);
|
||||
return;
|
||||
}
|
||||
scheduleIdleCheck();
|
||||
return;
|
||||
}
|
||||
if (!reconcileSessionState(Date.now())) return;
|
||||
scheduleIdleCheck();
|
||||
};
|
||||
@@ -166,34 +128,12 @@ export const initSessionManager = () => {
|
||||
|
||||
export const markUserActive = (at: number = Date.now()) => {
|
||||
const session = useSessionStore();
|
||||
if (session.locked) return;
|
||||
if (!reconcileSessionState(at)) return;
|
||||
session.recordUserActivity(at);
|
||||
broadcast({ type: "ACTIVE", at });
|
||||
scheduleIdleCheck();
|
||||
};
|
||||
|
||||
export const markNetworkActive = (at: number = Date.now()) => {
|
||||
const session = useSessionStore();
|
||||
if (session.locked) return;
|
||||
if (!reconcileSessionState(at)) return;
|
||||
session.recordNetworkActivity(at);
|
||||
broadcast({ type: "NETWORK", at });
|
||||
scheduleIdleCheck();
|
||||
};
|
||||
|
||||
export const lockSession = (reason: "idle" | "extend_failed" | "token_invalid") => {
|
||||
const session = useSessionStore();
|
||||
const auth = useAuthStore();
|
||||
if (session.locked) return;
|
||||
const email = auth.user?.email || "";
|
||||
const autoLogoutMs = AUTO_LOGOUT_TIMEOUT_HOURS * 60 * 60 * 1000;
|
||||
const deadlineAt = getLastActiveAt(session) + autoLogoutMs;
|
||||
session.lock(reason, email, deadlineAt);
|
||||
broadcast({ type: "LOCK", reason, email, deadlineAt });
|
||||
scheduleIdleCheck();
|
||||
};
|
||||
|
||||
const setLogoutReason = (reason?: string) => {
|
||||
try {
|
||||
if (!reason) {
|
||||
@@ -221,7 +161,7 @@ const performLogout = (reason?: string) => {
|
||||
const auth = useAuthStore();
|
||||
const session = useSessionStore();
|
||||
auth.logout();
|
||||
session.unlock();
|
||||
session.resetActivity();
|
||||
clearToken();
|
||||
router.replace("/login");
|
||||
};
|
||||
@@ -259,10 +199,10 @@ export const extendAccessToken = async (reason: "early" | "response-401") => {
|
||||
} catch (err: any) {
|
||||
const status = err?.response?.status;
|
||||
if (status === 401) {
|
||||
lockSession("extend_failed");
|
||||
forceLogout(LOGOUT_REASON_AUTH_EXPIRED);
|
||||
authFailed = true;
|
||||
} else if (status === 403) {
|
||||
forceLogout();
|
||||
forceLogout(LOGOUT_REASON_AUTH_EXPIRED);
|
||||
authFailed = true;
|
||||
}
|
||||
return { token: null, authFailed };
|
||||
@@ -278,40 +218,13 @@ export const startTokenKeepAlive = () => {
|
||||
const token = getToken();
|
||||
if (!token) return;
|
||||
const session = useSessionStore();
|
||||
if (session.locked) return;
|
||||
const expAt = parseJwtExp(token);
|
||||
if (!expAt) return;
|
||||
const remaining = expAt - Date.now();
|
||||
const timeoutMs = IDLE_TIMEOUT_MINUTES * 60 * 1000;
|
||||
const active = Date.now() - getLastActiveAt(session) < timeoutMs;
|
||||
const active = Date.now() - session.lastUserActiveAt < timeoutMs;
|
||||
if (active && remaining < EXTEND_EARLY_SECONDS * 1000) {
|
||||
void extendAccessToken("early");
|
||||
}
|
||||
}, 10000);
|
||||
};
|
||||
|
||||
export const unlockWithPassword = async (email: string, password: string) => {
|
||||
const session = useSessionStore();
|
||||
const auth = useAuthStore();
|
||||
const { data: loginKey } = await getLoginKey();
|
||||
const ciphertext = await encryptLoginPayload(loginKey.public_key, {
|
||||
email,
|
||||
password,
|
||||
challenge: loginKey.challenge,
|
||||
});
|
||||
const { data } = await unlockSession({
|
||||
key_id: loginKey.key_id,
|
||||
challenge: loginKey.challenge,
|
||||
ciphertext,
|
||||
});
|
||||
updateToken(data.accessToken);
|
||||
session.unlock();
|
||||
try {
|
||||
await auth.fetchMe();
|
||||
} catch {
|
||||
// token已更新但用户信息拉取失败时,避免界面进入无角色状态
|
||||
forceLogout();
|
||||
throw new Error("无法获取用户信息,请重新登录");
|
||||
}
|
||||
markUserActive();
|
||||
};
|
||||
|
||||
@@ -82,18 +82,21 @@ describe("auth store logout", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("clears session lock state when logging out", async () => {
|
||||
it("resets session activity state when logging out", async () => {
|
||||
const { useAuthStore } = await import("./auth");
|
||||
const { useSessionStore } = await import("./session");
|
||||
const session = useSessionStore();
|
||||
const auth = useAuthStore();
|
||||
const staleTs = Date.now() - 60_000;
|
||||
|
||||
session.lock("token_invalid", "user@example.com", Date.now() + 60_000);
|
||||
session.recordUserActivity(staleTs);
|
||||
session.setLastExtendAt(staleTs);
|
||||
session.showTimeoutWarning(staleTs + 30_000);
|
||||
auth.logout();
|
||||
|
||||
expect(session.locked).toBe(false);
|
||||
expect(session.lockReason).toBeNull();
|
||||
expect(session.lockEmail).toBe("");
|
||||
expect(session.lastUserActiveAt).toBeGreaterThan(staleTs);
|
||||
expect(session.lastExtendAt).toBe(0);
|
||||
expect(session.timeoutWarningVisible).toBe(false);
|
||||
});
|
||||
|
||||
it("uses encrypted login by default outside a secure browser context", async () => {
|
||||
|
||||
@@ -26,8 +26,7 @@ export const useAuthStore = defineStore("auth", () => {
|
||||
: await encryptedLogin(email, password);
|
||||
token.value = data.access_token;
|
||||
setToken(data.access_token);
|
||||
// 避免锁屏态下 fetchMe 被请求拦截
|
||||
useSessionStore().unlock();
|
||||
useSessionStore().resetActivity();
|
||||
localStorage.setItem(LAST_LOGIN_EMAIL_KEY, email);
|
||||
const me = await fetchMeAction();
|
||||
const studyStore = useStudyStore();
|
||||
@@ -71,7 +70,7 @@ export const useAuthStore = defineStore("auth", () => {
|
||||
token.value = null;
|
||||
user.value = null;
|
||||
forceLogin.value = false;
|
||||
sessionStore.unlock();
|
||||
sessionStore.resetActivity();
|
||||
clearToken();
|
||||
studyStore.clearCurrentStudy();
|
||||
};
|
||||
|
||||
@@ -8,21 +8,20 @@ describe("session store", () => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("resets activity timestamps when unlocking a previously stale session", async () => {
|
||||
it("resets activity timestamps and token extension state", async () => {
|
||||
const { useSessionStore } = await import("./session");
|
||||
const session = useSessionStore();
|
||||
const staleTs = Date.now() - 2 * 60 * 60 * 1000 - 1_000;
|
||||
|
||||
session.recordUserActivity(staleTs);
|
||||
session.recordNetworkActivity(staleTs);
|
||||
session.setLastExtendAt(staleTs);
|
||||
session.lock("token_invalid", "user@example.com", staleTs + 10_000);
|
||||
session.showTimeoutWarning(staleTs + 30_000);
|
||||
|
||||
session.unlock();
|
||||
session.resetActivity();
|
||||
|
||||
expect(session.locked).toBe(false);
|
||||
expect(session.lastUserActiveAt).toBe(Date.now());
|
||||
expect(session.lastNetworkActiveAt).toBe(Date.now());
|
||||
expect(session.lastExtendAt).toBe(0);
|
||||
expect(session.timeoutWarningVisible).toBe(false);
|
||||
expect(session.timeoutAt).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,67 +1,49 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { ref } from "vue";
|
||||
|
||||
export type LockReason = "idle" | "extend_failed" | "token_invalid";
|
||||
|
||||
export const useSessionStore = defineStore("session", () => {
|
||||
const locked = ref(false);
|
||||
const lockReason = ref<LockReason | null>(null);
|
||||
const lockEmail = ref<string>("");
|
||||
const unlockAttempts = ref(0);
|
||||
const lockAutoLogoutDeadlineAt = ref(0);
|
||||
const lastUserActiveAt = ref(Date.now());
|
||||
const lastNetworkActiveAt = ref(Date.now());
|
||||
const lastExtendAt = ref(0);
|
||||
const timeoutWarningVisible = ref(false);
|
||||
const timeoutAt = ref(0);
|
||||
|
||||
const recordUserActivity = (ts: number = Date.now()) => {
|
||||
lastUserActiveAt.value = ts;
|
||||
timeoutWarningVisible.value = false;
|
||||
timeoutAt.value = 0;
|
||||
};
|
||||
|
||||
const recordNetworkActivity = (ts: number = Date.now()) => {
|
||||
lastNetworkActiveAt.value = ts;
|
||||
};
|
||||
|
||||
const lock = (reason: LockReason, email?: string, autoLogoutDeadlineAt?: number) => {
|
||||
locked.value = true;
|
||||
lockReason.value = reason;
|
||||
lockEmail.value = (email || "").trim();
|
||||
lockAutoLogoutDeadlineAt.value = autoLogoutDeadlineAt || 0;
|
||||
};
|
||||
|
||||
const unlock = () => {
|
||||
const resetActivity = () => {
|
||||
const now = Date.now();
|
||||
locked.value = false;
|
||||
lockReason.value = null;
|
||||
lockEmail.value = "";
|
||||
lockAutoLogoutDeadlineAt.value = 0;
|
||||
unlockAttempts.value = 0;
|
||||
lastUserActiveAt.value = now;
|
||||
lastNetworkActiveAt.value = now;
|
||||
lastExtendAt.value = 0;
|
||||
};
|
||||
|
||||
const incrementUnlockAttempt = () => {
|
||||
unlockAttempts.value += 1;
|
||||
timeoutWarningVisible.value = false;
|
||||
timeoutAt.value = 0;
|
||||
};
|
||||
|
||||
const setLastExtendAt = (ts: number) => {
|
||||
lastExtendAt.value = ts;
|
||||
};
|
||||
|
||||
const showTimeoutWarning = (deadlineAt: number) => {
|
||||
timeoutWarningVisible.value = true;
|
||||
timeoutAt.value = deadlineAt;
|
||||
};
|
||||
|
||||
const clearTimeoutWarning = () => {
|
||||
timeoutWarningVisible.value = false;
|
||||
timeoutAt.value = 0;
|
||||
};
|
||||
|
||||
return {
|
||||
locked,
|
||||
lockReason,
|
||||
lockEmail,
|
||||
lockAutoLogoutDeadlineAt,
|
||||
unlockAttempts,
|
||||
lastUserActiveAt,
|
||||
lastNetworkActiveAt,
|
||||
lastExtendAt,
|
||||
timeoutWarningVisible,
|
||||
timeoutAt,
|
||||
recordUserActivity,
|
||||
recordNetworkActivity,
|
||||
lock,
|
||||
unlock,
|
||||
incrementUnlockAttempt,
|
||||
resetActivity,
|
||||
setLastExtendAt,
|
||||
showTimeoutWarning,
|
||||
clearTimeoutWarning,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -44,7 +44,6 @@ describe("FAQ project permissions", () => {
|
||||
expect(source).toContain("const onRowClick = (row: FaqItem) =>");
|
||||
expect(source).not.toContain('column?.property !== "question"');
|
||||
expect(source).toContain('@click.stop="remove(scope.row)"');
|
||||
expect(source).toContain('@click.stop="toggle(scope.row)"');
|
||||
});
|
||||
|
||||
it("splits FAQ category create update and delete controls by backend operation permissions", () => {
|
||||
@@ -53,8 +52,9 @@ describe("FAQ project permissions", () => {
|
||||
expect(source).toContain('const canCreateCategory = computed(() => can("faq.category.create"))');
|
||||
expect(source).toContain('const canUpdateCategory = computed(() => can("faq.category.update"))');
|
||||
expect(source).toContain('const canDeleteCategory = computed(() => can("faq.category.delete"))');
|
||||
expect(source).toContain('action="faq.category.update"');
|
||||
expect(source).toContain('action="faq.category.delete"');
|
||||
expect(source).toContain(':can-create="canCreateCategory"');
|
||||
expect(source).toContain(':can-update="canUpdateCategory"');
|
||||
expect(source).toContain(':can-delete="canDeleteCategory"');
|
||||
expect(source).not.toContain("const canDelete = computed(() => isAdmin.value)");
|
||||
});
|
||||
|
||||
|
||||
@@ -74,4 +74,17 @@ describe("Login protocol agreement", () => {
|
||||
expect(restoreIndex).toBeLessThan(projectOverviewRouteIndex);
|
||||
expect(source).toContain("preferActive: !!auth.user?.is_admin");
|
||||
});
|
||||
|
||||
it("shows persistent logout reason notices on the login card", () => {
|
||||
const source = readLoginView();
|
||||
|
||||
expect(source).toContain('v-if="logoutNotice"');
|
||||
expect(source).toContain("LOGOUT_REASON_TIMEOUT");
|
||||
expect(source).toContain("LOGOUT_REASON_AUTH_EXPIRED");
|
||||
expect(source).toContain("LOGOUT_REASON_MANUAL");
|
||||
expect(source).toContain("30 分钟未检测到任何操作。为保护项目数据,请重新登录后继续。");
|
||||
expect(source).toContain("登录状态已失效");
|
||||
expect(source).toContain("已安全退出");
|
||||
expect(source).toContain(".logout-notice");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,23 @@
|
||||
<p class="sys-subtitle">Log in to your account</p>
|
||||
</div>
|
||||
|
||||
<div v-if="logoutNotice" class="logout-notice" :class="'logout-notice--' + logoutNotice.type">
|
||||
<div class="logout-notice-icon" aria-hidden="true">
|
||||
<svg v-if="logoutNotice.type === 'warning'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<circle cx="12" cy="12" r="10"></circle>
|
||||
<path d="M12 7v6"></path>
|
||||
<path d="M12 17h.01"></path>
|
||||
</svg>
|
||||
<svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M20 6 9 17l-5-5"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="logout-notice-body">
|
||||
<strong>{{ logoutNotice.title }}</strong>
|
||||
<span>{{ logoutNotice.message }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-form
|
||||
ref="formRef"
|
||||
:model="form"
|
||||
@@ -133,7 +150,12 @@ import { ElMessage, type FormInstance, type FormRules } from "element-plus";
|
||||
import { useAuthStore } from "../store/auth";
|
||||
import { useStudyStore } from "../store/study";
|
||||
import { TEXT, requiredMessage } from "../locales";
|
||||
import { consumeLogoutReason, LOGOUT_REASON_TIMEOUT } from "../session/sessionManager";
|
||||
import {
|
||||
consumeLogoutReason,
|
||||
LOGOUT_REASON_AUTH_EXPIRED,
|
||||
LOGOUT_REASON_MANUAL,
|
||||
LOGOUT_REASON_TIMEOUT,
|
||||
} from "../session/sessionManager";
|
||||
import { authProtocolSections } from "../content/authProtocol";
|
||||
|
||||
const auth = useAuthStore();
|
||||
@@ -162,13 +184,30 @@ const rules: FormRules<typeof form> = {
|
||||
|
||||
const loading = ref(false);
|
||||
const protocolDialogVisible = ref(false);
|
||||
const logoutNotice = ref<{ type: "info" | "warning"; title: string; message: string } | null>(null);
|
||||
|
||||
const protocolSections = authProtocolSections;
|
||||
|
||||
onMounted(async () => {
|
||||
const logoutReason = consumeLogoutReason();
|
||||
if (logoutReason === LOGOUT_REASON_TIMEOUT) {
|
||||
ElMessage.warning("长时间未操作,已自动退出登录,请重新登录");
|
||||
logoutNotice.value = {
|
||||
type: "warning",
|
||||
title: "已自动退出登录",
|
||||
message: "30 分钟未检测到任何操作。为保护项目数据,请重新登录后继续。",
|
||||
};
|
||||
} else if (logoutReason === LOGOUT_REASON_AUTH_EXPIRED) {
|
||||
logoutNotice.value = {
|
||||
type: "warning",
|
||||
title: "登录状态已失效",
|
||||
message: "当前会话无法继续使用,请重新登录。",
|
||||
};
|
||||
} else if (logoutReason === LOGOUT_REASON_MANUAL) {
|
||||
logoutNotice.value = {
|
||||
type: "info",
|
||||
title: "已安全退出",
|
||||
message: "本机登录状态已清除,需要时可再次登录。",
|
||||
};
|
||||
}
|
||||
form.email = localStorage.getItem("ctms_last_login_email") || "";
|
||||
form.rememberPassword = localStorage.getItem(REMEMBER_PASSWORD_KEY) === "true";
|
||||
@@ -357,6 +396,62 @@ const onSubmit = async () => {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.logout-notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
margin: -14px 0 24px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid;
|
||||
}
|
||||
|
||||
.logout-notice--warning {
|
||||
color: #8a5b12;
|
||||
background: #fff7e8;
|
||||
border-color: #f3d19e;
|
||||
}
|
||||
|
||||
.logout-notice--info {
|
||||
color: #315f49;
|
||||
background: #eef8f2;
|
||||
border-color: #b9dec8;
|
||||
}
|
||||
|
||||
.logout-notice-icon {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.logout-notice-icon svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.logout-notice-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.logout-notice-body strong {
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.logout-notice-body span {
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.login-form :deep(.el-form-item) {
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,18 @@ import { resolve } from "node:path";
|
||||
const readAuditLogsView = () => readFileSync(resolve(__dirname, "./AuditLogs.vue"), "utf8");
|
||||
|
||||
describe("audit logs access", () => {
|
||||
it("keeps the audit summary header compact", () => {
|
||||
const source = readAuditLogsView();
|
||||
|
||||
expect(source).toContain("padding: 10px 16px;");
|
||||
expect(source).toContain("padding: 9px 12px;");
|
||||
expect(source).toContain("width: 32px;");
|
||||
expect(source).toContain("height: 32px;");
|
||||
expect(source).toContain(".stat-icon svg { width: 18px; height: 18px; }");
|
||||
expect(source).toContain(".stat-value { font-size: 20px;");
|
||||
expect(source).toContain(".stat-label { font-size: 11px;");
|
||||
});
|
||||
|
||||
it("loads audit logs from the selected project context", () => {
|
||||
const source = readAuditLogsView();
|
||||
|
||||
|
||||
@@ -651,17 +651,17 @@ onMounted(async () => {
|
||||
.stats-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
gap: 10px;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--unified-shell-divider);
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
gap: 10px;
|
||||
padding: 9px 12px;
|
||||
border-radius: 10px;
|
||||
background: var(--ctms-neutral-100);
|
||||
transition: var(--ctms-transition);
|
||||
}
|
||||
@@ -672,24 +672,24 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.stat-icon svg { width: 20px; height: 20px; }
|
||||
.stat-icon svg { width: 18px; height: 18px; }
|
||||
.stat-card--total .stat-icon { background: #e8edf3; color: var(--ctms-primary); }
|
||||
.stat-card--success .stat-icon { background: #e6f4ed; color: var(--ctms-success); }
|
||||
.stat-card--fail .stat-icon { background: #fde8e8; color: var(--ctms-danger); }
|
||||
.stat-card--operators .stat-icon { background: #eef2f6; color: var(--ctms-info); }
|
||||
|
||||
.stat-body { display: flex; flex-direction: column; }
|
||||
.stat-value { font-size: 22px; font-weight: 700; line-height: 1.2; color: var(--ctms-text-main); }
|
||||
.stat-label { font-size: 12px; color: var(--ctms-text-secondary); margin-top: 2px; }
|
||||
.stat-value { font-size: 20px; font-weight: 700; line-height: 1.2; color: var(--ctms-text-main); }
|
||||
.stat-label { font-size: 11px; color: var(--ctms-text-secondary); margin-top: 2px; }
|
||||
|
||||
/* 筛选栏 */
|
||||
.audit-toolbar {
|
||||
|
||||
@@ -74,6 +74,17 @@ describe("project management access", () => {
|
||||
expect(source).not.toContain('fixed="right"');
|
||||
});
|
||||
|
||||
it("keeps the project summary header compact", () => {
|
||||
const source = readProjects();
|
||||
|
||||
expect(source).toContain("padding: 10px 16px;");
|
||||
expect(source).toContain("padding: 9px 12px;");
|
||||
expect(source).toContain("width: 32px;");
|
||||
expect(source).toContain("height: 32px;");
|
||||
expect(source).toContain("font-size: 20px;");
|
||||
expect(source).toContain("font-size: 11px;");
|
||||
});
|
||||
|
||||
it("renders project names as plain text and moves setup configuration to a gear action", () => {
|
||||
const source = readProjects();
|
||||
|
||||
|
||||
@@ -375,16 +375,16 @@ onMounted(() => {
|
||||
.stats-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
gap: 10px;
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
gap: 10px;
|
||||
padding: 9px 12px;
|
||||
border-radius: 10px;
|
||||
background: var(--ctms-neutral-100);
|
||||
transition: var(--ctms-transition);
|
||||
}
|
||||
@@ -395,9 +395,9 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -405,8 +405,8 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.stat-icon svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.stat-card--total .stat-icon { background: #e8edf3; color: var(--ctms-primary); }
|
||||
@@ -420,14 +420,14 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 22px;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
color: var(--ctms-text-main);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
font-size: 11px;
|
||||
color: var(--ctms-text-secondary);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
@@ -17,14 +17,49 @@ describe("Admin users table labels", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Admin users table layout", () => {
|
||||
it("uses a wider name column, even remaining columns, and compact icon actions", () => {
|
||||
const viewSource = readUsersView();
|
||||
|
||||
expect(viewSource).toContain('table-layout="fixed"');
|
||||
expect(viewSource).toContain(':label="TEXT.common.fields.name" width="360"');
|
||||
expect(viewSource).not.toContain('width="20%"');
|
||||
expect(viewSource).not.toContain('width="180"');
|
||||
expect(viewSource).not.toContain('width="160"');
|
||||
expect(viewSource).not.toContain('width="100"');
|
||||
expect(viewSource).not.toContain('fixed="right"');
|
||||
expect(viewSource).toContain('class="action-btn"');
|
||||
expect(viewSource).toContain("width: 28px;");
|
||||
expect(viewSource).toContain("gap: 4px;");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Admin users summary header", () => {
|
||||
it("keeps the management summary header compact", () => {
|
||||
const viewSource = readUsersView();
|
||||
|
||||
expect(viewSource).toContain("padding: 10px 16px;");
|
||||
expect(viewSource).toContain("padding: 9px 12px;");
|
||||
expect(viewSource).toContain("width: 32px;");
|
||||
expect(viewSource).toContain("height: 32px;");
|
||||
expect(viewSource).toContain("font-size: 20px;");
|
||||
expect(viewSource).toContain("font-size: 11px;");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Admin users filters", () => {
|
||||
it("applies keyword and status filters from the first page", () => {
|
||||
it("applies keyword automatically and status filters from the first page", () => {
|
||||
const viewSource = readUsersView();
|
||||
|
||||
expect(viewSource).toContain("@keyup.enter=\"applyFilters\"");
|
||||
expect(viewSource).toContain("@clear=\"applyFilters\"");
|
||||
expect(viewSource).toContain("@change=\"applyFilters\"");
|
||||
expect(viewSource).toContain("@click=\"applyFilters\"");
|
||||
expect(viewSource).not.toContain("@click=\"applyFilters\"");
|
||||
expect(viewSource).not.toContain(":icon=\"Refresh\"");
|
||||
expect(viewSource).not.toContain("Refresh } from");
|
||||
expect(viewSource).toContain("watch(searchKeyword, () => {");
|
||||
expect(viewSource).toContain("scheduleKeywordSearch();");
|
||||
expect(viewSource).toContain("keywordSearchTimer = setTimeout(() => {");
|
||||
expect(viewSource).toContain("}, 300);");
|
||||
expect(viewSource).toContain("page.value = 1");
|
||||
expect(viewSource).toContain("keyword: searchKeyword.value || undefined");
|
||||
expect(viewSource).toContain("status: statusFilter.value || undefined");
|
||||
|
||||
@@ -65,7 +65,6 @@
|
||||
clearable
|
||||
class="filter-input-comp"
|
||||
:prefix-icon="Search"
|
||||
@clear="applyFilters"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</div>
|
||||
@@ -77,9 +76,6 @@
|
||||
<el-option :label="TEXT.enums.userStatus.DISABLED" value="DISABLED" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="filter-item-form">
|
||||
<el-button @click="applyFilters" :icon="Refresh">{{ TEXT.common.actions.search }}</el-button>
|
||||
</div>
|
||||
<div class="filter-spacer"></div>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">{{ TEXT.common.actions.add }}{{ TEXT.modules.adminUsers.userLabel }}</el-button>
|
||||
</div>
|
||||
@@ -88,7 +84,7 @@
|
||||
<!-- 用户表格 -->
|
||||
<div class="unified-section user-table-section">
|
||||
<el-table :data="users" v-loading="loading" class="user-table" style="width: 100%" table-layout="fixed">
|
||||
<el-table-column :label="TEXT.common.fields.name" min-width="200">
|
||||
<el-table-column :label="TEXT.common.fields.name" width="360">
|
||||
<template #default="scope">
|
||||
<div class="user-cell">
|
||||
<div class="user-avatar" :class="'avatar--' + (scope.row.status || '').toLowerCase()">
|
||||
@@ -102,40 +98,42 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="clinical_department" :label="TEXT.modules.adminUsers.clinicalDepartmentLabel" show-overflow-tooltip />
|
||||
<el-table-column :label="TEXT.common.fields.status" width="100">
|
||||
<el-table-column :label="TEXT.common.fields.status">
|
||||
<template #default="scope">
|
||||
<span class="status-dot" :class="'dot--' + (scope.row.status || '').toLowerCase()"></span>
|
||||
{{ statusLabel(scope.row.status) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="created_at" :label="TEXT.modules.adminUsers.createdAt" width="160" show-overflow-tooltip>
|
||||
<el-table-column prop="created_at" :label="TEXT.modules.adminUsers.createdAt" show-overflow-tooltip>
|
||||
<template #default="scope">
|
||||
<span class="text-muted">{{ displayDateTime(scope.row.created_at) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="TEXT.common.labels.actions" width="180" align="center" fixed="right">
|
||||
<el-table-column :label="TEXT.common.labels.actions" align="center">
|
||||
<template #default="scope">
|
||||
<div class="action-row">
|
||||
<el-tooltip :content="TEXT.common.actions.edit" placement="top">
|
||||
<el-button link type="primary" :icon="Edit" @click="openEdit(scope.row)" />
|
||||
<el-button link type="primary" :icon="Edit" class="action-btn" @click="openEdit(scope.row)" />
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="scope.row.status === 'ACTIVE' ? TEXT.common.actions.disable : TEXT.common.actions.enable" placement="top">
|
||||
<el-button
|
||||
link
|
||||
:type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'"
|
||||
:icon="scope.row.status === 'ACTIVE' ? Lock : Unlock"
|
||||
class="action-btn"
|
||||
:disabled="isLastAdmin(scope.row)"
|
||||
@click="toggleStatus(scope.row)"
|
||||
/>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="TEXT.modules.adminUsers.resetPassword" placement="top">
|
||||
<el-button link type="warning" :icon="Key" @click="openReset(scope.row)" />
|
||||
<el-button link type="warning" :icon="Key" class="action-btn" @click="openReset(scope.row)" />
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="TEXT.common.actions.delete" placement="top">
|
||||
<el-button
|
||||
link
|
||||
type="danger"
|
||||
:icon="Delete"
|
||||
class="action-btn"
|
||||
:disabled="scope.row.id === auth.user?.id"
|
||||
@click="onDelete(scope.row)"
|
||||
/>
|
||||
@@ -164,9 +162,9 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { Edit, Delete, Key, Lock, Unlock, Search, Plus, Refresh } from "@element-plus/icons-vue";
|
||||
import { Edit, Delete, Key, Lock, Unlock, Search, Plus } from "@element-plus/icons-vue";
|
||||
import { fetchUsers, updateUser, deleteUser } from "../../api/users";
|
||||
import { fetchStudies } from "../../api/studies";
|
||||
import { listMembers } from "../../api/members";
|
||||
@@ -191,6 +189,7 @@ const statusFilter = ref("");
|
||||
const editingUser = ref<UserInfo | null>(null);
|
||||
const resetUser = ref<UserInfo | null>(null);
|
||||
const auth = useAuthStore();
|
||||
let keywordSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const activeCount = computed(() => allUsers.value.filter(u => u.status === 'ACTIVE').length);
|
||||
const pendingCount = computed(() => allUsers.value.filter(u => u.status === 'PENDING').length);
|
||||
@@ -251,10 +250,30 @@ const loadUsers = async () => {
|
||||
};
|
||||
|
||||
const applyFilters = () => {
|
||||
clearKeywordSearchTimer();
|
||||
page.value = 1;
|
||||
loadUsers();
|
||||
};
|
||||
|
||||
const clearKeywordSearchTimer = () => {
|
||||
if (!keywordSearchTimer) return;
|
||||
clearTimeout(keywordSearchTimer);
|
||||
keywordSearchTimer = null;
|
||||
};
|
||||
|
||||
const scheduleKeywordSearch = () => {
|
||||
clearKeywordSearchTimer();
|
||||
keywordSearchTimer = setTimeout(() => {
|
||||
keywordSearchTimer = null;
|
||||
page.value = 1;
|
||||
loadUsers();
|
||||
}, 300);
|
||||
};
|
||||
|
||||
watch(searchKeyword, () => {
|
||||
scheduleKeywordSearch();
|
||||
});
|
||||
|
||||
const onPageSizeChange = (size: number) => {
|
||||
pageSize.value = size;
|
||||
page.value = 1;
|
||||
@@ -360,23 +379,27 @@ const findUserProjects = async (userId: string) => {
|
||||
onMounted(() => {
|
||||
loadUsers();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearKeywordSearchTimer();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.stats-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
gap: 10px;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--unified-shell-divider);
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
gap: 10px;
|
||||
padding: 9px 12px;
|
||||
border-radius: 10px;
|
||||
background: var(--ctms-neutral-100);
|
||||
transition: var(--ctms-transition);
|
||||
}
|
||||
@@ -387,9 +410,9 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -397,8 +420,8 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.stat-icon svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.stat-card--total .stat-icon {
|
||||
@@ -427,14 +450,14 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 22px;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
color: var(--ctms-text-main);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
font-size: 11px;
|
||||
color: var(--ctms-text-secondary);
|
||||
margin-top: 2px;
|
||||
}
|
||||
@@ -559,10 +582,49 @@ onMounted(() => {
|
||||
.action-row {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
padding: 2px;
|
||||
border-radius: 8px;
|
||||
background: rgba(248, 250, 252, 0.72);
|
||||
box-shadow: inset 0 0 0 1px rgba(148, 163, 184, 0.14);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
min-height: 28px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border-radius: 7px;
|
||||
font-size: 15px;
|
||||
background: linear-gradient(180deg, rgba(255, 255, 255, 0.94), rgba(248, 250, 252, 0.82));
|
||||
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 0 0 1px rgba(148, 163, 184, 0.16);
|
||||
transition: transform 120ms ease, box-shadow 120ms ease, background-color 120ms ease;
|
||||
}
|
||||
|
||||
.action-row :deep(.el-button + .el-button) {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.action-row :deep(.el-button .el-icon) {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
|
||||
.action-btn:hover {
|
||||
transform: translateY(-1px);
|
||||
background: #fff;
|
||||
box-shadow: 0 4px 10px rgba(15, 23, 42, 0.1), inset 0 0 0 1px rgba(148, 163, 184, 0.22);
|
||||
}
|
||||
|
||||
.action-btn.is-disabled {
|
||||
transform: none;
|
||||
opacity: 0.45;
|
||||
box-shadow: inset 0 0 0 1px rgba(148, 163, 184, 0.12);
|
||||
}
|
||||
|
||||
/* 表格区域 */
|
||||
.user-table-section {
|
||||
padding: 0;
|
||||
|
||||
@@ -14,6 +14,7 @@ describe("DocumentDetail role labels", () => {
|
||||
expect(source).toContain("label: `${name}(${roleLabel(m.role_in_study)})`");
|
||||
expect(source).toContain("return roleLabel(row.target_id);");
|
||||
expect(source).toContain("await loadRoleTemplates();");
|
||||
expect(source).toContain("await loadDetail();");
|
||||
expect(source).not.toContain("displayEnum(TEXT.enums.userRole, value)");
|
||||
expect(source).not.toContain("displayEnum(TEXT.enums.userRole, m.role_in_study)");
|
||||
});
|
||||
@@ -99,8 +100,8 @@ describe("DocumentDetail editor overlays", () => {
|
||||
it("uses right-side drawers for upload and distribution forms", () => {
|
||||
const source = readSource();
|
||||
|
||||
expect(source).toContain("upload-editor-drawer");
|
||||
expect(source).toContain("distribution-editor-drawer");
|
||||
expect(source).toContain("upload-drawer");
|
||||
expect(source).toContain("editor-drawer");
|
||||
expect(source).toContain('direction="rtl"');
|
||||
expect(source).toContain(':show-close="false"');
|
||||
expect(source).toContain("editor-header");
|
||||
|
||||
@@ -870,7 +870,10 @@ watch(previewVisible, (visible) => {
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(() => { loadDetail(); });
|
||||
onMounted(async () => {
|
||||
await loadRoleTemplates();
|
||||
await loadDetail();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -45,19 +45,22 @@ describe("ContractFeeDetail permissions", () => {
|
||||
it("keeps payment table columns evenly distributed with clear labels", () => {
|
||||
const source = readDetail();
|
||||
|
||||
expect(source).toContain(':label="TEXT.modules.feeContracts.paymentSeqColumn"');
|
||||
expect(source).toContain('v-for="(payment, index) in detail.payments"');
|
||||
expect(source).toContain("TEXT.modules.feeContracts.paymentSeq");
|
||||
expect(source).toContain("TEXT.modules.feeContracts.paidFlag");
|
||||
expect(source).toContain("TEXT.modules.feeContracts.verifiedFlag");
|
||||
expect(source).toContain("tl-panel-amount");
|
||||
expect(source).not.toContain('width="20%"');
|
||||
expect(source.match(/min-width="180"/g)).toHaveLength(5);
|
||||
expect(source).not.toContain(".payment-table :deep(col:nth-child(-n + 5))");
|
||||
expect(source).toContain(':label="TEXT.common.fields.amount" align="left" header-align="left" min-width="180"');
|
||||
});
|
||||
|
||||
it("uses ten-thousand yuan as the only amount unit and hides currency", () => {
|
||||
const source = readDetail();
|
||||
|
||||
expect(source).toContain("formatAmountWan(detail.contract_amount)");
|
||||
expect(source).toContain("formatAmountWan(scope.row.amount)");
|
||||
expect(source).toContain('<span class="amount-unit">万</span>');
|
||||
expect(source).toContain("formatAmountWan(payment.amount)");
|
||||
expect(source).toContain('<span class="stat-tile-unit">万</span>');
|
||||
expect(source).toContain('<span class="amount-unit-sm">万</span>');
|
||||
expect(source).not.toContain("TEXT.common.fields.currency");
|
||||
expect(source).not.toContain("detail.currency");
|
||||
expect(source).not.toContain("currencyDefault");
|
||||
|
||||
@@ -20,18 +20,18 @@ describe("DrugShipments project permissions", () => {
|
||||
it("uses flexible data columns so the table fills the available page width", () => {
|
||||
const source = readSource();
|
||||
|
||||
expect(source).toContain('class="ctms-table shipment-table"');
|
||||
expect(source).toContain('class="shipment-table"');
|
||||
expect(source).toContain('style="width: 100%"');
|
||||
expect(source).toContain('table-layout="fixed"');
|
||||
expect(source).toContain(':label="TEXT.common.labels.actions" width="130"');
|
||||
expect(source).toContain(':label="TEXT.common.labels.actions" fixed="right"');
|
||||
expect(source).not.toMatch(/prop="(?:site_name|direction|ship_date|receive_date|quantity|batch_no|status|remark)"[^>]+(?:min-width|width)=/);
|
||||
});
|
||||
|
||||
it("keeps edit and delete actions on one line", () => {
|
||||
const source = readSource();
|
||||
|
||||
expect(source).toContain('class="shipment-actions"');
|
||||
expect(source).toContain(".shipment-actions");
|
||||
expect(source).toContain('class="cell-actions"');
|
||||
expect(source).toContain(".cell-actions");
|
||||
expect(source).toContain("white-space: nowrap;");
|
||||
});
|
||||
|
||||
@@ -43,11 +43,10 @@ describe("DrugShipments project permissions", () => {
|
||||
expect(source).toContain('entity-type="drug_shipment"');
|
||||
expect(source).toContain(':entity-id="editingId"');
|
||||
expect(source).toContain(':mode="\'upload\'"');
|
||||
expect(source).toContain(':center-upload-card-content="true"');
|
||||
expect(source).toContain("attachmentPanelRef.value?.pendingSnapshot() || []");
|
||||
expect(source).toContain("await attachmentPanelRef.value?.uploadPending(shipmentId)");
|
||||
expect(source).toContain("uploadPending");
|
||||
expect(source).toContain("group-dot-attachment");
|
||||
expect(source).toContain("dot--purple");
|
||||
expect(source).not.toContain("uploadAttachment");
|
||||
expect(source).not.toContain("pendingFiles");
|
||||
expect(source).not.toContain("upload-card-label");
|
||||
|
||||
@@ -23,11 +23,11 @@ describe("MaterialEquipment project permissions", () => {
|
||||
it("keeps the visible table columns evenly distributed", () => {
|
||||
const source = readSource();
|
||||
|
||||
expect(source).toContain('class="ctms-table equipment-table"');
|
||||
expect(source).toContain('class="equipment-table"');
|
||||
expect(source).toContain('style="width: 100%"');
|
||||
expect(source).toContain('table-layout="fixed"');
|
||||
expect(source).toContain('label="操作"');
|
||||
expect(source).not.toMatch(/<el-table-column[^>]+label="操作"[^>]+(?:width|min-width)=/);
|
||||
expect(source).not.toMatch(/<el-table-column[^>]+prop="(?:name|specModel|unit|brand)"[^>]+(?:width|min-width)=/);
|
||||
});
|
||||
|
||||
it("opens the detail page from row clicks instead of a detail action button", () => {
|
||||
@@ -54,7 +54,6 @@ describe("MaterialEquipment project permissions", () => {
|
||||
expect(source).toContain('entity-type="material_equipment"');
|
||||
expect(source).toContain(':entity-id="editingId"');
|
||||
expect(source).toContain(':mode="\'upload\'"');
|
||||
expect(source).toContain(':center-upload-card-content="true"');
|
||||
expect(source).toContain("attachmentPanelRef.value?.pendingSnapshot() || []");
|
||||
expect(source).toContain("await attachmentPanelRef.value?.uploadPending(equipmentId)");
|
||||
expect(source).toContain("uploadPending");
|
||||
|
||||
@@ -20,10 +20,10 @@ describe("StartupFeasibilityEthics project permissions", () => {
|
||||
expect(source).toContain('v-if="canReadEthics"');
|
||||
expect(source).toContain("if (!canReadFeasibility.value)");
|
||||
expect(source).toContain("if (!canReadEthics.value)");
|
||||
expect(source).toContain('v-if="canCreateFeasibility"');
|
||||
expect(source).toContain('v-if="activeTab === \'feasibility\' && canCreateFeasibility"');
|
||||
expect(source).toContain('v-if="canUpdateFeasibility"');
|
||||
expect(source).toContain('v-if="canDeleteFeasibility"');
|
||||
expect(source).toContain('v-if="canCreateEthics"');
|
||||
expect(source).toContain('v-if="activeTab === \'ethics\' && canCreateEthics"');
|
||||
expect(source).toContain('v-if="canUpdateEthics"');
|
||||
expect(source).toContain('v-if="canDeleteEthics"');
|
||||
});
|
||||
|
||||
@@ -30,9 +30,10 @@ describe("route view overlays are mounted only when visible", () => {
|
||||
file: "./subjects/SubjectDetail.vue",
|
||||
snippets: [
|
||||
'<el-dialog v-if="historyDialogVisible"',
|
||||
'<el-dialog v-if="visitDialogVisible"',
|
||||
'<el-dialog v-if="aeDialogVisible"',
|
||||
'<el-dialog v-if="pdDialogVisible"',
|
||||
'<VisitEditorDrawer',
|
||||
'<el-drawer v-if="adherenceDrawerVisible"',
|
||||
'<el-drawer v-if="aeDrawerVisible"',
|
||||
'<el-drawer v-if="pdDrawerVisible"',
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -106,13 +106,13 @@ describe("startup auth form/detail permissions", () => {
|
||||
it("shows training and authorization dates under positive status in the training table", () => {
|
||||
const source = read("./KickoffDetail.vue");
|
||||
|
||||
expect(source).toContain("trainingStatusLabel(scope.row)");
|
||||
expect(source).toContain("authorizationStatusLabel(scope.row)");
|
||||
expect(source).toContain("status-dot--yes");
|
||||
expect(source).toContain("status-dot--no");
|
||||
expect(source).toContain("scope.row.trained && scope.row.trained_date");
|
||||
expect(source).toContain("scope.row.authorized && scope.row.authorized_date");
|
||||
expect(source).toContain('class="status-date-small"');
|
||||
expect(source).not.toContain("scope.row.trained ? TEXT.common.boolean.yes : TEXT.common.boolean.no");
|
||||
expect(source).not.toContain("scope.row.authorized ? TEXT.common.boolean.yes : TEXT.common.boolean.no");
|
||||
expect(source).toContain('class="status-date"');
|
||||
expect(source).toContain("scope.row.trained ? TEXT.common.boolean.yes : TEXT.common.boolean.no");
|
||||
expect(source).toContain("scope.row.authorized ? TEXT.common.boolean.yes : TEXT.common.boolean.no");
|
||||
});
|
||||
|
||||
it("loads training authorizations for the current kickoff site only", () => {
|
||||
|
||||
@@ -10,7 +10,8 @@ describe("SubjectDetail medication adherence", () => {
|
||||
|
||||
expect(source).toContain('name="medicationAdherence"');
|
||||
expect(source).toContain("actual_medication_count");
|
||||
expect(source).toContain("保存用药次数");
|
||||
expect(source).toContain("saveMedicationAdherence");
|
||||
expect(source).toContain("<div class=\"editor-title\">用药依从性</div>");
|
||||
expect(source).toContain("实际用药次数为试验期间实际药物暴露次数");
|
||||
expect(source).toContain("75%~125% 范围内(包含边界值)");
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user