ERP:初始化销售退货逻辑 50%

This commit is contained in:
YunaiV 2024-02-12 06:08:09 +08:00
parent dbc367ad95
commit 926286fe08
19 changed files with 1263 additions and 39 deletions

View File

@ -26,7 +26,9 @@ public interface ErrorCodeConstants {
ErrorCode SALE_ORDER_UPDATE_FAIL_APPROVE = new ErrorCode(1_020_201_005, "销售订单({})已审核,无法修改");
ErrorCode SALE_ORDER_NOT_APPROVE = new ErrorCode(1_020_201_006, "销售订单未审核,无法操作");
ErrorCode SALE_ORDER_ITEM_OUT_FAIL_PRODUCT_EXCEED = new ErrorCode(1_020_201_007, "销售订单项({})超过最大允许出库数量({})");
ErrorCode SALE_ORDER_PROCESS_FAIL_EXISTS_OUT = new ErrorCode(1_020_201_002, "反审核失败,已存在对应的销售出库单");
ErrorCode SALE_ORDER_PROCESS_FAIL_EXISTS_OUT = new ErrorCode(1_020_201_008, "反审核失败,已存在对应的销售出库单");
ErrorCode SALE_ORDER_ITEM_RETURN_FAIL_OUT_EXCEED = new ErrorCode(1_020_201_009, "销售订单项({})超过最大允许退货数量({})");
ErrorCode SALE_ORDER_PROCESS_FAIL_EXISTS_RETURN = new ErrorCode(1_020_201_010, "反审核失败,已存在对应的销售退货单");
// ========== ERP 销售出库1-030-202-000 ==========
ErrorCode SALE_OUT_NOT_EXISTS = new ErrorCode(1_020_202_000, "销售出库单不存在");
@ -36,6 +38,14 @@ public interface ErrorCodeConstants {
ErrorCode SALE_OUT_NO_EXISTS = new ErrorCode(1_020_202_004, "生成出库单失败,请重新提交");
ErrorCode SALE_OUT_UPDATE_FAIL_APPROVE = new ErrorCode(1_020_202_005, "销售出库单({})已审核,无法修改");
// ========== ERP 销售退货1-030-203-000 ==========
ErrorCode SALE_RETURN_NOT_EXISTS = new ErrorCode(1_020_203_000, "销售退货单不存在");
ErrorCode SALE_RETURN_DELETE_FAIL_APPROVE = new ErrorCode(1_020_203_001, "销售退货单({})已审核,无法删除");
ErrorCode SALE_RETURN_PROCESS_FAIL = new ErrorCode(1_020_203_002, "反审核失败,只有已审核的退货单才能反审核");
ErrorCode SALE_RETURN_APPROVE_FAIL = new ErrorCode(1_020_203_003, "审核失败,只有未审核的退货单才能审核");
ErrorCode SALE_RETURN_NO_EXISTS = new ErrorCode(1_020_203_004, "生成退货单失败,请重新提交");
ErrorCode SALE_RETURN_UPDATE_FAIL_APPROVE = new ErrorCode(1_020_203_005, "销售退货单({})已审核,无法修改");
// ========== ERP 仓库 1-030-400-000 ==========
ErrorCode WAREHOUSE_NOT_EXISTS = new ErrorCode(1_030_400_000, "仓库不存在");
ErrorCode WAREHOUSE_NOT_ENABLE = new ErrorCode(1_030_400_001, "仓库({})未启用");

View File

@ -33,6 +33,9 @@ public enum ErpStockRecordBizTypeEnum implements IntArrayValuable {
SALE_OUT(50, "销售出库"),
SALE_OUT_CANCEL(51, "销售出库(作废)"),
SALE_RETURN(60, "销售退货入库"),
SALE_RETURN_CANCEL(61, "销售退货入库(作废)"),
;
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(ErpStockRecordBizTypeEnum::getType).toArray();

View File

@ -0,0 +1,165 @@
package cn.iocoder.yudao.module.erp.controller.admin.sale;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpCustomerDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnItemDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.ErpStockDO;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.sale.ErpCustomerService;
import cn.iocoder.yudao.module.erp.service.sale.ErpSaleReturnService;
import cn.iocoder.yudao.module.erp.service.stock.ErpStockService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
@Tag(name = "管理后台 - ERP 销售退货")
@RestController
@RequestMapping("/erp/sale-return")
@Validated
public class ErpSaleReturnController {
@Resource
private ErpSaleReturnService saleReturnService;
@Resource
private ErpStockService stockService;
@Resource
private ErpProductService productService;
@Resource
private ErpCustomerService customerService;
@Resource
private AdminUserApi adminUserApi;
@PostMapping("/create")
@Operation(summary = "创建销售退货")
@PreAuthorize("@ss.hasPermission('erp:stock-return:create')")
public CommonResult<Long> createSaleReturn(@Valid @RequestBody ErpSaleReturnSaveReqVO createReqVO) {
return success(saleReturnService.createSaleReturn(createReqVO));
}
@PutMapping("/update")
@Operation(summary = "更新销售退货")
@PreAuthorize("@ss.hasPermission('erp:stock-return:update')")
public CommonResult<Boolean> updateSaleReturn(@Valid @RequestBody ErpSaleReturnSaveReqVO updateReqVO) {
saleReturnService.updateSaleReturn(updateReqVO);
return success(true);
}
@PutMapping("/update-status")
@Operation(summary = "更新销售退货的状态")
@PreAuthorize("@ss.hasPermission('erp:stock-return:update-status')")
public CommonResult<Boolean> updateSaleReturnStatus(@RequestParam("id") Long id,
@RequestParam("status") Integer status) {
saleReturnService.updateSaleReturnStatus(id, status);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除销售退货")
@Parameter(name = "ids", description = "编号数组", required = true)
@PreAuthorize("@ss.hasPermission('erp:stock-return:delete')")
public CommonResult<Boolean> deleteSaleReturn(@RequestParam("ids") List<Long> ids) {
saleReturnService.deleteSaleReturn(ids);
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得销售退货")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('erp:stock-return:query')")
public CommonResult<ErpSaleReturnRespVO> getSaleReturn(@RequestParam("id") Long id) {
ErpSaleReturnDO saleReturn = saleReturnService.getSaleReturn(id);
if (saleReturn == null) {
return success(null);
}
List<ErpSaleReturnItemDO> saleReturnItemList = saleReturnService.getSaleReturnItemListByReturnId(id);
Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
convertSet(saleReturnItemList, ErpSaleReturnItemDO::getProductId));
return success(BeanUtils.toBean(saleReturn, ErpSaleReturnRespVO.class, saleReturnVO ->
saleReturnVO.setItems(BeanUtils.toBean(saleReturnItemList, ErpSaleReturnRespVO.Item.class, item -> {
ErpStockDO stock = stockService.getStock(item.getProductId(), item.getWarehouseId());
item.setStockCount(stock != null ? stock.getCount() : BigDecimal.ZERO);
MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
.setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()));
}))));
}
@GetMapping("/page")
@Operation(summary = "获得销售退货分页")
@PreAuthorize("@ss.hasPermission('erp:stock-return:query')")
public CommonResult<PageResult<ErpSaleReturnRespVO>> getSaleReturnPage(@Valid ErpSaleReturnPageReqVO pageReqVO) {
PageResult<ErpSaleReturnDO> pageResult = saleReturnService.getSaleReturnPage(pageReqVO);
return success(buildSaleReturnVOPageResult(pageResult));
}
@GetMapping("/export-excel")
@Operation(summary = "导出销售退货 Excel")
@PreAuthorize("@ss.hasPermission('erp:stock-return:export')")
@OperateLog(type = EXPORT)
public void exportSaleReturnExcel(@Valid ErpSaleReturnPageReqVO pageReqVO,
HttpServletResponse response) throws IOException {
pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
List<ErpSaleReturnRespVO> list = buildSaleReturnVOPageResult(saleReturnService.getSaleReturnPage(pageReqVO)).getList();
// 导出 Excel
ExcelUtils.write(response, "销售退货.xls", "数据", ErpSaleReturnRespVO.class, list);
}
private PageResult<ErpSaleReturnRespVO> buildSaleReturnVOPageResult(PageResult<ErpSaleReturnDO> pageResult) {
if (CollUtil.isEmpty(pageResult.getList())) {
return PageResult.empty(pageResult.getTotal());
}
// 1.1 退货项
List<ErpSaleReturnItemDO> saleReturnItemList = saleReturnService.getSaleReturnItemListByReturnIds(
convertSet(pageResult.getList(), ErpSaleReturnDO::getId));
Map<Long, List<ErpSaleReturnItemDO>> saleReturnItemMap = convertMultiMap(saleReturnItemList, ErpSaleReturnItemDO::getReturnId);
// 1.2 商品信息
Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
convertSet(saleReturnItemList, ErpSaleReturnItemDO::getProductId));
// 1.3 客户信息
Map<Long, ErpCustomerDO> customerMap = customerService.getCustomerMap(
convertSet(pageResult.getList(), ErpSaleReturnDO::getCustomerId));
// 1.4 管理员信息
Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
convertSet(pageResult.getList(), erpStockRecordDO -> Long.parseLong(erpStockRecordDO.getCreator())));
// 2. 开始拼接
return BeanUtils.toBean(pageResult, ErpSaleReturnRespVO.class, saleReturn -> {
saleReturn.setItems(BeanUtils.toBean(saleReturnItemMap.get(saleReturn.getId()), ErpSaleReturnRespVO.Item.class,
item -> MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
.setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()))));
saleReturn.setProductNames(CollUtil.join(saleReturn.getItems(), "", ErpSaleReturnRespVO.Item::getProductName));
MapUtils.findAndThen(customerMap, saleReturn.getCustomerId(), supplier -> saleReturn.setCustomerName(supplier.getName()));
MapUtils.findAndThen(userMap, Long.parseLong(saleReturn.getCreator()), user -> saleReturn.setCreatorName(user.getNickname()));
});
}
}

View File

@ -30,7 +30,7 @@ public class ErpSaleOutPageReqVO extends PageParam {
@Schema(description = "备注", example = "你猜")
private String remark;
@Schema(description = "销售状态", example = "2")
@Schema(description = "出库状态", example = "2")
private Integer status;
@Schema(description = "创建者")

View File

@ -10,7 +10,7 @@ import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Schema(description = "管理后台 - ERP 出库出库 Response VO")
@Schema(description = "管理后台 - ERP 销售出库 Response VO")
@Data
@ExcelIgnoreUnannotated
public class ErpSaleOutRespVO {

View File

@ -0,0 +1,51 @@
package cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@Schema(description = "管理后台 - ERP 销售退货分页 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class ErpSaleReturnPageReqVO extends PageParam {
@Schema(description = "销售单编号", example = "XS001")
private String no;
@Schema(description = "客户编号", example = "1724")
private Long customerId;
@Schema(description = "退货时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime[] returnTime;
@Schema(description = "备注", example = "你猜")
private String remark;
@Schema(description = "退货状态", example = "2")
private Integer status;
@Schema(description = "创建者")
private String creator;
@Schema(description = "产品编号", example = "1")
private Long productId;
@Schema(description = "仓库编号", example = "1")
private Long warehouseId;
@Schema(description = "结算账号编号", example = "1")
private Long accountId;
@Schema(description = "销售单号", example = "1")
private String orderNo;
}

View File

@ -0,0 +1,152 @@
package cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Schema(description = "管理后台 - ERP 销售退货 Response VO")
@Data
@ExcelIgnoreUnannotated
public class ErpSaleReturnRespVO {
@Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "17386")
@ExcelProperty("编号")
private Long id;
@Schema(description = "退货单编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "XS001")
@ExcelProperty("退货单编号")
private String no;
@Schema(description = "退货状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "2")
@ExcelProperty("退货状态")
private Integer status;
@Schema(description = "客户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1724")
private Long customerId;
@Schema(description = "客户名称", example = "芋道")
@ExcelProperty("客户名称")
private String customerName;
@Schema(description = "结算账户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "311.89")
@ExcelProperty("结算账户编号")
private Long accountId;
@Schema(description = "退货员编号", example = "1888")
private Long saleUserId;
@Schema(description = "退货时间", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("退货时间")
private LocalDateTime outTime;
@Schema(description = "销售订单编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "17386")
private Long orderId;
@Schema(description = "销售订单号", requiredMode = Schema.RequiredMode.REQUIRED, example = "XS001")
private String orderNo;
@Schema(description = "合计数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "15663")
@ExcelProperty("合计数量")
private BigDecimal totalCount;
@Schema(description = "最终合计价格", requiredMode = Schema.RequiredMode.REQUIRED, example = "24906")
@ExcelProperty("最终合计价格")
private BigDecimal totalPrice;
@Schema(description = "合计产品价格,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "7127")
private BigDecimal totalProductPrice;
@Schema(description = "合计税额,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "7127")
private BigDecimal totalTaxPrice;
@Schema(description = "优惠率,百分比", requiredMode = Schema.RequiredMode.REQUIRED, example = "99.88")
private BigDecimal discountPercent;
@Schema(description = "优惠金额,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "7127")
private BigDecimal discountPrice;
@Schema(description = "定金金额,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "7127")
private BigDecimal otherPrice;
@Schema(description = "本次退款,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "7127")
private BigDecimal refundPrice;
@Schema(description = "本次欠款,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "666")
private BigDecimal debtPrice;
@Schema(description = "附件地址", example = "https://www.iocoder.cn")
@ExcelProperty("附件地址")
private String fileUrl;
@Schema(description = "备注", example = "你猜")
@ExcelProperty("备注")
private String remark;
@Schema(description = "审核人", example = "芋道")
private String creator;
@Schema(description = "审核人名称", example = "芋道")
private String creatorName;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("创建时间")
private LocalDateTime createTime;
@Schema(description = "退货项列表", requiredMode = Schema.RequiredMode.REQUIRED)
private List<Item> items;
@Schema(description = "产品信息", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("产品信息")
private String productNames;
@Data
public static class Item {
@Schema(description = "退货项编号", example = "11756")
private Long id;
@Schema(description = "销售订单项编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "11756")
private Long orderItemId;
@Schema(description = "仓库编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "3113")
private Long warehouseId;
@Schema(description = "产品编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "3113")
private Long productId;
@Schema(description = "产品单位单位", requiredMode = Schema.RequiredMode.REQUIRED, example = "3113")
private Long productUnitId;
@Schema(description = "产品单价", example = "100.00")
private BigDecimal productPrice;
@Schema(description = "产品数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "100.00")
@NotNull(message = "产品数量不能为空")
private BigDecimal count;
@Schema(description = "税率,百分比", example = "99.88")
private BigDecimal taxPercent;
@Schema(description = "税额,单位:元", example = "100.00")
private BigDecimal taxPrice;
@Schema(description = "备注", example = "随便")
private String remark;
// ========== 关联字段 ==========
@Schema(description = "产品名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "巧克力")
private String productName;
@Schema(description = "产品条码", requiredMode = Schema.RequiredMode.REQUIRED, example = "A9985")
private String productBarCode;
@Schema(description = "产品单位名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "")
private String productUnitName;
@Schema(description = "库存数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "100.00")
private BigDecimal stockCount; // 该字段仅仅在详情编辑时使用
}
}

View File

@ -0,0 +1,88 @@
package cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Schema(description = "管理后台 - ERP 销售退货新增/修改 Request VO")
@Data
public class ErpSaleReturnSaveReqVO {
@Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "17386")
private Long id;
@Schema(description = "结算账户编号", example = "31189")
private Long accountId;
@Schema(description = "销售员编号", example = "1888")
private Long saleUserId;
@Schema(description = "退货时间", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "退货时间不能为空")
private LocalDateTime returnTime;
@Schema(description = "销售订单编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "17386")
@NotNull(message = "销售订单编号不能为空")
private Long orderId;
@Schema(description = "优惠率,百分比", requiredMode = Schema.RequiredMode.REQUIRED, example = "99.88")
private BigDecimal discountPercent;
@Schema(description = "其它金额,单位:元", example = "7127")
private BigDecimal otherPrice;
@Schema(description = "本次退款,单位:元", requiredMode = Schema.RequiredMode.REQUIRED, example = "7127")
@NotNull(message = "本次退款不能为空")
private BigDecimal refundPrice;
@Schema(description = "附件地址", example = "https://www.iocoder.cn")
private String fileUrl;
@Schema(description = "备注", example = "你猜")
private String remark;
@Schema(description = "退货清单列表")
private List<Item> items;
@Data
public static class Item {
@Schema(description = "退货项编号", example = "11756")
private Long id;
@Schema(description = "销售订单项编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "11756")
@NotNull(message = "销售订单项编号不能为空")
private Long orderItemId;
@Schema(description = "仓库编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "3113")
@NotNull(message = "仓库编号不能为空")
private Long warehouseId;
@Schema(description = "产品编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "3113")
@NotNull(message = "产品编号不能为空")
private Long productId;
@Schema(description = "产品单位单位", requiredMode = Schema.RequiredMode.REQUIRED, example = "3113")
@NotNull(message = "产品单位单位不能为空")
private Long productUnitId;
@Schema(description = "产品单价", example = "100.00")
private BigDecimal productPrice;
@Schema(description = "产品数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "100.00")
@NotNull(message = "产品数量不能为空")
private BigDecimal count;
@Schema(description = "税率,百分比", example = "99.88")
private BigDecimal taxPercent;
@Schema(description = "备注", example = "随便")
private String remark;
}
}

View File

@ -0,0 +1,133 @@
package cn.iocoder.yudao.module.erp.dal.dataobject.sale;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.ErpAccountDO;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* ERP 销售退货 DO
*
* @author 芋道源码
*/
@TableName(value = "erp_sale_return")
@KeySequence("erp_sale_return_seq") // 用于 OraclePostgreSQLKingbaseDB2H2 数据库的主键自增如果是 MySQL 等数据库可不写
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ErpSaleReturnDO extends BaseDO {
/**
* 编号
*/
@TableId
private Long id;
/**
* 销售退货单号
*/
private String no;
/**
* 退货状态
*
* 枚举 {@link cn.iocoder.yudao.module.erp.enums.ErpAuditStatus}
*/
private Integer status;
/**
* 客户编号
*
* 关联 {@link ErpCustomerDO#getId()}
*/
private Long customerId;
/**
* 结算账户编号
*
* 关联 {@link ErpAccountDO#getId()}
*/
private Long accountId;
/**
* 销售员编号
*
* 关联 AdminUserDO id 字段
*/
private Long saleUserId;
/**
* 退货时间
*/
private LocalDateTime returnTime;
/**
* 销售订单编号
*
* 关联 {@link ErpSaleOrderDO#getId()}
*/
private Long orderId;
/**
* 销售订单号
*
* 冗余 {@link ErpSaleOrderDO#getNo()}
*/
private String orderNo;
/**
* 合计数量
*/
private BigDecimal totalCount;
/**
* 最终合计价格单位
*
* totalPrice = totalProductPrice + totalTaxPrice - discountPrice
*/
private BigDecimal totalPrice;
/**
* 合计产品价格单位
*/
private BigDecimal totalProductPrice;
/**
* 合计税额单位
*/
private BigDecimal totalTaxPrice;
/**
* 优惠率百分比
*/
private BigDecimal discountPercent;
/**
* 优惠金额单位
*
* discountPrice = (totalProductPrice + totalTaxPrice) * discountPercent
*/
private BigDecimal discountPrice;
/**
* 其它金额单位
*/
private BigDecimal otherPrice;
/**
* 本次收款单位
*
* refundPrice = totalPrice + otherPrice - debtPrice
*/
private BigDecimal refundPrice;
/**
* 本次欠款单位
*/
private BigDecimal debtPrice;
/**
* 附件地址
*/
private String fileUrl;
/**
* 备注
*/
private String remark;
}

View File

@ -0,0 +1,95 @@
package cn.iocoder.yudao.module.erp.dal.dataobject.sale;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.ErpWarehouseDO;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.math.BigDecimal;
/**
* ERP 销售退货项 DO
*
* @author 芋道源码
*/
@TableName("erp_sale_return_items")
@KeySequence("erp_sale_return_items_seq") // 用于 OraclePostgreSQLKingbaseDB2H2 数据库的主键自增如果是 MySQL 等数据库可不写
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ErpSaleReturnItemDO extends BaseDO {
/**
* 编号
*/
@TableId
private Long id;
/**
* 销售退货编号
*
* 关联 {@link ErpSaleReturnDO##getId()}
*/
private Long returnId;
/**
* 销售订单项编号
*
* 关联 {@link ErpSaleOrderItemDO#getId()}
* 目的方便更新关联的销售订单项的退货数量
*/
private Long orderItemId;
/**
* 仓库编号
*
* 关联 {@link ErpWarehouseDO#getId()}
*/
private Long warehouseId;
/**
* 产品编号
*
* 关联 {@link ErpProductDO#getId()}
*/
private Long productId;
/**
* 产品单位单位
*
* 冗余 {@link ErpProductDO#getUnitId()}
*/
private Long productUnitId;
/**
* 产品单位单价单位
*/
private BigDecimal productPrice;
/**
* 数量
*/
private BigDecimal count;
/**
* 总价单位
*
* totalPrice = productPrice * count
*/
private BigDecimal totalPrice;
/**
* 税率百分比
*/
private BigDecimal taxPercent;
/**
* 税额单位
*
* taxPrice = totalPrice * taxPercent
*/
private BigDecimal taxPrice;
/**
* 备注
*/
private String remark;
}

View File

@ -22,16 +22,16 @@ import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.
@Mapper
public interface ErpSaleOutItemMapper extends BaseMapperX<ErpSaleOutItemDO> {
default List<ErpSaleOutItemDO> selectListByOutId(Long orderId) {
return selectList(ErpSaleOutItemDO::getOutId, orderId);
default List<ErpSaleOutItemDO> selectListByOutId(Long outId) {
return selectList(ErpSaleOutItemDO::getOutId, outId);
}
default List<ErpSaleOutItemDO> selectListByOutIds(Collection<Long> orderIds) {
return selectList(ErpSaleOutItemDO::getOutId, orderIds);
default List<ErpSaleOutItemDO> selectListByOutIds(Collection<Long> outIds) {
return selectList(ErpSaleOutItemDO::getOutId, outIds);
}
default int deleteByOutId(Long orderId) {
return delete(ErpSaleOutItemDO::getOutId, orderId);
default int deleteByOutId(Long outId) {
return delete(ErpSaleOutItemDO::getOutId, outId);
}
/**

View File

@ -0,0 +1,56 @@
package cn.iocoder.yudao.module.erp.dal.mysql.sale;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnItemDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
/**
* ERP 销售退货项 Mapper
*
* @author 芋道源码
*/
@Mapper
public interface ErpSaleReturnItemMapper extends BaseMapperX<ErpSaleReturnItemDO> {
default List<ErpSaleReturnItemDO> selectListByReturnId(Long returnId) {
return selectList(ErpSaleReturnItemDO::getReturnId, returnId);
}
default List<ErpSaleReturnItemDO> selectListByReturnIds(Collection<Long> returnIds) {
return selectList(ErpSaleReturnItemDO::getReturnId, returnIds);
}
default int deleteByReturnId(Long returnId) {
return delete(ErpSaleReturnItemDO::getReturnId, returnId);
}
/**
* 基于销售订单编号查询每个销售订单项的出库数量之和
*
* @param returnIds 出库订单项编号数组
* @return key销售订单项编号value出库数量之和
*/
default Map<Long, BigDecimal> selectOrderItemCountSumMapByReturnIds(Collection<Long> returnIds) {
if (CollUtil.isEmpty(returnIds)) {
return Collections.emptyMap();
}
// SQL sum 查询
List<Map<String, Object>> result = selectMaps(new QueryWrapper<ErpSaleReturnItemDO>()
.select("order_item_id, SUM(count) AS sumCount")
.groupBy("order_item_id")
.in("return_id", returnIds));
// 获得数量
return convertMap(result, obj -> (Long) obj.get("order_item_id"), obj -> (BigDecimal) obj.get("sumCount"));
}
}

View File

@ -0,0 +1,56 @@
package cn.iocoder.yudao.module.erp.dal.mysql.sale;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnPageReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnItemDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* ERP 销售退货 Mapper
*
* @author 芋道源码
*/
@Mapper
public interface ErpSaleReturnMapper extends BaseMapperX<ErpSaleReturnDO> {
default PageResult<ErpSaleReturnDO> selectPage(ErpSaleReturnPageReqVO reqVO) {
MPJLambdaWrapperX<ErpSaleReturnDO> query = new MPJLambdaWrapperX<ErpSaleReturnDO>()
.likeIfPresent(ErpSaleReturnDO::getNo, reqVO.getNo())
.eqIfPresent(ErpSaleReturnDO::getCustomerId, reqVO.getCustomerId())
.betweenIfPresent(ErpSaleReturnDO::getReturnTime, reqVO.getReturnTime())
.eqIfPresent(ErpSaleReturnDO::getStatus, reqVO.getStatus())
.likeIfPresent(ErpSaleReturnDO::getRemark, reqVO.getRemark())
.eqIfPresent(ErpSaleReturnDO::getCreator, reqVO.getCreator())
.eqIfPresent(ErpSaleReturnDO::getAccountId, reqVO.getAccountId())
.likeIfPresent(ErpSaleReturnDO::getOrderNo, reqVO.getOrderNo())
.orderByDesc(ErpSaleReturnDO::getId);
if (reqVO.getWarehouseId() != null || reqVO.getProductId() != null) {
query.leftJoin(ErpSaleReturnItemDO.class, ErpSaleReturnItemDO::getReturnId, ErpSaleReturnDO::getId)
.eq(reqVO.getWarehouseId() != null, ErpSaleReturnItemDO::getWarehouseId, reqVO.getWarehouseId())
.eq(reqVO.getProductId() != null, ErpSaleReturnItemDO::getProductId, reqVO.getProductId())
.groupBy(ErpSaleReturnDO::getId); // 避免 1 对多查询产生相同的 1
}
return selectJoinPage(reqVO, ErpSaleReturnDO.class, query);
}
default int updateByIdAndStatus(Long id, Integer status, ErpSaleReturnDO updateObj) {
return update(updateObj, new LambdaUpdateWrapper<ErpSaleReturnDO>()
.eq(ErpSaleReturnDO::getId, id).eq(ErpSaleReturnDO::getStatus, status));
}
default ErpSaleReturnDO selectByNo(String no) {
return selectOne(ErpSaleReturnDO::getNo, no);
}
default List<ErpSaleReturnDO> selectListByOrderId(Long orderId) {
return selectList(ErpSaleReturnDO::getOrderId, orderId);
}
}

View File

@ -46,6 +46,10 @@ public class ErpNoRedisDAO {
* 销售出库 {@link cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleOutDO}
*/
public static final String SALE_OUT_NO_PREFIX = "XSCK";
/**
* 销售退货 {@link cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnDO}
*/
public static final String SALE_RETURN_NO_PREFIX = "XSTH";
@Resource
private StringRedisTemplate stringRedisTemplate;

View File

@ -46,9 +46,17 @@ public interface ErpSaleOrderService {
* 更新销售订单的出库数量
*
* @param id 编号
* @param returnCountMap 出库数量 Mapkey 销售订单项编号value 出库数量
* @param outCountMap 出库数量 Mapkey 销售订单项编号value 出库数量
*/
void updateSaleOrderOutCount(Long id, Map<Long, BigDecimal> returnCountMap);
void updateSaleOrderOutCount(Long id, Map<Long, BigDecimal> outCountMap);
/**
* 更新销售订单的退货数量
*
* @param orderId 编号
* @param returnCountMap 退货数量 Mapkey 销售订单项编号value 退货数量
*/
void updateSaleOrderReturnCount(Long orderId, Map<Long, BigDecimal> returnCountMap);
/**
* 删除销售订单

View File

@ -149,7 +149,10 @@ public class ErpSaleOrderServiceImpl implements ErpSaleOrderService {
if (!approve && saleOrder.getOutCount().compareTo(BigDecimal.ZERO) > 0) {
throw exception(SALE_ORDER_PROCESS_FAIL_EXISTS_OUT);
}
// TODO @芋艿需要校验是不是有有退货
// 1.4 存在销售退货单无法反审核
if (!approve && saleOrder.getReturnCount().compareTo(BigDecimal.ZERO) > 0) {
throw exception(SALE_ORDER_PROCESS_FAIL_EXISTS_RETURN);
}
// 2. 更新状态
int updateCount = saleOrderMapper.updateByIdAndStatus(id, saleOrder.getStatus(),
@ -159,26 +162,6 @@ public class ErpSaleOrderServiceImpl implements ErpSaleOrderService {
}
}
@Override
public void updateSaleOrderOutCount(Long id, Map<Long, BigDecimal> returnCountMap) {
List<ErpSaleOrderItemDO> orderItems = saleOrderItemMapper.selectListByOrderId(id);
// 1. 更新每个销售订单项
orderItems.forEach(item -> {
BigDecimal outCount = returnCountMap.getOrDefault(item.getId(), BigDecimal.ZERO);
if (item.getOutCount().equals(outCount)) {
return;
}
if (outCount.compareTo(item.getCount()) > 0) {
throw exception(SALE_ORDER_ITEM_OUT_FAIL_PRODUCT_EXCEED,
productService.getProduct(item.getProductId()).getName(), item.getCount());
}
saleOrderItemMapper.updateById(new ErpSaleOrderItemDO().setId(item.getId()).setOutCount(outCount));
});
// 2. 更新销售订单
BigDecimal totalOutCount = getSumValue(returnCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO);
saleOrderMapper.updateById(new ErpSaleOrderDO().setId(id).setOutCount(totalOutCount));
}
private List<ErpSaleOrderItemDO> validateSaleOrderItems(List<ErpSaleOrderSaveReqVO.Item> list) {
// 1. 校验产品存在
List<ErpProductDO> productList = productService.validProductList(
@ -218,6 +201,46 @@ public class ErpSaleOrderServiceImpl implements ErpSaleOrderService {
}
}
@Override
public void updateSaleOrderOutCount(Long id, Map<Long, BigDecimal> outCountMap) {
List<ErpSaleOrderItemDO> orderItems = saleOrderItemMapper.selectListByOrderId(id);
// 1. 更新每个销售订单项
orderItems.forEach(item -> {
BigDecimal outCount = outCountMap.getOrDefault(item.getId(), BigDecimal.ZERO);
if (item.getOutCount().equals(outCount)) {
return;
}
if (outCount.compareTo(item.getCount()) > 0) {
throw exception(SALE_ORDER_ITEM_OUT_FAIL_PRODUCT_EXCEED,
productService.getProduct(item.getProductId()).getName(), item.getCount());
}
saleOrderItemMapper.updateById(new ErpSaleOrderItemDO().setId(item.getId()).setOutCount(outCount));
});
// 2. 更新销售订单
BigDecimal totalOutCount = getSumValue(outCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO);
saleOrderMapper.updateById(new ErpSaleOrderDO().setId(id).setOutCount(totalOutCount));
}
@Override
public void updateSaleOrderReturnCount(Long orderId, Map<Long, BigDecimal> returnCountMap) {
List<ErpSaleOrderItemDO> orderItems = saleOrderItemMapper.selectListByOrderId(orderId);
// 1. 更新每个销售订单项
orderItems.forEach(item -> {
BigDecimal returnCount = returnCountMap.getOrDefault(item.getId(), BigDecimal.ZERO);
if (item.getReturnCount().equals(returnCount)) {
return;
}
if (returnCount.compareTo(item.getOutCount()) > 0) {
throw exception(SALE_ORDER_ITEM_RETURN_FAIL_OUT_EXCEED,
productService.getProduct(item.getProductId()).getName(), item.getOutCount());
}
saleOrderItemMapper.updateById(new ErpSaleOrderItemDO().setId(item.getId()).setReturnCount(returnCount));
});
// 2. 更新销售订单
BigDecimal totalReturnCount = getSumValue(returnCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO);
saleOrderMapper.updateById(new ErpSaleOrderDO().setId(orderId).setReturnCount(totalReturnCount));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteSaleOrder(List<Long> ids) {

View File

@ -40,7 +40,7 @@ import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;
// TODO 芋艿记录操作日志
/**
* ERP 销售订单 Service 实现类
* ERP 销售出库 Service 实现类
*
* @author 芋道源码
*/
@ -74,7 +74,7 @@ public class ErpSaleOutServiceImpl implements ErpSaleOutService {
public Long createSaleOut(ErpSaleOutSaveReqVO createReqVO) {
// 1.1 校验销售订单已审核
ErpSaleOrderDO saleOrder = saleOrderService.validateSaleOrder(createReqVO.getOrderId());
// 1.2 校验订单项的有效性
// 1.2 校验出库项的有效性
List<ErpSaleOutItemDO> saleOutItems = validateSaleOutItems(createReqVO.getItems());
// 1.3 校验结算账户
accountService.validateAccount(createReqVO.getAccountId());
@ -88,13 +88,13 @@ public class ErpSaleOutServiceImpl implements ErpSaleOutService {
throw exception(SALE_OUT_NO_EXISTS);
}
// 2.1 插入订单
// 2.1 插入出库
ErpSaleOutDO saleOut = BeanUtils.toBean(createReqVO, ErpSaleOutDO.class, in -> in
.setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()))
.setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
calculateTotalPrice(saleOut, saleOutItems);
saleOutMapper.insert(saleOut);
// 2.2 插入订单
// 2.2 插入出库
saleOutItems.forEach(o -> o.setOutId(saleOut.getId()));
saleOutItemMapper.insertBatch(saleOutItems);
@ -122,12 +122,12 @@ public class ErpSaleOutServiceImpl implements ErpSaleOutService {
// 1.5 校验订单项的有效性
List<ErpSaleOutItemDO> saleOutItems = validateSaleOutItems(updateReqVO.getItems());
// 2.1 更新订单
// 2.1 更新出库
ErpSaleOutDO updateObj = BeanUtils.toBean(updateReqVO, ErpSaleOutDO.class)
.setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
calculateTotalPrice(updateObj, saleOutItems);
saleOutMapper.updateById(updateObj);
// 2.2 更新订单
// 2.2 更新出库
updateSaleOutItemList(updateReqVO.getId(), saleOutItems);
// 3.1 更新销售订单的出库数量
@ -278,7 +278,7 @@ public class ErpSaleOutServiceImpl implements ErpSaleOutService {
return saleOutMapper.selectPage(pageReqVO);
}
// ==================== 订单 ====================
// ==================== 销售出库 ====================
@Override
public List<ErpSaleOutItemDO> getSaleOutItemListByOutId(Long outId) {

View File

@ -0,0 +1,84 @@
package cn.iocoder.yudao.module.erp.service.sale;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnItemDO;
import jakarta.validation.Valid;
import java.util.Collection;
import java.util.List;
/**
* ERP 销售退货 Service 接口
*
* @author 芋道源码
*/
public interface ErpSaleReturnService {
/**
* 创建销售退货
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createSaleReturn(@Valid ErpSaleReturnSaveReqVO createReqVO);
/**
* 更新销售退货
*
* @param updateReqVO 更新信息
*/
void updateSaleReturn(@Valid ErpSaleReturnSaveReqVO updateReqVO);
/**
* 更新销售退货的状态
*
* @param id 编号
* @param status 状态
*/
void updateSaleReturnStatus(Long id, Integer status);
/**
* 删除销售退货
*
* @param ids 编号数组
*/
void deleteSaleReturn(List<Long> ids);
/**
* 获得销售退货
*
* @param id 编号
* @return 销售退货
*/
ErpSaleReturnDO getSaleReturn(Long id);
/**
* 获得销售退货分页
*
* @param pageReqVO 分页查询
* @return 销售退货分页
*/
PageResult<ErpSaleReturnDO> getSaleReturnPage(ErpSaleReturnPageReqVO pageReqVO);
// ==================== 销售退货项 ====================
/**
* 获得销售退货项列表
*
* @param returnId 销售退货编号
* @return 销售退货项列表
*/
List<ErpSaleReturnItemDO> getSaleReturnItemListByReturnId(Long returnId);
/**
* 获得销售退货项 List
*
* @param returnIds 销售退货编号数组
* @return 销售退货项 List
*/
List<ErpSaleReturnItemDO> getSaleReturnItemListByReturnIds(Collection<Long> returnIds);
}

View File

@ -0,0 +1,296 @@
package cn.iocoder.yudao.module.erp.service.sale;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleReturnItemDO;
import cn.iocoder.yudao.module.erp.dal.mysql.sale.ErpSaleReturnItemMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.sale.ErpSaleReturnMapper;
import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO;
import cn.iocoder.yudao.module.erp.enums.ErpAuditStatus;
import cn.iocoder.yudao.module.erp.enums.stock.ErpStockRecordBizTypeEnum;
import cn.iocoder.yudao.module.erp.service.finance.ErpAccountService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.stock.ErpStockRecordService;
import cn.iocoder.yudao.module.erp.service.stock.bo.ErpStockRecordCreateReqBO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;
// TODO 芋艿记录操作日志
/**
* ERP 销售退货 Service 实现类
*
* @author 芋道源码
*/
@Service
@Validated
public class ErpSaleReturnServiceImpl implements ErpSaleReturnService {
@Resource
private ErpSaleReturnMapper saleReturnMapper;
@Resource
private ErpSaleReturnItemMapper saleReturnItemMapper;
@Resource
private ErpNoRedisDAO noRedisDAO;
@Resource
private ErpProductService productService;
@Resource
@Lazy // 延迟加载避免循环依赖
private ErpSaleOrderService saleOrderService;
@Resource
private ErpAccountService accountService;
@Resource
private ErpStockRecordService stockRecordService;
@Resource
private AdminUserApi adminUserApi;
@Override
@Transactional(rollbackFor = Exception.class)
public Long createSaleReturn(ErpSaleReturnSaveReqVO createReqVO) {
// 1.1 校验销售订单已审核
ErpSaleOrderDO saleOrder = saleOrderService.validateSaleOrder(createReqVO.getOrderId());
// 1.2 校验退货项的有效性
List<ErpSaleReturnItemDO> saleReturnItems = validateSaleReturnItems(createReqVO.getItems());
// 1.3 校验结算账户
accountService.validateAccount(createReqVO.getAccountId());
// 1.4 校验销售人员
if (createReqVO.getSaleUserId() != null) {
adminUserApi.validateUser(createReqVO.getSaleUserId());
}
// 1.5 生成调拨单号并校验唯一性
String no = noRedisDAO.generate(ErpNoRedisDAO.SALE_RETURN_NO_PREFIX);
if (saleReturnMapper.selectByNo(no) != null) {
throw exception(SALE_RETURN_NO_EXISTS);
}
// 2.1 插入退货
ErpSaleReturnDO saleReturn = BeanUtils.toBean(createReqVO, ErpSaleReturnDO.class, in -> in
.setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()))
.setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
calculateTotalPrice(saleReturn, saleReturnItems);
saleReturnMapper.insert(saleReturn);
// 2.2 插入退货项
saleReturnItems.forEach(o -> o.setReturnId(saleReturn.getId()));
saleReturnItemMapper.insertBatch(saleReturnItems);
// 3. 更新销售订单的退货数量
updateSaleOrderReturnCount(createReqVO.getOrderId());
return saleReturn.getId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateSaleReturn(ErpSaleReturnSaveReqVO updateReqVO) {
// 1.1 校验存在
ErpSaleReturnDO saleReturn = validateSaleReturnExists(updateReqVO.getId());
if (ErpAuditStatus.APPROVE.getStatus().equals(saleReturn.getStatus())) {
throw exception(SALE_RETURN_UPDATE_FAIL_APPROVE, saleReturn.getNo());
}
// 1.2 校验销售订单已审核
ErpSaleOrderDO saleOrder = saleOrderService.validateSaleOrder(updateReqVO.getOrderId());
// 1.3 校验结算账户
accountService.validateAccount(updateReqVO.getAccountId());
// 1.4 校验销售人员
if (updateReqVO.getSaleUserId() != null) {
adminUserApi.validateUser(updateReqVO.getSaleUserId());
}
// 1.5 校验订单项的有效性
List<ErpSaleReturnItemDO> saleReturnItems = validateSaleReturnItems(updateReqVO.getItems());
// 2.1 更新退货
ErpSaleReturnDO updateObj = BeanUtils.toBean(updateReqVO, ErpSaleReturnDO.class)
.setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
calculateTotalPrice(updateObj, saleReturnItems);
saleReturnMapper.updateById(updateObj);
// 2.2 更新退货项
updateSaleReturnItemList(updateReqVO.getId(), saleReturnItems);
// 3.1 更新销售订单的出库数量
updateSaleOrderReturnCount(updateObj.getOrderId());
// 3.2 注意如果销售订单编号变更了需要更新销售订单的出库数量
if (ObjectUtil.notEqual(saleReturn.getOrderId(), updateObj.getOrderId())) {
updateSaleOrderReturnCount(saleReturn.getOrderId());
}
}
private void calculateTotalPrice(ErpSaleReturnDO saleReturn, List<ErpSaleReturnItemDO> saleReturnItems) {
saleReturn.setTotalCount(getSumValue(saleReturnItems, ErpSaleReturnItemDO::getCount, BigDecimal::add));
saleReturn.setTotalProductPrice(getSumValue(saleReturnItems, ErpSaleReturnItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
saleReturn.setTotalTaxPrice(getSumValue(saleReturnItems, ErpSaleReturnItemDO::getTaxPrice, BigDecimal::add, BigDecimal.ZERO));
saleReturn.setTotalPrice(saleReturn.getTotalProductPrice().add(saleReturn.getTotalTaxPrice()));
// 计算优惠价格
if (saleReturn.getDiscountPercent() == null) {
saleReturn.setDiscountPercent(BigDecimal.ZERO);
}
saleReturn.setDiscountPrice(MoneyUtils.priceMultiplyPercent(saleReturn.getTotalPrice(), saleReturn.getDiscountPercent()));
saleReturn.setTotalPrice(saleReturn.getTotalPrice().subtract(saleReturn.getDiscountPrice()));
// 计算应退金额
BigDecimal allPrice = saleReturn.getTotalPrice().add(saleReturn.getOtherPrice());
saleReturn.setDebtPrice(allPrice.subtract(saleReturn.getRefundPrice()));
}
private void updateSaleOrderReturnCount(Long orderId) {
// 1.1 查询销售订单对应的销售出库单列表
List<ErpSaleReturnDO> saleReturns = saleReturnMapper.selectListByOrderId(orderId);
// 1.2 查询对应的销售订单项的出库数量
Map<Long, BigDecimal> returnCountMap = saleReturnItemMapper.selectOrderItemCountSumMapByReturnIds(
convertList(saleReturns, ErpSaleReturnDO::getId));
// 2. 更新销售订单的出库数量
saleOrderService.updateSaleOrderReturnCount(orderId, returnCountMap);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateSaleReturnStatus(Long id, Integer status) {
boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
// 1.1 校验存在
ErpSaleReturnDO saleReturn = validateSaleReturnExists(id);
// 1.2 校验状态
if (saleReturn.getStatus().equals(status)) {
throw exception(approve ? SALE_RETURN_APPROVE_FAIL : SALE_RETURN_PROCESS_FAIL);
}
// 2. 更新状态
int updateCount = saleReturnMapper.updateByIdAndStatus(id, saleReturn.getStatus(),
new ErpSaleReturnDO().setStatus(status));
if (updateCount == 0) {
throw exception(approve ? SALE_RETURN_APPROVE_FAIL : SALE_RETURN_PROCESS_FAIL);
}
// 3. 变更库存
List<ErpSaleReturnItemDO> saleReturnItems = saleReturnItemMapper.selectListByReturnId(id);
Integer bizType = approve ? ErpStockRecordBizTypeEnum.SALE_RETURN.getType()
: ErpStockRecordBizTypeEnum.SALE_RETURN_CANCEL.getType();
saleReturnItems.forEach(saleReturnItem -> {
BigDecimal count = approve ? saleReturnItem.getCount().negate() : saleReturnItem.getCount();
stockRecordService.createStockRecord(new ErpStockRecordCreateReqBO(
saleReturnItem.getProductId(), saleReturnItem.getWarehouseId(), count,
bizType, saleReturnItem.getReturnId(), saleReturnItem.getId(), saleReturn.getNo()));
});
}
private List<ErpSaleReturnItemDO> validateSaleReturnItems(List<ErpSaleReturnSaveReqVO.Item> list) {
// 1. 校验产品存在
List<ErpProductDO> productList = productService.validProductList(
convertSet(list, ErpSaleReturnSaveReqVO.Item::getProductId));
Map<Long, ErpProductDO> productMap = convertMap(productList, ErpProductDO::getId);
// 2. 转化为 ErpSaleReturnItemDO 列表
return convertList(list, o -> BeanUtils.toBean(o, ErpSaleReturnItemDO.class, item -> {
item.setProductUnitId(productMap.get(item.getProductId()).getUnitId());
item.setTotalPrice(MoneyUtils.priceMultiply(item.getProductPrice(), item.getCount()));
if (item.getTotalPrice() == null) {
return;
}
if (item.getTaxPercent() == null) {
item.setTaxPercent(BigDecimal.ZERO);
} else {
item.setTaxPrice(MoneyUtils.priceMultiplyPercent(item.getTotalPrice(), item.getTaxPercent()));
}
}));
}
private void updateSaleReturnItemList(Long id, List<ErpSaleReturnItemDO> newList) {
// 第一步对比新老数据获得添加修改删除的列表
List<ErpSaleReturnItemDO> oldList = saleReturnItemMapper.selectListByReturnId(id);
List<List<ErpSaleReturnItemDO>> diffList = diffList(oldList, newList, // id 不同就认为是不同的记录
(oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));
// 第二步批量添加修改删除
if (CollUtil.isNotEmpty(diffList.get(0))) {
diffList.get(0).forEach(o -> o.setReturnId(id));
saleReturnItemMapper.insertBatch(diffList.get(0));
}
if (CollUtil.isNotEmpty(diffList.get(1))) {
saleReturnItemMapper.updateBatch(diffList.get(1));
}
if (CollUtil.isNotEmpty(diffList.get(2))) {
saleReturnItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpSaleReturnItemDO::getId));
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteSaleReturn(List<Long> ids) {
// 1. 校验不处于已审批
List<ErpSaleReturnDO> saleReturns = saleReturnMapper.selectBatchIds(ids);
if (CollUtil.isEmpty(saleReturns)) {
return;
}
saleReturns.forEach(saleReturn -> {
if (ErpAuditStatus.APPROVE.getStatus().equals(saleReturn.getStatus())) {
throw exception(SALE_RETURN_DELETE_FAIL_APPROVE, saleReturn.getNo());
}
});
// 2. 遍历删除并记录操作日志
saleReturns.forEach(saleReturn -> {
// 2.1 删除订单
saleReturnMapper.deleteById(saleReturn.getId());
// 2.2 删除订单项
saleReturnItemMapper.deleteByReturnId(saleReturn.getId());
// 2.3 更新销售订单的出库数量
updateSaleOrderReturnCount(saleReturn.getOrderId());
});
}
private ErpSaleReturnDO validateSaleReturnExists(Long id) {
ErpSaleReturnDO saleReturn = saleReturnMapper.selectById(id);
if (saleReturn == null) {
throw exception(SALE_RETURN_NOT_EXISTS);
}
return saleReturn;
}
@Override
public ErpSaleReturnDO getSaleReturn(Long id) {
return saleReturnMapper.selectById(id);
}
@Override
public PageResult<ErpSaleReturnDO> getSaleReturnPage(ErpSaleReturnPageReqVO pageReqVO) {
return saleReturnMapper.selectPage(pageReqVO);
}
// ==================== 销售退货项 ====================
@Override
public List<ErpSaleReturnItemDO> getSaleReturnItemListByReturnId(Long returnId) {
return saleReturnItemMapper.selectListByReturnId(returnId);
}
@Override
public List<ErpSaleReturnItemDO> getSaleReturnItemListByReturnIds(Collection<Long> returnIds) {
if (CollUtil.isEmpty(returnIds)) {
return Collections.emptyList();
}
return saleReturnItemMapper.selectListByReturnIds(returnIds);
}
}