app.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import React from 'react';
  2. import { BasicLayoutProps, Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
  3. import { Button, notification, Result } from 'antd';
  4. import { history, RequestConfig } from 'umi';
  5. import RightContent from '@/components/RightContent';
  6. import { ResponseError } from 'umi-request';
  7. import { queryCurrent, getMenu } from './services/user';
  8. import defaultSettings from '../config/defaultSettings';
  9. import { DesktopOutlined, MessageOutlined, SendOutlined, TeamOutlined, QrcodeOutlined, DatabaseOutlined, ReadOutlined, MobileOutlined, FundViewOutlined, RadarChartOutlined, BarChartOutlined, WechatOutlined, BookOutlined, FileImageOutlined, EyeOutlined, UserOutlined } from '@ant-design/icons';
  10. import { getMyMenu, headrRouter } from '../config/routerConfig';
  11. import { ReactComponent as LaunchSvg } from '@/assets/launch.svg'
  12. import { ReactComponent as AdLaunchSvg } from '@/assets/adLaunch.svg'
  13. import { ReactComponent as MaterialSvg } from '@/assets/material.svg'
  14. import { ReactComponent as GdtSvg } from '@/assets/gdt.svg'
  15. import { ReactComponent as MonitorSvg } from '@/assets/monitor.svg'
  16. import versions from './utils/versions';
  17. interface CurrentUser {
  18. avatar?: string;
  19. name?: string;
  20. title?: string;
  21. group?: string;
  22. signature?: string;
  23. tags?: {
  24. key: string;
  25. label: string;
  26. }[];
  27. userId?: string;
  28. powerLevel?: number;
  29. access?: 'user' | 'guest' | 'admin' | any;
  30. unreadCount?: number;
  31. companyList?: any[],
  32. onlineCompanyId?: number
  33. }
  34. export async function getInitialState(): Promise<{
  35. currentUser?: CurrentUser;
  36. settings?: LayoutSettings;
  37. menu?: any,
  38. loading?: boolean,
  39. collapsed?: string,
  40. onCollapse?: (onCollapse: boolean) => void
  41. }> {
  42. // 如果是登录页面,不执行
  43. if (sessionStorage.getItem('Admin-Token')) {
  44. //开始版本号对比
  45. versions()
  46. try {
  47. sessionStorage.removeItem('msg')
  48. let currentUser = {}
  49. let userInfo: any = await queryCurrent();//用户信息
  50. let companyInfo = userInfo?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
  51. currentUser = { access: 'admin', powerLevel: userInfo?.data?.userInfo?.powerLevel, name: userInfo?.data?.userInfo?.nickname || '', userId: userInfo?.data?.userInfo?.userId, phone: userInfo?.data?.userInfo?.phone || '', companyList: companyInfo, onlineCompanyId: userInfo?.data?.onlineCompanyId }//处理个人信息
  52. let menu: any = await getMenu().then(async (res: any) => {//获取菜单并处理
  53. let { code, data } = res
  54. let path = getMyMenu(code, data)
  55. if (userInfo?.data?.userInfo?.account === 'admin' && path.length > 0) {//假如是ADMIN加入api测试
  56. path[0].routes.push({ key: 0, path: '/operatePage/apitest', name: 'api测试', icon: '', component: './operatePage/apitest', roles: 'admin' })
  57. }
  58. return { data: path }
  59. });
  60. localStorage.setItem('sex', userInfo?.data?.userInfo?.sex)
  61. localStorage.setItem('userId', userInfo?.data?.userInfo?.userId)
  62. localStorage.setItem('name', userInfo?.data?.userInfo?.nickname)
  63. return {
  64. currentUser,
  65. settings: { ...defaultSettings },
  66. loading: false,
  67. menu,
  68. collapsed: '0',
  69. onCollapse: (collapsed: boolean) => {
  70. let v = collapsed ? '1' : '0'
  71. localStorage.setItem('collapsed', v)
  72. }
  73. };
  74. } catch (error) {
  75. console.log(111111, error)
  76. history.push('/user/login');
  77. }
  78. }
  79. return {
  80. settings: defaultSettings,
  81. };
  82. }
  83. // 枚举转译服务端菜单icon
  84. const IconMap = {
  85. desktop: <DesktopOutlined />,
  86. message: <MessageOutlined />,
  87. send: <SendOutlined />,
  88. team: <TeamOutlined />,
  89. database: <DatabaseOutlined />,
  90. qrcode: <QrcodeOutlined />,
  91. read: <ReadOutlined />,
  92. mobile: <MobileOutlined />,
  93. fundView: <FundViewOutlined />,
  94. radarChart: <RadarChartOutlined />,
  95. barChart: <BarChartOutlined />,
  96. wechat: <WechatOutlined />,
  97. book: <BookOutlined />,
  98. peoples: <UserOutlined />,
  99. 'file-image': <FileImageOutlined />,
  100. launch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><LaunchSvg /></span>,
  101. adLaunch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><AdLaunchSvg /></span>,
  102. material: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MaterialSvg /></span>,
  103. gdt: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GdtSvg /></span>,
  104. monitor: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MonitorSvg /></span>,
  105. eye: <EyeOutlined />
  106. };
  107. //处理菜单
  108. const loopMenuItem = (menus: MenuDataItem[],): MenuDataItem[] => {
  109. let menu = menus?.map(({ icon, routes, roles, ...item }) => {
  110. let newItem = JSON.parse(JSON.stringify(item))
  111. newItem.key = item?.path || item?.key
  112. return {
  113. ...newItem,
  114. hideInMenu: false,//校验隐藏菜单
  115. icon: icon && IconMap[icon as string],
  116. children: routes && loopMenuItem(routes),
  117. }
  118. })
  119. return menu
  120. }
  121. export const layout = ({
  122. initialState
  123. }: {
  124. initialState: { settings?: LayoutSettings; currentUser?: CurrentUser; menu?: any; loading: boolean, collapsed: string, onCollapse: any };
  125. }): BasicLayoutProps => {
  126. return {
  127. menuDataRender: () => {
  128. return loopMenuItem(initialState?.menu?.data || [])
  129. },//解析服务端菜单
  130. rightContentRender: () => <RightContent />,
  131. disableContentMargin: false,
  132. collapsed: localStorage.collapsed === '1',
  133. onCollapse: initialState.onCollapse,
  134. breakpoint: false,
  135. // footerRender: () => <Footer />,
  136. onPageChange: () => {
  137. headrRouter(initialState, history)
  138. let { pathname, query } = history.location
  139. if (query?.t) {//带token直接进入对应页面
  140. sessionStorage.setItem('Admin-Token', decodeURIComponent(query.t as any))
  141. location.href = window.location.origin + '/#' + pathname
  142. location.reload()
  143. } else if (!initialState?.currentUser?.name && history.location.pathname !== '/user/login') {
  144. history.push('/user/login');
  145. }
  146. },
  147. splitMenus: true,//配合mix分割菜单
  148. menuHeaderRender: undefined,
  149. ...initialState?.settings,
  150. };
  151. };
  152. const codeMessage = {
  153. 200: '服务器成功返回请求的数据。',
  154. 201: '新建或修改数据成功。',
  155. 202: '一个请求已经进入后台排队(异步任务)。',
  156. 204: '删除数据成功。',
  157. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  158. 401: '用户没有权限(令牌、用户名、密码错误)。',
  159. 403: '用户得到授权,但是访问是被禁止的。',
  160. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  161. 405: '请求方法不被允许。',
  162. 406: '请求的格式不可得。',
  163. 410: '请求的资源被永久删除,且不会再得到的。',
  164. 422: '当创建一个对象时,发生一个验证错误。',
  165. 500: '服务器发生错误,请检查服务器。',
  166. 502: '网关错误。',
  167. 503: '服务不可用,服务器暂时过载或维护。',
  168. 504: '网关超时。',
  169. };
  170. /**
  171. * 异常处理程序
  172. */
  173. const errorHandler = (error: ResponseError) => {
  174. const { response } = error;
  175. if (response && response.status) {
  176. const errorText = codeMessage[response.status] || response.statusText;
  177. const { status, url } = response;
  178. notification.error({
  179. message: `请求错误 ${status}: ${url}`,
  180. description: errorText,
  181. });
  182. }
  183. if (!response) {
  184. notification.error({
  185. description: '您的网络发生异常,无法连接服务器',
  186. message: '网络异常',
  187. });
  188. }
  189. throw error;
  190. };
  191. //请求处理
  192. export const request: RequestConfig = {
  193. errorHandler,
  194. timeout: 300000,
  195. headers: { ['Authorization']: 'Bearer ' + sessionStorage.getItem('Admin-Token') },
  196. errorConfig: {
  197. adaptor: (resData: any) => {
  198. let div: any
  199. // if (!document.getElementById('notificationPop')) {
  200. // div = document.createElement('div')
  201. // div.id = 'notificationPop'
  202. // }
  203. if (resData.code === 500) {
  204. let msg = sessionStorage.getItem('msg')
  205. if (resData.msg === '令牌验证失败') {//
  206. if (history.location.pathname !== '/user/login') {
  207. if (!msg) {
  208. // document.body.appendChild(div)
  209. const key = `open${Date.now()}`;
  210. const btn = (
  211. <Button type="primary" onClick={() => {
  212. // setCookie('Admin-Token', '1', -300)
  213. sessionStorage.removeItem('Admin-Token')
  214. history.push('/user/login')
  215. notification.close(key)
  216. sessionStorage.removeItem('msg')
  217. // document.body.removeChild(div)
  218. }}>
  219. 重新登录
  220. </Button>
  221. );
  222. const description = (
  223. <Result
  224. status="500"
  225. title='令牌验证失败!'
  226. subTitle="长时间没有操作,令牌失效请重新登录!"
  227. extra={btn}
  228. />
  229. )
  230. sessionStorage.setItem('msg', 'true')
  231. notification.open({
  232. message: '',
  233. description,
  234. duration: null,
  235. getContainer: () => document.getElementById('notificationPop') || document.getElementById('root') as HTMLElement,
  236. key,
  237. style: { zIndex: 999999, right: '50%', top: '50%', transform: 'translate(50%, -50%)', position: 'fixed', transition: 'all 0s' },
  238. onClose: () => {
  239. // setCookie('Admin-Token', '1', -300)
  240. sessionStorage.removeItem('Admin-Token')
  241. history.push('/user/login')
  242. sessionStorage.removeItem('msg')
  243. // document.body.removeChild(div)
  244. }
  245. });
  246. }
  247. return { ...resData }
  248. } else {
  249. sessionStorage.removeItem('Admin-Token')
  250. }
  251. }
  252. if (!msg) {
  253. sessionStorage.setItem('msg', 'true')
  254. notification.error({
  255. message: resData.msg,
  256. onClose: () => {
  257. sessionStorage.removeItem('msg')
  258. }
  259. });
  260. }
  261. }
  262. if (resData.code === 310) {//权限错误
  263. let msg = sessionStorage.getItem('msg')
  264. sessionStorage.removeItem('Admin-Token')
  265. history.push('/user/login')
  266. if (!msg) {
  267. sessionStorage.setItem('msg', 'true')
  268. notification.error({
  269. message: resData.msg,
  270. onClose: () => {
  271. sessionStorage.removeItem('msg')
  272. }
  273. });
  274. }
  275. }
  276. return {
  277. ...resData,
  278. }
  279. },
  280. },
  281. };