From 2656ae9bce8544d81da66c07aaede5386d6fbebb Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期五, 25 七月 2025 15:41:01 +0800
Subject: [PATCH] 1.序列化问题 2.设备领用逻辑优化

---
 main-business/src/main/java/com/ruoyi/business/service/impl/SalesRecordServiceImpl.java |  206 +++++++++++++++++++++++++++++++++++++++++++++------
 1 files changed, 180 insertions(+), 26 deletions(-)

diff --git a/main-business/src/main/java/com/ruoyi/business/service/impl/SalesRecordServiceImpl.java b/main-business/src/main/java/com/ruoyi/business/service/impl/SalesRecordServiceImpl.java
index 2f162a7..da90280 100644
--- a/main-business/src/main/java/com/ruoyi/business/service/impl/SalesRecordServiceImpl.java
+++ b/main-business/src/main/java/com/ruoyi/business/service/impl/SalesRecordServiceImpl.java
@@ -4,6 +4,7 @@
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.ruoyi.basic.entity.CoalInfo;
@@ -17,11 +18,16 @@
 import com.ruoyi.business.mapper.OfficialInventoryMapper;
 import com.ruoyi.business.mapper.SalesRecordMapper;
 import com.ruoyi.business.service.SalesRecordService;
+import com.ruoyi.business.vo.SalesRecordExportVo;
 import com.ruoyi.common.core.domain.entity.SysUser;
 import com.ruoyi.common.exception.base.BaseException;
+import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.bean.BeanUtils;
+import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.system.mapper.SysUserMapper;
+import jakarta.servlet.http.HttpServletResponse;
 import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -33,13 +39,9 @@
 import java.time.format.DateTimeFormatter;
 import java.time.format.DateTimeParseException;
 import java.time.temporal.TemporalAdjusters;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 import java.util.function.Function;
 import java.util.stream.Collectors;
-import java.util.*;
 
 /**
  * <p>
@@ -50,6 +52,7 @@
  * @since 2025-06-11
  */
 @Service
+@Slf4j
 @RequiredArgsConstructor
 public class SalesRecordServiceImpl extends ServiceImpl<SalesRecordMapper, SalesRecord> implements SalesRecordService {
 
@@ -67,6 +70,29 @@
     public IPage<SalesRecordDto> selectSalesRecordList(Page<SalesRecord> page, SalesRecordDto salesRecordDto) {
         // 1. 鍒涘缓鏌ヨ鏉′欢锛屾寜鍒涘缓鏃堕棿鍊掑簭鎺掑簭
         LambdaQueryWrapper<SalesRecord> queryWrapper = new LambdaQueryWrapper<>();
+
+        // 鎸夋棩鏈熸煡璇�
+        if (salesRecordDto.getSaleDate() != null) {
+            queryWrapper.eq(SalesRecord::getSaleDate, salesRecordDto.getSaleDate());
+        }
+
+        // 鎸夌叅绉嶅悕绉版煡璇�
+        if (StringUtils.isNotBlank(salesRecordDto.getCoal())) {
+            LambdaQueryWrapper<CoalInfo> coalQueryWrapper = new LambdaQueryWrapper<>();
+            coalQueryWrapper.like(CoalInfo::getCoal, salesRecordDto.getCoal());
+            List<CoalInfo> coalInfos = coalInfoMapper.selectList(coalQueryWrapper);
+
+            if (!coalInfos.isEmpty()) {
+                List<Long> coalIds = coalInfos.stream()
+                        .map(CoalInfo::getId)
+                        .collect(Collectors.toList());
+                queryWrapper.in(SalesRecord::getCoalId, coalIds);
+            } else {
+                // 濡傛灉娌℃湁鍖归厤鐨勭叅绉嶏紝鐩存帴杩斿洖绌虹粨鏋�
+                queryWrapper.eq(SalesRecord::getCoalId, -1L); // 浣跨敤涓嶅彲鑳藉瓨鍦ㄧ殑ID
+            }
+        }
+
         queryWrapper.orderByDesc(SalesRecord::getCreateTime);
 
         // 2. 鑾峰彇鍒嗛〉鐨勯攢鍞褰�
@@ -122,20 +148,20 @@
         // 鍙傛暟鏍¢獙
         validateSalesRecordDto(salesRecordDto);
 
-        // 鏇存柊姝e紡搴撳緟琛ュ簱鏁伴噺
+        // 鑾峰彇鐓ょ搴撳瓨淇℃伅
         OfficialInventory officialInventory = officialInventoryMapper.selectById(salesRecordDto.getCoalId());
         if (officialInventory == null) {
             throw new BaseException("姝e紡搴撶叅绉嶄俊鎭笉瀛樺湪");
         }
-        if (salesRecordDto.getSaleQuantity().compareTo(officialInventory.getInventoryQuantity()) > 0) {
-            throw new BaseException("閿�鍞暟閲忎笉鑳藉ぇ浜庡簱瀛樻暟閲�");
-        }
-        officialInventory.setInventoryQuantity(officialInventory.getInventoryQuantity().subtract(salesRecordDto.getSaleQuantity()));
-        officialInventory.setPendingReplenishment(salesRecordDto.getSaleQuantity());
-        officialInventoryMapper.updateById(officialInventory);
+
+        // 澶勭悊閿�鍞暟閲忓彉鏇撮�昏緫
+        SalesRecord existingRecord = salesRecordDto.getId() == null ? null : salesRecordMapper.selectById(salesRecordDto.getId());
+        handleQuantityChanges(salesRecordDto, officialInventory, existingRecord);
 
         // 鏋勫缓閿�鍞褰曞疄浣�
         SalesRecord salesRecord = buildSalesRecord(salesRecordDto, officialInventory.getCoalId());
+        // 璁剧疆閿�鍞褰曚腑鐨勫簱瀛樻暟閲�
+        salesRecord.setInventoryQuantity(officialInventory.getInventoryQuantity());
 
         // 澶勭悊鏂板/鏇存柊閫昏緫
         if (salesRecordDto.getId() == null) {
@@ -145,18 +171,52 @@
         }
     }
 
-    private void validateSalesRecordDto(SalesRecordDto dto) {
-        if (dto == null) {
-            throw new BaseException("閿�鍞褰曟暟鎹笉鑳戒负绌�");
+    private void handleQuantityChanges(SalesRecordDto dto, OfficialInventory officialInventory, SalesRecord existingRecord) {
+        if (existingRecord == null) {
+            // 鏂板璁板綍
+            if (dto.getSaleQuantity().compareTo(officialInventory.getInventoryQuantity()) > 0) {
+                throw new BaseException("閿�鍞暟閲忎笉鑳藉ぇ浜庡簱瀛樻暟閲�");
+            }
+            // 鏇存柊搴撳瓨鏁伴噺
+            officialInventory.setInventoryQuantity(officialInventory.getInventoryQuantity().subtract(dto.getSaleQuantity()));
+            // 璁剧疆寰呰ˉ搴撴暟閲�
+            if (dto.isAdd()) {
+                officialInventory.setPendingReplenishment(
+                        officialInventory.getPendingReplenishment() == null ?
+                                dto.getSaleQuantity() :
+                                officialInventory.getPendingReplenishment().add(dto.getSaleQuantity())
+                );
+            }
+        } else {
+            // 鏇存柊璁板綍
+            // 姣旇緝閿�鍞暟閲忔槸鍚︽湁鍙樺寲
+            int quantityComparison = dto.getSaleQuantity().compareTo(existingRecord.getSaleQuantity());
+            if (quantityComparison != 0) {
+                // 璁$畻鏁伴噺宸��
+                BigDecimal quantityDiff = dto.getSaleQuantity().subtract(existingRecord.getSaleQuantity());
+
+                // 妫�鏌ユ柊鏁伴噺鏄惁浼氬鑷村簱瀛樹笉瓒�
+                if (quantityComparison > 0 && quantityDiff.compareTo(officialInventory.getInventoryQuantity()) > 0) {
+                    throw new BaseException("閿�鍞暟閲忓鍔犲悗涓嶈兘澶т簬搴撳瓨鏁伴噺");
+                }
+
+                // 鏇存柊搴撳瓨鏁伴噺
+                officialInventory.setInventoryQuantity(officialInventory.getInventoryQuantity().subtract(quantityDiff));
+
+                // 鏇存柊寰呰ˉ搴撴暟閲忥紙濡傛灉鏄渶瑕佽ˉ搴撶殑璁板綍锛�
+                if (dto.isAdd()) {
+                    BigDecimal pendingDiff = officialInventory.getPendingReplenishment() == null ?
+                            quantityDiff :
+                            officialInventory.getPendingReplenishment().add(quantityDiff);
+                    officialInventory.setPendingReplenishment(pendingDiff);
+                }
+            }
         }
-        if (dto.getRegistrantId() == null) {
-            throw new BaseException("鐧昏浜篒D涓嶈兘涓虹┖");
-        }
-        if (dto.getCustomerId() == null) {
-            throw new BaseException("瀹㈡埛ID涓嶈兘涓虹┖");
-        }
-        if (dto.getCoalId() == null) {
-            throw new BaseException("璇烽�夋嫨涓�鏉$叅绉嶄俊鎭�");
+
+        // 鏇存柊搴撳瓨璁板綍
+        int updateResult = officialInventoryMapper.updateById(officialInventory);
+        if (updateResult <= 0) {
+            throw new BaseException("搴撳瓨鏇存柊澶辫触");
         }
     }
 
@@ -169,7 +229,7 @@
         if (registrant == null) {
             throw new BaseException("鐧昏浜轰俊鎭笉瀛樺湪");
         }
-        record.setRegistrant(registrant.getUserName());
+        record.setRegistrant(registrant.getNickName());
 
         // 璁剧疆瀹㈡埛淇℃伅
         Customer customer = customerMapper.selectById(dto.getCustomerId());
@@ -200,6 +260,21 @@
         return record;
     }
 
+    private void validateSalesRecordDto(SalesRecordDto dto) {
+        if (dto == null) {
+            throw new BaseException("閿�鍞褰曟暟鎹笉鑳戒负绌�");
+        }
+        if (dto.getRegistrantId() == null) {
+            throw new BaseException("鐧昏浜篒D涓嶈兘涓虹┖");
+        }
+        if (dto.getCustomerId() == null) {
+            throw new BaseException("瀹㈡埛ID涓嶈兘涓虹┖");
+        }
+        if (dto.getCoalId() == null) {
+            throw new BaseException("璇烽�夋嫨涓�鏉$叅绉嶄俊鎭�");
+        }
+    }
+
     private int insertSalesRecord(SalesRecord record) {
         int result = salesRecordMapper.insert(record);
         if (result <= 0) {
@@ -228,6 +303,59 @@
                 .set("deleted", 1);  // 璁剧疆 deleted 涓� 1 琛ㄧず宸插垹闄�
         // 鎵ц鎵归噺閫昏緫鍒犻櫎
         return salesRecordMapper.update(null, updateWrapper);
+    }
+
+    @Override
+    public void salesRecordExport(HttpServletResponse response, SalesRecordDto salesRecordDto) {
+        List<Long> ids = salesRecordDto.getExportIds();
+        List<SalesRecord> list;
+        if (ids != null && !ids.isEmpty()) {
+            list = salesRecordMapper.selectByIds(ids);
+        } else {
+            list = salesRecordMapper.selectList(null);
+        }
+        List<SalesRecordExportVo> exportData = convertToExportVo(list);
+        ExcelUtil<SalesRecordExportVo> util = new ExcelUtil<>(SalesRecordExportVo.class);
+        util.exportExcel(response, exportData, "閿�鍞嚭搴撴暟鎹�");
+    }
+
+    private List<SalesRecordExportVo> convertToExportVo(List<SalesRecord> list) {
+        // 1. 鎻愬墠鏀堕泦鎵�鏈夐渶瑕佹煡璇㈢殑coalId锛岄伩鍏峃+1鏌ヨ闂
+        Set<Long> coalIds = list.stream()
+                .filter(Objects::nonNull)
+                .map(SalesRecord::getCoalId)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toSet());
+
+        // 2. 鎵归噺鏌ヨcoalInfo鏁版嵁
+        Map<Long, CoalInfo> coalInfoMap = CollectionUtils.isEmpty(coalIds)
+                ? Collections.emptyMap()
+                : coalInfoMapper.selectByIds(coalIds).stream()
+                .filter(Objects::nonNull)
+                .collect(Collectors.toMap(CoalInfo::getId, Function.identity()));
+
+        // 3. 杞崲鏁版嵁
+        return list.stream()
+                .filter(Objects::nonNull)
+                .map(record -> {
+                    try {
+                        SalesRecordExportVo vo = new SalesRecordExportVo();
+
+                        // 鎷疯礉鍩虹灞炴��
+                        BeanUtils.copyProperties(record, vo);
+
+                        // 璁剧疆鍏宠仈鐨刢oal淇℃伅
+                        Optional.ofNullable(record.getCoalId())
+                                .map(coalInfoMap::get)
+                                .ifPresent(coalInfo -> vo.setCoal(coalInfo.getCoal()));
+                        return vo;
+                    } catch (Exception e) {
+                        log.error("杞崲閿�鍞褰昖O寮傚父锛岃褰旾D: {}", record.getId(), e);
+                        return null;
+                    }
+                })
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
     }
 
     @Override
@@ -482,7 +610,7 @@
 
         // 4. 鎵归噺鏌ヨ鐓ょ淇℃伅骞跺~鍏呭埌缁撴灉涓�
         if (!coalIds.isEmpty()) {
-            List<CoalInfo> coalInfos = coalInfoMapper.selectBatchIds(coalIds);
+            List<CoalInfo> coalInfos = coalInfoMapper.selectByIds(coalIds);
             for (CoalInfo coalInfo : coalInfos) {
                 Map<String, Object> record = resultMap.get(coalInfo.getId());
                 if (record != null) {
@@ -491,8 +619,33 @@
             }
         }
 
-        // 鏈�缁堢粨鏋滄槸涓�涓狶ist<Map>锛屾瘡涓狹ap鍖呭惈鍚堝苟鍚庣殑閿�鍞暟鎹拰瀵瑰簲鐨勭叅绉嶄俊鎭�
         List<Map<String, Object>> results = new ArrayList<>(resultMap.values());
+
+        //鏈堝害鏁版嵁
+        //鏌ヨ鎵�鏈夌叅绉嶄俊鎭�
+        List<CoalInfo> allCoalTypes = coalInfoMapper.selectList(
+                new QueryWrapper<CoalInfo>().orderByAsc("id")
+        );
+        //棰勮绠楅攢閲忥細鎸塩oalId鍒嗙粍缁熻鎬婚攢閲�
+        Map<Long, BigDecimal> salesByCoalId = salesRecords.stream()
+                .collect(Collectors.groupingBy(
+                        SalesRecord::getCoalId,
+                        Collectors.reducing(
+                                BigDecimal.ZERO,
+                                SalesRecord::getSaleQuantity,
+                                BigDecimal::add
+                        )
+                ));
+
+        // 2. 鍒涘缓 resultMouth锛屽瓨鍌ㄧ叅绉嶅強鍏堕攢閲忥紙Map 缁撴瀯锛�
+        Map<String, BigDecimal> resultMouthMap = new LinkedHashMap<>();
+        for (CoalInfo coal : allCoalTypes) {
+            resultMouthMap.put(
+                    coal.getCoal(),  // 鐓ょ鍚嶇О锛堝 "鏃犵儫鐓�"锛�
+                    salesByCoalId.getOrDefault(coal.getId(), BigDecimal.valueOf(0)) // 閿�閲�
+            );
+        }
+
         result.put("revenueAmount", revenueAmount.setScale(2, RoundingMode.HALF_UP));
         result.put("changeRate", changeRate);
         result.put("trend", trend);
@@ -501,6 +654,7 @@
         result.put("trendQuantity", trendQuantity);
         result.put("revenueDistribution", revenueDistribution);
         result.put("salesResults", results);
+        result.put("resultMouth", resultMouthMap);
 
         return result;
     }

--
Gitblit v1.9.3