app.tsx 15 KB

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