企业微信

This commit is contained in:
super committed 2026-04-20 09:08:58 +08:00
1 parent 46ac70f4c5
commit a9fc852abb
33 files changed
+4875 -106

No files matched your search

+233 -11
View File
@@ -9,6 +9,13 @@ import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '../config';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import {
buildWecomLoginDialogContent,
formatWecomFieldLabel,
normalizeWecomMatchRules,
type WecomLoginDialogContent,
type WecomMatchField,
} from '../utils/wecom';
import {
Settings,
LayoutGrid,
@@ -81,6 +88,16 @@ interface Announcement {
created_at: string;
}
interface WecomBindPromptState {
binding_token: string;
allowed_fields: WecomMatchField[];
wecom_name?: string;
field: WecomMatchField;
value: string;
submitting: boolean;
error: string;
}
// State
const isLoading = ref(true);
const currentUser = ref<{ id: number; username: string; role: string; default_agent_id?: number | null } | null>(null);
@@ -118,6 +135,14 @@ const registerForm = ref({ username: '', password: '', email: '', real_name: '',
const forgotPasswordForm = ref({ email: '' });
const pendingAgentId = ref<number | null>(null);
const isWecomLoggingIn = ref(false);
const wecomEntryHint = ref('');
const wecomLoginDialog = ref<WecomLoginDialogContent | null>(null);
const wecomBindPrompt = ref<WecomBindPromptState | null>(null);
const clearWecomCallbackQuery = () => {
const nextUrl = `${window.location.pathname}${window.location.hash || ''}`;
window.history.replaceState({}, '', nextUrl);
};
const handleForgotPassword = async () => {
if (!forgotPasswordForm.value.email) {
@@ -452,6 +477,85 @@ const handleWecomLogin = async () => {
}
};
const openWecomLoginDialog = (payload: Record<string, unknown>) => {
wecomLoginDialog.value = buildWecomLoginDialogContent(payload, t);
};
const openWecomBindPrompt = (payload: Record<string, unknown>) => {
const allowedFields = normalizeWecomMatchRules(payload.allowed_fields).fields;
const fallbackFields: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
const fields: WecomMatchField[] = allowedFields.length ? allowedFields : fallbackFields;
wecomBindPrompt.value = {
binding_token: String(payload.binding_token || ''),
allowed_fields: fields,
wecom_name: String(payload.wecom_name || ''),
field: fields[0] || 'employee_id',
value: '',
submitting: false,
error: '',
};
};
const formatWecomBindPromptError = (payload: Record<string, unknown>) => {
const errorCode = String(payload.error_code || '');
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') return t('login.wecomBindInputNotFound');
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') return t('login.wecomBindInputAmbiguous');
if (errorCode === 'WECOM_BIND_SESSION_EXPIRED') return t('login.wecomBindSessionExpired');
if (errorCode === 'WECOM_BIND_CONFLICT') return t('login.wecomBindConflict');
if (errorCode === 'WECOM_BIND_FIELD_NOT_ALLOWED') return t('login.wecomBindFieldNotAllowed');
if (errorCode === 'WECOM_BIND_INPUT_VALUE_REQUIRED') return t('login.wecomBindValueRequired');
if (String(payload.error || '').includes('Account is disabled')) return t('login.wecomAccountDisabled');
return String(payload.error || t('login.wecomLoginFailed'));
};
const submitWecomCompleteBind = async () => {
if (!wecomBindPrompt.value) return;
if (!wecomBindPrompt.value.value.trim()) {
wecomBindPrompt.value.error = t('login.wecomBindValueRequired');
return;
}
wecomBindPrompt.value.submitting = true;
wecomBindPrompt.value.error = '';
try {
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
const res = await fetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
binding_token: wecomBindPrompt.value.binding_token,
field: wecomBindPrompt.value.field,
value: wecomBindPrompt.value.value.trim(),
}),
});
const data = await res.json();
if (!res.ok) {
wecomBindPrompt.value.error = formatWecomBindPromptError(data);
if (String(data.error_code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
openWecomLoginDialog(data);
wecomBindPrompt.value = null;
}
return;
}
wecomLoginDialog.value = null;
persistLoginUser(data);
sessionStorage.removeItem('hxops_wecom_state');
wecomBindPrompt.value = null;
window.history.replaceState({}, '', '/workspace');
await fetchHome();
} catch (e) {
console.error(e);
if (wecomBindPrompt.value) {
wecomBindPrompt.value.error = t('login.wecomLoginFailed');
}
} finally {
if (wecomBindPrompt.value) {
wecomBindPrompt.value.submitting = false;
}
}
};
const tryWecomCallbackLogin = async () => {
if (!config.auth?.wecom?.enabled) return false;
@@ -462,7 +566,8 @@ const tryWecomCallbackLogin = async () => {
const expectedState = sessionStorage.getItem('hxops_wecom_state');
if (expectedState && state && state !== expectedState) {
alert(t('login.wecomInvalidState'));
openWecomLoginDialog({ error: 'Invalid or expired WeCom state' });
clearWecomCallbackQuery();
return true;
}
@@ -476,19 +581,18 @@ const tryWecomCallbackLogin = async () => {
});
const data = await res.json();
if (!res.ok) {
const rawError = String(data.error || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = t('login.wecomAccountDisabled');
sessionStorage.removeItem('hxops_wecom_state');
if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt(data);
clearWecomCallbackQuery();
return true;
}
alert(friendly);
openWecomLoginDialog(data);
clearWecomCallbackQuery();
return true;
}
wecomLoginDialog.value = null;
persistLoginUser(data);
sessionStorage.removeItem('hxops_wecom_state');
window.history.replaceState({}, '', '/workspace');
@@ -496,7 +600,9 @@ const tryWecomCallbackLogin = async () => {
return true;
} catch (e) {
console.error(e);
alert(t('login.wecomLoginFailed'));
sessionStorage.removeItem('hxops_wecom_state');
openWecomLoginDialog({ error: t('login.wecomLoginFailed') });
clearWecomCallbackQuery();
return true;
} finally {
isWecomLoggingIn.value = false;
@@ -572,6 +678,45 @@ const navigateWithQuickQuestion = (agentId: number, question: string) => {
window.open(url, '_blank');
};
const handleWecomDeeplinkContext = async () => {
const params = new URLSearchParams(window.location.search);
const traceId = params.get('wecom_trace');
const target = params.get('target');
const agentIdRaw = params.get('agent_id');
const preset = params.get('preset');
if (!traceId && !target) return;
wecomEntryHint.value = t('workspace.wecomEntryNotice');
if (traceId && isLoggedIn.value) {
try {
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
await fetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ trace_id: traceId }),
});
} catch (e) {
console.warn('Failed to mark WeCom deeplink opened', e);
}
}
if (target === 'chat' && agentIdRaw && isLoggedIn.value) {
const agentId = Number(agentIdRaw);
if (Number.isInteger(agentId) && agents.value.some((a) => a.id === agentId)) {
const url = router.resolve({
path: `/chat/${agentId}`,
query: preset ? { preset } : {},
}).href;
window.open(url, '_blank');
}
}
if (traceId || target) {
window.history.replaceState({}, '', '/workspace');
}
};
// Favorites
const toggleFavorite = async (agentId: number) => {
if (favoriteAgentIds.value.includes(agentId)) {
@@ -697,6 +842,7 @@ onMounted(async () => {
loadAuthUser();
if (currentUser.value && currentUser.value.role !== 'guest') {
await fetchHome();
await handleWecomDeeplinkContext();
} else {
await fetchPublicAgents();
isLoading.value = false;
@@ -922,6 +1068,9 @@ onMounted(async () => {
<!-- Logged In Layout -->
<div v-else class="space-y-8 animate-fade-in">
<div v-if="wecomEntryHint" class="rounded-xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{{ wecomEntryHint }}
</div>
<!-- Draggable Sections -->
<div
v-for="(section, index) in layoutSections"
@@ -1147,6 +1296,79 @@ onMounted(async () => {
</div>
</div>
</main>
<div v-if="wecomLoginDialog" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
<div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-lg p-8 animate-slide-up relative border border-slate-200 dark:border-slate-700">
<button @click="wecomLoginDialog = null" class="absolute top-4 right-4 text-slate-400 hover:text-slate-600">
<X class="w-5 h-5" />
</button>
<div class="mb-5">
<div class="w-12 h-12 bg-amber-100 text-amber-700 rounded-xl flex items-center justify-center mb-4">
<Lock class="w-6 h-6" />
</div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ wecomLoginDialog.title }}</h3>
<p class="text-sm text-slate-600 dark:text-slate-300 mt-3 leading-6">{{ wecomLoginDialog.summary }}</p>
</div>
<div v-if="wecomLoginDialog.details.length" class="rounded-2xl bg-slate-50 dark:bg-slate-800/80 border border-slate-200 dark:border-slate-700 px-4 py-4 space-y-3">
<p v-for="(detail, index) in wecomLoginDialog.details" :key="`${detail}-${index}`" class="text-sm text-slate-600 dark:text-slate-300 leading-6">
{{ detail }}
</p>
</div>
<p v-if="wecomLoginDialog.technical" class="mt-4 text-xs text-slate-400 break-all">
{{ $t('login.wecomTechnicalInfo', { detail: wecomLoginDialog.technical }) }}
</p>
<div class="flex justify-end gap-3 mt-8">
<button @click="wecomLoginDialog = null" class="btn-secondary">{{ $t('admin.close') }}</button>
<button @click="wecomLoginDialog = null; handleWecomLogin()" class="btn-primary" :disabled="isWecomLoggingIn">
{{ $t('login.wecomRetry') }}
</button>
</div>
</div>
</div>
<div v-if="wecomBindPrompt" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
<div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-lg p-8 animate-slide-up relative border border-slate-200 dark:border-slate-700">
<button @click="wecomBindPrompt = null" class="absolute top-4 right-4 text-slate-400 hover:text-slate-600">
<X class="w-5 h-5" />
</button>
<div class="mb-6">
<div class="w-12 h-12 bg-blue-100 text-blue-700 rounded-xl flex items-center justify-center mb-4">
<User class="w-6 h-6" />
</div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ $t('login.wecomBindPromptTitle') }}</h3>
<p class="text-sm text-slate-600 dark:text-slate-300 mt-3 leading-6">
{{ $t('login.wecomBindPromptDesc', { name: wecomBindPrompt.wecom_name || '-' }) }}
</p>
</div>
<div class="space-y-4">
<div>
<label class="mb-1.5 block text-xs font-semibold text-slate-600 uppercase">{{ $t('login.wecomBindField') }}</label>
<select v-model="wecomBindPrompt.field" class="input-field">
<option v-for="field in wecomBindPrompt.allowed_fields" :key="field" :value="field">
{{ formatWecomFieldLabel(field, t) }}
</option>
</select>
</div>
<div>
<label class="mb-1.5 block text-xs font-semibold text-slate-600 uppercase">{{ $t('login.wecomBindValue') }}</label>
<input
v-model="wecomBindPrompt.value"
class="input-field"
:placeholder="$t('login.wecomBindValuePlaceholder', { field: formatWecomFieldLabel(wecomBindPrompt.field, t) })"
@keyup.enter="submitWecomCompleteBind"
/>
</div>
<p class="text-xs text-slate-500 leading-5">{{ $t('login.wecomBindPromptHint') }}</p>
<p v-if="wecomBindPrompt.error" class="text-sm text-red-600 leading-6">{{ wecomBindPrompt.error }}</p>
</div>
<div class="flex justify-end gap-3 mt-8">
<button @click="wecomBindPrompt = null" class="btn-secondary">{{ $t('admin.close') }}</button>
<button @click="submitWecomCompleteBind" class="btn-primary" :disabled="wecomBindPrompt.submitting">
{{ wecomBindPrompt.submitting ? $t('login.wecomConnecting') : $t('login.wecomBindSubmit') }}
</button>
</div>
</div>
</div>
<!-- Register Modal -->
<div v-if="showRegisterModal" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">