app.tsx 13 KB

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