app.tsx 13 KB

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