| | |
| | | package com.ruoyi.productionPlan.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.ruoyi.common.exception.base.BaseException; |
| | | import com.ruoyi.common.utils.StringUtils; |
| | | import com.ruoyi.common.utils.bean.BeanUtils; |
| | | import com.ruoyi.common.utils.http.HttpUtils; |
| | | import com.ruoyi.common.utils.poi.ExcelUtil; |
| | | import com.ruoyi.framework.config.AliDingConfig; |
| | | import com.ruoyi.production.pojo.ProductMaterial; |
| | | import com.ruoyi.framework.util.AliDingUtils; |
| | | import com.ruoyi.production.pojo.ProductMaterialSku; |
| | | import com.ruoyi.production.pojo.ProductOrder; |
| | | import com.ruoyi.production.service.ProductMaterialService; |
| | |
| | | import com.ruoyi.productionPlan.dto.ProductionPlanDto; |
| | | import com.ruoyi.productionPlan.dto.ProductionPlanImportDto; |
| | | import com.ruoyi.productionPlan.dto.ProductionPlanSummaryDto; |
| | | import com.ruoyi.productionPlan.enums.DataSourceTypeEnum; |
| | | import com.ruoyi.productionPlan.mapper.ProductOrderPlanMapper; |
| | | import com.ruoyi.productionPlan.mapper.ProductionPlanMapper; |
| | | import com.ruoyi.productionPlan.pojo.ProductOrderPlan; |
| | |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.math.BigDecimal; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.time.*; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.time.format.DateTimeParseException; |
| | | import java.time.Instant; |
| | | import java.time.LocalDateTime; |
| | | import java.time.ZoneId; |
| | | import java.util.*; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | | import java.util.stream.Collectors; |
| | | |
| | | import static com.ruoyi.productionPlan.enums.DataSourceTypeEnum.PRODUCTION_FORECAST; |
| | | |
| | | /** |
| | | * <br> |
| | |
| | | |
| | | // 校验是否存在不同的产品名称 |
| | | String firstProductName = plans.get(0).getProductName(); |
| | | if (plans.stream().anyMatch(p -> !p.getProductName().equals(firstProductName))) { |
| | | if (plans.stream().anyMatch(p -> p.getProductName() == null || !p.getProductName().equals(firstProductName))) { |
| | | throw new BaseException("合并失败,存在不同的产品名称"); |
| | | } |
| | | |
| | | // 校验是否存在不同的产品规格 |
| | | String firstProductSpec = plans.get(0).getSpecification(); |
| | | if (plans.stream().anyMatch(p -> !p.getSpecification().equals(firstProductSpec))) { |
| | | if (plans.stream().anyMatch(p -> p.getSpecification() == null || !p.getSpecification().equals(firstProductSpec))) { |
| | | throw new BaseException("合并失败,存在不同的产品规格"); |
| | | } |
| | | |
| | | // 叠加剩余方数 |
| | | BigDecimal totalRemainingVolume = plans.stream() |
| | | .map(ProductionPlan::getRemainingVolume) |
| | | .filter(v -> v != null) |
| | | .filter(Objects::nonNull) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add); |
| | | // 判断下发数量是否大于等于剩余方数 |
| | | if (productionPlanDto.getTotalAssignedQuantity().compareTo(totalRemainingVolume) > 0) { |
| | |
| | | if (assignedVolume.add(remainingVolume).compareTo(productionPlanDto.getTotalAssignedQuantity()) >= 0) { |
| | | // 最后一个计划,分配剩余方数 |
| | | BigDecimal lastRemainingVolume = productionPlanDto.getTotalAssignedQuantity().subtract(assignedVolume); |
| | | plan.setStatus(1); |
| | | if (lastRemainingVolume.compareTo(BigDecimal.ZERO) <= 0) { |
| | | plan.setStatus(2); |
| | | } |
| | | plan.setAssignedQuantity(plan.getAssignedQuantity().add(lastRemainingVolume)); |
| | | productOrderPlan.setAssignedQuantity(lastRemainingVolume); |
| | | productionPlanMapper.updateById(plan); |
| | |
| | | } |
| | | |
| | | // 分配当前计划方数 |
| | | plan.setStatus(1); |
| | | if (remainingVolume.compareTo(BigDecimal.ZERO) <= 0) { |
| | | plan.setStatus(2); |
| | | } |
| | | plan.setAssignedQuantity(plan.getAssignedQuantity().add(remainingVolume)); |
| | | productOrderPlan.setAssignedQuantity(remainingVolume); |
| | | // 更新生产计划 |
| | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public boolean add(ProductionPlanDto productionPlanDto) { |
| | | productionPlanDto.setDataSourceType(PRODUCTION_FORECAST.getCode()); |
| | | productionPlanDto.setDataSourceType(DataSourceTypeEnum.MANUAL.getCode()); |
| | | productionPlanDto.setStatus(0); |
| | | productionPlanMapper.insert(productionPlanDto); |
| | | return true; |
| | | } |
| | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public boolean update(ProductionPlanDto productionPlanDto) { |
| | | // 已下发状态,不能编辑 |
| | | if (productionPlanDto.getStatus() != 0) { |
| | | throw new BaseException("已下发或部分下发状态,不能编辑"); |
| | | } |
| | | // 查询是否有关联订单 |
| | | boolean hasProductOrderPlan = productOrderPlanMapper.selectList(Wrappers.<ProductOrderPlan>lambdaQuery().eq(ProductOrderPlan::getProductionPlanId, productionPlanDto.getId())).stream().anyMatch(p -> p.getProductOrderId() != null); |
| | | if (hasProductOrderPlan) { |
| | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public boolean delete(List<Long> ids) { |
| | | // 如果存在已下发的计划,则不能删除 |
| | | if (productionPlanMapper.selectList(Wrappers.<ProductionPlan>lambdaQuery().in(ProductionPlan::getId, ids)).stream().anyMatch(p -> p.getStatus() == 1 || p.getStatus() == 2)) { |
| | | throw new BaseException("删除失败,存在已下发或部分下发的计划"); |
| | | } |
| | | // 如果有关联订单,则不能删除 |
| | | if (productOrderPlanMapper.selectList(Wrappers.<ProductOrderPlan>lambdaQuery().in(ProductOrderPlan::getProductionPlanId, ids)).stream().anyMatch(p -> p.getProductOrderId() != null)) { |
| | | throw new BaseException("删除失败,存在关联订单"); |
| | |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void syncProdData(Integer dataSyncType) { |
| | | if (!syncLock.tryLock()) { |
| | | log.warn("同步正在进行中,本次 {} 同步请求被跳过", dataSyncType == 1 ? "手动" : "定时任务"); |
| | | log.warn("同步正在进行中,本次 {} 同步请求被跳过", dataSyncType == 1 ? "手动同步" : "定时任务同步"); |
| | | return; |
| | | } |
| | | |
| | | try { |
| | | // 获取 AccessToken |
| | | String accessToken = getAccessToken(); |
| | | if (StringUtils.isEmpty(accessToken)) { |
| | | JSONArray searchConditions = new JSONArray(); |
| | | JSONObject condition = new JSONObject(); |
| | | condition.put("key", "processApprovedResult"); |
| | | JSONArray valueArray = new JSONArray(); |
| | | valueArray.add("agree"); |
| | | |
| | | condition.put("value", valueArray); |
| | | condition.put("type", "ARRAY"); |
| | | condition.put("operator", "in"); |
| | | condition.put("componentName", "SelectField"); |
| | | searchConditions.add(condition); |
| | | |
| | | String searchFieldJson = searchConditions.toJSONString(); |
| | | |
| | | JSONArray dataArr = AliDingUtils.getFormDataList(aliDingConfig, aliDingConfig.getProducePlanFormUuid(), searchFieldJson, this, ProductionPlan::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<ProductionPlan> list = parseProductionPlans(dataArr, dataSyncType, totalCount); |
| | | if (!list.isEmpty()) { |
| | | // 处理更新或新增 |
| | | int affected = processSaveOrUpdate(list); |
| | | totalSynced += affected; |
| | | } |
| | | |
| | | // 判断是否还有下一页 |
| | | hasMore = (pageNumber * pageSize) < totalCount; |
| | | pageNumber++; |
| | | |
| | | log.info("正在同步第 {} 页,当前已同步 {}/{}", pageNumber - 1, totalSynced, totalCount); |
| | | // 解析并保存数据 |
| | | List<ProductionPlan> list = parseProductionPlans(dataArr, dataSyncType, 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() { |
| | | // 查询本地数据库中 formModifiedTime 最大的记录 |
| | | LambdaQueryWrapper<ProductionPlan> queryWrapper = new LambdaQueryWrapper<>(); |
| | | queryWrapper.orderByDesc(ProductionPlan::getFormModifiedTime).last("LIMIT 1"); |
| | | ProductionPlan 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.getProducePlanFormUuid()); |
| | | searchParam.put("currentPage", pageNumber); |
| | | searchParam.put("pageSize", pageSize); |
| | | |
| | | JSONArray searchConditions = new JSONArray(); |
| | | JSONObject condition = new JSONObject(); |
| | | condition.put("key", "processApprovedResult"); |
| | | JSONArray valueArray = new JSONArray(); |
| | | valueArray.add("agree"); |
| | | |
| | | condition.put("value", valueArray); |
| | | condition.put("type", "ARRAY"); |
| | | condition.put("operator", "in"); |
| | | condition.put("componentName", "SelectField"); |
| | | searchConditions.add(condition); |
| | | |
| | | searchParam.put("searchFieldJson", searchConditions.toJSONString()); |
| | | |
| | | // 默认按修改时间升序排序,确保分页拉取数据的连续性 |
| | | // "+" 表示升序,"gmt_modified" 是官方内置字段 |
| | | searchParam.put("orderConfigJson", "{\"gmt_modified\":\"+\"}"); |
| | | |
| | | // 设置修改时间筛选区间 (格式必须为yyyy-MM-dd HH:mm:ss) |
| | | 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<ProductionPlan> parseProductionPlans(JSONArray dataArr, Integer dataSyncType, Integer totalCount) { |
| | |
| | | plan.setModifierName(modifyUser.getJSONObject("userName").getString("nameInChinese")); |
| | | } |
| | | |
| | | plan.setFormCreatedTime(parseUtcTime(item.getString("createdTimeGMT"))); |
| | | plan.setFormModifiedTime(parseUtcTime(item.getString("modifiedTimeGMT"))); |
| | | plan.setDataSyncType(dataSyncType); |
| | | plan.setDataSourceType(1); |
| | | plan.setFormCreatedTime(AliDingUtils.parseUtcTime(item.getString("createdTimeGMT"))); |
| | | plan.setFormModifiedTime(AliDingUtils.parseUtcTime(item.getString("modifiedTimeGMT"))); |
| | | plan.setDataSourceType(DataSourceTypeEnum.DING_TALK.getCode()); |
| | | plan.setCreateTime(now); |
| | | plan.setUpdateTime(now); |
| | | plan.setTotalCount(totalCount); |
| | |
| | | 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<ProductionPlanSummaryDto> summaryByProductType(ProductionPlanSummaryDto query) { |
| | | return baseMapper.selectSummaryByProductType(query); |
| | |
| | | entity.setAssignedQuantity(BigDecimal.ZERO); |
| | | entity.setCreateTime(LocalDateTime.now()); |
| | | entity.setUpdateTime(LocalDateTime.now()); |
| | | entity.setDataSourceType(2); |
| | | entity.setDataSyncType(1); |
| | | entity.setDataSourceType(DataSourceTypeEnum.DING_TALK.getCode()); |
| | | |
| | | // 根据物料编码填充关联ID |
| | | if (StringUtils.isNotEmpty(dto.getMaterialCode())) { |