企业微信

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

+524 -5
View File
@@ -15,6 +15,7 @@ import { useI18n } from 'vue-i18n';
import { config } from '../config';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom';
import {
ArrowLeft,
// Save,
@@ -38,7 +39,8 @@ import {
Megaphone,
Link2,
Unlink2,
RefreshCw
RefreshCw,
CircleHelp
} from 'lucide-vue-next';
import * as XLSX from 'xlsx';
@@ -157,6 +159,61 @@ interface LoginAuditRow {
ip?: string | null;
user_agent?: string | null;
created_at?: string | null;
error_code?: string | null;
match_rules?: string | null;
match_operator?: string | null;
match_result?: string | null;
}
interface WecomNotifySettings {
enabled: boolean;
base_url: string;
events: string[];
}
interface WecomNotifyMetrics {
window_days: number;
total: number;
sent: number;
failed: number;
send_success_rate: number;
opened_24h: number;
opened_24h_rate: number;
by_event: Record<string, { sent: number; failed: number }>;
}
interface WecomSystemSettings {
enabled: boolean;
corp_id: string;
agent_id: string;
secret: string;
redirect_uri: string;
auto_create_user: boolean;
match_rules: string;
match_operator: 'AND' | 'OR';
first_login_bind_mode: 'match_rules' | 'input_verify';
first_login_input_fields: string;
employee_id_source: string;
mobile_normalize: boolean;
callback_token: string;
encoding_aes_key: string;
callback_url: string;
homepage_url: string;
trusted_domain: string;
/** HTTPS origin shown to WeCom (e.g. https://ai.company.com) */
public_base_url: string;
}
interface WecomIntegrationManifest {
public_base_url: string;
callback_url: string;
callback_token: string;
encoding_aes_key: string;
oauth_redirect_uri: string;
homepage_url: string;
trusted_domain: string;
authorize_api: string;
login_api: string;
}
// 获取路由实例,用于页面跳转
@@ -316,6 +373,34 @@ const wecomBoundOnly = ref(false);
const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
const wecomNotifySettings = ref<WecomNotifySettings>({
enabled: true,
base_url: '',
events: [],
});
const wecomNotifyEventsText = ref('');
const wecomNotifyMetrics = ref<WecomNotifyMetrics | null>(null);
const wecomSystemSettings = ref<WecomSystemSettings>({
enabled: true,
corp_id: '',
agent_id: '',
secret: '',
redirect_uri: '',
auto_create_user: true,
match_rules: 'employee_id,mobile',
match_operator: 'AND',
first_login_bind_mode: 'match_rules',
first_login_input_fields: 'employee_id,mobile,email',
employee_id_source: 'userid',
mobile_normalize: true,
callback_token: '',
encoding_aes_key: '',
callback_url: '',
homepage_url: '',
trusted_domain: '',
public_base_url: '',
});
const wecomIntegrationManifest = ref<WecomIntegrationManifest | null>(null);
// Batch Operation Refs
const selectedUserIds = ref<number[]>([]);
@@ -750,8 +835,210 @@ const loadWecomAudits = async () => {
}
};
const loadWecomSystemSettings = async () => {
try {
const res = await fetch('/api/admin/wecom/system-settings', { headers: getAuthHeaders() });
if (res.ok) {
wecomSystemSettings.value = await res.json();
}
} catch (e) {
console.error('Error loading WeCom system settings:', e);
}
};
const loadWecomIntegrationManifest = async () => {
try {
const res = await fetch('/api/admin/wecom/integration-manifest', { headers: getAuthHeaders() });
if (res.ok) {
wecomIntegrationManifest.value = await res.json();
}
} catch (e) {
console.error('Error loading WeCom integration manifest:', e);
}
};
const copyText = async (text: string) => {
if (!text) return;
try {
await navigator.clipboard.writeText(text);
alert(t('admin.wecom.msg.copySuccess'));
} catch (e) {
console.error(e);
alert(t('admin.wecom.msg.copyFailed'));
}
};
const getWecomAuditReasonText = (row: LoginAuditRow) => formatWecomAuditReason(row, t);
const getWecomAuditMetaText = (row: LoginAuditRow) => buildWecomAuditMeta(row, t).join(' | ');
function normalizeWecomPublicBase(input: string): string | null {
const raw = (input || '').trim();
if (!raw) return null;
let url = raw;
if (!/^https?:\/\//i.test(url)) url = `https://${url}`;
url = url.replace(/\/+$/, '');
try {
const u = new URL(url);
if (!u.hostname) return null;
return `${u.protocol}//${u.host}`;
} catch {
return null;
}
}
function ensureWecomIntegrationManifest() {
if (!wecomIntegrationManifest.value) {
wecomIntegrationManifest.value = {
public_base_url: '',
callback_url: '',
callback_token: '',
encoding_aes_key: '',
oauth_redirect_uri: '',
homepage_url: '',
trusted_domain: '',
authorize_api: '',
login_api: '',
};
}
}
function patchWecomIntegrationManifestFromSettings() {
ensureWecomIntegrationManifest();
const s = wecomSystemSettings.value;
const base = normalizeWecomPublicBase(s.public_base_url);
const prev = wecomIntegrationManifest.value!;
wecomIntegrationManifest.value = {
...prev,
callback_token: s.callback_token || '',
encoding_aes_key: s.encoding_aes_key || '',
};
if (!base) return;
wecomIntegrationManifest.value = {
...wecomIntegrationManifest.value!,
public_base_url: base,
callback_url: s.callback_url || `${base}/api/user/wecom/callback`,
oauth_redirect_uri: s.redirect_uri || `${base}/workspace`,
homepage_url: s.homepage_url || `${base}/workspace`,
trusted_domain: s.trusted_domain || new URL(base).hostname,
authorize_api: `${base}/api/user/wecom/authorize-url`,
login_api: `${base}/api/user/wecom/login`,
};
}
function generateWecomAddressesFromPublicBase() {
const base = normalizeWecomPublicBase(wecomSystemSettings.value.public_base_url);
if (!base) {
alert(t('admin.wecom.msg.publicBaseRequired'));
return;
}
const host = new URL(base).hostname;
wecomSystemSettings.value.callback_url = `${base}/api/user/wecom/callback`;
wecomSystemSettings.value.homepage_url = `${base}/workspace`;
wecomSystemSettings.value.trusted_domain = host;
wecomSystemSettings.value.redirect_uri = `${base}/workspace`;
patchWecomIntegrationManifestFromSettings();
}
function generateWecomCallbackToken() {
const bytes = new Uint8Array(24);
crypto.getRandomValues(bytes);
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
wecomSystemSettings.value.callback_token = hex;
patchWecomIntegrationManifestFromSettings();
}
function generateWecomEncodingAesKey() {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
let bin = '';
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
const b64 = btoa(bin);
const key43 = b64.replace(/=+$/, '');
wecomSystemSettings.value.encoding_aes_key = key43;
patchWecomIntegrationManifestFromSettings();
}
const saveWecomSystemSettings = async () => {
isSaving.value = true;
try {
const payload = {
...wecomSystemSettings.value,
match_operator: (wecomSystemSettings.value.match_operator || 'AND').toUpperCase(),
};
const res = await fetch('/api/admin/wecom/system-settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || t('admin.msg.failed'));
wecomSystemSettings.value = data.settings || wecomSystemSettings.value;
await loadWecomIntegrationManifest();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const loadWecomNotifySettings = async () => {
try {
const res = await fetch('/api/admin/wecom/notify-settings', { headers: getAuthHeaders() });
if (res.ok) {
wecomNotifySettings.value = await res.json();
wecomNotifyEventsText.value = (wecomNotifySettings.value.events || []).join(',');
}
} catch (e) {
console.error('Error loading WeCom notify settings:', e);
}
};
const saveWecomNotifySettings = async () => {
isSaving.value = true;
try {
wecomNotifySettings.value.events = wecomNotifyEventsText.value
.split(',')
.map((x) => x.trim())
.filter(Boolean);
const res = await fetch('/api/admin/wecom/notify-settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(wecomNotifySettings.value),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || t('admin.msg.failed'));
wecomNotifySettings.value = data.settings || wecomNotifySettings.value;
await loadWecomNotifyMetrics();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const loadWecomNotifyMetrics = async () => {
try {
const res = await fetch('/api/admin/wecom/notify-metrics', { headers: getAuthHeaders() });
if (res.ok) {
wecomNotifyMetrics.value = await res.json();
}
} catch (e) {
console.error('Error loading WeCom notify metrics:', e);
}
};
const refreshWecomData = async () => {
await Promise.all([loadWecomBindings(), loadWecomAudits()]);
await Promise.all([
loadWecomBindings(),
loadWecomAudits(),
loadWecomSystemSettings(),
loadWecomIntegrationManifest(),
loadWecomNotifySettings(),
loadWecomNotifyMetrics(),
]);
};
const bindWecomUser = async () => {
@@ -819,7 +1106,12 @@ const exportWecomAudits = () => {
Source: row.source || '',
Username: row.username || '',
Status: row.status || '',
Reason: row.reason || '',
Reason: getWecomAuditReasonText(row),
Meta: getWecomAuditMetaText(row),
ErrorCode: row.error_code || '',
MatchRules: row.match_rules || '',
MatchOperator: row.match_operator || '',
MatchResult: row.match_result || '',
IP: row.ip || '',
WecomUserId: row.wecom_userid || '',
UserAgent: row.user_agent || '',
@@ -2864,6 +3156,227 @@ const handlePermissionImport = async (event: Event) => {
</div>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.systemSettings') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<label class="inline-flex items-center gap-2 text-sm text-gray-700">
<input v-model="wecomSystemSettings.enabled" type="checkbox" class="w-4 h-4 rounded text-blue-600 border-gray-300" />
{{ t('admin.wecom.fields.enabled') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.enabled')" />
</label>
<label class="inline-flex items-center gap-2 text-sm text-gray-700">
<input v-model="wecomSystemSettings.auto_create_user" type="checkbox" class="w-4 h-4 rounded text-blue-600 border-gray-300" />
{{ t('admin.wecom.fields.autoCreateUser') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.autoCreateUser')" />
</label>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.corpId') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.corpId')" />
</label>
<input v-model="wecomSystemSettings.corp_id" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.agentId') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.agentId')" />
</label>
<input v-model="wecomSystemSettings.agent_id" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.secret') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.secret')" />
</label>
<input v-model="wecomSystemSettings.secret" type="password" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.redirectUri') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.redirectUri')" />
</label>
<input v-model="wecomSystemSettings.redirect_uri" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.publicBaseUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.publicBaseUrl')" />
</label>
<div class="flex flex-wrap gap-2">
<input
v-model="wecomSystemSettings.public_base_url"
:placeholder="t('admin.wecom.publicBasePlaceholder')"
class="input-field flex-1 min-w-[200px]"
/>
<button type="button" class="btn-secondary px-4 shrink-0" @click="generateWecomAddressesFromPublicBase">
{{ t('admin.wecom.generateAddresses') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.callbackToken') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.callbackToken')" />
</label>
<div class="flex gap-2">
<input v-model="wecomSystemSettings.callback_token" class="input-field flex-1 min-w-0" />
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomCallbackToken">
{{ t('admin.wecom.generateToken') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.encodingAesKey') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.encodingAesKey')" />
</label>
<div class="flex gap-2">
<input v-model="wecomSystemSettings.encoding_aes_key" class="input-field flex-1 min-w-0 font-mono text-xs" />
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomEncodingAesKey">
{{ t('admin.wecom.generateEncodingKey') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.callbackUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.callbackUrl')" />
</label>
<input v-model="wecomSystemSettings.callback_url" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.homepageUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.homepageUrl')" />
</label>
<input v-model="wecomSystemSettings.homepage_url" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.trustedDomain') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.trustedDomain')" />
</label>
<input v-model="wecomSystemSettings.trusted_domain" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.matchRules') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.matchRules')" />
</label>
<input v-model="wecomSystemSettings.match_rules" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.matchOperator') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.matchOperator')" />
</label>
<select v-model="wecomSystemSettings.match_operator" class="input-field">
<option value="AND">AND</option>
<option value="OR">OR</option>
</select>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.firstLoginBindMode') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.firstLoginBindMode')" />
</label>
<select v-model="wecomSystemSettings.first_login_bind_mode" class="input-field">
<option value="match_rules">{{ t('admin.wecom.bindModes.match_rules') }}</option>
<option value="input_verify">{{ t('admin.wecom.bindModes.input_verify') }}</option>
</select>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.firstLoginInputFields') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.firstLoginInputFields')" />
</label>
<input v-model="wecomSystemSettings.first_login_input_fields" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-gray-500">
{{ t('admin.wecom.fields.employeeIdSource') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.employeeIdSource')" />
</label>
<input v-model="wecomSystemSettings.employee_id_source" class="input-field" />
</div>
<label class="inline-flex items-center gap-2 text-sm text-gray-700 pt-7">
<input v-model="wecomSystemSettings.mobile_normalize" type="checkbox" class="w-4 h-4 rounded text-blue-600 border-gray-300" />
{{ t('admin.wecom.fields.mobileNormalize') }}
<CircleHelp class="w-3.5 h-3.5 text-gray-400" :title="t('admin.wecom.tips.mobileNormalize')" />
</label>
</div>
<div class="flex justify-end">
<button @click="saveWecomSystemSettings" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
{{ t('admin.save') }}
</button>
</div>
</div>
<div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.notifySettings') }}</h3>
<label class="inline-flex items-center gap-2 text-sm text-gray-700">
<input v-model="wecomNotifySettings.enabled" type="checkbox" class="w-4 h-4 rounded text-blue-600 border-gray-300" />
{{ t('admin.wecom.notifyEnabled') }}
</label>
<input v-model="wecomNotifySettings.base_url" :placeholder="t('admin.wecom.notifyBaseUrl')" class="input-field" />
<input v-model="wecomNotifyEventsText" :placeholder="t('admin.wecom.notifyEvents')" class="input-field" />
<div class="flex justify-end">
<button @click="saveWecomNotifySettings" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
{{ t('admin.save') }}
</button>
</div>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.notifyMetrics') }}</h3>
<div v-if="wecomNotifyMetrics" class="grid grid-cols-2 gap-3 text-sm">
<div class="rounded-lg bg-gray-50 px-3 py-2">
<div class="text-gray-500">{{ t('admin.wecom.metricTotal') }}</div>
<div class="text-lg font-semibold text-gray-900">{{ wecomNotifyMetrics.total }}</div>
</div>
<div class="rounded-lg bg-gray-50 px-3 py-2">
<div class="text-gray-500">{{ t('admin.wecom.metricSuccessRate') }}</div>
<div class="text-lg font-semibold text-emerald-700">{{ wecomNotifyMetrics.send_success_rate }}%</div>
</div>
<div class="rounded-lg bg-gray-50 px-3 py-2">
<div class="text-gray-500">{{ t('admin.wecom.metricOpenedRate') }}</div>
<div class="text-lg font-semibold text-blue-700">{{ wecomNotifyMetrics.opened_24h_rate }}%</div>
</div>
<div class="rounded-lg bg-gray-50 px-3 py-2">
<div class="text-gray-500">{{ t('admin.wecom.metricWindowDays') }}</div>
<div class="text-lg font-semibold text-gray-900">{{ wecomNotifyMetrics.window_days }}</div>
</div>
</div>
</div>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.integrationCopyTitle') }}</h3>
<p class="text-xs text-gray-500">{{ t('admin.wecom.integrationCopyDesc') }}</p>
<p class="text-xs text-amber-800 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">{{ t('admin.wecom.integrationCopySecretsNote') }}</p>
<div v-if="wecomIntegrationManifest" class="grid grid-cols-1 gap-3">
<div v-for="item in [
{ key: 'public_base_url', label: t('admin.wecom.copyFields.publicBaseUrl') },
{ key: 'callback_url', label: t('admin.wecom.copyFields.callbackUrl') },
{ key: 'callback_token', label: t('admin.wecom.copyFields.callbackToken') },
{ key: 'encoding_aes_key', label: t('admin.wecom.copyFields.encodingAesKey') },
{ key: 'oauth_redirect_uri', label: t('admin.wecom.copyFields.oauthRedirectUri') },
{ key: 'homepage_url', label: t('admin.wecom.copyFields.homepageUrl') },
{ key: 'trusted_domain', label: t('admin.wecom.copyFields.trustedDomain') },
{ key: 'authorize_api', label: t('admin.wecom.copyFields.authorizeApi') },
{ key: 'login_api', label: t('admin.wecom.copyFields.loginApi') },
]" :key="item.key">
<label class="mb-1.5 block text-xs text-gray-500">{{ item.label }}</label>
<div class="flex gap-2">
<input :value="(wecomIntegrationManifest as any)[item.key] || ''" readonly class="input-field flex-1 bg-gray-50 font-mono text-xs" />
<button class="btn-secondary px-3" @click="copyText(String((wecomIntegrationManifest as any)[item.key] || ''))">{{ t('admin.wecom.copy') }}</button>
</div>
</div>
</div>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.bindingList') }}</h3>
@@ -2959,7 +3472,14 @@ const handlePermissionImport = async (event: Event) => {
{{ t('admin.wecom.auditStatus.' + row.status) }}
</span>
</td>
<td class="px-4 py-3 text-xs text-gray-600 max-w-[360px] truncate" :title="row.reason || ''">{{ row.reason || '-' }}</td>
<td class="px-4 py-3 text-xs text-gray-600 max-w-[360px] align-top">
<div class="max-w-[360px] whitespace-normal break-words">
<div class="text-xs text-gray-700 leading-5">{{ getWecomAuditReasonText(row) }}</div>
<div v-if="getWecomAuditMetaText(row)" class="mt-1 text-[11px] text-gray-400 leading-5" :title="getWecomAuditMetaText(row)">
{{ getWecomAuditMetaText(row) }}
</div>
</div>
</td>
<td class="px-4 py-3 text-xs text-gray-600 font-mono">{{ row.ip || '-' }}</td>
</tr>
</tbody>
@@ -3708,4 +4228,3 @@ const handlePermissionImport = async (event: Event) => {
</div>
</div>
</template>
+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">