refactor(frontend): 重构前端第二版

This commit is contained in:
sophie committed 2026-06-11 13:47:06 +08:00
1 parent 2631f78b00
commit 4b562cfa82
205 files changed
+15399 -12015

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
/**
* shared/utils/agentTabs.ts
* 多标签页 Agent 会话协调(避免重复打开)。
*/
const agentWindowName = (agentId: number): string => `hxops_agent_${agentId}`;
const isBlankWindow = (win: Window): boolean => {
try {
const href = win.location.href;
return href === 'about:blank' || href.endsWith('about:blank');
} catch {
return true;
}
};
/** Mark this browser tab as the chat window for an agent (used by window.open target name). */
export const registerOpenAgentId = (agentId: number | null): void => {
if (agentId && Number.isFinite(agentId) && agentId > 0) {
window.name = agentWindowName(agentId);
return;
}
if (window.name.startsWith('hxops_agent_')) {
window.name = '';
}
};
/** App startup hook (kept for compatibility). */
export const initAgentTabSync = (): void => {
// Named-window focus does not require background listeners.
};
/**
* Focus an existing same-agent tab without reload, or open a new one.
*
* Per HTML: window.open('', target) focuses an existing named window and
* ignores the URL, so the page is not refreshed.
*/
export const openAgentChatTab = (url: string, agentId: number): void => {
const target = agentWindowName(agentId);
const existing = window.open('', target);
if (!existing || existing.closed) {
const opened = window.open(url, target);
opened?.focus();
return;
}
existing.focus();
if (isBlankWindow(existing)) {
try {
existing.location.href = url;
} catch {
window.open(url, target);
}
}
};
+174
View File
@@ -0,0 +1,174 @@
/**
* shared/utils/auth.ts
* 认证 token / 用户读写、logout、跨标签同步。
*/
export interface AuthUser {
id?: number;
username?: string;
real_name?: string;
employee_id?: string;
role?: string;
token?: string;
access_token?: string;
refresh_token?: string;
expires_in?: number;
token_expires_at?: number;
}
export const getStoredAuthUser = (): AuthUser | null => {
const candidates = [
sessionStorage.getItem('hxops_user'),
localStorage.getItem('hxops_user'),
];
for (const stored of candidates) {
if (!stored) continue;
try {
const data = JSON.parse(stored);
return (data.user || data) as AuthUser;
} catch {
continue;
}
}
return null;
};
export const getAuthToken = (): string => {
const user = getStoredAuthUser();
const token = user?.access_token || user?.token;
return token ? String(token) : '';
};
export const getAuthHeaders = (): Record<string, string> => {
const token = getAuthToken();
if (!token) return {};
return { Authorization: `Bearer ${token}` };
};
export const saveAuthUser = (user: AuthUser, remember = false): void => {
const next = { ...user };
if (next.expires_in && !next.token_expires_at) {
// Pre-compute an absolute expiry timestamp for later proactive checks.
next.token_expires_at = Date.now() + Number(next.expires_in) * 1000;
}
const payload = remember
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
: { user: next };
if (remember) {
localStorage.setItem('hxops_user', JSON.stringify(payload));
sessionStorage.removeItem('hxops_user');
} else {
sessionStorage.setItem('hxops_user', JSON.stringify(payload));
localStorage.removeItem('hxops_user');
}
};
const AUTH_LOGOUT_KEY = 'hxops_auth_logout';
const AUTH_BC_NAME = 'hxops_auth';
let _authBroadcast: BroadcastChannel | null = null;
let _authSyncInitialized = false;
const clearAuthStorage = (): void => {
localStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_wecom_state');
sessionStorage.removeItem('hxops_casdoor_state');
};
const broadcastLogout = (): void => {
try {
localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now()));
localStorage.removeItem(AUTH_LOGOUT_KEY);
} catch {
// ignore quota / private mode errors
}
try {
if (!_authBroadcast) {
_authBroadcast = new BroadcastChannel(AUTH_BC_NAME);
}
_authBroadcast.postMessage({ type: 'logout', ts: Date.now() });
} catch {
// BroadcastChannel may be unavailable
}
};
const dispatchLogout = (detail: Record<string, unknown> = {}): void => {
window.dispatchEvent(new CustomEvent('hxops:logout', { detail }));
};
const handleRemoteLogout = (): void => {
if (!getStoredAuthUser()) return;
clearAuthStorage();
dispatchLogout({ remote: true });
};
/** Clear credentials and notify other tabs in the same browser. */
export const logoutAuth = (): void => {
clearAuthStorage();
broadcastLogout();
dispatchLogout({ source: 'local' });
};
export const clearAuthUser = (): void => {
logoutAuth();
};
/** Listen for logout in other tabs (storage + BroadcastChannel). */
export const initAuthSync = (): void => {
if (_authSyncInitialized) return;
_authSyncInitialized = true;
window.addEventListener('storage', (event: StorageEvent) => {
if (event.key === 'hxops_user' && event.newValue === null && event.oldValue != null) {
handleRemoteLogout();
return;
}
if (event.key === AUTH_LOGOUT_KEY && event.newValue != null) {
handleRemoteLogout();
}
});
try {
if (!_authBroadcast) {
_authBroadcast = new BroadcastChannel(AUTH_BC_NAME);
}
_authBroadcast.onmessage = (event: MessageEvent) => {
if (event.data?.type === 'logout') {
handleRemoteLogout();
}
};
} catch {
// ignore
}
};
let _refreshing: Promise<string | null> | null = null;
export const refreshAccessToken = async (): Promise<string | null> => {
// Single-flight guard: concurrent 401s share one refresh request.
const current = getStoredAuthUser();
const refreshToken = current?.refresh_token;
if (!refreshToken) return null;
if (_refreshing) return _refreshing;
_refreshing = (async () => {
try {
// Backend endpoint wraps Casdoor refresh flow.
const res = await fetch('/api/user/casdoor/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!res.ok) return null;
const data = await res.json();
if (!data?.access_token) return null;
// Preserve existing profile fields while replacing rotated token material.
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
return String(data.access_token);
} catch {
return null;
} finally {
_refreshing = null;
}
})();
return _refreshing;
};
+51
View File
@@ -0,0 +1,51 @@
/**
* shared/utils/casdoor.ts
* Casdoor OAuth 错误文案解析。
*/
import type { BusinessError } from '@/shared/api/client';
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
function cleanText(value: unknown): string {
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
}
export function pickCasdoorErrorCode(err: BusinessError): string {
const code = cleanText(err.code);
if (code.startsWith('CASDOOR_') || code === 'ACCOUNT_DISABLED' || code === 'AUTH.INCORRECT_CURRENT_PASSWORD') {
return code;
}
const detailsCode = cleanText(err.details?.error_code);
if (detailsCode) return detailsCode;
const raw = cleanText(err.message).toLowerCase();
if (raw.includes('invalid or expired casdoor state')) return 'CASDOOR_STATE_EXPIRED';
if (raw.includes('invalid_grant')) return 'CASDOOR_INVALID_CREDENTIALS';
if (raw.includes("doesn't exist") || raw.includes('does not exist')) return 'CASDOOR_USER_NOT_IN_IDP';
return code;
}
export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn): string {
const errorCode = pickCasdoorErrorCode(err);
const keyMap: Record<string, string> = {
CASDOOR_INVALID_CREDENTIALS: 'login.casdoorErrors.invalidCredentials',
CASDOOR_CODE_EXPIRED: 'login.casdoorErrors.codeExpired',
CASDOOR_STATE_EXPIRED: 'login.casdoorErrors.stateExpired',
CASDOOR_USER_NOT_FOUND: 'workspace.msg.casdoorNotMatchedContactAdmin',
ACCOUNT_DISABLED: 'login.accountDisabled',
CASDOOR_ACCESS_DENIED: 'login.casdoorErrors.accessDenied',
CASDOOR_CONFIG_ERROR: 'login.casdoorErrors.configError',
CASDOOR_AUTH_FAILED: 'login.casdoorErrors.authFailed',
CASDOOR_PASSWORD_POLICY: 'login.casdoorErrors.passwordPolicy',
CASDOOR_SET_PASSWORD_FAILED: 'login.casdoorErrors.setPasswordFailed',
CASDOOR_USER_NOT_IN_IDP: 'login.casdoorErrors.userNotInIdp',
'AUTH.INCORRECT_CURRENT_PASSWORD': 'login.casdoorErrors.incorrectCurrentPassword',
'VALIDATION.INVALID_PARAM': 'login.casdoorErrors.stateExpired',
};
const key = keyMap[errorCode];
if (key) return t(key);
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 === 'Invalid or expired Casdoor state') return t('login.casdoorErrors.stateExpired');
return raw || t('login.casdoorErrors.authFailed');
}
+40
View File
@@ -0,0 +1,40 @@
/**
* shared/utils/clipboard.ts
* 剪贴板写入兼容封装。
*/
/**
* Copy plain text to the clipboard with fallbacks for restricted browsers
* (e.g. WeCom embedded WebView, HTTP deployments).
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
const value = String(text ?? '');
if (!value.trim()) return false;
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(value);
return true;
} catch {
// Fall through to legacy copy.
}
}
try {
const textarea = document.createElement('textarea');
textarea.value = value;
textarea.setAttribute('readonly', 'true');
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '0';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, value.length);
const ok = document.execCommand('copy');
document.body.removeChild(textarea);
return ok;
} catch {
return false;
}
}
@@ -0,0 +1,24 @@
/**
* shared/utils/lastChatAgent.ts
* 最近访问的聊天 Agent ID 持久化。
*/
const STORAGE_KEY = 'hxops_last_chat_agent_id';
export function getLastChatAgentId(fallback = 16): number {
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
const id = Number(raw);
return Number.isFinite(id) && id > 0 ? id : fallback;
} catch {
return fallback;
}
}
export function setLastChatAgentId(agentId: number): void {
if (!Number.isFinite(agentId) || agentId <= 0) return;
try {
sessionStorage.setItem(STORAGE_KEY, String(agentId));
} catch {
// ignore storage failures
}
}
+335
View File
@@ -0,0 +1,335 @@
/**
* shared/utils/wecom.ts
* 企业微信登录/绑定相关工具与文案格式化。
*/
export type WecomMatchField = 'employee_id' | 'mobile' | 'email';
export interface WecomNormalizedMatchRules {
operator: 'AND' | 'OR';
fields: WecomMatchField[];
}
export interface WecomLoginErrorPayload {
error?: string | null;
error_code?: string | null;
reason?: string | null;
missing_field?: string | null;
candidate_count?: number | null;
match_rules?: unknown;
}
export interface WecomLoginDialogContent {
title: string;
summary: string;
details: string[];
technical?: string;
}
export interface WecomAuditRowLike {
status?: string | null;
reason?: string | null;
error_code?: string | null;
match_rules?: string | null;
match_operator?: string | null;
match_result?: string | null;
}
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
const KNOWN_MATCH_FIELDS: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
function cleanText(value: unknown): string {
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
}
function normalizeMatchField(value: unknown): WecomMatchField | null {
const normalized = cleanText(value).toLowerCase();
return KNOWN_MATCH_FIELDS.includes(normalized as WecomMatchField)
? (normalized as WecomMatchField)
: null;
}
function getFieldGuide(field: WecomMatchField | null, t: TranslateFn): string {
if (field === 'mobile') return t('login.wecomFieldGuides.mobile');
if (field === 'email') return t('login.wecomFieldGuides.email');
if (field === 'employee_id') return t('login.wecomFieldGuides.employee_id');
return t('login.wecomFieldGuides.default');
}
function extractMissingField(reason: string): WecomMatchField | null {
if (!reason.startsWith('missing_attr:')) return null;
return normalizeMatchField(reason.split(':', 2)[1]);
}
function formatRuleList(fields: WecomMatchField[], operator: 'AND' | 'OR', t: TranslateFn): string {
if (fields.length === 0) return t('login.wecomFieldLabels.match_rules');
const labels = fields.map((field) => formatWecomFieldLabel(field, t));
if (labels.length === 1) return labels[0] || t('login.wecomFieldLabels.match_rules');
const joiner = operator === 'OR' ? ` ${t('login.wecomRuleJoin.or')} ` : ` ${t('login.wecomRuleJoin.and')} `;
return labels.join(joiner);
}
function buildTechnicalInfo(errorCode: string, rawError: string): string | undefined {
const parts: string[] = [];
if (errorCode) parts.push(`code=${errorCode}`);
if (rawError) parts.push(rawError);
return parts.length ? parts.join(' | ') : undefined;
}
export function normalizeWecomMatchRules(
input: unknown,
fallbackOperator: unknown = 'AND',
): WecomNormalizedMatchRules {
let fieldsSource: unknown[] = [];
let operator: 'AND' | 'OR' = cleanText(fallbackOperator).toUpperCase() === 'OR' ? 'OR' : 'AND';
if (Array.isArray(input)) {
fieldsSource = input;
} else if (typeof input === 'string') {
fieldsSource = input.split(',');
} else if (input && typeof input === 'object') {
const maybeRules = input as Record<string, unknown>;
fieldsSource = Array.isArray(maybeRules.fields) ? maybeRules.fields : [];
operator = cleanText(maybeRules.operator).toUpperCase() === 'OR' ? 'OR' : operator;
}
const fields = fieldsSource
.map((value) => normalizeMatchField(value))
.filter((value): value is WecomMatchField => Boolean(value));
return { operator, fields };
}
export function formatWecomFieldLabel(field: unknown, t: TranslateFn): string {
const normalized = normalizeMatchField(field);
if (normalized === 'employee_id') return t('login.wecomFieldLabels.employee_id');
if (normalized === 'mobile') return t('login.wecomFieldLabels.mobile');
if (normalized === 'email') return t('login.wecomFieldLabels.email');
return t('login.wecomFieldLabels.match_rules');
}
export function formatWecomRuleText(
input: unknown,
t: TranslateFn,
fallbackOperator: unknown = 'AND',
): string {
const rules = normalizeWecomMatchRules(input, fallbackOperator);
return formatRuleList(rules.fields, rules.operator, t);
}
export function buildWecomLoginDialogContent(
payload: WecomLoginErrorPayload,
t: TranslateFn,
): WecomLoginDialogContent {
const rawError = cleanText(payload.error);
const errorCode = cleanText(payload.error_code);
const reason = cleanText(payload.reason);
const rulesText = formatWecomRuleText(payload.match_rules, t);
const technical = buildTechnicalInfo(errorCode, rawError);
if (errorCode === 'WECOM_MATCH_ATTR_MISSING') {
const missingField = normalizeMatchField(payload.missing_field) || extractMissingField(reason);
return {
title: t('login.wecomDialogTitles.matchAttrMissing'),
summary: t('login.wecomDialogSummaries.matchAttrMissing', {
field: formatWecomFieldLabel(missingField, t),
}),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
getFieldGuide(missingField, t),
t('login.wecomDialogDetails.bindFallback'),
],
technical,
};
}
if (errorCode === 'WECOM_MATCH_AMBIGUOUS') {
const candidateCount = Number(payload.candidate_count || 0);
return {
title: t('login.wecomDialogTitles.matchAmbiguous'),
summary: candidateCount > 1
? t('login.wecomDialogSummaries.matchAmbiguousWithCount', { count: candidateCount })
: t('login.wecomDialogSummaries.matchAmbiguous'),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
t('login.wecomDialogDetails.ambiguousAction'),
],
technical,
};
}
if (errorCode === 'WECOM_BIND_REQUIRED') {
return {
title: t('login.wecomDialogTitles.bindRequired'),
summary: t('login.wecomDialogSummaries.bindRequired'),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
t('login.wecomDialogDetails.bindRequiredAction'),
],
technical,
};
}
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
return {
title: t('login.wecomDialogTitles.bindInputRequired'),
summary: t('login.wecomDialogSummaries.bindInputRequired'),
details: [
t('login.wecomDialogDetails.bindInputRequiredAction'),
],
technical,
};
}
if (errorCode === 'WECOM_BIND_CONFLICT') {
return {
title: t('login.wecomDialogTitles.bindConflict'),
summary: t('login.wecomDialogSummaries.bindConflict'),
details: [
rawError || t('login.wecomDialogDetails.bindConflictAction'),
t('login.wecomDialogDetails.bindConflictAction'),
],
technical,
};
}
if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') {
return {
title: t('login.wecomDialogTitles.notInScope'),
summary: t('login.wecomDialogSummaries.notInScope'),
details: [
rawError || t('login.wecomDialogDetails.notInScopeAction'),
],
technical,
};
}
if (rawError.includes('Invalid or expired WeCom state')) {
return {
title: t('login.wecomDialogTitles.stateExpired'),
summary: t('login.wecomStateExpired'),
details: [t('login.wecomDialogDetails.retryLogin')],
technical,
};
}
if (rawError.includes('Account is disabled')) {
return {
title: t('login.wecomDialogTitles.accountDisabled'),
summary: t('login.wecomAccountDisabled'),
details: [t('login.wecomDialogDetails.contactAdmin')],
technical,
};
}
if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
return {
title: t('login.wecomDialogTitles.bindRequired'),
summary: t('login.wecomDialogSummaries.bindRequired'),
details: [
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
t('login.wecomDialogDetails.bindRequiredAction'),
],
technical,
};
}
return {
title: t('login.wecomDialogTitles.loginFailed'),
summary: rawError || t('login.wecomLoginFailed'),
details: [t('login.wecomDialogDetails.retryLogin')],
technical,
};
}
function formatWecomMatchResult(result: string, t: TranslateFn): string {
if (result === 'already_bound') return t('admin.wecom.auditResults.already_bound');
if (result === 'matched_and_bound') return t('admin.wecom.auditResults.matched_and_bound');
if (result === 'auto_created') return t('admin.wecom.auditResults.auto_created');
if (result === 'input_verified_and_bound') return t('admin.wecom.auditResults.input_verified_and_bound');
return result || '-';
}
export function formatWecomAuditReason(row: WecomAuditRowLike, t: TranslateFn): string {
const reason = cleanText(row.reason);
const errorCode = cleanText(row.error_code);
if (cleanText(row.status) === 'success') {
const result = cleanText(row.match_result);
return result ? formatWecomMatchResult(result, t) : t('admin.wecom.auditMessages.loginSuccess');
}
if (errorCode === 'WECOM_MATCH_ATTR_MISSING') {
const field = extractMissingField(reason);
return t('admin.wecom.auditMessages.matchAttrMissing', {
field: formatWecomFieldLabel(field, t),
});
}
if (errorCode === 'WECOM_MATCH_AMBIGUOUS') {
return t('admin.wecom.auditMessages.matchAmbiguous');
}
if (errorCode === 'WECOM_BIND_REQUIRED') {
return t('admin.wecom.auditMessages.bindRequired');
}
if (errorCode === 'WECOM_BIND_CONFLICT') {
return t('admin.wecom.auditMessages.bindConflict');
}
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
return t('admin.wecom.auditMessages.bindInputRequired');
}
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') {
return t('admin.wecom.auditMessages.bindInputNotFound');
}
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') {
return t('admin.wecom.auditMessages.bindInputAmbiguous');
}
if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') {
return t('admin.wecom.auditMessages.notInScope');
}
if (reason === 'invalid_state') return t('admin.wecom.auditMessages.invalidState');
if (reason === 'missing_code') return t('admin.wecom.auditMessages.missingCode');
if (reason === 'account_disabled') return t('admin.wecom.auditMessages.accountDisabled');
if (reason.startsWith('auth_failed:')) {
return t('admin.wecom.auditMessages.authFailed', {
detail: reason.split(':', 2)[1] || '-',
});
}
if (reason.startsWith('user_fetch_failed:')) {
return t('admin.wecom.auditMessages.userFetchFailed', {
detail: reason.split(':', 2)[1] || '-',
});
}
if (reason.startsWith('not_in_agent_scope:')) return t('admin.wecom.auditMessages.notInScope');
if (reason.startsWith('exception:')) {
return t('admin.wecom.auditMessages.exception', {
detail: reason.split(':', 2)[1] || '-',
});
}
return reason || '-';
}
export function buildWecomAuditMeta(row: WecomAuditRowLike, t: TranslateFn): string[] {
const items: string[] = [];
const rulesText = formatWecomRuleText(row.match_rules, t, row.match_operator);
if (cleanText(row.match_rules)) {
items.push(t('admin.wecom.auditMeta.rules', { rules: rulesText }));
}
if (cleanText(row.match_result)) {
items.push(t('admin.wecom.auditMeta.result', {
result: formatWecomMatchResult(cleanText(row.match_result), t),
}));
}
if (cleanText(row.error_code)) {
items.push(t('admin.wecom.auditMeta.errorCode', { code: cleanText(row.error_code) }));
}
return items;
}