Compare commits

..

5 Commits

Author SHA1 Message Date
zhuotianyuan af1cebe29d fix(订单同步): 修复订单同步功能并添加日期范围选择
修复订单同步接口调用参数错误
在同步表单中添加日期范围选择器
调整订单来源统计接口名称拼写错误
2026-01-14 20:04:07 +08:00
tikkhun d0097aec38 feat(Product): 新增品牌空间页面
refactor: 优化订单列表和统计页面的代码格式和逻辑

style: 调整多个页面的代码格式和导入顺序

fix: 修复订单列表中的物流信息显示问题

chore: 更新路由配置添加品牌空间页面
2026-01-14 19:57:15 +08:00
tikkhun 66256acee0 feat(产品分类): 在分类页面显示短名称并支持编辑短名称字段
feat(CSV工具): 增强SKU生成功能并支持CSV文件解析

1. 在分类页面显示短名称并支持编辑短名称字段
2. 重构SKU生成逻辑,支持更多属性组合
3. 添加对CSV文件的支持,优化中文编码处理
4. 增加尺寸和数量属性支持
5. 添加为single类型生成bundle SKU的选项
6. 优化表单选项显示,同时展示名称和短名称
2026-01-14 19:54:13 +08:00
zhuotianyuan bf32957f0a feat: 添加webhook地址字段和区域选择功能
在站点列表和编辑表单中添加webhook地址字段
在订单列表中添加付款日期字段
在统计页面添加国家/区域选择功能,支持多选和搜索
引入i18n-iso-countries库实现国家名称本地化
2026-01-10 07:27:41 +00:00
tikkhun 49448cefb5 feat(Product): 实现产品SKU批量生成工具页面
添加CSV工具页面,支持上传CSV/Excel文件并根据配置自动生成SKU
移除EditForm中未使用的siteSkuCodes状态及相关逻辑
2026-01-10 15:19:14 +08:00
26 changed files with 2067 additions and 368 deletions

View File

@ -164,6 +164,11 @@ export default defineConfig({
path: '/product/attribute',
component: './Product/Attribute',
},
{
name: '产品品牌空间',
path: '/product/brandspace',
component: './Product/BrandSpace',
},
// sync
{
name: '同步产品',
@ -174,7 +179,7 @@ export default defineConfig({
name: '产品CSV 工具',
path: '/product/csvtool',
component: './Product/CsvTool',
}
},
],
},
{

View File

@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { sitecontrollerAll } from '@/servers/api/site';
import { useEffect, useState } from 'react';
// 站点数据的类型定义
interface Site {

View File

@ -116,7 +116,6 @@ const CustomerList: React.FC = () => {
const { message } = App.useApp();
const [syncModalVisible, setSyncModalVisible] = useState(false);
const columns: ProColumns<API.GetCustomerDTO>[] = [
{
title: 'ID',
@ -318,25 +317,27 @@ const CustomerList: React.FC = () => {
actionRef={actionRef}
columns={columns}
rowKey="id"
request={async (params, sorter,filter) => {
console.log('custoemr request',params, sorter,filter)
request={async (params, sorter, filter) => {
console.log('custoemr request', params, sorter, filter);
const { current, pageSize, ...restParams } = params;
const orderBy:any = {}
const orderBy: any = {};
Object.entries(sorter).forEach(([key, value]) => {
orderBy[key] = value === 'ascend' ? 'asc' : 'desc';
})
});
// 构建查询参数
const queryParams: any = {
page: current || 1,
per_page: pageSize || 20,
where: {
...filter,
...restParams
...restParams,
},
orderBy
orderBy,
};
const result = await customercontrollerGetcustomerlist({params: queryParams});
const result = await customercontrollerGetcustomerlist({
params: queryParams,
});
console.log(queryParams, result);
return {
total: result?.data?.total || 0,
@ -344,7 +345,6 @@ const CustomerList: React.FC = () => {
success: true,
};
}}
search={{
labelWidth: 'auto',
span: 6,

View File

@ -137,7 +137,8 @@ const ListPage: React.FC = () => {
{
title: '账单地址',
dataIndex: 'billing',
render: (_, record) => JSON.stringify(record?.billing || record?.shipping),
render: (_, record) =>
JSON.stringify(record?.billing || record?.shipping),
},
{
title: '标签',

View File

@ -56,6 +56,7 @@ import {
ProFormTextArea,
ProTable,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
import {
App,
Button,
@ -76,7 +77,6 @@ import {
} from 'antd';
import React, { useMemo, useRef, useState } from 'react';
import RelatedOrders from '../../Subscription/Orders/RelatedOrders';
import { request } from '@umijs/max';
const ListPage: React.FC = () => {
const actionRef = useRef<ActionType>();
@ -191,7 +191,7 @@ const ListPage: React.FC = () => {
request: async () => {
try {
const result = await sitecontrollerAll();
const {success, data}= result
const { success, data } = result;
if (success && data) {
return data.map((site: any) => ({
label: site.name,
@ -281,9 +281,15 @@ const ListPage: React.FC = () => {
{(record as any)?.fulfillments?.map((item: any) => {
if (!item) return;
return (
<div style={{ display:"flex", alignItems:"center",'flexDirection':'column' }}>
<span>: {item.shipping_provider}</span>
<span>: {item.tracking_number}</span>
<div
style={{
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
}}
>
<span>: {item.shipping_provider}</span>
<span>: {item.tracking_number}</span>
</div>
);
})}
@ -519,10 +525,12 @@ const ListPage: React.FC = () => {
method: 'POST',
data: {
ids: selectedRowKeys,
}
},
});
if (res?.success && res.data) {
const blob = new Blob([res.data], { type: 'text/csv;charset=utf-8;' });
const blob = new Blob([res.data], {
type: 'text/csv;charset=utf-8;',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
@ -539,10 +547,7 @@ const ListPage: React.FC = () => {
}
}}
>
<Button
type="primary"
ghost
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
@ -634,36 +639,36 @@ const Detail: React.FC<{
)
? []
: [
<Divider type="vertical" />,
<Button
type="primary"
onClick={async () => {
try {
if (!record.siteId || !record.externalOrderId) {
message.error('站点ID或外部订单ID不存在');
return;
<Divider type="vertical" />,
<Button
type="primary"
onClick={async () => {
try {
if (!record.siteId || !record.externalOrderId) {
message.error('站点ID或外部订单ID不存在');
return;
}
const {
success,
message: errMsg,
data,
} = await ordercontrollerSyncorderbyid({
siteId: record.siteId,
orderId: record.externalOrderId,
});
if (!success) {
throw new Error(errMsg);
}
showSyncResult(data as SyncResultData, '订单');
tableRef.current?.reload();
} catch (error: any) {
message.error(error?.message || '同步失败');
}
const {
success,
message: errMsg,
data,
} = await ordercontrollerSyncorderbyid({
siteId: record.siteId,
orderId: record.externalOrderId,
});
if (!success) {
throw new Error(errMsg);
}
showSyncResult(data as SyncResultData, '订单');
tableRef.current?.reload();
} catch (error: any) {
message.error(error?.message || '同步失败');
}
}}
>
</Button>,
]),
}}
>
</Button>,
]),
// ...(['processing', 'pending_reshipment'].includes(record.orderStatus)
// ? [
// <Divider type="vertical" />,
@ -682,152 +687,152 @@ const Detail: React.FC<{
'pending_refund',
].includes(record.orderStatus)
? [
<Divider type="vertical" />,
<Popconfirm
title="转至售后"
description="确认转至售后?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
<Divider type="vertical" />,
<Popconfirm
title="转至售后"
description="确认转至售后?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerChangestatus(
{
id: record.id,
},
{
status: 'after_sale_pending',
},
);
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
const { success, message: errMsg } =
await ordercontrollerChangestatus(
{
id: record.id,
},
{
status: 'after_sale_pending',
},
);
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
]
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
]
: []),
...(record.orderStatus === 'after_sale_pending'
? [
<Divider type="vertical" />,
<Popconfirm
title="转至取消"
description="确认转至取消?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerCancelorder({
id: record.id,
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
<Divider type="vertical" />,
<Popconfirm
title="转至退款"
description="确认转至退款?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerRefundorder({
id: record.id,
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
退
</Button>
</Popconfirm>,
<Divider type="vertical" />,
<Popconfirm
title="转至完成"
description="确认转至完成?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerCompletedorder({
id: record.id,
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
<Divider type="vertical" />,
<Popconfirm
title="转至待补发"
description="确认转至待补发?"
onConfirm={async () => {
try {
const { success, message: errMsg } =
await ordercontrollerChangestatus(
{
<Divider type="vertical" />,
<Popconfirm
title="转至取消"
description="确认转至取消?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerCancelorder({
id: record.id,
},
{
status: 'pending_reshipment',
},
);
if (!success) {
throw new Error(errMsg);
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
]
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
<Divider type="vertical" />,
<Popconfirm
title="转至退款"
description="确认转至退款?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerRefundorder({
id: record.id,
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
退
</Button>
</Popconfirm>,
<Divider type="vertical" />,
<Popconfirm
title="转至完成"
description="确认转至完成?"
onConfirm={async () => {
try {
if (!record.id) {
message.error('订单ID不存在');
return;
}
const { success, message: errMsg } =
await ordercontrollerCompletedorder({
id: record.id,
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
<Divider type="vertical" />,
<Popconfirm
title="转至待补发"
description="确认转至待补发?"
onConfirm={async () => {
try {
const { success, message: errMsg } =
await ordercontrollerChangestatus(
{
id: record.id,
},
{
status: 'pending_reshipment',
},
);
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
} catch (error: any) {
message.error(error.message);
}
}}
>
<Button type="primary" ghost>
</Button>
</Popconfirm>,
]
: []),
]}
>
@ -1090,31 +1095,31 @@ const Detail: React.FC<{
}
actions={
v.state === 'waiting-for-scheduling' ||
v.state === 'waiting-for-transit'
v.state === 'waiting-for-transit'
? [
<Popconfirm
title="取消运单"
description="确认取消运单?"
onConfirm={async () => {
try {
const { success, message: errMsg } =
await logisticscontrollerDelshipment({
id: v.id,
});
if (!success) {
throw new Error(errMsg);
<Popconfirm
title="取消运单"
description="确认取消运单?"
onConfirm={async () => {
try {
const { success, message: errMsg } =
await logisticscontrollerDelshipment({
id: v.id,
});
if (!success) {
throw new Error(errMsg);
}
tableRef.current?.reload();
initRequest();
} catch (error: any) {
message.error(error.message);
}
tableRef.current?.reload();
initRequest();
} catch (error: any) {
message.error(error.message);
}
}}
>
<DeleteFilled />
</Popconfirm>,
]
}}
>
<DeleteFilled />
</Popconfirm>,
]
: []
}
>
@ -1936,7 +1941,7 @@ const Shipping: React.FC<{
name="description"
placeholder="请输入描述"
width="lg"
// rules={[{ required: true, message: '请输入描述' }]}
// rules={[{ required: true, message: '请输入描述' }]}
/>
</ProForm.Group>
</ProFormList>

View File

@ -2,6 +2,7 @@ import * as dictApi from '@/servers/api/dict';
import {
ActionType,
PageContainer,
ProColumns,
ProTable,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
@ -219,11 +220,35 @@ const AttributePage: React.FC = () => {
];
// 右侧字典项列表列定义(紧凑样式)
const dictItemColumns: any[] = [
{ title: '名称', dataIndex: 'name', key: 'name', copyable: true },
{ title: '标题', dataIndex: 'title', key: 'title', copyable: true },
{ title: '中文标题', dataIndex: 'titleCN', key: 'titleCN', copyable: true },
{ title: '简称', dataIndex: 'shortName', key: 'shortName', copyable: true },
const dictItemColumns: ProColumns<any>[] = [
{
title: '名称',
dataIndex: 'name',
key: 'name',
copyable: true,
sorter: true,
},
{
title: '标题',
dataIndex: 'title',
key: 'title',
copyable: true,
sorter: true,
},
{
title: '中文标题',
dataIndex: 'titleCN',
key: 'titleCN',
copyable: true,
sorter: true,
},
{
title: '简称',
dataIndex: 'shortName',
key: 'shortName',
copyable: true,
sorter: true,
},
{
title: '图片',
dataIndex: 'image',

View File

@ -0,0 +1,452 @@
import { PageContainer } from '@ant-design/pro-components';
import { request } from '@umijs/max';
import {
Card,
Col,
Image,
Layout,
Row,
Select,
Space,
Typography,
message,
} from 'antd';
import React, { useEffect, useState } from 'react';
const { Sider, Content } = Layout;
const { Title, Text } = Typography;
const { Option } = Select;
// Define interfaces
interface Brand {
id: number;
name: string;
shortName?: string;
image?: string;
}
interface Attribute {
id: number;
name: string;
title: string;
}
interface AttributeValue {
id: number;
name: string;
title: string;
titleCN?: string;
value?: string;
image?: string;
}
interface Product {
id: number;
sku: string;
name: string;
image?: string;
brandId: number;
brandName: string;
attributes: { [key: string]: any };
}
const BrandSpace: React.FC = () => {
// State management
const [brands, setBrands] = useState<Brand[]>([]);
const [selectedBrand, setSelectedBrand] = useState<number | null>(null);
const [attributes, setAttributes] = useState<Attribute[]>([]);
const [selectedAttribute, setSelectedAttribute] = useState<string | null>(
null,
);
const [attributeValues, setAttributeValues] = useState<AttributeValue[]>([]);
const [selectedAttributeValue, setSelectedAttributeValue] = useState<
number | null
>(null);
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(false);
// Fetch brands list
const fetchBrands = async () => {
try {
const response = await request('/dict/items', {
params: { dictId: 'brand' }, // Assuming brand is a dict
});
const brandList = Array.isArray(response)
? response
: response?.data || [];
setBrands(brandList);
// Set default brand to "yoone" if exists
const defaultBrand = brandList.find((brand) => brand.name === 'yoone');
if (defaultBrand) {
setSelectedBrand(defaultBrand.id);
}
} catch (error) {
console.error('Failed to fetch brands:', error);
message.error('获取品牌列表失败');
}
};
// Fetch attributes list
const fetchAttributes = async () => {
try {
// Get all dicts that are attributes (excluding non-attribute dicts)
const response = await request('/dict/list');
const dictList = Array.isArray(response)
? response
: response?.data || [];
// Filter out non-attribute dicts (assuming attributes are specific dicts)
const attributeDicts = dictList.filter((dict: any) =>
['strength', 'flavor', 'humidity', 'size', 'version'].includes(
dict.name,
),
);
setAttributes(attributeDicts);
// Set default attribute to strength if exists
const defaultAttribute = attributeDicts.find(
(attr) => attr.name === 'strength',
);
if (defaultAttribute) {
setSelectedAttribute(defaultAttribute.name);
}
} catch (error) {
console.error('Failed to fetch attributes:', error);
message.error('获取属性列表失败');
}
};
// Fetch attribute values based on selected attribute
const fetchAttributeValues = async (attributeName: string) => {
try {
const response = await request('/dict/items', {
params: { dictId: attributeName },
});
const values = Array.isArray(response) ? response : response?.data || [];
setAttributeValues(values);
} catch (error) {
console.error('Failed to fetch attribute values:', error);
message.error('获取属性值列表失败');
}
};
// Fetch products based on filters
const fetchProducts = async () => {
if (!selectedBrand) return;
setLoading(true);
try {
const params: any = {
brandId: selectedBrand,
};
// Add attribute filter if selected
if (selectedAttribute) {
// If attribute value is selected, filter by both attribute and value
if (selectedAttributeValue) {
params[selectedAttribute] = selectedAttributeValue;
} else {
// If only attribute is selected, filter by attribute presence
params[selectedAttribute] = 'hasValue';
}
}
const response = await request('/product/list', {
params,
});
const productList = Array.isArray(response)
? response
: response?.data || [];
setProducts(productList);
} catch (error) {
console.error('Failed to fetch products:', error);
message.error('获取产品列表失败');
} finally {
setLoading(false);
}
};
// Initial data fetch
useEffect(() => {
fetchBrands();
fetchAttributes();
}, []);
// Fetch attribute values when attribute changes
useEffect(() => {
if (selectedAttribute) {
fetchAttributeValues(selectedAttribute);
setSelectedAttributeValue(null); // Reset selected value when attribute changes
}
}, [selectedAttribute]);
// Fetch products when filters change
useEffect(() => {
fetchProducts();
}, [selectedBrand, selectedAttribute, selectedAttributeValue]);
// Handle brand selection change
const handleBrandChange = (value: number) => {
setSelectedBrand(value);
};
// Handle attribute selection change
const handleAttributeChange = (value: string) => {
setSelectedAttribute(value);
};
// Handle attribute value selection change
const handleAttributeValueChange = (value: number) => {
setSelectedAttributeValue(value);
};
return (
<PageContainer title="品牌空间">
<Layout style={{ minHeight: 'calc(100vh - 64px)', background: '#fff' }}>
{/* Top Brand Selection */}
<div style={{ padding: '16px', borderBottom: '1px solid #f0f0f0' }}>
<Space direction="vertical" style={{ width: '100%' }}>
<Title level={4} style={{ margin: 0 }}>
</Title>
<Select
placeholder="请选择品牌"
style={{ width: 300 }}
value={selectedBrand}
onChange={handleBrandChange}
allowClear
>
{brands.map((brand) => (
<Option key={brand.id} value={brand.id}>
{brand.name}
</Option>
))}
</Select>
</Space>
</div>
<Layout>
{/* Left Attribute Selection */}
<Sider
width={240}
style={{ background: '#fafafa', borderRight: '1px solid #f0f0f0' }}
>
<div style={{ padding: '16px' }}>
<Space direction="vertical" style={{ width: '100%' }}>
<Title level={5} style={{ margin: 0 }}>
</Title>
<Select
placeholder="请选择属性类型"
style={{ width: '100%' }}
value={selectedAttribute}
onChange={handleAttributeChange}
allowClear
>
{attributes.map((attr) => (
<Option key={attr.id} value={attr.name}>
{attr.title}
</Option>
))}
</Select>
{selectedAttribute && (
<>
<Title level={5} style={{ margin: '16px 0 8px 0' }}>
</Title>
<Select
placeholder={`请选择${
attributes.find((a) => a.name === selectedAttribute)
?.title
}`}
style={{ width: '100%' }}
value={selectedAttributeValue}
onChange={handleAttributeValueChange}
allowClear
>
{attributeValues.map((value) => (
<Option key={value.id} value={value.id}>
<Space>
{value.image && (
<Image
src={value.image}
style={{
width: 24,
height: 24,
objectFit: 'cover',
borderRadius: 4,
}}
/>
)}
<span>
{value.titleCN || value.title || value.name}
</span>
</Space>
</Option>
))}
</Select>
</>
)}
{/* Filter Summary */}
{selectedBrand && (
<div
style={{
marginTop: 24,
padding: 12,
background: '#fff',
borderRadius: 8,
}}
>
<Text strong>:</Text>
<div style={{ marginTop: 8 }}>
<Text type="secondary">: </Text>
<Text>
{brands.find((b) => b.id === selectedBrand)?.name}
</Text>
</div>
{selectedAttribute && (
<div style={{ marginTop: 4 }}>
<Text type="secondary">
{
attributes.find((a) => a.name === selectedAttribute)
?.title
}
:
</Text>
<Text>
{selectedAttributeValue
? attributeValues.find(
(v) => v.id === selectedAttributeValue,
)?.titleCN ||
attributeValues.find(
(v) => v.id === selectedAttributeValue,
)?.title
: '所有值'}
</Text>
</div>
)}
</div>
)}
</Space>
</div>
</Sider>
{/* Main Content - Product List */}
<Content style={{ padding: '16px' }}>
<div style={{ marginBottom: 16 }}>
<Title level={4} style={{ margin: 0 }}>
<Text type="secondary" style={{ fontSize: 16, marginLeft: 8 }}>
({products.length} )
</Text>
</Title>
</div>
{loading ? (
<div style={{ textAlign: 'center', padding: '64px' }}>
<Text>...</Text>
</div>
) : products.length > 0 ? (
<Row gutter={[16, 16]}>
{products.map((product) => (
<Col xs={24} sm={12} md={8} lg={6} key={product.id}>
<Card
hoverable
style={{
height: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
<div
style={{
height: 200,
overflow: 'hidden',
marginBottom: 12,
}}
>
<Image
src={
product.image ||
'https://via.placeholder.com/200x200?text=No+Image'
}
alt={product.name}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
</div>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
}}
>
<Text
type="secondary"
style={{ fontSize: 12, marginBottom: 4 }}
>
{product.sku}
</Text>
<Title
level={5}
style={{
margin: '4px 0',
fontSize: 16,
height: 48,
overflow: 'hidden',
}}
>
{product.name}
</Title>
<div
style={{
marginTop: 'auto',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Text
strong
style={{ fontSize: 18, color: '#ff4d4f' }}
>
¥{product.price || '--'}
</Text>
</div>
</div>
</Card>
</Col>
))}
</Row>
) : (
<div
style={{
textAlign: 'center',
padding: '64px',
background: '#fafafa',
borderRadius: 8,
}}
>
<Text type="secondary"></Text>
</div>
)}
</Content>
</Layout>
</Layout>
</PageContainer>
);
};
export default BrandSpace;

View File

@ -246,7 +246,7 @@ const CategoryPage: React.FC = () => {
>
<List.Item.Meta
title={`${item.title}(${item.titleCN ?? '-'})`}
description={item.name}
description={`${item.name} | ${item.shortName ?? '-'}`}
/>
</List.Item>
)}
@ -255,7 +255,9 @@ const CategoryPage: React.FC = () => {
<Content style={{ padding: '24px' }}>
{selectedCategory ? (
<Card
title={`分类:${selectedCategory.title} (${selectedCategory.name})`}
title={`分类:${selectedCategory.title} (${
selectedCategory.shortName ?? selectedCategory.name
})`}
extra={
<Button type="primary" onClick={handleAddAttribute}>
@ -319,6 +321,9 @@ const CategoryPage: React.FC = () => {
<Form.Item name="titleCN" label="中文名称">
<Input />
</Form.Item>
<Form.Item name="shortName" label="短名称">
<Input />
</Form.Item>
<Form.Item name="name" label="标识 (Code)">
<Input />
</Form.Item>

View File

@ -1,7 +1,905 @@
export default function CsvTool() {
return (
<div>
<h1>CSV </h1>
</div>
);
import { productcontrollerGetcategoriesall } from '@/servers/api/product';
import { UploadOutlined } from '@ant-design/icons';
import {
PageContainer,
ProForm,
ProFormSelect,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
import { Button, Card, Checkbox, Col, Input, message, Row, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import * as XLSX from 'xlsx';
// 定义站点接口
interface Site {
id: number;
name: string;
skuPrefix?: string;
isDisabled?: boolean;
}
// 定义选项接口,用于下拉选择框的选项
interface Option {
name: string; // 显示名称
shortName: string; // 短名称用于生成SKU
}
// 定义配置接口
interface SkuConfig {
brands: Option[];
categories: Option[];
flavors: Option[];
strengths: Option[];
humidities: Option[];
versions: Option[];
sizes: Option[];
quantities: Option[];
}
// 定义通用属性映射接口用于存储属性名称和shortName的对应关系
interface AttributeMapping {
[attributeName: string]: string; // key: 属性名称, value: 属性shortName
}
// 定义所有属性映射的接口
interface AttributeMappings {
brands: AttributeMapping;
categories: AttributeMapping;
flavors: AttributeMapping;
strengths: AttributeMapping;
humidities: AttributeMapping;
versions: AttributeMapping;
sizes: AttributeMapping;
quantities: AttributeMapping;
}
/**
* @description CSV工具页面SKU
*/
const CsvTool: React.FC = () => {
// 状态管理
const [form] = ProForm.useForm();
const [file, setFile] = useState<File | null>(null);
const [csvData, setCsvData] = useState<any[]>([]);
const [processedData, setProcessedData] = useState<any[]>([]);
const [isProcessing, setIsProcessing] = useState(false);
const [sites, setSites] = useState<Site[]>([]);
const [selectedSites, setSelectedSites] = useState<Site[]>([]); // 现在使用多选
const [generateBundleSkuForSingle, setGenerateBundleSkuForSingle] =
useState(true); // 是否为type为single的记录生成包含quantity的bundle SKU
const [config, setConfig] = useState<SkuConfig>({
brands: [],
categories: [],
flavors: [],
strengths: [],
humidities: [],
versions: [],
sizes: [],
quantities: [],
});
// 所有属性名称到shortName的映射
const [attributeMappings, setAttributeMappings] = useState<AttributeMappings>(
{
brands: {},
categories: {},
flavors: {},
strengths: {},
humidities: {},
versions: {},
sizes: {},
quantities: {},
},
);
// 在组件加载时获取站点列表和字典数据
useEffect(() => {
const fetchAllData = async () => {
try {
message.loading({ content: '正在加载数据...', key: 'loading' });
// 1. 获取站点列表
const sitesResponse = await request('/site/all');
const siteList = sitesResponse?.data || sitesResponse || [];
setSites(siteList);
// 默认选择所有站点
setSelectedSites(siteList);
// 2. 获取字典数据
const dictListResponse = await request('/dict/list');
const dictList = dictListResponse?.data || dictListResponse || [];
// 3. 根据字典名称获取字典项返回包含name和shortName的完整对象数组
const getDictItems = async (dictName: string) => {
try {
const dict = dictList.find((d: any) => d.name === dictName);
if (!dict) {
console.warn(`Dictionary ${dictName} not found`);
return { options: [], mapping: {} };
}
const itemsResponse = await request('/dict/items', {
params: { dictId: dict.id },
});
const items = itemsResponse?.data || itemsResponse || [];
// 创建完整的选项数组
const options = items.map((item: any) => ({
name: item.name,
shortName: item.shortName || item.name,
}));
// 创建name到shortName的映射
const mapping = items.reduce((acc: AttributeMapping, item: any) => {
acc[item.name] = item.shortName || item.name;
return acc;
}, {});
return { options, mapping };
} catch (error) {
console.error(`Failed to fetch items for ${dictName}:`, error);
return { options: [], mapping: {} };
}
};
// 4. 获取所有字典项(品牌、口味、强度、湿度、版本、尺寸、数量)
const [
brandResult,
flavorResult,
strengthResult,
humidityResult,
versionResult,
sizeResult,
quantityResult,
] = await Promise.all([
getDictItems('brand'),
getDictItems('flavor'),
getDictItems('strength'),
getDictItems('humidity'),
getDictItems('version'),
getDictItems('size'),
getDictItems('quantity'),
]);
// 5. 获取商品分类列表
const categoriesResponse = await productcontrollerGetcategoriesall();
const categoryOptions =
categoriesResponse?.data?.map((category: any) => ({
name: category.name,
shortName: category.shortName || category.name,
})) || [];
// 商品分类的映射如果分类有shortName的话
const categoryMapping =
categoriesResponse?.data?.reduce(
(acc: AttributeMapping, category: any) => {
acc[category.name] = category.shortName || category.name;
return acc;
},
{},
) || {};
// 6. 设置所有属性映射
setAttributeMappings({
brands: brandResult.mapping,
categories: categoryMapping,
flavors: flavorResult.mapping,
strengths: strengthResult.mapping,
humidities: humidityResult.mapping,
versions: versionResult.mapping,
sizes: sizeResult.mapping,
quantities: quantityResult.mapping,
});
// 更新配置状态
const newConfig = {
brands: brandResult.options,
categories: categoryOptions,
flavors: flavorResult.options,
strengths: strengthResult.options,
humidities: humidityResult.options,
versions: versionResult.options,
sizes: sizeResult.options,
quantities: quantityResult.options,
};
setConfig(newConfig);
// 设置表单值时只需要name数组
form.setFieldsValue({
brands: brandResult.options.map((opt) => opt.name),
categories: categoryOptions.map((opt) => opt.name),
flavors: flavorResult.options.map((opt) => opt.name),
strengths: strengthResult.options.map((opt) => opt.name),
humidities: humidityResult.options.map((opt) => opt.name),
versions: versionResult.options.map((opt) => opt.name),
sizes: sizeResult.options.map((opt) => opt.name),
quantities: quantityResult.options.map((opt) => opt.name),
generateBundleSkuForSingle: true,
});
message.success({ content: '数据加载成功', key: 'loading' });
} catch (error) {
console.error('Failed to fetch data:', error);
message.error({
content: '数据加载失败,请刷新页面重试',
key: 'loading',
});
}
};
fetchAllData();
}, [form]);
/**
* @description
*/
const handleFileUpload = (uploadedFile: File) => {
// 检查文件类型
if (!uploadedFile.name.match(/\.(csv|xlsx|xls)$/)) {
message.error('请上传 CSV 或 Excel 格式的文件!');
return false;
}
setFile(uploadedFile);
const reader = new FileReader();
// 检查是否为CSV文件
const isCsvFile = uploadedFile.name.match(/\.csv$/i);
if (isCsvFile) {
// 对于CSV文件使用readAsText并指定UTF-8编码以正确处理中文
reader.onload = (e) => {
try {
const textData = e.target?.result as string;
// 使用XLSX.read处理CSV文本数据指定type为'csv'并设置编码
const workbook = XLSX.read(textData, {
type: 'string',
codepage: 65001, // UTF-8 encoding
cellText: true,
cellDates: true,
});
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
if (jsonData.length < 2) {
message.error('文件为空或缺少表头!');
setCsvData([]);
return;
}
// 将数组转换为对象数组
const headers = jsonData[0] as string[];
const rows = jsonData.slice(1).map((rowArray: any) => {
const rowData: { [key: string]: any } = {};
headers.forEach((header, index) => {
rowData[header] = rowArray[index];
});
return rowData;
});
message.success(`成功解析 ${rows.length} 条数据.`);
setCsvData(rows);
setProcessedData([]); // 清空旧的处理结果
} catch (error) {
message.error('CSV文件解析失败,请检查文件格式和编码!');
console.error('CSV Parse Error:', error);
setCsvData([]);
}
};
reader.readAsText(uploadedFile, 'UTF-8');
} else {
// 对于Excel文件继续使用readAsArrayBuffer
reader.onload = (e) => {
try {
const data = e.target?.result;
// 如果是ArrayBuffer使用type: 'array'来处理
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
if (jsonData.length < 2) {
message.error('文件为空或缺少表头!');
setCsvData([]);
return;
}
// 将数组转换为对象数组
const headers = jsonData[0] as string[];
const rows = jsonData.slice(1).map((rowArray: any) => {
const rowData: { [key: string]: any } = {};
headers.forEach((header, index) => {
rowData[header] = rowArray[index];
});
return rowData;
});
message.success(`成功解析 ${rows.length} 条数据.`);
setCsvData(rows);
setProcessedData([]); // 清空旧的处理结果
} catch (error) {
message.error('Excel文件解析失败,请检查文件格式!');
console.error('Excel Parse Error:', error);
setCsvData([]);
}
};
reader.readAsArrayBuffer(uploadedFile);
}
reader.onerror = (error) => {
message.error('文件读取失败!');
console.error('File Read Error:', error);
};
return false; // 阻止antd Upload组件的默认上传行为
};
/**
* @description CSV并触发下载
*/
const downloadData = (data: any[]) => {
if (data.length === 0) return;
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(workbook, worksheet, 'Products with SKU');
const fileName = `products_with_sku_${Date.now()}.xlsx`;
XLSX.writeFile(workbook, fileName);
message.success('下载任务已开始!');
};
/**
* @description SKU
* @param {string} brand -
* @param {string} category -
* @param {string} flavor -
* @param {string} strength -
* @param {string} humidity - 湿
* @param {string} version -
* @param {string} type -
* @returns {string} SKU
*/
const generateSku = (
brand: string,
version: string,
category: string,
flavor: string,
strength: string,
humidity: string,
size: string,
quantity?: any,
type?: string,
): string => {
// 构建SKU组件不包含站点前缀
const skuComponents: string[] = [];
// 按顺序添加SKU组件所有属性都使用shortName
if (brand) {
// 使用品牌的shortName如果没有则使用品牌名称
const brandShortName = attributeMappings.brands[brand] || brand;
skuComponents.push(brandShortName);
}
if (version) {
// 使用版本的shortName如果没有则使用版本名称
const versionShortName = attributeMappings.versions[version] || version;
skuComponents.push(versionShortName);
}
if (category) {
// 使用分类的shortName如果没有则使用分类名称
const categoryShortName =
attributeMappings.categories[category] || category;
skuComponents.push(categoryShortName);
}
if (flavor) {
// 使用口味的shortName如果没有则使用口味名称
const flavorShortName = attributeMappings.flavors[flavor] || flavor;
skuComponents.push(flavorShortName);
}
if (strength) {
// 使用强度的shortName如果没有则使用强度名称
const strengthShortName =
attributeMappings.strengths[strength] || strength;
skuComponents.push(strengthShortName);
}
if (humidity) {
// 使用湿度的shortName如果没有则使用湿度名称
const humidityShortName =
attributeMappings.humidities[humidity] || humidity;
skuComponents.push(humidityShortName);
}
if (size) {
// 使用尺寸的shortName如果没有则使用尺寸名称
const sizeShortName = attributeMappings.sizes[size] || size;
skuComponents.push(sizeShortName);
}
// 如果type为single且启用了生成bundle SKU则添加quantity
if (
quantity
) {
console.log(quantity, attributeMappings.quantities[quantity])
// 使用quantity的shortName如果没有则使用quantity但匹配 4 个零
const quantityShortName = attributeMappings.quantities[quantity] || Number(quantity).toString().padStart(4, '0');
skuComponents.push(quantityShortName);
}
// 合并所有组件,使用短横线分隔
return skuComponents.join('-').toUpperCase();
};
/**
* @description 使
* @param {string} brand -
* @param {string} version -
* @param {string} category -
* @param {string} flavor -
* @param {string} strength -
* @param {string} humidity - 湿
* @param {string} size -
* @param {any} quantity -
* @param {string} type -
* @returns {string}
*/
const generateName = (
brand: string,
version: string,
category: string,
flavor: string,
strength: string,
humidity: string,
size: string,
quantity?: any,
type?: string,
): string => {
// 构建产品名称组件数组
const nameComponents: string[] = [];
// 按顺序添加组件:品牌 -> 版本 -> 品类 -> 风味 -> 毫克数(强度) -> 湿度 -> 型号 -> 数量
if (brand) nameComponents.push(brand);
if (version) nameComponents.push(version);
if (category) nameComponents.push(category);
if (flavor) nameComponents.push(flavor);
if (strength) nameComponents.push(strength);
if (humidity) nameComponents.push(humidity);
if (size) nameComponents.push(size);
// 如果有数量且类型为bundle或者生成bundle的single产品则添加数量
if (
type==='bundle' && quantity
) {
nameComponents.push(String(quantity));
}
// 使用空格连接所有组件
return nameComponents.join(' ');
};
/**
* @description siteSkus
* @param {string} baseSku - SKU
* @returns {string} siteSkus
*/
const generateSiteSkus = (baseSku: string): string => {
// 如果没有站点或基础SKU为空返回空字符串
if (selectedSites.length === 0 || !baseSku) return '';
// 为每个站点生成siteSku
const siteSkus = selectedSites.map((site) => {
// 如果站点有shortName则添加前缀否则使用基础SKU
if (site.skuPrefix) {
return `${site.skuPrefix}-${baseSku}`;
}
return baseSku;
});
// 使用分号分隔所有站点的siteSkus
return [baseSku, ...siteSkus].join(';').toUpperCase();
};
/**
* @description 核心逻辑:根据配置处理CSV数据并生成SKU
*/
const handleProcessData = async () => {
if (csvData.length === 0) {
message.warning('请先上传并成功解析一个CSV文件.');
return;
}
if (selectedSites.length === 0) {
message.warning('没有可用的站点.');
return;
}
setIsProcessing(true);
message.loading({ content: '正在生成SKU...', key: 'processing' });
try {
// 获取表单中的最新配置
await form.validateFields();
// 处理每条数据生成SKU和siteSkus
const dataWithSku = csvData.map((row) => {
const brand = row.attribute_brand || '';
const category = row.category || '';
const flavor = row.attribute_flavor || '';
const strength = row.attribute_strength || '';
const humidity = row.attribute_humidity || '';
const version = row.attribute_version || '';
const size = row.attribute_size || row.size || '';
// 将quantity保存到attribute_quantity字段
const quantity = row.attribute_quantity || row.quantity;
// 获取产品类型
const type = row.type || '';
// 生成基础SKU不包含站点前缀
const baseSku = generateSku(
brand,
version,
category,
flavor,
strength,
humidity,
size,
quantity,
type,
);
const name = generateName(
brand,
version,
category,
flavor,
strength,
humidity,
size,
quantity,
type,
);
// 为所有站点生成带前缀的siteSkus
const siteSkus = generateSiteSkus(baseSku);
// 返回包含新SKU和siteSkus的行数据将SKU直接保存到sku栏
return {
...row,
sku: baseSku, // 直接生成在sku栏
generatedName: name,
// name: name, // 生成的产品名称
siteSkus,
attribute_quantity: quantity, // 确保quantity保存到attribute_quantity
};
});
// Determine which data to use for processing and download
let finalData = dataWithSku;
// If generateBundleSkuForSingle is enabled, generate bundle products for single products
if (generateBundleSkuForSingle) {
// Filter out single records
const singleRecords = dataWithSku.filter(
(row) => row.type === 'single',
);
// Get quantity values from the config (same source as other attributes like brand)
const quantityValues = config.quantities.map(quantity=>quantity.name)
// Generate bundle products for each single record and quantity
const generatedBundleRecords = singleRecords.flatMap((singleRecord) => {
return quantityValues.map((quantity) => {
// Extract all necessary attributes from the single record
const brand = singleRecord.attribute_brand || '';
const version = singleRecord.attribute_version || '';
const category = singleRecord.category || '';
const flavor = singleRecord.attribute_flavor || '';
const strength = singleRecord.attribute_strength || '';
const humidity = singleRecord.attribute_humidity || '';
const size = singleRecord.attribute_size || singleRecord.size || '';
// Generate bundle SKU with the quantity
const bundleSku = generateSku(
brand,
version,
category,
flavor,
strength,
humidity,
size,
quantity,
'bundle',
);
// Generate bundle name with the quantity
const bundleName = generateName(
brand,
version,
category,
flavor,
strength,
humidity,
size,
quantity,
'bundle',
);
// Generate siteSkus for the bundle
const bundleSiteSkus = generateSiteSkus(bundleSku);
// Create the bundle record
return {
...singleRecord,
type: 'bundle', // Change type to bundle
sku: bundleSku, // Use the new bundle SKU
name: bundleName, // Use the new bundle name
siteSkus: bundleSiteSkus,
attribute_quantity: quantity, // Set the attribute_quantity
component_1_sku: singleRecord.sku, // Set component_1_sku to the single product's sku
component_1_quantity: Number(quantity), // Set component_1_quantity to the same as attribute_quantity
};
});
});
// Combine original dataWithSku with generated bundle records
finalData = [...dataWithSku, ...generatedBundleRecords];
}
// Set the processed data
setProcessedData(finalData);
message.success({
content: 'SKU生成成功!正在自动下载...',
key: 'processing',
});
// 自动下载 the final data (with or without generated bundle products)
downloadData(finalData);
} catch (error) {
message.error({
content: '处理失败,请检查配置或文件.',
key: 'processing',
});
console.error('Processing Error:', error);
} finally {
setIsProcessing(false);
}
};
return (
<PageContainer title="产品SKU批量生成工具">
<Row gutter={[16, 16]}>
{/* 左侧:配置表单 */}
<Col xs={24} md={10}>
<Card title="1. 配置SKU生成规则">
<ProForm
form={form}
initialValues={config}
onFinish={handleProcessData}
submitter={false}
>
<ProFormSelect
name="brands"
label="品牌列表"
mode="tags"
placeholder="请输入品牌,按回车确认"
rules={[{ required: true, message: '至少需要一个品牌' }]}
tooltip="品牌名称会作为SKU的第一个组成部分"
options={config.brands.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="categories"
label="商品分类"
mode="tags"
placeholder="请输入分类,按回车确认"
rules={[{ required: true, message: '至少需要一个分类' }]}
tooltip="分类名称会作为SKU的第二个组成部分"
options={config.categories.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="flavors"
label="口味列表"
mode="tags"
placeholder="请输入口味,按回车确认"
rules={[{ required: true, message: '至少需要一个口味' }]}
tooltip="口味名称会作为SKU的第三个组成部分"
options={config.flavors.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="strengths"
label="强度列表"
mode="tags"
placeholder="请输入强度,按回车确认"
tooltip="强度信息会作为SKU的第四个组成部分"
options={config.strengths.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="humidities"
label="湿度列表"
mode="tags"
placeholder="请输入湿度,按回车确认"
tooltip="湿度信息会作为SKU的第五个组成部分"
options={config.humidities.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="versions"
label="版本列表"
mode="tags"
placeholder="请输入版本,按回车确认"
tooltip="版本信息会作为SKU的第六个组成部分"
options={config.versions.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="sizes"
label="尺寸列表"
mode="tags"
placeholder="请输入尺寸,按回车确认"
tooltip="尺寸信息会作为SKU的第七个组成部分"
options={config.sizes.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
/>
<ProFormSelect
name="quantities"
label="数量列表"
mode="tags"
placeholder="请输入数量,按回车确认"
tooltip="数量信息会作为bundle SKU的组成部分"
options={config.quantities.map((opt) => ({
label: `${opt.name} (${opt.shortName})`,
value: opt.name,
}))}
fieldProps={{ allowClear: true }}
/>
<ProForm.Item
name="generateBundleSkuForSingle"
label="为type=single生成bundle产品数据行"
tooltip="为类型为single的记录生成包含quantity的bundle SKU"
valuePropName="checked"
initialValue={true}
>
<Checkbox onChange={setGenerateBundleSkuForSingle}>
single类型生成bundle SKU
</Checkbox>
</ProForm.Item>
</ProForm>
</Card>
{/* 显示所有站点及其shortname */}
<Card title="3. 所有站点信息" style={{ marginTop: '16px' }}>
<div style={{ maxHeight: '200px', overflowY: 'auto' }}>
{sites.length > 0 ? (
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ backgroundColor: '#fafafa' }}>
<th
style={{
padding: '8px',
textAlign: 'left',
borderBottom: '1px solid #e8e8e8',
}}
>
</th>
<th
style={{
padding: '8px',
textAlign: 'left',
borderBottom: '1px solid #e8e8e8',
}}
>
ShortName
</th>
</tr>
</thead>
<tbody>
{sites.map((site) => (
<tr key={site.id}>
<td
style={{
padding: '8px',
borderBottom: '1px solid #e8e8e8',
}}
>
{site.name}
</td>
<td
style={{
padding: '8px',
borderBottom: '1px solid #e8e8e8',
fontWeight: 'bold',
}}
>
{site.skuPrefix}
</td>
</tr>
))}
</tbody>
</table>
) : (
<p style={{ textAlign: 'center', color: '#999' }}>
</p>
)}
</div>
<div style={{ marginTop: '10px', fontSize: '12px', color: '#666' }}>
<p>
shortName将作为前缀添加到生成的SKU中
</p>
</div>
</Card>
</Col>
{/* 右侧:文件上传与操作 */}
<Col xs={24} md={14}>
<Card title="2. 上传文件并操作">
<Upload
beforeUpload={handleFileUpload}
maxCount={1}
showUploadList={!!file}
onRemove={() => {
setFile(null);
setCsvData([]);
setProcessedData([]);
}}
>
<Button icon={<UploadOutlined />}> CSV </Button>
</Upload>
<div style={{ marginTop: 16 }}>
<label style={{ display: 'block', marginBottom: 8 }}>
</label>
<Input value={file ? file.name : '暂未选择文件'} readOnly />
</div>
<Button
type="primary"
onClick={handleProcessData}
disabled={
csvData.length === 0 ||
isProcessing ||
selectedSites.length === 0
}
loading={isProcessing}
style={{ marginTop: '20px' }}
>
SKU
</Button>
{/* 显示处理结果摘要 */}
{processedData.length > 0 && (
<div
style={{
marginTop: '20px',
padding: '10px',
backgroundColor: '#f0f9eb',
borderRadius: '4px',
}}
>
<p style={{ margin: 0, color: '#52c41a' }}>
{processedData.length} SKU
</p>
</div>
)}
</Card>
</Col>
</Row>
</PageContainer>
);
};
export default CsvTool;

View File

@ -77,7 +77,7 @@ const CreateForm: React.FC<{
const strengthName: string = String(strengthValues?.[0] || '');
const flavorName: string = String(flavorValues?.[0] || '');
const humidityName: string = String(humidityValues?.[0] || '');
console.log(formValues)
console.log(formValues);
// 调用模板渲染API来生成SKU
const {
data: rendered,
@ -86,25 +86,25 @@ const CreateForm: React.FC<{
} = await templatecontrollerRendertemplate(
{ name: 'product.sku' },
{
category: formValues.category,
category: formValues.category,
attributes: [
{
dict: {name: "brand"},
dict: { name: 'brand' },
shortName: brandName || '',
},
{
dict: {name: "flavor"},
dict: { name: 'flavor' },
shortName: flavorName || '',
},
{
dict: {name: "strength"},
dict: { name: 'strength' },
shortName: strengthName || '',
},
{
dict: {name: "humidity"},
dict: { name: 'humidity' },
shortName: humidityName ? capitalize(humidityName) : '',
},
]
],
},
);
if (!success) {
@ -153,8 +153,8 @@ const CreateForm: React.FC<{
humidityName === 'dry'
? 'Dry'
: humidityName === 'moisture'
? 'Moisture'
: capitalize(humidityName),
? 'Moisture'
: capitalize(humidityName),
},
);
if (!success) {
@ -219,20 +219,21 @@ const CreateForm: React.FC<{
// 根据产品类型决定是否组装 attributes
// 如果产品类型为 bundle则 attributes 为空数组
// 如果产品类型为 single则根据 activeAttributes 动态组装 attributes
const attributes = values.type === 'bundle'
? []
: activeAttributes.flatMap((attr: any) => {
const dictName = attr.name;
const key = `${dictName}Values`;
const vals = values[key];
if (vals && Array.isArray(vals)) {
return vals.map((v: string) => ({
dictName: dictName,
name: v,
}));
}
return [];
});
const attributes =
values.type === 'bundle'
? []
: activeAttributes.flatMap((attr: any) => {
const dictName = attr.name;
const key = `${dictName}Values`;
const vals = values[key];
if (vals && Array.isArray(vals)) {
return vals.map((v: string) => ({
dictName: dictName,
name: v,
}));
}
return [];
});
const payload: any = {
name: (values as any).name,

View File

@ -4,7 +4,6 @@ import {
productcontrollerGetcategoryattributes,
productcontrollerGetproductcomponents,
productcontrollerGetproductlist,
productcontrollerGetproductsiteskus,
productcontrollerUpdateproduct,
} from '@/servers/api/product';
import { sitecontrollerAll } from '@/servers/api/site';
@ -36,7 +35,6 @@ const EditForm: React.FC<{
const [stockStatus, setStockStatus] = useState<
'in-stock' | 'out-of-stock' | null
>(null);
const [siteSkuCodes, setSiteSkuCodes] = useState<string[]>([]);
const [sites, setSites] = useState<any[]>([]);
const [categories, setCategories] = useState<any[]>([]);
@ -100,15 +98,6 @@ const EditForm: React.FC<{
const { data: componentsData } =
await productcontrollerGetproductcomponents({ id: record.id });
setComponents(componentsData || []);
// 获取站点SKU详细信息
const { data: siteSkusData } = await productcontrollerGetproductsiteskus({
id: record.id,
});
// 只提取code字段组成字符串数组
const codes = siteSkusData
? siteSkusData.map((item: any) => item.code)
: [];
setSiteSkuCodes(codes);
})();
}, [record]);
@ -130,10 +119,10 @@ const EditForm: React.FC<{
type: type,
categoryId: (record as any).categoryId || (record as any).category?.id,
// 初始化站点SKU为字符串数组
siteSkus: siteSkuCodes,
// 修改后代码:
siteSkus: (record.siteSkus || []).map((code) => ({ code })),
};
}, [record, components, type, siteSkuCodes]);
}, [record, components, type]);
return (
<DrawerForm<any>
title="编辑"
@ -198,7 +187,7 @@ const EditForm: React.FC<{
attributes,
type: values.type, // 直接使用 type
categoryId: values.categoryId,
siteSkus: values.siteSkus || [], // 直接传递字符串数组
siteSkus: values.siteSkus.map((v: { code: string }) => v.code) || [], // 直接传递字符串数组
// 连带更新 components
components:
values.type === 'bundle'
@ -221,6 +210,8 @@ const EditForm: React.FC<{
return false;
}}
>
{/* {JSON.stringify(record)}
{JSON.stringify(initialValues)} */}
<ProForm.Group>
<ProFormText
name="sku"
@ -324,9 +315,17 @@ const EditForm: React.FC<{
rules={[{ required: true, message: '请输入单品SKU' }]}
request={async ({ keyWords }) => {
const params = keyWords
? { where: {sku: keyWords, name: keyWords, type: 'single'} }
: { 'per_page': 9999 , where: {type: 'single'} };
const { data } = await productcontrollerGetproductlist(params);
? {
where: {
sku: keyWords,
name: keyWords,
type: 'single',
},
}
: { per_page: 9999, where: { type: 'single' } };
const { data } = await productcontrollerGetproductlist(
params,
);
if (!data || !data.items) {
return [];
}

View File

@ -1,11 +1,11 @@
import { showBatchOperationResult } from '@/utils/showResult';
import { productcontrollerBatchsynctosite } from '@/servers/api/product';
import { sitecontrollerAll } from '@/servers/api/site';
import { templatecontrollerRendertemplate } from '@/servers/api/template';
import { productcontrollerBatchsynctosite } from '@/servers/api/product';
import { showBatchOperationResult } from '@/utils/showResult';
import {
ModalForm,
ProFormSelect,
ProFormDependency,
ProFormSelect,
ProFormText,
} from '@ant-design/pro-components';
import { App, Button, Tag } from 'antd';
@ -36,12 +36,14 @@ const SyncToSiteModal: React.FC<SyncToSiteModalProps> = ({
product: API.Product,
): Promise<string> => {
try {
console.log('site', currentSite)
console.log('site', currentSite);
const { data: renderedSku } = await templatecontrollerRendertemplate(
{ name: 'site.product.sku' },
{ site: currentSite, product },
);
return renderedSku || `${currentSite.skuPrefix || ''}${product.sku || ''}`;
return (
renderedSku || `${currentSite.skuPrefix || ''}${product.sku || ''}`
);
} catch (error) {
return `${currentSite.skuPrefix || ''}${product.sku || ''}`;
}
@ -95,15 +97,16 @@ const SyncToSiteModal: React.FC<SyncToSiteModalProps> = ({
}
}}
onFinish={async (values) => {
console.log(`values`,values)
console.log(`values`, values);
if (!values.siteId) return false;
try {
const siteSkusMap = values.siteSkus || {};
const data = products.map((product) => ({
productId: product.id,
siteSku: siteSkusMap[product.id] || `${values.siteId}-${product.sku}`,
siteSku:
siteSkusMap[product.id] || `${values.siteId}-${product.sku}`,
}));
console.log(`data`,data)
console.log(`data`, data);
const result = await productcontrollerBatchsynctosite({
siteId: values.siteId,
data,
@ -128,7 +131,14 @@ const SyncToSiteModal: React.FC<SyncToSiteModalProps> = ({
<ProFormDependency key={row.id} name={['siteId']}>
{({ siteId }) => (
<div style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8 }}>
<div
style={{
display: 'flex',
gap: 8,
alignItems: 'center',
marginBottom: 8,
}}
>
<div style={{ minWidth: 220 }}>SKU: {row.sku || '-'}</div>
<div style={{ minWidth: 150 }}>
SKU:{' '}
@ -150,9 +160,12 @@ const SyncToSiteModal: React.FC<SyncToSiteModalProps> = ({
fieldProps={{
onChange: (e) => {
// 手动输入时更新表单值
const currentValues = formRef.current?.getFieldValue('siteSkus') || {};
const currentValues =
formRef.current?.getFieldValue('siteSkus') || {};
currentValues[row.id] = e.target.value;
formRef.current?.setFieldsValue({ siteSkus: currentValues });
formRef.current?.setFieldsValue({
siteSkus: currentValues,
});
},
}}
/>
@ -162,11 +175,18 @@ const SyncToSiteModal: React.FC<SyncToSiteModalProps> = ({
size="small"
onClick={async () => {
if (siteId) {
const currentSite = sites.find((s: any) => s.id === siteId) || {};
const siteSku = await generateSingleSiteSku(currentSite, row);
const currentValues = formRef.current?.getFieldValue('siteSkus') || {};
const currentSite =
sites.find((s: any) => s.id === siteId) || {};
const siteSku = await generateSingleSiteSku(
currentSite,
row,
);
const currentValues =
formRef.current?.getFieldValue('siteSkus') || {};
currentValues[row.id] = siteSku;
formRef.current?.setFieldsValue({ siteSkus: currentValues });
formRef.current?.setFieldsValue({
siteSkus: currentValues,
});
}
}}
>

View File

@ -3,9 +3,8 @@ import {
productcontrollerBatchupdateproduct,
productcontrollerDeleteproduct,
productcontrollerGetcategoriesall,
productcontrollerGetproductcomponents,
productcontrollerGetproductlist,
productcontrollerUpdatenamecn
productcontrollerUpdatenamecn,
} from '@/servers/api/product';
import {
ActionType,
@ -14,7 +13,7 @@ import {
ProColumns,
ProFormSelect,
ProFormText,
ProTable
ProTable,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
import { App, Button, Modal, Popconfirm, Tag, Upload } from 'antd';
@ -154,13 +153,18 @@ const BatchEditModal: React.FC<{
</ModalForm>
);
};
const ProductList = ({ filter, columns }: { filter: { skus: string[] }, columns: any[] }) => {
const ProductList = ({
filter,
columns,
}: {
filter: { skus: string[] };
columns: any[];
}) => {
return (
<ProTable
request={async (pag) => {
const { data, success } = await productcontrollerGetproductlist({
where: filter
where: filter,
});
if (!success) return [];
return data || [];
@ -170,7 +174,7 @@ const ProductList = ({ filter, columns }: { filter: { skus: string[] }, columns:
rowKey="id"
bordered
size="small"
scroll={{ x: "max-content" }}
scroll={{ x: 'max-content' }}
headerTitle={null}
toolBarRender={false}
/>
@ -219,6 +223,7 @@ const List: React.FC = () => {
{
title: '关联商品',
dataIndex: 'siteSkus',
width: 200,
render: (_, record) => (
<>
{record.siteSkus?.map((siteSku, index) => (
@ -244,7 +249,6 @@ const List: React.FC = () => {
},
},
{
title: '价格',
dataIndex: 'price',
@ -257,7 +261,7 @@ const List: React.FC = () => {
hideInSearch: true,
sorter: true,
},
{
{
title: '商品类型',
dataIndex: 'category',
render: (_, record: any) => {
@ -443,7 +447,6 @@ const List: React.FC = () => {
onError?.(error);
}
}}
>
<Button></Button>
</Upload>,
@ -506,8 +509,8 @@ const List: React.FC = () => {
sortField = field;
sortOrder = sort[field];
}
const { current, pageSize, ...where } = params
console.log(`params`, params)
const { current, pageSize, ...where } = params;
console.log(`params`, params);
const { data, success } = await productcontrollerGetproductlist({
where,
page: current || 1,
@ -573,5 +576,4 @@ const List: React.FC = () => {
);
};
export default List;

View File

@ -1,4 +1,3 @@
import { showBatchOperationResult } from '@/utils/showResult';
import {
productcontrollerBatchsynctosite,
productcontrollerGetproductlist,

View File

@ -5,14 +5,29 @@ import {
sitecontrollerList,
sitecontrollerUpdate,
} from '@/servers/api/site';
import { subscriptioncontrollerSync } from '@/servers/api/subscription';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import { ActionType, ProColumns, ProTable, DrawerForm, ProFormSelect, ProFormSwitch } from '@ant-design/pro-components';
import { Button, message, notification, Popconfirm, Space, Tag, Form } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import EditSiteForm from '../Shop/EditSiteForm'; // 引入重构后的表单组件
import { subscriptioncontrollerSync } from '@/servers/api/subscription';
import {
ActionType,
DrawerForm,
ProColumns,
ProFormSelect,
ProFormSwitch,
ProTable,
} from '@ant-design/pro-components';
import {
Button,
Form,
message,
notification,
Popconfirm,
Space,
Tag,
} from 'antd';
import * as countries from 'i18n-iso-countries';
import zhCN from 'i18n-iso-countries/langs/zh';
import React, { useEffect, useRef, useState } from 'react';
import EditSiteForm from '../Shop/EditSiteForm'; // 引入重构后的表单组件
// 区域数据项类型
interface AreaItem {
@ -49,7 +64,6 @@ const SiteList: React.FC = () => {
const [batchEditForm] = Form.useForm();
countries.registerLocale(zhCN);
const handleSync = async (ids: number[]) => {
if (!ids.length) return;
const hide = message.loading('正在同步...', 0);
@ -206,8 +220,8 @@ const SiteList: React.FC = () => {
},
{
// 地区列配置
title: "地区",
dataIndex: "areas",
title: '地区',
dataIndex: 'areas',
hideInSearch: true,
render: (_, row) => {
// 如果没有关联地区,显示"全局"标签
@ -310,10 +324,10 @@ const SiteList: React.FC = () => {
try {
const { current, pageSize, name, type } = params;
const resp = await sitecontrollerList({
current,
pageSize,
keyword: name || undefined,
type: type || undefined,
current,
pageSize,
keyword: name || undefined,
type: type || undefined,
});
// 假设 resp 直接就是后端返回的结构,包含 items 和 total
return {

View File

@ -465,7 +465,11 @@ const CustomerPage: React.FC = () => {
<ProTable
rowKey="id"
search={false}
pagination={{ pageSize: 20 ,showSizeChanger: true, showQuickJumper: true,}}
pagination={{
pageSize: 20,
showSizeChanger: true,
showQuickJumper: true,
}}
columns={[
{ title: '订单号', dataIndex: 'number', copyable: true },
{

View File

@ -1,4 +1,3 @@
import { areacontrollerGetarealist } from '@/servers/api/area';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import {
DrawerForm,
@ -9,9 +8,9 @@ import {
ProFormTextArea,
} from '@ant-design/pro-components';
import { Form } from 'antd';
import React, { useEffect } from 'react';
import * as countries from 'i18n-iso-countries';
import zhCN from 'i18n-iso-countries/langs/zh';
import React, { useEffect } from 'react';
// 定义组件的 props 类型
interface EditSiteFormProps {
@ -41,7 +40,8 @@ const EditSiteForm: React.FC<EditSiteFormProps> = ({
// 如果是编辑模式并且有初始值
if (isEdit && initialValues) {
// 编辑模式下, 设置表单值为初始值
const { token, consumerKey, consumerSecret, ...safeInitialValues } = initialValues;
const { token, consumerKey, consumerSecret, ...safeInitialValues } =
initialValues;
// 清空敏感字段, 让用户输入最新的数据
form.setFieldsValue({
...safeInitialValues,

View File

@ -68,7 +68,7 @@ const OrdersPage: React.FC = () => {
dataIndex: 'id',
},
{
title:'订单号',
title: '订单号',
dataIndex: 'number',
},
{
@ -127,7 +127,7 @@ const OrdersPage: React.FC = () => {
title: '客户姓名',
dataIndex: 'customer_name',
},
{
{
title: '客户IP',
dataIndex: 'customer_ip_address',
},
@ -190,7 +190,7 @@ const OrdersPage: React.FC = () => {
ellipsis: true,
copyable: true,
},
{
{
title: '发货状态',
dataIndex: 'fulfillment_status',
// hideInSearch: true,
@ -384,8 +384,7 @@ const OrdersPage: React.FC = () => {
setSelectedRowKeys={setSelectedRowKeys}
siteId={siteId}
/>,
<Button disabled></Button>
,
<Button disabled></Button>,
<Button
title="批量删除"
danger
@ -541,9 +540,12 @@ const OrdersPage: React.FC = () => {
return { status: key, count: 0 };
}
try {
const res = await request(`/site-api/${siteId}/orders/count`, {
params: { ...baseWhere, status: rawStatus },
});
const res = await request(
`/site-api/${siteId}/orders/count`,
{
params: { ...baseWhere, status: rawStatus },
},
);
const totalCount = Number(res?.data?.total || 0);
return { status: key, count: totalCount };
} catch (err) {

View File

@ -20,11 +20,10 @@ import {
} from '@ant-design/pro-components';
import { Button, Space, Tag } from 'antd';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import ReactECharts from 'echarts-for-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import zhCN from 'i18n-iso-countries/langs/zh';
countries.registerLocale(zhCN);
dayjs.extend(weekOfYear);
const highlightText = (text: string, keyword: string) => {
if (!keyword) return text;
@ -143,7 +142,7 @@ const ListPage: React.FC = () => {
});
if (success) {
const res = data?.sort(() => -1);
const formatMap = {
const formatMap = {
month: 'YYYY-MM',
week: 'YYYY年第WW周',
day: 'YYYY-MM-DD',
@ -151,14 +150,16 @@ const ListPage: React.FC = () => {
const format = formatMap[params.grouping] || 'YYYY-MM-DD';
if (params.grouping === 'week') {
setXAxis(res?.map((v) => {
const [year, week] = v.order_date.split('-');
return `${year}年第${week}`;
}));
setXAxis(
res?.map((v) => {
const [year, week] = v.order_date.split('-');
return `${year}年第${week}`;
}),
);
} else {
setXAxis(res?.map((v) => dayjs(v.order_date).format(format)));
}
setSeries([
setSeries([
{
name: 'TOGO CPC订单数',
type: 'line',
@ -612,7 +613,7 @@ const ListPage: React.FC = () => {
name="date"
/>
{/* <ProFormText label="关键词" name="keyword" /> */}
<ProFormSelect
<ProFormSelect
label="统计周期"
name="grouping"
initialValue="day"

View File

@ -51,9 +51,15 @@ const ListPage: React.FC = () => {
show: true,
formatter: function (params) {
if (!params.value) return '';
return Math.abs(params.value)
+ '\n'
+ Math.abs(data?.inactiveRes?.find((item) => item.order_month === params.name)?.new_user_total || 0);
return (
Math.abs(params.value) +
'\n' +
Math.abs(
data?.inactiveRes?.find(
(item) => item.order_month === params.name,
)?.new_user_total || 0,
)
);
},
color: '#000000',
},
@ -71,9 +77,15 @@ const ListPage: React.FC = () => {
show: true,
formatter: function (params) {
if (!params.value) return '';
return Math.abs(params.value)
+ '\n'
+ Math.abs(data?.inactiveRes?.find((item) => item.order_month === params.name)?.old_user_total || 0);
return (
Math.abs(params.value) +
'\n' +
Math.abs(
data?.inactiveRes?.find(
(item) => item.order_month === params.name,
)?.old_user_total || 0,
)
);
},
color: '#000000',
},
@ -93,10 +105,17 @@ const ListPage: React.FC = () => {
show: true,
formatter: function (params) {
if (!params.value) return '';
return Math.abs(params.value)
+ '\n' +
+Math.abs(data?.res?.find((item) => item.order_month === params.name &&
item.first_order_month_group === v)?.total || 0);
return (
Math.abs(params.value) +
'\n' +
+Math.abs(
data?.res?.find(
(item) =>
item.order_month === params.name &&
item.first_order_month_group === v,
)?.total || 0,
)
);
},
color: '#000000',
},

View File

@ -0,0 +1,249 @@
import { ordercontrollerGetordersales } from '@/servers/api/order';
import { sitecontrollerAll } from '@/servers/api/site';
import {
ActionType,
PageContainer,
ProColumns,
ProFormSwitch,
ProTable,
} from '@ant-design/pro-components';
import { Button } from 'antd';
import dayjs from 'dayjs';
import { saveAs } from 'file-saver';
import { useRef, useState } from 'react';
import * as XLSX from 'xlsx';
const ListPage: React.FC = () => {
const actionRef = useRef<ActionType>();
const formRef = useRef();
const [total, setTotal] = useState(0);
const [isSource, setIsSource] = useState(false);
const [yooneTotal, setYooneTotal] = useState({});
const columns: ProColumns<API.OrderSaleDTO>[] = [
{
title: '时间段',
dataIndex: 'dateRange',
valueType: 'dateTimeRange',
hideInTable: true,
formItemProps: {
rules: [
{
required: true,
message: '请选择时间段',
},
],
},
},
{
title: '排除套装',
dataIndex: 'exceptPackage',
valueType: 'switch',
hideInTable: true,
},
{
title: '产品名称',
dataIndex: 'sku',
},
{
title: '产品名称',
dataIndex: 'name',
},
{
title: '站点',
dataIndex: 'siteId',
valueType: 'select',
request: async () => {
const { data = [] } = await sitecontrollerAll();
return data.map((item) => ({
label: item.name,
value: item.id,
}));
},
hideInTable: true,
},
// {
// title: '分类',
// dataIndex: 'categoryName',
// hideInSearch: true,
// hideInTable: isSource,
// },
{
title: '数量',
dataIndex: 'totalQuantity',
hideInSearch: true,
},
{
title: '一单订单数',
dataIndex: 'firstOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.firstOrderCount;
return `${record.firstOrderCount}(${record.firstOrderYOONEBoxCount})`;
},
},
{
title: '两单订单数',
dataIndex: 'secondOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.secondOrderCount;
return `${record.secondOrderCount}(${record.secondOrderYOONEBoxCount})`;
},
},
{
title: '三单订单数',
dataIndex: 'thirdOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.thirdOrderCount;
return `${record.thirdOrderCount}(${record.thirdOrderYOONEBoxCount})`;
},
},
{
title: '三单以上订单数',
dataIndex: 'moreThirdOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.moreThirdOrderCount;
return `${record.moreThirdOrderCount}(${record.moreThirdOrderYOONEBoxCount})`;
},
},
{
title: '订单数',
dataIndex: 'totalOrders',
hideInSearch: true,
},
];
return (
<PageContainer ghost>
<ProTable
headerTitle="查询表格"
actionRef={actionRef}
formRef={formRef}
rowKey="id"
params={{ isSource }}
form={{
// ignoreRules: false,
initialValues: {
dateRange: [dayjs().startOf('month'), dayjs().endOf('month')],
},
}}
request={async ({ dateRange, ...param }) => {
const [startDate, endDate] = dateRange.values();
const { data, success } = await ordercontrollerGetordersales({
startDate,
endDate,
...param,
});
if (success) {
setTotal(data?.totalQuantity || 0);
setYooneTotal({
yoone3Quantity: data?.yoone3Quantity || 0,
yoone6Quantity: data?.yoone6Quantity || 0,
yoone9Quantity: data?.yoone9Quantity || 0,
yoone12Quantity: data?.yoone12Quantity || 0,
yoone12QuantityNew: data?.yoone12QuantityNew || 0,
yoone15Quantity: data?.yoone15Quantity || 0,
yoone18Quantity: data?.yoone18Quantity || 0,
zexQuantity: data?.zexQuantity || 0,
});
return {
total: data?.total || 0,
data: data?.items || [],
};
}
setTotal(0);
setYooneTotal({});
return {
data: [],
};
}}
columns={columns}
dateFormatter="number"
footer={() => `总计: ${total}`}
toolBarRender={() => [
<Button
type="primary"
onClick={async () => {
const { dateRange, param } = formRef.current?.getFieldsValue();
const [startDate, endDate] = dateRange.values();
const { data, success } = await ordercontrollerGetordersales({
startDate: dayjs(startDate).valueOf(),
endDate: dayjs(endDate).valueOf(),
...param,
current: 1,
pageSize: 20000,
});
if (!success) return;
// 表头
const headers = ['产品名', '数量'];
// 数据行
const rows = (data?.items || []).map((item) => {
return [item.name, item.totalQuantity];
});
// 导出
const sheet = XLSX.utils.aoa_to_sheet([headers, ...rows]);
const book = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book, sheet, '销售');
const buffer = XLSX.write(book, {
bookType: 'xlsx',
type: 'array',
});
const blob = new Blob([buffer], {
type: 'application/octet-stream',
});
saveAs(blob, '销售.xlsx');
}}
>
</Button>,
<ProFormSwitch
label="原产品"
fieldProps={{
value: isSource,
onChange: () => setIsSource(!isSource),
}}
/>,
]}
/>
<div
style={{
background: '#fff',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
padding: '10px',
marginTop: '20px',
}}
>
<div>
YOONE:{' '}
{(yooneTotal.yoone3Quantity || 0) +
(yooneTotal.yoone6Quantity || 0) +
(yooneTotal.yoone9Quantity || 0) +
(yooneTotal.yoone12Quantity || 0) +
(yooneTotal.yoone15Quantity || 0) +
(yooneTotal.yoone18Quantity || 0) +
(yooneTotal.zexQuantity || 0)}
</div>
<div>YOONE 3MG: {yooneTotal.yoone3Quantity || 0}</div>
<div>YOONE 6MG: {yooneTotal.yoone6Quantity || 0}</div>
<div>YOONE 9MG: {yooneTotal.yoone9Quantity || 0}</div>
<div>YOONE 12MG新: {yooneTotal.yoone12QuantityNew || 0}</div>
<div>
YOONE 12MG白:{' '}
{(yooneTotal.yoone12Quantity || 0) -
(yooneTotal.yoone12QuantityNew || 0)}
</div>
<div>YOONE 15MG: {yooneTotal.yoone15Quantity || 0}</div>
<div>YOONE 18MG: {yooneTotal.yoone18Quantity || 0}</div>
<div>ZEX: {yooneTotal.zexQuantity || 0}</div>
</div>
</PageContainer>
);
};
export default ListPage;

View File

@ -41,6 +41,10 @@ const ListPage: React.FC = () => {
valueType: 'switch',
hideInTable: true,
},
{
title: '产品名称',
dataIndex: 'sku',
},
{
title: '产品名称',
dataIndex: 'name',
@ -73,37 +77,31 @@ const ListPage: React.FC = () => {
title: '一单订单数',
dataIndex: 'firstOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.firstOrderCount;
return `${record.firstOrderCount}(${record.firstOrderYOONEBoxCount})`;
},
},
{
title: '一单YOONE盒数',
dataIndex: 'firstOrderYOONEBoxCount',
hideInSearch: true,
},
{
title: '两单订单数',
dataIndex: 'secondOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.secondOrderCount;
return `${record.secondOrderCount}(${record.secondOrderYOONEBoxCount})`;
},
},
{
title: '两单YOONE盒数',
dataIndex: 'secondOrderYOONEBoxCount',
hideInSearch: true,
},
{
title: '三单订单数',
dataIndex: 'thirdOrderCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.thirdOrderCount;
return `${record.thirdOrderCount}(${record.thirdOrderYOONEBoxCount})`;
},
},
{
title: '三单以上订单数',
dataIndex: 'moreThirdOrderCount',
title: '三单YOONE盒数',
dataIndex: 'thirdOrderYOONEBoxCount',
hideInSearch: true,
render(_, record) {
if (isSource) return record.moreThirdOrderCount;
return `${record.moreThirdOrderCount}(${record.moreThirdOrderYOONEBoxCount})`;
},
},
{
title: '订单数',

View File

@ -16,9 +16,9 @@ import {
ProTable,
} from '@ant-design/pro-components';
import { App, Button, Divider, Popconfirm, Space, Tag } from 'antd';
import { useRef } from 'react';
import * as countries from 'i18n-iso-countries';
import zhCN from 'i18n-iso-countries/langs/zh';
import { useRef } from 'react';
// 初始化中文语言包
countries.registerLocale(zhCN);