diff --git a/.env.development b/.env.development index 368e979..eff519f 100644 --- a/.env.development +++ b/.env.development @@ -10,12 +10,13 @@ VITE_APP_BASE_API='/dev-api' # 本机环境 VITE_LOCALHOST=false # 本地开发环境 -VITE_BASE_API='http://192.168.0.212:8082' +VITE_BASE_API='http://192.168.0.212:8083' #VITE_BASE_API='http://192.168.0.212:8082' -VITE_WS_URL='ws://192.168.0.212:8082/cs/chat' +VITE_WS_URL='192.168.0.212:8083/cs/chat' # 默认头像 -VITE_DEFAULT_USER_IMAGE='https://ts3.tc.mm.bing.net/th?id=ORMS.48a27ca8353fa47bf0dc8df38854d0e1&pid=Wdp&w=312&h=172&qlt=90&c=1&rs=1&dpr=1&p=0' +#VITE_DEFAULT_USER_IMAGE='https://ts3.tc.mm.bing.net/th?id=ORMS.48a27ca8353fa47bf0dc8df38854d0e1&pid=Wdp&w=312&h=172&qlt=90&c=1&rs=1&dpr=1&p=0' +VITE_DEFAULT_USER_IMAGE='https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' # 应用访问路径 例如使用前缀 /admin/ VITE_APP_CONTEXT_PATH='/' diff --git a/src/api/system/customer/index.ts b/src/api/system/customer/index.ts index 8f830f6..61e2171 100644 --- a/src/api/system/customer/index.ts +++ b/src/api/system/customer/index.ts @@ -133,3 +133,13 @@ export const resetPwdUser = (userId: string, password: string) => { } }); }; +/** + * 重置App用户密码 + * @param userId + */ +export const getUserMainDevices = (userId: string) => { + return request({ + url: `/customer/user/${userId}/devices`, + method: 'get', + }); +}; diff --git a/src/api/system/device/index.ts b/src/api/system/device/index.ts index 3858a2b..8e113d3 100644 --- a/src/api/system/device/index.ts +++ b/src/api/system/device/index.ts @@ -62,3 +62,22 @@ export const delDevice = (deviceId: string | number | Array) => method: 'delete' }); }; + +/** + * 获取设备 可选 位置 + * @param deviceId + */ +export const getLocationListOptions = (deviceId: string): AxiosPromise<{ + locationId: string; + locationName: string; + homeName: string; + homeId: string; +}[]> => { + return request({ + url: '/device/device/locationOptions', + method: 'get', + params: { + deviceId, + } + }); +}; diff --git a/src/components/AwaitTime/index.vue b/src/components/AwaitTime/index.vue new file mode 100644 index 0000000..ed8cc12 --- /dev/null +++ b/src/components/AwaitTime/index.vue @@ -0,0 +1,39 @@ + + + + + diff --git a/src/components/AwaitTime/useWaitTimerManager.ts b/src/components/AwaitTime/useWaitTimerManager.ts new file mode 100644 index 0000000..57f0923 --- /dev/null +++ b/src/components/AwaitTime/useWaitTimerManager.ts @@ -0,0 +1,64 @@ +import {ref, type Ref} from 'vue' + +type TimerItem = { + id: string | number + startTime: number + display: Ref +} + +// 页面级管理器,不要全局单例!多个页面同时打开表格会互相干扰 +export function useWaitTimerManager() { + const activeMap = new Map() + let rafId: number | null = null + let lastUpdate = 0 + + const formatSeconds = (seconds: number) => { + const h = Math.floor(seconds / 3600) + const m = Math.floor((seconds % 3600) / 60) + const s = Math.floor(seconds % 60) + return [h, m, s].map(v => String(v).padStart(2, '0')).join(':') + } + + function tick(ts: number) { + rafId = requestAnimationFrame(tick) + // 1s 更新一次即可 + if (ts - lastUpdate < 1000) return + lastUpdate = ts + + const now = Date.now() + for (const item of activeMap.values()) { + const sec = Math.floor((now - item.startTime) / 1000) + item.display.value = formatSeconds(sec) + } + } + + function start() { + if (!rafId) { + rafId = requestAnimationFrame(tick) + } + } + + function stop() { + if (rafId) { + cancelAnimationFrame(rafId) + rafId = null + } + } + + // 组件进来注册 + function register(id: string | number, startTime: number, display: Ref) { + activeMap.set(id, {id, startTime, display}) + start() + } + + // 组件注销(状态变了 / 组件销毁) + function unregister(id: string | number) { + activeMap.delete(id) + // 没有任务了就停掉raf,省资源 + if (activeMap.size === 0) { + stop() + } + } + + return {register, unregister} +} diff --git a/src/components/Editor/cskb.vue b/src/components/Editor/cskb.vue index 9d0fba8..16c7819 100644 --- a/src/components/Editor/cskb.vue +++ b/src/components/Editor/cskb.vue @@ -16,18 +16,38 @@ @onCreated="handleCreated" /> - -
-

请输入标准回复话术,可使用「有序步骤」插入分步指引,例如:

-
-
    -
  1. 确认设备已通电并处于配网模式(指示灯橙色快闪)
  2. -
  3. 打开APP「我的设备」→ 添加设备,选择对应型号
  4. -
  5. 输入2.4G Wi-Fi密码并等待约30秒完成连接
  6. -
+
@@ -39,32 +59,34 @@ import {Editor as WangEditor, Toolbar as EditorToolbar} from '@wangeditor-next/e import modal from '@/plugins/modal'; import {propTypes} from '@/utils/propTypes'; import {globalHeaders} from '@/utils/request'; +import {html2Text} from '@/utils'; import {shallowRef, ref, computed, watch, onBeforeUnmount} from 'vue'; const props = defineProps({ - /* 编辑器的内容 */ modelValue: propTypes.string, - /* 高度 */ height: propTypes.number.def(400), - /* 最小高度 */ minHeight: propTypes.number.def(400), - /* 只读 */ readOnly: propTypes.bool.def(false), - /* 图片上传文件大小限制(MB) */ fileSize: propTypes.number.def(5), - /* 视频上传文件大小限制(MB) */ videoSize: propTypes.number.def(100), - /* 类型(base64格式、url格式) */ type: propTypes.string.def('url'), - /* 精简工具栏(仅加粗/有序步骤/图片/链接/清除格式) */ - simpleToolbar: propTypes.bool.def(false) + simpleToolbar: propTypes.bool.def(false), + maxTextLength: propTypes.number.def(1000), + maxImageCount: propTypes.number.def(3), + maxLinkCount: propTypes.number.def(5) }); -const emit = defineEmits(['update:modelValue']); +const emit = defineEmits(['update:modelValue', 'countChange']); const editorRef = shallowRef(); const content = ref(''); -const wordCount = ref(0); +const textCount = ref(0); +const imageCount = ref(0); +const linkCount = ref(0); +const lastValidHtml = ref(''); + +const IMG_REGEX = /]*>/gi; +const A_TAG_REGEX = /]*>.*?<\/a>/gi; const baseUrl = import.meta.env.VITE_APP_BASE_API; const uploadOssUrl = baseUrl + '/resource/oss/upload'; @@ -102,6 +124,19 @@ const toolbarConfig = computed>(() => { } }); +/* ==================== 内容度量 ==================== */ + +function measureHtml(html: string) { + const textLen = html2Text(html).length; + const imgMatch = html.match(IMG_REGEX); + const linkMatch = html.match(A_TAG_REGEX); + return { + textLen, + imgNum: imgMatch ? imgMatch.length : 0, + linkNum: linkMatch ? linkMatch.length : 0 + }; +} + /* ==================== OSS 上传 ==================== */ const uploadToOss = async (file: File): Promise<{ url: string; fileName: string }> => { @@ -161,12 +196,24 @@ const validateVideoFile = (file: File) => { /* ==================== wangeditor 菜单配置 ==================== */ +function checkImageQuotaBeforeUpload(): boolean { + if (!editorRef.value) return false; + const html = editorRef.value.getHtml(); + const {imgNum} = measureHtml(html); + if (imgNum >= props.maxImageCount) { + modal.msgError(`图片数量不能超过 ${props.maxImageCount} 张,请先删除已插入的图片`); + return false; + } + return true; +} + const getUploadImageMenuConfig = () => { if (props.type === 'base64') { return { allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml'], customUpload(file: File, insertFn: (url: string, alt?: string, href?: string) => void) { if (!validateImageFile(file)) return; + if (!checkImageQuotaBeforeUpload()) return; modal.loading('正在上传图片,请稍候...'); const reader = new FileReader(); @@ -190,11 +237,12 @@ const getUploadImageMenuConfig = () => { allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml'], async customUpload(file: File, insertFn: (url: string, alt?: string, href?: string) => void) { if (!validateImageFile(file)) return; + if (!checkImageQuotaBeforeUpload()) return; modal.loading('正在上传图片,请稍候...'); try { const result = await uploadToOss(file); - insertFn(result.url, file.name, result.url); + insertFn(result.url, file.name); } catch { modal.msgError('图片上传失败'); } finally { @@ -224,7 +272,6 @@ const getUploadVideoMenuConfig = () => ({ const editorConfig = computed>(() => ({ placeholder: props.simpleToolbar ? '请输入标准回复话术...' : '请输入内容', autoFocus: false, - maxLength: 2000, MENU_CONF: { uploadImage: getUploadImageMenuConfig() as any, uploadVideo: getUploadVideoMenuConfig() as any @@ -239,9 +286,37 @@ const editorConfig = computed>(() => ({ /* ==================== 事件处理 ==================== */ +function updateCounts(html: string) { + const {textLen, imgNum, linkNum} = measureHtml(html); + textCount.value = textLen; + imageCount.value = imgNum; + linkCount.value = linkNum; + emit('countChange', {textLength: textLen, imageCount: imgNum, linkCount: linkNum, htmlLength: html.length}); +} + const handleChange = () => { if (!editorRef.value) return; - wordCount.value = editorRef.value.getText().length; + const html = editorRef.value.getHtml(); + console.log(html) + const {textLen, imgNum, linkNum} = measureHtml(html); + updateCounts(html); + + const textOver = textLen > props.maxTextLength; + const imgOver = imgNum > props.maxImageCount; + const linkOver = linkNum > props.maxLinkCount; + + if (textOver || imgOver || linkOver) { + const msgs: string[] = []; + if (textOver) msgs.push(`纯文本超过 ${props.maxTextLength} 字`); + if (imgOver) msgs.push(`图片超过 ${props.maxImageCount} 张`); + if (linkOver) msgs.push(`链接超过 ${props.maxLinkCount} 条`); + modal.msgError(msgs.join(';') + ',已自动恢复'); + editorRef.value.setHtml(lastValidHtml.value); + updateCounts(lastValidHtml.value); + return; + } + + lastValidHtml.value = html; }; const syncReadOnly = () => { @@ -258,7 +333,9 @@ const syncReadOnly = () => { const handleCreated = (editor: IDomEditor) => { editorRef.value = editor; syncReadOnly(); - wordCount.value = editor.getText().length; + const html = editor.getHtml(); + updateCounts(html); + lastValidHtml.value = html; }; /* ==================== 双向数据绑定(直接透传HTML) ==================== */ @@ -324,6 +401,11 @@ onBeforeUnmount(() => { min-height: inherit; } +.editor-footer { + display: flex; + flex-direction: column; +} + .editor-tip { padding: 12px 16px; font-size: 13px; @@ -338,8 +420,27 @@ onBeforeUnmount(() => { border-radius: 4px; } -.word-count { - text-align: right; - margin-top: 4px; +.counter-bar { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 8px; + padding: 6px 12px; + font-size: 12px; + color: #999; + border-top: 1px solid var(--el-border-color); + background: #fafafa; +} + +.counter-bar .warn { + color: #e6a23c; +} + +.counter-bar .danger { + color: #f56c6c; +} + +.counter-bar .divider { + color: #dcdfe6; } diff --git a/src/components/FormItemTip/index.vue b/src/components/FormItemTip/index.vue index bf0b4aa..ac9c50b 100644 --- a/src/components/FormItemTip/index.vue +++ b/src/components/FormItemTip/index.vue @@ -116,12 +116,16 @@ @update:model-value="$emit('update:modelValue', $event)" > + > + + {{ item[labelKey] }} + + @@ -182,6 +186,7 @@ import {ref} from 'vue' import {genFileId} from 'element-plus' import type {UploadInstance, UploadProps, UploadRawFile} from 'element-plus' +import defaultImage from '@/assets/images/default.png' defineOptions({inheritAttrs: false}) @@ -252,7 +257,8 @@ const isOptionDisabled = (item: Record) => { const showPassword = ref(false) const upload = ref() -const defaultImag = import.meta.env.VITE_DEFAULT_USER_IMAGE; + +const defaultImag = defaultImage || import.meta.env.VITE_DEFAULT_USER_IMAGE; const imageUrl = ref('') watch( diff --git a/src/layout/components/Navbar.vue b/src/layout/components/Navbar.vue index 82eeed3..d5c1483 100644 --- a/src/layout/components/Navbar.vue +++ b/src/layout/components/Navbar.vue @@ -123,13 +123,10 @@ const logout = async () => { type: 'warning' } as ElMessageBoxOptions); userStore.logout().then(() => { + csSessionStore.destroyWs() router.replace({ path: '/login', - query: { - redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/') - } }); - csSessionStore.destroyWs() tab.closeAllPage(); }); }; diff --git a/src/store/modules/csSession.ts b/src/store/modules/csSession.ts index 09a3e54..ddbf23d 100644 --- a/src/store/modules/csSession.ts +++ b/src/store/modules/csSession.ts @@ -45,7 +45,23 @@ type CsQueueType = { }, type: 'cs:queue' } - +type CsMessageType = { + data: { + "clientMsgId": string, + "content": string, + "createTime": string, + "messageId": string, + "msgType": string, + "ossId": null, + "senderId": string, + "senderType": string, + "seq": number, + "sessionId": string, + "url": string + }, + type: 'cs:message' +} +type CsMessageDataType = CsMessageType['data'] /** ws 消息 → 业务侧消费的消息结构(与 chat UI 对齐) */ export interface ChatMessage { @@ -119,7 +135,7 @@ export const useCsSessionStore = defineStore('csSession', () => { } // 设置客服负责所有用户的消息 - function setAllUsersMessages(sessionId: string, data) { + function setAllUsersMessages(sessionId: string, data: CsMessageDataType) { allUsersMessages[sessionId] = [ ...(allUsersMessages[sessionId] || []), data @@ -140,6 +156,8 @@ export const useCsSessionStore = defineStore('csSession', () => { // 消息会话 不是 当前会话,且是 指定会话id 时,才增加未读消息数量 if (currentSessionId.value !== item.sessionId) { item.unreadCount = (item.unreadCount || 0) + 1 + } else { + item.unreadCount = 0 } } }); @@ -219,7 +237,7 @@ export const useCsSessionStore = defineStore('csSession', () => { url: wsUrl, heartbeatInterval: 15_000, maxReconnectAttempts: 10, - debug: true, + debug: import.meta.env.VITE_APP_ENV === 'development', }); // ── 业务消息 handler:收到什么类型就做什么事 ── @@ -257,7 +275,7 @@ export const useCsSessionStore = defineStore('csSession', () => { getRightUserList(); }); // cs:message 接受消息 - ws.registerHandler('cs:message', (pkt) => { + ws.registerHandler('cs:message', (pkt: CsMessageType) => { console.log('接受消息:', pkt.data.content) setAllUsersMessages(pkt.data.sessionId, pkt.data) }); @@ -308,9 +326,12 @@ export const useCsSessionStore = defineStore('csSession', () => { /** 彻底销毁 ws(登出时调) */ function destroyWs() { - ws?.destroy(); - ws = null; - wsStatus.value = 'closed'; + if (!ws) return + if (ws) { + ws?.destroy(); + ws = null; + wsStatus.value = 'closed'; + } } /* ===================== 消息辅助 ===================== */ @@ -321,6 +342,7 @@ export const useCsSessionStore = defineStore('csSession', () => { return userLists.value[activeUserType.value]; }) + // 设置未读消息数量 function setReadCount(sessionId: string, count: number) { userLists.value[activeUserType.value].forEach(item => { if (item.sessionId === sessionId) { @@ -367,6 +389,7 @@ export const useCsSessionStore = defineStore('csSession', () => { setSending(true) client.sendString(JSON.stringify(sendObj)) toggleSession() + getRightUserList() } catch (err) { console.error('消息发送失败:', err) } diff --git a/src/views/login.vue b/src/views/login.vue index c10db35..3c8db15 100644 --- a/src/views/login.vue +++ b/src/views/login.vue @@ -80,7 +80,7 @@
账号登录
- + {{ $t("login.login") }} {{ $t("login.logging") }} -

如需开通管理员账号,请联系系统管理员

+

如需开通账号,请联系系统管理员

diff --git a/src/views/system/conversation/compontents/ChatInput.vue b/src/views/system/conversation/compontents/ChatInput.vue index 1d0343f..88a2c92 100644 --- a/src/views/system/conversation/compontents/ChatInput.vue +++ b/src/views/system/conversation/compontents/ChatInput.vue @@ -5,9 +5,11 @@ diff --git a/src/views/system/conversation/compontents/MessageList/index.vue b/src/views/system/conversation/compontents/MessageList/index.vue index 9547fe7..c616ea2 100644 --- a/src/views/system/conversation/compontents/MessageList/index.vue +++ b/src/views/system/conversation/compontents/MessageList/index.vue @@ -113,7 +113,6 @@ const handleScroll = () => { prevScrollTop = currentTop if (scrollingUp && currentTop <= TOP_THRESHOLD && !props.loadingHistory && !isLoadingMore) { - console.log('向上滚动到顶部了') isLoadingMore = true; setTimeout(() => { isLoadingMore = false diff --git a/src/views/system/conversation/conversationMain.vue b/src/views/system/conversation/conversationMain.vue index 95bee55..03d4c19 100644 --- a/src/views/system/conversation/conversationMain.vue +++ b/src/views/system/conversation/conversationMain.vue @@ -161,7 +161,7 @@ const acceptAgentList = ref([]) // 获取转接客服列表 function getAgentList() { getAgentPresence().then(res => { - acceptAgentList.value = res.data; + acceptAgentList.value = res.data.filter(item => item.activeSessionCount !== 1) }) } @@ -198,10 +198,11 @@ const submitForm = () => { demoFormRef.value?.validate(async (valid: boolean) => { if (valid) { buttonLoading.value = true; - console.log(form.value) transferAgentPresence(form.value).then(() => { csSessionStore.getRightUserList() csSessionStore.setCurrentUserInfoMain(null) + ElMessage.success('转接成功') + cancel() }).finally(() => { buttonLoading.value = false; }) diff --git a/src/views/system/conversation/index.vue b/src/views/system/conversation/index.vue index 9943dbd..087575c 100644 --- a/src/views/system/conversation/index.vue +++ b/src/views/system/conversation/index.vue @@ -133,8 +133,18 @@ - - + + + + + + { `批量会话导出${new Date().getTime()}.xlsx` ); }; + + +import {provide} from 'vue' +import {useWaitTimerManager} from '@/components/AwaitTime/useWaitTimerManager' +import AwaitTime from '@/components/AwaitTime/index.vue' + +const {register, unregister} = useWaitTimerManager() +provide('timerManager', {register, unregister}) + + onMounted(() => { getList(); getOverViewSession() diff --git a/src/views/system/conversation/main.vue b/src/views/system/conversation/main.vue index 74bab24..c780e3c 100644 --- a/src/views/system/conversation/main.vue +++ b/src/views/system/conversation/main.vue @@ -5,10 +5,11 @@ import {deskCsAgentDeskBySessionId, getDeskCsAgentHistory} from "@/api/system/cs import {hiddenPhone} from "@/utils/phone"; import {MAX_MESSAGES} from "@/store/modules/csSession"; import {download as requestDownload} from "@/utils/request"; +import defaultAvatar from '@/assets/images/default.png' const router = useRouter() const route = useRoute() -const defaultImage = import.meta.env.VITE_DEFAULT_USER_IMAGE; +const defaultImage = defaultAvatar || import.meta.env.VITE_DEFAULT_USER_IMAGE; const form = ref({ "customer": { @@ -34,6 +35,7 @@ const form = ref({ } }) const msgList = ref([]) +const messageListRef = ref(null) onMounted(() => { if (route.query.id) { @@ -42,8 +44,8 @@ onMounted(() => { let latestSeq = Math.max(form.value.session.latestSeq - MAX_MESSAGES, 0) getDeskCsAgentHistory(form.value.session.sessionId, latestSeq, form.value.session.latestSeq).then(res => { msgList.value = res.data || [] - console.log(msgList.value) loadingHistory.value = false + messageListRef?.value.scrollToBottom() }) }) } @@ -58,7 +60,6 @@ function rollback() { const loadingHistory = ref(false) function handleLoadMore() { - console.log('loading history') loadingHistory.value = true if (!form.value.session.sessionId) return console.log('滚动到顶部了,想要加载更多消息') @@ -69,7 +70,6 @@ function handleLoadMore() { // 2. 减去 MAX_MESSAGES 条消息 let latestSeq = Math.max(seq - MAX_MESSAGES, 0) // 3. 拉取过往新消息 - // console.log('拉取过往新消息从', latestSeq) getDeskCsAgentHistory(form.value.session.sessionId, latestSeq, seq).then(res => { msgList.value = [...res.data || [], ...msgList.value] loadingHistory.value = false @@ -128,7 +128,7 @@ function exportCsSessionStore() {
-
diff --git a/src/views/system/cskb/add.vue b/src/views/system/cskb/add.vue index 6210070..84bc0de 100644 --- a/src/views/system/cskb/add.vue +++ b/src/views/system/cskb/add.vue @@ -4,6 +4,9 @@ import cskbEditor from '@/components/Editor/cskb.vue' import {FormInstance, FormRules} from "element-plus"; import {addCsKb} from "@/api/system/cskb"; import modal from "@/plugins/modal"; +import {useDict} from "@/utils/dict"; + +const {com_question_categories} = toRefs(useDict('com_question_categories')); const formRef = ref() const router = useRouter(); @@ -36,7 +39,7 @@ const actions = { resolved: {"buttonCode": "resolved", "label": "已解决", "sort": 1, value: 'resolved'}, transfer_human: {"buttonCode": "transfer_human", "label": "转人工", "sort": 2, value: 'transfer_human'}, } - +const ActionsButtons = ref([]) function handleBack() { router.replace({ @@ -46,11 +49,10 @@ function handleBack() { async function submit(isEnable = false) { if (!formRef.value) return - console.log(form.value) await formRef.value.validate((valid) => { if (valid) { // isEnable=true 代表保存并启用 - form.value.buttons = form.value.buttons.map(item => { + form.value.buttons = ActionsButtons.value.map(item => { return actions[item] }) addCsKb(form.value).then(() => { @@ -116,8 +118,12 @@ function reset() { @@ -142,7 +148,7 @@ function reset() { (useDict('com_question_categories')); // 表单实例 const formRef = ref() const router = useRouter(); @@ -47,8 +50,7 @@ function init() { if (route.query.id) { getCsKb(route.query.id as string).then(res => { form.value = res.data; - form.value.buttons = res.data.buttons.map(item => actions[item.buttonCode].value); - + ActionsButtons.value = res.data.buttons.map(item => actions[item.buttonCode].value); showForm.value = JSON.parse(JSON.stringify(form.value)); }) } @@ -63,7 +65,7 @@ const actions = { 'value': 'resolved', "sort": 1 }, - transfer_human: { + "transfer_human": { "buttonCode": "transfer_human", "buttonId": "2108377417910558722", "kbId": "1761700000000002001", @@ -73,6 +75,7 @@ const actions = { } } +const ActionsButtons = ref([]) onMounted(() => { init() }) @@ -89,7 +92,7 @@ async function submit() { await formRef.value.validate((valid) => { if (valid) { // 这里调用新增/编辑接口 - form.value.buttons = form.value.buttons.map(item => { + form.value.buttons = ActionsButtons.value.map(item => { return actions[item] }) console.log('校验通过,提交数据', form.value) @@ -153,6 +156,8 @@ function handleCancel() { v-model="form.category" :inputAttrs="{ placeholder: '请选择问题分类'}" label="问题分类" + :radioOptions="com_question_categories" + type="select" prop="category" tip="必填,可选:设备配网 / 耗材滤芯 / 固件升级 / 设备报修" > @@ -176,7 +181,7 @@ function handleCancel() { {{ scope.row.title }} - + + +