app.tsx 10 KB

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