feat(ecom): 订单管理新增批量删除功能

- OrderServiceImpl 新增 deleteOrders 批量删除接口,单次最多500条
- 新增 BatchDeleteOrderDTO 参数校验
- 前端订单列表新增勾选框,支持批量删除选中订单
- OssServiceImpl 简化上传逻辑,移除冗余代码
- 更新 OSS 凭证配置
This commit is contained in:
小蟑螂
2026-05-05 16:20:28 +08:00
parent 31dc0cb2a1
commit a1953d5447
12 changed files with 203 additions and 198 deletions
@@ -9,6 +9,7 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.BatchDeleteOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.BatchImportOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.CreateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderFilterDTO;
@@ -57,6 +58,14 @@ public class OrderController {
return ApiResponse.success("订单删除成功");
}
@Operation(summary = "批量删除订单", description = "按ID批量删除订单,须属于当前公司")
@PostMapping("/batch-delete")
@RequirePermission(value = "ecom:order:delete", description = "删除订单", allowSuper = true)
public ApiResponse<Void> batchDeleteOrders(@Valid @RequestBody BatchDeleteOrderDTO dto) {
orderService.deleteOrders(dto.getOrderIds());
return ApiResponse.success("批量删除订单成功");
}
@Operation(summary = "分页获取订单列表", description = "分页获取订单列表,支持条件过滤")
@PostMapping("/list")
@RequirePermission(value = "ecom:order:read", description = "查询订单列表", allowSuper = true)
@@ -0,0 +1,21 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
/**
* 批量删除订单 DTO
*/
@Data
@Schema(description = "批量删除订单DTO")
public class BatchDeleteOrderDTO {
@Schema(description = "订单ID列表", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "订单ID列表不能为空")
@Size(max = 500, message = "单次最多删除500条订单")
private List<Long> orderIds;
}
@@ -11,6 +11,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.BatchImportResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.OrderVO;
import java.util.List;
/**
* 订单服务接口
*/
@@ -40,6 +42,13 @@ public interface OrderService extends IService<OrderPO> {
*/
void deleteOrder(Long id);
/**
* 批量删除订单(须属于当前公司)
*
* @param orderIds 订单ID列表
*/
void deleteOrders(List<Long> orderIds);
/**
* 分页获取订单列表
*
@@ -259,6 +259,36 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
this.removeById(id);
}
/**
* 批量删除订单
*/
@Override
@Transactional
public void deleteOrders(List<Long> orderIds) {
if (orderIds == null || orderIds.isEmpty()) {
throw new BusinessException("请选择要删除的订单");
}
List<Long> uniqueIds = orderIds.stream()
.filter(java.util.Objects::nonNull)
.distinct()
.toList();
if (uniqueIds.isEmpty()) {
throw new BusinessException("请选择要删除的订单");
}
if (uniqueIds.size() > 500) {
throw new BusinessException("单次最多删除500条订单");
}
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getCompanyId, companyId)
.in(OrderPO::getId, uniqueIds);
long matched = this.count(wrapper);
if (matched != uniqueIds.size()) {
throw new BusinessException("存在无效订单或无权删除的订单");
}
this.remove(wrapper);
}
/**
* 获取订单分页列表
* @param pageQueryDTO 分页查询DTO
@@ -8,17 +8,8 @@ import top.xyquan.ecomdmbbackend.modules.sys.file.config.OssConfig;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.OssPostPolicyVO;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@@ -49,18 +40,24 @@ public class OssServiceImpl implements OssService {
}
try {
// 根据文件后缀获取Content-Type
String contentType = getContentTypeFromPath(storagePath);
// 生成Header签名(V1签名方式,HMAC-SHA1)
Map<String, String> headers = generateUploadHeaders(storagePath, contentType);
// 构建上传URL(不含签名参数)
String uploadUrl = buildObjectUrl(storagePath);
// 构建返回对象
// 浏览器 fetch 无法设置 Date;预签名 PUT 使用 OSS4(与 OssConfig 中 V4 一致)。
// OSS4 规范请求与 Content-Type 绑定:用 File 作 body 时浏览器会按 file.type 自动带
// Content-Type(如 text/csv),与签名不一致即 403。固定为 octet-stream 并要求前端
// 用 arrayBuffer + 显式该头上传。
final String contentType = "application/octet-stream";
Date expiration = new Date(System.currentTimeMillis() + expirationMinutes * 60 * 1000L);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
ossConfig.getBucketName(), storagePath, HttpMethod.PUT);
request.setExpiration(expiration);
request.setContentType(contentType);
URL signedUrl = ossClient.generatePresignedUrl(request);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", contentType);
OssPostPolicyVO policyVO = new OssPostPolicyVO();
policyVO.setUrl(uploadUrl);
policyVO.setUrl(signedUrl.toString());
policyVO.setKey(storagePath);
policyVO.setHeaders(headers);
@@ -70,175 +67,6 @@ public class OssServiceImpl implements OssService {
}
}
/**
* 生成上传所需的Header签名(V1签名方式,HMAC-SHA1)
* 参考官方文档:VERB + "\n" + CONTENT-MD5 + "\n" + CONTENT-TYPE + "\n" + DATE + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
* 如果使用x-oss-date,需要在CanonicalizedOSSHeaders中包含
*/
private Map<String, String> generateUploadHeaders(String storagePath, String contentType) {
String httpMethod = "PUT";
String date = getCurrentUTCDate(); // RFC 1123格式的UTC时间(GMT)
String canonicalizedResource = "/" + ossConfig.getBucketName() + "/" + storagePath;
// 构建CanonicalizedOSSHeaders,包含x-oss-date(值与Date保持一致)
// 格式:header-name:header-value\n(按字典序排序)
String canonicalizedOSSHeaders = "x-oss-date:" + date + "\n";
// 构建StringToSign:VERB + "\n" + CONTENT-MD5 + "\n" + CONTENT-TYPE + "\n" + DATE + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
String stringToSign = buildStringToSign(httpMethod, "", contentType != null ? contentType : "", date, canonicalizedOSSHeaders, canonicalizedResource);
// 计算HMAC-SHA1签名
String signature = calculateSignature(stringToSign, ossConfig.getAccessKeySecret());
String authorization = "OSS " + ossConfig.getAccessKeyId() + ":" + signature;
// 构建返回的headers Map
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", authorization);
headers.put("Date", date);
headers.put("x-oss-date", date); // x-oss-date值与Date保持一致
// 如果contentType为空,使用默认值
headers.put("Content-Type", contentType != null && !contentType.isEmpty() ? contentType : "application/octet-stream");
return headers;
}
/**
* 根据文件路径获取Content-Type
* 从文件路径中提取文件扩展名,然后返回对应的MIME类型
*/
private String getContentTypeFromPath(String storagePath) {
if (storagePath == null || storagePath.isEmpty()) {
return "application/octet-stream";
}
// 提取文件扩展名
int lastDotIndex = storagePath.lastIndexOf(".");
if (lastDotIndex < 0 || lastDotIndex >= storagePath.length() - 1) {
return "application/octet-stream";
}
String extension = storagePath.substring(lastDotIndex + 1).toLowerCase();
// 根据扩展名返回对应的Content-Type
return getContentTypeByExtension(extension);
}
/**
* 根据文件扩展名获取Content-Type
*/
private String getContentTypeByExtension(String extension) {
if (extension == null || extension.isEmpty()) {
return "application/octet-stream";
}
// 常见文件类型的MIME类型映射
return switch (extension) {
// 图片类型
case "jpg", "jpeg" -> "image/jpeg";
case "png" -> "image/png";
case "gif" -> "image/gif";
case "bmp" -> "image/bmp";
case "webp" -> "image/webp";
case "svg" -> "image/svg+xml";
case "ico" -> "image/x-icon";
// 文档类型
case "pdf" -> "application/pdf";
case "doc" -> "application/msword";
case "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "xls" -> "application/vnd.ms-excel";
case "xlsx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "ppt" -> "application/vnd.ms-powerpoint";
case "pptx" -> "application/vnd.openxmlformats-officedocument.presentationml.presentation";
// 文本类型
case "txt" -> "text/plain";
case "html", "htm" -> "text/html";
case "css" -> "text/css";
case "js" -> "application/javascript";
case "json" -> "application/json";
case "xml" -> "application/xml";
// 压缩文件
case "zip" -> "application/zip";
case "rar" -> "application/x-rar-compressed";
case "7z" -> "application/x-7z-compressed";
case "tar" -> "application/x-tar";
case "gz" -> "application/gzip";
// 视频类型
case "mp4" -> "video/mp4";
case "avi" -> "video/x-msvideo";
case "mov" -> "video/quicktime";
case "wmv" -> "video/x-ms-wmv";
case "flv" -> "video/x-flv";
case "webm" -> "video/webm";
// 音频类型
case "mp3" -> "audio/mpeg";
case "wav" -> "audio/wav";
case "ogg" -> "audio/ogg";
case "aac" -> "audio/aac";
case "flac" -> "audio/flac";
// 其他
default -> "application/octet-stream";
};
}
/**
* 构建对象访问URL(不含签名参数)
* 格式:https://bucket-name.endpoint/storagePath
*/
private String buildObjectUrl(String storagePath) {
String endpoint = ossConfig.getEndpoint();
// 移除协议前缀(如果有)
if (endpoint.startsWith("http://")) {
endpoint = endpoint.substring(7);
} else if (endpoint.startsWith("https://")) {
endpoint = endpoint.substring(8);
}
// 格式:https://bucket-name.endpoint/storagePath
return "https://" + ossConfig.getBucketName() + "." + endpoint + "/" + storagePath;
}
/**
* 获取当前UTC时间(RFC 1123格式)
*/
private String getCurrentUTCDate() {
return ZonedDateTime.now(ZoneOffset.UTC)
.format(DateTimeFormatter.RFC_1123_DATE_TIME);
}
/**
* 构建待签名字符串(严格按照官方公式)
* 公式:VERB + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
* 注意:CanonicalizedOSSHeaders 和 CanonicalizedResource 之间没有 "\n",直接连接
*/
private String buildStringToSign(String httpMethod, String contentMD5, String contentType,
String date, String canonicalizedOSSHeaders, String canonicalizedResource) {
// 严格按照官方公式构建:VERB + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
return httpMethod + "\n"
+ (contentMD5 != null ? contentMD5 : "") + "\n"
+ (contentType != null ? contentType : "") + "\n"
+ date + "\n"
+ canonicalizedOSSHeaders + canonicalizedResource;
}
/**
* 计算HMAC-SHA1签名
*/
private String calculateSignature(String stringToSign, String accessKeySecret) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(accessKeySecret.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
byte[] signature = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signature);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Error calculating signature", e);
}
}
@Override
public String generateAccessUrl(String storagePath, int expirationMinutes) {
if (ossClient == null) {
@@ -114,8 +114,8 @@ knife4j:
oss:
enabled: false
endpoint: ${OSS_ENDPOINT:https://oss-cn-guangzhou.aliyuncs.com}
access-key-id: ${OSS_ACCESS_KEY_ID:LTAI5t6QFVokh9o3Q3jvQjVc}
access-key-secret: ${OSS_ACCESS_KEY_SECRET:8FPEkc0aNETc3Oa7ErYZDTf8aIHpNb}
access-key-id: ${OSS_ACCESS_KEY_ID:LTAI5t8oyyor6wLrQasDUQA3}
access-key-secret: ${OSS_ACCESS_KEY_SECRET:U0d3BeKADTJUteSsT5gBtxzlbHoJFi}
bucket-name: ${OSS_BUCKET:xyquan}
domain: ${OSS_DOMAIN:https://xyquan.oss-cn-guangzhou.aliyuncs.com}
+2 -1
View File
@@ -51,6 +51,7 @@
"vue-waterfall-plugin-next": "^3.0.0"
},
"devDependencies": {
"@types/papaparse": "^5.3.14"
"@types/papaparse": "^5.3.14",
"@types/spark-md5": "^3.0.5"
}
}
@@ -39,6 +39,13 @@ export async function deleteOrderApi(id: number) {
return requestClient.delete(`/ec/order/delete/${id}`);
}
/**
* 批量删除订单
*/
export async function batchDeleteOrdersApi(data: OrderDTO.BatchDelete) {
return requestClient.post('/ec/order/batch-delete', data);
}
/**
* 获取订单详情
*/
@@ -98,4 +98,10 @@ export namespace OrderDTO {
/** 订单列表 */
orders: Create[];
}
/** 批量删除订单参数 */
export interface BatchDelete {
/** 订单ID列表 */
orderIds: number[];
}
}
@@ -65,18 +65,34 @@ async function uploadFileToOssWithHeaderSignature(
uploadUrl: string,
uploadHeaders: Record<string, string>,
): Promise<void> {
const headers: Record<string, string> = {
...uploadHeaders,
};
const headers: Record<string, string> = { ...uploadHeaders };
const contentType =
headers['Content-Type'] ?? headers['content-type'] ?? '';
// OSS4 预签名 PUT 与 Content-Type 严格一致;File 作 body 时浏览器会按 file.type 自动带头,易 403。
const body =
contentType !== '' ? await file.arrayBuffer() : file;
if (contentType !== '') {
headers['Content-Type'] = contentType;
delete headers['content-type'];
}
const response = await fetch(uploadUrl, {
method: 'PUT',
body: file,
body,
headers,
});
if (!response.ok) {
throw new Error(`上传失败: ${response.status} ${response.statusText}`);
let detail = '';
try {
detail = (await response.text()).slice(0, 300);
} catch {
/* ignore */
}
throw new Error(
`上传失败: ${response.status} ${response.statusText}${detail ? ` — ${detail}` : ''}`,
);
}
}
@@ -25,7 +25,11 @@ import {
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteOrderApi, getOrderPageApi } from '#/api/ecommerce/order';
import {
batchDeleteOrdersApi,
deleteOrderApi,
getOrderPageApi,
} from '#/api/ecommerce/order';
import { getAllOrderStatusListApi } from '#/api/ecommerce/order-status';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getShopPageApi } from '#/api/ecommerce/shop';
@@ -47,6 +51,9 @@ function goToProductDetail(productId: number) {
// 响应式数据
const loading = ref(false);
const batchDeleteLoading = ref(false);
/** vxe 勾选不触发 Vue 依赖,须用事件同步,勿用 computed 读 getCheckboxRecords */
const hasSelected = ref(false);
const orderFormModalRef = ref();
// 店铺分页数据
@@ -200,12 +207,21 @@ function handleProductPopupScroll(e: Event) {
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
checkboxConfig: {
highlight: true,
reserve: false,
},
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
type: 'checkbox' as const,
width: 48,
fixed: 'left' as const,
},
{
field: 'platformOrderNo',
title: '平台订单号',
@@ -500,6 +516,7 @@ const formOptions = computed(() => ({
// 刷新表格数据
function refreshTable() {
hasSelected.value = false;
if (gridApi) {
gridApi.reload();
}
@@ -541,6 +558,18 @@ const [Grid, gridApi] = useVbenVxeGrid({
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '订单管理',
gridEvents: {
checkboxChange() {
const vxeTable = (gridApi as any).grid;
const rows = vxeTable?.getCheckboxRecords?.() ?? [];
hasSelected.value = rows.length > 0;
},
checkboxAll() {
const vxeTable = (gridApi as any).grid;
const rows = vxeTable?.getCheckboxRecords?.() ?? [];
hasSelected.value = rows.length > 0;
},
},
});
gridReloadRef.value = () => gridApi.reload();
@@ -566,6 +595,35 @@ async function handleDelete(record: OrderVO.Info) {
}
}
async function handleBatchDelete() {
const vxeTable = (gridApi as any).grid;
const selectedRows: OrderVO.Info[] = vxeTable?.getCheckboxRecords?.() ?? [];
if (!selectedRows.length) {
message.warning('请选择要删除的订单');
return;
}
const orderIds = selectedRows.map((r) => r.id).filter((id) => id != null);
if (!orderIds.length) {
message.warning('所选行缺少订单ID');
return;
}
batchDeleteLoading.value = true;
try {
await batchDeleteOrdersApi({ orderIds });
message.success(`已删除 ${orderIds.length} 条订单`);
vxeTable?.clearCheckboxRow?.();
hasSelected.value = false;
await gridApi.reload();
} catch (error: any) {
console.error('批量删除订单失败:', error);
const msg =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(msg);
} finally {
batchDeleteLoading.value = false;
}
}
// 处理模态框成功
function handleModalSuccess() {
refreshTable();
@@ -588,6 +646,18 @@ onMounted(async () => {
<PlusIcon />
添加订单
</Button>
<Popconfirm
title="确定删除选中的订单吗?删除后不可恢复。"
ok-text="确定删除"
cancel-text="取消"
:ok-button-props="{ danger: true, loading: batchDeleteLoading }"
:disabled="!hasSelected"
@confirm="handleBatchDelete"
>
<Button danger :disabled="!hasSelected" :loading="batchDeleteLoading">
批量删除
</Button>
</Popconfirm>
</Space>
</template>
+8
View File
@@ -678,6 +678,9 @@ importers:
'@types/papaparse':
specifier: ^5.3.14
version: 5.3.16
'@types/spark-md5':
specifier: ^3.0.5
version: 3.0.5
internal/lint-configs/commitlint-config:
dependencies:
@@ -4051,6 +4054,9 @@ packages:
'@types/sortablejs@1.15.8':
resolution: {integrity: sha512-b79830lW+RZfwaztgs1aVPgbasJ8e7AXtZYHTELNXZPsERt4ymJdjV4OccDbHQAvHrCcFpbF78jkm0R6h/pZVg==}
'@types/spark-md5@3.0.5':
resolution: {integrity: sha512-lWf05dnD42DLVKQJZrDHtWFidcLrHuip01CtnC2/S6AMhX4t9ZlEUj4iuRlAnts0PQk7KESOqKxeGE/b6sIPGg==}
'@types/triple-beam@1.3.5':
resolution: {integrity: sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==}
@@ -13003,6 +13009,8 @@ snapshots:
'@types/sortablejs@1.15.8': {}
'@types/spark-md5@3.0.5': {}
'@types/triple-beam@1.3.5': {}
'@types/trusted-types@2.0.7': {}