package cn.iocoder.yudao.module.aftersales.service.cancellation;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import cn.iocoder.yudao.module.aftersales.controller.admin.cancellation.vo.AfterSaleCancellationApproveReqVO;
import cn.iocoder.yudao.module.aftersales.controller.admin.cancellation.vo.AfterSaleCancellationSaveReqVO;
import cn.iocoder.yudao.module.aftersales.controller.admin.returnobj.vo.AfterSaleReturnSaveReqVO;
import cn.iocoder.yudao.module.aftersales.dal.dataobject.cancellation.AfterSaleCancellationDO;
import cn.iocoder.yudao.module.aftersales.dal.mysql.cancellation.AfterSaleCancellationMapper;
import cn.iocoder.yudao.module.aftersales.dal.redis.no.AfterSaleNoRedisDAO;
import cn.iocoder.yudao.module.aftersales.service.returnobj.AfterSaleReturnService;
import cn.iocoder.yudao.module.crm.api.contract.CrmContractApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Objects;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.aftersales.enums.ErrorCodeConstants.*;
/**
* 售后统一退单/变更受理。
*
*
把「客户退货、合同变更、合同终止」收敛为同一受理流程,不依赖 ERP 销售订单:
*
* - 退货:审批通过后生成售后退货单(复用 {@link AfterSaleReturnService});
* - 合同终止:审批通过后作废 CRM 合同(status=50);
* - 合同变更:CRM 无「变更中」状态,审批通过仅落地受理记录,变更内容在合同备注或附件体现。
*
* 下游动作执行结果写入 executed / executeRemark,便于失败后人工补做,不静默吞掉错误。
*/
@Slf4j
@Service
public class AfterSaleCancellationService {
/** 状态:0 草稿 1 待审批 2 已通过 3 已驳回 4 已取消 */
private static final int ST_DRAFT = 0;
private static final int ST_PENDING = 1;
private static final int ST_APPROVED = 2;
private static final int ST_REJECTED = 3;
private static final int ST_CANCELLED = 4;
/** CRM 合同作废状态 */
private static final int CRM_CONTRACT_INVALID = 50;
@Resource private AfterSaleCancellationMapper mapper;
@Resource private AfterSaleNoRedisDAO noRedisDAO;
@Resource private AfterSaleReturnService returnService;
@Resource private CrmContractApi crmContractApi;
public PageResult page(PageParam page, String code, String type,
Integer status, Long customerId) {
return mapper.selectPage(page, code, type, status, customerId);
}
public AfterSaleCancellationDO get(Long id) {
AfterSaleCancellationDO row = id == null ? null : mapper.selectById(id);
if (row == null) throw exception(CANCELLATION_NOT_EXISTS);
return row;
}
@Transactional(rollbackFor = Exception.class)
public Long create(AfterSaleCancellationSaveReqVO req, Long userId) {
validateByType(req);
var row = BeanUtils.toBean(req, AfterSaleCancellationDO.class);
row.setStatus(ST_DRAFT);
row.setApplicantId(userId);
row.setExecuted(0);
row.setCode(noRedisDAO.generate(AfterSaleNoRedisDAO.CANCELLATION_NO_PREFIX));
try {
mapper.insert(row);
} catch (DuplicateKeyException e) {
throw exception(CANCELLATION_NOT_EXISTS);
}
return row.getId();
}
@Transactional(rollbackFor = Exception.class)
public void update(AfterSaleCancellationSaveReqVO req) {
AfterSaleCancellationDO old = get(req.getId());
if (!Objects.equals(old.getStatus(), ST_DRAFT)) throw exception(CANCELLATION_UPDATE_FAIL_STATUS);
validateByType(req);
var update = new AfterSaleCancellationDO();
BeanUtils.copyProperties(req, update);
update.setId(old.getId());
update.setCode(old.getCode());
update.setStatus(ST_DRAFT);
mapper.updateById(update);
}
@Transactional(rollbackFor = Exception.class)
public void submit(Long id) {
AfterSaleCancellationDO old = get(id);
if (!Objects.equals(old.getStatus(), ST_DRAFT)) throw exception(CANCELLATION_SUBMIT_FAIL_STATUS);
if (mapper.update(null, new LambdaUpdateWrapper()
.eq(AfterSaleCancellationDO::getId, id)
.eq(AfterSaleCancellationDO::getStatus, ST_DRAFT)
.set(AfterSaleCancellationDO::getStatus, ST_PENDING)) != 1) {
throw exception(CANCELLATION_SUBMIT_FAIL_STATUS);
}
}
@Transactional(rollbackFor = Exception.class)
public void cancel(Long id) {
AfterSaleCancellationDO old = get(id);
if (!Objects.equals(old.getStatus(), ST_DRAFT) && !Objects.equals(old.getStatus(), ST_PENDING)) {
throw exception(CANCELLATION_CANCEL_FAIL_STATUS);
}
if (mapper.update(null, new LambdaUpdateWrapper()
.eq(AfterSaleCancellationDO::getId, id)
.in(AfterSaleCancellationDO::getStatus, ST_DRAFT, ST_PENDING)
.set(AfterSaleCancellationDO::getStatus, ST_CANCELLED)) != 1) {
throw exception(CANCELLATION_CANCEL_FAIL_STATUS);
}
}
public void delete(Long id) {
AfterSaleCancellationDO old = get(id);
if (!Objects.equals(old.getStatus(), ST_DRAFT)) throw exception(CANCELLATION_UPDATE_FAIL_STATUS);
mapper.deleteById(id);
}
@javax.annotation.Nullable
public Long getReturnId(Long id) {
AfterSaleCancellationDO row = mapper.selectById(id);
return row == null ? null : row.getReturnId();
}
/**
* 审批:通过后执行下游动作;驳回必须填意见。
*
* @return 通过时生成的退货单编号(非退货类型为 null)
*/
@Transactional(rollbackFor = Exception.class)
public Long approve(AfterSaleCancellationApproveReqVO req, Long userId) {
if (!Boolean.TRUE.equals(req.getApproved())
&& (req.getRemark() == null || req.getRemark().isBlank())) {
throw exception(CANCELLATION_APPROVE_REMARK_REQUIRED);
}
AfterSaleCancellationDO task = get(req.getId());
if (!Objects.equals(task.getStatus(), ST_PENDING)) throw exception(CANCELLATION_APPROVE_FAIL_STATUS);
int target = Boolean.TRUE.equals(req.getApproved()) ? ST_APPROVED : ST_REJECTED;
if (mapper.update(null, new LambdaUpdateWrapper()
.eq(AfterSaleCancellationDO::getId, task.getId())
.eq(AfterSaleCancellationDO::getStatus, ST_PENDING)
.set(AfterSaleCancellationDO::getStatus, target)
.set(AfterSaleCancellationDO::getApproverId, userId)
.set(AfterSaleCancellationDO::getApprovalTime, LocalDateTime.now())
.set(AfterSaleCancellationDO::getApprovalRemark, req.getRemark())) != 1) {
throw exception(CANCELLATION_APPROVE_FAIL_STATUS);
}
if (!Boolean.TRUE.equals(req.getApproved())) return null;
return executeDownstream(task, userId);
}
/** 审批通过后的下游动作;失败时记录原因但不回滚审批结论,便于人工补做。 */
private Long executeDownstream(AfterSaleCancellationDO task, Long userId) {
Long returnId = null;
String remark;
boolean ok = true;
try {
switch (task.getType()) {
case "RETURN" -> {
var vo = new AfterSaleReturnSaveReqVO();
vo.setTicketId(task.getTicketId());
vo.setCustomerId(task.getCustomerId());
vo.setReturnType(task.getReturnType() == null ? 1 : task.getReturnType());
vo.setReturnReason(task.getReason());
returnId = returnService.createReturn(vo, userId);
remark = "已生成退货单 " + returnId;
}
case "CONTRACT_TERMINATE" -> {
crmContractApi.updateContractStatus(task.getContractId(), CRM_CONTRACT_INVALID).getCheckedData();
remark = "已作废 CRM 合同 " + task.getContractId();
}
case "CONTRACT_CHANGE" -> remark = "变更受理已通过;CRM 合同内容请按附件同步维护";
default -> { ok = false; remark = "未知受理类型:" + task.getType(); }
}
} catch (Exception e) {
ok = false;
remark = "下游执行失败:" + e.getMessage();
log.warn("退单受理[{}]下游动作失败:{}", task.getCode(), e.getMessage());
}
var update = new AfterSaleCancellationDO();
update.setId(task.getId());
update.setExecuted(ok ? 1 : 0);
update.setExecuteRemark(remark);
if (returnId != null) update.setReturnId(returnId);
mapper.updateById(update);
return returnId;
}
/** 按类型校验必填:退货需工单;合同变更/终止需合同。 */
private void validateByType(AfterSaleCancellationSaveReqVO req) {
switch (req.getType()) {
case "RETURN" -> {
if (req.getTicketId() == null) throw exception(CANCELLATION_RETURN_TICKET_REQUIRED);
}
case "CONTRACT_CHANGE", "CONTRACT_TERMINATE" -> {
if (req.getContractId() == null) throw exception(CANCELLATION_CONTRACT_REQUIRED);
}
default -> { }
}
}
}