refactor: 优化代码格式和结构,修复类型定义和样式问题

feat(access): 添加模板权限控制
feat(product): 新增品牌管理页面
fix(typings): 修正EnumTransformOptions类型定义
style: 统一代码缩进和格式
refactor(login): 调整设备指纹hook导入顺序
refactor(order): 优化订单商品聚合页面代码结构
refactor(subscription): 重构订阅订单相关组件
refactor(track): 调整物流跟踪页面代码结构
refactor(stock): 优化库存调拨表单逻辑
refactor(customer): 重构客户列表评分组件
refactor(product): 优化产品列表中文名编辑组件
refactor(logistics): 调整物流服务列表代码结构
refactor(site): 优化站点列表表单和操作逻辑
refactor(dict): 重构字典管理页面代码结构
This commit is contained in:
tikkhun 2025-11-28 00:08:31 +08:00
parent 7dfbc30e94
commit bd4096258e
29 changed files with 1501 additions and 990 deletions

View File

@ -1,10 +1,10 @@
import { defineConfig } from '@umijs/max'; import { defineConfig } from '@umijs/max';
import { codeInspectorPlugin } from 'code-inspector-plugin';
const isDev = process.env.NODE_ENV === 'development'; const isDev = process.env.NODE_ENV === 'development';
const UMI_APP_API_URL = isDev const UMI_APP_API_URL = isDev
? 'http://localhost:7001' ? 'http://localhost:7001'
: 'https://api.yoone.ca'; : 'https://api.yoone.ca';
import { codeInspectorPlugin } from 'code-inspector-plugin';
export default defineConfig({ export default defineConfig({
hash: true, hash: true,
@ -23,7 +23,7 @@ export default defineConfig({
config.plugin('code-inspector-plugin').use( config.plugin('code-inspector-plugin').use(
codeInspectorPlugin({ codeInspectorPlugin({
bundler: 'webpack', bundler: 'webpack',
}) }),
); );
}, },
routes: [ routes: [
@ -93,9 +93,9 @@ export default defineConfig({
component: './Product/List', component: './Product/List',
}, },
{ {
name: '商品分类', name: '品牌',
path: '/product/category', path: '/product/brand',
component: './Product/Category', component: './Product/Brand',
}, },
{ {
name: '强度', name: '强度',

View File

@ -1,2 +1 @@
# WEB # WEB

View File

@ -11,7 +11,7 @@ export default (initialState: any) => {
const canSeeStatistics = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('statistics') ?? false); const canSeeStatistics = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('statistics') ?? false);
const canSeeSite = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('site') ?? false); const canSeeSite = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('site') ?? false);
const canSeeDict = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('dict') ?? false); const canSeeDict = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('dict') ?? false);
const canSeeTemplate = (isSuper || isAdmin) || (initialState?.user?.permissions?.includes('template') ?? false);
return { return {
canSeeOrganiza, canSeeOrganiza,
canSeeProduct, canSeeProduct,
@ -22,5 +22,6 @@ export default (initialState: any) => {
canSeeStatistics, canSeeStatistics,
canSeeSite, canSeeSite,
canSeeDict, canSeeDict,
canSeeTemplate,
}; };
}; };

View File

@ -1,4 +1,3 @@
import { sitecontrollerAll } from '@/servers/api/site'; import { sitecontrollerAll } from '@/servers/api/site';
import { SyncOutlined } from '@ant-design/icons'; import { SyncOutlined } from '@ant-design/icons';
import { import {
@ -7,13 +6,13 @@ import {
ProForm, ProForm,
ProFormSelect, ProFormSelect,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { App, Button } from 'antd'; import { Button } from 'antd';
import React from 'react'; import React from 'react';
// 定义SyncForm组件的props类型 // 定义SyncForm组件的props类型
interface SyncFormProps { interface SyncFormProps {
tableRef: React.MutableRefObject<ActionType | undefined>; tableRef: React.MutableRefObject<ActionType | undefined>;
onFinish: (values:any) => Promise<void>; onFinish: (values: any) => Promise<void>;
} }
/** /**

View File

@ -40,8 +40,8 @@ const ListPage: React.FC = () => {
title: '客户编号', title: '客户编号',
dataIndex: 'customerId', dataIndex: 'customerId',
render: (_, record) => { render: (_, record) => {
if(!record.customerId) return '-'; if (!record.customerId) return '-';
return String(record.customerId).padStart(6,0) return String(record.customerId).padStart(6, 0);
}, },
sorter: true, sorter: true,
}, },
@ -95,31 +95,37 @@ const ListPage: React.FC = () => {
title: '等级', title: '等级',
hideInSearch: true, hideInSearch: true,
render: (_, record) => { render: (_, record) => {
if(!record.yoone_orders || !record.yoone_total) return '-' if (!record.yoone_orders || !record.yoone_total) return '-';
if(Number(record.yoone_orders) === 1 && Number(record.yoone_total) > 0 ) return 'B' if (Number(record.yoone_orders) === 1 && Number(record.yoone_total) > 0)
return '-' return 'B';
} return '-';
},
}, },
{ {
title: '评星', title: '评星',
dataIndex: 'rate', dataIndex: 'rate',
width: 200, width: 200,
render: (_, record) => { render: (_, record) => {
return <Rate onChange={async(val)=>{ return (
try{ <Rate
const { success, message: msg } = await customercontrollerSetrate({ onChange={async (val) => {
try {
const { success, message: msg } =
await customercontrollerSetrate({
id: record.customerId, id: record.customerId,
rate: val rate: val,
}); });
if (success) { if (success) {
message.success(msg); message.success(msg);
actionRef.current?.reload(); actionRef.current?.reload();
} }
}catch(e){ } catch (e) {
message.error(e.message); message.error(e.message);
} }
}} value={record.rate} /> }}
value={record.rate}
/>
);
}, },
}, },
{ {

View File

@ -1,8 +1,18 @@
import { PageContainer } from '@ant-design/pro-components';
import { Input, Button, Table, Layout, Space, Modal, message, Form, Upload } from 'antd';
import React, { useState, useEffect } from 'react';
import { request } from '@umijs/max';
import { UploadOutlined } from '@ant-design/icons'; import { UploadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { request } from '@umijs/max';
import {
Button,
Form,
Input,
Layout,
Modal,
Space,
Table,
Upload,
message,
} from 'antd';
import React, { useEffect, useState } from 'react';
const { Sider, Content } = Layout; const { Sider, Content } = Layout;
@ -26,7 +36,11 @@ const DictPage: React.FC = () => {
// 控制字典项模态框的显示 // 控制字典项模态框的显示
const [isDictItemModalVisible, setIsDictItemModalVisible] = useState(false); const [isDictItemModalVisible, setIsDictItemModalVisible] = useState(false);
const [editingDictItem, setEditingDictItem] = useState<any>(null); const [editingDictItem, setEditingDictItem] = useState<any>(null);
const [dictItemForm, setDictItemForm] = useState({ name: '', title: '', value: '' }); const [dictItemForm, setDictItemForm] = useState({
name: '',
title: '',
value: '',
});
// 获取字典列表 // 获取字典列表
const fetchDicts = async (title?: string) => { const fetchDicts = async (title?: string) => {
@ -181,7 +195,6 @@ const DictPage: React.FC = () => {
// 左侧字典列表的列定义 // 左侧字典列表的列定义
const dictColumns = [ const dictColumns = [
{ {
title: '名称', title: '名称',
dataIndex: 'name', dataIndex: 'name',
@ -197,10 +210,23 @@ const DictPage: React.FC = () => {
key: 'action', key: 'action',
render: (_: any, record: any) => ( render: (_: any, record: any) => (
<Space> <Space>
<Button type="link" onClick={(e) => { e.stopPropagation(); handleEditDict(record); }}> <Button
type="link"
onClick={(e) => {
e.stopPropagation();
handleEditDict(record);
}}
>
</Button> </Button>
<Button type="link" danger onClick={(e) => { e.stopPropagation(); handleDeleteDict(record.id); }}> <Button
type="link"
danger
onClick={(e) => {
e.stopPropagation();
handleDeleteDict(record.id);
}}
>
</Button> </Button>
</Space> </Space>
@ -225,8 +251,16 @@ const DictPage: React.FC = () => {
key: 'action', key: 'action',
render: (_: any, record: any) => ( render: (_: any, record: any) => (
<Space size="middle"> <Space size="middle">
<Button type="link" onClick={() => handleEditDictItem(record)}></Button> <Button type="link" onClick={() => handleEditDictItem(record)}>
<Button type="link" danger onClick={() => handleDeleteDictItem(record.id)}></Button>
</Button>
<Button
type="link"
danger
onClick={() => handleDeleteDictItem(record.id)}
>
</Button>
</Space> </Space>
), ),
}, },
@ -235,10 +269,27 @@ const DictPage: React.FC = () => {
return ( return (
<PageContainer> <PageContainer>
<Layout style={{ background: '#fff' }}> <Layout style={{ background: '#fff' }}>
<Sider width={300} style={{ background: '#fff', padding: '16px', borderRight: '1px solid #f0f0f0' }}> <Sider
width={300}
style={{
background: '#fff',
padding: '16px',
borderRight: '1px solid #f0f0f0',
}}
>
<Space direction="vertical" style={{ width: '100%' }}> <Space direction="vertical" style={{ width: '100%' }}>
<Input.Search placeholder="搜索字典" onSearch={handleSearch} onChange={e => setSearchText(e.target.value)} enterButton allowClear /> <Input.Search
<Button type="primary" onClick={() => setIsAddDictModalVisible(true)} block> placeholder="搜索字典"
onSearch={handleSearch}
onChange={(e) => setSearchText(e.target.value)}
enterButton
allowClear
/>
<Button
type="primary"
onClick={() => setIsAddDictModalVisible(true)}
block
>
</Button> </Button>
<Space> <Space>
@ -246,7 +297,7 @@ const DictPage: React.FC = () => {
name="file" name="file"
action="/dict/import" action="/dict/import"
showUploadList={false} showUploadList={false}
onChange={info => { onChange={(info) => {
if (info.file.status === 'done') { if (info.file.status === 'done') {
message.success(`${info.file.name} 文件上传成功`); message.success(`${info.file.name} 文件上传成功`);
fetchDicts(); fetchDicts();
@ -257,14 +308,16 @@ const DictPage: React.FC = () => {
> >
<Button icon={<UploadOutlined />}></Button> <Button icon={<UploadOutlined />}></Button>
</Upload> </Upload>
<Button onClick={() => window.open('/dict/template')}></Button> <Button onClick={() => window.open('/dict/template')}>
</Button>
</Space> </Space>
<Table <Table
dataSource={dicts} dataSource={dicts}
columns={dictColumns} columns={dictColumns}
rowKey="id" rowKey="id"
loading={loadingDicts} loading={loadingDicts}
onRow={record => ({ onRow={(record) => ({
onClick: () => { onClick: () => {
// 如果点击的是当前已选中的行,则取消选择 // 如果点击的是当前已选中的行,则取消选择
if (selectedDict?.id === record.id) { if (selectedDict?.id === record.id) {
@ -274,14 +327,20 @@ const DictPage: React.FC = () => {
} }
}, },
})} })}
rowClassName={record => (selectedDict?.id === record.id ? 'ant-table-row-selected' : '')} rowClassName={(record) =>
selectedDict?.id === record.id ? 'ant-table-row-selected' : ''
}
pagination={false} pagination={false}
/> />
</Space> </Space>
</Sider> </Sider>
<Content style={{ padding: '16px' }}> <Content style={{ padding: '16px' }}>
<Space direction="vertical" style={{ width: '100%' }}> <Space direction="vertical" style={{ width: '100%' }}>
<Button type="primary" onClick={handleAddDictItem} disabled={!selectedDict}> <Button
type="primary"
onClick={handleAddDictItem}
disabled={!selectedDict}
>
</Button> </Button>
<Space> <Space>
@ -291,7 +350,7 @@ const DictPage: React.FC = () => {
data={{ dictId: selectedDict?.id }} data={{ dictId: selectedDict?.id }}
showUploadList={false} showUploadList={false}
disabled={!selectedDict} disabled={!selectedDict}
onChange={info => { onChange={(info) => {
if (info.file.status === 'done') { if (info.file.status === 'done') {
message.success(`${info.file.name} 文件上传成功`); message.success(`${info.file.name} 文件上传成功`);
fetchDictItems(selectedDict.id); fetchDictItems(selectedDict.id);
@ -300,11 +359,23 @@ const DictPage: React.FC = () => {
} }
}} }}
> >
<Button icon={<UploadOutlined />} disabled={!selectedDict}></Button> <Button icon={<UploadOutlined />} disabled={!selectedDict}>
</Button>
</Upload> </Upload>
<Button onClick={() => window.open('/dict/item/template')} disabled={!selectedDict}></Button> <Button
onClick={() => window.open('/dict/item/template')}
disabled={!selectedDict}
>
</Button>
</Space> </Space>
<Table dataSource={dictItems} columns={dictItemColumns} rowKey="id" loading={loadingDictItems} /> <Table
dataSource={dictItems}
columns={dictItemColumns}
rowKey="id"
loading={loadingDictItems}
/>
</Space> </Space>
</Content> </Content>
</Layout> </Layout>
@ -317,13 +388,31 @@ const DictPage: React.FC = () => {
> >
<Form layout="vertical"> <Form layout="vertical">
<Form.Item label="名称"> <Form.Item label="名称">
<Input placeholder="名称 (e.g., zyn)" value={dictItemForm.name} onChange={e => setDictItemForm({ ...dictItemForm, name: e.target.value })} /> <Input
placeholder="名称 (e.g., zyn)"
value={dictItemForm.name}
onChange={(e) =>
setDictItemForm({ ...dictItemForm, name: e.target.value })
}
/>
</Form.Item> </Form.Item>
<Form.Item label="标题"> <Form.Item label="标题">
<Input placeholder="标题 (e.g., ZYN)" value={dictItemForm.title} onChange={e => setDictItemForm({ ...dictItemForm, title: e.target.value })} /> <Input
placeholder="标题 (e.g., ZYN)"
value={dictItemForm.title}
onChange={(e) =>
setDictItemForm({ ...dictItemForm, title: e.target.value })
}
/>
</Form.Item> </Form.Item>
<Form.Item label="值 (可选)"> <Form.Item label="值 (可选)">
<Input placeholder="值 (可选)" value={dictItemForm.value} onChange={e => setDictItemForm({ ...dictItemForm, value: e.target.value })} /> <Input
placeholder="值 (可选)"
value={dictItemForm.value}
onChange={(e) =>
setDictItemForm({ ...dictItemForm, value: e.target.value })
}
/>
</Form.Item> </Form.Item>
</Form> </Form>
</Modal> </Modal>
@ -336,10 +425,18 @@ const DictPage: React.FC = () => {
> >
<Form layout="vertical"> <Form layout="vertical">
<Form.Item label="字典名称"> <Form.Item label="字典名称">
<Input placeholder="字典名称 (e.g., brand)" value={newDictName} onChange={e => setNewDictName(e.target.value)} /> <Input
placeholder="字典名称 (e.g., brand)"
value={newDictName}
onChange={(e) => setNewDictName(e.target.value)}
/>
</Form.Item> </Form.Item>
<Form.Item label="字典标题"> <Form.Item label="字典标题">
<Input placeholder="字典标题 (e.g., 品牌)" value={newDictTitle} onChange={e => setNewDictTitle(e.target.value)} /> <Input
placeholder="字典标题 (e.g., 品牌)"
value={newDictTitle}
onChange={(e) => setNewDictTitle(e.target.value)}
/>
</Form.Item> </Form.Item>
</Form> </Form>
</Modal> </Modal>

View File

@ -1,3 +1,4 @@
import { useDeviceFingerprint } from '@/hooks/useDeviceFingerprint';
import { usercontrollerGetuser, usercontrollerLogin } from '@/servers/api/user'; import { usercontrollerGetuser, usercontrollerLogin } from '@/servers/api/user';
import { LockOutlined, UserOutlined } from '@ant-design/icons'; import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { import {
@ -7,7 +8,6 @@ import {
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max'; import { history, useModel } from '@umijs/max';
import { App, theme } from 'antd'; import { App, theme } from 'antd';
import {useDeviceFingerprint} from '@/hooks/useDeviceFingerprint';
import { useState } from 'react'; import { useState } from 'react';
const Page = () => { const Page = () => {
@ -15,28 +15,32 @@ const Page = () => {
const { token } = theme.useToken(); const { token } = theme.useToken();
const { message } = App.useApp(); const { message } = App.useApp();
const deviceId = useDeviceFingerprint(); const deviceId = useDeviceFingerprint();
const [ isAuth, setIsAuth ] = useState(false) const [isAuth, setIsAuth] = useState(false);
console.log(deviceId) ; console.log(deviceId);
const onFinish = async (values: { username: string; password: string }) => { const onFinish = async (values: { username: string; password: string }) => {
try { try {
const { data, success, code, message: msg } = await usercontrollerLogin({...values, deviceId}); const {
data,
success,
code,
message: msg,
} = await usercontrollerLogin({ ...values, deviceId });
if (success) { if (success) {
message.success('登录成功'); message.success('登录成功');
localStorage.setItem('token', data?.token as string); localStorage.setItem('token', data?.token as string);
const { data: user } = await usercontrollerGetuser(); const { data: user } = await usercontrollerGetuser();
setInitialState({ user }); setInitialState({ user });
history.push('/'); history.push('/');
return return;
} }
if(code === 10001){ if (code === 10001) {
message.info("验证码已发送至管理邮箱") message.info('验证码已发送至管理邮箱');
setIsAuth(true); setIsAuth(true);
return; return;
} }
message.error(msg); message.error(msg);
} catch { } catch {
message.error('登录失败'); message.error('登录失败');
} }
@ -100,16 +104,17 @@ const Page = () => {
}, },
]} ]}
/> />
{ {isAuth ? (
isAuth?
<ProFormText <ProFormText
name="authCode" name="authCode"
label="验证码" label="验证码"
width="lg" width="lg"
placeholder="请输入验证码" placeholder="请输入验证码"
rules={[{ required: true, message: '请输入验证码' }]} rules={[{ required: true, message: '请输入验证码' }]}
/>:<></> />
} ) : (
<></>
)}
{/* <div {/* <div
style={{ style={{
marginBlockEnd: 24, marginBlockEnd: 24,

View File

@ -1,12 +1,14 @@
import { logisticscontrollerGetlist, logisticscontrollerGetshipmentlabel, import {
logisticscontrollerDeleteshipment, logisticscontrollerDeleteshipment,
logisticscontrollerUpdateshipmentstate logisticscontrollerGetlist,
} from '@/servers/api/logistics'; logisticscontrollerGetshipmentlabel,
logisticscontrollerUpdateshipmentstate,
} from '@/servers/api/logistics';
import { sitecontrollerAll } from '@/servers/api/site';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock'; import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import { formatUniuniShipmentState } from '@/utils/format'; import { formatUniuniShipmentState } from '@/utils/format';
import { printPDF } from '@/utils/util'; import { printPDF } from '@/utils/util';
import { CopyOutlined } from '@ant-design/icons'; import { CopyOutlined } from '@ant-design/icons';
import { ToastContainer, toast } from 'react-toastify';
import { import {
ActionType, ActionType,
PageContainer, PageContainer,
@ -15,7 +17,7 @@ import {
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { App, Button, Divider, Popconfirm } from 'antd'; import { App, Button, Divider, Popconfirm } from 'antd';
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import { sitecontrollerAll } from '@/servers/api/site'; import { ToastContainer } from 'react-toastify';
const ListPage: React.FC = () => { const ListPage: React.FC = () => {
const actionRef = useRef<ActionType>(); const actionRef = useRef<ActionType>();
@ -69,7 +71,9 @@ const ListPage: React.FC = () => {
<CopyOutlined <CopyOutlined
onClick={async () => { onClick={async () => {
try { try {
await navigator.clipboard.writeText(record.return_tracking_number); await navigator.clipboard.writeText(
record.return_tracking_number,
);
message.success('复制成功!'); message.success('复制成功!');
} catch (err) { } catch (err) {
message.error('复制失败!'); message.error('复制失败!');
@ -106,7 +110,9 @@ const ListPage: React.FC = () => {
disabled={isLoading} disabled={isLoading}
onClick={async () => { onClick={async () => {
setIsLoading(true); setIsLoading(true);
const { data } = await logisticscontrollerGetshipmentlabel({shipmentId:record.id}); const { data } = await logisticscontrollerGetshipmentlabel({
shipmentId: record.id,
});
const content = data.content; const content = data.content;
printPDF([content]); printPDF([content]);
setIsLoading(false); setIsLoading(false);
@ -120,7 +126,9 @@ const ListPage: React.FC = () => {
disabled={isLoading} disabled={isLoading}
onClick={async () => { onClick={async () => {
setIsLoading(true); setIsLoading(true);
const res = await logisticscontrollerUpdateshipmentstate({shipmentId:record.id}); const res = await logisticscontrollerUpdateshipmentstate({
shipmentId: record.id,
});
console.log('res', res); console.log('res', res);
setIsLoading(false); setIsLoading(false);
@ -137,7 +145,7 @@ const ListPage: React.FC = () => {
try { try {
setIsLoading(true); setIsLoading(true);
const { success, message: errMsg } = const { success, message: errMsg } =
await logisticscontrollerDeleteshipment({id:record.id}); await logisticscontrollerDeleteshipment({ id: record.id });
if (!success) { if (!success) {
throw new Error(errMsg); throw new Error(errMsg);
} }

View File

@ -1,6 +1,5 @@
import { import {
logisticscontrollerGetservicelist, logisticscontrollerGetservicelist,
logisticscontrollerSyncservices,
logisticscontrollerToggleactive, logisticscontrollerToggleactive,
} from '@/servers/api/logistics'; } from '@/servers/api/logistics';
import { import {
@ -10,7 +9,7 @@ import {
ProFormSwitch, ProFormSwitch,
ProTable, ProTable,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { App, Button } from 'antd'; import { App } from 'antd';
import { useRef } from 'react'; import { useRef } from 'react';
const ListPage: React.FC = () => { const ListPage: React.FC = () => {

View File

@ -1,11 +1,15 @@
import React, { useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType, ProTableProps } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { App } from 'antd';
import dayjs from 'dayjs';
import { ordercontrollerGetordersales } from '@/servers/api/order'; import { ordercontrollerGetordersales } from '@/servers/api/order';
import { sitecontrollerAll } from '@/servers/api/site'; import { sitecontrollerAll } from '@/servers/api/site';
import type {
ActionType,
ProColumns,
ProTableProps,
} from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { App } from 'antd';
import dayjs from 'dayjs';
import React, { useRef } from 'react';
// 列表行数据结构(订单商品聚合) // 列表行数据结构(订单商品聚合)
interface OrderItemAggRow { interface OrderItemAggRow {
@ -87,7 +91,10 @@ const OrderItemsPage: React.FC = () => {
request: async () => { request: async () => {
// 拉取站点列表(后台 /site/all) // 拉取站点列表(后台 /site/all)
const { data = [] } = await sitecontrollerAll(); const { data = [] } = await sitecontrollerAll();
return (data || []).map((item: any) => ({ label: item.siteName, value: item.id })); return (data || []).map((item: any) => ({
label: item.siteName,
value: item.id,
}));
}, },
}, },
{ {
@ -104,7 +111,9 @@ const OrderItemsPage: React.FC = () => {
]; ];
// 表格请求方法:调用 /order/getOrderSales 接口并设置 isSource=true 获取订单项聚合 // 表格请求方法:调用 /order/getOrderSales 接口并设置 isSource=true 获取订单项聚合
const request: ProTableProps<OrderItemAggRow>['request'] = async (params:any) => { const request: ProTableProps<OrderItemAggRow>['request'] = async (
params: any,
) => {
try { try {
const { current = 1, pageSize = 10, siteId, name } = params as any; const { current = 1, pageSize = 10, siteId, name } = params as any;
const [startDate, endDate] = (params as any).dateRange || []; const [startDate, endDate] = (params as any).dateRange || [];
@ -115,7 +124,9 @@ const OrderItemsPage: React.FC = () => {
siteId, siteId,
name, name,
isSource: true as any, isSource: true as any,
startDate: startDate ? (dayjs(startDate).toISOString() as any) : undefined, startDate: startDate
? (dayjs(startDate).toISOString() as any)
: undefined,
endDate: endDate ? (dayjs(endDate).toISOString() as any) : undefined, endDate: endDate ? (dayjs(endDate).toISOString() as any) : undefined,
} as any); } as any);
const { success, data, message: errMsg } = resp as any; const { success, data, message: errMsg } = resp as any;
@ -132,10 +143,12 @@ const OrderItemsPage: React.FC = () => {
}; };
return ( return (
<PageContainer title='订单商品概览'> <PageContainer title="订单商品概览">
<ProTable<OrderItemAggRow> <ProTable<OrderItemAggRow>
actionRef={actionRef} actionRef={actionRef}
rowKey={(r) => `${r.externalProductId}-${r.externalVariationId}-${r.name}`} rowKey={(r) =>
`${r.externalProductId}-${r.externalVariationId}-${r.name}`
}
columns={columns} columns={columns}
request={request} request={request}
pagination={{ showSizeChanger: true }} pagination={{ showSizeChanger: true }}

View File

@ -2,16 +2,13 @@ import styles from '../../../style/order-list.css';
import InternationalPhoneInput from '@/components/InternationalPhoneInput'; import InternationalPhoneInput from '@/components/InternationalPhoneInput';
import SyncForm from '@/components/SyncForm'; import SyncForm from '@/components/SyncForm';
import { HistoryOrder } from '@/pages/Statistics/Order';
import { ORDER_STATUS_ENUM } from '@/constants'; import { ORDER_STATUS_ENUM } from '@/constants';
import { HistoryOrder } from '@/pages/Statistics/Order';
import { import {
logisticscontrollerCreateshipment, logisticscontrollerCreateshipment,
logisticscontrollerGetshipmentfee,
logisticscontrollerDelshipment, logisticscontrollerDelshipment,
logisticscontrollerGetpaymentmethods, logisticscontrollerGetshipmentfee,
logisticscontrollerGetratelist,
logisticscontrollerGetshippingaddresslist, logisticscontrollerGetshippingaddresslist,
// logisticscontrollerGetshipmentlabel,
} from '@/servers/api/logistics'; } from '@/servers/api/logistics';
import { import {
ordercontrollerCancelorder, ordercontrollerCancelorder,
@ -23,14 +20,13 @@ import {
ordercontrollerGetorderdetail, ordercontrollerGetorderdetail,
ordercontrollerGetorders, ordercontrollerGetorders,
ordercontrollerRefundorder, ordercontrollerRefundorder,
ordercontrollerSyncorder,
ordercontrollerSyncorderbyid, ordercontrollerSyncorderbyid,
ordercontrollerUpdateorderitems, ordercontrollerUpdateorderitems,
} from '@/servers/api/order'; } from '@/servers/api/order';
import { productcontrollerSearchproducts } from '@/servers/api/product'; import { productcontrollerSearchproducts } from '@/servers/api/product';
import { wpproductcontrollerSearchproducts } from '@/servers/api/wpProduct';
import { sitecontrollerAll } from '@/servers/api/site'; import { sitecontrollerAll } from '@/servers/api/site';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock'; import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import { wpproductcontrollerSearchproducts } from '@/servers/api/wpProduct';
import { formatShipmentState, formatSource } from '@/utils/format'; import { formatShipmentState, formatSource } from '@/utils/format';
import { import {
CodeSandboxOutlined, CodeSandboxOutlined,
@ -38,12 +34,10 @@ import {
DeleteFilled, DeleteFilled,
DownOutlined, DownOutlined,
FileDoneOutlined, FileDoneOutlined,
SyncOutlined,
TagsOutlined, TagsOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { import {
ActionType, ActionType,
DrawerForm,
ModalForm, ModalForm,
PageContainer, PageContainer,
ProColumns, ProColumns,
@ -66,7 +60,6 @@ import {
Button, Button,
Card, Card,
Col, Col,
Descriptions,
Divider, Divider,
Drawer, Drawer,
Dropdown, Dropdown,
@ -80,10 +73,8 @@ import {
TabsProps, TabsProps,
Tag, Tag,
} from 'antd'; } from 'antd';
import Item from 'antd/es/list/Item';
import RelatedOrders from '../../Subscription/Orders/RelatedOrders';
import React, { useMemo, useRef, useState } from 'react'; import React, { useMemo, useRef, useState } from 'react';
import { printPDF } from '@/utils/util'; import RelatedOrders from '../../Subscription/Orders/RelatedOrders';
const ListPage: React.FC = () => { const ListPage: React.FC = () => {
const actionRef = useRef<ActionType>(); const actionRef = useRef<ActionType>();
@ -130,14 +121,13 @@ const ListPage: React.FC = () => {
label: '已申请退款', label: '已申请退款',
}, },
{ {
key: 'refund_approved', key: 'refund_approved',
label: "已退款", label: '已退款',
// label: '退款申请已通过', // label: '退款申请已通过',
}, },
{ {
key: 'refund_cancelled', key: 'refund_cancelled',
label: "已完成" label: '已完成',
// label: '已取消退款', // label: '已取消退款',
}, },
// { // {
@ -180,9 +170,16 @@ const ListPage: React.FC = () => {
dataIndex: 'isSubscription', dataIndex: 'isSubscription',
hideInSearch: true, hideInSearch: true,
render: (_, record) => { render: (_, record) => {
const related = Array.isArray((record as any)?.related) ? (record as any).related : []; const related = Array.isArray((record as any)?.related)
const isSub = related.some((it: any) => it?.externalSubscriptionId || it?.billing_period || it?.line_items); ? (record as any).related
return <Tag color={isSub ? 'green' : 'default'}>{isSub ? '是' : '否'}</Tag>; : [];
const isSub = related.some(
(it: any) =>
it?.externalSubscriptionId || it?.billing_period || it?.line_items,
);
return (
<Tag color={isSub ? 'green' : 'default'}>{isSub ? '是' : '否'}</Tag>
);
}, },
}, },
{ {
@ -307,7 +304,11 @@ const ListPage: React.FC = () => {
record.orderStatus, record.orderStatus,
) ? ( ) ? (
<> <>
<Shipping id={record.id as number} tableRef={actionRef} setActiveLine={setActiveLine} /> <Shipping
id={record.id as number}
tableRef={actionRef}
setActiveLine={setActiveLine}
/>
<Divider type="vertical" /> <Divider type="vertical" />
</> </>
) : ( ) : (
@ -364,11 +365,12 @@ const ListPage: React.FC = () => {
}, },
{ {
key: 'history', key: 'history',
label: label: (
<HistoryOrder <HistoryOrder
email={record.customer_email} email={record.customer_email}
tableRef={actionRef} tableRef={actionRef}
/>, />
),
}, },
{ {
key: 'note', key: 'note',
@ -445,11 +447,14 @@ const ListPage: React.FC = () => {
actionRef={actionRef} actionRef={actionRef}
rowKey="id" rowKey="id"
rowClassName={(record) => { rowClassName={(record) => {
return record.id === activeLine ? styles['selected-line-order-protable'] : ''; return record.id === activeLine
? styles['selected-line-order-protable']
: '';
}} }}
toolBarRender={() => [ toolBarRender={() => [
<CreateOrder tableRef={actionRef} />, <CreateOrder tableRef={actionRef} />,
<SyncForm onFinish={async (values: any) => { <SyncForm
onFinish={async (values: any) => {
try { try {
const { success, message: errMsg } = const { success, message: errMsg } =
await ordercontrollerSyncorderbyid(values); await ordercontrollerSyncorderbyid(values);
@ -461,7 +466,9 @@ const ListPage: React.FC = () => {
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '同步失败'); message.error(error?.message || '同步失败');
} }
}} tableRef={actionRef} />, }}
tableRef={actionRef}
/>,
]} ]}
request={async ({ date, ...param }: any) => { request={async ({ date, ...param }: any) => {
if (param.status === 'all') { if (param.status === 'all') {
@ -494,7 +501,7 @@ const Detail: React.FC<{
tableRef: React.MutableRefObject<ActionType | undefined>; tableRef: React.MutableRefObject<ActionType | undefined>;
orderId: number; orderId: number;
record: API.Order; record: API.Order;
setActiveLine: Function setActiveLine: Function;
}> = ({ tableRef, orderId, record, setActiveLine }) => { }> = ({ tableRef, orderId, record, setActiveLine }) => {
const [visiable, setVisiable] = useState(false); const [visiable, setVisiable] = useState(false);
const { message } = App.useApp(); const { message } = App.useApp();
@ -526,10 +533,14 @@ const Detail: React.FC<{
return ( return (
<> <>
<Button key="detail" type="primary" onClick={() => { <Button
key="detail"
type="primary"
onClick={() => {
setVisiable(true); setVisiable(true);
setActiveLine(record.id); setActiveLine(record.id);
}}> }}
>
<FileDoneOutlined /> <FileDoneOutlined />
</Button> </Button>
@ -770,7 +781,9 @@ const Detail: React.FC<{
/> />
<ProDescriptions.Item label="金额" dataIndex="total" /> <ProDescriptions.Item label="金额" dataIndex="total" />
<ProDescriptions.Item label="客户邮箱" dataIndex="customer_email" /> <ProDescriptions.Item label="客户邮箱" dataIndex="customer_email" />
<ProDescriptions.Item label="联系电话" span={3} <ProDescriptions.Item
label="联系电话"
span={3}
render={(_, record) => { render={(_, record) => {
return ( return (
<div> <div>
@ -779,7 +792,8 @@ const Detail: React.FC<{
</span> </span>
</div> </div>
); );
}} /> }}
/>
<ProDescriptions.Item label="交易Id" dataIndex="transaction_id" /> <ProDescriptions.Item label="交易Id" dataIndex="transaction_id" />
<ProDescriptions.Item label="IP" dataIndex="customer_id_address" /> <ProDescriptions.Item label="IP" dataIndex="customer_id_address" />
<ProDescriptions.Item label="设备" dataIndex="device_type" /> <ProDescriptions.Item label="设备" dataIndex="device_type" />
@ -899,13 +913,13 @@ const Detail: React.FC<{
}} }}
/> />
{/* 显示 related order */} {/* 显示 related order */}
<ProDescriptions.Item <ProDescriptions.Item
label="关联" label="关联"
span={3} span={3}
render={(_, record) => { render={(_, record) => {
return <RelatedOrders data={record?.related} />; return <RelatedOrders data={record?.related} />;
}} }}
/> />
{/* 订单内容 */} {/* 订单内容 */}
<ProDescriptions.Item <ProDescriptions.Item
label="订单内容" label="订单内容"
@ -926,12 +940,7 @@ const Detail: React.FC<{
label="换货" label="换货"
span={3} span={3}
render={(_, record) => { render={(_, record) => {
return ( return <SalesChange detailRef={ref} id={record.id as number} />;
<SalesChange
detailRef={ref}
id={record.id as number}
/>
)
}} }}
/> />
<ProDescriptions.Item <ProDescriptions.Item
@ -1183,7 +1192,8 @@ const Shipping: React.FC<{
}, },
}} }}
trigger={ trigger={
<Button type="primary" <Button
type="primary"
onClick={() => { onClick={() => {
setActiveLine(id); setActiveLine(id);
}} }}
@ -1278,10 +1288,16 @@ const Shipping: React.FC<{
], ],
}, },
}, },
}; };
}} }}
onFinish={async ({ customer_note, notes, items, details, externalOrderId, ...data }) => { onFinish={async ({
customer_note,
notes,
items,
details,
externalOrderId,
...data
}) => {
details.origin.email_addresses = details.origin.email_addresses =
details.origin.email_addresses.split(','); details.origin.email_addresses.split(',');
details.destination.email_addresses = details.destination.email_addresses =
@ -1290,8 +1306,11 @@ const Shipping: React.FC<{
details.destination.phone_number.phone; details.destination.phone_number.phone;
details.origin.phone_number.number = details.origin.phone_number.phone; details.origin.phone_number.number = details.origin.phone_number.phone;
try { try {
const { success, message: errMsg, ...resShipment } = const {
await logisticscontrollerCreateshipment( success,
message: errMsg,
...resShipment
} = await logisticscontrollerCreateshipment(
{ orderId: id }, { orderId: id },
{ {
details, details,
@ -1333,11 +1352,7 @@ const Shipping: React.FC<{
} }
}} }}
> >
<ProFormText <ProFormText label="订单号" readonly name={'externalOrderId'} />
label="订单号"
readonly
name={"externalOrderId"}
/>
<ProFormText label="客户备注" readonly name="customer_note" /> <ProFormText label="客户备注" readonly name="customer_note" />
<ProFormList <ProFormList
label="后台备注" label="后台备注"
@ -1890,7 +1905,14 @@ const Shipping: React.FC<{
loading={ratesLoading} loading={ratesLoading}
onClick={async () => { onClick={async () => {
try { try {
const { customer_note, notes, items, details, externalOrderId, ...data } = formRef.current?.getFieldsValue(); const {
customer_note,
notes,
items,
details,
externalOrderId,
...data
} = formRef.current?.getFieldsValue();
const originEmail = details.origin.email_addresses; const originEmail = details.origin.email_addresses;
const destinationEmail = details.destination.email_addresses; const destinationEmail = details.destination.email_addresses;
details.origin.email_addresses = details.origin.email_addresses =
@ -1899,41 +1921,54 @@ const Shipping: React.FC<{
details.destination.email_addresses.split(','); details.destination.email_addresses.split(',');
details.destination.phone_number.number = details.destination.phone_number.number =
details.destination.phone_number.phone; details.destination.phone_number.phone;
details.origin.phone_number.number = details.origin.phone_number.phone; details.origin.phone_number.number =
const res = details.origin.phone_number.phone;
await logisticscontrollerGetshipmentfee( const res = await logisticscontrollerGetshipmentfee({
{
stockPointId: data.stockPointId, stockPointId: data.stockPointId,
sender: details.origin.contact_name, sender: details.origin.contact_name,
startPhone: details.origin.phone_number, startPhone: details.origin.phone_number,
startPostalCode: details.origin.address.postal_code.replace(/\s/g, ''), startPostalCode: details.origin.address.postal_code.replace(
/\s/g,
'',
),
pickupAddress: details.origin.address.address_line_1, pickupAddress: details.origin.address.address_line_1,
shipperCountryCode: details.origin.address.country, shipperCountryCode: details.origin.address.country,
receiver: details.destination.contact_name, receiver: details.destination.contact_name,
city: details.destination.address.city, city: details.destination.address.city,
province: details.destination.address.region, province: details.destination.address.region,
country: details.destination.address.country, country: details.destination.address.country,
postalCode: details.destination.address.postal_code.replace(/\s/g, ''), postalCode: details.destination.address.postal_code.replace(
/\s/g,
'',
),
deliveryAddress: details.destination.address.address_line_1, deliveryAddress: details.destination.address.address_line_1,
receiverPhone: details.destination.phone_number.number, receiverPhone: details.destination.phone_number.number,
receiverEmail: details.destination.email_addresses, receiverEmail: details.destination.email_addresses,
length: details.packaging_properties.packages[0].measurements.cuboid.l, length:
width: details.packaging_properties.packages[0].measurements.cuboid.w, details.packaging_properties.packages[0].measurements.cuboid.l,
height: details.packaging_properties.packages[0].measurements.cuboid.h, width:
dimensionUom: details.packaging_properties.packages[0].measurements.cuboid.unit, details.packaging_properties.packages[0].measurements.cuboid.w,
weight: details.packaging_properties.packages[0].measurements.weight.value, height:
weightUom: details.packaging_properties.packages[0].measurements.weight.unit, details.packaging_properties.packages[0].measurements.cuboid.h,
}, dimensionUom:
); details.packaging_properties.packages[0].measurements.cuboid
.unit,
weight:
details.packaging_properties.packages[0].measurements.weight
.value,
weightUom:
details.packaging_properties.packages[0].measurements.weight
.unit,
});
if (!res?.success) throw new Error(res?.message); if (!res?.success) throw new Error(res?.message);
const fee = res.data; const fee = res.data;
setShipmentFee(fee); setShipmentFee(fee);
details.origin.email_addresses = originEmail; details.origin.email_addresses = originEmail;
details.destination.email_addresses = destinationEmail; details.destination.email_addresses = destinationEmail;
formRef.current?.setFieldValue("details", { formRef.current?.setFieldValue('details', {
...details, ...details,
shipmentFee: fee shipmentFee: fee,
}); });
message.success('获取运费成功'); message.success('获取运费成功');
} catch (error: any) { } catch (error: any) {
@ -1945,9 +1980,9 @@ const Shipping: React.FC<{
</Button> </Button>
<ProFormText <ProFormText
readonly readonly
name={["details", "shipmentFee"]} name={['details', 'shipmentFee']}
fieldProps={{ fieldProps={{
value: (shipmentFee / 100.0).toFixed(2) value: (shipmentFee / 100.0).toFixed(2),
}} }}
/> />
</ModalForm> </ModalForm>
@ -1961,7 +1996,6 @@ const SalesChange: React.FC<{
}> = ({ id, detailRef }) => { }> = ({ id, detailRef }) => {
const formRef = useRef<ProFormInstance>(); const formRef = useRef<ProFormInstance>();
return ( return (
<ModalForm <ModalForm
formRef={formRef} formRef={formRef}
@ -1986,7 +2020,8 @@ const SalesChange: React.FC<{
orderId: id, orderId: id,
}); });
if (!success || !data) return {}; if (!success || !data) return {};
data.sales = data.sales?.reduce((acc: API.OrderSale[], cur: API.OrderSale) => { data.sales = data.sales?.reduce(
(acc: API.OrderSale[], cur: API.OrderSale) => {
let idx = acc.findIndex((v: any) => v.productId === cur.productId); let idx = acc.findIndex((v: any) => v.productId === cur.productId);
if (idx === -1) { if (idx === -1) {
acc.push(cur); acc.push(cur);
@ -1998,48 +2033,44 @@ const SalesChange: React.FC<{
[], [],
); );
// setOptions( // setOptions(
// data.sales?.map((item) => ({ // data.sales?.map((item) => ({
// label: item.name, // label: item.name,
// value: item.sku, // value: item.sku,
// })) || [], // })) || [],
// ); // );
return { ...data}; return { ...data };
}} }}
onFinish={async (formData: any) => { onFinish={async (formData: any) => {
const { sales } = formData; const { sales } = formData;
const res = await ordercontrollerUpdateorderitems({ orderId: id }, sales); const res = await ordercontrollerUpdateorderitems(
{ orderId: id },
sales,
);
if (!res.success) { if (!res.success) {
message.error(`更新货物信息失败: ${res.message}`); message.error(`更新货物信息失败: ${res.message}`);
return false; return false;
} }
message.success('更新成功') message.success('更新成功');
detailRef?.current?.reload(); detailRef?.current?.reload();
return true; return true;
}} }}
> >
<ProFormList <ProFormList label="换货订单" name="items">
label="换货订单"
name="items"
>
<ProForm.Group> <ProForm.Group>
<ProFormSelect <ProFormSelect
params={{ }} params={{}}
request={async ({ keyWords }) => { request={async ({ keyWords }) => {
try { try {
const { data } = await wpproductcontrollerSearchproducts({ const { data } = await wpproductcontrollerSearchproducts({
name: keyWords, name: keyWords,
}); });
return ( return data?.map((item) => {
data?.map((item) => {
return { return {
label: `${item.name}`, label: `${item.name}`,
value: item?.sku, value: item?.sku,
}; };
}) });
);
} catch (error: any) { } catch (error: any) {
return []; return [];
} }
@ -2065,17 +2096,11 @@ const SalesChange: React.FC<{
precision: 0, precision: 0,
}} }}
/> />
</ProForm.Group> </ProForm.Group>
</ProFormList> </ProFormList>
<ProFormList <ProFormList label="换货产品" name="sales">
label="换货产品"
name="sales"
>
<ProForm.Group> <ProForm.Group>
<ProFormSelect <ProFormSelect
params={{}} params={{}}
request={async ({ keyWords }) => { request={async ({ keyWords }) => {
@ -2083,14 +2108,12 @@ const SalesChange: React.FC<{
const { data } = await productcontrollerSearchproducts({ const { data } = await productcontrollerSearchproducts({
name: keyWords, name: keyWords,
}); });
return ( return data?.map((item) => {
data?.map((item) => {
return { return {
label: `${item.name} - ${item.nameCn}`, label: `${item.name} - ${item.nameCn}`,
value: item?.sku, value: item?.sku,
}; };
}) });
);
} catch (error: any) { } catch (error: any) {
return []; return [];
} }
@ -2120,7 +2143,7 @@ const SalesChange: React.FC<{
</ProFormList> </ProFormList>
</ModalForm> </ModalForm>
); );
} };
const CreateOrder: React.FC<{ const CreateOrder: React.FC<{
tableRef?: React.MutableRefObject<ActionType | undefined>; tableRef?: React.MutableRefObject<ActionType | undefined>;

View File

@ -86,15 +86,13 @@ const List: React.FC = () => {
return ( return (
<PageContainer header={{ title: '品牌列表' }}> <PageContainer header={{ title: '品牌列表' }}>
<ProTable<API.Brand> <ProTable<any>
headerTitle="查询表格" headerTitle="查询表格"
actionRef={actionRef} actionRef={actionRef}
rowKey="id" rowKey="id"
toolBarRender={() => [<CreateForm tableRef={actionRef} />]} toolBarRender={() => [<CreateForm tableRef={actionRef} />]}
request={async (params) => { request={async (params) => {
const { data, success } = await productcontrollerGetbrands( const { data, success } = await productcontrollerGetbrands(params);
params,
);
return { return {
total: data?.total || 0, total: data?.total || 0,
data: data?.items || [], data: data?.items || [],

View File

@ -26,24 +26,33 @@ const NameCn: React.FC<{
id: number; id: number;
value: string | undefined; value: string | undefined;
tableRef: React.MutableRefObject<ActionType | undefined>; tableRef: React.MutableRefObject<ActionType | undefined>;
}> = ({value,tableRef, id}) => { }> = ({ value, tableRef, id }) => {
const { message } = App.useApp(); const { message } = App.useApp();
const [editable, setEditable] = React.useState<boolean>(false); const [editable, setEditable] = React.useState<boolean>(false);
if (!editable) return <div onClick={() => setEditable(true)}>{value||'-'}</div>; if (!editable)
return <ProFormText initialValue={value} fieldProps={{autoFocus:true, onBlur:async(e: React.FocusEvent<HTMLInputElement>) => { return <div onClick={() => setEditable(true)}>{value || '-'}</div>;
if(!e.target.value) return setEditable(false) return (
<ProFormText
initialValue={value}
fieldProps={{
autoFocus: true,
onBlur: async (e: React.FocusEvent<HTMLInputElement>) => {
if (!e.target.value) return setEditable(false);
const { success, message: errMsg } = const { success, message: errMsg } =
await productcontrollerUpdateproductnamecn({ await productcontrollerUpdateproductnamecn({
id, id,
nameCn: e.target.value, nameCn: e.target.value,
}) });
setEditable(false) setEditable(false);
if (!success) { if (!success) {
return message.error(errMsg) return message.error(errMsg);
} }
tableRef?.current?.reload() tableRef?.current?.reload();
}}} /> },
} }}
/>
);
};
const List: React.FC = () => { const List: React.FC = () => {
const actionRef = useRef<ActionType>(); const actionRef = useRef<ActionType>();
// 状态:存储当前选中的行 // 状态:存储当前选中的行
@ -61,7 +70,7 @@ const List: React.FC = () => {
render: (_, record) => { render: (_, record) => {
return ( return (
<NameCn value={record.nameCn} id={record.id} tableRef={actionRef} /> <NameCn value={record.nameCn} id={record.id} tableRef={actionRef} />
) );
}, },
}, },
{ {

View File

@ -264,7 +264,7 @@ const UpdateStatus: React.FC<{
}, },
{ {
status, status,
stock_status stock_status,
}, },
); );
if (!success) { if (!success) {
@ -296,7 +296,6 @@ const UpdateStatus: React.FC<{
); );
}; };
const UpdateForm: React.FC<{ const UpdateForm: React.FC<{
tableRef: React.MutableRefObject<ActionType | undefined>; tableRef: React.MutableRefObject<ActionType | undefined>;
values: API.WpProductDTO; values: API.WpProductDTO;

View File

@ -1,12 +1,11 @@
import { UploadOutlined } from '@ant-design/icons';
import React, { useState } from 'react';
import { import {
PageContainer, PageContainer,
ProForm, ProForm,
ProFormSelect, ProFormSelect,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { Button, Card, Col, Input, message, Row, Upload } from 'antd'; import { Button, Card, Col, Input, message, Row, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons'; import React, { useState } from 'react';
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
// 定义配置接口 // 定义配置接口
@ -22,7 +21,10 @@ interface TagConfig {
/** /**
* @description * @description
*/ */
const parseName = (name: string, brands: string[]): [string, string, string, string] => { const parseName = (
name: string,
brands: string[],
): [string, string, string, string] => {
const nm = name.trim(); const nm = name.trim();
const dryMatch = nm.match(/\(([^)]*)\)/); const dryMatch = nm.match(/\(([^)]*)\)/);
const dryness = dryMatch ? dryMatch[1].trim() : ''; const dryness = dryMatch ? dryMatch[1].trim() : '';
@ -75,11 +77,18 @@ const splitFlavorTokens = (flavorPart: string): string[] => {
/** /**
* @description Fruit, Mint * @description Fruit, Mint
*/ */
const classifyExtraTags = (flavorPart: string, fruitKeys: string[], mintKeys: string[]): string[] => { const classifyExtraTags = (
flavorPart: string,
fruitKeys: string[],
mintKeys: string[],
): string[] => {
const tokens = splitFlavorTokens(flavorPart); const tokens = splitFlavorTokens(flavorPart);
const fLower = flavorPart.toLowerCase(); const fLower = flavorPart.toLowerCase();
const isFruit = fruitKeys.some(key => fLower.includes(key)) || tokens.some(t => fruitKeys.includes(t)); const isFruit =
const isMint = mintKeys.some(key => fLower.includes(key)) || tokens.includes('mint'); fruitKeys.some((key) => fLower.includes(key)) ||
tokens.some((t) => fruitKeys.includes(t));
const isMint =
mintKeys.some((key) => fLower.includes(key)) || tokens.includes('mint');
const extras: string[] = []; const extras: string[] = [];
if (isFruit) extras.push('Fruit'); if (isFruit) extras.push('Fruit');
@ -94,8 +103,12 @@ const computeTags = (name: string, sku: string, config: TagConfig): string => {
const [brand, flavorPart, mg, dryness] = parseName(name, config.brands); const [brand, flavorPart, mg, dryness] = parseName(name, config.brands);
const tokens = splitFlavorTokens(flavorPart); const tokens = splitFlavorTokens(flavorPart);
const tokensForFlavor = tokens.filter(t => !config.nonFlavorTokens.includes(t)); const tokensForFlavor = tokens.filter(
const flavorTag = tokensForFlavor.map(t => t.charAt(0).toUpperCase() + t.slice(1)).join(''); (t) => !config.nonFlavorTokens.includes(t),
);
const flavorTag = tokensForFlavor
.map((t) => t.charAt(0).toUpperCase() + t.slice(1))
.join('');
let tags: string[] = []; let tags: string[] = [];
if (brand) tags.push(brand); if (brand) tags.push(brand);
@ -133,11 +146,13 @@ const computeTags = (name: string, sku: string, config: TagConfig): string => {
} }
} }
tags.push(...classifyExtraTags(flavorPart, config.fruitKeys, config.mintKeys)); tags.push(
...classifyExtraTags(flavorPart, config.fruitKeys, config.mintKeys),
);
// 去重并保留顺序 // 去重并保留顺序
const seen = new Set<string>(); const seen = new Set<string>();
const finalTags = tags.filter(t => { const finalTags = tags.filter((t) => {
if (t && !seen.has(t)) { if (t && !seen.has(t)) {
seen.add(t); seen.add(t);
return true; return true;
@ -152,9 +167,22 @@ const computeTags = (name: string, sku: string, config: TagConfig): string => {
const DEFAULT_CONFIG = { const DEFAULT_CONFIG = {
brands: ['YOONE', 'ZYN', 'ZEX', 'JUX', 'WHITE FOX'], brands: ['YOONE', 'ZYN', 'ZEX', 'JUX', 'WHITE FOX'],
fruitKeys: [ fruitKeys: [
'apple', 'blueberry', 'citrus', 'mango', 'peach', 'grape', 'cherry', 'apple',
'strawberry', 'watermelon', 'orange', 'lemon', 'lemonade', 'blueberry',
'razz', 'pineapple', 'berry', 'fruit', 'citrus',
'mango',
'peach',
'grape',
'cherry',
'strawberry',
'watermelon',
'orange',
'lemon',
'lemonade',
'razz',
'pineapple',
'berry',
'fruit',
], ],
mintKeys: ['mint', 'wintergreen', 'peppermint', 'spearmint', 'menthol'], mintKeys: ['mint', 'wintergreen', 'peppermint', 'spearmint', 'menthol'],
nonFlavorTokens: ['slim', 'pouches', 'pouch', 'mini', 'dry'], nonFlavorTokens: ['slim', 'pouches', 'pouch', 'mini', 'dry'],
@ -266,10 +294,15 @@ const WpToolPage: React.FC = () => {
}); });
setProcessedData(dataWithTags); setProcessedData(dataWithTags);
message.success({ content: 'Tags 生成成功!现在可以下载了。', key: 'processing' }); message.success({
content: 'Tags 生成成功!现在可以下载了。',
key: 'processing',
});
} catch (error) { } catch (error) {
message.error({ content: '处理失败,请检查配置或文件。', key: 'processing' }); message.error({
content: '处理失败,请检查配置或文件。',
key: 'processing',
});
console.error('Processing Error:', error); console.error('Processing Error:', error);
} finally { } finally {
setIsProcessing(false); setIsProcessing(false);
@ -368,7 +401,9 @@ const WpToolPage: React.FC = () => {
<Button icon={<UploadOutlined />}> CSV </Button> <Button icon={<UploadOutlined />}> CSV </Button>
</Upload> </Upload>
<div style={{ marginTop: 16 }}> <div style={{ marginTop: 16 }}>
<label style={{ display: 'block', marginBottom: 8 }}></label> <label style={{ display: 'block', marginBottom: 8 }}>
</label>
<Input value={file ? file.name : '暂未选择文件'} readOnly /> <Input value={file ? file.name : '暂未选择文件'} readOnly />
</div> </div>
<Button <Button

View File

@ -1,8 +1,16 @@
import React, { useEffect, useRef, useState } from 'react'; import {
import { ActionType, ProColumns, ProTable, ProFormInstance } from '@ant-design/pro-components'; ActionType,
import { DrawerForm, ProFormText, ProFormSelect, ProFormSwitch } from '@ant-design/pro-components'; DrawerForm,
import { Button, message, Popconfirm, Space, Tag } from 'antd'; ProColumns,
ProFormInstance,
ProFormSelect,
ProFormSwitch,
ProFormText,
ProTable,
} from '@ant-design/pro-components';
import { request } from '@umijs/max'; import { request } from '@umijs/max';
import { Button, message, Popconfirm, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
// 站点数据项类型(前端不包含密钥字段,后端列表不返回密钥) // 站点数据项类型(前端不包含密钥字段,后端列表不返回密钥)
interface SiteItem { interface SiteItem {
@ -58,10 +66,21 @@ const SiteList: React.FC = () => {
// 表格列定义 // 表格列定义
const columns: ProColumns<SiteItem>[] = [ const columns: ProColumns<SiteItem>[] = [
{ title: 'ID', dataIndex: 'id', width: 80, sorter: true, hideInSearch: true }, {
title: 'ID',
dataIndex: 'id',
width: 80,
sorter: true,
hideInSearch: true,
},
{ title: '站点名称', dataIndex: 'siteName', width: 220 }, { title: '站点名称', dataIndex: 'siteName', width: 220 },
{ title: 'API 地址', dataIndex: 'apiUrl', width: 280, hideInSearch: true }, { title: 'API 地址', dataIndex: 'apiUrl', width: 280, hideInSearch: true },
{ title: 'SKU 前缀', dataIndex: 'skuPrefix', width: 160, hideInSearch: true }, {
title: 'SKU 前缀',
dataIndex: 'skuPrefix',
width: 160,
hideInSearch: true,
},
{ {
title: '平台', title: '平台',
dataIndex: 'type', dataIndex: 'type',
@ -101,7 +120,9 @@ const SiteList: React.FC = () => {
</Button> </Button>
<Popconfirm <Popconfirm
title={row.isDisabled ? '启用站点' : '禁用站点'} title={row.isDisabled ? '启用站点' : '禁用站点'}
description={row.isDisabled ? '确认启用该站点?' : '确认禁用该站点?'} description={
row.isDisabled ? '确认启用该站点?' : '确认禁用该站点?'
}
onConfirm={async () => { onConfirm={async () => {
try { try {
await request(`/site/disable/${row.id}`, { await request(`/site/disable/${row.id}`, {
@ -159,7 +180,9 @@ const SiteList: React.FC = () => {
...(values.siteName ? { siteName: values.siteName } : {}), ...(values.siteName ? { siteName: values.siteName } : {}),
...(values.apiUrl ? { apiUrl: values.apiUrl } : {}), ...(values.apiUrl ? { apiUrl: values.apiUrl } : {}),
...(values.type ? { type: values.type } : {}), ...(values.type ? { type: values.type } : {}),
...(typeof values.isDisabled === 'boolean' ? { isDisabled: values.isDisabled } : {}), ...(typeof values.isDisabled === 'boolean'
? { isDisabled: values.isDisabled }
: {}),
...(values.skuPrefix ? { skuPrefix: values.skuPrefix } : {}), ...(values.skuPrefix ? { skuPrefix: values.skuPrefix } : {}),
}; };
// 仅当输入了新密钥时才提交,未输入则保持原本值 // 仅当输入了新密钥时才提交,未输入则保持原本值
@ -169,7 +192,10 @@ const SiteList: React.FC = () => {
if (values.consumerSecret && values.consumerSecret.trim()) { if (values.consumerSecret && values.consumerSecret.trim()) {
payload.consumerSecret = values.consumerSecret.trim(); payload.consumerSecret = values.consumerSecret.trim();
} }
await request(`/site/update/${editing.id}`, { method: 'PUT', data: payload }); await request(`/site/update/${editing.id}`, {
method: 'PUT',
data: payload,
});
} else { } else {
// 新增站点时要求填写 consumerKey 和 consumerSecret // 新增站点时要求填写 consumerKey 和 consumerSecret
if (!values.consumerKey || !values.consumerSecret) { if (!values.consumerKey || !values.consumerSecret) {
@ -233,9 +259,18 @@ const SiteList: React.FC = () => {
onFinish={handleSubmit} onFinish={handleSubmit}
> >
{/* 站点名称,必填 */} {/* 站点名称,必填 */}
<ProFormText name="siteName" label="站点名称" placeholder="例如:本地商店" rules={[{ required: true, message: '站点名称为必填项' }]} /> <ProFormText
name="siteName"
label="站点名称"
placeholder="例如:本地商店"
rules={[{ required: true, message: '站点名称为必填项' }]}
/>
{/* API 地址,可选 */} {/* API 地址,可选 */}
<ProFormText name="apiUrl" label="API 地址" placeholder="例如https://shop.example.com" /> <ProFormText
name="apiUrl"
label="API 地址"
placeholder="例如https://shop.example.com"
/>
{/* 平台类型选择 */} {/* 平台类型选择 */}
<ProFormSelect <ProFormSelect
name="type" name="type"
@ -247,11 +282,27 @@ const SiteList: React.FC = () => {
/> />
{/* 是否禁用 */} {/* 是否禁用 */}
<ProFormSwitch name="isDisabled" label="禁用" /> <ProFormSwitch name="isDisabled" label="禁用" />
<ProFormText name="skuPrefix" label="SKU 前缀" placeholder={editing ? '留空表示不修改' : '可选'} /> <ProFormText
name="skuPrefix"
label="SKU 前缀"
placeholder={editing ? '留空表示不修改' : '可选'}
/>
{/* WooCommerce REST consumer key新增必填编辑不填则保持原值 */} {/* WooCommerce REST consumer key新增必填编辑不填则保持原值 */}
<ProFormText name="consumerKey" label="Key" placeholder={editing ? '留空表示不修改' : '必填'} rules={editing ? [] : [{ required: true, message: 'Key 为必填项' }]} /> <ProFormText
name="consumerKey"
label="Key"
placeholder={editing ? '留空表示不修改' : '必填'}
rules={editing ? [] : [{ required: true, message: 'Key 为必填项' }]}
/>
{/* WooCommerce REST consumer secret新增必填编辑不填则保持原值 */} {/* WooCommerce REST consumer secret新增必填编辑不填则保持原值 */}
<ProFormText name="consumerSecret" label="Secret" placeholder={editing ? '留空表示不修改' : '必填'} rules={editing ? [] : [{ required: true, message: 'Secret 为必填项' }]} /> <ProFormText
name="consumerSecret"
label="Secret"
placeholder={editing ? '留空表示不修改' : '必填'}
rules={
editing ? [] : [{ required: true, message: 'Secret 为必填项' }]
}
/>
</DrawerForm> </DrawerForm>
</> </>
); );

View File

@ -1,39 +1,47 @@
import React, { useEffect, useState, useMemo, useRef } from "react" import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
statisticscontrollerGetinativeusersbymonth,
statisticscontrollerGetordersorce,
} from '@/servers/api/statistics';
import { import {
ActionType, ActionType,
PageContainer, ProColumns, ProTable, PageContainer,
} from '@ant-design/pro-components'; ProColumns,
import { statisticscontrollerGetordersorce, statisticscontrollerGetinativeusersbymonth } from "@/servers/api/statistics"; ProTable,
import ReactECharts from 'echarts-for-react'; } from '@ant-design/pro-components';
import { App, Button, Space, Tag } from 'antd'; import { Space, Tag } from 'antd';
import { HistoryOrder } from "../Order";
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import ReactECharts from 'echarts-for-react';
import { HistoryOrder } from '../Order';
const ListPage: React.FC = () => { const ListPage: React.FC = () => {
const [data, setData] = useState({}); const [data, setData] = useState({});
useEffect(() => { useEffect(() => {
statisticscontrollerGetordersorce().then(({ data, success }) => { statisticscontrollerGetordersorce().then(({ data, success }) => {
if(success) setData(data) if (success) setData(data);
}); });
}, []); }, []);
const option = useMemo(() => { const option = useMemo(() => {
if(!data.inactiveRes) return {} if (!data.inactiveRes) return {};
const xAxisData = data?.inactiveRes?.map(v=> v.order_month)?.sort(_=>-1) const xAxisData = data?.inactiveRes
const arr = data?.res?.map(v=>v.first_order_month_group) ?.map((v) => v.order_month)
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index).sort((a,b)=> a.localeCompare(b)) ?.sort((_) => -1);
const arr = data?.res?.map((v) => v.first_order_month_group);
const uniqueArr = arr
.filter((item, index) => arr.indexOf(item) === index)
.sort((a, b) => a.localeCompare(b));
const series = [ const series = [
{ {
name: '新客户', name: '新客户',
type: 'bar', type: 'bar',
data: data?.inactiveRes?.map(v=> v.new_user_count)?.sort(_=>-1), data: data?.inactiveRes?.map((v) => v.new_user_count)?.sort((_) => -1),
label: { label: {
show: true, show: true,
}, },
emphasis: { emphasis: {
focus: 'series' focus: 'series',
}, },
xAxisIndex: 0, xAxisIndex: 0,
yAxisIndex: 0, yAxisIndex: 0,
@ -41,86 +49,100 @@ const ListPage: React.FC = () => {
{ {
name: '老客户', name: '老客户',
type: 'bar', type: 'bar',
data: data?.inactiveRes?.map(v=> v.old_user_count)?.sort(_=>-1), data: data?.inactiveRes?.map((v) => v.old_user_count)?.sort((_) => -1),
label: { label: {
show: true, show: true,
}, },
emphasis: { emphasis: {
focus: 'series' focus: 'series',
}, },
xAxisIndex: 0, xAxisIndex: 0,
yAxisIndex: 0, yAxisIndex: 0,
}, },
...uniqueArr?.map(v => { ...uniqueArr?.map((v) => {
data?.res?.filter(item => item.order_month === v) data?.res?.filter((item) => item.order_month === v);
return { return {
name: v, name: v,
type: "bar", type: 'bar',
stack: "total", stack: 'total',
label: { label: {
"show": true, show: true,
formatter: function(params) { formatter: function (params) {
if(!params.value) return '' if (!params.value) return '';
return Math.abs(params.value) return Math.abs(params.value);
}, },
color: '#fff' color: '#fff',
}, },
"data": xAxisData.map(month => { data: xAxisData.map((month) => {
return (data?.res?.find(item => item.order_month === month && item.first_order_month_group === v)?.order_count || 0) return (
data?.res?.find(
(item) =>
item.order_month === month &&
item.first_order_month_group === v,
)?.order_count || 0
);
}), }),
xAxisIndex: 0, xAxisIndex: 0,
yAxisIndex: 0, yAxisIndex: 0,
} };
}), }),
{ {
name: '未复购客户', name: '未复购客户',
type: 'bar', type: 'bar',
data: data?.inactiveRes?.map(v=> -v.inactive_user_count)?.sort(_=>-1), data: data?.inactiveRes
stack: "total", ?.map((v) => -v.inactive_user_count)
?.sort((_) => -1),
stack: 'total',
label: { label: {
show: true, show: true,
}, },
emphasis: { emphasis: {
focus: 'series' focus: 'series',
}, },
xAxisIndex: 1, xAxisIndex: 1,
yAxisIndex: 1, yAxisIndex: 1,
barWidth: "60%", barWidth: '60%',
itemStyle: { itemStyle: {
color: '#f44336' color: '#f44336',
}
}, },
] },
];
return { return {
grid: [ grid: [
{ top: '10%', height: '70%' }, { top: '10%', height: '70%' },
{ bottom: '10%', height: '10%' } { bottom: '10%', height: '10%' },
], ],
legend: { legend: {
selectedMode: false selectedMode: false,
}, },
xAxis: [{ xAxis: [
{
type: 'category', type: 'category',
data: xAxisData, data: xAxisData,
gridIndex: 0, gridIndex: 0,
},{ },
{
type: 'category', type: 'category',
data: xAxisData, data: xAxisData,
gridIndex: 1, gridIndex: 1,
}], },
yAxis: [{ ],
yAxis: [
{
type: 'value', type: 'value',
gridIndex: 0, gridIndex: 0,
},{ },
{
type: 'value', type: 'value',
gridIndex: 1, gridIndex: 1,
}], },
],
series, series,
} };
}, [data]) }, [data]);
const [tableData, setTableData] = useState<any[]>([]) const [tableData, setTableData] = useState<any[]>([]);
const actionRef = useRef<ActionType>(); const actionRef = useRef<ActionType>();
const columns: ProColumns[] = [ const columns: ProColumns[] = [
{ {
@ -220,7 +242,7 @@ const ListPage: React.FC = () => {
}, },
}, },
]; ];
return( return (
<PageContainer ghost> <PageContainer ghost>
<ReactECharts <ReactECharts
option={option} option={option}
@ -228,17 +250,17 @@ const ListPage: React.FC = () => {
onEvents={{ onEvents={{
click: async (params) => { click: async (params) => {
if (params.componentType === 'series') { if (params.componentType === 'series') {
setTableData([]) setTableData([]);
const {success, data} = await statisticscontrollerGetinativeusersbymonth({ const { success, data } =
month: params.name await statisticscontrollerGetinativeusersbymonth({
}) month: params.name,
if(success) setTableData(data) });
if (success) setTableData(data);
} }
}, },
}} }}
/> />
{ {tableData?.length ? (
tableData?.length ?
<ProTable <ProTable
search={false} search={false}
headerTitle="查询表格" headerTitle="查询表格"
@ -247,11 +269,11 @@ const ListPage: React.FC = () => {
dataSource={tableData} dataSource={tableData}
columns={columns} columns={columns}
/> />
:<></> ) : (
<></>
} )}
</PageContainer> </PageContainer>
) );
} };
export default ListPage; export default ListPage;

View File

@ -223,14 +223,17 @@ const ListPage: React.FC = () => {
(yooneTotal.yoone12Quantity || 0) + (yooneTotal.yoone12Quantity || 0) +
(yooneTotal.yoone15Quantity || 0) + (yooneTotal.yoone15Quantity || 0) +
(yooneTotal.yoone18Quantity || 0) + (yooneTotal.yoone18Quantity || 0) +
(yooneTotal.zexQuantity || 0) (yooneTotal.zexQuantity || 0)}
}
</div> </div>
<div>YOONE 3MG: {yooneTotal.yoone3Quantity || 0}</div> <div>YOONE 3MG: {yooneTotal.yoone3Quantity || 0}</div>
<div>YOONE 6MG: {yooneTotal.yoone6Quantity || 0}</div> <div>YOONE 6MG: {yooneTotal.yoone6Quantity || 0}</div>
<div>YOONE 9MG: {yooneTotal.yoone9Quantity || 0}</div> <div>YOONE 9MG: {yooneTotal.yoone9Quantity || 0}</div>
<div>YOONE 12MG新: {yooneTotal.yoone12QuantityNew || 0}</div> <div>YOONE 12MG新: {yooneTotal.yoone12QuantityNew || 0}</div>
<div>YOONE 12MG白: {(yooneTotal.yoone12Quantity || 0) - (yooneTotal.yoone12QuantityNew || 0)}</div> <div>
YOONE 12MG白:{' '}
{(yooneTotal.yoone12Quantity || 0) -
(yooneTotal.yoone12QuantityNew || 0)}
</div>
<div>YOONE 15MG: {yooneTotal.yoone15Quantity || 0}</div> <div>YOONE 15MG: {yooneTotal.yoone15Quantity || 0}</div>
<div>YOONE 18MG: {yooneTotal.yoone18Quantity || 0}</div> <div>YOONE 18MG: {yooneTotal.yoone18Quantity || 0}</div>
<div>ZEX: {yooneTotal.zexQuantity || 0}</div> <div>ZEX: {yooneTotal.zexQuantity || 0}</div>

View File

@ -427,9 +427,7 @@ const UpdateForm: React.FC<{
<ProFormTextArea label="备注" name="note" width={'lg'} /> <ProFormTextArea label="备注" name="note" width={'lg'} />
<ProFormDependency name={['items']}> <ProFormDependency name={['items']}>
{({ items }) => { {({ items }) => {
return ( return '数量:' + items?.reduce((acc, cur) => acc + cur.quantity, 0);
'数量:' + items?.reduce((acc, cur) => acc + cur.quantity, 0)
);
}} }}
</ProFormDependency> </ProFormDependency>
<ProFormList<API.PurchaseOrderItem> <ProFormList<API.PurchaseOrderItem>

View File

@ -31,12 +31,12 @@ const ListPage: React.FC = () => {
dataIndex: 'operationType', dataIndex: 'operationType',
valueType: 'select', valueType: 'select',
valueEnum: { valueEnum: {
'in': { in: {
text: '入库' text: '入库',
},
out: {
text: '出库',
}, },
"out": {
text: '出库'
}
}, },
}, },
{ {

View File

@ -207,7 +207,7 @@ const CreateForm: React.FC<{
drawerProps={{ drawerProps={{
destroyOnHidden: true, destroyOnHidden: true,
}} }}
onFinish={async ({orderNumber,...values}) => { onFinish={async ({ orderNumber, ...values }) => {
try { try {
const { success, message: errMsg } = const { success, message: errMsg } =
await stockcontrollerCreatetransfer(values); await stockcontrollerCreatetransfer(values);
@ -272,9 +272,15 @@ const CreateForm: React.FC<{
rules={[{ required: true, message: '请选择源目标仓库' }]} rules={[{ required: true, message: '请选择源目标仓库' }]}
/> />
<ProFormTextArea name="note" label="备注" /> <ProFormTextArea name="note" label="备注" />
<ProFormText name={'orderNumber'} addonAfter={<Button onClick={async () => { <ProFormText
const orderNumber = await form.getFieldValue('orderNumber') name={'orderNumber'}
const { data } = await stockcontrollerGetpurchaseorder({orderNumber}) addonAfter={
<Button
onClick={async () => {
const orderNumber = await form.getFieldValue('orderNumber');
const { data } = await stockcontrollerGetpurchaseorder({
orderNumber,
});
form.setFieldsValue({ form.setFieldsValue({
items: data?.map( items: data?.map(
(item: { productName: string; productSku: string }) => ({ (item: { productName: string; productSku: string }) => ({
@ -285,11 +291,19 @@ const CreateForm: React.FC<{
}, },
}), }),
), ),
}) });
}}></Button>} /> }}
>
</Button>
}
/>
<ProFormDependency name={['items']}> <ProFormDependency name={['items']}>
{({ items }) => { {({ items }) => {
return '数量:' + (items?.reduce?.((acc, cur) => acc + cur.quantity, 0)||0); return (
'数量:' +
(items?.reduce?.((acc, cur) => acc + cur.quantity, 0) || 0)
);
}} }}
</ProFormDependency> </ProFormDependency>
<ProFormList <ProFormList

View File

@ -1,4 +1,8 @@
import React, { useRef, useState } from 'react'; import { sitecontrollerAll } from '@/servers/api/site';
import {
subscriptioncontrollerList,
subscriptioncontrollerSync,
} from '@/servers/api/subscription';
import { import {
ActionType, ActionType,
DrawerForm, DrawerForm,
@ -7,14 +11,10 @@ import {
ProFormSelect, ProFormSelect,
ProTable, ProTable,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { App, Button, Tag, Drawer, List } from 'antd'; import { App, Button, Drawer, List, Tag } from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';
import { request } from 'umi'; import { request } from 'umi';
import {
subscriptioncontrollerList,
subscriptioncontrollerSync,
} from '@/servers/api/subscription';
import { sitecontrollerAll } from '@/servers/api/site';
/** /**
* () * ()
@ -77,7 +77,11 @@ const ListPage: React.FC = () => {
valueEnum: SUBSCRIPTION_STATUS_ENUM, valueEnum: SUBSCRIPTION_STATUS_ENUM,
// 以 Tag 形式展示,更易辨识 // 以 Tag 形式展示,更易辨识
render: (_, row) => render: (_, row) =>
row?.status ? <Tag>{SUBSCRIPTION_STATUS_ENUM[row.status]?.text || row.status}</Tag> : '-', row?.status ? (
<Tag>{SUBSCRIPTION_STATUS_ENUM[row.status]?.text || row.status}</Tag>
) : (
'-'
),
width: 120, width: 120,
}, },
{ {
@ -152,9 +156,9 @@ const ListPage: React.FC = () => {
const { success, data, message: errMsg } = resp as any; const { success, data, message: errMsg } = resp as any;
if (!success) throw new Error(errMsg || '获取失败'); if (!success) throw new Error(errMsg || '获取失败');
// 仅保留与父订单号完全一致的订单(避免模糊匹配误入) // 仅保留与父订单号完全一致的订单(避免模糊匹配误入)
const candidates: any[] = (Array.isArray(data) ? data : []).filter( const candidates: any[] = (
(c: any) => String(c?.externalOrderId) === parentNumber Array.isArray(data) ? data : []
); ).filter((c: any) => String(c?.externalOrderId) === parentNumber);
// 拉取详情,补充状态、金额、时间 // 拉取详情,补充状态、金额、时间
const details = [] as any[]; const details = [] as any[];
for (const c of candidates) { for (const c of candidates) {
@ -230,14 +234,22 @@ const ListPage: React.FC = () => {
<List.Item> <List.Item>
<List.Item.Meta <List.Item.Meta
title={`#${item?.externalOrderId || '-'}`} title={`#${item?.externalOrderId || '-'}`}
description={`关系:${item?.relationship || '-'},站点:${item?.siteName || '-'}`} description={`关系:${item?.relationship || '-'},站点:${
item?.siteName || '-'
}`}
/> />
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}> <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<span>{item?.date_created ? dayjs(item.date_created).format('YYYY-MM-DD HH:mm') : '-'}</span> <span>
{item?.date_created
? dayjs(item.date_created).format('YYYY-MM-DD HH:mm')
: '-'}
</span>
<Tag>{item?.status || '-'}</Tag> <Tag>{item?.status || '-'}</Tag>
<span> <span>
{item?.currency_symbol || ''} {item?.currency_symbol || ''}
{typeof item?.total === 'number' ? item.total.toFixed(2) : item?.total ?? '-'} {typeof item?.total === 'number'
? item.total.toFixed(2)
: item?.total ?? '-'}
</span> </span>
</div> </div>
</List.Item> </List.Item>
@ -274,7 +286,9 @@ const SyncForm: React.FC<{
*/ */
onFinish={async (values) => { onFinish={async (values) => {
try { try {
const { success, message: errMsg } = await subscriptioncontrollerSync(values); const { success, message: errMsg } = await subscriptioncontrollerSync(
values,
);
if (!success) { if (!success) {
throw new Error(errMsg); throw new Error(errMsg);
} }

View File

@ -1,31 +1,21 @@
import React, { useEffect, useRef, useState } from 'react';
import {
App,
Button,
Card,
Divider,
Drawer,
Empty,
Popconfirm,
Space,
Tag,
} from 'antd';
import { ActionType, ProDescriptions } from '@ant-design/pro-components';
import { CopyOutlined, DeleteFilled } from '@ant-design/icons'; import { CopyOutlined, DeleteFilled } from '@ant-design/icons';
import { ActionType, ProDescriptions } from '@ant-design/pro-components';
import { App, Button, Card, Divider, Drawer, Empty, Popconfirm } from 'antd';
import React, { useEffect, useRef } from 'react';
// 服务器 API 引用(保持与原 index.tsx 一致) // 服务器 API 引用(保持与原 index.tsx 一致)
import { logisticscontrollerDelshipment } from '@/servers/api/logistics';
import { import {
ordercontrollerChangestatus, ordercontrollerChangestatus,
ordercontrollerGetorderdetail, ordercontrollerGetorderdetail,
ordercontrollerSyncorderbyid, ordercontrollerSyncorderbyid,
} from '@/servers/api/order'; } from '@/servers/api/order';
import { logisticscontrollerDelshipment } from '@/servers/api/logistics';
import { sitecontrollerAll } from '@/servers/api/site'; import { sitecontrollerAll } from '@/servers/api/site';
// 工具与子组件 // 工具与子组件
import { ORDER_STATUS_ENUM } from '@/constants';
import { formatShipmentState, formatSource } from '@/utils/format'; import { formatShipmentState, formatSource } from '@/utils/format';
import RelatedOrders from './RelatedOrders'; import RelatedOrders from './RelatedOrders';
import { ORDER_STATUS_ENUM } from '@/constants';
// 为保持原文件结构简单,此处从 index.tsx 引入的子组件仍由原文件导出或保持原状 // 为保持原文件结构简单,此处从 index.tsx 引入的子组件仍由原文件导出或保持原状
// 若后续需要彻底解耦,可将 OrderNote / Shipping / SalesChange 也独立到文件 // 若后续需要彻底解耦,可将 OrderNote / Shipping / SalesChange 也独立到文件
@ -59,14 +49,18 @@ const OrderDetailDrawer: React.FC<OrderDetailDrawerProps> = ({
// 加载详情数据(与 index.tsx 中完全保持一致) // 加载详情数据(与 index.tsx 中完全保持一致)
const initRequest = async () => { const initRequest = async () => {
const { data, success }: API.OrderDetailRes = await ordercontrollerGetorderdetail({ orderId }); const { data, success }: API.OrderDetailRes =
await ordercontrollerGetorderdetail({ orderId });
if (!success || !data) return { data: {} } as any; if (!success || !data) return { data: {} } as any;
data.sales = data.sales?.reduce((acc: API.OrderSale[], cur: API.OrderSale) => { data.sales = data.sales?.reduce(
(acc: API.OrderSale[], cur: API.OrderSale) => {
const idx = acc.findIndex((v: any) => v.productId === cur.productId); const idx = acc.findIndex((v: any) => v.productId === cur.productId);
if (idx === -1) acc.push(cur); if (idx === -1) acc.push(cur);
else acc[idx].quantity += cur.quantity; else acc[idx].quantity += cur.quantity;
return acc; return acc;
}, []); },
[],
);
return { data } as any; return { data } as any;
}; };
@ -220,65 +214,178 @@ const OrderDetailDrawer: React.FC<OrderDetailDrawerProps> = ({
: []), : []),
]} ]}
> >
<ProDescriptions labelStyle={{ width: '100px' }} actionRef={ref} request={initRequest}> <ProDescriptions
<ProDescriptions.Item label="站点" dataIndex="siteId" valueType="select" request={async () => { labelStyle={{ width: '100px' }}
actionRef={ref}
request={initRequest}
>
<ProDescriptions.Item
label="站点"
dataIndex="siteId"
valueType="select"
request={async () => {
const { data = [] } = await sitecontrollerAll(); const { data = [] } = await sitecontrollerAll();
return data.map((item) => ({ label: item.siteName, value: item.id })); return data.map((item) => ({
}} /> label: item.siteName,
<ProDescriptions.Item label="订单日期" dataIndex="date_created" valueType="dateTime" /> value: item.id,
<ProDescriptions.Item label="订单状态" dataIndex="orderStatus" valueType="select" valueEnum={ORDER_STATUS_ENUM as any} /> }));
}}
/>
<ProDescriptions.Item
label="订单日期"
dataIndex="date_created"
valueType="dateTime"
/>
<ProDescriptions.Item
label="订单状态"
dataIndex="orderStatus"
valueType="select"
valueEnum={ORDER_STATUS_ENUM as any}
/>
<ProDescriptions.Item label="金额" dataIndex="total" /> <ProDescriptions.Item label="金额" dataIndex="total" />
<ProDescriptions.Item label="客户邮箱" dataIndex="customer_email" /> <ProDescriptions.Item label="客户邮箱" dataIndex="customer_email" />
<ProDescriptions.Item label="联系电话" span={3} render={(_, r: any) => ( <ProDescriptions.Item
<div><span>{r?.shipping?.phone || r?.billing?.phone || '-'}</span></div> label="联系电话"
)} /> span={3}
render={(_, r: any) => (
<div>
<span>{r?.shipping?.phone || r?.billing?.phone || '-'}</span>
</div>
)}
/>
<ProDescriptions.Item label="交易Id" dataIndex="transaction_id" /> <ProDescriptions.Item label="交易Id" dataIndex="transaction_id" />
<ProDescriptions.Item label="IP" dataIndex="customer_id_address" /> <ProDescriptions.Item label="IP" dataIndex="customer_id_address" />
<ProDescriptions.Item label="设备" dataIndex="device_type" /> <ProDescriptions.Item label="设备" dataIndex="device_type" />
<ProDescriptions.Item label="来源" render={(_, r: any) => formatSource(r.source_type, r.utm_source)} /> <ProDescriptions.Item
<ProDescriptions.Item label="原订单状态" dataIndex="status" valueType="select" valueEnum={ORDER_STATUS_ENUM as any} /> label="来源"
<ProDescriptions.Item label="支付链接" dataIndex="payment_url" span={3} copyable /> render={(_, r: any) => formatSource(r.source_type, r.utm_source)}
<ProDescriptions.Item label="客户备注" dataIndex="customer_note" span={3} /> />
<ProDescriptions.Item label="发货信息" span={3} render={(_, r: any) => ( <ProDescriptions.Item
label="原订单状态"
dataIndex="status"
valueType="select"
valueEnum={ORDER_STATUS_ENUM as any}
/>
<ProDescriptions.Item
label="支付链接"
dataIndex="payment_url"
span={3}
copyable
/>
<ProDescriptions.Item
label="客户备注"
dataIndex="customer_note"
span={3}
/>
<ProDescriptions.Item
label="发货信息"
span={3}
render={(_, r: any) => (
<div> <div>
<div>company:<span>{r?.shipping?.company || r?.billing?.company || '-'}</span></div> <div>
<div>first_name:<span>{r?.shipping?.first_name || r?.billing?.first_name || '-'}</span></div> company:
<div>last_name:<span>{r?.shipping?.last_name || r?.billing?.last_name || '-'}</span></div> <span>
<div>country:<span>{r?.shipping?.country || r?.billing?.country || '-'}</span></div> {r?.shipping?.company || r?.billing?.company || '-'}
<div>state:<span>{r?.shipping?.state || r?.billing?.state || '-'}</span></div> </span>
<div>city:<span>{r?.shipping?.city || r?.billing?.city || '-'}</span></div>
<div>postcode:<span>{r?.shipping?.postcode || r?.billing?.postcode || '-'}</span></div>
<div>phone:<span>{r?.shipping?.phone || r?.billing?.phone || '-'}</span></div>
<div>address_1:<span>{r?.shipping?.address_1 || r?.billing?.address_1 || '-'}</span></div>
</div> </div>
)} /> <div>
<ProDescriptions.Item label="原始订单" span={3} render={(_, r: any) => ( first_name:
<span>
{r?.shipping?.first_name || r?.billing?.first_name || '-'}
</span>
</div>
<div>
last_name:
<span>
{r?.shipping?.last_name || r?.billing?.last_name || '-'}
</span>
</div>
<div>
country:
<span>
{r?.shipping?.country || r?.billing?.country || '-'}
</span>
</div>
<div>
state:
<span>{r?.shipping?.state || r?.billing?.state || '-'}</span>
</div>
<div>
city:<span>{r?.shipping?.city || r?.billing?.city || '-'}</span>
</div>
<div>
postcode:
<span>
{r?.shipping?.postcode || r?.billing?.postcode || '-'}
</span>
</div>
<div>
phone:
<span>{r?.shipping?.phone || r?.billing?.phone || '-'}</span>
</div>
<div>
address_1:
<span>
{r?.shipping?.address_1 || r?.billing?.address_1 || '-'}
</span>
</div>
</div>
)}
/>
<ProDescriptions.Item
label="原始订单"
span={3}
render={(_, r: any) => (
<ul> <ul>
{(r?.items || []).map((item: any) => ( {(r?.items || []).map((item: any) => (
<li key={item.id}>{item.name}:{item.quantity}</li> <li key={item.id}>
{item.name}:{item.quantity}
</li>
))} ))}
</ul> </ul>
)} /> )}
<ProDescriptions.Item label="关联" span={3} render={(_, r: any) => ( />
<RelatedOrders data={r?.related} /> <ProDescriptions.Item
)} /> label="关联"
<ProDescriptions.Item label="订单内容" span={3} render={(_, r: any) => ( span={3}
render={(_, r: any) => <RelatedOrders data={r?.related} />}
/>
<ProDescriptions.Item
label="订单内容"
span={3}
render={(_, r: any) => (
<ul> <ul>
{(r?.sales || []).map((item: any) => ( {(r?.sales || []).map((item: any) => (
<li key={item.id}>{item.name}:{item.quantity}</li> <li key={item.id}>
{item.name}:{item.quantity}
</li>
))} ))}
</ul> </ul>
)} /> )}
<ProDescriptions.Item label="换货" span={3} render={(_, r: any) => ( />
<ProDescriptions.Item
label="换货"
span={3}
render={(_, r: any) => (
<SalesChangeComponent detailRef={ref} id={r.id as number} /> <SalesChangeComponent detailRef={ref} id={r.id as number} />
)} /> )}
<ProDescriptions.Item label="备注" span={3} render={(_, r: any) => { />
if (!r.notes || r.notes.length === 0) return (<Empty description="暂无备注" />); <ProDescriptions.Item
label="备注"
span={3}
render={(_, r: any) => {
if (!r.notes || r.notes.length === 0)
return <Empty description="暂无备注" />;
return ( return (
<div style={{ width: '100%' }}> <div style={{ width: '100%' }}>
{r.notes.map((note: any) => ( {r.notes.map((note: any) => (
<div style={{ marginBottom: 10 }} key={note.id}> <div style={{ marginBottom: 10 }} key={note.id}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}> <div
style={{
display: 'flex',
justifyContent: 'space-between',
}}
>
<span>{note.username}</span> <span>{note.username}</span>
<span>{note.createdAt}</span> <span>{note.createdAt}</span>
</div> </div>
@ -287,38 +394,90 @@ const OrderDetailDrawer: React.FC<OrderDetailDrawerProps> = ({
))} ))}
</div> </div>
); );
}} /> }}
<ProDescriptions.Item label="物流信息" span={3} render={(_, r: any) => { />
if (!r.shipment || r.shipment.length === 0) return (<Empty description="暂无物流信息" />); <ProDescriptions.Item
label="物流信息"
span={3}
render={(_, r: any) => {
if (!r.shipment || r.shipment.length === 0)
return <Empty description="暂无物流信息" />;
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}> <div
style={{
display: 'flex',
flexDirection: 'column',
width: '100%',
}}
>
{r.shipment.map((v: any) => ( {r.shipment.map((v: any) => (
<Card key={v.id} style={{ marginBottom: '10px' }} extra={formatShipmentState(v.state)} title={<> <Card
key={v.id}
style={{ marginBottom: '10px' }}
extra={formatShipmentState(v.state)}
title={
<>
{v.tracking_provider} {v.tracking_provider}
{v.primary_tracking_number} {v.primary_tracking_number}
<CopyOutlined onClick={async () => { <CopyOutlined
try { await navigator.clipboard.writeText(v.tracking_url); message.success('复制成功!'); } onClick={async () => {
catch { message.error('复制失败!'); } try {
}} /> await navigator.clipboard.writeText(
</>} v.tracking_url,
actions={ (v.state === 'waiting-for-scheduling' || v.state === 'waiting-for-transit') ? [ );
<Popconfirm key="action-cancel" title="取消运单" description="确认取消运单?" onConfirm={async () => { message.success('复制成功!');
try { const { success, message: errMsg } = await logisticscontrollerDelshipment({ id: v.id }); if (!success) throw new Error(errMsg); tableRef.current?.reload(); ref.current?.reload?.(); } } catch {
catch (error: any) { message.error(error.message); } message.error('复制失败!');
}}> }
<DeleteFilled /> }}
</Popconfirm> />
] : [] } </>
}
actions={
v.state === 'waiting-for-scheduling' ||
v.state === 'waiting-for-transit'
? [
<Popconfirm
key="action-cancel"
title="取消运单"
description="确认取消运单?"
onConfirm={async () => {
try {
const { success, message: errMsg } =
await logisticscontrollerDelshipment({
id: v.id,
});
if (!success) throw new Error(errMsg);
tableRef.current?.reload();
ref.current?.reload?.();
} catch (error: any) {
message.error(error.message);
}
}}
> >
<div>: {Array.isArray(v?.orderIds) ? v.orderIds.join(',') : '-'}</div> <DeleteFilled />
{Array.isArray(v?.items) && v.items.map((item: any) => (
<div key={item.id}>{item.name}: {item.quantity}</div> </Popconfirm>,
]
: []
}
>
<div>
:{' '}
{Array.isArray(v?.orderIds) ? v.orderIds.join(',') : '-'}
</div>
{Array.isArray(v?.items) &&
v.items.map((item: any) => (
<div key={item.id}>
{item.name}: {item.quantity}
</div>
))} ))}
</Card> </Card>
))} ))}
</div> </div>
); );
}} /> }}
/>
</ProDescriptions> </ProDescriptions>
</Drawer> </Drawer>
); );

View File

@ -1,7 +1,7 @@
import React from 'react';
import { Empty, Tag } from 'antd'; import { Empty, Tag } from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime'; import relativeTime from 'dayjs/plugin/relativeTime';
import React from 'react';
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@ -12,17 +12,36 @@ dayjs.extend(relativeTime);
*/ */
const RelatedOrders: React.FC<{ data?: any[] }> = ({ data = [] }) => { const RelatedOrders: React.FC<{ data?: any[] }> = ({ data = [] }) => {
const rows = (Array.isArray(data) ? data : []).map((it: any) => { const rows = (Array.isArray(data) ? data : []).map((it: any) => {
const isSubscription = !!it?.externalSubscriptionId || !!it?.billing_period || !!it?.line_items; const isSubscription =
const number = isSubscription ? `#${it?.externalSubscriptionId || it?.id}` : `#${it?.externalOrderId || it?.id}`; !!it?.externalSubscriptionId || !!it?.billing_period || !!it?.line_items;
const number = isSubscription
? `#${it?.externalSubscriptionId || it?.id}`
: `#${it?.externalOrderId || it?.id}`;
const relationship = isSubscription ? 'Subscription' : 'Order'; const relationship = isSubscription ? 'Subscription' : 'Order';
const dateRaw = it?.start_date || it?.date_created || it?.createdAt || it?.updatedAt; const dateRaw =
it?.start_date || it?.date_created || it?.createdAt || it?.updatedAt;
const dateText = dateRaw ? dayjs(dateRaw).fromNow() : '-'; const dateText = dateRaw ? dayjs(dateRaw).fromNow() : '-';
const status = (isSubscription ? it?.status : it?.orderStatus) || '-'; const status = (isSubscription ? it?.status : it?.orderStatus) || '-';
const statusLower = String(status).toLowerCase(); const statusLower = String(status).toLowerCase();
const color = statusLower === 'active' ? 'green' : statusLower === 'cancelled' ? 'red' : 'default'; const color =
statusLower === 'active'
? 'green'
: statusLower === 'cancelled'
? 'red'
: 'default';
const totalNum = Number(it?.total || 0); const totalNum = Number(it?.total || 0);
const totalText = isSubscription ? `$${totalNum.toFixed(2)} / ${it?.billing_period || 'period'}` : `$${totalNum.toFixed(2)}`; const totalText = isSubscription
return { key: `${isSubscription ? 'sub' : 'order'}-${it?.id}`, number, relationship, dateText, status, color, totalText }; ? `$${totalNum.toFixed(2)} / ${it?.billing_period || 'period'}`
: `$${totalNum.toFixed(2)}`;
return {
key: `${isSubscription ? 'sub' : 'order'}-${it?.id}`,
number,
relationship,
dateText,
status,
color,
totalText,
};
}); });
if (rows.length === 0) return <Empty description="暂无关联" />; if (rows.length === 0) return <Empty description="暂无关联" />;
@ -30,7 +49,14 @@ const RelatedOrders: React.FC<{ data?: any[] }> = ({ data = [] }) => {
return ( return (
<div style={{ width: '100%' }}> <div style={{ width: '100%' }}>
{/* 表头(英文文案,符合国际化默认英文的要求) */} {/* 表头(英文文案,符合国际化默认英文的要求) */}
<div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr 1fr', padding: '8px 0', fontWeight: 600 }}> <div
style={{
display: 'grid',
gridTemplateColumns: '1.5fr 1fr 1fr 1fr 1fr',
padding: '8px 0',
fontWeight: 600,
}}
>
<div></div> <div></div>
<div></div> <div></div>
<div></div> <div></div>
@ -39,11 +65,23 @@ const RelatedOrders: React.FC<{ data?: any[] }> = ({ data = [] }) => {
</div> </div>
<div> <div>
{rows.map((r) => ( {rows.map((r) => (
<div key={r.key} style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr 1fr', padding: '6px 0', borderTop: '1px solid #f0f0f0' }}> <div
<div><a>{r.number}</a></div> key={r.key}
style={{
display: 'grid',
gridTemplateColumns: '1.5fr 1fr 1fr 1fr 1fr',
padding: '6px 0',
borderTop: '1px solid #f0f0f0',
}}
>
<div>
<a>{r.number}</a>
</div>
<div>{r.relationship}</div> <div>{r.relationship}</div>
<div style={{ color: '#1677ff' }}>{r.dateText}</div> <div style={{ color: '#1677ff' }}>{r.dateText}</div>
<div><Tag color={r.color}>{r.status}</Tag></div> <div>
<Tag color={r.color}>{r.status}</Tag>
</div>
<div>{r.totalText}</div> <div>{r.totalText}</div>
</div> </div>
))} ))}

View File

@ -1,12 +1,16 @@
import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType, ProTableProps } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { App, Tag, Button } from 'antd';
import dayjs from 'dayjs';
import { ordercontrollerGetorders } from '@/servers/api/order'; import { ordercontrollerGetorders } from '@/servers/api/order';
import OrderDetailDrawer from './OrderDetailDrawer';
import { sitecontrollerAll } from '@/servers/api/site'; import { sitecontrollerAll } from '@/servers/api/site';
import type {
ActionType,
ProColumns,
ProTableProps,
} from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { App, Button, Tag } from 'antd';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';
import OrderDetailDrawer from './OrderDetailDrawer';
interface OrderItemRow { interface OrderItemRow {
id: number; id: number;
@ -43,7 +47,10 @@ const OrdersPage: React.FC = () => {
valueType: 'select', valueType: 'select',
request: async () => { request: async () => {
const { data = [] } = await sitecontrollerAll(); const { data = [] } = await sitecontrollerAll();
return (data || []).map((item: any) => ({ label: item.siteName, value: item.id })); return (data || []).map((item: any) => ({
label: item.siteName,
value: item.id,
}));
}, },
}, },
{ {
@ -51,7 +58,10 @@ const OrdersPage: React.FC = () => {
dataIndex: 'date_created', dataIndex: 'date_created',
width: 180, width: 180,
hideInSearch: true, hideInSearch: true,
render: (_, row) => (row?.date_created ? dayjs(row.date_created).format('YYYY-MM-DD HH:mm') : '-'), render: (_, row) =>
row?.date_created
? dayjs(row.date_created).format('YYYY-MM-DD HH:mm')
: '-',
}, },
{ {
title: '邮箱', title: '邮箱',
@ -109,7 +119,14 @@ const OrdersPage: React.FC = () => {
const request: ProTableProps<OrderItemRow>['request'] = async (params) => { const request: ProTableProps<OrderItemRow>['request'] = async (params) => {
try { try {
const { current = 1, pageSize = 10, siteId, keyword, customer_email, payment_method } = params as any; const {
current = 1,
pageSize = 10,
siteId,
keyword,
customer_email,
payment_method,
} = params as any;
const [startDate, endDate] = (params as any).dateRange || []; const [startDate, endDate] = (params as any).dateRange || [];
const resp = await ordercontrollerGetorders({ const resp = await ordercontrollerGetorders({
current, current,
@ -119,7 +136,9 @@ const OrdersPage: React.FC = () => {
customer_email, customer_email,
payment_method, payment_method,
isSubscriptionOnly: true as any, isSubscriptionOnly: true as any,
startDate: startDate ? (dayjs(startDate).toISOString() as any) : undefined, startDate: startDate
? (dayjs(startDate).toISOString() as any)
: undefined,
endDate: endDate ? (dayjs(endDate).toISOString() as any) : undefined, endDate: endDate ? (dayjs(endDate).toISOString() as any) : undefined,
} as any); } as any);
const { success, data, message: errMsg } = resp as any; const { success, data, message: errMsg } = resp as any;
@ -136,10 +155,10 @@ const OrdersPage: React.FC = () => {
}; };
return ( return (
<PageContainer title='订阅订单'> <PageContainer title="订阅订单">
<ProTable<OrderItemRow> <ProTable<OrderItemRow>
actionRef={actionRef} actionRef={actionRef}
rowKey='id' rowKey="id"
columns={columns} columns={columns}
request={request} request={request}
pagination={{ showSizeChanger: true }} pagination={{ showSizeChanger: true }}

View File

@ -87,7 +87,9 @@ const List: React.FC = () => {
rowKey="id" rowKey="id"
toolBarRender={() => [<CreateForm tableRef={actionRef} />]} toolBarRender={() => [<CreateForm tableRef={actionRef} />]}
request={async (params) => { request={async (params) => {
const response = await templatecontrollerGettemplatelist(params as any) as any; const response = (await templatecontrollerGettemplatelist(
params as any,
)) as any;
return { return {
data: response.items || [], data: response.items || [],
total: response.total || 0, total: response.total || 0,
@ -202,5 +204,4 @@ const UpdateForm: React.FC<{
); );
}; };
export default List; export default List;

View File

@ -1,6 +1,6 @@
import { import {
logisticscontrollerGetlistbyorderid,
logisticscontrollerGetorderlist, logisticscontrollerGetorderlist,
logisticscontrollerGetlistbyorderid
} from '@/servers/api/logistics'; } from '@/servers/api/logistics';
import { SearchOutlined } from '@ant-design/icons'; import { SearchOutlined } from '@ant-design/icons';
import { PageContainer, ProFormSelect } from '@ant-design/pro-components'; import { PageContainer, ProFormSelect } from '@ant-design/pro-components';
@ -16,8 +16,9 @@ const TrackPage: React.FC = () => {
debounceTime={500} debounceTime={500}
request={async ({ keyWords }) => { request={async ({ keyWords }) => {
if (!keyWords || keyWords.length < 3) return []; if (!keyWords || keyWords.length < 3) return [];
const { data: trackList } = const { data: trackList } = await logisticscontrollerGetorderlist({
await logisticscontrollerGetorderlist({ number: keyWords }); number: keyWords,
});
return trackList?.map((v) => { return trackList?.map((v) => {
return { return {
label: v.siteName + ' ' + v.externalOrderId, label: v.siteName + ' ' + v.externalOrderId,
@ -29,7 +30,7 @@ const TrackPage: React.FC = () => {
prefix: '订单号', prefix: '订单号',
async onChange(value: string) { async onChange(value: string) {
setId(value); setId(value);
setData({}) setData({});
const { data } = await logisticscontrollerGetlistbyorderid({ const { data } = await logisticscontrollerGetlistbyorderid({
id, id,
@ -53,8 +54,7 @@ const TrackPage: React.FC = () => {
), ),
}} }}
/> />
{ {data?.item ? (
data?.item ?
<div> <div>
<div> <div>
<h4></h4> <h4></h4>
@ -64,10 +64,11 @@ const TrackPage: React.FC = () => {
</div> </div>
))} ))}
</div> </div>
</div> : <></> </div>
} ) : (
{ <></>
data?.saleItem ? )}
{data?.saleItem ? (
<div> <div>
<div> <div>
<h4></h4> <h4></h4>
@ -77,8 +78,10 @@ const TrackPage: React.FC = () => {
</div> </div>
))} ))}
</div> </div>
</div> : <></> </div>
} ) : (
<></>
)}
</PageContainer> </PageContainer>
); );
}; };

8
typings.d.ts vendored
View File

@ -1,16 +1,14 @@
import '@umijs/max/typings'; import '@umijs/max/typings';
declare namespace BaseType { declare namespace BaseType {
type EnumTransformOptions = {
type EnumTransformOptions {
value: string; // 用于作为 value 的字段名 value: string; // 用于作为 value 的字段名
label: string; // 用于作为 text 的字段名 label: string; // 用于作为 text 的字段名
status?: string | undefined; // 可选:用于设置状态的字段名 status?: string | undefined; // 可选:用于设置状态的字段名
color?: string | undefined; // 可选:用于设置颜色的字段名 color?: string | undefined; // 可选:用于设置颜色的字段名
} };
} }
declare global { declare global {
const UMI_APP_API_URL: string; const UMI_APP_API_URL: string;
} }