From 4b61be20efa8cdc1a9086b07a2fdc16725c55099 Mon Sep 17 00:00:00 2001
From: chenrui <1187576398@qq.com>
Date: 星期二, 27 五月 2025 11:01:36 +0800
Subject: [PATCH] 销售台账功能修改

---
 src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java |  391 ++++++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 340 insertions(+), 51 deletions(-)

diff --git a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
index 52ec03e..08189ff 100644
--- a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -3,27 +3,40 @@
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.ruoyi.basic.mapper.CustomerMapper;
 import com.ruoyi.basic.pojo.Customer;
 import com.ruoyi.common.exception.base.BaseException;
 import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.other.mapper.TempFileMapper;
+import com.ruoyi.other.pojo.TempFile;
+import com.ruoyi.sales.dto.MonthlyAmountDto;
 import com.ruoyi.sales.dto.SalesLedgerDto;
-import com.ruoyi.sales.mapper.SalesLedgerMapper;
-import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
-import com.ruoyi.sales.pojo.SalesLedger;
-import com.ruoyi.sales.pojo.SalesLedgerProduct;
+import com.ruoyi.sales.mapper.*;
+import com.ruoyi.sales.pojo.*;
 import com.ruoyi.sales.service.ISalesLedgerService;
-import lombok.AllArgsConstructor;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FilenameUtils;
 import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.script.DefaultRedisScript;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import java.io.IOException;
 import java.lang.reflect.Field;
 import java.math.BigDecimal;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
 import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.YearMonth;
 import java.time.format.DateTimeFormatter;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
@@ -37,14 +50,29 @@
  * @date 2025-05-08
  */
 @Service
-@AllArgsConstructor
+@RequiredArgsConstructor
+@Slf4j
 public class SalesLedgerServiceImpl extends ServiceImpl<SalesLedgerMapper, SalesLedger> implements ISalesLedgerService {
 
-    private SalesLedgerMapper salesLedgerMapper;
+    private final SalesLedgerMapper salesLedgerMapper;
 
-    private CustomerMapper customerMapper;
+    private final CustomerMapper customerMapper;
 
-    private SalesLedgerProductMapper salesLedgerProductMapper;
+    private final SalesLedgerProductMapper salesLedgerProductMapper;
+
+    private final CommonFileMapper commonFileMapper;
+
+    private final TempFileMapper tempFileMapper;
+
+    private final ReceiptPaymentMapper receiptPaymentMapper;
+
+    private final InvoiceLedgerMapper invoiceLedgerMapper;
+
+    @Autowired
+    private InvoiceRegistrationProductMapper invoiceRegistrationProductMapper;
+
+    @Value("${file.upload-dir}")
+    private String uploadDir;
 
     private static final String LOCK_PREFIX = "contract_no_lock:";
     private static final long LOCK_WAIT_TIMEOUT = 10; // 閿佺瓑寰呰秴鏃舵椂闂达紙绉掞級
@@ -54,11 +82,7 @@
 
     @Override
     public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
-        LambdaQueryWrapper<SalesLedger> queryWrapper = new LambdaQueryWrapper<>();
-        if (StringUtils.isNotBlank(salesLedgerDto.getCustomerName())) {
-            queryWrapper.eq(SalesLedger::getCustomerName, salesLedgerDto.getCustomerName());
-        }
-        return salesLedgerMapper.selectList(queryWrapper);
+        return salesLedgerMapper.selectSalesLedgerList(salesLedgerDto);
     }
 
     public SalesLedgerDto getSalesLedgerWithProducts(SalesLedgerDto salesLedgerDto) {
@@ -72,15 +96,195 @@
         LambdaQueryWrapper<SalesLedgerProduct> productWrapper = new LambdaQueryWrapper<>();
         productWrapper.eq(SalesLedgerProduct::getSalesLedgerId, salesLedger.getId());
         List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
+        for (SalesLedgerProduct product : products) {
+            product.setOriginalNoInvoiceNum(product.getNoInvoiceNum());
+        }
 
-        // 3. 杞崲 DTO
+        // 3.鏌ヨ涓婁紶鏂囦欢
+        LambdaQueryWrapper<CommonFile> salesLedgerFileWrapper = new LambdaQueryWrapper<>();
+        salesLedgerFileWrapper.eq(CommonFile::getCommonId, salesLedger.getId());
+        List<CommonFile> salesLedgerFiles = commonFileMapper.selectList(salesLedgerFileWrapper);
+
+        // 4. 杞崲 DTO
         SalesLedgerDto resultDto = new SalesLedgerDto();
         BeanUtils.copyProperties(salesLedger, resultDto);
         if (!products.isEmpty()) {
             resultDto.setHasChildren(true);
             resultDto.setProductData(products);
+            resultDto.setSalesLedgerFiles(salesLedgerFiles);
         }
         return resultDto;
+    }
+
+    @Override
+    public List<Map<String, Object>> getSalesNo() {
+        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.select(SalesLedger::getId, SalesLedger::getSalesContractNo);
+
+        // 鑾峰彇鍘熷鏌ヨ缁撴灉
+        List<Map<String, Object>> result = salesLedgerMapper.selectMaps(queryWrapper);
+
+        // 灏嗕笅鍒掔嚎鍛藉悕杞崲涓洪┘宄板懡鍚�
+        return result.stream().map(map -> map.entrySet().stream()
+                .collect(Collectors.toMap(
+                        entry -> underlineToCamel(entry.getKey()),
+                        Map.Entry::getValue))
+        ).collect(Collectors.toList());
+    }
+
+    @Override
+    public BigDecimal getContractAmount() {
+        LocalDate now = LocalDate.now();
+        YearMonth currentMonth = YearMonth.from(now);
+
+        // 鍒涘缓LambdaQueryWrapper
+        LambdaQueryWrapper<SalesLedger> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.ge(SalesLedger::getEntryDate, currentMonth.atDay(1).atStartOfDay())  // 澶т簬绛変簬鏈湀绗竴澶�
+                .lt(SalesLedger::getEntryDate, currentMonth.plusMonths(1).atDay(1).atStartOfDay()); // 灏忎簬涓嬫湀绗竴澶�
+
+        // 鎵ц鏌ヨ骞惰绠楁�诲拰
+        List<SalesLedger> salesLedgers = salesLedgerMapper.selectList(queryWrapper);
+
+        BigDecimal totalContractAmount = salesLedgers.stream()
+                .map(SalesLedger::getContractAmount)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+        return totalContractAmount;
+    }
+
+    @Override
+    public List getTopFiveList() {
+        // 鏌ヨ鍘熷鏁版嵁
+        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.select(SalesLedger::getCustomerId,
+                        SalesLedger::getCustomerName,
+                        SalesLedger::getContractAmount)
+                .orderByDesc(SalesLedger::getContractAmount);
+        List<SalesLedger> records = salesLedgerMapper.selectList(queryWrapper);
+
+        // 鎸夊鎴稩D鍒嗙粍骞惰仛鍚堥噾棰�
+        Map<Long, GroupedCustomer> groupedMap = new LinkedHashMap<>(); // 浣跨敤LinkedHashMap淇濇寔鎺掑簭
+        for (SalesLedger record : records) {
+            groupedMap.computeIfAbsent(record.getCustomerId(),
+                            k -> new GroupedCustomer(record.getCustomerId(), record.getCustomerName()))
+                    .addAmount(record.getContractAmount());
+        }
+
+        // 杞崲涓虹粨鏋滃垪琛ㄥ苟鍙栧墠5
+        return groupedMap.values().stream()
+                .sorted(Comparator.comparing(GroupedCustomer::getTotalAmount).reversed())
+                .limit(5)
+                .map(customer -> {
+                    Map<String, Object> result = new HashMap<>();
+                    result.put("customerId", customer.getCustomerId());
+                    result.put("customerName", customer.getCustomerName());
+                    result.put("totalAmount", customer.getTotalAmount());
+                    return result;
+                })
+                .collect(Collectors.toList());
+    }
+
+    @Override
+    public List<MonthlyAmountDto> getAmountHalfYear() {
+        LocalDate now = LocalDate.now();
+        YearMonth currentMonth = YearMonth.from(now);
+
+        List<MonthlyAmountDto> monthlyAmounts = new ArrayList<>();
+
+        for (int i = 0; i < 6; i++) {
+            YearMonth targetMonth = currentMonth.minusMonths(i);
+            LocalDate firstDayOfMonth = targetMonth.atDay(1);
+            LocalDate firstDayOfNextMonth = targetMonth.plusMonths(1).atDay(1);
+
+            LocalDateTime startOfMonth = firstDayOfMonth.atStartOfDay();
+            LocalDateTime startOfNextMonth = firstDayOfNextMonth.atStartOfDay();
+
+            LambdaQueryWrapper<ReceiptPayment> receiptPaymentLambdaQueryWrapper = new LambdaQueryWrapper<>();
+            receiptPaymentLambdaQueryWrapper.ge(ReceiptPayment::getCreateTime, startOfMonth)
+                    .lt(ReceiptPayment::getCreateTime, startOfNextMonth);
+
+            LambdaQueryWrapper<InvoiceLedger> invoiceLedgerLambdaQueryWrapper = new LambdaQueryWrapper<>();
+            invoiceLedgerLambdaQueryWrapper.ge(InvoiceLedger::getCreateTime, startOfMonth)
+                    .lt(InvoiceLedger::getCreateTime, startOfNextMonth);
+
+            // 鑾峰彇鍥炴閲戦
+            List<ReceiptPayment> receiptPaymentList = receiptPaymentMapper.selectList(receiptPaymentLambdaQueryWrapper);
+            //寮�绁ㄩ噾棰�
+            List<InvoiceLedger> invoiceLedgerList = invoiceLedgerMapper.selectList(invoiceLedgerLambdaQueryWrapper);
+
+            // 浣跨敤 Stream 姹傚拰
+            BigDecimal invoiceAmount = invoiceLedgerList.stream()
+                    .map(InvoiceLedger::getInvoiceTotal)
+                    .filter(Objects::nonNull)
+                    .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+            BigDecimal receiptAmount = receiptPaymentList.stream()
+                    .map(ReceiptPayment::getReceiptPaymentAmount)
+                    .filter(Objects::nonNull)
+                    .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+            MonthlyAmountDto monthlyAmount = new MonthlyAmountDto();
+            monthlyAmount.setMonth(targetMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")));
+            monthlyAmount.setInvoiceAmount(invoiceAmount);
+            monthlyAmount.setReceiptAmount(receiptAmount);
+
+            monthlyAmounts.add(monthlyAmount);
+        }
+        Collections.reverse(monthlyAmounts);
+        return monthlyAmounts;
+    }
+
+    // 鍐呴儴绫荤敤浜庡瓨鍌ㄨ仛鍚堢粨鏋�
+    private static class GroupedCustomer {
+        private final Long customerId;
+        private final String customerName;
+        private BigDecimal totalAmount = BigDecimal.ZERO;
+
+        public GroupedCustomer(Long customerId, String customerName) {
+            this.customerId = customerId;
+            this.customerName = customerName;
+        }
+
+        public void addAmount(BigDecimal amount) {
+            if (amount != null) {
+                this.totalAmount = this.totalAmount.add(amount);
+            }
+        }
+
+        public Long getCustomerId() {
+            return customerId;
+        }
+
+        public String getCustomerName() {
+            return customerName;
+        }
+
+        public BigDecimal getTotalAmount() {
+            return totalAmount;
+        }
+    }
+
+    /**
+     * 涓嬪垝绾垮懡鍚嶈浆椹煎嘲鍛藉悕
+     */
+    private String underlineToCamel(String param) {
+        if (param == null || "".equals(param.trim())) {
+            return "";
+        }
+        int len = param.length();
+        StringBuilder sb = new StringBuilder(len);
+        for (int i = 0; i < len; i++) {
+            char c = param.charAt(i);
+            if (c == '_') {
+                if (++i < len) {
+                    sb.append(Character.toUpperCase(param.charAt(i)));
+                }
+            } else {
+                sb.append(Character.toLowerCase(c));
+            }
+        }
+        return sb.toString();
     }
 
     @Override
@@ -102,47 +306,128 @@
         return salesLedgerMapper.deleteBatchIds(idList);
     }
 
+    @Override
     @Transactional(rollbackFor = Exception.class)
     public int addOrUpdateSalesLedger(SalesLedgerDto salesLedgerDto) {
-        // 1. 鏍¢獙瀹㈡埛淇℃伅
-        Customer customer = customerMapper.selectById(salesLedgerDto.getCustomerId());
-        if (customer == null) {
-            throw new BaseException("瀹㈡埛涓嶅瓨鍦�");
+        try {
+            // 1. 鏍¢獙瀹㈡埛淇℃伅
+            Customer customer = customerMapper.selectById(salesLedgerDto.getCustomerId());
+            if (customer == null) {
+                throw new BaseException("瀹㈡埛涓嶅瓨鍦�");
+            }
+
+            // 2. DTO杞珽ntity
+            SalesLedger salesLedger = convertToEntity(salesLedgerDto);
+            salesLedger.setCustomerName(customer.getCustomerName());
+            salesLedger.setTenantId(customer.getTenantId());
+
+            // 3. 鏂板鎴栨洿鏂颁富琛�
+            if (salesLedger.getId() == null) {
+                String contractNo = generateSalesContractNo();
+                salesLedger.setSalesContractNo(contractNo);
+                salesLedgerMapper.insert(salesLedger);
+            } else {
+                salesLedgerMapper.updateById(salesLedger);
+            }
+
+            // 4. 澶勭悊瀛愯〃鏁版嵁
+            List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
+            if (productList != null && !productList.isEmpty()) {
+                handleSalesLedgerProducts(salesLedger.getId(), productList, salesLedgerDto.getType());
+                updateMainContractAmount(
+                        salesLedger.getId(),
+                        productList,
+                        SalesLedgerProduct::getTaxInclusiveTotalPrice,
+                        salesLedgerMapper,
+                        SalesLedger.class
+                );
+            }
+
+            // 5. 杩佺Щ涓存椂鏂囦欢鍒版寮忕洰褰�
+            if (salesLedgerDto.getTempFileIds() != null && !salesLedgerDto.getTempFileIds().isEmpty()) {
+                migrateTempFilesToFormal(salesLedger.getId(), salesLedgerDto.getTempFileIds());
+            }
+            return 1;
+        } catch (IOException e) {
+            throw new BaseException("鏂囦欢杩佺Щ澶辫触: " + e.getMessage());
         }
-
-        // 2. DTO杞珽ntity
-        SalesLedger salesLedger = convertToEntity(salesLedgerDto);
-        salesLedger.setCustomerName(customer.getCustomerName());
-        salesLedger.setTenantId(customer.getTenantId());
-
-        // 3. 鏂板鎴栨洿鏂颁富琛�
-        if (salesLedger.getId() == null) {
-            // 鐢熸垚鍚堝悓缂栧彿
-            String contractNo = generateSalesContractNo();
-            salesLedger.setSalesContractNo(contractNo);
-            salesLedgerMapper.insert(salesLedger);
-        } else {
-            salesLedgerMapper.updateById(salesLedger);
-        }
-
-        // 4. 澶勭悊瀛愯〃鏁版嵁
-        List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
-        if (productList != null && !productList.isEmpty()) {
-            handleSalesLedgerProducts(salesLedger.getId(), productList);
-
-            // 鉁� 璋冪敤閫氱敤鏂规硶鏇存柊涓昏〃閲戦
-            updateMainContractAmount(
-                    salesLedger.getId(),
-                    productList,
-                    SalesLedgerProduct::getTaxInclusiveTotalPrice,
-                    salesLedgerMapper,
-                    SalesLedger.class
-            );
-        }
-        return 1; // 鎿嶄綔鎴愬姛杩斿洖1
     }
 
-    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products) {
+    // 鏂囦欢杩佺Щ鏂规硶
+
+    /**
+     * 灏嗕复鏃舵枃浠惰縼绉诲埌姝e紡鐩綍
+     *
+     * @param businessId  涓氬姟ID锛堥攢鍞彴璐D锛�
+     * @param tempFileIds 涓存椂鏂囦欢ID鍒楄〃
+     * @throws IOException 鏂囦欢鎿嶄綔寮傚父
+     */
+    private void migrateTempFilesToFormal(Long businessId, List<String> tempFileIds) throws IOException {
+        if (CollectionUtils.isEmpty(tempFileIds)) {
+            return;
+        }
+
+        // 鏋勫缓姝e紡鐩綍璺緞锛堟寜涓氬姟绫诲瀷鍜屾棩鏈熷垎缁勶級
+        String formalDir = uploadDir + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
+
+        Path formalDirPath = Paths.get(formalDir);
+
+        // 纭繚姝e紡鐩綍瀛樺湪锛堥�掑綊鍒涘缓锛�
+        if (!Files.exists(formalDirPath)) {
+            Files.createDirectories(formalDirPath);
+        }
+
+        for (String tempFileId : tempFileIds) {
+            // 鏌ヨ涓存椂鏂囦欢璁板綍
+            TempFile tempFile = tempFileMapper.selectById(tempFileId);
+            if (tempFile == null) {
+                log.warn("涓存椂鏂囦欢涓嶅瓨鍦紝璺宠繃澶勭悊: {}", tempFileId);
+                continue;
+            }
+
+            // 鏋勫缓姝e紡鏂囦欢鍚嶏紙鍖呭惈涓氬姟ID鍜屾椂闂存埑锛岄伩鍏嶅啿绐侊級
+            String originalFilename = tempFile.getOriginalName();
+            String fileExtension = FilenameUtils.getExtension(originalFilename);
+            String formalFilename = businessId + "_" +
+                    System.currentTimeMillis() + "_" +
+                    UUID.randomUUID().toString().substring(0, 8) +
+                    (StringUtils.hasText(fileExtension) ? "." + fileExtension : "");
+
+            Path formalFilePath = formalDirPath.resolve(formalFilename);
+
+            try {
+                // 鎵ц鏂囦欢杩佺Щ锛堜娇鐢ㄥ師瀛愭搷浣滅‘淇濆畨鍏ㄦ�э級
+                Files.move(
+                        Paths.get(tempFile.getTempPath()),
+                        formalFilePath,
+                        StandardCopyOption.REPLACE_EXISTING,
+                        StandardCopyOption.ATOMIC_MOVE
+                );
+                log.info("鏂囦欢杩佺Щ鎴愬姛: {} -> {}", tempFile.getTempPath(), formalFilePath);
+
+                // 鏇存柊鏂囦欢璁板綍锛堝叧鑱斿埌涓氬姟ID锛�
+                CommonFile fileRecord = new CommonFile();
+                fileRecord.setCommonId(businessId);
+                fileRecord.setName(originalFilename);
+                fileRecord.setUrl(formalFilePath.toString());
+                fileRecord.setCreateTime(LocalDateTime.now());
+                fileRecord.setType("1");
+                commonFileMapper.insert(fileRecord);
+
+                // 鍒犻櫎涓存椂鏂囦欢璁板綍
+                tempFileMapper.deleteById(tempFile);
+
+                log.info("鏂囦欢杩佺Щ鎴愬姛: {} -> {}", tempFile.getTempPath(), formalFilePath);
+            } catch (IOException e) {
+                log.error("鏂囦欢杩佺Щ澶辫触: {}", tempFile.getTempPath(), e);
+                // 鍙�夋嫨鍥炴粴浜嬪姟鎴栬褰曞け璐ユ枃浠�
+                throw new IOException("鏂囦欢杩佺Щ寮傚父", e);
+            }
+        }
+    }
+
+
+    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products, Integer type) {
         // 鎸塈D鍒嗙粍锛屽尯鍒嗘柊澧炲拰鏇存柊鐨勮褰�
         Map<Boolean, List<SalesLedgerProduct>> partitionedProducts = products.stream()
                 .peek(p -> p.setSalesLedgerId(salesLedgerId))
@@ -154,12 +439,16 @@
         // 鎵ц鏇存柊鎿嶄綔
         if (!updateList.isEmpty()) {
             for (SalesLedgerProduct product : updateList) {
+                product.setType(type);
                 salesLedgerProductMapper.updateById(product);
             }
         }
         // 鎵ц鎻掑叆鎿嶄綔
         if (!insertList.isEmpty()) {
             for (SalesLedgerProduct salesLedgerProduct : insertList) {
+                salesLedgerProduct.setType(type);
+                salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity().intValue());
+                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
                 salesLedgerProductMapper.insert(salesLedgerProduct);
             }
         }

--
Gitblit v1.9.3