diff --git a/backend/app/api/user.py b/backend/app/api/user.py index c29de4ab..52f2a0b4 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -1,4 +1,4 @@ -from flask import Blueprint, request, jsonify, current_app +from flask import Blueprint, request, jsonify, current_app from app import db from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message diff --git a/frontend/dist/index.html b/frontend/dist/index.html index bb754957..83f5014b 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -10,8 +10,8 @@ AI工作台 - - + +
diff --git a/frontend/src/composables/useChat.ts b/frontend/src/composables/useChat.ts index 72e182b9..a20dad44 100644 --- a/frontend/src/composables/useChat.ts +++ b/frontend/src/composables/useChat.ts @@ -22,9 +22,14 @@ interface ChatMessage { // 对话消息结构:用户/助手文本 + 可选的来源与归因信息 role: 'user' | 'assistant'; content: string; + type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result'; retriever_resources?: RetrieverResource[]; attribution_parts?: string[]; chat_log_id?: number; + payload?: any; + local_id?: string; + local_only?: boolean; + rated?: boolean; } // 统一资源格式为数组,兼容 list 或 { data: list } 两种结构 diff --git a/frontend/src/utils/auth.ts b/frontend/src/utils/auth.ts index 60aaba5f..f761c384 100644 --- a/frontend/src/utils/auth.ts +++ b/frontend/src/utils/auth.ts @@ -1,6 +1,8 @@ export interface AuthUser { id?: number; username?: string; + real_name?: string; + employee_id?: string; role?: string; token?: string; access_token?: string; diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 052606dd..68d7a77a 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -13,7 +13,7 @@ import { ref, onMounted, onBeforeUnmount, computed } from 'vue'; import { useI18n } from 'vue-i18n'; import { useChat } from '../composables/useChat'; -import { Send, Bot, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, Crown, ChevronDown, Sparkles, User, Database, Mic, LogOut, MessageSquareText } from 'lucide-vue-next'; +import { Send, Bot, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, Crown, ChevronDown, Sparkles, User, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink } from 'lucide-vue-next'; import { marked } from 'marked'; import { useRoute, useRouter } from 'vue-router'; import { config } from '../config'; @@ -28,6 +28,21 @@ const currentUser = ref(getStoredAuthUser()); const showUserDropdown = ref(false); const userMenuRef = ref(null); +const currentUserDisplayName = computed(() => { + const realName = currentUser.value?.real_name?.trim(); + if (realName) return realName; + const username = currentUser.value?.username?.trim(); + if (username) return username; + return '当前用户'; +}); + +const currentUserEmployeeId = computed(() => { + const employeeId = currentUser.value?.employee_id?.trim(); + if (employeeId) return employeeId; + const username = currentUser.value?.username?.trim(); + return username || '-'; +}); + const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => { if (!showUserDropdown.value) return; const target = event.target as Node | null; @@ -350,6 +365,7 @@ const shouldExpandSourceDetails = (msg: any): boolean => { const shouldRenderMessage = (msg: any): boolean => { if (msg?.role === 'user') return true; + if (msg?.type === 'leave-form' || msg?.type === 'leave-confirmation' || msg?.type === 'leave-result') return true; const content = (msg?.content || '').trim(); if (content) return true; if (getMessageLinks(msg).length > 0) return true; @@ -397,6 +413,253 @@ const input = ref(''); const currentAgent = ref(null); const showGeneralFeedbackDialog = ref(false); const activeFeedbackMessageIndex = ref(null); +const browserPanelOpen = ref(false); +const browserDraftUrl = ref(''); +const browserCurrentUrl = ref(''); +const browserFrameKey = ref(0); +const browserPanelWidth = ref(420); +const isBrowserResizing = ref(false); +const viewportWidth = ref(typeof window === 'undefined' ? 1440 : window.innerWidth); + +const MIN_BROWSER_PANEL_WIDTH = 320; +const MAX_BROWSER_PANEL_WIDTH = 960; + +const LEAVE_TYPES = [ + { label: '事假(小时)', value: '005' }, + { label: '病假(小时)', value: '006' }, + { label: '丧假(天)', value: '007' }, + { label: '年假(天)', value: '010' }, + { label: '因公出差(小时)', value: '021' }, + { label: '调休假(小时)', value: '025' }, + { label: '产假(天)', value: '401' }, + { label: '陪产假(天)', value: '402' }, + { label: '婚假(天)', value: '403' }, + { label: '住院病假(小时)', value: '405' }, + { label: '工伤假(天)', value: '406' }, + { label: '返乡假(小时)', value: 'ZZ01' }, + { label: '事假(经理专用小时)', value: 'ZZ04' }, + { label: '病假(经理专用小时)', value: 'ZZ05' }, + { label: '丧假(经理专用天)', value: 'ZZ07' }, + { label: '产假(经理专用天)', value: 'ZZ08' }, + { label: '陪产假(经理专用天)', value: 'ZZ09' }, + { label: '婚假(经理专用天)', value: 'ZZ10' }, + { label: '其他假(小时)', value: '035' }, + { label: '育儿假(小时)', value: '408' } +]; + +const getLeaveTypeLabel = (val: string) => { + const t = LEAVE_TYPES.find(x => x.value === val); + return t ? t.label : val; +}; + +const LEAVE_RESULT_QUERY_URL = 'http://192.168.100.221:8888/'; + +interface LeaveRequestFormData { + applicantName: string; + employeeId: string; + applyTime: string; + leaveType: string; + startTime: string; + endTime: string; + durationHours: number; + isOutOfOffice: boolean; + isWorkInjury: boolean; +} + +interface LeaveFormPayload { + formId: string; + form: LeaveRequestFormData; + submitting: boolean; + confirmationGenerated: boolean; +} + +interface LeaveConfirmationPayload { + formId: string; + form: LeaveRequestFormData; + submitting: boolean; + confirmed?: boolean; +} + +interface LeaveResultPayload { + formId: string; + success: boolean; + referenceNo: string; + submittedAt: string; +} + +let leaveFlowCounter = 0; + +const formatDateTime = (date: Date) => { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + return `${year}-${month}-${day}T${hours}:${minutes}`; +}; + +const parseDateTime = (value: string) => { + const normalized = (value || '').trim().replace('T', ' '); + const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/); + if (!match) return null; + const [, year, month, day, hour, minute] = match; + const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute)); + return Number.isNaN(date.getTime()) ? null : date; +}; + +const calculateDurationHours = (startTime: string, endTime: string) => { + const start = parseDateTime(startTime); + const end = parseDateTime(endTime); + if (!start || !end || end.getTime() <= start.getTime()) return 0; + return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2)); +}; + +const formatDurationLabel = (hours: number) => { + if (!hours) return '0 小时'; + if (hours >= 8 && Number.isInteger((hours / 8) * 10) && (hours / 8) >= 1) { + const days = Number((hours / 8).toFixed(2)); + return `${days} 天 / ${hours} 小时`; + } + return `${hours} 小时`; +}; + +const createLeaveFormData = (): LeaveRequestFormData => { + const now = new Date(); + const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000); + const startTime = formatDateTime(now); + const endTime = formatDateTime(oneHourLater); + return { + applicantName: currentUserDisplayName.value, + employeeId: currentUserEmployeeId.value, + applyTime: formatDateTime(now), + leaveType: '', + startTime, + endTime, + durationHours: calculateDurationHours(startTime, endTime), + isOutOfOffice: false, + isWorkInjury: false, + }; +}; + +const newLocalMessageId = (prefix: string) => { + leaveFlowCounter += 1; + return `${prefix}-${Date.now()}-${leaveFlowCounter}`; +}; + +const syncLeaveDuration = (form: LeaveRequestFormData) => { + form.durationHours = calculateDurationHours(form.startTime, form.endTime); +}; + +const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, ''); + +const isLeaveIntent = (content: string) => { + const normalized = getLeaveIntentNormalized(content); + return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程|请假流程)/.test(normalized); +}; + +const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => ( + msg?.type === 'leave-form' && msg?.payload ? msg.payload as LeaveFormPayload : null +); + +const getLeaveConfirmationPayload = (msg: any): LeaveConfirmationPayload | null => ( + msg?.type === 'leave-confirmation' && msg?.payload ? msg.payload as LeaveConfirmationPayload : null +); + +const getLeaveResultPayload = (msg: any): LeaveResultPayload | null => ( + msg?.type === 'leave-result' && msg?.payload ? msg.payload as LeaveResultPayload : null +); + +const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId); + +const browserPanelStyle = computed(() => { + if (viewportWidth.value < 1024) return undefined; + return { width: `${browserPanelWidth.value}px` }; +}); + +const normalizeBrowserInput = (value: string) => { + const raw = (value || '').trim(); + if (!raw) return ''; + if (/^https?:\/\//i.test(raw)) return raw; + if (/^localhost(?::\d+)?(\/.*)?$/i.test(raw)) return `http://${raw}`; + if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?(\/.*)?$/.test(raw)) return `http://${raw}`; + if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$/.test(raw)) return `https://${raw}`; + return ''; +}; + +const toggleBrowserPanel = () => { + browserPanelOpen.value = !browserPanelOpen.value; +}; + +const loadBrowserPage = () => { + const normalized = normalizeBrowserInput(browserDraftUrl.value); + if (!normalized) { + showMessageDialog('warning', '请输入有效的网址,例如 `https://example.com` 或 `localhost:8891`。'); + return; + } + browserCurrentUrl.value = normalized; + browserDraftUrl.value = normalized; + browserFrameKey.value += 1; + browserPanelOpen.value = true; +}; + +const refreshBrowserPage = () => { + if (!browserCurrentUrl.value) { + loadBrowserPage(); + return; + } + browserFrameKey.value += 1; +}; + +const openBrowserInNewTab = () => { + const normalized = browserCurrentUrl.value || normalizeBrowserInput(browserDraftUrl.value); + if (!normalized) { + showMessageDialog('warning', '请先输入可打开的网址。'); + return; + } + window.open(normalized, '_blank', 'noopener,noreferrer'); +}; + +const handleBrowserUrlEnter = (event: KeyboardEvent) => { + if (event.key !== 'Enter') return; + event.preventDefault(); + loadBrowserPage(); +}; + +const clampBrowserPanelWidth = (width: number) => { + const maxAllowed = Math.min(MAX_BROWSER_PANEL_WIDTH, Math.max(MIN_BROWSER_PANEL_WIDTH, Math.floor(window.innerWidth * 0.7))); + return Math.min(Math.max(width, MIN_BROWSER_PANEL_WIDTH), maxAllowed); +}; + +const handleBrowserResizeMove = (event: MouseEvent) => { + if (!isBrowserResizing.value) return; + browserPanelWidth.value = clampBrowserPanelWidth(window.innerWidth - event.clientX); +}; + +const stopBrowserResize = () => { + if (!isBrowserResizing.value) return; + isBrowserResizing.value = false; + document.body.style.cursor = ''; + document.body.style.userSelect = ''; + window.removeEventListener('mousemove', handleBrowserResizeMove); + window.removeEventListener('mouseup', stopBrowserResize); +}; + +const startBrowserResize = (event: MouseEvent) => { + if (viewportWidth.value < 1024) return; + event.preventDefault(); + isBrowserResizing.value = true; + document.body.style.cursor = 'col-resize'; + document.body.style.userSelect = 'none'; + window.addEventListener('mousemove', handleBrowserResizeMove); + window.addEventListener('mouseup', stopBrowserResize); +}; + +const syncViewportWidth = () => { + viewportWidth.value = window.innerWidth; + if (viewportWidth.value >= 1024) { + browserPanelWidth.value = clampBrowserPanelWidth(browserPanelWidth.value); + } +}; const handleOpenFeedback = (index: number) => { activeFeedbackMessageIndex.value = index; @@ -445,6 +708,26 @@ const handleSend = async (textOrEvent?: string | Event) => { // Clear input if sending from input box (not resending/regenerating) if (typeof textOrEvent !== 'string') input.value = ''; + + if (isLeaveIntent(content)) { + const formId = newLocalMessageId('leave-form'); + const payload: LeaveFormPayload = { + formId, + form: createLeaveFormData(), + submitting: false, + confirmationGenerated: false, + }; + messages.value.push({ role: 'user', content, type: 'text' }); + messages.value.push({ + role: 'assistant', + type: 'leave-form', + content: '已为你生成请假申请表,请直接在下方填写并提交。', + payload, + local_id: formId, + local_only: true, + }); + return; + } await sendMessage(content, agentId); @@ -458,6 +741,101 @@ const handleSend = async (textOrEvent?: string | Event) => { } }; +const validateLeaveForm = (form: LeaveRequestFormData) => { + if (!form.applicantName.trim()) return '申请人不能为空。'; + if (!form.employeeId.trim()) return '工号不能为空。'; + if (!form.leaveType.trim()) return '请选择假别。'; + if (!parseDateTime(form.startTime)) return '开始时间格式不正确。'; + if (!parseDateTime(form.endTime)) return '结束时间格式不正确。'; + if (calculateDurationHours(form.startTime, form.endTime) <= 0) return '结束时间必须晚于开始时间。'; + return ''; +}; + +const submitLeaveForm = (msg: any) => { + const payload = getLeaveFormPayload(msg); + if (!payload) return; + syncLeaveDuration(payload.form); + const error = validateLeaveForm(payload.form); + if (error) { + showMessageDialog('warning', error); + return; + } + + const existingConfirmIndex = messages.value.findIndex((item: any) => item?.type === 'leave-confirmation' && item?.payload?.formId === payload.formId); + if (existingConfirmIndex >= 0) { + messages.value.splice(existingConfirmIndex, 1); + } + + payload.confirmationGenerated = true; + const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData; + messages.value.push({ + role: 'assistant', + type: 'leave-confirmation', + content: '请确认以下请假信息,确认无误后再提交到 OA。', + payload: { + formId: payload.formId, + form: summary, + submitting: false, + }, + local_id: newLocalMessageId('leave-confirm'), + local_only: true, + }); +}; + +const editLeaveConfirmation = (msg: any, index: number) => { + const payload = getLeaveConfirmationPayload(msg); + if (!payload) return; + const sourceIndex = findMessageIndexByLocalId(payload.formId); + if (sourceIndex >= 0) { + const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]); + if (sourcePayload) { + sourcePayload.confirmationGenerated = false; + } + } + messages.value.splice(index, 1); +}; + +const confirmLeaveSubmission = async (msg: any) => { + const payload = getLeaveConfirmationPayload(msg); + if (!payload || payload.submitting) return; + payload.submitting = true; + + const sourceIndex = findMessageIndexByLocalId(payload.formId); + if (sourceIndex >= 0) { + const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]); + if (sourcePayload) { + sourcePayload.submitting = true; + sourcePayload.confirmationGenerated = true; + } + } + + await new Promise((resolve) => window.setTimeout(resolve, 900)); + + const referenceNo = `OA-${Date.now().toString().slice(-8)}`; + messages.value.push({ + role: 'assistant', + type: 'leave-result', + content: `请假单已生成,具体单据请到 ${LEAVE_RESULT_QUERY_URL} 查询。\n\n当前为前端演示提交流程,真实 OA 对接开发中。`, + payload: { + formId: payload.formId, + success: true, + referenceNo, + submittedAt: formatDateTime(new Date()), + }, + local_id: newLocalMessageId('leave-result'), + local_only: true, + }); + + payload.submitting = false; + payload.confirmed = true; + if (sourceIndex >= 0) { + const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]); + if (sourcePayload) { + sourcePayload.submitting = false; + } + } +}; + const copyToClipboard = async (text: string, index: number) => { try { await navigator.clipboard.writeText(text); @@ -569,6 +947,7 @@ const loadAgent = async () => { onMounted(async () => { document.addEventListener('mousedown', handleDocumentPointerDown); document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true }); + window.addEventListener('resize', syncViewportWidth); await loadAgent(); await loadHistory(); @@ -584,6 +963,8 @@ onMounted(async () => { onBeforeUnmount(() => { document.removeEventListener('mousedown', handleDocumentPointerDown); document.removeEventListener('touchstart', handleDocumentPointerDown); + window.removeEventListener('resize', syncViewportWidth); + stopBrowserResize(); }); /** @@ -754,6 +1135,8 @@ const showChatRating = ref(false); diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index 6fd59356..360abc1b 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -445,29 +445,6 @@ const handleLogin = async () => { } }; -const handleCasdoorLogin = async () => { - if (!config.auth?.casdoor?.enabled) return; - try { - // Ask backend to build a server-side-tracked authorize URL (includes state). - const api = config.auth.casdoor.authorizeApi || '/api/user/casdoor/authorize-url'; - const callbackPath = config.auth.casdoor.callbackPath || '/casdoor-callback'; - const redirectUri = `${window.location.origin}${callbackPath}`; - const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`); - const data = await res.json(); - if (!res.ok || !data.url) { - showMessageDialog('error', data.error || t('login.requestFailed')); - return; - } - if (data.state) { - sessionStorage.setItem('hxops_casdoor_state', data.state); - } - window.location.href = data.url; - } catch (e) { - console.error(e); - showMessageDialog('error', t('login.requestFailed')); - } -}; - const tryCasdoorCallbackLogin = async () => { if (!config.auth?.casdoor?.enabled) return false; const casdoorPath = config.auth.casdoor.callbackPath || '/casdoor-callback'; diff --git a/tmp_qjlx_seg.txt b/tmp_qjlx_seg.txt new file mode 100644 index 00000000..1cbb8214 --- /dev/null +++ b/tmp_qjlx_seg.txt @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ + | + +
+ + + + +
+ + + + + + + + diff --git a/tmp_qjlx_utf8.txt b/tmp_qjlx_utf8.txt new file mode 100644 index 00000000..233bf6ae --- /dev/null +++ b/tmp_qjlx_utf8.txt @@ -0,0 +1,182 @@ +urnvalue = Array(e.parentelement.parentelement.cells(0).innerText,e.parentelement.parentelement.cells(1).innerText,e.parentelement.parentelement.cells(2).innerText) + // window.parent.returnvalue = e.parentelement.parentelement.cells(0).innerText + window.parent.Close + End If + +End Sub +Sub BrowseTable_onmouseover() + Set e = window.event.srcElement + If e.TagName = "TD" Then + e.parentelement.className = "Selected" + ElseIf e.TagName = "A" Then + e.parentelement.parentelement.className = "Selected" + End If +End Sub +Sub BrowseTable_onmouseout() + Set e = window.event.srcElement + If e.TagName = "TD" Or e.TagName = "A" Then + If e.TagName = "TD" Then + Set p = e.parentelement + Else + Set p = e.parentelement.parentelement + End If + If p.RowIndex Mod 2 Then + p.className = "DataLight" + Else + p.className = "DataDark" + End If + End If +End Sub + + + + --> + +