feat: 优化景区素材

This commit is contained in:
2025-10-25 18:04:01 +08:00
parent 839f682ca8
commit 10a8e2a1ea
12 changed files with 515 additions and 552 deletions
-1
View File
@@ -27,7 +27,6 @@ export default [
{ path: '/orders/tourismFile.html', component: '@/pages/orders/TourismFile' },
{ path: '/orders/homeCarousel.html', component: '@/pages/orders/HomeCarousel' },
{ path: '/orders/refund.html', component: '@/pages/orders/Refund' },
{ path: '/orders/statistics.html', component: '@/pages/orders/Statistics' },
{ path: '/orders/profitSharing.html', component: '@/pages/orders/ProfitSharing' },
{ path: '/orders/profit-sharing/statistics.html', component: '@/pages/orders/ProfitSharing/Statistics' },
{ path: '/orders/videoTemplate.html', component: '@/pages/orders/VideoTemplate' },
@@ -1,63 +0,0 @@
import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Col, Row, Statistic, DatePicker, Space, message, Form } from 'antd';
import { SearchBarPlus } from '@/components/ui';
import { ordersApi } from '@/services/orders';
const { RangePicker } = DatePicker;
const StatisticsPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const [stat, setStat] = useState<any>({});
const [range, setRange] = useState<any>();
const load = async (p?: any) => {
setLoading(true);
try {
const res = await ordersApi.dashboard(p);
setStat(res?.data || res);
} catch (e) {
message.error('加载统计失败');
} finally { setLoading(false); }
};
useEffect(() => { load(); }, []);
return (
<PageContainer header={{ title: '订单统计' }}>
<SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={() => load(range)}
onFinish={async (values) => {
const v = (values as any)?.timeRange;
const base: any = {};
if (v && v.length === 2) {
base.startTime = v[0]?.toISOString();
base.endTime = v[1]?.toISOString();
}
// 合并租户筛选参数
const r = { ...values, ...base } as any;
delete r.timeRange;
setRange(r);
await load(r);
}}
>
<Form.Item name="timeRange" label="时间范围">
<RangePicker showTime />
</Form.Item>
</SearchBarPlus>
<Row gutter={16}>
<Col span={6}><Card loading={loading}><Statistic title="订单总数" value={stat?.totalOrders || 0} /></Card></Col>
<Col span={6}><Card loading={loading}><Statistic title="支付总额" value={stat?.totalAmount || 0} precision={2} /></Card></Col>
<Col span={6}><Card loading={loading}><Statistic title="退款总额" value={stat?.refundAmount || 0} precision={2} /></Card></Col>
<Col span={6}><Card loading={loading}><Statistic title="转化率" value={stat?.conversionRate || 0} suffix="%" /></Card></Col>
</Row>
</PageContainer>
);
};
export default StatisticsPage;
@@ -0,0 +1,151 @@
import React, { useState } from 'react';
import { ModalForm, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Button, Image, Upload, message, Row, Col } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
export interface TourismFileItem {
id?: number;
tourismId?: number;
type?: number;
status?: number; // 0 启用,1 禁用
imageUrl?: string; // 保存时使用后端返回的 path
linkUrl?: string;
description?: string;
}
export interface TourismFileFormProps {
open: boolean;
title: string;
initialValues?: Partial<TourismFileItem>;
onOpenChange: (v: boolean) => void;
onFinish: (values: TourismFileItem) => Promise<boolean>;
tourismOptions: Array<{ label: string; value: number }>; // 项目下拉
}
const TYPE_OPTIONS = [
{ label: '视频', value: 5 },
{ label: '首页 Banner', value: 6 },
{ label: '展示图片', value: 4 },
{ label: '景区详情', value: 3 },
{ label: '景区小图展示', value: 2 },
{ label: '活动', value: 1 },
] as const;
const STATUS_OPTIONS = [
{ label: '启用', value: 0 },
{ label: '禁用', value: 1 },
] as const;
const TourismFileForm: React.FC<TourismFileFormProps> = ({ open, title, initialValues, onOpenChange, onFinish, tourismOptions }) => {
const [uploadPreviewUrl, setUploadPreviewUrl] = useState<string | undefined>();
const [uploadPath, setUploadPath] = useState<string | undefined>();
const doUpload = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const token = (typeof window !== 'undefined') ? sessionStorage.getItem('access_token') : undefined;
const headers: Record<string, string> = {};
if (token) headers['Authorization'] = 'Bearer ' +token;
const resp = await fetch('/api-file/files-anon', { method: 'POST', body: formData, headers });
const data = await resp.json();
if (!data || (!data.url && !data.path)) throw new Error('上传失败');
return data as { url: string; path: string };
};
return (
<ModalForm<TourismFileItem>
title={title}
visible={open}
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
onVisibleChange={(v) => {
if (!v) {
setUploadPreviewUrl(undefined);
setUploadPath(undefined);
}
onOpenChange(v);
}}
onFinish={async (values) => {
const payload: TourismFileItem = { ...(initialValues || {}), ...values } as any;
if (uploadPath) payload.imageUrl = uploadPath;
if (!payload.imageUrl) {
message.warning('请先上传资源');
return false;
}
return onFinish(payload);
}}
initialValues={initialValues}
modalProps={{ destroyOnClose: true }}
>
<Row gutter={16}>
<Col span={12}>
<ProFormSelect
rules={[{ required: true, message: '请选择项目' }]}
name="tourismId"
label="项目"
options={tourismOptions}
showSearch
/>
</Col>
<Col span={12}>
<ProFormSelect
rules={[{ required: true, message: '请选择资源类型' }]}
name="type"
label="资源类型"
options={TYPE_OPTIONS as any}
/>
</Col>
<Col span={12}>
<ProFormSelect name="status" label="状态" options={STATUS_OPTIONS as any} initialValue={0} />
</Col>
<Col span={12}>
<ProFormText name="linkUrl" label="页面链接" placeholder="可为空" />
</Col>
<Col span={24}>
<ProFormText
rules={[{ required: true, message: '请输入资源描述' }]}
name="description"
label="资源描述"
placeholder="请输入资源描述"
/>
</Col>
<Col span={24}>
<ProForm.Item label="资源文件">
<Upload
maxCount={1}
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const r = await doUpload(file as File);
setUploadPreviewUrl(r.url);
setUploadPath(r.path);
onSuccess?.('ok');
}
} catch (err) {
onError?.(err as any);
}
}}
accept="image/*,video/*"
>
<Button icon={<UploadOutlined />}>上传图片/视频</Button>
</Upload>
</ProForm.Item>
</Col>
{(uploadPreviewUrl || initialValues?.imageUrl) && (
<Col span={24}>
<div style={{ marginTop: 12 }}>
<Image src={uploadPreviewUrl || initialValues?.imageUrl} width={200} />
</div>
</Col>
)}
</Row>
</ModalForm>
);
};
export default TourismFileForm;
@@ -1,24 +1,18 @@
import React, { useEffect, useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui';
import {
ModalForm,
PageContainer,
ProForm,
ProFormSelect,
ProFormText,
ProTable,
} from '@ant-design/pro-components';
import { Button, Image, Popconfirm, Space, Tag, Upload, message, Form } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageContainer, ProFormSelect } from '@ant-design/pro-components';
import { Button, Image, Popconfirm, Space, Tag, message, Pagination } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import TourismFileForm, { TourismFileItem } from './components/TourismFileForm';
// 资源类型枚举(用于卡片展示的颜色)
const TYPE_OPTIONS = [
{ label: '视频', value: 5, color: '#f5222d' },
{ label: '首页 Banner', value: 6, color: '#2f54eb' },
{ label: '展示封面', value: 4, color: '#52c41a' },
{ label: '入口引导', value: 3, color: '#722ed1' },
{ label: '服务小结展示', value: 2, color: '#13c2c2' },
{ label: '展示图片', value: 4, color: '#52c41a' },
{ label: '景区详情', value: 3, color: '#722ed1' },
{ label: '景区小图展示', value: 2, color: '#13c2c2' },
{ label: '活动', value: 1, color: '#1890ff' },
] as const;
@@ -28,218 +22,197 @@ const STATUS_OPTIONS = [
] as const;
const TourismFilePage: React.FC = () => {
const actionRef = useRef<ActionType>();
const [query, setQuery] = useState<Record<string, any>>({});
const [tourismOptions, setTourismOptions] = useState<Array<{ label: string; value: number }>>([]);
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<any>();
const [uploadPreviewUrl, setUploadPreviewUrl] = useState<string | undefined>();
const [uploadPath, setUploadPath] = useState<string | undefined>();
const [editUploadPreviewUrl, setEditUploadPreviewUrl] = useState<string | undefined>();
const [editUploadPath, setEditUploadPath] = useState<string | undefined>();
// 分组数据(按项目分组)与分页
const [groups, setGroups] = useState<Array<{ tourismId: number; tourismName?: string; files: any[] }>>([]);
const [loading, setLoading] = useState(false);
const fetchingRef = useRef(false);
const [pagination, setPagination] = useState<{ current: number; pageSize: number; total: number }>({ current: 1, pageSize: 10, total: 0 });
// 加载可选项目列表(用于筛选与表单下拉)
useEffect(() => {
(async () => {
try {
const res = await ordersApi.tourism({ page: 1, limit: 1000 });
const list: Array<{ id: number; tourismName: string }> = (res as any).data || res?.data || [];
setTourismOptions(list.map((it) => ({ label: (it as any).tourismName, value: (it as any).id })));
} catch (e) {
// 忽略错误以不影响页面
}
const res = await ordersApi.tourism({ page: 1, limit: 1000, tenantId: query?.tenantId, includeChildren: query?.includeChildren });
const list: Array<{ id: number; tourismName: string }> = (res as any)?.data || [];
setTourismOptions(list.map((it: any) => ({ label: it.tourismName, value: it.id })));
} catch {}
})();
}, []);
// 租户切换时刷新
}, [query?.tenantId, query?.includeChildren]);
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{
title: '旅游项目',
dataIndex: 'tourismId',
render: (_: any, record: any) => tourismOptions.find((o) => o.value === record.tourismId)?.label || record.tourismName || '-',
},
{
title: '图片/预览',
dataIndex: 'imageUrl',
search: false,
width: 140,
render: (_: any, record: any) =>
record.type === 5 ? (
<video src={record.imageUrl} controls style={{ width: 120, height: 80, objectFit: 'cover' }} />
) : (
<Image src={record.imageUrl} width={120} height={80} style={{ objectFit: 'cover' }} />
),
},
{ title: '页面链接', dataIndex: 'linkUrl', ellipsis: true, copyable: true },
{ title: '描述', dataIndex: 'description', ellipsis: true },
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v: number) => <Tag color={v === 0 ? 'green' : 'default'}>{v === 0 ? '启用' : '禁用'}</Tag>,
},
{
title: '类型',
dataIndex: 'type',
width: 120,
render: (v: number) => {
const t = TYPE_OPTIONS.find((i) => i.value === Number(v));
return t ? <Tag color={t.color}>{t.label}</Tag> : '-';
},
},
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 },
{
title: '操作',
key: 'action',
width: 160,
render: (_: any, record: any) => (
<Space>
<a
onClick={() => {
setCurrent(record);
setEditOpen(true);
setEditUploadPreviewUrl(undefined);
setEditUploadPath(undefined);
}}
>
编辑
</a>
<Popconfirm
title={`确认删除资源[${record.id}]?`}
onConfirm={async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteTourismFile(record.id);
message.success('删除成功');
actionRef.current?.reload();
} catch (e) {
message.error('删除失败');
} finally {
hide();
}
}}
>
<a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm>
</Space>
),
},
];
const doUpload = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const resp = await fetch('/api-file/files-anon', { method: 'POST', body: formData });
const data = await resp.json();
if (!data || (!data.url && !data.path)) throw new Error('上传失败');
return data as { url: string; path: string };
// 加载查询结果(含分页)
const loadGroups = async (extra?: Record<string, any>) => {
const params = { ...(query || {}), ...(extra || {}), current: pagination.current, pageSize: pagination.pageSize };
if (fetchingRef.current) return; // 防抖去重
fetchingRef.current = true;
setLoading(true);
try {
const res = await ordersApi.tourismFilesGroupedByTenant(params as any);
setGroups(Array.isArray((res as any)?.data) ? (res as any).data : []);
setPagination((p) => ({ ...p, total: Number((res as any)?.total || 0) }));
} catch (e) {
setGroups([]);
setPagination((p) => ({ ...p, total: 0 }));
} finally {
fetchingRef.current = false;
setLoading(false);
}
};
// 首次与查询/分页变化时刷新
useEffect(() => {
loadGroups();
}, [query, pagination.current, pagination.pageSize]);
return (
<PageContainer header={{ title: '旅游资源管理' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => actionRef.current?.reload()} onFinish={async (values) => setQuery(values)}>
<ProFormText name="description" label="资源描述" placeholder="请输入关键字" />
<ProFormSelect name="tourismId" label="项目" placeholder="请选择" options={tourismOptions} showSearch />
<ProFormSelect name="type" label="资源类型" placeholder="请选择" options={TYPE_OPTIONS as any} />
<PageContainer header={{ title: '景区素材管理' }}>
<SearchBarPlus
defaultCollapsed
split
span={8 as any}
hideReset
onFinish={async (values) => {
// 查询提交后重置到第1页
setPagination((p) => ({ ...p, current: 1 }));
setQuery(values);
}}
>
<ProFormSelect name="status" label="状态" placeholder="请选择" options={STATUS_OPTIONS as any} />
</SearchBarPlus>
<ActionBar left={<Button size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</Button>} />
<GlassCard>
<ProTable<any>
rowKey="id"
headerTitle="资源列表"
actionRef={actionRef}
request={(p) => ordersApi.tourismFile({ ...p, ...query })}
columns={columns}
search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true, defaultPageSize: 10 }}
/>
{loading ? (
<div style={{ padding: 24 }}>加载中...</div>
) : (
<div>
{groups && groups.length ? (
groups.map((g) => (
<div key={g.tourismId} style={{ marginBottom: 24 }}>
<h3 style={{ marginBottom: 12 }}>{g.tourismName || `项目#${g.tourismId}`}</h3>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(320px, 1fr))', gap: 16 }}>
{(g.files || []).map((record: any) => (
<div key={record.id} style={{ border: '1px solid #f0f0f0', borderRadius: 8, padding: 12 }}>
<div style={{ marginBottom: 8 }}>
{Number(record.type) === 5 ? (
<video src={record.imageUrl} controls style={{ width: '100%', height: 180, objectFit: 'cover', borderRadius: 4 }} />
) : (
<Image src={record.imageUrl} width={'100%'} height={180} style={{ objectFit: 'cover', borderRadius: 4 }} />
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
<Tag color={Number(record.status) === 0 ? 'green' : 'default'}>{Number(record.status) === 0 ? '启用' : '禁用'}</Tag>
<Tag color={(TYPE_OPTIONS.find((i) => i.value === Number(record.type)) || ({} as any)).color || 'default'}>
{(TYPE_OPTIONS.find((i) => i.value === Number(record.type)) || ({} as any)).label || '未知类型'}
</Tag>
</div>
<div style={{ fontSize: 12, color: '#666', marginBottom: 8 }}>{record.description || '-'}</div>
{record.linkUrl ? (
<div style={{ fontSize: 12, color: '#999' }}>
链接:
<a href={record.linkUrl} target="_blank" rel="noreferrer">
{record.linkUrl}
</a>
</div>
) : null}
<div style={{ marginTop: 8 }}>
<Space>
<a
style={{ color: '#1677ff' }}
onClick={() => {
setCurrent(record);
setEditOpen(true);
}}
>
编辑
</a>
<Popconfirm
title={`确认删除资源[${record.id}]?`}
onConfirm={async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteTourismFile(record.id);
message.success('删除成功');
loadGroups();
} catch (e) {
message.error('删除失败');
} finally {
hide();
}
}}
>
<a style={{ color: '#ff4d4f' }}>删除</a>
</Popconfirm>
</Space>
</div>
</div>
))}
</div>
</div>
))
) : (
<div style={{ padding: 24, color: '#999' }}>暂无数据</div>
)}
</div>
)}
{/* 分页 */}
<div style={{ marginTop: 16, textAlign: 'right' }}>
<span style={{ marginRight: 12, color: '#999' }}>共 {pagination.total} 条</span>
<Pagination
current={pagination.current}
pageSize={pagination.pageSize}
total={pagination.total}
showSizeChanger
showQuickJumper
onChange={(cur, size) => {
setPagination({ current: cur, pageSize: (size as number) || pagination.pageSize, total: pagination.total });
}}
/>
</div>
</GlassCard>
{/* 新建 */}
<ModalForm
<TourismFileForm
title="新增资源"
open={createOpen}
onOpenChange={(v: boolean) => {
if (!v) {
setUploadPreviewUrl(undefined);
setUploadPath(undefined);
}
setCreateOpen(v);
}}
onFinish={async (values) => {
if (!uploadPath) {
message.warning('请先上传资源');
return false;
}
tourismOptions={tourismOptions}
onOpenChange={setCreateOpen}
onFinish={async (values: TourismFileItem) => {
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateTourismFile({ ...values, imageUrl: uploadPath, status: values.status ?? 0 });
await ordersApi.saveOrUpdateTourismFile({ ...values, status: values.status ?? 0 });
message.success('新增成功');
actionRef.current?.reload();
loadGroups();
return true;
} catch (e) {
message.error('保存失败');
message.error('新增失败');
return false;
} finally {
hide();
}
}}
>
<ProForm.Group>
<ProFormSelect rules={[{ required: true, message: '请选择项目' }]} width="md" name="tourismId" label="项目" options={tourismOptions} showSearch />
<ProFormSelect rules={[{ required: true, message: '请选择资源类型' }]} width="md" name="type" label="资源类型" options={TYPE_OPTIONS as any} />
<ProFormSelect width="md" name="status" label="状态" options={STATUS_OPTIONS as any} initialValue={0} />
<ProFormText width="md" name="linkUrl" label="页面链接" placeholder="可为空" />
<ProFormText rules={[{ required: true, message: '请输入资源描述' }]} width="md" name="description" label="资源描述" placeholder="请输入资源描述" />
</ProForm.Group>
<Upload
maxCount={1}
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const r = await doUpload(file as File);
setUploadPreviewUrl(r.url);
setUploadPath(r.path);
onSuccess?.('ok');
}
} catch (err) {
onError?.(err as any);
}
}}
accept="image/*,video/*"
>
<Button icon={<UploadOutlined />}>上传图片/视频</Button>
</Upload>
{uploadPreviewUrl && (
<div style={{ marginTop: 12 }}>
{(ProForm as any) && <Image src={uploadPreviewUrl} width={200} />}
</div>
)}
</ModalForm>
/>
{/* 编辑 */}
<ModalForm
<TourismFileForm
title="编辑资源"
open={editOpen}
initialValues={current}
onOpenChange={(v: boolean) => {
if (!v) {
setEditUploadPreviewUrl(undefined);
setEditUploadPath(undefined);
}
setEditOpen(v);
}}
onFinish={async (values) => {
const payload = { ...(current || {}), ...values } as any;
if (editUploadPath) payload.imageUrl = editUploadPath;
tourismOptions={tourismOptions}
onOpenChange={setEditOpen}
onFinish={async (values: TourismFileItem) => {
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateTourismFile(payload);
await ordersApi.saveOrUpdateTourismFile({ ...(current || {}), ...values });
message.success('修改成功');
actionRef.current?.reload();
loadGroups();
return true;
} catch (e) {
message.error('修改失败');
@@ -248,42 +221,9 @@ const TourismFilePage: React.FC = () => {
hide();
}
}}
>
<ProForm.Group>
<ProFormSelect rules={[{ required: true, message: '请选择项目' }]} width="md" name="tourismId" label="项目" options={tourismOptions} showSearch />
<ProFormSelect rules={[{ required: true, message: '请选择资源类型' }]} width="md" name="type" label="资源类型" options={TYPE_OPTIONS as any} />
<ProFormSelect width="md" name="status" label="状态" options={STATUS_OPTIONS as any} />
<ProFormText width="md" name="linkUrl" label="页面链接" placeholder="可为空" />
<ProFormText rules={[{ required: true, message: '请输入资源描述' }]} width="md" name="description" label="资源描述" placeholder="请输入资源描述" />
</ProForm.Group>
<Upload
maxCount={1}
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const r = await doUpload(file as File);
setEditUploadPreviewUrl(r.url);
setEditUploadPath(r.path);
onSuccess?.('ok');
}
} catch (err) {
onError?.(err as any);
}
}}
accept="image/*,video/*"
>
<Button icon={<UploadOutlined />}>上传图片/视频</Button>
</Upload>
{(editUploadPreviewUrl || current?.imageUrl) && (
<div style={{ marginTop: 12 }}>
<Image src={editUploadPreviewUrl || current?.imageUrl} width={200} />
</div>
)}
</ModalForm>
/>
</PageContainer>
);
};
export default TourismFilePage;
+14 -5
View File
@@ -1,4 +1,4 @@
import { request } from 'umi';
import { request } from 'umi';
export interface OrderItem {
id: number;
@@ -12,6 +12,15 @@ export interface OrderItem {
}
export const ordersApi = {
// 按租户分组获取景区资源(新接口)
tourismFilesGroupedByTenant: async (params: { tenantId?: string; includeChildren?: boolean; type?: number; status?: number; description?: string; tourismId?: number; current?: number; pageSize?: number }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism/files/grouped/by-tenant', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
const list = (res as any)?.data ?? (res as any)?.data?.data ?? (res as any)?.rows ?? (res as any);
const total = (res as any)?.count ?? (res as any)?.data?.count ?? (Array.isArray(list) ? list.length : 0);
return { data: (Array.isArray(list) ? list : []), total } as { data: Array<{ tourismId: number; tourismName?: string; files: any[] }>; total: number };
},
// 订单列表
order: async (params: { current?: number; pageSize?: number; orderNo?: string; orderStatus?: number; tourismId?: number; payType?: number }) => {
const { current, pageSize, ...rest } = params || {};
@@ -48,7 +57,6 @@ export const ordersApi = {
const res = await request(`/api-order/qrcode/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
// 按景区ID查询二维码列表
qrcodeListByTourism: async (params: { current?: number; pageSize?: number; tourismId: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
@@ -67,7 +75,7 @@ export const ordersApi = {
return (res as any).data || res;
},
deleteTourism: async (id: number) => {
// 后端删除接口为 DELETE /tourism(从请求体读取 id),不支持 path 变量
// 后端删除接口:DELETE /tourism(从请求体读取 id),不支持 path 变量
const res = await request('/api-order/tourism', { method: 'DELETE', data: { id } });
return (res as any).data || res;
},
@@ -150,7 +158,7 @@ export const ordersApi = {
return res as any;
},
// 视频模板(注意后端路径前缀为 /video/template)
// 视频模板(注意后端路径前缀 /video/template)
getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/video/template/list', {
@@ -174,7 +182,7 @@ export const ordersApi = {
return (res as any).data || res;
},
updateVideoTemplateStatus: async (id: number, status: number) => {
// 后端定义为 /{id}/status/{status}
// 后端定义:/{id}/status/{status}
const res = await request(`/api-order/video/template/${id}/status/${status}`, { method: 'PUT' });
return (res as any).data || res;
},
@@ -261,3 +269,4 @@ export const ordersApi = {
return (res as any).data || res;
},
};
-202
View File
@@ -1,202 +0,0 @@
# 前端RSA加密使用指南
## 概述
本项目提供了与后端RSAUtil对应的前端RSA加密解决方案,确保敏感数据在传输过程中的安全性。
## 核心文件
- `rsaUtil.ts` - RSA加密核心工具类
- `securityUtil.ts` - 安全辅助工具类
- `useSecurity.ts` - React Hook,提供安全操作
- `SecureLoginForm` - 安全登录表单组件
## 基本使用
### 1. 密码加密
```typescript
import RSAUtil from '@/utils/rsaUtil';
// 加密密码
const encryptedPassword = RSAUtil.encryptPassword('user123456');
// 或使用便捷导入
import { encryptPassword } from '@/utils/rsaUtil';
const encrypted = encryptPassword('user123456');
```
### 2. 登录表单处理
```typescript
import { useSecurity } from '@/hooks/useSecurity';
const LoginPage = () => {
const { secureLogin } = useSecurity();
const handleLogin = async (values) => {
const secureData = await secureLogin(values);
if (secureData) {
// 发送到后端
api.login(secureData);
}
};
};
```
### 3. 批量敏感字段加密
```typescript
import SecurityUtil from '@/utils/securityUtil';
const userForm = {
username: 'admin',
password: '123456',
email: 'admin@example.com'
};
// 只加密密码字段
const secureForm = SecurityUtil.processFormData(userForm, ['password']);
```
### 4. 使用安全登录组件
```typescript
import SecureLoginForm from '@/components/SecureLoginForm';
const LoginPage = () => {
const handleLogin = async (loginData) => {
// loginData.password 已经被自动加密
const response = await api.login(loginData);
// 处理登录响应
};
return (
<SecureLoginForm
onLogin={handleLogin}
showPasswordStrength={true}
/>
);
};
```
## 安全最佳实践
### 1. 加密时机
- ✅ 在发送请求前立即加密
- ✅ 在表单提交时加密
- ❌ 不要在组件状态中存储加密数据
- ❌ 不要过早加密(影响用户体验)
### 2. 错误处理
```typescript
const encryptedData = RSAUtil.encrypt(sensitiveData);
if (!encryptedData) {
// 处理加密失败
message.error('数据加密失败,请重试');
return;
}
```
### 3. 加密前验证
```typescript
// 密码强度验证
const strength = SecurityUtil.validatePasswordStrength(password);
if (strength.level === 'weak') {
// 提示用户增强密码
}
// 输入安全过滤
const safeInput = SecurityUtil.sanitizeInput(userInput);
```
### 4. 敏感数据脱敏
```typescript
// 显示时脱敏
const maskedPhone = SecurityUtil.maskSensitiveData('13812345678', 'phone');
// 结果: 138****5678
```
## 与后端对接
### 后端解密示例
你的后端使用 `RSAUtil.decryptOne()` 方法解密:
```java
// Java后端
String rawPassword = RSAUtil.decryptOne(req.getPassword());
```
### 前后端数据流程
1. 前端: 用户输入密码 `"123456"`
2. 前端: RSA加密 → `"LBS9qzlDcBQ..."`(Base64 + URL编码)
3. 后端: 接收加密数据
4. 后端: `RSAUtil.decryptOne()` 解密 → `"123456"`
## 安全注意事项
### 1. 公钥管理
- 公钥已硬编码在代码中(与后端保持一致)
- 生产环境建议通过API动态获取公钥
- 定期轮换密钥对
### 2. HTTPS传输
```typescript
// 确保API请求使用HTTPS
const API_BASE_URL = process.env.NODE_ENV === 'production'
? 'https://your-domain.com/api'
: 'http://localhost:9900';
```
### 3. 内存安全
```typescript
// 避免在控制台输出敏感信息
if (process.env.NODE_ENV !== 'development') {
console.log = () => {};
}
```
### 4. 输入验证
```typescript
// 在加密前验证输入
if (!password || password.trim() === '') {
throw new Error('密码不能为空');
}
if (password.length < 6) {
throw new Error('密码长度不能少于6位');
}
```
## 常见问题
### Q: 加密失败怎么办?
A: 检查输入数据是否为空,确认jsencrypt库已正确安装
### Q: 前后端加密解密不匹配?
A: 确认公钥私钥对是否一致,检查Base64编码格式
### Q: 性能优化建议?
A:
- RSA加密较慢,只加密敏感字段
- 考虑使用Web Worker处理大量数据加密
- 合理使用缓存
## 测试
```typescript
// 简单测试
const testData = 'test123';
const encrypted = RSAUtil.encrypt(testData);
console.log('加密结果:', encrypted);
console.log('是否已加密:', RSAUtil.isEncrypted(encrypted));
```
## 升级指南
如需更新加密算法或密钥:
1. 与后端协调更新时间
2. 更新 `rsaUtil.ts` 中的公钥
3. 测试前后端对接
4. 发布更新