This commit is contained in:
archer
2023-07-25 21:53:26 +08:00
parent c5f50b65c9
commit b367082d38
25 changed files with 230 additions and 276 deletions

View File

@@ -0,0 +1,83 @@
import React from 'react';
import {
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalBody,
Flex,
Box,
Table,
Thead,
Tbody,
Tr,
Th,
Td,
TableContainer
} from '@chakra-ui/react';
import { UserBillType } from '@/types/user';
import dayjs from 'dayjs';
import { BillSourceMap } from '@/constants/user';
import { formatPrice } from '@/utils/user';
const BillDetail = ({ bill, onClose }: { bill: UserBillType; onClose: () => void }) => {
return (
<Modal isOpen={true} onClose={onClose} isCentered>
<ModalOverlay />
<ModalContent minW={'min(90vw,600px)'}>
<ModalHeader></ModalHeader>
<ModalBody>
<Flex alignItems={'center'} pb={4}>
<Box flex={'0 0 80px'}>:</Box>
<Box>{bill.id}</Box>
</Flex>
<Flex alignItems={'center'} pb={4}>
<Box flex={'0 0 80px'}>:</Box>
<Box>{dayjs(bill.time).format('YYYY/MM/DD HH:mm:ss')}</Box>
</Flex>
<Flex alignItems={'center'} pb={4}>
<Box flex={'0 0 80px'}>:</Box>
<Box>{bill.appName}</Box>
</Flex>
<Flex alignItems={'center'} pb={4}>
<Box flex={'0 0 80px'}>:</Box>
<Box>{BillSourceMap[bill.source]}</Box>
</Flex>
<Flex alignItems={'center'} pb={4}>
<Box flex={'0 0 80px'}>:</Box>
<Box fontWeight={'bold'}>{bill.total}</Box>
</Flex>
<Box pb={4}>
<Box flex={'0 0 80px'} mb={1}>
</Box>
<TableContainer>
<Table>
<Thead>
<Tr>
<Th></Th>
<Th>AI模型</Th>
<Th>Token长度</Th>
<Th></Th>
</Tr>
</Thead>
<Tbody>
{bill.list.map((item, i) => (
<Tr key={i}>
<Td>{item.moduleName}</Td>
<Td>{item.model}</Td>
<Td>{item.tokenLen}</Td>
<Td>{formatPrice(item.amount)}</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
</Box>
</ModalBody>
</ModalContent>
</Modal>
);
};
export default BillDetail;

View File

@@ -0,0 +1,108 @@
import React, { useState } from 'react';
import {
Table,
Thead,
Tbody,
Tr,
Th,
Td,
TableContainer,
Flex,
Box,
Button
} from '@chakra-ui/react';
import { BillSourceMap } from '@/constants/user';
import { getUserBills } from '@/api/user';
import type { UserBillType } from '@/types/user';
import { usePagination } from '@/hooks/usePagination';
import { useLoading } from '@/hooks/useLoading';
import dayjs from 'dayjs';
import MyIcon from '@/components/Icon';
import DateRangePicker, { type DateRangeType } from '@/components/DateRangePicker';
import { addDays } from 'date-fns';
import dynamic from 'next/dynamic';
import { useGlobalStore } from '@/store/global';
const BillDetail = dynamic(() => import('./BillDetail'));
const BillTable = () => {
const { Loading } = useLoading();
const [dateRange, setDateRange] = useState<DateRangeType>({
from: addDays(new Date(), -7),
to: new Date()
});
const { isPc } = useGlobalStore();
const {
data: bills,
isLoading,
Pagination,
getData
} = usePagination<UserBillType>({
api: getUserBills,
pageSize: isPc ? 20 : 10,
params: {
dateStart: dateRange.from || new Date(),
dateEnd: addDays(dateRange.to || new Date(), 1)
}
});
const [billDetail, setBillDetail] = useState<UserBillType>();
return (
<Flex flexDirection={'column'} py={[0, 5]} h={'100%'} position={'relative'}>
<TableContainer px={[3, 8]} position={'relative'} flex={'1 0 0'} h={0} overflowY={'auto'}>
<Table>
<Thead>
<Tr>
<Th></Th>
<Th></Th>
<Th></Th>
<Th></Th>
<Th></Th>
</Tr>
</Thead>
<Tbody fontSize={'sm'}>
{bills.map((item) => (
<Tr key={item.id}>
<Td>{dayjs(item.time).format('YYYY/MM/DD HH:mm:ss')}</Td>
<Td>{BillSourceMap[item.source]}</Td>
<Td>{item.appName || '-'}</Td>
<Td>{item.total}</Td>
<Td>
<Button size={'sm'} variant={'base'} onClick={() => setBillDetail(item)}>
</Button>
</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
{!isLoading && bills.length === 0 && (
<Flex flex={'1 0 0'} flexDirection={'column'} alignItems={'center'}>
<MyIcon name="empty" w={'48px'} h={'48px'} color={'transparent'} />
<Box mt={2} color={'myGray.500'}>
使~
</Box>
</Flex>
)}
<Flex w={'100%'} mt={4} px={[3, 8]} alignItems={'center'} justifyContent={'flex-end'}>
<DateRangePicker
defaultDate={dateRange}
position="top"
onChange={setDateRange}
onSuccess={() => getData(1)}
/>
<Box ml={3}>
<Pagination />
</Box>
</Flex>
<Loading loading={isLoading} fixed={false} />
{!!billDetail && <BillDetail bill={billDetail} onClose={() => setBillDetail(undefined)} />}
</Flex>
);
};
export default BillTable;

View File

@@ -0,0 +1,139 @@
import React, { useCallback } from 'react';
import { Box, Flex, Button, useDisclosure } from '@chakra-ui/react';
import { useForm } from 'react-hook-form';
import { UserUpdateParams } from '@/types/user';
import { putUserInfo } from '@/api/user';
import { useToast } from '@/hooks/useToast';
import { useGlobalStore } from '@/store/global';
import { useUserStore } from '@/store/user';
import { UserType } from '@/types/user';
import { useRouter } from 'next/router';
import { useQuery } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
import { useSelectFile } from '@/hooks/useSelectFile';
import { compressImg } from '@/utils/file';
import { getErrText } from '@/utils/tools';
import { feConfigs } from '@/store/static';
import Loading from '@/components/Loading';
import Avatar from '@/components/Avatar';
const PayModal = dynamic(() => import('./PayModal'), {
loading: () => <Loading fixed={false} />,
ssr: false
});
const UserInfo = () => {
const router = useRouter();
const { userInfo, updateUserInfo, initUserInfo } = useUserStore();
const { setLoading } = useGlobalStore();
const { reset } = useForm<UserUpdateParams>({
defaultValues: userInfo as UserType
});
const { toast } = useToast();
const {
isOpen: isOpenPayModal,
onClose: onClosePayModal,
onOpen: onOpenPayModal
} = useDisclosure();
const { File, onOpen: onOpenSelectFile } = useSelectFile({
fileType: '.jpg,.png',
multiple: false
});
const onclickSave = useCallback(
async (data: UserUpdateParams) => {
setLoading(true);
try {
await putUserInfo({
avatar: data.avatar
});
updateUserInfo({
avatar: data.avatar
});
reset(data);
toast({
title: '更新数据成功',
status: 'success'
});
} catch (error) {
toast({
title: getErrText(error),
status: 'error'
});
}
setLoading(false);
},
[reset, setLoading, toast, updateUserInfo]
);
const onSelectFile = useCallback(
async (e: File[]) => {
const file = e[0];
if (!file) return;
try {
const src = await compressImg({
file,
maxW: 100,
maxH: 100
});
onclickSave({
...userInfo,
avatar: src
});
} catch (err: any) {
toast({
title: typeof err === 'string' ? err : '头像选择异常',
status: 'warning'
});
}
},
[onclickSave, toast, userInfo]
);
useQuery(['init'], initUserInfo, {
onSuccess(res) {
reset(res);
}
});
return (
<Flex flexDirection={'column'} alignItems={'center'} py={[0, 8]} fontSize={['lg', 'xl']}>
<Flex mt={6} alignItems={'center'} w={'260px'}>
<Box flex={'0 0 50px'}>:</Box>
<Box flex={1} pl={10}>
<Avatar
src={userInfo?.avatar}
w={['34px', '44px']}
h={['34px', '44px']}
cursor={'pointer'}
title={'点击切换头像'}
onClick={onOpenSelectFile}
/>
</Box>
</Flex>
<Flex mt={6} alignItems={'center'} w={'260px'}>
<Box flex={'0 0 50px'}>:</Box>
<Box>{userInfo?.username}</Box>
</Flex>
{feConfigs?.show_userDetail && (
<Box mt={6} w={'260px'} whiteSpace={'nowrap'}>
<Flex alignItems={'center'}>
<Box flex={'0 0 50px'}>:</Box>
<Box>
<strong>{userInfo?.balance}</strong>
</Box>
<Button size={['xs', 'sm']} w={['70px', '80px']} ml={5} onClick={onOpenPayModal}>
</Button>
</Flex>
</Box>
)}
{isOpenPayModal && <PayModal onClose={onClosePayModal} />}
<File onSelect={onSelectFile} />
</Flex>
);
};
export default UserInfo;

View File

@@ -0,0 +1,89 @@
import React from 'react';
import { Box, Flex, useTheme } from '@chakra-ui/react';
import { getInforms, readInform } from '@/api/user';
import { usePagination } from '@/hooks/usePagination';
import { useLoading } from '@/hooks/useLoading';
import type { informSchema } from '@/types/mongoSchema';
import { formatTimeToChatTime } from '@/utils/tools';
import { useGlobalStore } from '@/store/global';
import MyIcon from '@/components/Icon';
const BillTable = () => {
const theme = useTheme();
const { Loading } = useLoading();
const { isPc } = useGlobalStore();
const {
data: informs,
isLoading,
total,
pageSize,
Pagination,
getData,
pageNum
} = usePagination<informSchema>({
api: getInforms,
pageSize: isPc ? 20 : 10
});
return (
<Flex flexDirection={'column'} py={[0, 5]} h={'100%'} position={'relative'}>
<Box px={[3, 8]} position={'relative'} flex={'1 0 0'} h={0} overflowY={'auto'}>
{informs.map((item) => (
<Box
key={item._id}
border={theme.borders.md}
py={2}
px={4}
borderRadius={'md'}
cursor={item.read ? 'default' : 'pointer'}
position={'relative'}
_notLast={{ mb: 3 }}
onClick={async () => {
if (!item.read) {
await readInform(item._id);
getData(pageNum);
}
}}
>
<Flex alignItems={'center'} justifyContent={'space-between'}>
<Box>{item.title}</Box>
<Box ml={2} color={'myGray.500'}>
{formatTimeToChatTime(item.time)}
</Box>
</Flex>
<Box fontSize={'sm'} color={'myGray.600'}>
{item.content}
</Box>
{!item.read && (
<Box
w={'5px'}
h={'5px'}
borderRadius={'10px'}
bg={'myRead.600'}
position={'absolute'}
bottom={'8px'}
right={'8px'}
></Box>
)}
</Box>
))}
</Box>
{!isLoading && informs.length === 0 && (
<Flex flex={'1 0 0'} flexDirection={'column'} alignItems={'center'} pt={'-48px'}>
<MyIcon name="empty" w={'48px'} h={'48px'} color={'transparent'} />
<Box mt={2} color={'myGray.500'}>
~
</Box>
</Flex>
)}
{total > pageSize && (
<Flex w={'100%'} mt={4} px={[3, 8]} justifyContent={'flex-end'}>
<Pagination />
</Flex>
)}
<Loading loading={isLoading && informs.length === 0} fixed={false} />
</Flex>
);
};
export default BillTable;

View File

@@ -0,0 +1,154 @@
import React, { useState, useCallback } from 'react';
import {
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
Button,
Input,
Box,
Grid
} from '@chakra-ui/react';
import { getPayCode, checkPayResult } from '@/api/user';
import { useToast } from '@/hooks/useToast';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { getErrText } from '@/utils/tools';
import Markdown from '@/components/Markdown';
const PayModal = ({ onClose }: { onClose: () => void }) => {
const router = useRouter();
const { toast } = useToast();
const [inputVal, setInputVal] = useState<number | ''>('');
const [loading, setLoading] = useState(false);
const [payId, setPayId] = useState('');
const handleClickPay = useCallback(async () => {
if (!inputVal || inputVal <= 0 || isNaN(+inputVal)) return;
setLoading(true);
try {
// 获取支付二维码
const res = await getPayCode(inputVal);
new window.QRCode(document.getElementById('payQRCode'), {
text: res.codeUrl,
width: 128,
height: 128,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: window.QRCode.CorrectLevel.H
});
setPayId(res.payId);
} catch (err) {
toast({
title: getErrText(err),
status: 'error'
});
}
setLoading(false);
}, [inputVal, toast]);
useQuery(
[payId],
() => {
if (!payId) return null;
return checkPayResult(payId);
},
{
enabled: !!payId,
refetchInterval: 3000,
onSuccess(res) {
if (!res) return;
toast({
title: '充值成功',
status: 'success'
});
router.reload();
}
}
);
return (
<>
<Modal
isOpen={true}
onClose={() => {
if (payId) return;
onClose();
}}
>
<ModalOverlay />
<ModalContent minW={'auto'}>
<ModalHeader></ModalHeader>
{!payId && <ModalCloseButton />}
<ModalBody py={0}>
{!payId && (
<>
<Grid gridTemplateColumns={'repeat(4,1fr)'} gridGap={5} mb={4}>
{[10, 20, 50, 100].map((item) => (
<Button
key={item}
variant={item === inputVal ? 'solid' : 'outline'}
onClick={() => setInputVal(item)}
>
{item}
</Button>
))}
</Grid>
<Box mb={4}>
<Input
value={inputVal}
type={'number'}
step={1}
placeholder={'其他金额,请取整数'}
onChange={(e) => {
setInputVal(Math.floor(+e.target.value));
}}
></Input>
</Box>
<Markdown
source={`
| 计费项 | 价格: 元/ 1K tokens(包含上下文)|
| --- | --- |
| 知识库 - 索引 | 0.002 |
| FastAI4k - 对话 | 0.015 |
| FastAI16k - 对话 | 0.03 |
| FastAI-Plus - 对话 | 0.45 |
| 文件拆分 | 0.03 |`}
/>
</>
)}
{/* 付费二维码 */}
<Box textAlign={'center'}>
{payId && <Box mb={3}>: {inputVal}</Box>}
<Box id={'payQRCode'} display={'inline-block'}></Box>
</Box>
</ModalBody>
<ModalFooter>
{!payId && (
<>
<Button variant={'base'} onClick={onClose}>
</Button>
<Button
ml={3}
isLoading={loading}
isDisabled={!inputVal || inputVal === 0}
onClick={handleClickPay}
>
</Button>
</>
)}
</ModalFooter>
</ModalContent>
</Modal>
</>
);
};
export default PayModal;

View File

@@ -0,0 +1,108 @@
import React, { useState, useCallback } from 'react';
import {
Button,
Table,
Thead,
Tbody,
Tr,
Th,
Td,
TableContainer,
Flex,
Box
} from '@chakra-ui/react';
import { getPayOrders, checkPayResult } from '@/api/user';
import { PaySchema } from '@/types/mongoSchema';
import dayjs from 'dayjs';
import { useQuery } from '@tanstack/react-query';
import { formatPrice } from '@/utils/user';
import { useGlobalStore } from '@/store/global';
import { useToast } from '@/hooks/useToast';
import { useLoading } from '@/hooks/useLoading';
import MyIcon from '@/components/Icon';
const PayRecordTable = () => {
const { Loading, setIsLoading } = useLoading();
const [payOrders, setPayOrders] = useState<PaySchema[]>([]);
const { toast } = useToast();
const handleRefreshPayOrder = useCallback(
async (payId: string) => {
setIsLoading(true);
try {
const data = await checkPayResult(payId);
toast({
title: data,
status: 'info'
});
const res = await getPayOrders();
setPayOrders(res);
} catch (error: any) {
toast({
title: error?.message,
status: 'warning'
});
console.log(error);
}
setIsLoading(false);
},
[setIsLoading, toast]
);
const { isInitialLoading } = useQuery(['initPayOrder'], getPayOrders, {
onSuccess(res) {
setPayOrders(res);
}
});
return (
<Box position={'relative'} h={'100%'}>
{!isInitialLoading && payOrders.length === 0 ? (
<Flex h={'100%'} flexDirection={'column'} alignItems={'center'} justifyContent={'center'}>
<MyIcon name="empty" w={'48px'} h={'48px'} color={'transparent'} />
<Box mt={2} color={'myGray.500'}>
~
</Box>
</Flex>
) : (
<TableContainer py={[0, 5]} px={[3, 8]} h={'100%'} overflow={'overlay'}>
<Table>
<Thead>
<Tr>
<Th></Th>
<Th></Th>
<Th></Th>
<Th></Th>
<Th></Th>
</Tr>
</Thead>
<Tbody fontSize={'sm'}>
{payOrders.map((item) => (
<Tr key={item._id}>
<Td>{item.orderId}</Td>
<Td>
{item.createTime ? dayjs(item.createTime).format('YYYY/MM/DD HH:mm:ss') : '-'}
</Td>
<Td>{formatPrice(item.price)}</Td>
<Td>{item.status}</Td>
<Td>
{item.status === 'NOTPAY' && (
<Button onClick={() => handleRefreshPayOrder(item._id)} size={'sm'}>
</Button>
)}
</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
)}
<Loading loading={isInitialLoading} fixed={false} />
</Box>
);
};
export default PayRecordTable;

View File

@@ -0,0 +1,128 @@
import React, { useCallback, useRef } from 'react';
import { Box, Flex, useTheme } from '@chakra-ui/react';
import { useGlobalStore } from '@/store/global';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';
import { clearCookie } from '@/utils/user';
import { useUserStore } from '@/store/user';
import { useConfirm } from '@/hooks/useConfirm';
import PageContainer from '@/components/PageContainer';
import SideTabs from '@/components/SideTabs';
import Tabs from '@/components/Tabs';
import UserInfo from './components/Info';
import { serviceSideProps } from '@/utils/i18n';
const BillTable = dynamic(() => import('./components/BillTable'), {
ssr: false
});
const PayRecordTable = dynamic(() => import('./components/PayRecordTable'), {
ssr: false
});
const InformTable = dynamic(() => import('./components/InformTable'), {
ssr: false
});
enum TabEnum {
'info' = 'info',
'bill' = 'bill',
'pay' = 'pay',
'inform' = 'inform',
'loginout' = 'loginout'
}
const Account = ({ currentTab }: { currentTab: `${TabEnum}` }) => {
const tabList = useRef([
{ icon: 'meLight', label: '个人信息', id: TabEnum.info, Component: <BillTable /> },
{ icon: 'billRecordLight', label: '消费记录', id: TabEnum.bill, Component: <BillTable /> },
{ icon: 'payRecordLight', label: '充值记录', id: TabEnum.pay, Component: <PayRecordTable /> },
{ icon: 'informLight', label: '通知', id: TabEnum.inform, Component: <InformTable /> },
{ icon: 'loginoutLight', label: '登出', id: TabEnum.loginout, Component: () => <></> }
]);
const { openConfirm, ConfirmChild } = useConfirm({
content: '确认退出登录?'
});
const router = useRouter();
const theme = useTheme();
const { isPc } = useGlobalStore();
const { setUserInfo } = useUserStore();
const setCurrentTab = useCallback(
(tab: string) => {
if (tab === TabEnum.loginout) {
openConfirm(() => {
clearCookie();
setUserInfo(null);
router.replace('/login');
})();
} else {
router.replace({
query: {
currentTab: tab
}
});
}
},
[openConfirm, router, setUserInfo]
);
return (
<PageContainer>
<Flex flexDirection={['column', 'row']} h={'100%'} pt={[4, 0]}>
{isPc ? (
<Flex
flexDirection={'column'}
p={4}
h={'100%'}
flex={'0 0 200px'}
borderRight={theme.borders.base}
>
<SideTabs
flex={1}
mx={'auto'}
mt={2}
w={'100%'}
list={tabList.current}
activeId={currentTab}
onChange={setCurrentTab}
/>
</Flex>
) : (
<Box mb={3}>
<Tabs
m={'auto'}
w={'90%'}
size={isPc ? 'md' : 'sm'}
list={tabList.current.map((item) => ({
id: item.id,
label: item.label
}))}
activeId={currentTab}
onChange={setCurrentTab}
/>
</Box>
)}
<Box flex={'1 0 0'} h={'100%'} pb={[4, 0]}>
{currentTab === TabEnum.info && <UserInfo />}
{currentTab === TabEnum.bill && <BillTable />}
{currentTab === TabEnum.pay && <PayRecordTable />}
{currentTab === TabEnum.inform && <InformTable />}
</Box>
</Flex>
<ConfirmChild />
</PageContainer>
);
};
export async function getServerSideProps(content: any) {
return {
props: {
currentTab: content?.query?.currentTab || TabEnum.info,
...(await serviceSideProps(content))
}
};
}
export default Account;