SettlementDiffServiceImpl.java 9.15 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.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vion.dto.SettlementDiffDTO;
import vion.mapper.SettlementDiffMapper;
import vion.model.Contract;
import vion.model.FileInfo;
import vion.model.SettlementDiff;
import vion.service.IContractPaymentService;
import vion.service.IContractService;
import vion.service.IFileService;
import vion.service.ISettlementDiffService;
import vion.vo.SettlementDiffVO;
import vion.vo.UserVO;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author HlQ
 * @date 2023/12/25
 */
@Service
@RequiredArgsConstructor
public class SettlementDiffServiceImpl extends MPJBaseServiceImpl<SettlementDiffMapper, SettlementDiff> implements ISettlementDiffService {

    private final IContractService contractService;
    private final IContractPaymentService contractPaymentService;
    private final IFileService fileService;
    private final Converter converter;

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

    @Override
    public Page<SettlementDiffVO> list(String no, SettlementDiffDTO dto) {
        Page<SettlementDiff> diffPage = this.lambdaQuery(converter.convert(dto, SettlementDiff.class))
                .eq(SettlementDiff::getContractNo, no)
                .page(Page.of(dto.getPageNum(), dto.getPageSize()));
        List<SettlementDiffVO> voList = converter.convert(diffPage.getRecords(), SettlementDiffVO.class);
        return Page.<SettlementDiffVO>of(diffPage.getCurrent(), diffPage.getSize(), diffPage.getTotal()).setRecords(voList);
    }

    @Override
    public SettlementDiffVO getVOById(Long id) {
        return converter.convert(this.getById(id), SettlementDiffVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(SettlementDiffDTO dto) {
        SettlementDiff settlementDiff = converter.convert(dto, SettlementDiff.class);
        if (this.save(settlementDiff)) {
            BigDecimal diffAmount = settlementDiff.getSettlementDiff();

            // 余额 = 总合同额 - 已收 + 差异
            // 应收 = 总合同额 * 比例 + 差异  (冲抵项为应收)
            //     = (总合同额 + 差异) * 比例 (冲抵项为合同额)
            Contract existContract = contractService.lambdaQuery().eq(Contract::getContractNo, settlementDiff.getContractNo()).one();
            if (settlementDiff.getOffsetItem() == 1) {
                existContract.setTotalAmount(NumberUtil.add(existContract.getTotalAmount(), diffAmount));
                Contract contractDto = new Contract();
                contractDto.setId(existContract.getId());
                contractPaymentService.calMoney(existContract, contractDto);
                contractService.updateById(contractDto);
            } else if (settlementDiff.getOffsetItem() == 2) {
                Contract contractDto = new Contract();
                contractDto.setId(existContract.getId());
                contractDto.setReceivableAmount(NumberUtil.add(existContract.getReceivableAmount(), diffAmount));
                contractDto.setOutstandingAmount(NumberUtil.add(existContract.getOutstandingAmount(), diffAmount));
                contractService.updateById(contractDto);
            }
            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 + "settlementDiff" + FileUtil.FILE_SEPARATOR + dto.getContractNo() + 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(settlementDiff.getId());
                            fileInfo.setContractId(dto.getContractId());
                            fileInfo.setSourceType(15);
                            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 "新增成功";
        }
        return "新增失败";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(Long id, SettlementDiffDTO dto) {
        SettlementDiff settlementDiff = converter.convert(dto, SettlementDiff.class);
        if (this.updateById(settlementDiff)) {
            SettlementDiff existDiff = this.getById(id);
            BigDecimal diffAmount = existDiff.getSettlementDiff();

            // 余额 = 总合同额 - 已收 + 差异
            // 应收 = 总合同额 * 比例 + 差异  (冲抵项为应收)
            //     = (总合同额 + 差异) * 比例 (冲抵项为合同额)
            Contract existContract = contractService.lambdaQuery().eq(Contract::getContractNo, existDiff.getContractNo()).one();
            if (existDiff.getOffsetItem() == 1) {
                existContract.setTotalAmount(NumberUtil.add(existContract.getTotalAmount(), diffAmount));
                Contract contractDto = new Contract();
                contractDto.setId(existContract.getId());
                contractPaymentService.calMoney(existContract, contractDto);
                contractService.updateById(contractDto);
            } else if (existDiff.getOffsetItem() == 2) {
                Contract contractDto = new Contract();
                contractDto.setId(existContract.getId());
                contractDto.setReceivableAmount(NumberUtil.add(existContract.getReceivableAmount(), diffAmount));
                contractDto.setOutstandingAmount(NumberUtil.add(existContract.getOutstandingAmount(), diffAmount));
                contractService.updateById(contractDto);
            }

            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 + "settlementDiff" + FileUtil.FILE_SEPARATOR + dto.getContractNo() + 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(id);
                            fileInfo.setContractId(dto.getContractId());
                            fileInfo.setSourceType(15);
                            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 "更新成功";
        }
        return "更新失败";
    }
}