完成订单批量导入功能

This commit is contained in:
ah--desktop
2025-09-14 20:00:31 +08:00
parent 6e710c37c1
commit 1ac8445a90
70 changed files with 5596 additions and 933 deletions
@@ -0,0 +1,154 @@
package top.xyquan.ecomdmbbackend.common.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;
/**
* 日期时间配置类
* 支持多种时间格式的自动解析
*/
@Configuration
public class DateTimeConfig {
/**
* 支持的时间格式列表
*/
private static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = Arrays.asList(
// 标准格式:yyyy-MM-dd HH:mm:ss
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
// ISO 8601格式:yyyy-MM-ddTHH:mm:ss
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
// 带毫秒的ISO格式:yyyy-MM-ddTHH:mm:ss.SSS
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"),
// 带毫秒的标准格式:yyyy-MM-dd HH:mm:ss.SSS
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"),
// 日期格式:yyyy-MM-dd
DateTimeFormatter.ofPattern("yyyy-MM-dd"),
// 中文格式:yyyy年MM月dd日 HH:mm:ss
DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"),
// 中文格式:yyyy年MM月dd日
DateTimeFormatter.ofPattern("yyyy年MM月dd日"),
// 斜杠格式:yyyy/MM/dd HH:mm:ss
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
// 斜杠格式:yyyy/MM/dd
DateTimeFormatter.ofPattern("yyyy/MM/dd"),
// 点格式:yyyy.MM.dd HH:mm:ss
DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"),
// 点格式:yyyy.MM.dd
DateTimeFormatter.ofPattern("yyyy.MM.dd")
);
/**
* 支持带时区的时间格式列表
*/
private static final List<DateTimeFormatter> ZONED_DATE_TIME_FORMATTERS = Arrays.asList(
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ss.SSSZ
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"),
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ssZ
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"),
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ss.SSSXXX
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"),
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ssXXX
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"),
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ss.SSSZ
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ssZ
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
);
/**
* 自定义LocalDateTime反序列化器
*/
public static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String dateTimeString = p.getText().trim();
if (dateTimeString == null || dateTimeString.isEmpty()) {
return null;
}
// 首先尝试带时区的格式
for (DateTimeFormatter formatter : ZONED_DATE_TIME_FORMATTERS) {
try {
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter);
return zonedDateTime.toLocalDateTime();
} catch (DateTimeParseException e) {
// 继续尝试下一个格式
}
}
// 然后尝试不带时区的格式
for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) {
try {
return LocalDateTime.parse(dateTimeString, formatter);
} catch (DateTimeParseException e) {
// 继续尝试下一个格式
}
}
// 如果所有格式都失败,抛出异常
throw new IOException("无法解析时间格式: " + dateTimeString +
"。支持的格式包括: yyyy-MM-dd HH:mm:ss, yyyy-MM-ddTHH:mm:ss, yyyy-MM-ddTHH:mm:ss.SSSZ, yyyy-MM-dd等");
}
}
/**
* 自定义LocalDateTime序列化器
* 统一输出格式为 yyyy-MM-dd HH:mm:ss
*/
public static class StandardLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
private static final DateTimeFormatter OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value == null) {
gen.writeNull();
} else {
gen.writeString(value.format(OUTPUT_FORMATTER));
}
}
}
/**
* 配置ObjectMapper支持多种时间格式
*/
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 注册Java时间模块
mapper.registerModule(new JavaTimeModule());
// 创建自定义模块
SimpleModule dateTimeModule = new SimpleModule();
// 添加反序列化器(输入)
dateTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer());
// 添加序列化器(输出)
dateTimeModule.addSerializer(LocalDateTime.class, new StandardLocalDateTimeSerializer());
// 注册自定义模块
mapper.registerModule(dateTimeModule);
return mapper;
}
}
@@ -9,9 +9,11 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
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.ec.model.dto.order.BatchImportOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.CreateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.OrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.UpdateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.BatchImportResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.OrderVO;
import top.xyquan.ecomdmbbackend.modules.ec.service.OrderService;
@@ -72,4 +74,12 @@ public class OrderController {
OrderVO orderVO = orderService.getOrderById(id);
return ApiResponse.success(orderVO);
}
@Operation(summary = "批量导入订单", description = "批量导入订单数据,支持部分成功部分失败")
@PostMapping("/batch-import")
@RequireRole(description = "批量导入订单", allowUser = false)
public ApiResponse<BatchImportResultVO> batchImportOrders(@Valid @RequestBody BatchImportOrderDTO batchImportOrderDTO) {
BatchImportResultVO result = orderService.batchImportOrders(batchImportOrderDTO);
return ApiResponse.success(result);
}
}
@@ -5,11 +5,14 @@ import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
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.ec.model.dto.product.CreateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductWithSpecsDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.ProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.UpdateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductVO;
@@ -63,4 +66,28 @@ public class ProductController {
PageResultVO<ProductVO> result = productService.getProductPage(pageQueryDTO);
return ApiResponse.success(result);
}
@Operation(summary = "一键创建商品和规格", description = "一次性创建商品和多个规格")
@PostMapping("/create-with-specs")
@RequireRole(description = "一键创建商品和规格", allowUser = false)
public ApiResponse<ProductVO> createProductWithSpecs(@Valid @RequestBody CreateProductWithSpecsDTO createProductWithSpecsDTO) {
ProductVO productVO = productService.createProductWithSpecs(createProductWithSpecsDTO);
return ApiResponse.success(productVO);
}
@Operation(summary = "根据名称精准查询商品", description = "根据商品名称精准查询商品信息,用于数据导入")
@GetMapping("/find-by-name/{name}")
@RequireRole(description = "根据名称查询商品", allowUser = true)
public ApiResponse<ProductVO> getProductByName(@Parameter(description = "商品名称") @PathVariable String name) {
ProductVO productVO = productService.getProductByName(name);
return ApiResponse.success(productVO);
}
@Operation(summary = "批量根据名称查询商品", description = "批量根据商品名称精准查询商品信息,用于数据导入")
@PostMapping("/find-by-names")
@RequireRole(description = "批量根据名称查询商品", allowUser = true)
public ApiResponse<List<ProductVO>> getProductsByNames(@RequestBody List<String> names) {
List<ProductVO> productVOs = productService.getProductsByNames(names);
return ApiResponse.success(productVOs);
}
}
@@ -1,79 +1,89 @@
package top.xyquan.ecomdmbbackend.modules.ec.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
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.ec.model.dto.product.CreateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.ProductSpecFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.UpdateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductSpecService;
import java.util.List;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductSpecService.ProductSpecQueryDTO;
/**
* 商品规格控制器
* 商品规格管理控制器
*/
@Tag(name = "电商-商品规格管理", description = "商品规格的增删改查接口")
@RestController
@RequestMapping("/api/ec/product-spec")
@RequiredArgsConstructor
@Tag(name = "电商-商品规格管理", description = "商品规格相关接口")
@RequestMapping("/ec/product-spec")
public class ProductSpecController {
private final ProductSpecService productSpecService;
@PostMapping
public ProductSpecController(ProductSpecService productSpecService) {
this.productSpecService = productSpecService;
}
@Operation(summary = "创建商品规格", description = "创建新的商品规格")
public ApiResponse<Long> createProductSpec(@Valid @RequestBody CreateProductSpecDTO dto) {
Long id = productSpecService.createProductSpec(dto);
return ApiResponse.success(id);
@PostMapping("/create")
@RequireRole(description = "创建商品规格", allowUser = false)
public ApiResponse<ProductSpecVO> createProductSpec(@Valid @RequestBody CreateProductSpecDTO createProductSpecDTO) {
ProductSpecVO productSpecVO = productSpecService.createProductSpec(createProductSpecDTO);
return ApiResponse.success(productSpecVO);
}
@PutMapping
@Operation(summary = "更新商品规格", description = "更新商品规格信息")
public ApiResponse<Void> updateProductSpec(@Valid @RequestBody UpdateProductSpecDTO dto) {
productSpecService.updateProductSpec(dto);
return ApiResponse.success();
@Operation(summary = "更新商品规格", description = "更新现有商品规格信息")
@PutMapping("/update/{id}")
@RequireRole(description = "更新商品规格", allowUser = false)
public ApiResponse<ProductSpecVO> updateProductSpec(@Valid @RequestBody UpdateProductSpecDTO updateProductSpecDTO,
@Parameter(description = "商品规格ID") @PathVariable Long id) {
ProductSpecVO productSpecVO = productSpecService.updateProductSpec(updateProductSpecDTO, id);
return ApiResponse.success(productSpecVO);
}
@DeleteMapping("/{id}")
@Operation(summary = "删除商品规格", description = "删除指定的商品规格")
@Operation(summary = "删除商品规格", description = "删除指定商品规格")
@DeleteMapping("/delete/{id}")
@RequireRole(description = "删除商品规格", allowUser = false)
public ApiResponse<Void> deleteProductSpec(
@Parameter(description = "规格ID", required = true) @PathVariable Long id) {
@Parameter(description = "商品规格ID") @PathVariable Long id) {
productSpecService.deleteProductSpec(id);
return ApiResponse.success();
}
@GetMapping("/{id}")
@Operation(summary = "查询商品规格详情", description = "根据ID查询商品规格详情")
public ApiResponse<ProductSpecVO> getProductSpecById(
@Parameter(description = "规格ID", required = true) @PathVariable Long id) {
ProductSpecVO vo = productSpecService.getProductSpecById(id);
return ApiResponse.success(vo);
}
@GetMapping("/page")
@Operation(summary = "分页查询商品规格", description = "分页查询商品规格列表")
public ApiResponse<IPage<ProductSpecVO>> getProductSpecPage(
@Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Long current,
@Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
ProductSpecFilterDTO filter) {
Page<ProductSpecVO> page = new Page<>(current, size);
IPage<ProductSpecVO> result = productSpecService.getProductSpecPage(page, filter);
@Operation(summary = "分页获取商品规格列表", description = "分页获取商品规格列表,支持条件过滤")
@PostMapping("/page")
@RequireRole(description = "查询商品规格列表", allowUser = true)
public ApiResponse<PageResultVO<ProductSpecVO>> getProductSpecPage(
@Valid @RequestBody PageQueryDTO<ProductSpecFilterDTO> pageQueryDTO) {
PageResultVO<ProductSpecVO> result = productSpecService.getProductSpecPage(pageQueryDTO);
return ApiResponse.success(result);
}
@GetMapping("/product/{productId}")
@Operation(summary = "查询商品规格列表", description = "根据商品ID查询规格列表")
public ApiResponse<List<ProductSpecVO>> getProductSpecsByProductId(
@Parameter(description = "商品ID", required = true) @PathVariable Long productId) {
List<ProductSpecVO> list = productSpecService.getProductSpecsByProductId(productId);
return ApiResponse.success(list);
@Operation(summary = "根据商品名称和规格编码精准查询商品规格", description = "根据商品名称和规格编码精准查询商品规格信息,用于数据导入")
@GetMapping("/find-by-product-and-spec/{productName}/{specCode}")
@RequireRole(description = "根据商品名称和规格编码查询商品规格", allowUser = true)
public ApiResponse<ProductSpecVO> getProductSpecByProductAndSpec(
@Parameter(description = "商品名称") @PathVariable String productName,
@Parameter(description = "规格编码") @PathVariable String specCode) {
ProductSpecVO productSpecVO = productSpecService.getProductSpecByProductAndSpec(productName, specCode);
return ApiResponse.success(productSpecVO);
}
}
@Operation(summary = "批量根据商品名称和规格编码查询商品规格", description = "批量根据商品名称和规格编码精准查询商品规格信息,用于数据导入")
@PostMapping("/find-by-product-and-specs")
@RequireRole(description = "批量根据商品名称和规格编码查询商品规格", allowUser = true)
public ApiResponse<List<ProductVO>> getProductSpecsByProductAndSpecs(@RequestBody List<ProductSpecQueryDTO> queries) {
List<ProductVO> productVOs = productSpecService.getProductSpecsByProductAndSpecs(queries);
return ApiResponse.success(productVOs);
}
}
@@ -5,6 +5,9 @@ import io.swagger.v3.oas.annotations.Parameter;
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 java.util.List;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
@@ -14,6 +17,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.model.dto.shop.ShopFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.shop.UpdateShopDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ec.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
/**
* 店铺管理控制器
@@ -63,4 +68,33 @@ public class ShopController {
PageResultVO<ShopVO> result = shopService.getShopPage(pageQueryDTO);
return ApiResponse.success(result);
}
@Operation(summary = "上传店铺Logo", description = "上传店铺Logo图片,支持跨公司共享")
@PostMapping("/upload-logo")
@RequireRole(description = "上传店铺Logo", allowUser = false)
public ApiResponse<MediaImageVO> uploadLogo(@RequestParam("file") MultipartFile file) {
// 检查是否为图片文件
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
return ApiResponse.fail("只能上传图片文件");
}
MediaImageVO mediaImageVO = shopService.uploadLogo(file);
return ApiResponse.success(mediaImageVO);
}
@Operation(summary = "根据名称精准查询店铺", description = "根据店铺名称精准查询店铺信息,用于数据导入")
@GetMapping("/find-by-name/{name}")
@RequireRole(description = "根据名称查询店铺", allowUser = true)
public ApiResponse<ShopVO> getShopByName(@Parameter(description = "店铺名称") @PathVariable String name) {
ShopVO shopVO = shopService.getShopByName(name);
return ApiResponse.success(shopVO);
}
@Operation(summary = "批量根据名称查询店铺", description = "批量根据店铺名称精准查询店铺信息,用于数据导入")
@PostMapping("/find-by-names")
@RequireRole(description = "批量根据名称查询店铺", allowUser = true)
public ApiResponse<List<ShopVO>> getShopsByNames(@RequestBody List<String> names) {
List<ShopVO> shopVOs = shopService.getShopsByNames(names);
return ApiResponse.success(shopVOs);
}
}
@@ -0,0 +1,24 @@
package top.xyquan.ecomdmbbackend.modules.ec.model.dto.order;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量导入订单DTO
*/
@Data
@Schema(description = "批量导入订单DTO")
public class BatchImportOrderDTO {
/**
* 订单列表
*/
@Schema(description = "订单列表", required = true)
@NotEmpty(message = "订单列表不能为空")
@Valid
private List<CreateOrderDTO> orders;
}
@@ -1,14 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.ec.model.dto.order;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 创建订单DTO
@@ -33,7 +31,8 @@ public class CreateOrderDTO {
/**
* 订单状态ID
*/
@Schema(description = "订单状态ID", example = "1")
@Schema(description = "订单状态ID", example = "1", required = true)
@NotNull(message = "订单状态ID不能为空")
private Long statusId;
/**
@@ -57,10 +56,24 @@ public class CreateOrderDTO {
private LocalDateTime orderDate;
/**
* 订单明细列表
* 商品ID
*/
@Schema(description = "订单明细列表", required = true)
@NotEmpty(message = "订单明细不能为空")
@Valid
private List<CreateOrderItemDTO> orderItems;
@Schema(description = "商品ID", example = "1", required = true)
@NotNull(message = "商品ID不能为空")
private Long productId;
/**
* 商品规格ID
*/
@Schema(description = "商品规格ID", example = "1", required = true)
@NotNull(message = "商品规格ID不能为空")
private Long productSpecId;
/**
* 数量
*/
@Schema(description = "数量", example = "1", required = true)
@NotNull(message = "数量不能为空")
@Positive(message = "数量必须大于0")
private Integer quantity;
}
@@ -0,0 +1,68 @@
package top.xyquan.ecomdmbbackend.modules.ec.model.dto.product;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 一键创建商品和规格DTO
*/
@Data
@Schema(description = "一键创建商品和规格DTO")
public class CreateProductWithSpecsDTO {
/**
* 商品名称
*/
@Schema(description = "商品名称", example = "iPhone 15 Pro", required = true)
@NotBlank(message = "商品名称不能为空")
private String name;
/**
* 主图图片ID
*/
@Schema(description = "主图图片ID", example = "1")
private Long mainImageId;
/**
* 商品规格列表
*/
@Schema(description = "商品规格列表", required = true)
@NotEmpty(message = "商品规格列表不能为空")
@Valid
private List<ProductSpecDTO> specs;
/**
* 商品规格DTO
*/
@Data
@Schema(description = "商品规格DTO")
public static class ProductSpecDTO {
/**
* 规格名称
*/
@Schema(description = "规格名称", example = "128GB 深空黑色", required = true)
@NotBlank(message = "规格名称不能为空")
private String name;
/**
* 规格编码
*/
@Schema(description = "规格编码", example = "IPHONE15PRO-128G-BLACK")
private String specCode;
/**
* 成本价
*/
@Schema(description = "成本价", example = "8000.00", required = true)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
}
}
@@ -0,0 +1,70 @@
package top.xyquan.ecomdmbbackend.modules.ec.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 批量导入结果VO
*/
@Data
@Schema(description = "批量导入结果VO")
public class BatchImportResultVO {
/**
* 总数量
*/
@Schema(description = "总数量", example = "100")
private Integer totalCount;
/**
* 成功数量
*/
@Schema(description = "成功数量", example = "95")
private Integer successCount;
/**
* 失败数量
*/
@Schema(description = "失败数量", example = "5")
private Integer failureCount;
/**
* 成功创建的订单列表
*/
@Schema(description = "成功创建的订单列表")
private List<OrderVO> successOrders;
/**
* 失败记录列表
*/
@Schema(description = "失败记录列表")
private List<ImportFailureRecord> failureRecords;
/**
* 导入失败记录
*/
@Data
@Schema(description = "导入失败记录")
public static class ImportFailureRecord {
/**
* 失败行号(从1开始)
*/
@Schema(description = "失败行号", example = "3")
private Integer rowNumber;
/**
* 平台订单号
*/
@Schema(description = "平台订单号", example = "TB202401010003")
private String platformOrderNo;
/**
* 失败原因
*/
@Schema(description = "失败原因", example = "店铺不存在")
private String failureReason;
}
}
@@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 商品VO
@@ -59,4 +60,10 @@ public class ProductVO {
*/
@Schema(description = "更新人ID", example = "1")
private Long updateBy;
/**
* 商品规格列表
*/
@Schema(description = "商品规格列表")
private List<ProductSpecVO> specs;
}
@@ -3,10 +3,12 @@ package top.xyquan.ecomdmbbackend.modules.ec.service;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.BatchImportOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.CreateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.OrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.UpdateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.BatchImportResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.OrderVO;
/**
@@ -53,4 +55,12 @@ public interface OrderService extends IService<OrderPO> {
* @return 订单VO
*/
OrderVO getOrderById(Long id);
/**
* 批量导入订单
*
* @param batchImportOrderDTO 批量导入订单DTO
* @return 批量导入结果VO
*/
BatchImportResultVO batchImportOrders(BatchImportOrderDTO batchImportOrderDTO);
}
@@ -4,11 +4,14 @@ import com.baomidou.mybatisplus.extension.service.IService;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductWithSpecsDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.ProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.UpdateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductVO;
import java.util.List;
/**
* 商品服务接口
*/
@@ -45,4 +48,28 @@ public interface ProductService extends IService<ProductPO> {
* @return 分页结果
*/
PageResultVO<ProductVO> getProductPage(PageQueryDTO<ProductFilterDTO> pageQueryDTO);
/**
* 一键创建商品和规格
*
* @param createProductWithSpecsDTO 创建商品和规格DTO
* @return 商品VO
*/
ProductVO createProductWithSpecs(CreateProductWithSpecsDTO createProductWithSpecsDTO);
/**
* 根据名称精准查询商品
*
* @param name 商品名称
* @return 商品VO
*/
ProductVO getProductByName(String name);
/**
* 批量根据名称查询商品
*
* @param names 商品名称列表
* @return 商品VO列表
*/
List<ProductVO> getProductsByNames(List<String> names);
}
@@ -1,46 +1,92 @@
package top.xyquan.ecomdmbbackend.modules.ec.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.ProductSpecFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.UpdateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductVO;
import java.util.List;
/**
* 商品规格服务接口
*/
public interface ProductSpecService {
public interface ProductSpecService extends IService<ProductSpecPO> {
/**
* 创建商品规格
*
* @param createProductSpecDTO 创建商品规格DTO
* @return 商品规格VO
*/
Long createProductSpec(CreateProductSpecDTO dto);
ProductSpecVO createProductSpec(CreateProductSpecDTO createProductSpecDTO);
/**
* 更新商品规格
*
* @param updateProductSpecDTO 更新商品规格DTO
* @param id 规格ID
* @return 商品规格VO
*/
void updateProductSpec(UpdateProductSpecDTO dto);
ProductSpecVO updateProductSpec(UpdateProductSpecDTO updateProductSpecDTO, Long id);
/**
* 删除商品规格
*
* @param id 规格ID
*/
void deleteProductSpec(Long id);
/**
* 根据ID查询商品规格
* 分页获取商品规格列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果
*/
ProductSpecVO getProductSpecById(Long id);
PageResultVO<ProductSpecVO> getProductSpecPage(PageQueryDTO<ProductSpecFilterDTO> pageQueryDTO);
/**
* 分页查询商品规格
* 根据商品名称和规格编码精准查询商品规格
*
* @param productName 商品名称
* @param specCode 规格编码
* @return 商品规格VO
*/
IPage<ProductSpecVO> getProductSpecPage(Page<ProductSpecVO> page, ProductSpecFilterDTO filter);
ProductSpecVO getProductSpecByProductAndSpec(String productName, String specCode);
/**
* 根据商品ID查询规格列表
* 批量根据商品名称和规格编码查询商品规格
*
* @param queries 查询条件列表
* @return 包含规格信息的商品VO列表
*/
List<ProductSpecVO> getProductSpecsByProductId(Long productId);
}
List<ProductVO> getProductSpecsByProductAndSpecs(List<ProductSpecQueryDTO> queries);
/**
* 商品规格查询DTO
*/
class ProductSpecQueryDTO {
private String productName;
private String specCode;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getSpecCode() {
return specCode;
}
public void setSpecCode(String specCode) {
this.specCode = specCode;
}
}
}
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.ec.service;
import com.baomidou.mybatisplus.extension.service.IService;
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.ec.model.dto.shop.CreateShopDTO;
@@ -8,6 +9,9 @@ import top.xyquan.ecomdmbbackend.modules.ec.model.dto.shop.ShopFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.shop.UpdateShopDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import java.util.List;
/**
* 店铺服务接口
@@ -45,4 +49,28 @@ public interface ShopService extends IService<ShopPO> {
* @return 分页结果
*/
PageResultVO<ShopVO> getShopPage(PageQueryDTO<ShopFilterDTO> pageQueryDTO);
/**
* 上传店铺Logo
*
* @param file Logo文件
* @return 上传后的图片信息
*/
MediaImageVO uploadLogo(MultipartFile file);
/**
* 根据名称精准查询店铺
*
* @param name 店铺名称
* @return 店铺VO
*/
ShopVO getShopByName(String name);
/**
* 批量根据名称查询店铺
*
* @param names 店铺名称列表
* @return 店铺VO列表
*/
List<ShopVO> getShopsByNames(List<String> names);
}
@@ -12,20 +12,26 @@ import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.mapper.OrderItemMapper;
import top.xyquan.ecomdmbbackend.modules.ec.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.BatchImportOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.CreateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.CreateOrderItemDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.OrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.order.UpdateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.OrderItemPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.BatchImportResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.OrderItemVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.OrderVO;
import top.xyquan.ecomdmbbackend.modules.ec.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ec.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@@ -37,11 +43,17 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
private final CurrentUserContext currentUserContext;
private final ShopService shopService;
private final ProductService productService;
private final ProductSpecService productSpecService;
private final OrderItemMapper orderItemMapper;
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService, OrderItemMapper orderItemMapper) {
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService,
OrderItemMapper orderItemMapper) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
this.productSpecService = productSpecService;
this.orderItemMapper = orderItemMapper;
}
@@ -57,6 +69,19 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
throw new BusinessException("店铺不存在");
}
// 验证商品是否存在且属于当前公司
ProductPO product = productService.getById(createOrderDTO.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
// 验证商品规格是否存在且属于当前公司
ProductSpecPO productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
if (productSpec == null || !productSpec.getCompanyId().equals(companyId) ||
!productSpec.getProductId().equals(createOrderDTO.getProductId())) {
throw new BusinessException("商品规格不存在或不属于该商品");
}
// 验证平台订单号是否重复(如果提供了的话)
if (createOrderDTO.getPlatformOrderNo() != null && !createOrderDTO.getPlatformOrderNo().trim().isEmpty()) {
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
@@ -70,34 +95,40 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
// 创建订单
OrderPO order = new OrderPO();
BeanUtils.copyProperties(createOrderDTO, order);
// 设置公司ID
order.setCompanyId(companyId);
// 设置默认值
if (order.getStatusId() == null) {
// 默认使用状态码为0的订单状态(待发货)
order.setStatusId(1L); // 假设状态ID为1对应待发货状态
}
if (order.getShippingFee() == null) {
order.setShippingFee(java.math.BigDecimal.ZERO);
}
// 设置创建人ID
order.setShopId(createOrderDTO.getShopId());
order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo());
order.setStatusId(createOrderDTO.getStatusId());
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setShippingFee(createOrderDTO.getShippingFee() != null ? createOrderDTO.getShippingFee() : java.math.BigDecimal.ZERO);
order.setOrderDate(createOrderDTO.getOrderDate());
order.setCreateBy(currentUserContext.getCurrentUserId());
// 保存订单
this.save(order);
// 计算订单明细相关字段
java.math.BigDecimal unitPrice = createOrderDTO.getReceivedAmount().divide(
java.math.BigDecimal.valueOf(createOrderDTO.getQuantity()), 2, java.math.RoundingMode.HALF_UP);
java.math.BigDecimal costPrice = productSpec.getCostPrice();
java.math.BigDecimal subtotal = unitPrice.multiply(java.math.BigDecimal.valueOf(createOrderDTO.getQuantity()));
java.math.BigDecimal costTotal = costPrice.multiply(java.math.BigDecimal.valueOf(createOrderDTO.getQuantity()));
// 创建订单明细
for (CreateOrderItemDTO itemDTO : createOrderDTO.getOrderItems()) {
OrderItemPO orderItem = new OrderItemPO();
BeanUtils.copyProperties(itemDTO, orderItem);
orderItem.setOrderId(order.getId());
orderItem.setCreateBy(currentUserContext.getCurrentUserId());
orderItemMapper.insert(orderItem);
}
OrderItemPO orderItem = new OrderItemPO();
orderItem.setOrderId(order.getId());
orderItem.setProductId(createOrderDTO.getProductId());
orderItem.setProductSpecId(createOrderDTO.getProductSpecId());
orderItem.setProductName(product.getName()); // 冗余存储商品名称
orderItem.setSpecName(productSpec.getName()); // 冗余存储规格名称
orderItem.setQuantity(createOrderDTO.getQuantity());
orderItem.setUnitPrice(unitPrice); // 销售单价 = 实收金额 / 数量
orderItem.setCostPrice(costPrice); // 成本价(下单时快照)
orderItem.setSubtotal(subtotal); // 小计金额 = 销售单价 × 数量
orderItem.setCostTotal(costTotal); // 成本小计 = 成本价 × 数量
orderItem.setCreateBy(currentUserContext.getCurrentUserId());
orderItemMapper.insert(orderItem);
// 转换为VO并返回
return convertToVO(order);
@@ -267,6 +298,48 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
return orderVO;
}
@Override
@Transactional
public BatchImportResultVO batchImportOrders(BatchImportOrderDTO batchImportOrderDTO) {
List<CreateOrderDTO> orders = batchImportOrderDTO.getOrders();
List<OrderVO> successOrders = new ArrayList<>();
List<BatchImportResultVO.ImportFailureRecord> failureRecords = new ArrayList<>();
int totalCount = orders.size();
int successCount = 0;
int failureCount = 0;
for (int i = 0; i < orders.size(); i++) {
CreateOrderDTO orderDTO = orders.get(i);
int rowNumber = i + 1; // 行号从1开始
try {
// 尝试创建订单
OrderVO orderVO = createOrder(orderDTO);
successOrders.add(orderVO);
successCount++;
} catch (Exception e) {
// 记录失败信息
BatchImportResultVO.ImportFailureRecord failureRecord = new BatchImportResultVO.ImportFailureRecord();
failureRecord.setRowNumber(rowNumber);
failureRecord.setPlatformOrderNo(orderDTO.getPlatformOrderNo());
failureRecord.setFailureReason(e.getMessage());
failureRecords.add(failureRecord);
failureCount++;
}
}
// 构建返回结果
BatchImportResultVO result = new BatchImportResultVO();
result.setTotalCount(totalCount);
result.setSuccessCount(successCount);
result.setFailureCount(failureCount);
result.setSuccessOrders(successOrders);
result.setFailureRecords(failureRecords);
return result;
}
/**
* 转换为VO
*/
@@ -5,6 +5,7 @@ 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.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
@@ -12,11 +13,15 @@ import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductWithSpecsDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.ProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.UpdateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
@@ -33,10 +38,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
private final CurrentUserContext currentUserContext;
private final MediaImageService mediaImageService;
private final ProductSpecService productSpecService;
public ProductServiceImpl(CurrentUserContext currentUserContext, MediaImageService mediaImageService) {
public ProductServiceImpl(CurrentUserContext currentUserContext, MediaImageService mediaImageService, @Lazy ProductSpecService productSpecService) {
this.currentUserContext = currentUserContext;
this.mediaImageService = mediaImageService;
this.productSpecService = productSpecService;
}
@Override
@@ -186,12 +193,129 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
@Override
@Transactional
public ProductVO createProductWithSpecs(CreateProductWithSpecsDTO createProductWithSpecsDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证商品名称是否重复
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getName, createProductWithSpecsDTO.getName())
.eq(ProductPO::getCompanyId, companyId)
.isNull(ProductPO::getDeleteTime);
if (this.count(wrapper) > 0) {
throw new BusinessException("商品名称已存在");
}
// 创建商品
ProductPO product = new ProductPO();
product.setName(createProductWithSpecsDTO.getName());
product.setCompanyId(companyId);
// 处理主图图片关联
if (createProductWithSpecsDTO.getMainImageId() != null) {
MediaImageVO mainImage = mediaImageService.getImageById(createProductWithSpecsDTO.getMainImageId());
if (mainImage != null) {
product.setMainImageId(createProductWithSpecsDTO.getMainImageId());
product.setMainImage(mainImage.getUrl()); // 设置冗余字段
}
}
// 设置创建人ID
product.setCreateBy(currentUserContext.getCurrentUserId());
// 保存商品
this.save(product);
// 创建商品规格
List<CreateProductWithSpecsDTO.ProductSpecDTO> specDTOs = createProductWithSpecsDTO.getSpecs();
for (CreateProductWithSpecsDTO.ProductSpecDTO specDTO : specDTOs) {
ProductSpecPO productSpec = new ProductSpecPO();
productSpec.setCompanyId(companyId);
productSpec.setProductId(product.getId());
productSpec.setName(specDTO.getName());
productSpec.setSpecCode(specDTO.getSpecCode());
productSpec.setCostPrice(specDTO.getCostPrice());
productSpec.setCreateBy(currentUserContext.getCurrentUserId());
productSpecService.save(productSpec);
}
// 转换为VO并返回
return convertToVO(product);
}
/**
* 转换为VO
*/
private ProductVO convertToVO(ProductPO product) {
ProductVO productVO = new ProductVO();
BeanUtils.copyProperties(product, productVO);
// 查询商品规格列表
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
specWrapper.eq(ProductSpecPO::getProductId, product.getId())
.eq(ProductSpecPO::getCompanyId, product.getCompanyId())
.isNull(ProductSpecPO::getDeleteTime)
.orderByAsc(ProductSpecPO::getCreateTime);
List<ProductSpecPO> specPOs = productSpecService.list(specWrapper);
List<ProductSpecVO> specVOs = specPOs.stream()
.map(this::convertSpecToVO)
.collect(Collectors.toList());
productVO.setSpecs(specVOs);
return productVO;
}
@Override
public ProductVO getProductByName(String name) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 根据名称精准查询商品
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getName, name)
.eq(ProductPO::getCompanyId, companyId)
.isNull(ProductPO::getDeleteTime);
ProductPO product = this.getOne(wrapper);
if (product == null) {
return null;
}
return convertToVO(product);
}
@Override
public List<ProductVO> getProductsByNames(List<String> names) {
if (names == null || names.isEmpty()) {
return List.of();
}
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 批量根据名称查询商品
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.in(ProductPO::getName, names)
.eq(ProductPO::getCompanyId, companyId)
.isNull(ProductPO::getDeleteTime)
.orderByAsc(ProductPO::getName);
List<ProductPO> products = this.list(wrapper);
return products.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
/**
* 转换规格PO为VO
*/
private ProductSpecVO convertSpecToVO(ProductSpecPO productSpec) {
ProductSpecVO productSpecVO = new ProductSpecVO();
BeanUtils.copyProperties(productSpec, productSpecVO);
return productSpecVO;
}
}
@@ -3,19 +3,26 @@ package top.xyquan.ecomdmbbackend.modules.ec.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 lombok.RequiredArgsConstructor;
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 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.ec.mapper.ProductSpecMapper;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.CreateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.ProductSpecFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.dto.product.UpdateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ec.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@@ -23,90 +30,283 @@ import java.util.stream.Collectors;
* 商品规格服务实现类
*/
@Service
@RequiredArgsConstructor
public class ProductSpecServiceImpl implements ProductSpecService {
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpecPO> implements ProductSpecService {
private final ProductSpecMapper productSpecMapper;
private final CurrentUserContext currentUserContext;
private final ProductService productService;
@Override
@Transactional(rollbackFor = Exception.class)
public Long createProductSpec(CreateProductSpecDTO dto) {
ProductSpecPO po = new ProductSpecPO();
BeanUtils.copyProperties(dto, po);
po.setCompanyId(currentUserContext.getCurrentCompanyId());
po.setCreateBy(currentUserContext.getCurrentUserId());
po.setUpdateBy(currentUserContext.getCurrentUserId());
productSpecMapper.insert(po);
return po.getId();
public ProductSpecServiceImpl(CurrentUserContext currentUserContext, ProductService productService) {
this.currentUserContext = currentUserContext;
this.productService = productService;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateProductSpec(UpdateProductSpecDTO dto) {
ProductSpecPO po = new ProductSpecPO();
BeanUtils.copyProperties(dto, po);
po.setUpdateBy(currentUserContext.getCurrentUserId());
productSpecMapper.updateById(po);
@Transactional
public ProductSpecVO createProductSpec(CreateProductSpecDTO createProductSpecDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证商品是否存在
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductSpecPO::getProductId, createProductSpecDTO.getProductId())
.eq(ProductSpecPO::getCompanyId, companyId)
.isNull(ProductSpecPO::getDeleteTime);
if (this.count(wrapper) == 0) {
throw new BusinessException("商品不存在");
}
// 验证规格名称是否重复
wrapper.clear();
wrapper.eq(ProductSpecPO::getProductId, createProductSpecDTO.getProductId())
.eq(ProductSpecPO::getName, createProductSpecDTO.getName())
.eq(ProductSpecPO::getCompanyId, companyId)
.isNull(ProductSpecPO::getDeleteTime);
if (this.count(wrapper) > 0) {
throw new BusinessException("规格名称已存在");
}
// 创建商品规格
ProductSpecPO productSpec = new ProductSpecPO();
BeanUtils.copyProperties(createProductSpecDTO, productSpec);
productSpec.setCompanyId(companyId);
// 设置创建人ID
productSpec.setCreateBy(currentUserContext.getCurrentUserId());
// 保存商品规格
this.save(productSpec);
// 转换为VO并返回
return convertToVO(productSpec);
}
@Override
@Transactional(rollbackFor = Exception.class)
@Transactional
public ProductSpecVO updateProductSpec(UpdateProductSpecDTO updateProductSpecDTO, Long id) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证商品规格是否存在
ProductSpecPO existingProductSpec = this.getById(id);
if (existingProductSpec == null || !existingProductSpec.getCompanyId().equals(companyId)) {
throw new BusinessException("商品规格不存在");
}
// 验证规格名称是否重复(排除当前规格)
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductSpecPO::getProductId, existingProductSpec.getProductId())
.eq(ProductSpecPO::getName, updateProductSpecDTO.getName())
.eq(ProductSpecPO::getCompanyId, companyId)
.ne(ProductSpecPO::getId, id)
.isNull(ProductSpecPO::getDeleteTime);
if (this.count(wrapper) > 0) {
throw new BusinessException("规格名称已存在");
}
// 更新商品规格
ProductSpecPO productSpec = new ProductSpecPO();
BeanUtils.copyProperties(updateProductSpecDTO, productSpec);
productSpec.setId(id);
productSpec.setCompanyId(companyId);
productSpec.setProductId(existingProductSpec.getProductId());
// 设置更新人ID
productSpec.setUpdateBy(currentUserContext.getCurrentUserId());
// 更新商品规格
this.updateById(productSpec);
// 转换为VO并返回
return convertToVO(productSpec);
}
@Override
@Transactional
public void deleteProductSpec(Long id) {
ProductSpecPO po = new ProductSpecPO();
po.setId(id);
po.setDeleteBy(currentUserContext.getCurrentUserId());
po.setDeleteTime(java.time.LocalDateTime.now());
productSpecMapper.updateById(po);
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证商品规格是否存在
ProductSpecPO existingProductSpec = this.getById(id);
if (existingProductSpec == null || !existingProductSpec.getCompanyId().equals(companyId)) {
throw new BusinessException("商品规格不存在");
}
// 软删除商品规格
ProductSpecPO productSpec = new ProductSpecPO();
productSpec.setId(id);
productSpec.setDeleteTime(LocalDateTime.now());
productSpec.setDeleteBy(currentUserContext.getCurrentUserId());
this.updateById(productSpec);
}
@Override
public ProductSpecVO getProductSpecById(Long id) {
ProductSpecPO po = productSpecMapper.selectById(id);
if (po == null) {
public PageResultVO<ProductSpecVO> getProductSpecPage(PageQueryDTO<ProductSpecFilterDTO> pageQueryDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 创建分页对象
Page<ProductSpecPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
// 构建查询条件
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductSpecPO::getCompanyId, companyId)
.isNull(ProductSpecPO::getDeleteTime);
// 添加过滤条件
ProductSpecFilterDTO filter = pageQueryDTO.getFilters();
if (filter != null) {
if (filter.getProductId() != null) {
wrapper.eq(ProductSpecPO::getProductId, filter.getProductId());
}
if (filter.getName() != null && !filter.getName().trim().isEmpty()) {
wrapper.like(ProductSpecPO::getName, filter.getName());
}
}
// 排序
wrapper.orderByDesc(ProductSpecPO::getCreateTime);
// 执行分页查询
IPage<ProductSpecPO> pageResult = this.page(page, wrapper);
// 转换为VO
List<ProductSpecVO> voList = pageResult.getRecords().stream()
.map(this::convertToVO)
.collect(Collectors.toList());
// 构建分页结果
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
@Override
public ProductSpecVO getProductSpecByProductAndSpec(String productName, String specCode) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 先根据商品名称查询商品
LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>();
productWrapper.eq(ProductPO::getName, productName)
.eq(ProductPO::getCompanyId, companyId)
.isNull(ProductPO::getDeleteTime);
ProductPO product = productService.getOne(productWrapper);
if (product == null) {
return null;
}
ProductSpecVO vo = new ProductSpecVO();
BeanUtils.copyProperties(po, vo);
return vo;
// 根据商品ID和规格编码查询规格
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
specWrapper.eq(ProductSpecPO::getProductId, product.getId())
.eq(ProductSpecPO::getSpecCode, specCode)
.eq(ProductSpecPO::getCompanyId, companyId)
.isNull(ProductSpecPO::getDeleteTime);
ProductSpecPO productSpec = this.getOne(specWrapper);
if (productSpec == null) {
return null;
}
return convertToVO(productSpec);
}
@Override
public IPage<ProductSpecVO> getProductSpecPage(Page<ProductSpecVO> page, ProductSpecFilterDTO filter) {
Page<ProductSpecPO> poPage = new Page<>(page.getCurrent(), page.getSize());
IPage<ProductSpecPO> poPageResult = productSpecMapper.selectPageWithFilter(poPage, filter);
Page<ProductSpecVO> voPage = new Page<>(poPageResult.getCurrent(), poPageResult.getSize(), poPageResult.getTotal());
List<ProductSpecVO> voList = poPageResult.getRecords().stream()
.map(po -> {
ProductSpecVO vo = new ProductSpecVO();
BeanUtils.copyProperties(po, vo);
return vo;
public List<ProductVO> getProductSpecsByProductAndSpecs(List<ProductSpecQueryDTO> queries) {
if (queries == null || queries.isEmpty()) {
return List.of();
}
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 收集所有商品名称
List<String> productNames = queries.stream()
.map(ProductSpecQueryDTO::getProductName)
.distinct()
.collect(Collectors.toList());
// 批量查询商品
LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>();
productWrapper.in(ProductPO::getName, productNames)
.eq(ProductPO::getCompanyId, companyId)
.isNull(ProductPO::getDeleteTime);
List<ProductPO> products = productService.list(productWrapper);
if (products.isEmpty()) {
return List.of();
}
// 创建商品名称到ID的映射
var productNameToIdMap = products.stream()
.collect(Collectors.toMap(ProductPO::getName, ProductPO::getId));
// 收集所有规格编码
List<String> specCodes = queries.stream()
.map(ProductSpecQueryDTO::getSpecCode)
.distinct()
.collect(Collectors.toList());
// 批量查询规格
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
specWrapper.in(ProductSpecPO::getSpecCode, specCodes)
.in(ProductSpecPO::getProductId, productNameToIdMap.values())
.eq(ProductSpecPO::getCompanyId, companyId)
.isNull(ProductSpecPO::getDeleteTime);
List<ProductSpecPO> productSpecs = this.list(specWrapper);
// 按商品分组规格
var productSpecsMap = productSpecs.stream()
.collect(Collectors.groupingBy(ProductSpecPO::getProductId));
// 构建结果:包含规格信息的商品VO列表
return products.stream()
.filter(product -> {
// 检查该商品是否有匹配的规格
List<ProductSpecPO> specs = productSpecsMap.get(product.getId());
if (specs == null || specs.isEmpty()) {
return false;
}
// 检查是否有规格在查询条件中
return specs.stream()
.anyMatch(spec -> queries.stream()
.anyMatch(query ->
query.getProductName().equals(product.getName()) &&
query.getSpecCode().equals(spec.getSpecCode())
));
})
.map(product -> {
// 转换为商品VO
ProductVO productVO = new ProductVO();
BeanUtils.copyProperties(product, productVO);
// 添加匹配的规格信息
List<ProductSpecPO> specs = productSpecsMap.get(product.getId());
if (specs != null) {
List<ProductSpecVO> specVOs = specs.stream()
.filter(spec -> queries.stream()
.anyMatch(query ->
query.getProductName().equals(product.getName()) &&
query.getSpecCode().equals(spec.getSpecCode())
))
.map(this::convertToVO)
.collect(Collectors.toList());
productVO.setSpecs(specVOs);
}
return productVO;
})
.collect(Collectors.toList());
voPage.setRecords(voList);
return voPage;
}
@Override
public List<ProductSpecVO> getProductSpecsByProductId(Long productId) {
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductSpecPO::getProductId, productId)
.eq(ProductSpecPO::getDeleteTime, null)
.orderByAsc(ProductSpecPO::getId);
List<ProductSpecPO> poList = productSpecMapper.selectList(wrapper);
return poList.stream()
.map(po -> {
ProductSpecVO vo = new ProductSpecVO();
BeanUtils.copyProperties(po, vo);
return vo;
})
.collect(Collectors.toList());
/**
* 转换为VO
*/
private ProductSpecVO convertToVO(ProductSpecPO productSpec) {
ProductSpecVO productSpecVO = new ProductSpecVO();
BeanUtils.copyProperties(productSpec, productSpecVO);
return productSpecVO;
}
}
}
@@ -20,6 +20,7 @@ import top.xyquan.ecomdmbbackend.modules.ec.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;
@@ -187,6 +188,53 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
@Override
public MediaImageVO uploadLogo(MultipartFile file) {
// 上传Logo到媒体模块(支持哈希校验和跨公司共享)
return mediaImageService.uploadImageWithType(file, "logo");
}
@Override
public ShopVO getShopByName(String name) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 根据名称精准查询店铺
LambdaQueryWrapper<ShopPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ShopPO::getName, name)
.eq(ShopPO::getCompanyId, companyId)
.isNull(ShopPO::getDeleteTime);
ShopPO shop = this.getOne(wrapper);
if (shop == null) {
return null;
}
return convertToVO(shop);
}
@Override
public List<ShopVO> getShopsByNames(List<String> names) {
if (names == null || names.isEmpty()) {
return List.of();
}
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 批量根据名称查询店铺
LambdaQueryWrapper<ShopPO> wrapper = new LambdaQueryWrapper<>();
wrapper.in(ShopPO::getName, names)
.eq(ShopPO::getCompanyId, companyId)
.isNull(ShopPO::getDeleteTime)
.orderByAsc(ShopPO::getName);
List<ShopPO> shops = this.list(wrapper);
return shops.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
/**
* 转换为VO
*/
@@ -13,11 +13,6 @@ public class MediaImageFilterDTO {
*/
private String filename;
/**
* 图片分类
*/
private String type;
/**
* 标签
*/
@@ -39,7 +39,7 @@ public class MediaImagePO {
private String filename;
/**
* 图片分类 (设计图,实物图,细节图,工艺图,其他)
* 图片分类 (image,avatar,logo)
*/
@TableField("type")
private String type;
@@ -53,4 +53,14 @@ public interface MediaImageService {
* 分页获取图片列表
*/
PageResultVO<MediaImageVO> getImagePage(PageQueryDTO<MediaImageFilterDTO> pageQueryDTO);
/**
* 根据文件哈希和类型查询图片信息
*/
MediaImageVO getImageByHashAndType(String fileHash, String type);
/**
* 上传指定类型的图片
*/
MediaImageVO uploadImageWithType(MultipartFile file, String type);
}
@@ -48,7 +48,7 @@ public class MediaImageServiceImpl extends ServiceImpl<MediaImageMapper, MediaIm
String fileHash = FileHashUtils.calculateFileHash(file);
// 设置图片类型默认值
String type = "其他";
String type = "image";
// 检查当前公司是否已有相同哈希的图片且文件存在
List<MediaImagePO> existingImages = baseMapper.selectByFileHashes(List.of(fileHash));
@@ -223,6 +223,7 @@ public class MediaImageServiceImpl extends ServiceImpl<MediaImageMapper, MediaIm
// 构建查询条件
LambdaQueryWrapper<MediaImagePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(MediaImagePO::getCompanyId, companyId)
.eq(MediaImagePO::getType, "image") // 固定查询image类型
.isNull(MediaImagePO::getDeleteTime);
// 添加过滤条件
@@ -231,9 +232,6 @@ public class MediaImageServiceImpl extends ServiceImpl<MediaImageMapper, MediaIm
if (filter.getFilename() != null && !filter.getFilename().trim().isEmpty()) {
wrapper.like(MediaImagePO::getFilename, filter.getFilename());
}
if (filter.getType() != null && !filter.getType().trim().isEmpty()) {
wrapper.eq(MediaImagePO::getType, filter.getType());
}
if (filter.getTags() != null && !filter.getTags().trim().isEmpty()) {
wrapper.like(MediaImagePO::getTags, filter.getTags());
}
@@ -254,6 +252,64 @@ public class MediaImageServiceImpl extends ServiceImpl<MediaImageMapper, MediaIm
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
@Override
public MediaImageVO getImageByHashAndType(String fileHash, String type) {
if (fileHash == null || fileHash.trim().isEmpty()) {
return null;
}
List<MediaImagePO> mediaImages = baseMapper.selectByFileHashes(List.of(fileHash));
// 查找指定类型且文件存在的图片
MediaImagePO mediaImage = mediaImages.stream()
.filter(img -> type.equals(img.getType()) && FileHashUtils.fileExists(img.getUrl()))
.findFirst()
.orElse(null);
return mediaImage != null ? convertToVO(mediaImage) : null;
}
@Override
public MediaImageVO uploadImageWithType(MultipartFile file, String type) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 计算文件哈希
String fileHash = FileHashUtils.calculateFileHash(file);
// 检查是否已有相同哈希和类型的图片(支持跨公司共享)
MediaImageVO existingImage = getImageByHashAndType(fileHash, type);
if (existingImage != null) {
// 如果已存在,直接返回现有记录
return existingImage;
}
// 上传文件到对应目录
String fileUrl;
if ("avatar".equals(type)) {
fileUrl = FileUploadUtils.uploadAvatar(file);
} else if ("logo".equals(type)) {
fileUrl = FileUploadUtils.uploadLogo(file);
} else {
fileUrl = FileUploadUtils.uploadImage(file);
}
// 创建新记录
MediaImagePO mediaImage = new MediaImagePO();
mediaImage.setCompanyId(companyId);
mediaImage.setUrl(fileUrl);
mediaImage.setFilename(file.getOriginalFilename());
mediaImage.setType(type);
mediaImage.setFileHash(fileHash);
mediaImage.setUploadBy(currentUserContext.getCurrentUserId());
// 保存图片记录
this.save(mediaImage);
// 转换为VO并返回
return convertToVO(mediaImage);
}
/**
* 转换为VO
*/
@@ -5,6 +5,7 @@ import io.swagger.v3.oas.annotations.Parameter;
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;
@@ -14,6 +15,7 @@ import top.xyquan.ecomdmbbackend.modules.org.model.dto.company.CompanyFilterDTO;
import top.xyquan.ecomdmbbackend.modules.org.model.vo.CompanyVO;
import top.xyquan.ecomdmbbackend.modules.org.service.CompanyService;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
/**
* 公司管理控制器
@@ -63,4 +65,17 @@ public class CompanyController {
PageResultVO<CompanyVO> pageResult = companyService.getCompanyPage(pageQuery);
return ApiResponse.success(pageResult);
}
@Operation(summary = "上传公司Logo", description = "上传公司Logo图片")
@PostMapping("/upload-logo")
@RequireRole(description = "上传公司Logo", allowCompany = false)
public ApiResponse<CompanyVO> uploadLogo(@RequestParam("file") MultipartFile file) {
// 检查是否为图片文件
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
return ApiResponse.fail("只能上传图片文件");
}
CompanyVO companyVO = companyService.uploadLogo(file);
return ApiResponse.success(companyVO);
}
}
@@ -65,6 +65,6 @@ public class CompanyDTO {
/**
* 订阅到期时间
*/
@Schema(description = "订阅到期时间", example = "2024-12-31T23:59:59")
@Schema(description = "订阅到期时间", example = "2024-12-31 23:59:59")
private LocalDateTime expireTime;
}
@@ -59,6 +59,6 @@ public class CreateCompanyDTO {
/**
* 订阅到期时间
*/
@Schema(description = "订阅到期时间", example = "2024-12-31T23:59:59")
@Schema(description = "订阅到期时间", example = "2024-12-31 23:59:59")
private LocalDateTime expireTime;
}
@@ -59,6 +59,6 @@ public class UpdateCompanyDTO {
/**
* 订阅到期时间
*/
@Schema(description = "订阅到期时间", example = "2024-12-31T23:59:59")
@Schema(description = "订阅到期时间", example = "2024-12-31 23:59:59")
private LocalDateTime expireTime;
}
@@ -27,7 +27,7 @@ public class CompanyVO {
/**
* 订阅到期时间
*/
@Schema(description = "订阅到期时间", example = "2024-12-31T23:59:59")
@Schema(description = "订阅到期时间", example = "2024-12-31 23:59:59")
private LocalDateTime expiration;
/**
@@ -69,19 +69,19 @@ public class CompanyVO {
/**
* 订阅到期时间
*/
@Schema(description = "订阅到期时间", example = "2024-12-31T23:59:59")
@Schema(description = "订阅到期时间", example = "2024-12-31 23:59:59")
private LocalDateTime expireTime;
/**
* 创建时间
*/
@Schema(description = "创建时间", example = "2024-01-01T10:00:00")
@Schema(description = "创建时间", example = "2024-01-01 10:00:00")
private LocalDateTime createTime;
/**
* 更新时间
*/
@Schema(description = "更新时间", example = "2024-01-01T10:00:00")
@Schema(description = "更新时间", example = "2024-01-01 10:00:00")
private LocalDateTime updateTime;
/**
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.org.service;
import com.baomidou.mybatisplus.extension.service.IService;
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.org.model.dto.company.CreateCompanyDTO;
@@ -44,4 +45,12 @@ public interface CompanyService extends IService<CompanyPO> {
* @return 分页结果
*/
PageResultVO<CompanyVO> getCompanyPage(PageQueryDTO<CompanyFilterDTO> pageQuery);
/**
* 上传公司Logo
*
* @param file Logo文件
* @return 更新后的公司信息
*/
CompanyVO uploadLogo(MultipartFile file);
}
@@ -20,6 +20,7 @@ import top.xyquan.ecomdmbbackend.modules.org.service.CompanyService;
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;
@@ -95,6 +96,9 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// 更新公司
CompanyPO company = new CompanyPO();
BeanUtils.copyProperties(updateCompanyDTO, company);
// 设置公司ID(必须在updateById之前设置)
company.setId(id);
// 处理logo图片ID
if (updateCompanyDTO.getLogoImageId() != null) {
@@ -108,11 +112,9 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// 设置更新人ID
company.setUpdateBy(currentUserContext.getCurrentUserId());
// 保存公司
// 更新公司
this.updateById(company);
// 设置公司ID
company.setId(id);
// 转换为VO并返回
return convertToVO(company);
}
@@ -169,6 +171,32 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
return PageResultVO.create(records, pageResult.getTotal(), pageQuery.getPage(), pageQuery.getPageSize());
}
@Override
public CompanyVO uploadLogo(MultipartFile file) {
// 获取当前用户所属公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("用户未关联公司");
}
// 查询公司信息
CompanyPO company = this.getById(companyId);
if (company == null) {
throw new BusinessException("公司不存在");
}
// 上传Logo到媒体模块(支持哈希校验和共享)
MediaImageVO mediaImageVO = mediaImageService.uploadImageWithType(file, "logo");
String logoUrl = mediaImageVO.getUrl();
// 更新公司Logo信息
company.setLogo(logoUrl);
this.updateById(company);
// 转换为VO并返回
return convertToVO(company);
}
/**
* 转换为VO
*/
@@ -4,11 +4,13 @@ import io.swagger.v3.oas.annotations.Operation;
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.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.user.ChangePasswordDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.user.UpdateUserInfoDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.UserVO;
import top.xyquan.ecomdmbbackend.modules.sys.service.UserService;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
/**
* 用户管理控制器
@@ -44,4 +46,16 @@ public class UserController {
userService.changePassword(changePasswordDTO);
return ApiResponse.success();
}
@Operation(summary = "上传用户头像", description = "上传用户头像图片")
@PostMapping("/upload-avatar")
public ApiResponse<UserVO> uploadAvatar(@RequestParam("file") MultipartFile file) {
// 检查是否为图片文件
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
return ApiResponse.fail("只能上传图片文件");
}
UserVO userVO = userService.uploadAvatar(file);
return ApiResponse.success(userVO);
}
}
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.user.ChangePasswordDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.user.LoginDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.user.RegisterDTO;
@@ -59,4 +60,12 @@ public interface UserService extends IService<UserPO> {
* @param changePasswordDTO 密码信息
*/
void changePassword(ChangePasswordDTO changePasswordDTO);
/**
* 上传用户头像
*
* @param file 头像文件
* @return 更新后的用户信息
*/
UserVO uploadAvatar(MultipartFile file);
}
@@ -21,6 +21,7 @@ import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
import top.xyquan.ecomdmbbackend.utils.SecurityUtils;
import top.xyquan.ecomdmbbackend.utils.TokenPayload;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
@@ -220,6 +221,34 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
this.updateById(user);
}
@Override
public UserVO uploadAvatar(MultipartFile file) {
// 从Security上下文获取用户ID
Long userId = SecurityUtils.getCurrentUserId();
if (userId == null) {
throw new BusinessException("用户未登录");
}
// 查询用户信息
UserPO user = this.getById(userId);
if (user == null) {
throw new BusinessException("用户不存在");
}
// 上传头像到媒体模块(支持哈希校验和共享)
MediaImageVO mediaImageVO = mediaImageService.uploadImageWithType(file, "avatar");
String avatarUrl = mediaImageVO.getUrl();
// 更新用户头像信息
user.setAvatar(avatarUrl);
this.updateById(user);
// 转换为VO并返回
UserVO userVO = new UserVO();
BeanUtils.copyProperties(user, userVO);
return userVO;
}
/**
* 生成登录响应
*/
@@ -26,7 +26,7 @@ CREATE TABLE `media_image` (
`company_id` bigint unsigned NOT NULL,
`url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '图片URL',
`filename` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '原始文件名',
`type` enum('设计图','实物图','细节图','工艺图','其他') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '其他' COMMENT '图片分类',
`type` enum('image','avatar','logo') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT 'image' COMMENT '图片分类',
`file_hash` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '文件哈希值,用于去重',
`tags` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '标签,逗号分隔如 spring,工艺图,客户A',
`remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '图片说明',
@@ -25,6 +25,12 @@ public class FileUploadUtils {
// 文件目录
private static final String FILE_DIR = "files";
// 头像目录
private static final String AVATAR_DIR = "avatar";
// Logo目录
private static final String LOGO_DIR = "logo";
/**
* 上传图片
*/
@@ -39,6 +45,20 @@ public class FileUploadUtils {
return uploadFile(file, FILE_DIR);
}
/**
* 上传头像
*/
public static String uploadAvatar(MultipartFile file) {
return uploadFile(file, AVATAR_DIR);
}
/**
* 上传Logo
*/
public static String uploadLogo(MultipartFile file) {
return uploadFile(file, LOGO_DIR);
}
/**
* 上传文件到指定目录
*/