Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	backend/app/services/knowledge_cleaning/dify_sync_service.py
#	backend/app/services/knowledge_cleaning/settings_service.py
#	backend/tests/test_dify_sync_process_rule.py
#	docker-compose.yml
#	docs/funclist.md
#	frontend/package-lock.json
#	frontend/src/config.ts
#	frontend/src/features/admin/components/AdminNav.vue
#	frontend/src/features/admin/constants/modules.ts
#	frontend/src/features/admin/stores/admin-nav.store.ts
#	frontend/src/features/chat/components/messages/ChatMessageBubble.vue
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/auth.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/auth.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/auth.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/auth.json
#	frontend/src/locales/zh-TW/errors.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-11 14:55:20 +08:00
commit ca9c174f29
2050 files changed
+511839 -42320

No files matched your search

@@ -0,0 +1,46 @@
/**
* shared/api/client.stpErrors.spec.ts
* 用途:锁定 STP 错误码四语言映射(UI-05 / BE-04)。
* 依赖:vitest、vue-i18n、resolveLocalizedErrorMessage。
* 逻辑:断言 SHIPPING.STP_* 不回落英文后端 message。
*/
import { describe, expect, it, vi } from 'vitest';
vi.mock('@/i18n', async () => {
const { createI18n } = await import('vue-i18n');
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
errors: {
generic: '通用错误',
codes: {
'SHIPPING.STP_RETRY_ALREADY_CONFIRMED': '该复核单已确认建单,请改用确认后自动推进重试。',
'SHIPPING.STP_ENQUEUE_FAILED': '自动建单入队失败,请稍后重试或联系管理员。',
'SHIPPING.STP_NOT_ELIGIBLE': '当前订单尚未满足自动建单条件,请先完成校验与门禁后再重试。',
},
},
},
},
});
return { default: i18n };
});
describe('resolveLocalizedErrorMessage STP codes', () => {
it('maps SHIPPING.STP_* codes to locale text instead of English fallback', async () => {
const { resolveLocalizedErrorMessage } = await import('./client');
expect(resolveLocalizedErrorMessage(
'SHIPPING.STP_RETRY_ALREADY_CONFIRMED',
'Case already confirmed; use post-confirm auto progress retry',
)).toContain('已确认建单');
expect(resolveLocalizedErrorMessage(
'SHIPPING.STP_ENQUEUE_FAILED',
'STP enqueue failed',
)).toContain('入队失败');
expect(resolveLocalizedErrorMessage(
'SHIPPING.STP_NOT_ELIGIBLE',
'xfa_shadow_mode',
)).toContain('自动建单条件');
});
});
+102 -18
View File
@@ -1,9 +1,11 @@
/**
* shared/api/client.ts
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson。
* 所有 feature API 层应通过此模块发起 JSON 请求。
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。
* 依赖:auth、vue-i18n、shared/utils/download(Content-Disposition 文件名)。
* 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { parseContentDispositionFilename } from '@/shared/utils/download';
import i18n from '@/i18n';
export interface ApiSuccessEnvelope<T> {
@@ -43,9 +45,13 @@ export class BusinessError extends Error {
}
}
function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
const normalizedCode = code ? code.replace(/\./g, '_') : '';
const key = normalizedCode ? `errors.codes.${normalizedCode}` : '';
/**
* 按错误码解析当前语言文案,供 requestJson 与认证二进制下载共用。
* @param code - 后端 AppError 机器码
* @param fallbackMessage - 未配置错误码时的后端说明
* @returns 当前语言的用户可见错误信息
*/
export function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
const fallback = String(fallbackMessage || '').trim();
const isGenericFallback = (msg: string) => {
const v = msg.trim().toLowerCase();
@@ -55,21 +61,44 @@ function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string):
if (v.startsWith('http ')) return true;
return false;
};
if (key && i18n.global.te(key)) {
const localized = String(i18n.global.t(key));
if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) {
return `${localized} ${fallback}`;
/**
* 在 errors.codes 中查找文案:优先字面量键(含点号),再尝试下划线键与路径解析。
*/
const lookupCodeMessage = (rawCode: string): string | null => {
const bag = i18n.global.tm('errors.codes') as Record<string, unknown> | string | null;
if (bag && typeof bag === 'object' && !Array.isArray(bag)) {
const direct = bag[rawCode];
if (typeof direct === 'string' && direct.trim()) return direct;
const underscoredLeaf = rawCode.replace(/\./g, '_');
const viaUnderscore = bag[underscoredLeaf];
if (typeof viaUnderscore === 'string' && viaUnderscore.trim()) return viaUnderscore;
}
if (
normalizedCode === 'AUTH_FORBIDDEN'
&& fallback
&& !isGenericFallback(fallback)
&& fallback.toLowerCase() !== 'forbidden'
&& fallback !== localized
) {
return fallback;
const underscoredPath = `errors.codes.${rawCode.replace(/\./g, '_')}`;
if (i18n.global.te(underscoredPath)) return String(i18n.global.t(underscoredPath));
const dottedPath = `errors.codes.${rawCode}`;
if (i18n.global.te(dottedPath)) return String(i18n.global.t(dottedPath));
return null;
};
if (code) {
const localized = lookupCodeMessage(code);
if (localized) {
const normalizedCode = code.replace(/\./g, '_');
if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) {
return `${localized} ${fallback}`;
}
if (
normalizedCode === 'AUTH_FORBIDDEN'
&& fallback
&& !isGenericFallback(fallback)
&& fallback.toLowerCase() !== 'forbidden'
&& fallback !== localized
) {
return fallback;
}
return localized;
}
return localized;
}
if (fallback) return fallback;
if (i18n.global.te('errors.generic')) {
@@ -141,3 +170,58 @@ export async function requestJson<T>(url: string, init?: RequestInit): Promise<T
return data as T;
}
export type BlobDownloadResult = {
blob: Blob;
filename?: string;
requestId?: string;
};
/**
* 发起需鉴权的二进制下载;失败时按 Envelope 解析为 BusinessError(与 requestJson 同源)。
* @param url - 请求路径
* @param init - fetch 初始化参数
* @returns blob 与可选文件名、request_id
*/
export async function requestBlob(url: string, init?: RequestInit): Promise<BlobDownloadResult> {
const headers = new Headers(init?.headers || {});
const authHeaders = getAuthHeaders();
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
const res = await fetch(url, { ...init, headers });
const requestIdHeader = res.headers.get('X-Request-Id') || undefined;
const contentType = (res.headers.get('Content-Type') || '').toLowerCase();
if (!res.ok) {
let data: any = null;
if (contentType.includes('application/json')) {
try {
data = await res.json();
} catch {
data = null;
}
}
if (data && isEnvelope(data) && data.success === false) {
throw new BusinessError({
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`),
code: data.error?.code,
details: data.error?.details,
requestId: data.request_id || requestIdHeader,
status: res.status,
});
}
throw new BusinessError({
message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`),
code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR',
details: data?.details || {},
requestId: data?.request_id || requestIdHeader,
status: res.status,
});
}
const blob = await res.blob();
return {
blob,
filename: parseContentDispositionFilename(res.headers.get('Content-Disposition')),
requestId: requestIdHeader,
};
}
@@ -6,7 +6,7 @@
* 逻辑:KbWorkspaceOverlays、ChatViewOverlays、各管理端页面以 v-model 控制显隐。
*/
import { computed, onBeforeUnmount, watch } from 'vue';
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
interface Props {
@@ -18,6 +18,10 @@ interface Props {
confirmLoading?: boolean;
/** danger 用于删除;primary 用于写入等非破坏性确认 */
confirmTone?: 'danger' | 'primary';
/** 可选审计原因;开启 required 后确认前必须填写。 */
reasonLabel?: string;
reasonPlaceholder?: string;
reasonRequired?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
@@ -27,15 +31,20 @@ const props = withDefaults(defineProps<Props>(), {
cancelText: '',
confirmLoading: false,
confirmTone: 'danger',
reasonLabel: '',
reasonPlaceholder: '',
reasonRequired: false,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm'): void;
(e: 'confirm', reason: string): void;
(e: 'cancel'): void;
}>();
const { t } = useI18n();
const reason = ref('');
const reasonMissing = ref(false);
const resolvedTitle = computed(() => props.title || t('common.deleteDialog.defaultTitle'));
const resolvedMessage = computed(() => props.message || t('common.deleteDialog.defaultMessage'));
@@ -60,7 +69,12 @@ const handleCancel = () => {
* 核心逻辑:先 emit confirm 供父级执行删除,再 closeDialog,与取消行为一致,避免仅依赖父级 v-model 时弹窗残留。
*/
const handleConfirm = () => {
emit('confirm');
const resolvedReason = reason.value.trim();
if (props.reasonRequired && !resolvedReason) {
reasonMissing.value = true;
return;
}
emit('confirm', resolvedReason);
closeDialog();
};
@@ -74,6 +88,8 @@ watch(
() => props.modelValue,
(visible) => {
if (visible) {
reason.value = '';
reasonMissing.value = false;
document.addEventListener('keydown', handleEscKey);
return;
}
@@ -108,6 +124,12 @@ onBeforeUnmount(() => {
</div>
</div>
<label v-if="reasonLabel" class="mt-5 block space-y-1.5">
<span class="label-field">{{ reasonLabel }}<span v-if="reasonRequired" class="text-red-500"> *</span></span>
<textarea v-model="reason" rows="3" class="input-field w-full resize-y" :placeholder="reasonPlaceholder" @input="reasonMissing = false" />
<span v-if="reasonMissing" class="text-xs text-red-600">{{ t('common.required') }}</span>
</label>
<div class="mt-6 flex justify-end gap-2">
<button type="button" class="btn-secondary btn-sm" @click="handleCancel">
{{ resolvedCancelText }}
@@ -41,6 +41,7 @@ const props = defineProps<{
currentIndex?: number;
agentId?: number | null;
authHeaders?: Record<string, string>;
requiredDuration?: number;
}>();
const emit = defineEmits<{
@@ -49,6 +50,35 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
const countdownSeconds = ref(0);
let countdownTimer: ReturnType<typeof setInterval> | null = null;
const startCountdown = () => {
if (countdownTimer) {
clearInterval(countdownTimer);
countdownTimer = null;
}
if (props.requiredDuration && props.requiredDuration > 0) {
countdownSeconds.value = props.requiredDuration * 60;
countdownTimer = setInterval(() => {
if (countdownSeconds.value > 0) {
countdownSeconds.value--;
} else {
if (countdownTimer) clearInterval(countdownTimer);
}
}, 1000);
} else {
countdownSeconds.value = 0;
}
};
const stopCountdown = () => {
if (countdownTimer) {
clearInterval(countdownTimer);
countdownTimer = null;
}
};
const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
@@ -647,6 +677,9 @@ const loadContent = async () => {
watch(
() => [props.modelValue, activeFile.value?.url, activeFile.value?.name, activeIndex.value, activeFiles.value.length],
() => {
if (props.modelValue) {
startCountdown();
}
loadContent();
},
{ immediate: true }
@@ -657,6 +690,7 @@ watch(
(v) => {
if (!v) {
clearOfficeObjectUrl();
stopCountdown();
}
}
);
@@ -674,6 +708,9 @@ watch(
</div>
</div>
<div class="flex shrink-0 items-center gap-2">
<div v-if="countdownSeconds > 0" class="flex items-center justify-center h-8 w-8 rounded-full border border-red-200 bg-red-50 text-red-500 font-semibold text-xs shadow-sm">
{{ countdownSeconds }}s
</div>
<div v-if="isExcelPreviewFile" class="flex items-center gap-2 rounded-full border border-default bg-surface px-2 py-1">
<button
type="button"
@@ -4,6 +4,7 @@
* 用途:通用偏移分页条(摘要、每页条数、页码按钮)。
* 依赖:buildOffsetPageButtons、common.pagination i18n、components-ds 样式类。
* 逻辑:父组件 v-model:page / v-model:page-size,服务端或客户端分页均可复用。
* 每页条数用自定义 SVG 箭头,并隐藏系统原生/::picker-icon,避免 Windows 下双箭头。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -95,10 +96,10 @@ const onPageSizeChange = (size: number): void => {
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-xs text-secondary">
<span>{{ t('common.pagination.perPage') }}</span>
<span class="relative inline-flex items-center">
<span class="pagination-page-size relative inline-flex items-center">
<select
:value="pageSize"
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
class="admin-table-filter-input appearance-none bg-none pl-2 pr-7 py-1 text-xs leading-5"
@change="onPageSizeChange(Number(($event.target as HTMLSelectElement).value))"
>
<option v-for="size in pageSizeOptions" :key="`page-size-${size}`" :value="size">
@@ -154,3 +155,25 @@ const onPageSizeChange = (size: number): void => {
</div>
</div>
</template>
<style scoped>
/**
* 隐藏系统原生下拉箭头(含 Chromium ::picker-icon / Edge ::-ms-expand)。
* 只保留模板里的自定义 SVG,避免 Windows 下两个箭头叠在一起。
*/
.pagination-page-size select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-image: none;
}
.pagination-page-size select::-ms-expand {
display: none;
}
.pagination-page-size select::picker-icon {
display: none;
content: none;
}
</style>
@@ -10,6 +10,7 @@ export const AGENT_CODE_GENERIC = 'generic';
export const AGENT_CODE_SHIPPING_NOTICE = 'shipping_notice';
export const AGENT_CODE_FILE_CHECK = 'file_check';
export const AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review';
export const AGENT_CODE_IN_TRANSIT_TRANSFER = 'in_transit_transfer';
export interface AgentRegistryCapabilities {
streaming?: boolean;
+49 -6
View File
@@ -1,19 +1,22 @@
/**
* shared/utils/auth.ts
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步,以及 401 是否表示会话失效的判断。
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理;改密等业务 401 不得触发全局登出。
*/
export type FeaturePermissions = {
training_hr_manage?: boolean;
'contract_payment.access'?: boolean;
[key: string]: boolean | undefined;
};
export interface AuthUser {
id?: number;
username?: string;
real_name?: string;
employee_id?: string;
role?: string;
feature_permissions?: {
training_hr_manage?: boolean;
[key: string]: boolean | undefined;
};
feature_permissions?: FeaturePermissions;
token?: string;
access_token?: string;
refresh_token?: string;
@@ -107,6 +110,27 @@ export const getStoredAuthUser = (): AuthUser | null => {
return null;
};
/**
* 就地更新当前登录用户的若干字段,不改变 remember / expiry 所在存储。
* 核心逻辑:按 sessionStorage → localStorage 找到现有 payload,合并 partial 后写回同一位置。
* @param partial - 需要覆盖的用户字段(如首页刷新得到的 feature_permissions)
* @returns 合并后的用户;当前没有登录态时返回 null
*/
export const patchStoredAuthUser = (partial: Partial<AuthUser>): AuthUser | null => {
const candidates: Array<[Storage, string]> = [
[sessionStorage, AUTH_USER_KEY],
[localStorage, AUTH_USER_KEY],
];
for (const [storage, key] of candidates) {
const payload = readStoredAuthPayload(storage, key);
if (!payload?.user) continue;
const nextUser = { ...payload.user, ...partial };
storage.setItem(key, JSON.stringify({ ...payload, user: nextUser }));
return nextUser;
}
return null;
};
export const getAuthToken = (): string => {
const user = getStoredAuthUser();
const token = user?.access_token || user?.token;
@@ -306,6 +330,25 @@ export const initAuthSync = (): void => {
}
};
const BUSINESS_UNAUTHORIZED_CODES = new Set([
'CASDOOR_INVALID_CREDENTIALS',
'AUTH_INCORRECT_CURRENT_PASSWORD',
'AUTH_INCORRECT_PASSWORD',
'AUTH_PASSWORD_UNCHANGED',
]);
/**
* 判断 API 401 是否表示登录会话失效,从而需要清 token 并跳转登录页。
* 核心逻辑:空错误码按会话失效处理;改密/凭据类业务码即使历史接口返回 401 也不清会话。
* @param code - 后端 envelope error.code
* @returns true 时由全局 fetch 包装派发 hxops:unauthorized
*/
export function isSessionUnauthorizedError(code?: string | null): boolean {
const raw = String(code || '').trim();
if (!raw) return true;
return !BUSINESS_UNAUTHORIZED_CODES.has(raw.replace(/\./g, '_').toUpperCase());
}
let _refreshing: Promise<string | null> | null = null;
export const refreshAccessToken = async (): Promise<string | null> => {
+24 -2
View File
@@ -1,6 +1,8 @@
/**
* shared/utils/casdoor.ts
* Casdoor OAuth 错误文案解析。
* 用途:把 Casdoor / 改密相关 BusinessError 映射为登录与个人中心可读文案。
* 依赖:BusinessError、vue-i18n t()。
* 逻辑:优先用稳定 error.code;个人中心改密与管理端用户编辑共用同一套码。
*/
import type { BusinessError } from '@/shared/api/client';
@@ -10,9 +12,20 @@ function cleanText(value: unknown): string {
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
}
/**
* 从 BusinessError 取出可映射的 Casdoor / 改密错误码。
* 核心逻辑:优先稳定 code,其次 details.error_code,最后从英文原文兜底。
* @param err - requestJson 抛出的业务错误
* @returns 用于文案映射的错误码
*/
export function pickCasdoorErrorCode(err: BusinessError): string {
const code = cleanText(err.code);
if (code.startsWith('CASDOOR_') || code === 'ACCOUNT_DISABLED' || code === 'AUTH.INCORRECT_CURRENT_PASSWORD') {
if (
code.startsWith('CASDOOR_')
|| code === 'ACCOUNT_DISABLED'
|| code === 'AUTH.INCORRECT_CURRENT_PASSWORD'
|| code === 'AUTH.PASSWORD_UNCHANGED'
) {
return code;
}
const detailsCode = cleanText(err.details?.error_code);
@@ -24,6 +37,13 @@ export function pickCasdoorErrorCode(err: BusinessError): string {
return code;
}
/**
* 将 Casdoor / 改密错误转为当前语言用户可见文案。
* 核心逻辑:按 pickCasdoorErrorCode 查 i18n;未知码回退原始 message。
* @param err - 业务错误
* @param t - vue-i18n t 函数
* @returns 用户可见错误文案
*/
export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn): string {
const errorCode = pickCasdoorErrorCode(err);
const keyMap: Record<string, string> = {
@@ -39,6 +59,7 @@ export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn):
CASDOOR_SET_PASSWORD_FAILED: 'login.casdoorErrors.setPasswordFailed',
CASDOOR_USER_NOT_IN_IDP: 'login.casdoorErrors.userNotInIdp',
'AUTH.INCORRECT_CURRENT_PASSWORD': 'login.casdoorErrors.incorrectCurrentPassword',
'AUTH.PASSWORD_UNCHANGED': 'login.casdoorErrors.passwordUnchanged',
'VALIDATION.INVALID_PARAM': 'login.casdoorErrors.stateExpired',
};
const key = keyMap[errorCode];
@@ -46,6 +67,7 @@ export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn):
const raw = cleanText(err.message);
if (raw === 'Incorrect username or password') return t('login.casdoorErrors.invalidCredentials');
if (raw === 'Incorrect current password') return t('login.casdoorErrors.incorrectCurrentPassword');
if (raw === 'New password must differ from the current password') return t('login.casdoorErrors.passwordUnchanged');
if (raw === 'Invalid or expired Casdoor state') return t('login.casdoorErrors.stateExpired');
return raw || t('login.casdoorErrors.authFailed');
}
+37
View File
@@ -31,3 +31,40 @@ export function formatLocalDateTime(iso?: string | null): string {
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
/**
* Format an API timestamp as `YYYY-MM-DD HH:mm:ss`, preserving the source wall-clock time.
* Use for OA-sourced naive timestamps (e.g. contract archive date) where the stored value is the
* local time as shown on the source page and must NOT be shifted by the browser timezone.
* Backend may serialize microseconds (e.g. `...26.660127`); they are trimmed for reliable parsing.
* Empty values return `-`; invalid dates fall back to the original string for troubleshooting.
*
* @param iso - API timestamp string.
* @returns Wall-clock display text.
*/
export function formatNaiveDateTime(iso?: string | null): string {
if (!iso) return '-';
const normalized = iso.replace(/(\.\d{3})\d+/, '$1');
const d = new Date(normalized);
if (Number.isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
/**
* Format an API timestamp as `YYYY-MM-DD`, preserving the source wall-clock day.
* Use for OA-sourced naive timestamps (e.g. contract archive date) where only the date is
* meaningful and the trailing time part must not be shown. Parsing mirrors formatNaiveDateTime.
* Empty values return `-`; invalid dates fall back to the original string for troubleshooting.
*
* @param iso - API timestamp string.
* @returns Wall-clock date text (`YYYY-MM-DD`).
*/
export function formatNaiveDate(iso?: string | null): string {
if (!iso) return '-';
const normalized = iso.replace(/(\.\d{3})\d+/, '$1');
const d = new Date(normalized);
if (Number.isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
@@ -0,0 +1,73 @@
/**
* shared/utils/download.test.ts
* 用途:校验 Content-Disposition 解析与单次 blob 下载不会拼出怪名。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
parseContentDispositionFilename,
sanitizeDownloadFilename,
triggerBlobDownload,
} from './download';
describe('parseContentDispositionFilename', () => {
it('prefers RFC 5987 filename* over ASCII fallback', () => {
// 断言:Werkzeug/Flask 中文名会留下 ASCII 回退段,必须取 filename*。
const encoded = encodeURIComponent('企业文化.docx');
const disposition = `attachment; filename="download.docx"; filename*=UTF-8''${encoded}`;
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
});
it('does not concatenate unquoted ASCII fallback with filename*', () => {
// 断言:旧实现会得到 `docx; filename_=UTF-8''企业文化.docx`。
const encoded = encodeURIComponent('企业文化.docx');
const disposition = `inline; filename=docx; filename*=UTF-8''${encoded}`;
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
});
it('reads quoted filename when filename* is absent', () => {
expect(parseContentDispositionFilename('attachment; filename="report.pdf"')).toBe('report.pdf');
});
it('returns undefined for empty header', () => {
expect(parseContentDispositionFilename('')).toBeUndefined();
expect(parseContentDispositionFilename(null)).toBeUndefined();
});
});
describe('sanitizeDownloadFilename', () => {
it('keeps only the last path segment', () => {
expect(sanitizeDownloadFilename('dir/企业文化.docx')).toBe('企业文化.docx');
});
});
describe('triggerBlobDownload', () => {
afterEach(() => {
vi.unstubAllGlobals();
document.body.innerHTML = '';
});
it('clicks a single anchor with the original filename', () => {
// 断言:一次下载只产生一个 a[download],文件名与源文件一致。
const clicks: string[] = [];
const createObjectURL = vi.fn(() => 'blob:http://localhost/fake');
const revokeObjectURL = vi.fn();
vi.stubGlobal('URL', { createObjectURL, revokeObjectURL });
const originalCreateElement = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
const el = originalCreateElement(tagName);
if (tagName === 'a') {
vi.spyOn(el, 'click').mockImplementation(() => {
clicks.push(el.download);
});
}
return el;
});
triggerBlobDownload(new Blob(['hello']), '企业文化.docx');
expect(createObjectURL).toHaveBeenCalledTimes(1);
expect(clicks).toEqual(['企业文化.docx']);
expect(document.body.querySelectorAll('a')).toHaveLength(0);
});
});
+67
View File
@@ -0,0 +1,67 @@
/**
* shared/utils/download.ts
* 用途:浏览器受控下载的文件名解析与单次触发,避免 blob URL 被 window.open 再下一份。
* 依赖:无业务模块;仅使用 DOM URL / a[download]。
* 逻辑:requestBlob、知识库源文件等调用;Content-Disposition 优先 RFC 5987 filename*。
*/
/**
* 去掉路径与非法换行,得到可写入 a[download] 的纯文件名。
* 核心逻辑:只保留最后一段路径分量,避免把目录或响应头片段写进保存名。
* @param filename - 原始或解析得到的文件名
* @param fallback - 清洗后为空时的回退名
* @returns 可安全用作下载名的字符串
*/
export function sanitizeDownloadFilename(filename: string, fallback = 'download'): string {
const name = String(filename || '').replace(/\\/g, '/').split('/').pop()?.trim() || '';
const cleaned = name.replace(/[\r\n"]/g, '');
return cleaned || fallback;
}
/**
* 从 Content-Disposition 解析下载文件名,优先 RFC 5987 的 filename*。
* 核心逻辑:先取 filename*=UTF-8'',再取带引号或到分号为止的 filename=。
* 不能用贪婪的 filename="?([^"]+)"?,否则会把 `filename=docx; filename*=UTF-8''原名.docx` 整段当成文件名。
* @param disposition - 响应头原文
* @returns 解码后的文件名;无法解析时返回 undefined
*/
export function parseContentDispositionFilename(
disposition: string | null | undefined,
): string | undefined {
const value = String(disposition || '');
if (!value) return undefined;
const utf8Match = value.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
const quotedMatch = value.match(/filename\s*=\s*"([^"]+)"/i);
const unquotedMatch = value.match(/filename\s*=\s*([^;]+)/i);
const raw = (utf8Match?.[1] || quotedMatch?.[1] || unquotedMatch?.[1] || '').trim();
if (!raw) return undefined;
let decoded = raw;
try {
decoded = decodeURIComponent(raw);
} catch {
decoded = raw;
}
const name = sanitizeDownloadFilename(decoded, '');
return name || undefined;
}
/**
* 用 blob 触发一次浏览器下载,保存名使用给定文件名。
* 核心逻辑:只创建一条 a[download] 并 click;禁止 window.open blob URL,
* 因为 docx 等无法预览的类型会再下一份 UUID 名文件,且 noopener 使 open 返回 null 导致双下载。
* @param blob - 文件内容
* @param filename - 保存文件名,应与源文件名一致
*/
export function triggerBlobDownload(blob: Blob, filename: string): void {
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = sanitizeDownloadFilename(filename);
link.rel = 'noopener';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}
+34
View File
@@ -0,0 +1,34 @@
/**
* shared/utils/id.test.ts
* 用途:校验 createRandomUuid 在缺少 randomUUID 时仍可生成可用 ID。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createRandomUuid } from './id';
describe('createRandomUuid', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('uses crypto.randomUUID when available', () => {
// 断言:安全上下文走原生 API。
vi.stubGlobal('crypto', {
randomUUID: () => '11111111-2222-4333-8444-555555555555',
});
expect(createRandomUuid()).toBe('11111111-2222-4333-8444-555555555555');
});
it('falls back when randomUUID is missing (HTTP non-secure context)', () => {
// 断言:模拟内网 HTTP,无 randomUUID 也不抛错,且返回非空串。
vi.stubGlobal('crypto', {
getRandomValues: (bytes: Uint8Array) => {
for (let i = 0; i < bytes.length; i += 1) bytes[i] = i;
return bytes;
},
});
const value = createRandomUuid();
expect(value).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
);
});
});
+29
View File
@@ -0,0 +1,29 @@
/**
* shared/utils/id.ts
* 用途:生成客户端随机 ID(会话号、operation_id、幂等键等)。
* 依赖:Web Crypto(优先);无安全上下文时回退到 getRandomValues / Math.random。
* 逻辑:HTTP 内网(如 192.168.x)不是 secure context,`crypto.randomUUID` 不可用,
* 直接调用会在 Vue setup 阶段抛 TypeError 导致白屏;统一走本工具避免分叉。
*/
/**
* 生成 UUID 风格随机串;优先 `crypto.randomUUID`,HTTP 等非安全上下文自动降级。
* 核心逻辑:secure context 用原生 API;否则用 getRandomValues 拼 RFC4122 v4;再不行用时间戳+随机。
* @returns 形如 `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` 的字符串(降级路径不保证密码学强度)
*/
export function createRandomUuid(): string {
const webCrypto = globalThis.crypto;
if (webCrypto && typeof webCrypto.randomUUID === 'function') {
return webCrypto.randomUUID();
}
if (webCrypto && typeof webCrypto.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
webCrypto.getRandomValues(bytes);
// noUncheckedIndexedAccess 下 Uint8Array 下标为 number | undefined
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
return `fallback-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
}
+18
View File
@@ -0,0 +1,18 @@
/**
* shared/utils/redirect.ts
* 登录回跳目标解析:企微提醒卡片等深链场景下,登录页按 redirect 参数原样回跳。
* 依赖:无。被 app/router/guards.ts(守卫放行/跳转)与 features/auth(登录成功后回跳)共用。
*/
/**
* 校验并解析登录后回跳目标(企微提醒卡片等深链场景)。
* AI 触发时机:路由守卫拦截未登录访问时,以及密码/OAuth 登录成功后决定跳转目标时调用。
* 核心逻辑:仅接受站内相对路径(以 / 开头且不以 // 开头),拒绝外链与协议相对地址,防开放重定向。
* @param raw - 待校验的 redirect 参数(可能为 string | string[] | undefined)
* @returns 安全的站内路径;不合法时返回 null
*/
export function resolveSafeRedirect(raw: unknown): string | null {
const value = Array.isArray(raw) ? String(raw[0] ?? '') : String(raw ?? '');
if (!value.startsWith('/') || value.startsWith('//')) return null;
return value;
}