mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 02:39:19 +08:00
1
This commit is contained in:
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.importtask;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 订单导入映射配置(CSV 表头与订单字段、状态与状态ID 的映射)
|
||||
*/
|
||||
@Data
|
||||
public class OrderImportMappingConfig {
|
||||
|
||||
/**
|
||||
* 字段映射:CSV 表头 -> 订单字段
|
||||
*/
|
||||
@JsonProperty("fieldMapping")
|
||||
private List<FieldMappingItem> fieldMapping;
|
||||
|
||||
/**
|
||||
* 状态映射:CSV 状态文案 -> 订单状态ID
|
||||
*/
|
||||
@JsonProperty("statusMapping")
|
||||
private List<StatusMappingItem> statusMapping;
|
||||
|
||||
@Data
|
||||
public static class FieldMappingItem {
|
||||
private Boolean required;
|
||||
/** 订单/实体字段名,如 spec_code, link_product_name */
|
||||
private String fieldName;
|
||||
private String fieldLabel;
|
||||
/** CSV 表头名称,如 商品、订单号 */
|
||||
private String fileFieldName;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class StatusMappingItem {
|
||||
/** CSV 中的状态文案,如 已发货,待收货 */
|
||||
private String csvStatus;
|
||||
/** 系统订单状态ID */
|
||||
private Long mappedStatusId;
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.importtask;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单导入单行数据(由 CSV 解析后按 fieldMapping 得到)
|
||||
*/
|
||||
@Data
|
||||
public class OrderImportRow {
|
||||
|
||||
/** 行号(从 1 开始,含表头则为数据行号) */
|
||||
private int rowIndex;
|
||||
|
||||
/** 字段名 -> 原始字符串值 */
|
||||
private Map<String, String> values;
|
||||
|
||||
public OrderImportRow(int rowIndex, Map<String, String> values) {
|
||||
this.rowIndex = rowIndex;
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
public String get(String fieldName) {
|
||||
return values == null ? null : values.get(fieldName);
|
||||
}
|
||||
|
||||
public String getSpecCode() {
|
||||
return get("spec_code");
|
||||
}
|
||||
|
||||
public String getLinkProductName() {
|
||||
return get("link_product_name");
|
||||
}
|
||||
|
||||
public String getProductCode() {
|
||||
return get("product_code");
|
||||
}
|
||||
|
||||
public String getPlatformOrderNo() {
|
||||
return get("platform_order_no");
|
||||
}
|
||||
|
||||
public String getLinkSpecName() {
|
||||
return get("link_spec_name");
|
||||
}
|
||||
|
||||
public String getStatusText() {
|
||||
return get("status");
|
||||
}
|
||||
|
||||
/** 根据 statusMapping 将 CSV 状态文案解析为订单状态ID */
|
||||
public Long getMappedStatusId(List<OrderImportMappingConfig.StatusMappingItem> statusMapping) {
|
||||
String text = getStatusText();
|
||||
if (text == null || text.isBlank() || statusMapping == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = text.trim();
|
||||
for (OrderImportMappingConfig.StatusMappingItem item : statusMapping) {
|
||||
if (trimmed.equals(item.getCsvStatus() != null ? item.getCsvStatus().trim() : null)) {
|
||||
return item.getMappedStatusId();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Integer getProductQuantity() {
|
||||
String v = get("product_quantity");
|
||||
if (v == null || v.isBlank()) return null;
|
||||
try {
|
||||
return Integer.parseInt(v.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public BigDecimal getReceivedAmount() {
|
||||
String v = get("received_amount");
|
||||
if (v == null || v.isBlank()) return null;
|
||||
try {
|
||||
return new BigDecimal(v.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 下单时间,支持常见格式 */
|
||||
public LocalDateTime getOrderTime() {
|
||||
String v = get("order_time");
|
||||
if (v == null || v.isBlank()) return null;
|
||||
v = v.trim();
|
||||
DateTimeFormatter[] formatters = new DateTimeFormatter[]{
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"),
|
||||
DateTimeFormatter.ISO_LOCAL_DATE_TIME
|
||||
};
|
||||
for (DateTimeFormatter f : formatters) {
|
||||
try {
|
||||
return LocalDateTime.parse(v, f);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(v, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -15,6 +15,12 @@ import java.util.List;
|
||||
@Schema(description = "单店铺概览统计VO")
|
||||
public class ShopOverviewStatisticsVO {
|
||||
|
||||
/**
|
||||
* 店铺名称
|
||||
*/
|
||||
@Schema(description = "店铺名称", example = "淘宝旗舰店")
|
||||
private String shopName;
|
||||
|
||||
/**
|
||||
* 店铺总销售额
|
||||
*/
|
||||
|
||||
+10
@@ -63,4 +63,14 @@ public interface OrderService extends IService<OrderPO> {
|
||||
* @return 批量导入结果VO
|
||||
*/
|
||||
BatchImportResultVO batchImportOrders(BatchImportOrderDTO batchImportOrderDTO);
|
||||
|
||||
/**
|
||||
* 导入场景下创建订单(不依赖当前请求用户上下文)
|
||||
*
|
||||
* @param createOrderDTO 创建订单DTO
|
||||
* @param companyId 公司ID
|
||||
* @param userId 操作人ID
|
||||
* @return 订单VO
|
||||
*/
|
||||
OrderVO createOrderForImport(CreateOrderDTO createOrderDTO, Long companyId, Long userId);
|
||||
}
|
||||
|
||||
+16
@@ -7,6 +7,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.product.CreateProductDTO
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.product.ProductFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.product.UpdateProductDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductPO;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductVO;
|
||||
|
||||
/**
|
||||
@@ -45,4 +46,19 @@ public interface ProductService extends IService<ProductPO> {
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<ProductVO> getProductPage(PageQueryDTO<ProductFilterDTO> pageQueryDTO);
|
||||
|
||||
/**
|
||||
* 按公司ID和商品编码查询商品(导入用)
|
||||
*/
|
||||
ProductPO getByCompanyIdAndProductCode(Long companyId, String productCode);
|
||||
|
||||
/**
|
||||
* 按公司ID和商品名称查询商品(导入用)
|
||||
*/
|
||||
ProductPO getByCompanyIdAndName(Long companyId, String name);
|
||||
|
||||
/**
|
||||
* 导入场景下创建商品(不依赖当前请求用户上下文)
|
||||
*/
|
||||
ProductVO createProductForImport(CreateProductDTO createProductDTO, Long companyId, Long userId);
|
||||
}
|
||||
|
||||
+15
@@ -66,6 +66,21 @@ public interface ProductSpecService extends IService<ProductSpecPO> {
|
||||
*/
|
||||
List<ProductVO> getProductSpecsByProductAndSpecs(List<ProductSpecQueryDTO> queries);
|
||||
|
||||
/**
|
||||
* 按公司ID和规格编码查询规格(导入用,同公司下取第一个匹配)
|
||||
*/
|
||||
ProductSpecPO getByCompanyIdAndSpecCode(Long companyId, String specCode);
|
||||
|
||||
/**
|
||||
* 按公司ID、商品名称、规格编码查询规格(导入用)
|
||||
*/
|
||||
ProductSpecPO getByCompanyIdAndProductNameAndSpecCode(Long companyId, String productName, String specCode);
|
||||
|
||||
/**
|
||||
* 导入场景下创建商品规格(不依赖当前请求用户上下文)
|
||||
*/
|
||||
ProductSpecVO createProductSpecForImport(CreateProductSpecDTO createProductSpecDTO, Long companyId, Long userId);
|
||||
|
||||
/**
|
||||
* 商品规格查询DTO
|
||||
*/
|
||||
|
||||
+12
-2
@@ -6,7 +6,6 @@ import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ShopProductRelationMapper;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
@@ -187,7 +186,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
// 不使用事务:商品/规格创建均立即提交,避免事务回滚导致“商品不存在”等查询问题
|
||||
public void processImportTask(Long taskId) {
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
@@ -967,6 +966,17 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
product.setCreateBy(createBy);
|
||||
productMapper.insert(product);
|
||||
productId = product.getId();
|
||||
|
||||
// 验证商品确实创建成功
|
||||
if (productId == null) {
|
||||
throw new BusinessException("商品创建失败,未返回商品ID");
|
||||
}
|
||||
|
||||
// 验证商品确实存在(刷新实体,确保数据已提交)
|
||||
ProductPO verifyProduct = productMapper.selectById(productId);
|
||||
if (verifyProduct == null) {
|
||||
throw new BusinessException("商品创建后验证失败,商品ID: " + productId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
productId = product.getId();
|
||||
|
||||
+54
@@ -134,6 +134,60 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
return convertToVO(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderVO createOrderForImport(CreateOrderDTO createOrderDTO, Long companyId, Long userId) {
|
||||
ShopPO shop = shopService.getById(createOrderDTO.getShopId());
|
||||
if (shop == null || !shop.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
ProductPO product = productService.getById(createOrderDTO.getProductId());
|
||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
if (createOrderDTO.getProductSpecId() != null) {
|
||||
ProductSpecPO productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
|
||||
if (productSpec == null || !productSpec.getCompanyId().equals(companyId)
|
||||
|| !productSpec.getProductId().equals(createOrderDTO.getProductId())) {
|
||||
throw new BusinessException("商品规格不存在或不属于该商品");
|
||||
}
|
||||
}
|
||||
OrderStatusPO orderStatus = orderStatusService.getById(createOrderDTO.getStatusId());
|
||||
if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("订单状态不存在");
|
||||
}
|
||||
if (createOrderDTO.getPlatformOrderNo() != null && !createOrderDTO.getPlatformOrderNo().trim().isEmpty()) {
|
||||
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(OrderPO::getPlatformOrderNo, createOrderDTO.getPlatformOrderNo())
|
||||
.eq(OrderPO::getCompanyId, companyId);
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("平台订单号已存在");
|
||||
}
|
||||
}
|
||||
OrderPO order = new OrderPO();
|
||||
order.setCompanyId(companyId);
|
||||
order.setShopId(createOrderDTO.getShopId());
|
||||
order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo());
|
||||
order.setStatusId(createOrderDTO.getStatusId());
|
||||
order.setProductId(createOrderDTO.getProductId());
|
||||
order.setProductSpecId(createOrderDTO.getProductSpecId());
|
||||
order.setLinkProductName(createOrderDTO.getLinkProductName());
|
||||
order.setLinkSpecName(createOrderDTO.getLinkSpecName());
|
||||
order.setQuantity(createOrderDTO.getQuantity());
|
||||
order.setUnitPrice(createOrderDTO.getUnitPrice());
|
||||
order.setProductCost(createOrderDTO.getProductCost());
|
||||
order.setShippingCost(createOrderDTO.getShippingCost());
|
||||
order.setOtherCost(createOrderDTO.getOtherCost());
|
||||
order.setRemark(createOrderDTO.getRemark());
|
||||
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
|
||||
order.setOrderTime(createOrderDTO.getOrderTime());
|
||||
order.setCreateBy(userId);
|
||||
order.setImportTaskId(createOrderDTO.getImportTaskId());
|
||||
order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1);
|
||||
this.save(order);
|
||||
return convertToVO(order);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新订单
|
||||
* @param updateOrderDTO 更新订单DTO
|
||||
|
||||
+54
@@ -114,6 +114,60 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
return convertToVO(product);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductPO getByCompanyIdAndProductCode(Long companyId, String productCode) {
|
||||
if (companyId == null || productCode == null || productCode.isBlank()) return null;
|
||||
LambdaQueryWrapper<ProductPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductPO::getCompanyId, companyId).eq(ProductPO::getProductCode, productCode.trim());
|
||||
return this.getOne(w);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductPO getByCompanyIdAndName(Long companyId, String name) {
|
||||
if (companyId == null || name == null || name.isBlank()) return null;
|
||||
LambdaQueryWrapper<ProductPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductPO::getCompanyId, companyId).eq(ProductPO::getName, name.trim());
|
||||
return this.getOne(w);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ProductVO createProductForImport(CreateProductDTO createProductDTO, Long companyId, Long userId) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getName, createProductDTO.getName()).eq(ProductPO::getCompanyId, companyId);
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("商品名称已存在");
|
||||
}
|
||||
if (createProductDTO.getProductCode() != null && !createProductDTO.getProductCode().trim().isEmpty()) {
|
||||
LambdaQueryWrapper<ProductPO> codeWrapper = new LambdaQueryWrapper<>();
|
||||
codeWrapper.eq(ProductPO::getProductCode, createProductDTO.getProductCode().trim());
|
||||
if (this.count(codeWrapper) > 0) {
|
||||
throw new BusinessException("商品编码已存在");
|
||||
}
|
||||
}
|
||||
ProductPO product = new ProductPO();
|
||||
BeanUtils.copyProperties(createProductDTO, product);
|
||||
product.setCompanyId(companyId);
|
||||
product.setCreateBy(userId);
|
||||
this.save(product);
|
||||
if (createProductDTO.getSpecs() != null && !createProductDTO.getSpecs().isEmpty()) {
|
||||
for (CreateProductDTO.ProductSpecDTO specDTO : createProductDTO.getSpecs()) {
|
||||
ProductSpecPO spec = new ProductSpecPO();
|
||||
spec.setCompanyId(companyId);
|
||||
spec.setProductId(product.getId());
|
||||
spec.setName(specDTO.getName());
|
||||
spec.setSpecCode(specDTO.getSpecCode());
|
||||
spec.setProductCost(specDTO.getProductCost() != null ? specDTO.getProductCost() : java.math.BigDecimal.ZERO);
|
||||
spec.setShippingCost(specDTO.getShippingCost());
|
||||
spec.setOtherCost(specDTO.getOtherCost());
|
||||
spec.setRemark(specDTO.getRemark());
|
||||
spec.setCreateBy(userId);
|
||||
productSpecService.save(spec);
|
||||
}
|
||||
}
|
||||
return convertToVO(product);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新商品
|
||||
* @param updateProductDTO 更新商品DTO
|
||||
|
||||
+44
@@ -226,6 +226,50 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
|
||||
return convertToVO(productSpec);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductSpecPO getByCompanyIdAndSpecCode(Long companyId, String specCode) {
|
||||
if (companyId == null || specCode == null || specCode.isBlank()) return null;
|
||||
LambdaQueryWrapper<ProductSpecPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductSpecPO::getCompanyId, companyId).eq(ProductSpecPO::getSpecCode, specCode.trim()).last("LIMIT 1");
|
||||
return this.getOne(w);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductSpecPO getByCompanyIdAndProductNameAndSpecCode(Long companyId, String productName, String specCode) {
|
||||
if (companyId == null || productName == null || productName.isBlank() || specCode == null || specCode.isBlank()) return null;
|
||||
LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>();
|
||||
productWrapper.eq(ProductPO::getName, productName.trim()).eq(ProductPO::getCompanyId, companyId);
|
||||
ProductPO product = productService.getOne(productWrapper);
|
||||
if (product == null) return null;
|
||||
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
|
||||
specWrapper.eq(ProductSpecPO::getProductId, product.getId())
|
||||
.eq(ProductSpecPO::getSpecCode, specCode.trim())
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
return this.getOne(specWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ProductSpecVO createProductSpecForImport(CreateProductSpecDTO createProductSpecDTO, Long companyId, Long userId) {
|
||||
ProductPO product = productService.getById(createProductSpecDTO.getProductId());
|
||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSpecPO::getProductId, createProductSpecDTO.getProductId())
|
||||
.eq(ProductSpecPO::getName, createProductSpecDTO.getName())
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("规格名称已存在");
|
||||
}
|
||||
ProductSpecPO productSpec = new ProductSpecPO();
|
||||
BeanUtils.copyProperties(createProductSpecDTO, productSpec);
|
||||
productSpec.setCompanyId(companyId);
|
||||
productSpec.setCreateBy(userId);
|
||||
this.save(productSpec);
|
||||
return convertToVO(productSpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据商品名称和规格编码列表查询商品规格
|
||||
* @param queries 商品规格查询DTO列表
|
||||
|
||||
+2
-2
@@ -244,8 +244,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
*/
|
||||
@Override
|
||||
public SysFileUploadVO uploadLogo(MultipartFile file) {
|
||||
// 上传Logo到系统文件模块(支持哈希校验和跨公司共享)
|
||||
List<SysFileUploadVO> files = sysFileService.batchUploadFiles(Collections.singletonList(file));
|
||||
// 上传Logo到系统文件模块(支持哈希校验和跨公司共享),设置文件分类为logo
|
||||
List<SysFileUploadVO> files = sysFileService.batchUploadFiles(Collections.singletonList(file), "logo");
|
||||
if (files.isEmpty()) {
|
||||
throw new BusinessException("Logo上传失败");
|
||||
}
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.util;
|
||||
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.importtask.OrderImportMappingConfig;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.importtask.OrderImportRow;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单导入 CSV 解析工具:按字段映射与状态映射解析 CSV,得到订单行数据列表。
|
||||
*/
|
||||
public final class OrderImportCsvParser {
|
||||
|
||||
private static final String BOM = "\uFEFF";
|
||||
|
||||
private OrderImportCsvParser() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件路径解析订单导入 CSV
|
||||
*
|
||||
* @param filePath 文件路径(可为相对 user.dir 或绝对路径)
|
||||
* @param config 字段映射与状态映射配置
|
||||
* @return 解析后的订单行列表(不含表头)
|
||||
* @throws IOException 读取或解析失败
|
||||
*/
|
||||
public static List<OrderImportRow> parse(Path filePath, OrderImportMappingConfig config) throws IOException {
|
||||
try (InputStream in = Files.newInputStream(filePath)) {
|
||||
return parse(in, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从输入流解析订单导入 CSV(UTF-8)
|
||||
*
|
||||
* @param inputStream 输入流
|
||||
* @param config 字段映射与状态映射配置
|
||||
* @return 解析后的订单行列表(不含表头)
|
||||
* @throws IOException 读取或解析失败
|
||||
*/
|
||||
public static List<OrderImportRow> parse(InputStream inputStream, OrderImportMappingConfig config) throws IOException {
|
||||
if (config == null || config.getFieldMapping() == null || config.getFieldMapping().isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<OrderImportMappingConfig.FieldMappingItem> fieldMapping = config.getFieldMapping();
|
||||
// CSV 表头名 -> 实体字段名
|
||||
Map<String, String> fileHeaderToField = new HashMap<>();
|
||||
for (OrderImportMappingConfig.FieldMappingItem item : fieldMapping) {
|
||||
if (item.getFileFieldName() != null && item.getFieldName() != null) {
|
||||
fileHeaderToField.put(item.getFileFieldName().trim(), item.getFieldName());
|
||||
}
|
||||
}
|
||||
|
||||
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
CSVFormat format = CSVFormat.DEFAULT.builder()
|
||||
.setHeader()
|
||||
.setSkipHeaderRecord(true)
|
||||
.setTrim(true)
|
||||
.setIgnoreEmptyLines(true)
|
||||
.build();
|
||||
|
||||
List<OrderImportRow> rows = new ArrayList<>();
|
||||
try (CSVParser parser = CSVParser.parse(reader, format)) {
|
||||
List<String> headerNames = parser.getHeaderNames();
|
||||
if (headerNames == null) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
int rowIndex = 1;
|
||||
for (CSVRecord record : parser) {
|
||||
rowIndex++;
|
||||
Map<String, String> values = new HashMap<>();
|
||||
for (String fileHeader : headerNames) {
|
||||
if (fileHeader == null) continue;
|
||||
String normalizedHeader = fileHeader.startsWith(BOM) ? fileHeader.substring(BOM.length()).trim() : fileHeader.trim();
|
||||
String fieldName = fileHeaderToField.get(normalizedHeader);
|
||||
if (fieldName != null) {
|
||||
String value = record.get(fileHeader);
|
||||
if (value != null) {
|
||||
value = value.trim();
|
||||
}
|
||||
values.put(fieldName, value);
|
||||
}
|
||||
}
|
||||
rows.add(new OrderImportRow(rowIndex, values));
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
+56
-1
@@ -2,6 +2,9 @@ package top.xyquan.ecomdmbbackend.modules.sys.config;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.ClientBuilderConfiguration;
|
||||
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
|
||||
import com.aliyun.oss.common.comm.SignVersion;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -34,7 +37,29 @@ public class OssConfig {
|
||||
accessKeySecret == null || accessKeySecret.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
|
||||
String region = getRegion();
|
||||
|
||||
// 如果无法提取region,使用默认方式创建(V1签名)
|
||||
if (region == null || region.isEmpty()) {
|
||||
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
}
|
||||
|
||||
// 使用V4签名版本创建OSSClient(参考官方示例)
|
||||
// V4签名对时区容错性更好,推荐用于预签名URL
|
||||
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
|
||||
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
|
||||
|
||||
// 创建CredentialsProvider(参考官方示例)
|
||||
DefaultCredentialProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
|
||||
|
||||
// 按照官方示例的方式创建OSSClient
|
||||
return OSSClientBuilder.create()
|
||||
.endpoint(endpoint)
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.clientConfiguration(clientBuilderConfiguration)
|
||||
.region(region)
|
||||
.build();
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
@@ -48,5 +73,35 @@ public class OssConfig {
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() {
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
public String getAccessKeySecret() {
|
||||
return accessKeySecret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从endpoint提取region
|
||||
* 例如:oss-cn-hangzhou.aliyuncs.com -> cn-hangzhou
|
||||
* oss-cn-guangzhou.aliyuncs.com -> cn-guangzhou
|
||||
*/
|
||||
public String getRegion() {
|
||||
if (endpoint == null || endpoint.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String endpointWithoutProtocol = endpoint.replace("https://", "").replace("http://", "");
|
||||
// 格式:oss-cn-{region}.aliyuncs.com
|
||||
if (endpointWithoutProtocol.startsWith("oss-cn-")) {
|
||||
int start = "oss-cn-".length();
|
||||
int end = endpointWithoutProtocol.indexOf(".aliyuncs.com");
|
||||
if (end > start) {
|
||||
return "cn-" + endpointWithoutProtocol.substring(start, end);
|
||||
}
|
||||
}
|
||||
// 如果格式不匹配,尝试其他格式
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-1
@@ -5,9 +5,12 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
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.sys.model.dto.file.BatchCreateOssFileDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.SysFileFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.BatchSignUrlVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileVO;
|
||||
@@ -36,7 +39,7 @@ public class SysFileController {
|
||||
return ApiResponse.success(result);
|
||||
}
|
||||
|
||||
@Operation(summary = "批量获取URL签名", description = "批量获取OSS文件上传URL签名,如果文件已存在则返回文件信息")
|
||||
@Operation(summary = "批量获取Header签名", description = "批量获取OSS文件上传Header签名(V1签名方式,HMAC-SHA1),如果文件已存在则返回文件信息")
|
||||
@PostMapping("/batch-sign-url")
|
||||
public ApiResponse<BatchSignUrlVO> batchSignUrl(@Valid @RequestBody BatchSignUrlDTO dto) {
|
||||
BatchSignUrlVO result = sysFileService.batchSignUrl(dto);
|
||||
@@ -56,5 +59,12 @@ public class SysFileController {
|
||||
String accessUrl = sysFileService.getFileAccessUrl(fileId);
|
||||
return ApiResponse.success(accessUrl);
|
||||
}
|
||||
|
||||
@Operation(summary = "分页获取文件列表", description = "分页获取当前公司的文件列表,支持条件过滤")
|
||||
@PostMapping("/page")
|
||||
public ApiResponse<PageResultVO<SysFileVO>> getFilePage(@Valid @RequestBody PageQueryDTO<SysFileFilterDTO> pageQueryDTO) {
|
||||
PageResultVO<SysFileVO> result = sysFileService.getFilePage(pageQueryDTO);
|
||||
return ApiResponse.success(result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.file;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 系统文件分页查询过滤DTO
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "系统文件分页查询过滤DTO")
|
||||
public class SysFileFilterDTO {
|
||||
|
||||
/**
|
||||
* 文件名(模糊查询)
|
||||
*/
|
||||
@Schema(description = "文件名(模糊查询)", example = "logo")
|
||||
private String filename;
|
||||
|
||||
/**
|
||||
* 文件格式(精准查询)
|
||||
*/
|
||||
@Schema(description = "文件格式(精准查询)", example = "jpg")
|
||||
private String fileFormat;
|
||||
|
||||
/**
|
||||
* 存储类型(精准查询)
|
||||
*/
|
||||
@Schema(description = "存储类型(精准查询)", example = "oss", allowableValues = {"local", "oss", "s3", "qiniu", "cos"})
|
||||
private String storageType;
|
||||
|
||||
/**
|
||||
* 文件分类(精准查询)
|
||||
*/
|
||||
@Schema(description = "文件分类(精准查询)", example = "image")
|
||||
private String category;
|
||||
|
||||
/**
|
||||
* 标签(模糊查询)
|
||||
*/
|
||||
@Schema(description = "标签(模糊查询)", example = "logo")
|
||||
private String tags;
|
||||
|
||||
/**
|
||||
* 上传时间范围-开始时间
|
||||
*/
|
||||
@Schema(description = "上传时间范围-开始时间", example = "2024-01-01T00:00:00")
|
||||
private LocalDateTime startUploadTime;
|
||||
|
||||
/**
|
||||
* 上传时间范围-结束时间
|
||||
*/
|
||||
@Schema(description = "上传时间范围-结束时间", example = "2024-12-31T23:59:59")
|
||||
private LocalDateTime endUploadTime;
|
||||
}
|
||||
|
||||
+10
-3
@@ -4,12 +4,13 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 批量URL签名响应VO
|
||||
* 批量Header签名响应VO(Header签名)
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "批量URL签名响应VO")
|
||||
@Schema(description = "批量Header签名响应VO(Header签名)")
|
||||
public class BatchSignUrlVO {
|
||||
|
||||
@Schema(description = "文件信息列表")
|
||||
@@ -33,9 +34,15 @@ public class BatchSignUrlVO {
|
||||
@Schema(description = "是否已存在", example = "true")
|
||||
private Boolean exists;
|
||||
|
||||
@Schema(description = "上传URL(如果文件不存在,用于前端上传)", example = "https://oss.example.com/upload?signature=xxx")
|
||||
@Schema(description = "上传URL(如果文件不存在,不含签名参数)", example = "https://bucket.oss-cn-hangzhou.aliyuncs.com/uploads/2024/01/file.jpg")
|
||||
private String uploadUrl;
|
||||
|
||||
@Schema(description = "上传所需的Header签名信息(如果文件不存在,包含Authorization、Date、x-oss-date、Content-Type等)", example = "{\"Authorization\":\"OSS xxx:xxx\",\"Date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"x-oss-date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"Content-Type\":\"image/jpeg\"}")
|
||||
private Map<String, String> uploadHeaders;
|
||||
|
||||
@Schema(description = "存储路径/Key(如果文件不存在,用于前端创建文件记录时使用)", example = "uploads/2024/01/abc123def456.jpg")
|
||||
private String storagePath;
|
||||
|
||||
@Schema(description = "访问URL(如果文件已存在,临时签名URL)", example = "https://oss.example.com/file.jpg?signature=xxx")
|
||||
private String accessUrl;
|
||||
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OSS Header签名信息VO(V1签名方式)
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "OSS Header签名信息VO(V1签名方式)")
|
||||
public class OssPostPolicyVO {
|
||||
|
||||
@Schema(description = "OSS上传URL(不含签名参数,前端需要使用Header签名上传)", example = "https://your-bucket.oss-cn-hangzhou.aliyuncs.com/uploads/2024/01/file.jpg")
|
||||
private String url;
|
||||
|
||||
@Schema(description = "存储路径/Key", example = "uploads/2024/01/file.jpg")
|
||||
private String key;
|
||||
|
||||
@Schema(description = "上传所需的Header签名信息(包含Authorization、Date、x-oss-date、Content-Type等)", example = "{\"Authorization\":\"OSS xxx:xxx\",\"Date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"x-oss-date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"Content-Type\":\"image/jpeg\"}")
|
||||
private Map<String, String> headers;
|
||||
}
|
||||
|
||||
+6
-4
@@ -1,5 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.OssPostPolicyVO;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
@@ -8,13 +10,13 @@ import java.io.InputStream;
|
||||
public interface OssService {
|
||||
|
||||
/**
|
||||
* 生成上传URL(预签名URL)
|
||||
* 生成上传Header签名(V1签名方式,HMAC-SHA1)
|
||||
*
|
||||
* @param storagePath 存储路径/Key
|
||||
* @param expirationMinutes 过期时间(分钟)
|
||||
* @return 预签名URL
|
||||
* @param expirationMinutes 过期时间(分钟,当前Header签名不使用此参数,保留用于兼容)
|
||||
* @return Header签名信息(包含上传URL和签名headers)
|
||||
*/
|
||||
String generateUploadUrl(String storagePath, int expirationMinutes);
|
||||
OssPostPolicyVO generateUploadPolicy(String storagePath, int expirationMinutes);
|
||||
|
||||
/**
|
||||
* 生成访问URL(预签名URL)
|
||||
|
||||
+20
@@ -1,8 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchCreateOssFileDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.SysFileFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.BatchSignUrlVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileVO;
|
||||
@@ -22,6 +25,15 @@ public interface SysFileService {
|
||||
*/
|
||||
List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files);
|
||||
|
||||
/**
|
||||
* 批量上传文件(仅用于本地存储),支持设置文件分类
|
||||
*
|
||||
* @param files 文件列表
|
||||
* @param category 文件分类
|
||||
* @return 文件信息列表(不包含敏感信息)
|
||||
*/
|
||||
List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files, String category);
|
||||
|
||||
/**
|
||||
* 批量获取URL签名(用于前端上传到OSS)
|
||||
*
|
||||
@@ -45,5 +57,13 @@ public interface SysFileService {
|
||||
* @return 文件访问URL
|
||||
*/
|
||||
String getFileAccessUrl(Long fileId);
|
||||
|
||||
/**
|
||||
* 分页获取当前公司的文件列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<SysFileVO> getFilePage(PageQueryDTO<SysFileFilterDTO> pageQueryDTO);
|
||||
}
|
||||
|
||||
|
||||
+213
-11
@@ -1,14 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.HttpMethod;
|
||||
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.config.OssConfig;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.OssPostPolicyVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.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;
|
||||
|
||||
/**
|
||||
* OSS服务实现类
|
||||
@@ -25,34 +38,223 @@ public class OssServiceImpl implements OssService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateUploadUrl(String storagePath, int expirationMinutes) {
|
||||
public OssPostPolicyVO generateUploadPolicy(String storagePath, int expirationMinutes) {
|
||||
if (ossClient == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ossConfig.getBucketName() == null || ossConfig.getBucketName().isEmpty() ||
|
||||
storagePath == null || storagePath.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Date expiration = new Date(System.currentTimeMillis() + expirationMinutes * 60 * 1000L);
|
||||
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
|
||||
ossConfig.getBucketName(), storagePath);
|
||||
request.setExpiration(expiration);
|
||||
request.setMethod(com.aliyun.oss.HttpMethod.PUT);
|
||||
URL url = ossClient.generatePresignedUrl(request);
|
||||
return url.toString();
|
||||
// 根据文件后缀获取Content-Type
|
||||
String contentType = getContentTypeFromPath(storagePath);
|
||||
|
||||
// 生成Header签名(V1签名方式,HMAC-SHA1)
|
||||
Map<String, String> headers = generateUploadHeaders(storagePath, contentType);
|
||||
|
||||
// 构建上传URL(不含签名参数)
|
||||
String uploadUrl = buildObjectUrl(storagePath);
|
||||
|
||||
// 构建返回对象
|
||||
OssPostPolicyVO policyVO = new OssPostPolicyVO();
|
||||
policyVO.setUrl(uploadUrl);
|
||||
policyVO.setKey(storagePath);
|
||||
policyVO.setHeaders(headers);
|
||||
|
||||
return policyVO;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成上传所需的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) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Date expiration = new Date(System.currentTimeMillis() + expirationMinutes * 60 * 1000L);
|
||||
// 设置过期时间(参考官方示例:new Date(new Date().getTime() + 3600 * 1000L))
|
||||
Date expiration = new Date(new Date().getTime() + expirationMinutes * 60 * 1000L);
|
||||
|
||||
// 生成预签名URL(GET方法,用于下载,参考官方示例)
|
||||
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
|
||||
ossConfig.getBucketName(), storagePath);
|
||||
ossConfig.getBucketName(), storagePath, HttpMethod.GET);
|
||||
// 设置过期时间
|
||||
request.setExpiration(expiration);
|
||||
request.setMethod(com.aliyun.oss.HttpMethod.GET);
|
||||
|
||||
// 通过HTTP GET请求生成预签名URL
|
||||
URL url = ossClient.generatePresignedUrl(request);
|
||||
return url.toString();
|
||||
} catch (Exception e) {
|
||||
|
||||
+201
-6
@@ -1,17 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.mapper.SysFileMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchCreateOssFileDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.SysFileFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.SysFilePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.BatchSignUrlVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.OssPostPolicyVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.OssService;
|
||||
@@ -24,6 +30,7 @@ import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 系统文件服务实现类
|
||||
@@ -129,6 +136,129 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有找到有效的其他公司文件,或者文件不存在,则作为新文件处理
|
||||
if (storagePath == null) {
|
||||
// 没有任何公司有相同文件,生成新的存储路径并上传(仅本地存储)
|
||||
String relativePath = generateStoragePath(file.getOriginalFilename(), fileHash);
|
||||
storagePath = "./" + relativePath;
|
||||
saveFileToLocal(storagePath, file);
|
||||
|
||||
// 创建新记录
|
||||
SysFilePO sysFile = new SysFilePO();
|
||||
sysFile.setCompanyId(companyId);
|
||||
sysFile.setStorageType(storageType);
|
||||
sysFile.setStoragePath(storagePath);
|
||||
sysFile.setFilename(file.getOriginalFilename());
|
||||
sysFile.setFileFormat(getFileExtension(file.getOriginalFilename()).toLowerCase());
|
||||
sysFile.setMimeType(file.getContentType());
|
||||
sysFile.setFileSize(file.getSize());
|
||||
sysFile.setFileHash(fileHash);
|
||||
sysFile.setUploadBy(userId);
|
||||
|
||||
this.save(sysFile);
|
||||
result.add(convertToUploadVO(sysFile));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files, String category) {
|
||||
if (files == null || files.isEmpty()) {
|
||||
throw new BusinessException("文件列表不能为空");
|
||||
}
|
||||
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
List<SysFileUploadVO> result = new ArrayList<>();
|
||||
|
||||
for (MultipartFile file : files) {
|
||||
if (file.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 计算文件哈希
|
||||
String fileHash = FileHashUtils.calculateFileHash(file);
|
||||
|
||||
// 检查当前公司是否已有相同哈希的文件
|
||||
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(SysFilePO::getCompanyId, companyId)
|
||||
.eq(SysFilePO::getFileHash, fileHash)
|
||||
.isNull(SysFilePO::getDeleteTime)
|
||||
.last("LIMIT 1");
|
||||
SysFilePO existingFile = this.getOne(wrapper);
|
||||
|
||||
if (existingFile != null) {
|
||||
// 当前公司已有相同文件,先验证文件是否真的存在可访问
|
||||
if (verifyFileExists(existingFile)) {
|
||||
// 如果文件已存在但category不同,更新category
|
||||
if (category != null && !category.equals(existingFile.getCategory())) {
|
||||
existingFile.setCategory(category);
|
||||
this.updateById(existingFile);
|
||||
}
|
||||
result.add(convertToUploadVO(existingFile));
|
||||
continue;
|
||||
} else {
|
||||
// 文件不存在,删除无效记录,继续处理
|
||||
this.removeById(existingFile.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否有其他公司已有相同哈希的文件
|
||||
LambdaQueryWrapper<SysFilePO> otherCompanyWrapper = new LambdaQueryWrapper<>();
|
||||
otherCompanyWrapper.eq(SysFilePO::getFileHash, fileHash)
|
||||
.ne(SysFilePO::getCompanyId, companyId)
|
||||
.isNull(SysFilePO::getDeleteTime)
|
||||
.last("LIMIT 1");
|
||||
SysFilePO otherCompanyFile = this.getOne(otherCompanyWrapper);
|
||||
|
||||
String storagePath = null;
|
||||
String storageType = "local"; // 上传接口始终使用本地存储
|
||||
|
||||
if (otherCompanyFile != null) {
|
||||
// 其他公司已有相同文件,先验证文件是否真的存在可访问
|
||||
if (verifyFileExists(otherCompanyFile)) {
|
||||
// 文件存在,复制存储路径和类型
|
||||
storagePath = otherCompanyFile.getStoragePath();
|
||||
storageType = otherCompanyFile.getStorageType();
|
||||
|
||||
// 如果是本地存储,需要重新上传到当前公司的存储路径
|
||||
if ("local".equals(storageType)) {
|
||||
String relativePath = generateStoragePath(file.getOriginalFilename(), fileHash);
|
||||
storagePath = "./" + relativePath;
|
||||
saveFileToLocal(storagePath, file);
|
||||
}
|
||||
// 如果是OSS存储,直接使用相同的存储路径(OSS文件可以跨公司共享)
|
||||
|
||||
// 创建当前公司的文件记录
|
||||
SysFilePO sysFile = new SysFilePO();
|
||||
BeanUtils.copyProperties(otherCompanyFile, sysFile);
|
||||
sysFile.setId(null);
|
||||
sysFile.setCompanyId(companyId);
|
||||
sysFile.setStoragePath(storagePath);
|
||||
sysFile.setStorageType(storageType);
|
||||
sysFile.setFilename(file.getOriginalFilename());
|
||||
sysFile.setFileFormat(getFileExtension(file.getOriginalFilename()).toLowerCase());
|
||||
sysFile.setMimeType(file.getContentType());
|
||||
sysFile.setFileSize(file.getSize());
|
||||
sysFile.setFileHash(fileHash);
|
||||
sysFile.setCategory(category); // 设置文件分类
|
||||
sysFile.setUploadBy(userId);
|
||||
sysFile.setUploadTime(LocalDateTime.now());
|
||||
sysFile.setUpdateTime(null);
|
||||
sysFile.setUpdateBy(null);
|
||||
sysFile.setDeleteTime(null);
|
||||
sysFile.setDeleteBy(null);
|
||||
|
||||
this.save(sysFile);
|
||||
result.add(convertToUploadVO(sysFile));
|
||||
} else {
|
||||
// 文件不存在,删除无效记录,继续处理(当作新文件处理)
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有找到有效的其他公司文件,或者文件不存在,则作为新文件处理
|
||||
if (storagePath == null) {
|
||||
// 没有任何公司有相同文件,生成新的存储路径并上传(仅本地存储)
|
||||
@@ -146,6 +276,7 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
sysFile.setMimeType(file.getContentType());
|
||||
sysFile.setFileSize(file.getSize());
|
||||
sysFile.setFileHash(fileHash);
|
||||
sysFile.setCategory(category); // 设置文件分类
|
||||
sysFile.setUploadBy(userId);
|
||||
|
||||
this.save(sysFile);
|
||||
@@ -231,10 +362,15 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
}
|
||||
|
||||
if (otherCompanyFile == null) {
|
||||
// 文件不存在,返回OSS签名URL(不创建记录)
|
||||
// 文件不存在,返回OSS Header签名信息(不创建记录)
|
||||
signInfo.setExists(false);
|
||||
String storagePath = generateStoragePath(item.getFilename(), item.getFileHash());
|
||||
signInfo.setUploadUrl(ossService.generateUploadUrl(storagePath, 60));
|
||||
OssPostPolicyVO uploadPolicy = ossService.generateUploadPolicy(storagePath, 120);
|
||||
if (uploadPolicy != null && uploadPolicy.getUrl() != null) {
|
||||
signInfo.setUploadUrl(uploadPolicy.getUrl());
|
||||
signInfo.setUploadHeaders(uploadPolicy.getHeaders());
|
||||
signInfo.setStoragePath(storagePath); // 返回storagePath供前端创建文件记录时使用
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,12 +592,71 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
SysFileVO vo = new SysFileVO();
|
||||
BeanUtils.copyProperties(sysFile, vo);
|
||||
|
||||
// 如果是OSS存储,生成访问URL
|
||||
if ("oss".equals(sysFile.getStorageType())) {
|
||||
vo.setAccessUrl(ossService.generateAccessUrl(sysFile.getStoragePath(), 60));
|
||||
}
|
||||
// 使用工具类生成访问URL
|
||||
String accessUrl = SysFileUtils.getFileAccessUrl(sysFile.getStoragePath(), sysFile.getStorageType());
|
||||
vo.setAccessUrl(accessUrl);
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<SysFileVO> getFilePage(PageQueryDTO<SysFileFilterDTO> pageQueryDTO) {
|
||||
// 从token中获取公司ID
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
// 创建分页对象
|
||||
Page<SysFilePO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
|
||||
// 构建查询条件
|
||||
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(SysFilePO::getCompanyId, companyId)
|
||||
.isNull(SysFilePO::getDeleteTime); // 只查询未删除的文件
|
||||
|
||||
// 添加过滤条件
|
||||
SysFileFilterDTO filter = pageQueryDTO.getFilters();
|
||||
if (filter != null) {
|
||||
// 文件名(模糊查询)
|
||||
if (filter.getFilename() != null && !filter.getFilename().trim().isEmpty()) {
|
||||
wrapper.like(SysFilePO::getFilename, filter.getFilename());
|
||||
}
|
||||
// 文件格式(精准查询)
|
||||
if (filter.getFileFormat() != null && !filter.getFileFormat().trim().isEmpty()) {
|
||||
wrapper.eq(SysFilePO::getFileFormat, filter.getFileFormat());
|
||||
}
|
||||
// 存储类型(精准查询)
|
||||
if (filter.getStorageType() != null && !filter.getStorageType().trim().isEmpty()) {
|
||||
wrapper.eq(SysFilePO::getStorageType, filter.getStorageType());
|
||||
}
|
||||
// 文件分类(精准查询)
|
||||
if (filter.getCategory() != null && !filter.getCategory().trim().isEmpty()) {
|
||||
wrapper.eq(SysFilePO::getCategory, filter.getCategory());
|
||||
}
|
||||
// 标签(模糊查询)
|
||||
if (filter.getTags() != null && !filter.getTags().trim().isEmpty()) {
|
||||
wrapper.like(SysFilePO::getTags, filter.getTags());
|
||||
}
|
||||
// 上传时间范围
|
||||
if (filter.getStartUploadTime() != null) {
|
||||
wrapper.ge(SysFilePO::getUploadTime, filter.getStartUploadTime());
|
||||
}
|
||||
if (filter.getEndUploadTime() != null) {
|
||||
wrapper.le(SysFilePO::getUploadTime, filter.getEndUploadTime());
|
||||
}
|
||||
}
|
||||
|
||||
// 排序:按上传时间倒序
|
||||
wrapper.orderByDesc(SysFilePO::getUploadTime);
|
||||
|
||||
// 执行分页查询
|
||||
IPage<SysFilePO> pageResult = this.page(page, wrapper);
|
||||
|
||||
// 转换为VO并生成访问URL
|
||||
List<SysFileVO> voList = pageResult.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 构建分页结果
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user