gongchunyi
11 小时以前 ef7458a6eb8ad72f45b65a4e417a9d04f5015246
src/main/java/com/ruoyi/production/service/impl/ProductMaterialServiceImpl.java
@@ -1,6 +1,5 @@
package com.ruoyi.production.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@@ -8,8 +7,8 @@
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.AliDingConfig;
import com.ruoyi.framework.util.AliDingUtils;
import com.ruoyi.production.dto.ProductMaterialDto;
import com.ruoyi.production.dto.ProductMaterialGroupDto;
import com.ruoyi.production.enums.MaterialConfigTypeEnum;
@@ -25,13 +24,11 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
@@ -85,126 +82,52 @@
        }
        try {
            // 获取 AccessToken
            String accessToken = getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
            JSONArray searchConditions = new JSONArray();
            JSONObject statusCondition = new JSONObject();
            statusCondition.put("key", "processInstanceStatus");
            JSONArray statusValueArray = new JSONArray();
            statusValueArray.add("COMPLETED");
            statusCondition.put("value", statusValueArray);
            statusCondition.put("type", "ARRAY");
            statusCondition.put("operator", "in");
            statusCondition.put("componentName", "SelectField");
            searchConditions.add(statusCondition);
            JSONObject resultCondition = new JSONObject();
            resultCondition.put("key", "processApprovedResult");
            JSONArray resultValueArray = new JSONArray();
            resultValueArray.add("agree");
            resultCondition.put("value", resultValueArray);
            resultCondition.put("type", "ARRAY");
            resultCondition.put("operator", "in");
            resultCondition.put("componentName", "SelectField");
            searchConditions.add(resultCondition);
            String searchFieldJson = searchConditions.toJSONString();
            JSONArray dataArr = AliDingUtils.getFormDataList(aliDingConfig, aliDingConfig.getMaterialCodeFormUuid(), searchFieldJson, productMaterialSkuService, ProductMaterialSku::getFormModifiedTime);
            if (dataArr.isEmpty()) {
                log.info("没有更多新数据需要同步");
                return;
            }
            // 获取本地最后同步时间
            LocalDateTime lastSyncTime = getLastSyncTime();
            log.info("开始物料编码增量同步,本地最后修改时间: {}", lastSyncTime);
            int pageNumber = 1;
            int pageSize = 50;
            boolean hasMore = true;
            int totalSynced = 0;
            while (hasMore) {
                // 查询参数
                JSONObject searchParam = buildSearchParam(lastSyncTime, pageNumber, pageSize);
                // 调用宜搭接口拉取数据
                String dataRes = HttpUtils.sendPostJson(aliDingConfig.getSearchFormDataUrl(), searchParam.toJSONString(), StandardCharsets.UTF_8.name(), null, accessToken);
                if (StringUtils.isEmpty(dataRes)) {
                    log.warn("第 {} 页拉取数据为空", pageNumber);
                    break;
                }
                JSONObject resultObj = JSON.parseObject(dataRes);
                JSONArray dataArr = resultObj.getJSONArray("data");
                Integer totalCount = resultObj.getInteger("totalCount");
                if (dataArr == null || dataArr.isEmpty()) {
                    log.info("没有更多新数据需要同步");
                    break;
                }
                // 解析并保存数据
                List<ProductMaterialSku> list = parseProductMaterials(dataArr, totalCount);
                if (!list.isEmpty()) {
                    // 处理更新或新增
                    int affected = processSaveOrUpdate(list);
                    totalSynced += affected;
                }
                // 判断是否还有下一页
                hasMore = (pageNumber * pageSize) < totalCount;
                pageNumber++;
                log.info("正在同步第 {} 页,当前已同步 {}/{}", pageNumber - 1, totalSynced, totalCount);
            // 解析并保存数据
            List<ProductMaterialSku> list = parseProductMaterials(dataArr, dataArr.size());
            if (!list.isEmpty()) {
                // 处理更新或新增
                int affected = processSaveOrUpdate(list);
                log.info("物料数据同步完成,共同步 {} 条数据", affected);
            }
            log.info("物料数据同步完成,共同步 {} 条数据", totalSynced);
        } catch (Exception e) {
            log.error("同步物料编码异常", e);
        } finally {
            // 释放锁
            syncLock.unlock();
        }
    }
    private String getAccessToken() {
        String params = "appkey=" + aliDingConfig.getAppKey() + "&appsecret=" + aliDingConfig.getAppSecret();
        String tokenRes = HttpUtils.sendGet(aliDingConfig.getAccessTokenUrl(), params);
        JSONObject tokenObj = JSON.parseObject(tokenRes);
        String accessToken = tokenObj.getString("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            log.error("获取钉钉AccessToken失败: {}", tokenRes);
        }
        return accessToken;
    }
    private LocalDateTime getLastSyncTime() {
        LambdaQueryWrapper<ProductMaterialSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ProductMaterialSku::getFormModifiedTime).last("LIMIT 1");
        ProductMaterialSku lastRecord = productMaterialSkuService.getOne(queryWrapper);
        return lastRecord != null ? lastRecord.getFormModifiedTime() : null;
    }
    private JSONObject buildSearchParam(LocalDateTime lastSyncTime, int pageNumber, int pageSize) {
        JSONObject searchParam = new JSONObject();
        searchParam.put("appType", aliDingConfig.getAppType());
        searchParam.put("systemToken", aliDingConfig.getSystemToken());
        searchParam.put("userId", aliDingConfig.getUserId());
        searchParam.put("formUuid", aliDingConfig.getMaterialCodeFormUuid());
        searchParam.put("currentPage", pageNumber);
        searchParam.put("pageSize", pageSize);
        JSONArray searchConditions = new JSONArray();
        JSONObject statusCondition = new JSONObject();
        statusCondition.put("key", "processInstanceStatus");
        JSONArray statusValueArray = new JSONArray();
        statusValueArray.add("COMPLETED");
        statusCondition.put("value", statusValueArray);
        statusCondition.put("type", "ARRAY");
        statusCondition.put("operator", "in");
        statusCondition.put("componentName", "SelectField");
        searchConditions.add(statusCondition);
        JSONObject resultCondition = new JSONObject();
        resultCondition.put("key", "processApprovedResult");
        JSONArray resultValueArray = new JSONArray();
        resultValueArray.add("agree");
        resultCondition.put("value", resultValueArray);
        resultCondition.put("type", "ARRAY");
        resultCondition.put("operator", "in");
        resultCondition.put("componentName", "SelectField");
        searchConditions.add(resultCondition);
        searchParam.put("searchFieldJson", searchConditions.toJSONString());
        searchParam.put("orderConfigJson", "{\"gmt_modified\":\"+\"}");
        if (lastSyncTime != null) {
            String startTime = lastSyncTime.plusSeconds(1).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            searchParam.put("modifiedFromTimeGMT", startTime);
        }
        String endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        searchParam.put("modifiedToTimeGMT", endTime);
        return searchParam;
    }
    private List<ProductMaterialSku> parseProductMaterials(JSONArray dataArr, Integer totalCount) {
@@ -241,7 +164,7 @@
            sku.setSupplyType(formData.getString("selectField_la14k51j"));
            sku.setOriginatorName(originatorName);
            sku.setOriginatorOrg("宁夏中创绿能实业集团有限公司");
            sku.setFormModifiedTime(parseUtcTime(item.getString("modifiedTimeGMT")));
            sku.setFormModifiedTime(AliDingUtils.parseUtcTime(item.getString("modifiedTimeGMT")));
            sku.setCreateTime(now);
            sku.setUpdateTime(now);
@@ -334,86 +257,84 @@
        return affected;
    }
    private LocalDateTime parseUtcTime(String utcString) {
        if (StringUtils.isEmpty(utcString)) {
            return null;
        }
        try {
            OffsetDateTime odt = OffsetDateTime.parse(utcString);
            return odt.toLocalDateTime();
        } catch (DateTimeParseException ex) {
            log.warn("解析时间 {} 失败: {}", utcString, ex.getMessage());
            return null;
        }
    }
    @Override
    public List<ProductMaterialGroupDto> ProductMaterialList() {
        List<ProductMaterialConfig> materialConfigList = productMaterialConfigService.list(new LambdaQueryWrapper<ProductMaterialConfig>()
                .eq(ProductMaterialConfig::getConfigType, MaterialConfigTypeEnum.MATERIAL_TYPE.name()));
        List<ProductMaterialGroupDto> productMaterialMap = new ArrayList<>();
        if (materialConfigList == null || materialConfigList.isEmpty()) {
            return productMaterialMap;
    public List<ProductMaterialGroupDto> ProductMaterialList(Integer type) {
        List<ProductMaterialConfig> configList = productMaterialConfigService.list(new LambdaQueryWrapper<ProductMaterialConfig>()
                .eq(ProductMaterialConfig::getConfigType, MaterialConfigTypeEnum.MATERIAL_TYPE.name())
        );
        if (CollectionUtils.isEmpty(configList)) {
            return new ArrayList<>();
        }
        for (ProductMaterialConfig materialConfig : materialConfigList) {
        List<ProductMaterialGroupDto> result = new ArrayList<>();
        Map<Integer, List<ProductMaterialDto>> materialMap = new HashMap<>();
        if (type != null && type == 2) {
            List<ProductMaterial> materialList = this.list(new LambdaQueryWrapper<ProductMaterial>()
                    .select(
                            ProductMaterial::getId,
                            ProductMaterial::getMaterialTypeId,
                            ProductMaterial::getInventoryCategoryId,
                            ProductMaterial::getMaterialName
                    )
            );
            materialMap = materialList.stream()
                    .map(this::convert)
                    .collect(Collectors.groupingBy(ProductMaterialDto::getMaterialTypeId));
        }
        for (ProductMaterialConfig config : configList) {
            ProductMaterialGroupDto dto = new ProductMaterialGroupDto();
            dto.setConfigId(materialConfig.getId());
            dto.setConfigName(materialConfig.getConfigName());
            productMaterialMap.add(dto);
            dto.setConfigId(config.getId());
            dto.setConfigName(config.getConfigName());
            if (type != null && type == 2) {
                dto.setMaterialList(materialMap.getOrDefault(config.getId(), new ArrayList<>()));
            }
            result.add(dto);
        }
        return productMaterialMap;
        return result;
    }
    @Override
    public List<ProductMaterialGroupDto> productMaterialListByQuery(String materialName, Integer materialTypeId) {
        if (StringUtils.isEmpty(materialName) && materialTypeId == null) {
            return new ArrayList<>(0);
            return new ArrayList<>();
        }
        // 查询物料类型配置
        List<ProductMaterialConfig> materialConfigList = productMaterialConfigService.list(new LambdaQueryWrapper<ProductMaterialConfig>()
        LambdaQueryWrapper<ProductMaterial> wrapper = new LambdaQueryWrapper<>();
        //  只查询需要的字段数据
        wrapper.select(
                ProductMaterial::getId,
                ProductMaterial::getMaterialTypeId,
                ProductMaterial::getInventoryCategoryId,
                ProductMaterial::getMaterialName
        );
        if (StringUtils.isNotEmpty(materialName)) {
            wrapper.like(ProductMaterial::getMaterialName, materialName);
        }
        if (materialTypeId != null) {
            wrapper.eq(ProductMaterial::getMaterialTypeId, materialTypeId);
        }
        List<ProductMaterial> materials = this.list(wrapper);
        if (CollectionUtils.isEmpty(materials)) {
            return new ArrayList<>();
        }
        Map<Integer, List<ProductMaterialDto>> map = materials.stream()
                .map(this::convert)
                .collect(Collectors.groupingBy(ProductMaterialDto::getMaterialTypeId));
        List<ProductMaterialConfig> configList = productMaterialConfigService.list(new LambdaQueryWrapper<ProductMaterialConfig>()
                .eq(ProductMaterialConfig::getConfigType, MaterialConfigTypeEnum.MATERIAL_TYPE.name()));
        List<ProductMaterialGroupDto> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(materialConfigList)) {
            return result;
        }
        LambdaQueryWrapper<ProductMaterial> wrapper;
        for (ProductMaterialConfig materialConfig : materialConfigList) {
            wrapper = new LambdaQueryWrapper<>();
            //  指定需要的字段
            wrapper.select(
                    ProductMaterial::getId,
                    ProductMaterial::getMaterialTypeId,
                    ProductMaterial::getInventoryCategoryId,
                    ProductMaterial::getMaterialName
            );
            if (StringUtils.isNotEmpty(materialName)) {
                wrapper.eq(ProductMaterial::getMaterialTypeId, materialConfig.getId())
                        .like(ProductMaterial::getMaterialName, materialName);
            } else {
                if (!materialConfig.getId().equals(materialTypeId)) {
                    continue;
                }
                wrapper.eq(ProductMaterial::getMaterialTypeId, materialTypeId);
            }
            List<ProductMaterial> materialList = list(wrapper);
            if (CollectionUtils.isEmpty(materialList)) {
        for (ProductMaterialConfig config : configList) {
            List<ProductMaterialDto> dtoList = map.get(config.getId());
            if (CollectionUtils.isEmpty(dtoList)) {
                continue;
            }
            List<ProductMaterialDto> dtoList = materialList.stream().map(m -> {
                ProductMaterialDto dto = new ProductMaterialDto();
                dto.setId(m.getId());
                dto.setMaterialTypeId(m.getMaterialTypeId());
                dto.setInventoryCategoryId(m.getInventoryCategoryId());
                dto.setMaterialName(m.getMaterialName());
                return dto;
            }).collect(Collectors.toList());
            ProductMaterialGroupDto dto = new ProductMaterialGroupDto();
            dto.setConfigId(materialConfig.getId());
            dto.setConfigName(materialConfig.getConfigName());
            dto.setConfigId(config.getId());
            dto.setConfigName(config.getConfigName());
            dto.setMaterialList(dtoList);
            result.add(dto);
        }
@@ -421,6 +342,15 @@
        return result;
    }
    private ProductMaterialDto convert(ProductMaterial m) {
        ProductMaterialDto dto = new ProductMaterialDto();
        dto.setId(m.getId());
        dto.setMaterialName(m.getMaterialName());
        dto.setMaterialTypeId(m.getMaterialTypeId());
        dto.setInventoryCategoryId(m.getInventoryCategoryId());
        return dto;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProductMaterial(ProductMaterial productMaterial) {