From 423ac2a5e7e451248d8cdfc2cda3f32dba0ec8f8 Mon Sep 17 00:00:00 2001
From: gongchunyi <deslre0381@gmail.com>
Date: 星期三, 11 三月 2026 17:59:52 +0800
Subject: [PATCH] feat: 生产计划关联物料信息表

---
 src/main/java/com/ruoyi/production/service/impl/ProductMaterialServiceImpl.java |  306 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 306 insertions(+), 0 deletions(-)

diff --git a/src/main/java/com/ruoyi/production/service/impl/ProductMaterialServiceImpl.java b/src/main/java/com/ruoyi/production/service/impl/ProductMaterialServiceImpl.java
new file mode 100644
index 0000000..7367dc7
--- /dev/null
+++ b/src/main/java/com/ruoyi/production/service/impl/ProductMaterialServiceImpl.java
@@ -0,0 +1,306 @@
+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;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.http.HttpUtils;
+import com.ruoyi.framework.config.AliDingConfig;
+import com.ruoyi.production.enums.MaterialConfigTypeEnum;
+import com.ruoyi.production.mapper.ProductMaterialMapper;
+import com.ruoyi.production.pojo.ProductMaterial;
+import com.ruoyi.production.pojo.ProductMaterialConfig;
+import com.ruoyi.production.service.ProductMaterialConfigService;
+import com.ruoyi.production.service.ProductMaterialService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+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.ArrayList;
+import java.util.List;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * <br>
+ * 浜у搧鐗╂枡淇℃伅鎺ュ彛瀹炵幇绫�
+ * </br>
+ *
+ * @author deslrey
+ * @version 1.0
+ * @since 2026/03/11 16:36
+ */
+@Slf4j
+@Service
+public class ProductMaterialServiceImpl extends ServiceImpl<ProductMaterialMapper, ProductMaterial> implements ProductMaterialService {
+
+    @Autowired
+    private AliDingConfig aliDingConfig;
+
+    @Autowired
+    private ProductMaterialConfigService productMaterialConfigService;
+
+    /**
+     * 鍚屾閿侊紝闃叉鎵嬪姩鍜屽畾鏃朵换鍔″悓鏃舵墽琛�
+     */
+    private final ReentrantLock syncLock = new ReentrantLock();
+
+    @Override
+    public void loadProductMaterialData() {
+        syncProductMaterialData(1);
+    }
+
+    @Override
+    public void syncProductMaterialJob() {
+        syncProductMaterialData(2);
+    }
+
+    /**
+     * 鍚屾鏁版嵁
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public void syncProductMaterialData(Integer dataSyncType) {
+        if (!syncLock.tryLock()) {
+            log.warn("鍚屾姝e湪杩涜涓紝鏈 {} 鍚屾璇锋眰琚烦杩�", dataSyncType == 1 ? "鎵嬪姩" : "瀹氭椂浠诲姟");
+            return;
+        }
+
+        try {
+            // 鑾峰彇 AccessToken
+            String accessToken = getAccessToken();
+            if (StringUtils.isEmpty(accessToken)) {
+                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;
+                }
+
+                // 瑙f瀽骞朵繚瀛樻暟鎹�
+                List<ProductMaterial> list = parseProductMaterials(dataArr, totalCount);
+                if (!list.isEmpty()) {
+                    // 澶勭悊鏇存柊鎴栨柊澧�
+                    int affected = processSaveOrUpdate(list);
+                    totalSynced += affected;
+                }
+
+                // 鍒ゆ柇鏄惁杩樻湁涓嬩竴椤�
+                hasMore = (pageNumber * pageSize) < totalCount;
+                pageNumber++;
+
+                log.info("姝e湪鍚屾绗� {} 椤碉紝褰撳墠宸插悓姝� {}/{}", pageNumber - 1, totalSynced, totalCount);
+            }
+
+            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<ProductMaterial> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.orderByDesc(ProductMaterial::getFormModifiedTime).last("LIMIT 1");
+        ProductMaterial lastRecord = this.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<ProductMaterial> parseProductMaterials(JSONArray dataArr, Integer totalCount) {
+        List<ProductMaterial> list = new ArrayList<>();
+        LocalDateTime now = LocalDateTime.now();
+
+        for (int i = 0; i < dataArr.size(); i++) {
+            JSONObject item = dataArr.getJSONObject(i);
+            String formInstanceId = item.getString("formInstanceId");
+
+            JSONObject originator = item.getJSONObject("originator");
+            String originatorName = originator != null && originator.containsKey("userName")
+                    ? originator.getJSONObject("userName").getString("nameInChinese") : "鏈煡";
+
+            JSONObject formData = item.getJSONObject("formData");
+            ProductMaterial material = new ProductMaterial();
+
+            material.setFormInstanceId(formInstanceId);
+            material.setIdentifierCode(formData.getString("textField_l92h77ju"));
+            material.setMaterialCode(formData.getString("textField_l92f36f2"));
+            material.setMaterialName(formData.getString("textField_l92f36f5"));
+            material.setSpecification(formData.getString("textField_l92f36f6"));
+            material.setBaseUnit(formData.getString("textField_la147lnw"));
+            material.setMaterialAttribute(formData.getString("selectField_la14k51j"));
+            material.setFinishedProductName(formData.getString("radioField_lbkk2nn2"));
+            material.setRemark(formData.getString("textareaField_l92f36f9"));
+
+            // 澶勭悊鐗╂枡绫诲瀷鍜屽瓨璐х被鍒�
+            String materialType = formData.getString("selectField_l92f36fb");
+            String inventoryCat = formData.getString("selectField_la154noy");
+            material.setMaterialTypeId(getOrCreateConfigId(materialType, MaterialConfigTypeEnum.MATERIAL_TYPE.name()));
+            material.setInventoryCategoryId(getOrCreateConfigId(inventoryCat, MaterialConfigTypeEnum.INVENTORY_CAT.name()));
+
+            material.setOriginatorName(originatorName);
+            material.setOriginatorOrg("瀹佸涓垱缁胯兘瀹炰笟闆嗗洟鏈夐檺鍏徃");
+
+            material.setFormModifiedTime(parseUtcTime(item.getString("modifiedTimeGMT")));
+            material.setCreateTime(now);
+            material.setUpdateTime(now);
+
+            list.add(material);
+        }
+        return list;
+    }
+
+    private Integer getOrCreateConfigId(String name, String type) {
+        if (StringUtils.isEmpty(name)) {
+            return null;
+        }
+        ProductMaterialConfig config = productMaterialConfigService.getOne(new LambdaQueryWrapper<ProductMaterialConfig>()
+                .eq(ProductMaterialConfig::getConfigName, name)
+                .eq(ProductMaterialConfig::getConfigType, type));
+        if (config == null) {
+            config = new ProductMaterialConfig();
+            config.setConfigName(name);
+            config.setConfigType(type);
+            productMaterialConfigService.save(config);
+        }
+        return config.getId();
+    }
+
+    private int processSaveOrUpdate(List<ProductMaterial> list) {
+        if (list == null || list.isEmpty()) {
+            return 0;
+        }
+        int affected = 0;
+
+        for (ProductMaterial material : list) {
+            ProductMaterial exist = this.getOne(new LambdaQueryWrapper<ProductMaterial>()
+                    .eq(ProductMaterial::getFormInstanceId, material.getFormInstanceId()));
+
+            if (exist == null) {
+                this.save(material);
+                affected++;
+                log.info("鏂板鐗╂枡鏁版嵁 formInstanceId={}", material.getFormInstanceId());
+            } else {
+                if (exist.getFormModifiedTime() == null || !exist.getFormModifiedTime().equals(material.getFormModifiedTime())) {
+                    material.setId(exist.getId());
+                    material.setCreateTime(exist.getCreateTime());
+                    this.updateById(material);
+                    affected++;
+                    log.info("鏇存柊鐗╂枡鏁版嵁 formInstanceId={}", material.getFormInstanceId());
+                }
+            }
+        }
+        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("瑙f瀽鏃堕棿 {} 澶辫触: {}", utcString, ex.getMessage());
+            return null;
+        }
+    }
+}

--
Gitblit v1.9.3