Sfoglia il codice sorgente

feat: 增加实时工作状态推送

lanjianrong 4 anni fa
parent
commit
3e81926624

+ 10 - 9
src/app.tsx

@@ -4,8 +4,8 @@ import RightContent from '@/components/RightContent'
 import { message } from 'antd'
 import logo from '../public/logo.svg'
 import BasicModal, { BasicDrawer } from '@/components/Modal'
-import { AddressBook } from '@icon-park/react'
 import ws, { onMessage } from '@/utils/ws'
+import Book from './components/RightContent/Book'
 
 const loginPath = '/user/login'
 
@@ -65,11 +65,12 @@ export const layout = ({ initialState }) => {
     waterMarkProps: {
       content: initialState?.currentUser?.username
     },
-    onPageChange: async () => {
-      const { location } = history
+    onPageChange: async location => {
       // 如果没有登录,重定向到 login
       if (!initialState?.currentUser?.staffId && location.pathname !== loginPath) {
         history.replcae('/user/login')
+      } else {
+        Book.tryChangeWorkStatus(initialState?.currentUser?.staffId, location.pathname)
       }
 
       // if (
@@ -89,12 +90,12 @@ export const layout = ({ initialState }) => {
         <BasicModal />
       </>
     ),
-    links: [
-      <div className="ant-menu-title-content">
-        <AddressBook theme="outline" className="anticon" />
-        <span className="ant-pro-menu-item-title">通讯录</span>
-      </div>
-    ],
+    // links: [
+    //   <div className="ant-menu-title-content">
+    //     <AddressBook theme="outline" className="anticon" />
+    //     <span className="ant-pro-menu-item-title">通讯录</span>
+    //   </div>
+    // ],
     // menuHeaderRender: false,
     ...initialState?.settings
   }

+ 5 - 2
src/components/RightContent/AvatarDropdown.tsx

@@ -6,7 +6,8 @@ import { history, useModel } from 'umi'
 import { stringify } from 'querystring'
 import HeaderDropdown from '../HeaderDropdown'
 import styles from './index.less'
-import { clearAuthCache } from '@/utils/auth'
+import { clearAuthCache, removeToken } from '@/utils/auth'
+import ws from '@/utils/ws'
 
 export type GlobalHeaderRightProps = {
   menu?: boolean
@@ -20,6 +21,8 @@ const loginOut = async () => {
   const { redirect } = query
   // Note: There may be security issues, please note
   if (window.location.pathname !== '/user/login' && !redirect) {
+    // 断开socket连接
+    ws.disconnect()
     history.replace({
       pathname: '/user/login',
       search: stringify({
@@ -48,7 +51,7 @@ const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
           onOk: () => {
             setInitialState({ ...initialState, currentUser: undefined, roles: [], permData: {} })
             // 清除AuthCache
-            clearAuthCache()
+            removeToken()
             loginOut()
             return
           }

+ 18 - 1
src/components/RightContent/Book/index.tsx

@@ -1,7 +1,24 @@
-// import { MessageType } from '@/types/typing'
+import ws, { CmdType } from '@/utils/ws'
+// import menuLocal from '@/locales/zh-CN/menu'
+import { debounce } from 'lodash'
 
 const Book = () => {
   return <></>
 }
 
+// 员工工作状态
+function changeWorkStatus(userid: string, pathname: string) {
+  // const targetMenuLocal = menuLocal[`menu${pathname?.replaceAll('/', '.')}`]
+  const targetMenuLocal = `menu${pathname?.replaceAll('/', '.')}`
+
+  targetMenuLocal &&
+    ws.sendMessage({
+      cmd: CmdType.WorkStatus,
+      userid,
+      memo: targetMenuLocal
+    })
+}
+const tryChangeWorkStatus = debounce(changeWorkStatus, 1500)
+Book.tryChangeWorkStatus = tryChangeWorkStatus
+
 export default Book

+ 7 - 7
src/components/RightContent/Book/wsNotice.tsx

@@ -1,6 +1,7 @@
+import type { MessageType } from '@/types/typing'
 import { notification } from 'antd'
 
-enum noticeType {
+enum MsgType {
   Notification = 'notification',
   Message = 'message'
 }
@@ -10,9 +11,7 @@ enum mediaType {
   HolidayNotice = 2
 }
 // 版本发布
-function versionPublish(msg: WebSocketEventMap['message']) {
-  console.log('11')
-
+function versionPublish(msg: MessageType) {
   const { refresh, title } = msg
   notification.warning({
     message: '有新的版本更新, 请及时刷新页面',
@@ -29,10 +28,11 @@ function versionPublish(msg: WebSocketEventMap['message']) {
   })
 }
 
-export default (msg: WebSocketEventMap['message']) => {
-  const { media, notice } = msg
+export default (msg: MessageType) => {
+  const { media, msgType } = msg
+
   // 通知
-  if (notice === noticeType.Notification) {
+  if (msgType === MsgType.Notification) {
     media === mediaType.VersionUpdate && versionPublish(msg)
   }
 }

+ 11 - 3
src/pages/user/login/index.jsx

@@ -8,6 +8,7 @@ import styles from './index.less'
 import { apiLogin } from '@/services/login'
 import { setAuthCache } from '@/utils/auth'
 import { TOKEN_KEY } from '@/utils/cache/cacheEnum'
+import ws, { onMessage } from '@/utils/ws'
 
 const LoginMessage = ({ content }) => (
   <Alert
@@ -43,6 +44,10 @@ const Login = () => {
     const permData = await initialState?.fetchPermData?.()
     if (userInfo) {
       setInitialState({ ...initialState, ...userInfo, permData })
+      const { username, staffId: id, wsToken: token } = userInfo?.currentUser
+      ws.init(`ws://cld2qa.com/summon/v1/chat/link?username=${username}&id=${id}&token=${token}`, {
+        onMessage
+      })
     }
   }
 
@@ -118,7 +123,8 @@ const Login = () => {
             }}
             onFinish={async values => {
               handleSubmit(values)
-            }}>
+            }}
+          >
             <Tabs activeKey={type} onChange={setType}>
               <Tabs.TabPane
                 key="account"
@@ -189,14 +195,16 @@ const Login = () => {
             <div
               style={{
                 marginBottom: 24
-              }}>
+              }}
+            >
               <ProFormCheckbox noStyle name="autoLogin">
                 <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
               </ProFormCheckbox>
               <a
                 style={{
                   float: 'right'
-                }}>
+                }}
+              >
                 <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
               </a>
             </div>

+ 4 - 0
src/utils/auth/index.ts

@@ -32,6 +32,10 @@ export function clearAuthCache(immediate = true) {
   return fn(immediate)
 }
 
+export function removeToken() {
+  const fn = isLocal ? Persistent.removeLocal : Persistent.removeSession
+  return fn(TOKEN_KEY, true)
+}
 export function getPermAuthCache(dataType?: MainMenuKeyEnum) {
   const permAuthCache = getAuthCache(PERMISSION_SELECT_KEY)
   if (!dataType) return [null, null, permAuthCache]

+ 11 - 5
src/utils/ws.ts

@@ -10,8 +10,13 @@ enum ReadyState {
   Closed = 3
 }
 
-enum CmdType {
-  NoticeOrMessage = 13
+export enum CmdType {
+  /** @name 通知、消息 */
+  NoticeOrMessage = 13,
+  /** @name 在线员工列表 */
+  OnlineBook = 12,
+  /** @name 员工工作状态 */
+  WorkStatus = 14
 }
 
 interface Options {
@@ -87,13 +92,14 @@ class Ws {
 export function onMessage(msg: MessageType) {
   // 这里执行所有的message监听事件
 
-  // console.log(msg)
-
   switch (msg.cmd) {
+    // 通知、消息
     case CmdType.NoticeOrMessage:
       wsNotice(msg)
       break
-
+    // 在线员工列表
+    case CmdType.OnlineBook:
+      break
     default:
       break
   }