DeliveryRecordServiceImpl.java 10.7 KB
package vion.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import vion.dto.ContractDTO;
import vion.dto.DeliveryRecordDTO;
import vion.mapper.DeliveryRecordMapper;
import vion.model.*;
import vion.service.*;
import vion.third.DingMod;
import vion.vo.DeliveryRecordVO;
import vion.vo.UserVO;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HlQ
 * @date 2023/12/5
 */
@Service
@RequiredArgsConstructor
public class DeliveryRecordServiceImpl extends MPJBaseServiceImpl<DeliveryRecordMapper, DeliveryRecord> implements IDeliveryRecordService {

    private final IFileService fileService;
    private final IContractService contractService;
    private final IRContractUserService contractUserService;
    private final IPointInfoService pointInfoService;
    private final DingMod dingMod;
    private final RedisTemplate redisTemplate;
    private final Converter converter;

    @Value("${fileUrl:}")
    private String fileUrl;

    @Override
    public Page<DeliveryRecordVO> list(DeliveryRecordDTO dto) {
        MPJLambdaWrapper<DeliveryRecord> wrapper = new MPJLambdaWrapper<>(converter.convert(dto, DeliveryRecord.class))
                .selectAll(DeliveryRecord.class)
                .selectAs(Contract::getName, DeliveryRecordVO::getContractName)
                .selectAs(Contract::getCustomerName, DeliveryRecordVO::getCustomerName)
                .leftJoin(Contract.class, Contract::getContractNo, DeliveryRecord::getContractNo)
                .like(StrUtil.isNotBlank(dto.getContractName()), Contract::getName, dto.getContractName())
                .like(StrUtil.isNotBlank(dto.getCustomerName()), Contract::getCustomerName, dto.getCustomerName())
                .orderByDesc(DeliveryRecord::getCreateTime);
        Page<DeliveryRecordVO> voPage = this.selectJoinListPage(Page.of(dto.getPageNum(), dto.getPageSize()), DeliveryRecordVO.class, wrapper);
        Opt.ofEmptyAble(voPage.getRecords())
                .map(recs -> recs.stream().map(DeliveryRecordVO::getId).collect(Collectors.toList()))
                .map(ids -> {
                    List<FileInfo> fileInfos = fileService.lambdaQuery().in(FileInfo::getSourceId, ids).eq(FileInfo::getSourceType, 6).list();
                    return fileInfos.stream().collect(Collectors.groupingBy(FileInfo::getSourceId));
                })
                .filter(MapUtil::isNotEmpty)
                .ifPresent(map -> voPage.getRecords().forEach(rec -> rec.setFileList(map.get(rec.getId()))));
        return voPage;
    }

    @Override
    public String save(DeliveryRecordDTO dto) {
        DeliveryRecord record = converter.convert(dto, DeliveryRecord.class);
        if (this.save(record)) {
            updStatusAndPushMsg(record);

            Opt.ofNullable(dto.getFiles())
                    .ifPresent(fileList -> {
                        UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");

                        Arrays.stream(fileList).forEach(infile -> {
                            String orgName = infile.getOriginalFilename();
                            String mainName = FileUtil.mainName(orgName);
                            String fileExt = FileUtil.extName(orgName);
                            String filename = StrUtil.format("{}_{}.{}", mainName, DateUtil.format(new Date(), "yyyyMMdd_HHmmss"), fileExt);
                            String path = fileUrl + FileUtil.FILE_SEPARATOR + "delivery" + FileUtil.FILE_SEPARATOR + dto.getContractId() + FileUtil.FILE_SEPARATOR + record.getId() + FileUtil.FILE_SEPARATOR + filename;
                            File file = FileUtil.touch(path);
                            try {
                                infile.transferTo(file);
                            } catch (IOException e) {
                                log.error("保存文件出错", e);
                            }

                            FileInfo fileInfo = new FileInfo();
                            fileInfo.setStoreId(0L);
                            fileInfo.setSourceId(record.getId());
                            fileInfo.setContractId(dto.getContractId());
                            fileInfo.setSourceType(6);
                            fileInfo.setName(filename);
                            fileInfo.setUrl(path);
                            fileInfo.setType(FileUtil.extName(file));
                            fileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                            fileInfo.setUploader(userVO.getUsername());
                            fileService.save(fileInfo);
                        });
                    });
            return "新增成功";
        } else {
            return "新增失败";
        }
    }

    @Override
    public String saveBatch(List<DeliveryRecordDTO> dto) {
        List<DeliveryRecord> records = converter.convert(dto, DeliveryRecord.class);
        if (this.saveBatch(records)) {
            records.forEach(record -> updStatusAndPushMsg(record));
            return "新增成功";
        } else {
            return "新增失败";
        }
    }

    private void updStatusAndPushMsg(DeliveryRecord record) {
        ContractDTO contractDTO = new ContractDTO();
        contractDTO.setStatus(2);
        Contract existContract = contractService.lambdaQuery().eq(Contract::getContractNo, record.getContractNo()).one();
        if (existContract.getStatus() < 2) {
            contractService.updateById(null, record.getContractNo(), contractDTO);
        }
        // 更新点位信息的发货状态
        pointInfoService.lambdaUpdate().set(PointInfo::getShippingStatus, 1)
                .set(PointInfo::getCourierCompany, record.getCourierCompany())
                .set(PointInfo::getTrackingNumber, record.getTrackingNumber())
                .set(PointInfo::getStatus, 9)
                .eq(PointInfo::getContractNo, record.getContractNo()).update(new PointInfo());

        Opt.ofNullable(pointInfoService.lambdaQuery().eq(PointInfo::getContractNo, record.getContractNo()).one())
                .ifPresent(p -> pointInfoService.designPush(null, p, "发货"));

        List<String> useridList = contractUserService.listObjs(Wrappers.<RContractUser>lambdaQuery().select(RContractUser::getUserId).eq(RContractUser::getContractId, existContract.getId()), Object::toString);
        Opt.ofNullable(((User) redisTemplate.opsForValue().get("dingtalk:user:name:" + existContract.getSaleName())))
                .map(User::getUserid)
                .ifPresent(useridList::add);
        dingMod.sendMessage(buildMsg(useridList.stream().distinct().collect(Collectors.joining(",")), record, existContract));
    }

    JSONObject buildMsg(String userid, DeliveryRecord rec, Contract contract) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.set("agent_id", 2358374016L);
        jsonObj.set("userid_list", userid);

        JSONObject msg = new JSONObject();
        JSONObject content = new JSONObject();
        content.set("title", "设备发货提醒");
        String markdown = StrUtil.format("#### 发货通知" +
                        "  \n  #### 合同名称:{}" +
                        "  \n  #### 合同编号:{}" +
                        "  \n  #### 快递公司:{}" +
                        "  \n  #### 快递单号:{}" +
                        "  \n  #### 收件人:{}" +
                        "  \n  #### 发货日期:{}" +
                        "  \n  #### 发送时间:{}",
                contract.getName(), contract.getContractNo(), rec.getCourierCompany(), rec.getTrackingNumber(), rec.getConsignee(), DateUtil.formatDate(rec.getShipDate()), DateUtil.now());
        content.set("text", markdown);

        msg.set("msgtype", "markdown");
        msg.set("markdown", content);
        jsonObj.set("msg", msg);
        return jsonObj;
    }

    @Override
    public String updateById(DeliveryRecordDTO dto) {
        DeliveryRecord record = converter.convert(dto, DeliveryRecord.class);
        if (this.updateById(record)) {
            DeliveryRecord deliveryRecord = this.getById(dto.getId());
            Opt.ofNullable(dto.getFiles())
                    .ifPresent(fileList -> {
                        UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");

                        Arrays.stream(fileList).forEach(infile -> {
                            String orgName = infile.getOriginalFilename();
                            String mainName = FileUtil.mainName(orgName);
                            String fileExt = FileUtil.extName(orgName);
                            String filename = StrUtil.format("{}_{}.{}", mainName, DateUtil.format(new Date(), "yyyyMMdd_HHmmss"), fileExt);
                            String path = fileUrl + FileUtil.FILE_SEPARATOR + "delivery" + FileUtil.FILE_SEPARATOR + deliveryRecord.getContractId() + FileUtil.FILE_SEPARATOR + record.getId() + FileUtil.FILE_SEPARATOR + filename;
                            File file = FileUtil.touch(path);
                            try {
                                infile.transferTo(file);
                            } catch (IOException e) {
                                log.error("保存文件出错", e);
                            }

                            FileInfo fileInfo = new FileInfo();
                            fileInfo.setStoreId(0L);
                            fileInfo.setSourceId(record.getId());
                            fileInfo.setContractId(deliveryRecord.getContractId());
                            fileInfo.setSourceType(6);
                            fileInfo.setName(filename);
                            fileInfo.setUrl(path);
                            fileInfo.setType(FileUtil.extName(file));
                            fileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                            fileInfo.setUploader(userVO.getUsername());
                            fileService.save(fileInfo);
                        });
                    });
            return "更新成功";
        } else {
            return "更新失败";
        }
    }
}