Commit 2da39fad authored by 申中慧's avatar 申中慧

feat: 路由枚举配置

parent 6dcd80cd
{ {
"tabWidth": 2, "tabWidth": 2,
"semi": false, "semi": false,
"trailingComma": "none", "trailingComma": "all",
"singleQuote": true, "singleQuote": true,
"printWidth": 100, "printWidth": 100,
"arrowParens": "avoid", "arrowParens": "avoid",
"bracketSpacing": true, "bracketSpacing": true,
"endOfLine": "auto", "endOfLine": "auto",
"useTabs": false, "useTabs": false,
"quoteProps": "as-needed", "quoteProps": "as-needed",
......
...@@ -137,4 +137,4 @@ ...@@ -137,4 +137,4 @@
"vite-plugin-imagemin": "^0.6.1", "vite-plugin-imagemin": "^0.6.1",
"vite-plugin-mock": "^2.9.6" "vite-plugin-mock": "^2.9.6"
} }
} }
\ No newline at end of file
...@@ -47,7 +47,7 @@ ...@@ -47,7 +47,7 @@
{ {
"name": "TB-调整抵消", "name": "TB-调整抵消",
"path": "/ReportSys/trialSys/AuditAdjust", "path": "/ReportSys/trialSys/AuditAdjust",
"element": "accountAdjust", "element": "auditAdjust",
"type": "component", "type": "component",
"hideInMenu": true "hideInMenu": true
}, },
......
import React, { useEffect, useMemo, useRef, useState } from 'react' import React, { useEffect, useMemo, lazy, useRef, useState } from 'react'
import { Empty, Tabs } from 'antd' import { Empty, Tabs } from 'antd'
import WebFrame from '@/pages/web_frame' import type { TabsProps } from 'antd'
import { createMicroPageUrl } from '@/utils/pub' import useTabStore from '@/store/tab'
import useVoteStore from '@/store/vote' import { useNavigate } from 'react-router-dom'
import UnitMain, { UnitMenus } from '../../UnitMain' // 单体 import { routeMap } from '@/router'
import MergeMain, { MergeMenus } from '../../MergeMain' // 合并 import { NotFound } from '@/router/routes'
export type IUrlQueryType = Record<string, string> export type IUrlQueryType = Record<string, string>
const Nav: React.FC = props => { const Nav: React.FC = props => {
const items = useVoteStore(state => state.votes) const items = useTabStore(state => state.tabs)
console.log('🚀 ~ file: index.tsx:11 ~ items:', items) const activeKey = useTabStore(state => state.activeKey)
const activeKey = useVoteStore(state => state.activeKey) const setActiveKey = useTabStore(state => state.setActiveKey)
const setActiveKey = useVoteStore(state => state.setActiveKey) const setItems = useTabStore(state => state.addtabs)
const setItems = useVoteStore(state => state.addVotes) const removeItems = useTabStore(state => state.deletetabs)
const removeItems = useVoteStore(state => state.deleteVotes)
const newTabIndex = useRef(0) const newTabIndex = useRef(0)
const onChange = (newActiveKey: string) => { const onChange = (newActiveKey: string) => {
...@@ -37,7 +36,6 @@ const Nav: React.FC = props => { ...@@ -37,7 +36,6 @@ const Nav: React.FC = props => {
} }
}) })
const newPanes = items.filter(item => item.key !== targetKey) const newPanes = items.filter(item => item.key !== targetKey)
console.log('🚀 ~ file: index.tsx:47 ~ remove ~ items:', items)
if (newPanes.length && newActiveKey === targetKey) { if (newPanes.length && newActiveKey === targetKey) {
if (lastIndex >= 0) { if (lastIndex >= 0) {
newActiveKey = newPanes[lastIndex].key newActiveKey = newPanes[lastIndex].key
...@@ -49,7 +47,7 @@ const Nav: React.FC = props => { ...@@ -49,7 +47,7 @@ const Nav: React.FC = props => {
setActiveKey(newActiveKey) setActiveKey(newActiveKey)
} }
const onEdit = (targetKey: string, action: 'add' | 'remove') => { const onEdit = (targetKey: any, action: 'add' | 'remove') => {
if (action === 'add') { if (action === 'add') {
add() add()
} else { } else {
...@@ -57,28 +55,23 @@ const Nav: React.FC = props => { ...@@ -57,28 +55,23 @@ const Nav: React.FC = props => {
} }
} }
const creatTabPanes = () => { const tabPanes: TabsProps['items'] = useMemo(() => {
return items.map(item => { return items.map(item => {
return ( let element = item.element as string
<Tabs.TabPane tab={item.label} key={item.key}> element = element.slice(0, 1).toUpperCase() + element.slice(1)
{item.url ? ( const Element = routeMap[element]
<div> const pane = {
<WebFrame> key: item.key,
<iframe label: item.label,
src={createMicroPageUrl(item.url)} children: React.isValidElement(<Element></Element>) ? (
style={{ height: 500, width: '100%', border: 'none' }} <Element></Element>
/> ) : (
</WebFrame> <NotFound></NotFound>
</div> ),
) : ( }
<div> return pane
{!['4', '5'].includes(item.originData.mergeType) ? <MergeMain /> : <UnitMain />}
</div>
)}
</Tabs.TabPane>
)
}) })
} }, [items])
return ( return (
<div> <div>
...@@ -89,9 +82,8 @@ const Nav: React.FC = props => { ...@@ -89,9 +82,8 @@ const Nav: React.FC = props => {
activeKey={activeKey} activeKey={activeKey}
onChange={onChange} onChange={onChange}
onEdit={onEdit} onEdit={onEdit}
> items={tabPanes}
{creatTabPanes()} />
</Tabs>
</div> </div>
) )
} }
......
...@@ -22,7 +22,7 @@ function wrapPromise(promise: Promise<any>) { ...@@ -22,7 +22,7 @@ function wrapPromise(promise: Promise<any>) {
err => { err => {
status = 'error' status = 'error'
response = err response = err
} },
) )
const handler = { const handler = {
...@@ -32,7 +32,7 @@ function wrapPromise(promise: Promise<any>) { ...@@ -32,7 +32,7 @@ function wrapPromise(promise: Promise<any>) {
error: () => { error: () => {
throw response throw response
}, },
default: () => response default: () => response,
} }
const read = () => { const read = () => {
...@@ -64,7 +64,7 @@ async function getInitialState() { ...@@ -64,7 +64,7 @@ async function getInitialState() {
userName: '', userName: '',
dbname: '', dbname: '',
dbName: '', dbName: '',
DBName: '' DBName: '',
} }
try { try {
curUser = JSON.parse(window.localStorage?.getItem('cpasUserInfo') ?? '') curUser = JSON.parse(window.localStorage?.getItem('cpasUserInfo') ?? '')
...@@ -89,12 +89,12 @@ async function getInitialState() { ...@@ -89,12 +89,12 @@ async function getInitialState() {
DBName: '202205188806-C00014', DBName: '202205188806-C00014',
sjxmbh: curDataPart.projectCode, sjxmbh: curDataPart.projectCode,
zcbfid: '202205188806-C00014', //组成部分编号 zcbfid zcbfid: '202205188806-C00014', //组成部分编号 zcbfid
ZcbfID: '202205188806-C00014' // 组成部分编号 (报告系统使用非驼峰写法字段) ZcbfID: '202205188806-C00014', // 组成部分编号 (报告系统使用非驼峰写法字段)
} }
// 修改本地session的存值 // 修改本地session的存值
const electronSession = { const electronSession = {
params: curPart, params: curPart,
session: 'persist:local' session: 'persist:local',
} }
window.sessionStorage.setItem('electronParams', JSON.stringify(electronSession)) window.sessionStorage.setItem('electronParams', JSON.stringify(electronSession))
const initialState = { const initialState = {
...@@ -102,7 +102,7 @@ async function getInitialState() { ...@@ -102,7 +102,7 @@ async function getInitialState() {
menuJson: menuJsonData, menuJson: menuJsonData,
curUser: curUser, curUser: curUser,
sysName: 'main', sysName: 'main',
curPart curPart,
} }
// 存储到session // 存储到session
createSessionStorage.set('@@initialState', initialState) createSessionStorage.set('@@initialState', initialState)
...@@ -111,15 +111,18 @@ async function getInitialState() { ...@@ -111,15 +111,18 @@ async function getInitialState() {
console.log('🚀 ~ file: main.tsx:69 ~ 初始化state成功:', initialState) console.log('🚀 ~ file: main.tsx:69 ~ 初始化state成功:', initialState)
return initialState return initialState
} }
// 统计初始化配置的时间
const start = performance.now()
const resource = wrapPromise(getInitialState()) const resource = wrapPromise(getInitialState())
const end = performance.now()
console.info('Initial State Cost time', `${end - start}ms`)
interface InitialProps { interface InitialProps {
children?: ReactElement children?: ReactElement
} }
const Initail: React.FC<InitialProps> = ({ children }) => { const Initial: React.FC<InitialProps> = ({ children }) => {
const data = resource.read() const data = resource.read()
console.log('🚀 ~ file: initial.tsx:119 ~ Initail ~ data:', data) console.log('🚀 ~ file: initial.tsx:119 ~ Initail ~ data:', data)
return <>{children}</> return <>{children}</>
} }
export default Initail export default Initial
...@@ -16,12 +16,12 @@ import { CheckCircleOutlined } from '@ant-design/icons' ...@@ -16,12 +16,12 @@ import { CheckCircleOutlined } from '@ant-design/icons'
import { getCurProjectInfo } from '@/services/csService' import { getCurProjectInfo } from '@/services/csService'
import { showSelectProjectInfoDialog } from '@/components/csDialog' import { showSelectProjectInfoDialog } from '@/components/csDialog'
import useGlobalStore from '@/store/global' import useGlobalStore from '@/store/global'
import { SmileOutlined, HeartOutlined, FrownOutlined } from '@ant-design/icons'
import type { MenuProps } from 'antd' import type { MenuProps } from 'antd'
import { MailOutlined } from '@ant-design/icons'
import type { Settings as LayoutSettings } from '@ant-design/pro-layout' import type { Settings as LayoutSettings } from '@ant-design/pro-layout'
import type { SizeType } from 'antd/es/config-provider/SizeContext' import type { SizeType } from 'antd/es/config-provider/SizeContext'
import type { InputRef } from 'antd' import type { InputRef } from 'antd'
import usetabStore from '@/store/tab'
import Nav from '@/components/Nav'
type MenuItem = Required<MenuProps>['items'][number] type MenuItem = Required<MenuProps>['items'][number]
// 登录路由,这个比较特殊 // 登录路由,这个比较特殊
...@@ -74,21 +74,18 @@ export function layoutLinks(initialState: InitState): React.ReactNode[] { ...@@ -74,21 +74,18 @@ export function layoutLinks(initialState: InitState): React.ReactNode[] {
{' '} {' '}
{projectInfo.projectCode || '请选择项目'} {projectInfo.projectCode || '请选择项目'}
</span> </span>
</Button> </Button>,
] ]
} }
export function getSysName(pathname: string): SysName { export function getSysName(pathname: string): SysName {
return pathname.startsWith('/audit/') ? 'audit' : 'main' return pathname.startsWith('/audit/') ? 'audit' : 'main'
} }
const IconMap: { [key: string]: React.ReactNode } = {
smile: <SmileOutlined />,
heart: <HeartOutlined />,
frown: <FrownOutlined />
}
const LayoutPage: React.FC = () => { const LayoutPage: React.FC = () => {
const { initialState } = useGlobalStore() const { initialState } = useGlobalStore()
const addtabs = usetabStore(state => state.addtabs)
const activeKey = usetabStore(state => state.activeKey)
const setActiveKey = usetabStore(state => state.setActiveKey)
const { menuJson: menuList = [] } = initialState const { menuJson: menuList = [] } = initialState
console.log('🚀 ~ file: index.tsx:150 ~ menuList:', menuList) console.log('🚀 ~ file: index.tsx:150 ~ menuList:', menuList)
...@@ -103,6 +100,13 @@ const LayoutPage: React.FC = () => { ...@@ -103,6 +100,13 @@ const LayoutPage: React.FC = () => {
} }
}, [navigate, location]) }, [navigate, location])
useEffect(() => {
if (activeKey) {
setPathname(activeKey)
navigate(activeKey)
}
}, [activeKey])
// const initMenuList = menu => { // const initMenuList = menu => {
// const MenuListAll: MenuChild[] = [] // const MenuListAll: MenuChild[] = []
// menu.forEach(m => { // menu.forEach(m => {
...@@ -124,7 +128,7 @@ const LayoutPage: React.FC = () => { ...@@ -124,7 +128,7 @@ const LayoutPage: React.FC = () => {
const m = menus.map(({ icon, children, ...item }) => ({ const m = menus.map(({ icon, children, ...item }) => ({
...item, ...item,
icon: icon && getIcon(icon), icon: icon && getIcon(icon),
children: children && loopMenuItem(children) children: children && loopMenuItem(children),
})) }))
return m return m
...@@ -141,7 +145,7 @@ const LayoutPage: React.FC = () => { ...@@ -141,7 +145,7 @@ const LayoutPage: React.FC = () => {
? { ? {
hide: true, hide: true,
headerHeight: 0, headerHeight: 0,
childrenRender: initialState && initialState?.curUser ? MicroPage : undefined childrenRender: initialState && initialState?.curUser ? MicroPage : undefined,
} }
: {} : {}
// const menuItems: MenuItem[] = parseMenu(reduceRoute(menuJson)) // const menuItems: MenuItem[] = parseMenu(reduceRoute(menuJson))
...@@ -160,7 +164,7 @@ const LayoutPage: React.FC = () => { ...@@ -160,7 +164,7 @@ const LayoutPage: React.FC = () => {
links: layoutLinks(initialState), links: layoutLinks(initialState),
// 水印 // 水印
waterMarkProps: { waterMarkProps: {
content: initialState?.curUser?.usercode content: initialState?.curUser?.usercode,
}, },
// siderWidth: typeof SIDER_WIDTH !== 'undefined' ? SIDER_WIDTH : 208, // siderWidth: typeof SIDER_WIDTH !== 'undefined' ? SIDER_WIDTH : 208,
//siderWidth: initialState && initialState.siderWidth === 0 ? 0 : 208, //siderWidth: initialState && initialState.siderWidth === 0 ? 0 : 208,
...@@ -168,13 +172,14 @@ const LayoutPage: React.FC = () => { ...@@ -168,13 +172,14 @@ const LayoutPage: React.FC = () => {
// headerHeight: 43, // 48->43解决最外层有滚动条的问题 add by csb 20230221 // headerHeight: 43, // 48->43解决最外层有滚动条的问题 add by csb 20230221
headerHeight: 0, // 去掉logo,这里直接设置为0. add by szh 20230905 headerHeight: 0, // 去掉logo,这里直接设置为0. add by szh 20230905
childrenRender: initialState && initialState?.curUser ? PageTab : undefined, childrenRender: initialState && initialState?.curUser ? PageTab : undefined,
// childrenRender: initialState && initialState?.curUser ? Nav : undefined,
rightContentRender: () => <RightContent />, //不要皮肤\登录\等信息 rightContentRender: () => <RightContent />, //不要皮肤\登录\等信息
// links: layoutLinks(), // links: layoutLinks(),
menuHeaderRender: undefined, menuHeaderRender: undefined,
// 自定义 403 页面 // 自定义 403 页面
unAccessible: <div>unAccessible</div>, unAccessible: <div>unAccessible</div>,
...inPlatformLayout, ...inPlatformLayout,
...isMicroPageLayout ...isMicroPageLayout,
} }
console.log('🚀 ~ file: LayoutConfig.tsx:197 ~ layoutSetting:', layoutSetting) console.log('🚀 ~ file: LayoutConfig.tsx:197 ~ layoutSetting:', layoutSetting)
...@@ -191,13 +196,22 @@ const LayoutPage: React.FC = () => { ...@@ -191,13 +196,22 @@ const LayoutPage: React.FC = () => {
const { sjxmbh, ZcbfID } = sessionParams.params const { sjxmbh, ZcbfID } = sessionParams.params
const password = window.main.cryptoUtil(userInfo.aesPassword) const password = window.main.cryptoUtil(userInfo.aesPassword)
console.log( console.log(
`cpas://OpenLocalFile/?fileName=${path}&params=UserCode=${userCode} UserPwd=${password} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID}&workDir=./SysBPL` `cpas://OpenLocalFile/?fileName=${path}&params=UserCode=${userCode} UserPwd=${password} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID}&workDir=./SysBPL`,
) )
window.location.href = `cpas://OpenLocalFile/?fileName=${path}&params=UserCode=${userCode} UserPwd=${password} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID}&workDir=./SysBPL` window.location.href = `cpas://OpenLocalFile/?fileName=${path}&params=UserCode=${userCode} UserPwd=${password} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID}&workDir=./SysBPL`
} else { } else {
console.error('window["electronComponents"] false') console.error('window["electronComponents"] false')
} }
} else { } else {
// 添加到
addtabs({
key: params.key,
path: params.path,
closable: params.closable,
label: params.name,
element: params.element,
})
setActiveKey(params.key)
navigate(params?.path) navigate(params?.path)
} }
} }
...@@ -205,7 +219,7 @@ const LayoutPage: React.FC = () => { ...@@ -205,7 +219,7 @@ const LayoutPage: React.FC = () => {
<ProLayout <ProLayout
{...Settings} {...Settings}
location={{ location={{
pathname pathname,
}} }}
breadcrumbRender={undefined} breadcrumbRender={undefined}
onPageChange={params => { onPageChange={params => {
...@@ -226,9 +240,8 @@ const LayoutPage: React.FC = () => { ...@@ -226,9 +240,8 @@ const LayoutPage: React.FC = () => {
{...layoutSetting} {...layoutSetting}
menuDataRender={() => loopMenuItem(menuList)} menuDataRender={() => loopMenuItem(menuList)}
> >
{/* <PageContainer> */} <Nav></Nav>
<Outlet /> {/* <Outlet /> */}
{/* </PageContainer> */}
</ProLayout> </ProLayout>
) )
} }
......
...@@ -4,18 +4,18 @@ import { HashRouter } from 'react-router-dom' ...@@ -4,18 +4,18 @@ import { HashRouter } from 'react-router-dom'
import App from './App' import App from './App'
import SuspenceFallbackLoading from '@/layout/suspenceFallback' import SuspenceFallbackLoading from '@/layout/suspenceFallback'
import Initail from './initial' import Initial from './initial'
import './app.less' import './app.less'
const root = document.getElementById('root') as HTMLElement const root = document.getElementById('root') as HTMLElement
ReactDOM.createRoot(root).render( ReactDOM.createRoot(root).render(
// <React.StrictMode> // <React.StrictMode>
<Suspense fallback={<SuspenceFallbackLoading></SuspenceFallbackLoading>}> <Suspense fallback={<SuspenceFallbackLoading></SuspenceFallbackLoading>}>
<Initail> <Initial>
<HashRouter> <HashRouter>
<App /> <App />
</HashRouter> </HashRouter>
</Initail> </Initial>
</Suspense> </Suspense>
// </React.StrictMode> // </React.StrictMode>
) )
import { useState, useEffect, useContext, useMemo } from 'react';
import { Tabs, Menu, Button } from 'antd';
import type { MenuProps } from 'antd';
import { history } from 'umi';
import { mainRenderer } from '@/utils/electronUtil';
import { APP_NAME, getQueryParams } from '@/utils';
import { createMicroPageUrl } from '@/utils/pub';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
type MenuItem = Required<MenuProps>['items'][number];
export const getDetailMenus = () => [
{
key: 'statementData',
label: '报表项目基础数据',
url: createMicroPageUrl('/ReportSys/StatementData'),
},
{
key: 'unFinancialStatements',
label: '未审财务报表',
url: createMicroPageUrl('/ReportSys/unFinancialStatements'),
},
{
label: '审定财务报表',
key: 'approvedFinance',
url: createMicroPageUrl('/ReportSys/approvedFinance'),
},
];
export interface BalanceDetailProps { }
const creatTabPanes = () => {
return getDetailMenus().map((item, index) => {
const key = String(index);
return (
<Tabs.TabPane tab={item.label} key={key}>
<h5>我是展位符</h5>
</Tabs.TabPane>
);
});
};
const items: MenuProps['items'] = [
{
label: '报表项目基础数据',
key: '0',
},
{
label: '未审报表',
key: 'sub1',
children: [
{
label: '未审报表',
key: '1',
},
{
label: '未审报表',
key: '2',
},
{
label: '未审报表',
key: '3',
},
],
},
{
label: 'TB汇总',
key: 'sub2',
children: [
{
label: 'TB',
key: '4',
},
],
},
];
// submenu keys of first level
const rootSubmenuKeys = ['sub1', 'sub2', 'sub4'];
const BalanceDetail: React.FC<BalanceDetailProps> = () => {
const search = getQueryParams(history.location.search);
const { groupId = '' } = search;
const [collapsed, setCollapsed] = useState(true);
const [inlineIndent, setInlineIndent] = useState(10);
const toggleCollapsed = () => {
// setCollapsed(!collapsed);
};
const onClick: MenuProps['onClick'] = (e) => {
console.log('click ', e);
const activeKey = e.key;
mainRenderer('updateBalance', {
id: groupId,
appName: APP_NAME,
activeInx: Number(activeKey),
});
};
function onChange(activeKey: string) {
mainRenderer('updateBalance', {
id: groupId,
appName: APP_NAME,
activeInx: Number(activeKey),
});
}
return (
<div className="h-screen px-4">
{/* <Button type="primary" onClick={toggleCollapsed} style={{ marginBottom: 16 }}>
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</Button> */}
<Tabs onChange={onChange}>{creatTabPanes()}</Tabs>
{/* <Menu
mode="inline"
onClick={onClick}
items={items}
/> */}
</div>
);
};
export default BalanceDetail;
import React from 'react';
interface ApprovedFinancialStatementsProps {}
const ApprovedFinancialStatements: React.FC<ApprovedFinancialStatementsProps> = (props) => {
return (
<div>
<h1>审定报表</h1>
</div>
);
};
export default ApprovedFinancialStatements;
import React from 'react';
interface RelatedTransactionsProps {}
const RelatedTransactions: React.FC<RelatedTransactionsProps> = (props) => {
return <div />;
};
export default RelatedTransactions;
import React from 'react';
interface ReportGenerationProps {}
const ReportGeneration: React.FC<ReportGenerationProps> = (props) => {
// 组件实现
// ...
return (
<div>
<h1>报告生成</h1>
</div>
);
};
export default ReportGeneration;
export default function TBSummary() {
return <h1>TB 汇总</h1>;
}
export default function UnauditedFinancialStatements() {
return <>我是未审财务报表React组件页面</>;
}
export enum ReportType {
BaseData = 'baseData',
UnapprovedFinancialStatements = 'unapprovedFinancialStatements',
TBSummary = 'tbSummary',
RelatedTransactions = 'relatedTransactions',
ApprovedFinancialStatements = 'approvedFinancialStatements',
ReportGeneration = 'reportGeneration',
}
export const MergeMenus = [
{
label: '报表基础数据',
key: ReportType.BaseData,
},
{
label: '未审报表',
key: 'SubMenu',
children: [
{
label: '未审财务报表',
key: ReportType.UnapprovedFinancialStatements,
},
],
},
{
label: 'TB汇总',
key: ReportType.TBSummary,
},
{
label: '长投及关联交易',
key: ReportType.RelatedTransactions,
},
{
label: '审定报表',
key: ReportType.ApprovedFinancialStatements,
},
{
label: '报告生成',
key: ReportType.ReportGeneration,
},
];
import React, { useEffect, useMemo, useState } from 'react';
import BaseData from '../BaseData';
import UnapprovedFinancialStatements from './UnauditedFinancialStatements';
import { Tabs } from 'antd';
import WebFrame from '@/pages/web_frame';
import { createMicroPageUrl } from '@/utils/pub';
import { history } from 'umi';
interface MergeMainProps {}
export const MergeMenus = [
{
key: 'groupStructure',
label: <span>集团组织架构</span>,
url: '/groupStructure',
},
{
key: 'ac6',
label: (
<span>
IAS函证工具<em className="text-blue-500">(一层标签)</em>
</span>
),
// children: <RelatedTransactions />,
url: 'http://192.168.0.100:8086/cpas-cloud/ac6/?hideHeader=1',
},
];
const creatTabPanes = () => {
return MergeMenus.map((item) => {
return (
<Tabs.TabPane tab={item.label} key={item.key}>
{item.url ? (
<>
<WebFrame>
<iframe
src={createMicroPageUrl(item.url)}
style={{ height: 500, width: '100%', border: 'none' }}
/>
</WebFrame>
</>
) : (
item?.children || ''
)}
</Tabs.TabPane>
);
});
};
const MergeMain: React.FC<MergeMainProps> = (props) => {
const query = history.location.query;
console.log('🚀 ~ file: index.tsx:56 ~ history:', history.location);
return <Tabs>{creatTabPanes()}</Tabs>;
};
export default MergeMain;
import React, { useEffect } from 'react';
interface BaseDataProps {
// 属性类型定义
// ...
}
const BaseData: React.FC<BaseDataProps> = (props) => {
return (
<div>
<h3>我是React组件页面</h3>
{/* JSX 结构 */}
{/* ... */}
</div>
);
};
export default BaseData;
import React from 'react';
interface RelatedTransactionsProps {
// 属性类型定义
// ...
}
const RelatedTransactions: React.FC<RelatedTransactionsProps> = (props) => {
// 组件实现
// ...
return (
<div>
<h3>我是React组件页面</h3>
{/* JSX 结构 */}
{/* ... */}
</div>
);
};
export default RelatedTransactions;
import React from 'react';
interface AnnotationProps {
// 属性类型定义
// ...
}
const Annotation: React.FC<AnnotationProps> = (props) => {
// 组件实现
// ...
return (
<div>
<h3>我是附注React组件页面</h3>
{/* JSX 结构 */}
{/* ... */}
</div>
);
};
export default Annotation;
import React from 'react';
interface OffsetAdjustmentProps {
// 属性类型定义
// ...
}
const OffsetAdjustment: React.FC<OffsetAdjustmentProps> = (props) => {
// 组件实现
// ...
return (
<div>
<h3>我是调整抵消React组件页面</h3>
{/* JSX 结构 */}
{/* ... */}
</div>
);
};
export default OffsetAdjustment;
import { useState, useEffect, useContext, useMemo } from 'react';
import { Tabs } from 'antd';
import WebFrame from '@/pages/web_frame';
import { createMicroPageUrl } from '@/utils/pub';
// import NavigationBar from '@/pages/components/NavigationBar';
import { history } from 'umi';
import OffsetAdjustment from './OffsetAdjustment';
import Annotation from './Annotation';
export const TBMenus = [
{
key: 'ac6',
label: 'IAS函证工具',
url: 'http://192.168.0.100:8086/cpas-cloud/ac6/?hideHeader=1',
},
{
key: 'OffsetAdjustment',
label: '调整抵消',
children: <OffsetAdjustment />,
},
{
key: 'AnnotationPenetration',
label: '附注穿透',
url: 'https://juejin.cn/course',
},
{
key: 'Annotation',
label: (
<span>
附注<em className="text-blue-500">(二层标签)</em>
</span>
),
children: <Annotation />,
},
];
export interface UnitMainProps {}
const creatTabPanes = () => {
return TBMenus.map((item) => {
return (
<Tabs.TabPane tab={item.label} key={item.key}>
{item.url ? (
<>
<WebFrame>
<iframe
src={createMicroPageUrl(item.url)}
style={{ height: 500, width: '100%', border: 'none' }}
/>
</WebFrame>
</>
) : (
item?.children || ''
)}
</Tabs.TabPane>
);
});
};
// 单体
const TBMain: React.FC<UnitMainProps> = (props) => {
// const { currentGroupInfo } = useGroupParamsContext();
const query = history.location.query;
console.log('🚀 ~ file: index.tsx:56 ~ history:', history.location);
return <Tabs>{creatTabPanes()}</Tabs>;
};
export default TBMain;
export enum ReportType {
BaseData = '报表基础数据',
TB = 'TB',
RelatedTransactions = '关联交易',
}
export enum TBRootType {
TB = 'TB',
AnnotationPenetration = '附注穿透',
OffsetAdjustment = '调整抵消',
Annotation = '附注',
}
export const UnitMenus = [
{
label: '报表基础数据',
key: ReportType.BaseData,
},
{
label: 'TB',
key: ReportType.TB,
},
{
label: '关联交易',
key: ReportType.RelatedTransactions,
},
];
import { useState, useEffect, useContext, useMemo } from 'react';
import BaseData from './BaseData'; // 报表基础数据
import RelatedTransactions from './RelatedTransactions'; //
// import { useGroupParamsContext } from '../hooks/useGroupParamsContext';
// import NavigationBar from '@/pages/components/NavigationBar';
export const UnitMenus = (groupId) => {
return [
{
key: 'BaseData',
label: '报表基础数据',
children: <BaseData />,
},
{
key: 'TB',
label: 'TB',
url: `/mircopage/TB?groupId=${groupId}`,
},
{
key: 'RelatedTransactions',
label: '关联交易',
children: <RelatedTransactions />,
},
];
};
export interface UnitMainProps {}
const UnitMain: React.FC<UnitMainProps> = (props) => {
return <div />;
};
export default UnitMain;
import { useState, useEffect, useContext, useMemo } from 'react';
import BaseData from './BaseData'; // 报表基础数据
import RelatedTransactions from './RelatedTransactions'; // 关联交易
import TB from './TB'; // 关联交易
import { Tabs } from 'antd';
import { useGroupParamsContext } from '../hooks/useGroupParamsContext';
import WebFrame from '@/pages/web_frame';
import { createMicroPageUrl } from '@/utils/pub';
// import NavigationBar from '@/pages/components/NavigationBar';
import { history } from 'umi';
export const UnitMenus = [
{
key: 'BaseData',
label: '报表基础数据',
children: <BaseData />,
},
{
key: 'TB',
label: 'TB汇总',
children: <TB />,
},
{
key: 'RelatedTransactions',
label: (
<span>
关联交易<em className="text-blue-600">(一层标签)</em>
</span>
),
children: <RelatedTransactions />,
},
];
export interface UnitMainProps {}
const creatTabPanes = () => {
return UnitMenus.map((item) => {
return (
<Tabs.TabPane tab={item.label} key={item.key}>
{item.url ? (
<>
<WebFrame>
<iframe
src={createMicroPageUrl(item.url)}
style={{ height: 500, width: '100%', border: 'none' }}
/>
</WebFrame>
</>
) : (
item?.children || ''
)}
</Tabs.TabPane>
);
});
};
// 单体
const UnitMain: React.FC<UnitMainProps> = (props) => {
// const { currentGroupInfo } = useGroupParamsContext();
const query = history.location.query;
console.log('🚀 ~ file: index.tsx:56 ~ history:', history.location);
return <Tabs>{creatTabPanes()}</Tabs>;
};
export default UnitMain;
const prefix = '__GROUPINFO__';
const project = 'COMBINE';
export const GROUPINFO = project + prefix;
export const mergeTypeValue = {
1: '合并层',
2: '差异表',
3: '母分合并',
4: '分公司',
5: '子公司',
6: '本级',
};
import React, { createContext, useContext } from 'react';
interface GroupParamsContextProps {
queryParams: Record<string, string | undefined>;
currentGroupInfo: Record<string, string | undefined>;
setQueryParams: (newParams: Record<string, string | undefined>) => void;
}
export const GroupParamsContext = createContext<GroupParamsContextProps>({
queryParams: {},
currentGroupInfo: {},
setQueryParams: () => {},
});
export const useGroupParamsContext = () => {
return useContext(GroupParamsContext);
};
This diff is collapsed.
This diff is collapsed.
export const ds = [
{ ID: '1', expanded: true, name: 'Stores' },
{ ID: '1_1', categoryId: '1', expanded: true, name: 'Super Mart of the West' },
{ ID: '1_1_1', categoryId: '1_1', name: 'Video Players' },
{
ID: '1_1_1_1',
categoryId: '1_1_1',
icon: 'icon-queren',
name: 'HD Video Player',
price: 220,
},
{
ID: '1_1_1_2',
categoryId: '1_1_1',
icon: 'icon-queren',
name: 'SuperHD Video Player',
price: 270,
},
{ ID: '1_1_2', categoryId: '1_1', expanded: true, name: 'Televisions' },
{
ID: '1_1_2_1',
categoryId: '1_1_2',
icon: 'icon-zidong',
name: 'SuperLCD 42',
price: 1200,
},
{
ID: '1_1_2_2',
categoryId: '1_1_2',
icon: 'icon-zidong',
name: 'SuperLED 42',
price: 1450,
},
{
ID: '1_1_2_3',
categoryId: '1_1_2',
icon: 'icon-zidong',
name: 'SuperLED 50',
price: 1600,
},
{
ID: '1_1_2_4',
categoryId: '1_1_2',
icon: 'icon-zidong',
name: 'SuperLCD 55',
price: 1750,
},
{
ID: '1_1_2_5',
categoryId: '1_1_2',
icon: 'icon-zidong',
name: 'SuperLCD 70',
price: 4000,
},
{ ID: '1_1_3', categoryId: '1_1', name: 'Monitors' },
{ ID: '1_1_3_1', categoryId: '1_1_3', name: '19"' },
{
ID: '1_1_3_1_1',
categoryId: '1_1_3_1',
icon: 'icon-queren',
name: 'DesktopLCD 19',
price: 160,
},
{ ID: '1_1_4', categoryId: '1_1', name: 'Projectors' },
{
ID: '1_1_4_1',
categoryId: '1_1_4',
icon: 'icon-queren',
name: 'Projector Plus',
price: 550,
},
{
ID: '1_1_4_2',
categoryId: '1_1_4',
icon: 'icon-queren',
name: 'Projector PlusHD',
price: 750,
},
];
export type QueryParamsType = {
category?: string;
[propName: string]: any;
};
import React from 'react' import React from 'react'
import MainRouter, { getAllRoutes, reduceRoute } from './routes' import MainRouter, { getAllRoutes, reduceRoute, routeMap } from './routes'
export { getAllRoutes, reduceRoute, MainRouter } export { getAllRoutes, reduceRoute, MainRouter, routeMap }
import React, { lazy, ReactElement } from 'react' import React, { lazy, ReactElement, useMemo } from 'react'
import { Navigate, useRoutes, RouteProps, Link, Outlet } from 'react-router-dom' import { Navigate, useRoutes, RouteProps, Link, Outlet } from 'react-router-dom'
import ErrorPage from '@/ErrorPage'
import Login from '@/pages/user/Login'
import LayoutPage from '@/layout' import LayoutPage from '@/layout'
import { SmileFilled } from '@ant-design/icons' import { SmileFilled } from '@ant-design/icons'
import { createSessionStorage } from '@/utils/Storage' import { createSessionStorage } from '@/utils/Storage'
import WrapperRouteComponent from './config' import WrapperRouteComponent from './config'
import { AudTabPage } from '@/components/PageTab' // 账户
import Login from '@/pages/user/Login'
const NotFound = lazy(() => import('@/pages/404'))
const ChangePassword = lazy(() => import('../pages/user/ChangePd')) const ChangePassword = lazy(() => import('../pages/user/ChangePd'))
//异常组件
export const NotFound = lazy(() => import('@/pages/404'))
import ErrorPage from '@/ErrorPage'
// 业务
const Home = lazy(() => import('@/pages/home'))
const GroupStructure = lazy(() => import('@/pages/groupStructure'))
const ReportSys = lazy(() => import('@/pages/reportSys'))
const StatementData = lazy(() => import('@/pages/statementData'))
const UnFinancialStatements = lazy(() => import('@/pages/unFinancialStatements'))
const TrialBalance = lazy(() => import('@/pages/trialBalance'))
const AuditAdjust = lazy(() => import('@/pages/auditAdjust'))
const AccountAdjust = lazy(() => import('@/pages/accountAdjust'))
const ReportAnalysis = lazy(() => import('@/pages/reportAnalysis'))
const ApprovedFinance = lazy(() => import('@/pages/approvedFinance'))
const FinancialStatementsCheck = lazy(() => import('@/pages/financialStatementsCheck'))
const InternalTran = lazy(() => import('@/pages/internalTran'))
const ReportBuilder = lazy(() => import('@/pages/reportBuilder'))
const EntriesSummary = lazy(() => import('@/pages/entriesSummary'))
const DetailsSummary = lazy(() => import('@/pages/detailsSummary'))
const CorrespondenceStatistics = lazy(() => import('@/pages/correspondenceStatistics'))
// 路由枚举
export const routeMap: Record<string, React.LazyExoticComponent<any>> = {
Home,
GroupStructure,
ReportSys,
StatementData,
UnFinancialStatements,
TrialBalance,
AuditAdjust,
AccountAdjust,
ReportAnalysis,
ApprovedFinance,
FinancialStatementsCheck,
InternalTran,
ReportBuilder,
EntriesSummary,
DetailsSummary,
CorrespondenceStatistics,
}
export type RouteItemType = RouteProps & { export type RouteItemType = RouteProps & {
type?: string type?: string
...@@ -21,19 +57,6 @@ export type RouteItemType = RouteProps & { ...@@ -21,19 +57,6 @@ export type RouteItemType = RouteProps & {
element: RouteProps['element'] | string element: RouteProps['element'] | string
} }
// 路由样例
// {
// "path": "/groupStructure",
// "name": "集团架构",
// "element": "",
// "meta": {
// "icon": ""
// "title: '",
// "type": "component",
// "closable": false,
// "hideInMenu": true
// }
// }
export const reduceRoute: (params: any[]) => any[] = (routes: RouteItemType[]) => { export const reduceRoute: (params: any[]) => any[] = (routes: RouteItemType[]) => {
return routes.map(item => { return routes.map(item => {
const route = item const route = item
...@@ -45,25 +68,14 @@ export const reduceRoute: (params: any[]) => any[] = (routes: RouteItemType[]) = ...@@ -45,25 +68,14 @@ export const reduceRoute: (params: any[]) => any[] = (routes: RouteItemType[]) =
if (React.isValidElement(item.element)) { if (React.isValidElement(item.element)) {
route.element = item.element route.element = item.element
} else { } else {
// element 为字符串的情况,例如element: "Home", 首字母需要大写 let element = item.element as string
// 推荐大写,但有可能传入的大小写都有,这里尝试都加载。 element = element.slice(0, 1).toUpperCase() + element.slice(1)
let Element = null const Element = routeMap[element]
try { route.element = React.isValidElement(<Element />) ? <Element /> : <NotFound />
const LowercaseName =
(item.element as string).slice(0, 1).toLowerCase() + (item.element as string).slice(1)
Element = lazy(() => import(`@/pages/${LowercaseName}/index.tsx`))
} catch (error) {
try {
const UppercaseName =
(item.element as string).slice(0, 1).toUpperCase() + (item.element as string).slice(1)
Element = lazy(() => import(`@/pages/${UppercaseName}/index.tsx`))
} catch (error) {}
}
route.element = Element && <Element />
} }
} else { } else {
// element不存在的情况 // element不存在的情况
route.element = <></> route.element = <NotFound />
} }
if (item?.redirect) { if (item?.redirect) {
route.element = <Navigate to={item.redirect}></Navigate> route.element = <Navigate to={item.redirect}></Navigate>
...@@ -82,23 +94,23 @@ export const routeList: RouteItemType[] = [ ...@@ -82,23 +94,23 @@ export const routeList: RouteItemType[] = [
), ),
errorElement: <ErrorPage />, errorElement: <ErrorPage />,
icon: <SmileFilled />, icon: <SmileFilled />,
children: [] children: [],
}, },
{ {
path: '/login', path: '/login',
name: '登录', name: '登录',
element: <Login /> element: <Login />,
}, },
{ {
path: '*', path: '*',
element: <NotFound /> element: <NotFound />,
} },
] ]
// 获取主路由 // 获取主路由
export function getAllRoutes(routes: any) { export function getAllRoutes(routes: any) {
const { menuJson = [] } = createSessionStorage.get('@@initialState') || { const { menuJson = [] } = createSessionStorage.get('@@initialState') || {
menuJson: [] menuJson: [],
} }
const dynamicRoutes = reduceRoute(menuJson) || [] const dynamicRoutes = reduceRoute(menuJson) || []
routes.forEach(route => { routes.forEach(route => {
...@@ -107,8 +119,8 @@ export function getAllRoutes(routes: any) { ...@@ -107,8 +119,8 @@ export function getAllRoutes(routes: any) {
{ {
path: '/changePassword', path: '/changePassword',
name: 'changePassword', name: 'changePassword',
element: <ChangePassword /> element: <ChangePassword />,
} },
]) ])
} }
}) })
...@@ -116,7 +128,9 @@ export function getAllRoutes(routes: any) { ...@@ -116,7 +128,9 @@ export function getAllRoutes(routes: any) {
} }
export default function MainRouter() { export default function MainRouter() {
const allRoutes = getAllRoutes(routeList) const allRoutes = useMemo(() => {
return getAllRoutes(routeList)
}, [routeList])
console.log('🚀 ~ file: routes.tsx:121 ~ MainRouter ~ allRoutes:', allRoutes) console.log('🚀 ~ file: routes.tsx:121 ~ MainRouter ~ allRoutes:', allRoutes)
const element = useRoutes(allRoutes) const element = useRoutes(allRoutes)
return element return element
......
// refer https://github.com/pmndrs/zustand // refer https://github.com/pmndrs/zustand
import { create } from 'zustand' import { create } from 'zustand'
import { devtools, persist, createJSONStorage } from 'zustand/middleware' import { devtools, persist, createJSONStorage } from 'zustand/middleware'
import path from 'path'
type Store = { type Store = {
votes: any[] tabs: any[]
activeKey: any activeKey: any
} }
type Actions = { type Actions = {
getActiveVote: () => any getActivetab: () => any
addVotes: (vote: any) => void addtabs: (tab: any) => void
deleteVotes: (key: any) => void deletetabs: (key: any) => void
setActiveKey: (activeKey: any) => void setActiveKey: (activeKey: any) => void
} }
const voteStore = (set, get) => ({ const tabStore = (set, get) => ({
votes: [], tabs: [],
activeKey: '', activeKey: '',
getActiveVote: () => { getActivetab: () => {
const votes = get().votes const tabs = get().tabs
const activeKey = get().activeKey const activeKey = get().activeKey
const filterArr = votes.filter(vote => vote.key === activeKey) const filterArr = tabs.filter(tab => tab.path === activeKey)
return filterArr.length > 0 ? filterArr[0].originData : null return filterArr.length > 0 ? filterArr[0].originData : null
}, },
setActiveKey: activeKey => setActiveKey: activeKey =>
set(state => ({ set(state => ({
activeKey activeKey
})), })),
addVotes: vote => addtabs: tab =>
set(state => { set(state => {
const existIndex = state.votes.findIndex(item => item.key === vote.key) const existIndex = state.tabs.findIndex(item => item.path === tab.key)
if (existIndex === -1) { if (existIndex === -1) {
return { votes: [...state.votes, vote] } return { tabs: [...state.tabs, tab] }
} }
return { votes: [...state.votes] } return { tabs: [...state.tabs] }
}), }),
deleteVotes: key => deletetabs: key =>
set(state => { set(state => {
const existIndex = state.votes.findIndex(item => item.key === key) const existIndex = state.tabs.findIndex(item => item.path === key)
if (existIndex === -1) { if (existIndex === -1) {
return { votes: [...state.votes] } return { tabs: [...state.tabs] }
} }
state.votes.splice(existIndex, 1) state.tabs.splice(existIndex, 1)
return { votes: [...state.votes] } return { tabs: [...state.tabs] }
}) })
}) })
const useVoteStore = create<Store & Actions & any>()( const usetabStore = create<Store & Actions & any>()(
devtools( devtools(
persist(voteStore, { persist(tabStore, {
name: 'vote-storage', // name of the item in the storage (must be unique) name: 'tab-storage', // name of the item in the storage (must be unique)
storage: createJSONStorage(() => sessionStorage) // (optional) by default, 'localStorage' is used storage: createJSONStorage(() => sessionStorage) // (optional) by default, 'localStorage' is used
}) })
) )
) )
export default useVoteStore export default usetabStore
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment