!58 !57 feat: 航线管理页面优化

Merge pull request !58 from 鸭先知/test
This commit is contained in:
2025-11-04 07:00:03 +00:00
committed by Gitee
23 changed files with 892 additions and 164 deletions
+3 -1
View File
@@ -25,7 +25,9 @@
"Bash(git commit:*)", "Bash(git commit:*)",
"Read(//f/**)", "Read(//f/**)",
"Bash(git checkout:*)", "Bash(git checkout:*)",
"Bash(git diff:*)" "Bash(git diff:*)",
"Bash(grep:*)",
"Bash(npm run tsc:*)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []
@@ -1,8 +1,11 @@
package com.central.device.controller; package com.central.device.controller;
import cn.hutool.core.bean.BeanUtil;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.device.feign.FileCenterService;
import com.central.device.model.LineFile; import com.central.device.model.LineFile;
import com.central.device.model.vo.WaypointInfoVO;
import com.central.device.service.ILineFileService; import com.central.device.service.ILineFileService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
@@ -13,6 +16,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -32,6 +36,9 @@ import java.util.stream.Collectors;
public class LineFileController { public class LineFileController {
private final ILineFileService lineFileService; private final ILineFileService lineFileService;
@Resource
private FileCenterService fileCenterService;
/** /**
* 列表 * 列表
*/ */
@@ -56,7 +63,11 @@ public class LineFileController {
if (model == null) { if (model == null) {
return Result.failed("未找到对应的航线文件信息"); return Result.failed("未找到对应的航线文件信息");
} }
return Result.succeed(model, "查询成功"); String fileurl = fileCenterService.getFileViewUrl(model.getWaylineId());
WaypointInfoVO infoVO = new WaypointInfoVO();
BeanUtil.copyProperties(model,infoVO);
infoVO.setFileUrl(fileurl);
return Result.succeed(infoVO, "查询成功");
} catch (Exception e) { } catch (Exception e) {
log.error("查询航线文件失败,id: {}", id, e); log.error("查询航线文件失败,id: {}", id, e);
return Result.failed("查询航线文件失败:" + e.getMessage()); return Result.failed("查询航线文件失败:" + e.getMessage());
@@ -0,0 +1,73 @@
package com.central.device.feign;
import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.FileInfo;
import com.central.common.model.Result;
import com.central.device.feign.fallback.FileCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* user-center模块远程调用
*
* @author lsl
* @version 1.0
* @description user-center模块远程调用
* @create 2025/1/13
**/
@FeignClient(name = ServiceNameConstants.FILE_SERVICE, fallbackFactory = FileCenterServiceFallbackFactory.class, dismiss404 = true)
public interface FileCenterService {
/**
* 通过ID查询预览地址
*
* @param id 文件ID
* @return
*/
@GetMapping("/file/{id}")
String getFileViewUrl(@PathVariable("id") String id);
@GetMapping("/type/{id}")
String getFileContentType(@PathVariable("id") String id);
@GetMapping("/qrcode/{codeId}")
Result<Map> uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception;
@PostMapping("/path")
FileInfo creatFileInfo(@RequestBody String path);
@GetMapping("/files/path")
String getViewUrlByPath(@RequestParam("path") String path) ;
@GetMapping("/files/path/style")
String getViewUrlByPathStyle(@RequestParam("params") Map<String,String> params) ;
@GetMapping("/list/files")
List<String> getListFiles(@RequestParam("prefix") String prefix) ;
/**
* 预热文件到CDN
*
* @param urls 需要预热的URL列表
* @param area 预热范围:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
* @return 预热任务ID
*/
@PostMapping("/cdn/prefetch")
Result<String> prefetchFiles(@RequestBody List<String> urls, @RequestParam(value = "area", required = false) String area);
/**
* 批量预热文件到CDN
*
* @param urls 需要预热的URL列表
* @param batchSize 每批次处理的URL数量
* @param area 预热范围
* @return 预热任务执行结果
*/
@PostMapping("/cdn/batch/prefetch")
Result<Boolean> batchPrefetchFiles(@RequestBody List<String> urls,
@RequestParam(value = "batchSize", defaultValue = "100") int batchSize,
@RequestParam(value = "area", required = false) String area);
}
@@ -0,0 +1,78 @@
package com.central.device.feign.fallback;
import com.central.common.model.FileInfo;
import com.central.common.model.Result;
import com.central.device.feign.FileCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* 文件中心调用失败回调
*
* @author lsl
* @version 1.0
* @description 用户中心调用失败回调
* @create 2025/1/17 11:33
**/
@Slf4j
@Component
public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCenterService> {
@Override
public FileCenterService create(Throwable cause) {
return new FileCenterService() {
@Override
public String getFileViewUrl(String id) {
return "";
}
@Override
public String getFileContentType(String id) {
return "";
}
@Override
public Result<Map> uploadQrCodeFile(String codeId) throws Exception {
return null;
}
@Override
public FileInfo creatFileInfo(String path) {
return null;
}
@Override
public String getViewUrlByPath(String path) {
return "";
}
@Override
public String getViewUrlByPathStyle(Map<String, String> params) {
return "";
}
@Override
public List<String> getListFiles(String prefix) {
return List.of();
}
@Override
public Result<String> prefetchFiles(List<String> urls, String area) {
log.warn("CDN预热文件失败,URLs: {}, area: {}", urls, area, cause);
return Result.failed("CDN预热文件失败: " + cause.getMessage());
}
@Override
public Result<Boolean> batchPrefetchFiles(List<String> urls, int batchSize, String area) {
log.warn("CDN批量预热文件失败,URLs: {}, batchSize: {}, area: {}", urls, batchSize, area, cause);
return Result.failed("CDN批量预热文件失败: " + cause.getMessage());
}
};
}
}
@@ -38,4 +38,6 @@ public class LineFile extends SuperEntity {
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime; private Date updateTime;
private String tenantId; private String tenantId;
} }
@@ -0,0 +1,10 @@
package com.central.device.model.vo;
import com.central.device.model.LineFile;
import lombok.Data;
@Data
public class WaypointInfoVO extends LineFile {
private String fileUrl;
}
@@ -3,6 +3,22 @@
<mapper namespace="com.central.device.mapper.LineFileMapper"> <mapper namespace="com.central.device.mapper.LineFileMapper">
<select id="findList" resultType="com.central.device.model.LineFile"> <select id="findList" resultType="com.central.device.model.LineFile">
select * from wayline_file t select * from wayline_file t where 1=1
<if test="p.name != null and p.name != ''">
and t.name like concat('%', #{p.name}, '%')
</if>
<if test="p.waylineId != null and p.waylineId != ''">
and t.wayline_id = #{p.waylineId}
</if>
<if test="p.workspaceId != null and p.workspaceId != ''">
and t.workspace_id = #{p.workspaceId}
</if>
<if test="p.droneModelKey != null and p.droneModelKey != ''">
and t.drone_model_key = #{p.droneModelKey}
</if>
<if test="p.userName != null and p.userName != ''">
and t.user_name like concat('%', #{p.userName}, '%')
</if>
order by t.create_time desc
</select> </select>
</mapper> </mapper>
@@ -95,7 +95,7 @@ public class RefundServiceImpl extends SuperServiceImpl<RefundMapper, Refund> im
result.put("reason", refund.getRefundReason()); result.put("reason", refund.getRefundReason());
result.put("refundReason", refund.getRefundReason()); result.put("refundReason", refund.getRefundReason());
result.put("approveReason", refund.getApproveReason()); result.put("approveReason", refund.getApproveReason());
result.put("createTime", refund.getCreateTime()); result.put("refundTime", refund.getRefundTime());
result.put("applyTime", refund.getCreateTime()); result.put("applyTime", refund.getCreateTime());
// 处理图片列表 - refundImgs 可能是逗号分隔的字符串或JSON // 处理图片列表 - refundImgs 可能是逗号分隔的字符串或JSON
+2
View File
@@ -28,6 +28,7 @@
"moment": "^2.29.0", "moment": "^2.29.0",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"spark-md5": "^3.0.2",
"umi": "^3.5.0", "umi": "^3.5.0",
"xlsx": "^0.18.5" "xlsx": "^0.18.5"
}, },
@@ -35,6 +36,7 @@
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0", "@types/react-dom": "^17.0.0",
"@types/spark-md5": "^3.0.5",
"@umijs/preset-react": "^2.1.0", "@umijs/preset-react": "^2.1.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"typescript": "^4.5.0" "typescript": "^4.5.0"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

After

Width:  |  Height:  |  Size: 2.7 MiB

@@ -59,7 +59,8 @@ const BasicLayout: React.FC = (props: any) => {
if (!cand) return undefined; if (!cand) return undefined;
const lower = cand.toLowerCase(); const lower = cand.toLowerCase();
if (lower.startsWith('http')) return cand; // 澶栭摼 if (lower.startsWith('http')) return cand; // 澶栭摼
if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 闈欐€佽矾鐢? if (lower === '/welcome' || lower === 'welcome') return '/welcome'; if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 闈欐€佽矾鐢?
if (lower === '/welcome' || lower === 'welcome') return '/welcome';
// 鍏煎鍚庣鑿滃崟鏈甫 .html 鐨勫彾瀛愯矾鐢憋紝渚嬪 /system/tenant => /system/tenant.html // 鍏煎鍚庣鑿滃崟鏈甫 .html 鐨勫彾瀛愯矾鐢憋紝渚嬪 /system/tenant => /system/tenant.html
const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`; const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`;
const parts = ensureSlash.split('/').filter(Boolean); const parts = ensureSlash.split('/').filter(Boolean);
@@ -96,7 +97,7 @@ const BasicLayout: React.FC = (props: any) => {
const item: MenuDataItem = { const item: MenuDataItem = {
key: keyStr, key: keyStr,
name: menu.name || `鑿滃崟${index + 1}`, name: menu.name || `保存中${index + 1}`,
path, path,
icon: getIcon(path), icon: getIcon(path),
children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)), children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)),
@@ -1,14 +1,17 @@
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components'; import { ModalForm, ProForm, ProFormText } from '@ant-design/pro-components';
import { Button, Upload, message } from 'antd'; import { Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons'; import { UploadOutlined } from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { filesApi } from '@/services/files';
import SparkMD5 from 'spark-md5';
export type WaylineFormValues = { export type WaylineFormValues = {
id?: number; id?: number;
name?: string; name?: string;
workspaceId?: string;
waylineId?: string; waylineId?: string;
sign?: string; sign?: string;
workspaceId?: string;
}; };
interface WaylineFormProps { interface WaylineFormProps {
@@ -17,28 +20,75 @@ interface WaylineFormProps {
onVisibleChange: (v: boolean) => void; onVisibleChange: (v: boolean) => void;
onFinish: (values: WaylineFormValues) => Promise<boolean>; onFinish: (values: WaylineFormValues) => Promise<boolean>;
initialValues?: Partial<WaylineFormValues>; initialValues?: Partial<WaylineFormValues>;
workspaceOptions?: Array<{ label: string; value: string }>;
} }
// 简单上传到文件服务,返回 id/url/path /**
async function uploadWaylineFile(file: File) { * 计算文件的 MD5 值
const formData = new FormData(); */
formData.append('file', file); async function calculateFileMD5(file: File): Promise<string> {
const resp = await fetch('/api-file/files-anon', { method: 'POST', body: formData }); return new Promise((resolve, reject) => {
const data = await resp.json(); const reader = new FileReader();
if (!data || !data.id) throw new Error('上传失败'); const spark = new SparkMD5.ArrayBuffer();
return data as { id: string; url: string; path: string };
reader.onload = (e) => {
try {
spark.append(e.target?.result as ArrayBuffer);
resolve(spark.end());
} catch (err) {
reject(err);
}
};
reader.onerror = () => {
reject(new Error('文件读取失败'));
};
reader.readAsArrayBuffer(file);
});
} }
const WaylineForm: React.FC<WaylineFormProps> = ({ title, visible, onVisibleChange, onFinish, initialValues, workspaceOptions }) => { const WaylineForm: React.FC<WaylineFormProps> = ({ title, visible, onVisibleChange, onFinish, initialValues }) => {
const formRef = useRef<any>(); const formRef = useRef<any>();
const [fileInfo, setFileInfo] = useState<{ id: string; url: string } | undefined>(); const [fileInfo, setFileInfo] = useState<{ id: string; name: string; md5: string; url: string } | undefined>();
const [loading, setLoading] = useState(false);
/**
* 当编辑页面打开时,如果有waylineId,调用接口获取完整信息
*/
useEffect(() => { useEffect(() => {
if (initialValues) { if (visible && initialValues?.waylineId) {
setLoading(true);
deviceApi
.getWaylineInfoByWaylineId(initialValues.waylineId)
.then((data) => {
if (data) {
formRef.current?.setFieldsValue({
id: data.id,
name: data.name,
waylineId: data.waylineId,
sign: data.sign,
});
// 如果有fileUrl,设置文件信息
if (data.fileUrl) {
setFileInfo({
id: data.waylineId || data.id?.toString() || '',
name: data.name || 'wayline_file',
md5: data.sign || '',
url: data.fileUrl,
});
}
}
})
.catch((err) => {
console.error('获取航线信息失败:', err);
message.error('获取航线信息失败');
})
.finally(() => setLoading(false));
} else if (visible && initialValues) {
// 新增时直接回显
formRef.current?.setFieldsValue(initialValues); formRef.current?.setFieldsValue(initialValues);
} }
}, [initialValues]); }, [visible, initialValues?.waylineId]);
return ( return (
<ModalForm<WaylineFormValues> <ModalForm<WaylineFormValues>
@@ -47,7 +97,10 @@ const WaylineForm: React.FC<WaylineFormProps> = ({ title, visible, onVisibleChan
formRef={formRef} formRef={formRef}
onVisibleChange={(v) => { onVisibleChange={(v) => {
onVisibleChange?.(v); onVisibleChange?.(v);
if (!v) setFileInfo(undefined); if (!v) {
setFileInfo(undefined);
setLoading(false);
}
}} }}
onFinish={async (values) => { onFinish={async (values) => {
if (!values.waylineId && !fileInfo) { if (!values.waylineId && !fileInfo) {
@@ -56,32 +109,17 @@ const WaylineForm: React.FC<WaylineFormProps> = ({ title, visible, onVisibleChan
} }
const payload: WaylineFormValues = { const payload: WaylineFormValues = {
...initialValues, ...initialValues,
...values, name: fileInfo?.name || values.name, // 优先使用上传的文件名
waylineId: values.waylineId || fileInfo?.id, waylineId: values.waylineId || fileInfo?.id,
sign: fileInfo?.md5 || values.sign,
workspaceId: '1', // 工作区默认为 1
}; };
return onFinish(payload); return onFinish(payload);
}} }}
modalProps={{ destroyOnClose: true }} modalProps={{ destroyOnClose: true, confirmLoading: loading }}
> >
<ProForm.Group> {/* 上传文件放在第一位 */}
<ProFormText <div style={{ marginBottom: 12, fontWeight: 500 }}>航线文件</div>
name="name"
label="航线名称"
rules={[{ required: true, message: '请输入航线名称' }]}
width="md"
/>
<ProFormSelect
name="workspaceId"
label="工作区"
rules={[{ required: true, message: '请选择工作区' }]}
options={workspaceOptions}
width="md"
/>
<ProFormText name="waylineId" hidden />
<ProFormText name="sign" hidden />
</ProForm.Group>
<div style={{ marginBottom: 12 }}>航线文件</div>
<Upload <Upload
maxCount={1} maxCount={1}
accept=".kmz,.kml" accept=".kmz,.kml"
@@ -89,13 +127,29 @@ const WaylineForm: React.FC<WaylineFormProps> = ({ title, visible, onVisibleChan
customRequest={async ({ file, onSuccess, onError }) => { customRequest={async ({ file, onSuccess, onError }) => {
try { try {
if (file instanceof File) { if (file instanceof File) {
const r = await uploadWaylineFile(file); // 计算文件 MD5
setFileInfo({ id: r.id, url: r.url }); const md5 = await calculateFileMD5(file);
formRef.current?.setFieldsValue({ waylineId: r.id });
// 上传文件
const fileData = await filesApi.uploadFile(file);
setFileInfo({
id: fileData.id,
name: fileData.name,
md5: md5,
url: fileData.url,
});
formRef.current?.setFieldsValue({
waylineId: fileData.id,
name: fileData.name, // 自动填充返回的文件名到航线名称
sign: md5,
});
message.success('上传成功'); message.success('上传成功');
onSuccess?.('ok'); onSuccess?.('ok');
} }
} catch (err) { } catch (err) {
console.error('上传错误:', err);
message.error('上传失败'); message.error('上传失败');
onError?.(err as any); onError?.(err as any);
} }
@@ -104,8 +158,24 @@ const WaylineForm: React.FC<WaylineFormProps> = ({ title, visible, onVisibleChan
<Button icon={<UploadOutlined />}>{fileInfo ? '重新上传' : '上传文件'}</Button> <Button icon={<UploadOutlined />}>{fileInfo ? '重新上传' : '上传文件'}</Button>
</Upload> </Upload>
{fileInfo && ( {fileInfo && (
<div style={{ marginTop: 8, color: '#666' }}>已上传:{fileInfo.id}</div> <div style={{ marginTop: 8, padding: '8px 12px', backgroundColor: '#f5f5f5', borderRadius: 4 }}>
<div style={{ color: '#666', fontSize: 12 }}>已上传文件:</div>
<div style={{ color: '#1677ff', fontWeight: 500, marginTop: 4 }}>{fileInfo.name}</div>
<div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>MD5: {fileInfo.md5}</div>
</div>
)} )}
<ProForm.Group style={{ marginTop: 24 }}>
<ProFormText
name="name"
label="航线名称"
placeholder="请输入航线名称或使用上传的文件名"
rules={[{ required: true, message: '请输入航线名称' }]}
width="md"
/>
<ProFormText name="waylineId" hidden />
<ProFormText name="sign" hidden />
</ProForm.Group>
</ModalForm> </ModalForm>
); );
}; };
@@ -2,7 +2,8 @@ import React, { forwardRef, useImperativeHandle, useRef } from 'react';
import type { ActionType } from '@ant-design/pro-components'; import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components'; import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components'; import type { ProColumns } from '@ant-design/pro-components';
import { Space } from 'antd'; import { Space, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { deviceApi } from '@/services/device'; import { deviceApi } from '@/services/device';
import { downloadByUrl } from '@/utils/download'; import { downloadByUrl } from '@/utils/download';
@@ -21,27 +22,64 @@ const WaylineTable = forwardRef<WaylineTableRef, WaylineTableProps>(({ params, o
useImperativeHandle(ref, () => ({ reload: () => actionRef.current?.reload() })); useImperativeHandle(ref, () => ({ reload: () => actionRef.current?.reload() }));
/**
* 处理航线文件下载
* 先通过waylineId获取航线信息(包含fileUrl),再使用fileUrl下载
*/
const handleDownload = async (record: any) => {
try {
if (!record.waylineId) {
message.error('航线ID缺失');
return;
}
const hide = message.loading('获取航线信息中...');
try {
// 通过waylineId获取航线完整信息,包括fileUrl
const waylineInfo = await deviceApi.getWaylineInfoByWaylineId(record.waylineId);
hide();
if (!waylineInfo) {
message.error('无法获取航线信息');
return;
}
const fileUrl = waylineInfo.fileUrl;
if (!fileUrl) {
message.error('航线文件URL不存在');
return;
}
// 使用fileUrl直接下载
const fileName = record.name || `wayline_${record.waylineId}`;
downloadByUrl(fileUrl, fileName);
message.success('开始下载航线文件');
} catch (error) {
hide();
console.error('获取航线信息失败:', error);
message.error('获取航线信息失败');
}
} catch (error) {
message.error('下载失败');
console.error('下载航线文件错误:', error);
}
};
const columns: ProColumns<any>[] = [ const columns: ProColumns<any>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, { dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '航线名称', dataIndex: 'name' }, { title: '航线名称', dataIndex: 'name' },
{ title: '航线ID', dataIndex: 'waylineId' }, { title: '航线ID', dataIndex: 'waylineId' },
{ title: '空间ID', dataIndex: 'workspaceId' }, { title: '空间ID', dataIndex: 'workspaceId' },
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 }, { title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 },
{
title: '航线文件', dataIndex: 'fileUrl', search: false,
render: (_, record) => record.fileUrl ? (
<a
href={record.fileUrl}
onClick={(e) => { e.preventDefault(); downloadByUrl(record.fileUrl, record.name || 'wayline.kmz'); }}
>下载文件</a>
) : '-'
},
{ title: '文件签名', dataIndex: 'sign', ellipsis: true, copyable: true }, { title: '文件签名', dataIndex: 'sign', ellipsis: true, copyable: true },
{ {
title: '操作', key: 'action', valueType: 'option', title: '操作', key: 'action', valueType: 'option',
render: (_, record) => ( render: (_, record) => (
<Space> <Space>
<a onClick={() => onEdit?.(record)}>编辑</a> <a onClick={() => onEdit?.(record)}>编辑</a>
<a onClick={() => handleDownload(record)} title="下载航线文件">
<DownloadOutlined /> 下载
</a>
<a style={{ color: '#1677ff' }} onClick={() => onDelete?.(record)}>删除</a> <a style={{ color: '#1677ff' }} onClick={() => onDelete?.(record)}>删除</a>
</Space> </Space>
) )
@@ -62,3 +100,4 @@ const WaylineTable = forwardRef<WaylineTableRef, WaylineTableProps>(({ params, o
}); });
export default WaylineTable; export default WaylineTable;
@@ -62,8 +62,15 @@ const WaylinePage: React.FC = () => {
return ( return (
<PageContainer header={{ title: '航线管理' }}> <PageContainer header={{ title: '航线管理' }}>
<SearchBarPlus defaultCollapsed split span={6} onTenantChanged={() => tableRef.current?.reload()} onFinish={async (values) => setQuery(values)}> <SearchBarPlus
<ProFormText name="name" label="名称" placeholder="请输入关键字" /> defaultCollapsed
split span={6}
hideReset
showTenant={false}
onTenantChanged={() => tableRef.current?.reload()}
onFinish={async (values) => setQuery(values)}>
<ProFormText name="name" label="航线名称" />
<ProFormText name="waylineId" label="航线code" />
</SearchBarPlus> </SearchBarPlus>
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} /> <ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
@@ -0,0 +1,204 @@
import React, { useState } from 'react';
import {
ModalForm,
ProForm,
ProFormDigit,
ProFormSelect,
ProFormText,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Upload, message } from 'antd';
import { Image as AntImage } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { RcFile } from 'antd/es/upload';
export interface HomeCarouselItem {
id?: number;
imageUrl?: string;
linkUrl?: string;
sort?: number;
status?: number;
title?: string;
description?: string;
type?: number;
}
export interface CreateFormProps {
open: boolean;
initialValues?: Partial<HomeCarouselItem>;
onOpenChange: (v: boolean) => void;
onFinish: (values: HomeCarouselItem) => Promise<boolean>;
}
const CreateForm: React.FC<CreateFormProps> = ({
open,
initialValues,
onOpenChange,
onFinish,
}) => {
const [imageUrl, setImageUrl] = useState<string>(initialValues?.imageUrl || '');
const [imagePath, setImagePath] = useState<string>(initialValues?.imageUrl || '');
// 上传文件到服务器
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 };
};
const handleBeforeUpload = (file: RcFile) => {
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('只能上传图片文件');
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('图片大小不能超过10MB');
}
return isImage && isLt10M;
};
const isEdit = !!initialValues?.id;
return (
<ModalForm<HomeCarouselItem>
title={isEdit ? '编辑轮播图' : '新增轮播图'}
visible={open}
onVisibleChange={(visible) => {
onOpenChange(visible);
if (!visible) {
setImageUrl('');
setImagePath('');
}
}}
initialValues={initialValues}
onFinish={async (values) => {
if (!isEdit && !imagePath) {
message.error('请上传轮播图片');
return false;
}
return onFinish({
...values,
imageUrl: imagePath || values.imageUrl,
});
}}
modalProps={{
destroyOnClose: true,
maskClosable: false,
}}
>
<ProFormText
name="title"
label="标题"
placeholder="请输入轮播图标题"
rules={[{ required: true, message: '标题不能为空' }]}
/>
<ProFormText
name="linkUrl"
label="跳转链接"
placeholder="请输入跳转链接"
/>
<ProFormSelect
name="type"
label="类型"
placeholder="请选择类型"
options={[
{ label: '首页轮播', value: 0 },
{ label: '活动', value: 1 },
{ label: '其他', value: 2 },
]}
rules={[{ required: true, message: '请选择类型' }]}
/>
<ProFormTextArea
name="description"
label="描述"
placeholder="请输入轮播图描述"
fieldProps={{
rows: 3,
}}
/>
<ProFormDigit
name="sortOrder"
label="排序"
placeholder="请输入排序号"
min={1}
fieldProps={{ precision: 0 }}
initialValue={1}
/>
<ProFormSelect
name="status"
label="状态"
placeholder="请选择状态"
options={[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]}
rules={[{ required: true, message: '请选择状态' }]}
initialValue={1}
/>
<div style={{ marginBottom: 16 }}>
<label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
上传图片 {!isEdit && <span style={{ color: '#ff4d4f' }}>*</span>}
</label>
<Upload
maxCount={1}
accept="image/*"
showUploadList={false}
beforeUpload={handleBeforeUpload}
customRequest={async ({ file, onSuccess, onError }) => {
try {
if (file instanceof File) {
const r = await doUpload(file as File);
setImageUrl(r.url);
setImagePath(r.path);
message.success('上传成功');
onSuccess?.('ok');
}
} catch (err) {
message.error('上传失败');
onError?.(err as any);
}
}}
>
<Button icon={<UploadOutlined />}>
{imageUrl ? '更换图片' : isEdit ? '上传或更换图片' : '上传轮播图片'}
</Button>
</Upload>
</div>
{(imageUrl || (isEdit && initialValues?.imageUrl)) && (
<div style={{ marginTop: 16 }}>
<p style={{ marginBottom: 8 }}>图片预览:</p>
<AntImage
src={imageUrl || initialValues?.imageUrl}
width={200}
style={{ borderRadius: 4 }}
placeholder={
<div
style={{
background: '#f5f5f5',
height: 200,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
加载中...
</div>
}
/>
</div>
)}
</ModalForm>
);
};
export default CreateForm;
@@ -1,38 +0,0 @@
import React from 'react';
import { ModalForm, ProFormDigit, ProFormSelect, ProFormText } from '@ant-design/pro-components';
export interface HomeCarouselItem {
id?: number;
imageUrl?: string;
linkUrl?: string;
sort?: number;
status?: number;
}
export interface HomeCarouselFormProps {
open: boolean;
title: string;
initialValues?: Partial<HomeCarouselItem>;
onOpenChange: (v: boolean) => void;
onFinish: (values: HomeCarouselItem) => Promise<boolean>;
}
const HomeCarouselForm: React.FC<HomeCarouselFormProps> = ({ open, title, initialValues, onOpenChange, onFinish }) => {
return (
<ModalForm<HomeCarouselItem>
title={title}
visible={open}
onVisibleChange={onOpenChange}
onFinish={onFinish}
initialValues={initialValues}
modalProps={{ destroyOnClose: true }}
>
<ProFormText name="imageUrl" label="图片地址" rules={[{ required: true, message: '请输入图片地址' }]} />
<ProFormText name="linkUrl" label="跳转链接" />
<ProFormDigit name="sort" label="排序" min={1} fieldProps={{ precision: 0 }} initialValue={1} />
<ProFormSelect name="status" label="状态" valueEnum={{ 1: '启用', 0: '禁用' }} initialValue={1} />
</ModalForm>
);
};
export default HomeCarouselForm;
@@ -0,0 +1,55 @@
/**
* 首页轮播图管理 - 常量和类型定义
*/
// 状态选项
export const STATUS_OPTIONS = [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
];
// 状态枚举
export const STATUS_ENUM = {
ENABLED: 1,
DISABLED: 0,
} as const;
// 默认排序值
export const DEFAULT_SORT = 1;
// 默认状态值
export const DEFAULT_STATUS = 1;
// 上传配置
export const UPLOAD_CONFIG = {
maxCount: 1,
accept: 'image/*',
maxSize: 10 * 1024 * 1024, // 10MB
};
// 图片选项
export const IMAGE_PLACEHOLDER_STYLE = {
background: '#f5f5f5',
height: 100,
display: 'flex' as const,
alignItems: 'center' as const,
justifyContent: 'center' as const,
};
// API错误信息
export const ERROR_MESSAGES = {
UPLOAD_FAILED: '上传失败',
IMAGE_REQUIRED: '请上传轮播图片',
SAVE_FAILED: '保存失败',
DELETE_FAILED: '删除失败',
ONLY_IMAGE: '只能上传图片文件',
FILE_TOO_LARGE: '图片大小不能超过10MB',
} as const;
// API成功信息
export const SUCCESS_MESSAGES = {
UPLOAD_SUCCESS: '上传成功',
CREATE_SUCCESS: '新增成功',
UPDATE_SUCCESS: '修改成功',
DELETE_SUCCESS: '删除成功',
} as const;
@@ -1,98 +1,230 @@
import React, { useState } from 'react'; import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components'; import { PageContainer, ProTable, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, message } from 'antd'; import { Popconfirm, message, Space, Image as AntImage, Typography } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { ordersApi } from '@/services/orders'; import { ordersApi } from '@/services/orders';
import HomeCarouselForm, { HomeCarouselItem } from './components/HomeCarouselForm'; import CreateForm from './components/CreateForm';
import type { HomeCarouselItem } from './components/CreateForm';
const { Link } = Typography;
// 常量定义
const STATUS_OPTIONS = [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
];
const TYPE_OPTIONS = [
{ label: '首页轮播', value: 0 },
{ label: '活动', value: 1 },
{ label: '其他', value: 2 },
];
const HomeCarouselPage: React.FC = () => { const HomeCarouselPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false); const actionRef = useRef<ActionType>();
const [editOpen, setEditOpen] = useState(false); const [formOpen, setFormOpen] = useState(false);
const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined); const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({}); const [searchParams, setSearchParams] = useState<Record<string, any>>({});
const columns: any[] = [ // 处理删除
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, const handleDelete = async (record: HomeCarouselItem) => {
{ title: '图片', dataIndex: 'imageUrl', render: (v: string) => <img src={v} alt="img" style={{ width: 80, height: 40, objectFit: 'cover' }} /> }, const hide = message.loading('删除中...');
{ title: '跳转链接', dataIndex: 'linkUrl', ellipsis: true }, try {
{ title: '排序', dataIndex: 'sort' }, await ordersApi.deleteHomeCarousel(record.id!);
{ title: '状态', dataIndex: 'status', render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag> }, message.success('删除成功');
actionRef.current?.reload();
return true;
} catch (e) {
message.error('删除失败');
return false;
} finally {
hide();
}
};
const columns: ProColumns<HomeCarouselItem>[] = [
{ {
title: '操作', key: 'action', dataIndex: 'index',
valueType: 'indexBorder',
width: 48,
},
{
title: '标题',
dataIndex: 'title',
ellipsis: true,
copyable: true,
},
{
title: '类型',
dataIndex: 'type',
width: 100,
valueEnum: TYPE_OPTIONS.reduce((acc, curr) => ({
...acc,
[curr.value]: { text: curr.label },
}), {}),
},
{
title: '图片',
dataIndex: 'imageUrl',
width: 120,
render: (_: any, record: HomeCarouselItem) => ( render: (_: any, record: HomeCarouselItem) => (
record.imageUrl ? (
<AntImage
src={record.imageUrl}
width={100}
placeholder={
<div style={{ background: '#f5f5f5', height: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
加载中...
</div>
}
/>
) : (
<span>-</span>
)
),
},
{
title: '跳转链接',
dataIndex: 'redirectUrl',
ellipsis: true,
render: (_: any, record: HomeCarouselItem) => (
record.linkUrl ? <Link href={record.linkUrl} target="_blank">{record.linkUrl}</Link> : '-'
),
},
{
title: '描述',
dataIndex: 'description',
ellipsis: true,
},
{
title: '排序',
dataIndex: 'sortOrder',
width: 80,
},
{
title: '状态',
dataIndex: 'status',
width: 80,
valueEnum: {
1: { text: '启用', status: 'Success' },
0: { text: '禁用', status: 'Error' },
},
},
{
title: '操作',
valueType: 'option',
width: 180,
fixed: 'right',
render: (_, record) => (
<Space> <Space>
<a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a> <a
<Popconfirm title={`确认删除?`} onConfirm={async () => { onClick={() => {
const hide = message.loading('删除中...'); setCurrent(record);
try { setFormOpen(true);
await ordersApi.deleteHomeCarousel(record.id!); }}
message.success('删除成功'); >
} catch (e) { 编辑
message.error('删除失败'); </a>
} finally { hide(); } <Popconfirm
}}> title="确认删除轮播图?"
onConfirm={() => handleDelete(record)}
okText="确认"
cancelText="取消"
>
<a style={{ color: '#1677ff' }}>删除</a> <a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm> </Popconfirm>
</Space> </Space>
) ),
}, },
]; ];
return ( return (
<PageContainer header={{ title: '首页轮播' }}> <PageContainer header={{ title: '轮播图管理' }}>
<SearchBarPlus {/*<SearchBarPlus*/}
defaultCollapsed {/* defaultCollapsed*/}
split {/* split*/}
span={8} {/* span={8}*/}
onTenantChanged={() => { /* 仅触发表格刷新 */ }} {/* hideReset*/}
onFinish={async (values) => setParams(values)} {/* showTenant={false}*/}
/> {/* onFinish={async (values) => {*/}
{/* setSearchParams(values);*/}
{/* actionRef.current?.reload();*/}
{/* }}*/}
{/*>*/}
{/* <ProFormText*/}
{/* name="title"*/}
{/* label="标题"*/}
{/* placeholder="请输入标题关键字"*/}
{/* />*/}
{/* <ProFormSelect*/}
{/* name="status"*/}
{/* label="状态"*/}
{/* placeholder="请选择状态"*/}
{/* options={STATUS_OPTIONS}*/}
{/* fieldProps={{*/}
{/* allowClear: true,*/}
{/* }}*/}
{/* />*/}
{/*</SearchBarPlus>*/}
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} /> <ActionBar
left={
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => {
setCurrent(undefined);
setFormOpen(true);
}}>
新增轮播图
</GradientButton>
}
/>
<GlassCard> <GlassCard>
<ProTable<HomeCarouselItem> <ProTable<HomeCarouselItem>
rowKey="id" rowKey="id"
request={(p) => ordersApi.homeCarouselList({ ...(p as any), ...params })} actionRef={actionRef}
columns={columns} columns={columns}
request={(p) => ordersApi.homeCarousel({ ...(p as any), ...searchParams })}
search={false} search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }} pagination={{
defaultPageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
}}
toolBarRender={false}
/> />
</GlassCard> </GlassCard>
<HomeCarouselForm <CreateForm
title="新增轮播" open={formOpen}
open={createOpen} initialValues={current}
onOpenChange={setCreateOpen} onOpenChange={(visible) => {
setFormOpen(visible);
if (!visible) {
setCurrent(undefined);
}
}}
onFinish={async (values) => { onFinish={async (values) => {
const hide = message.loading('保存中...'); const hide = message.loading('保存中...');
try { try {
await ordersApi.saveOrUpdateHomeCarousel(values); if (current?.id) {
message.success('新增成功'); // 编辑模式
await ordersApi.saveOrUpdateHomeCarousel({ ...(current as any), ...values });
message.success('修改成功');
} else {
// 新增模式
await ordersApi.saveOrUpdateHomeCarousel(values);
message.success('新增成功');
}
actionRef.current?.reload();
return true; return true;
} catch (e) { } catch (e) {
message.error('保存失败'); message.error('保存失败');
return false; return false;
} finally { hide(); } } finally {
}} hide();
/> }
<HomeCarouselForm
title="编辑轮播"
open={editOpen}
initialValues={current}
onOpenChange={setEditOpen}
onFinish={async (values) => {
const hide = message.loading('保存中...');
try {
await ordersApi.saveOrUpdateHomeCarousel({ ...(current as any), ...values });
message.success('修改成功');
return true;
} catch (e) {
message.error('修改失败');
return false;
} finally { hide(); }
}} }}
/> />
</PageContainer> </PageContainer>
@@ -376,7 +376,13 @@ const RefundReviewModal: React.FC<RefundReviewModalProps> = ({
{/* 申请时间 */} {/* 申请时间 */}
<div style={{ marginBottom: 16 }}> <div style={{ marginBottom: 16 }}>
<span style={{ fontWeight: 'bold' }}>申请时间</span> <span style={{ fontWeight: 'bold' }}>申请时间</span>
<div style={{ marginTop: 4 }}>{formatTime(refundData?.createTime || refundData?.applyTime)}</div> <div style={{ marginTop: 4 }}>{formatTime(refundData?.applyTime || refundData?.applyTime)}</div>
<span style={{ fontWeight: 'bold' }}>退款时间</span>
<div style={{ marginTop: 4 }}>{formatTime(refundData?.refundTime || refundData?.refundTime)}</div>
</div>
<div style={{ marginBottom: 16 }}>
</div> </div>
<Divider /> <Divider />
@@ -38,13 +38,13 @@ const ResourcesActionCell: React.FC<{ record: OrderItem; onReload?: () => void;
<Space size="small" wrap style={{ minWidth: 120 }}> <Space size="small" wrap style={{ minWidth: 120 }}>
<Link onClick={() => setResourceModalVisible(true)}>资源列表</Link> <Link onClick={() => setResourceModalVisible(true)}>资源列表</Link>
<StatusUpdater record={record} onUpdated={onReload} canModifyStatus={canModifyStatus} /> <StatusUpdater record={record} onUpdated={onReload} canModifyStatus={canModifyStatus} />
{isTaskComplete && ( {canModifyStatus && isTaskComplete && (
<Link onClick={() => setCreateRefundModalVisible(true)}>创建退款</Link> <Link onClick={() => setCreateRefundModalVisible(true)}>创建退款</Link>
)} )}
{isRefunding && ( {canModifyStatus && isRefunding && (
<Link onClick={() => setRefundModalVisible(true)}>退款审核</Link> <Link onClick={() => setRefundModalVisible(true)}>退款审核</Link>
)} )}
{isRefundResolved && ( {canModifyStatus && isRefundResolved && (
<Link onClick={() => setRefundModalVisible(true)}>退款查看</Link> <Link onClick={() => setRefundModalVisible(true)}>退款查看</Link>
)} )}
</Space> </Space>
@@ -87,7 +87,7 @@ const TenantForm: React.FC<TenantFormProps> = ({ visible, title, initialValues,
</ProForm.Group> </ProForm.Group>
<ProForm.Group> <ProForm.Group>
<ProForm.Item name='parentTenantId' label='上级租户'> <ProForm.Item name='parentTenantId' label='上级租户'>
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={toTreeData(tree)} placeholder='选择上级租户' disabled={editing} /> <TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={toTreeData(tree)} placeholder='选择上级租户'/>
</ProForm.Item> </ProForm.Item>
<ProForm.Item name='tenantType' label='类型' rules={[{ required: true, message: '请选择类型' }]}> <ProForm.Item name='tenantType' label='类型' rules={[{ required: true, message: '请选择类型' }]}>
<Select style={{ width: 260 }} placeholder='选择类型' disabled={editing && !initialValues?.parentTenantId}> <Select style={{ width: 260 }} placeholder='选择类型' disabled={editing && !initialValues?.parentTenantId}>
@@ -30,6 +30,33 @@ export const deviceApi = {
const res = await request(`/api-device/wayline/${id}`, { method: 'DELETE' }); const res = await request(`/api-device/wayline/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
/**
* 根据航线ID获取航线详细信息(包括文件URL)
* @param waylineId 航线ID
* @returns 航线详细信息
*/
getWaylineInfoByWaylineId: async (waylineId: string) => {
const res = await request(`/api-device/wayline/${waylineId}`, { method: 'GET' });
return (res as any).data as {
id?: number;
name?: string;
waylineId?: string;
sign?: string;
workspaceId?: string;
fileUrl?: string;
objectKey?: string;
[k: string]: any;
};
},
/**
* 获取航线文件访问URL
* @param id 航线文件ID
* @returns 访问URL
*/
getWaylineFileUrl: async (id: number) => {
const res = await request(`/api-device/wayline/url/${id}`, { method: 'GET' });
return (res as any).data || '';
},
deviceList: async (params: { page?: number; limit?: number; [k:string]: any }) => { deviceList: async (params: { page?: number; limit?: number; [k:string]: any }) => {
const res = await request('/api-device/device', { method: 'GET', params }); const res = await request('/api-device/device', { method: 'GET', params });
return { data: (res as any).data, total: (res as any).count } as { data: DeviceItem[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: DeviceItem[]; total: number };
@@ -13,5 +13,36 @@ export const filesApi = {
const res = await request(`/api-file/files/${id}`, { method: 'DELETE' }); const res = await request(`/api-file/files/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
/**
* 上传文件通用接口
* @param file 上传的文件
* @returns 文件完整信息对象
*/
uploadFile: async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const resp = await request('/api-file/files-anon', {
method: 'POST',
body: formData,
});
const data = (resp as any);
if (!data || !data.id) throw new Error('上传失败');
return data as {
id: string;
name: string;
isImg: boolean;
contentType: string;
size: number;
path: string;
url: string;
source: string;
storageType: string | null;
createTime: string;
updateTime: string;
};
},
}; };