From dac03b5ff8efb1b733d37dce7553ed0aff32c780 Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期五, 09 五月 2025 17:47:02 +0800
Subject: [PATCH] 1.销售台账合同金额(所有产品含税总价)

---
 src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java |  257 +++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 239 insertions(+), 18 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 769cfe9..52ec03e 100644
--- a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -1,15 +1,34 @@
 package com.ruoyi.sales.service.impl;
 
 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.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.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.service.ISalesLedgerService;
-import org.springframework.beans.factory.annotation.Autowired;
+import lombok.AllArgsConstructor;
+import org.springframework.beans.BeanUtils;
+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.util.Arrays;
-import java.util.List;
+import java.lang.reflect.Field;
+import java.math.BigDecimal;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 
 /**
  * 閿�鍞彴璐ervice涓氬姟灞傚鐞�
@@ -18,32 +37,234 @@
  * @date 2025-05-08
  */
 @Service
+@AllArgsConstructor
 public class SalesLedgerServiceImpl extends ServiceImpl<SalesLedgerMapper, SalesLedger> implements ISalesLedgerService {
-    @Autowired
+
     private SalesLedgerMapper salesLedgerMapper;
 
+    private CustomerMapper customerMapper;
+
+    private SalesLedgerProductMapper salesLedgerProductMapper;
+
+    private static final String LOCK_PREFIX = "contract_no_lock:";
+    private static final long LOCK_WAIT_TIMEOUT = 10; // 閿佺瓑寰呰秴鏃舵椂闂达紙绉掞級
+    private static final long LOCK_EXPIRE_TIME = 30;  // 閿佽嚜鍔ㄨ繃鏈熸椂闂达紙绉掞級
+
+    private final RedisTemplate<String, String> redisTemplate;
+
     @Override
-    public List<SalesLedger> selectSalesLedgerList(SalesLedger salesLedger) {
-        return salesLedgerMapper.selectList(new LambdaQueryWrapper<>());
+    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);
+    }
+
+    public SalesLedgerDto getSalesLedgerWithProducts(SalesLedgerDto salesLedgerDto) {
+        // 1. 鏌ヨ涓昏〃
+        SalesLedger salesLedger = salesLedgerMapper.selectById(salesLedgerDto.getId());
+        if (salesLedger == null) {
+            throw new BaseException("鍙拌处涓嶅瓨鍦�");
+        }
+
+        // 2. 鏌ヨ瀛愯〃
+        LambdaQueryWrapper<SalesLedgerProduct> productWrapper = new LambdaQueryWrapper<>();
+        productWrapper.eq(SalesLedgerProduct::getSalesLedgerId, salesLedger.getId());
+        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
+
+        // 3. 杞崲 DTO
+        SalesLedgerDto resultDto = new SalesLedgerDto();
+        BeanUtils.copyProperties(salesLedger, resultDto);
+        if (!products.isEmpty()) {
+            resultDto.setHasChildren(true);
+            resultDto.setProductData(products);
+        }
+        return resultDto;
     }
 
     @Override
-    public SalesLedger selectSalesLedgerById(Long id) {
-        return salesLedgerMapper.selectById(id);
-    }
-
-    @Override
+    @Transactional(rollbackFor = Exception.class)
     public int deleteSalesLedgerByIds(Long[] ids) {
-        return salesLedgerMapper.deleteBatchIds(Arrays.asList(ids));
+        List<Long> idList = Arrays.stream(ids)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+
+        if (CollectionUtils.isEmpty(idList)) {
+            return 0;
+        }
+        // 1. 鍏堝垹闄ゅ瓙琛ㄦ暟鎹�
+        LambdaQueryWrapper<SalesLedgerProduct> productWrapper = new LambdaQueryWrapper<>();
+        productWrapper.in(SalesLedgerProduct::getSalesLedgerId, idList);
+        salesLedgerProductMapper.delete(productWrapper);
+
+        // 2. 鍐嶅垹闄や富琛ㄦ暟鎹�
+        return salesLedgerMapper.deleteBatchIds(idList);
     }
 
-    @Override
-    public int insertSalesLedger(SalesLedger salesLedger) {
-        return salesLedgerMapper.insert(salesLedger);
+    @Transactional(rollbackFor = Exception.class)
+    public int addOrUpdateSalesLedger(SalesLedgerDto salesLedgerDto) {
+        // 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);
+
+            // 鉁� 璋冪敤閫氱敤鏂规硶鏇存柊涓昏〃閲戦
+            updateMainContractAmount(
+                    salesLedger.getId(),
+                    productList,
+                    SalesLedgerProduct::getTaxInclusiveTotalPrice,
+                    salesLedgerMapper,
+                    SalesLedger.class
+            );
+        }
+        return 1; // 鎿嶄綔鎴愬姛杩斿洖1
     }
 
-    @Override
-    public int updateSalesLedger(SalesLedger salesLedger) {
-        return salesLedgerMapper.updateById(salesLedger);
+    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products) {
+        // 鎸塈D鍒嗙粍锛屽尯鍒嗘柊澧炲拰鏇存柊鐨勮褰�
+        Map<Boolean, List<SalesLedgerProduct>> partitionedProducts = products.stream()
+                .peek(p -> p.setSalesLedgerId(salesLedgerId))
+                .collect(Collectors.partitioningBy(p -> p.getId() != null));
+
+        List<SalesLedgerProduct> updateList = partitionedProducts.get(true);
+        List<SalesLedgerProduct> insertList = partitionedProducts.get(false);
+
+        // 鎵ц鏇存柊鎿嶄綔
+        if (!updateList.isEmpty()) {
+            for (SalesLedgerProduct product : updateList) {
+                salesLedgerProductMapper.updateById(product);
+            }
+        }
+        // 鎵ц鎻掑叆鎿嶄綔
+        if (!insertList.isEmpty()) {
+            for (SalesLedgerProduct salesLedgerProduct : insertList) {
+                salesLedgerProductMapper.insert(salesLedgerProduct);
+            }
+        }
+    }
+
+    private SalesLedger convertToEntity(SalesLedgerDto dto) {
+        SalesLedger entity = new SalesLedger();
+        BeanUtils.copyProperties(dto, entity);
+        return entity;
+    }
+
+    @Transactional(readOnly = true)
+    public String generateSalesContractNo() {
+        LocalDate currentDate = LocalDate.now();
+        String datePart = currentDate.format(DateTimeFormatter.BASIC_ISO_DATE);
+        String lockKey = LOCK_PREFIX + datePart;
+        String lockValue = Thread.currentThread().getId() + "-" + System.nanoTime(); // 鍞竴鏍囪瘑閿佹寔鏈夎��
+
+        try {
+            // 1. 灏濊瘯鑾峰彇鍒嗗竷寮忛攣锛堝惊鐜洿鍒拌秴鏃讹級
+            long startWaitTime = System.currentTimeMillis();
+            while (System.currentTimeMillis() - startWaitTime < LOCK_WAIT_TIMEOUT * 1000) {
+                // SET key value NX PX 30000锛氫粎褰撻攣涓嶅瓨鍦ㄦ椂鑾峰彇锛岃缃�30绉掕繃鏈�
+                Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, LOCK_EXPIRE_TIME, TimeUnit.SECONDS);
+                if (Boolean.TRUE.equals(locked)) {
+                    break; // 鎴愬姛鑾峰彇閿�
+                }
+                // 鐭殏浼戠湢閬垮厤蹇欑瓑寰�
+                try {
+                    Thread.sleep(100);
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new RuntimeException("鑾峰彇閿佹椂琚腑鏂�", e);
+                }
+            }
+
+            if (!redisTemplate.hasKey(lockKey)) {
+                throw new RuntimeException("鑾峰彇鍚堝悓缂栧彿鐢熸垚閿佸け璐ワ細瓒呮椂");
+            }
+
+            // 2. 鏌ヨ褰撳ぉ宸插瓨鍦ㄧ殑搴忓垪鍙凤紙涓庡師閫昏緫涓�鑷达級
+            List<Integer> existingSequences = salesLedgerMapper.selectSequencesByDate(datePart);
+            int nextSequence = findFirstMissingSequence(existingSequences);
+
+            return datePart + String.format("%02d", nextSequence);
+        } finally {
+            // 3. 閲婃斁閿侊紙浣跨敤Lua鑴氭湰淇濊瘉鍘熷瓙鎬э紝閬垮厤璇垹鍏朵粬绾跨▼鐨勯攣锛�
+            String luaScript = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
+            redisTemplate.execute(
+                    new DefaultRedisScript<>(luaScript, Long.class),
+                    Collections.singletonList(lockKey),
+                    lockValue // 鍙湁鎸佹湁鐩稿悓鍊肩殑绾跨▼鎵嶈兘鍒犻櫎閿�
+            );
+        }
+    }
+
+    private int findFirstMissingSequence(List<Integer> sequences) {
+        if (sequences.isEmpty()) {
+            return 1;
+        }
+        // 鎺掑簭鍚庢煡鎵剧涓�涓己澶辩殑姝f暣鏁帮紙涓庡師閫昏緫涓�鑷达級
+        sequences.sort(Integer::compareTo);
+        int next = 1;
+        for (int seq : sequences) {
+            if (seq == next) {
+                next++;
+            } else if (seq > next) {
+                break;
+            }
+        }
+        return next;
+    }
+
+    public <T, S> void updateMainContractAmount(
+            Long mainId,
+            List<T> subList,
+            Function<T, BigDecimal> amountGetter,
+            BaseMapper<S> mainMapper,
+            Class<S> mainEntityClass) {
+
+        if (mainId == null || subList == null || subList.isEmpty()) {
+            return;
+        }
+
+        // 璁$畻瀛愯〃閲戦鎬诲拰
+        BigDecimal totalAmount = subList.stream()
+                .map(amountGetter)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+        // 鏋勯�犱富琛ㄦ洿鏂板璞★紙鏀寔浠绘剰涓昏〃绫诲瀷锛�
+        try {
+            S entity = mainEntityClass.getDeclaredConstructor().newInstance();
+            Field idField = mainEntityClass.getDeclaredField("id");
+            idField.setAccessible(true);
+            idField.set(entity, mainId);
+
+            // 璁剧疆 contractAmount 瀛楁锛屾敞鎰忚繖閲屽亣璁惧瓧娈靛悕涓� "contractAmount"
+            Field amountField = mainEntityClass.getDeclaredField("contractAmount");
+            amountField.setAccessible(true);
+            amountField.set(entity, totalAmount);
+
+            mainMapper.updateById(entity);
+        } catch (Exception e) {
+            throw new RuntimeException("鍔ㄦ�佹洿鏂颁富琛ㄩ噾棰濆け璐�", e);
+        }
     }
 }

--
Gitblit v1.9.3