Browse Source

Merge remote-tracking branch 'origin/prod-5.1.3' into prod-5.1.3

zhongwei
liwen 3 months ago
parent
commit
0d571aab4e
  1. 65
      hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/electric/vo/ComprehensiveElectricVo.java
  2. 2
      hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/electric/vo/DeviceElectricVo.java
  3. 2
      hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/electric/vo/TableHeadVo.java
  4. 10
      hzims-service/equipment/src/main/java/com/hnac/hzims/electric/controller/ElectricReportController.java
  5. 5
      hzims-service/equipment/src/main/java/com/hnac/hzims/electric/service/IElectricReportService.java
  6. 114
      hzims-service/equipment/src/main/java/com/hnac/hzims/electric/service/impl/ElectricReportServiceImpl.java
  7. 57
      hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/constants/ErrorCode.java
  8. 16
      hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/handler/ResultBooleanStrategy.java
  9. 8
      hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/handler/ZhipuAnalysisHandlerGlm4v.java
  10. 49
      hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/service/impl/ZhipuAnalysisServiceImpl.java

65
hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/electric/vo/ComprehensiveElectricVo.java

@ -0,0 +1,65 @@
package com.hnac.hzims.electric.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author ysj
*/
@Data
public class ComprehensiveElectricVo {
@ApiModelProperty(value = "月份")
private String month;
@ApiModelProperty(value = "本月电量")
private Double monthGenerate;
@ApiModelProperty(value = "去年同月")
private Double lastMonthGenerate;
@ApiModelProperty(value = "月同比")
private Double lastMonthGenerateRate;
@ApiModelProperty(value = "年发电量")
private Double yearGenerate;
@ApiModelProperty(value = "去年同期")
private Double lastYearGenerate;
@ApiModelProperty(value = "年同比")
private Double lastYearGenerateRate;
@ApiModelProperty(value = "本月降雨")
private Double monthRain;
@ApiModelProperty(value = "去年同月")
private Double lastMonthRain;
@ApiModelProperty(value = "月同比")
private Double lastMonthRainRate;
@ApiModelProperty(value = "年降雨量")
private Double yearRain;
@ApiModelProperty(value = "去年同期")
private Double lastYearRain;
@ApiModelProperty(value = "年同比")
private Double lastYearRainRate;
@ApiModelProperty(value = "本月等效小时")
private Double monthEquivalent;
@ApiModelProperty(value = "去年同月")
private Double lastMonthEquivalent;
@ApiModelProperty(value = "年等效小时")
private Double yearEquivalent;
@ApiModelProperty(value = "去年同期")
private Double lastYearEquivalent;
}

2
hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/electric/vo/DeviceElectricVo.java

@ -5,7 +5,7 @@ import lombok.Data;
/** /**
* @author 表头 * @author ysj
*/ */
@Data @Data
public class DeviceElectricVo { public class DeviceElectricVo {

2
hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/electric/vo/TableHeadVo.java

@ -7,7 +7,7 @@ import java.util.List;
/** /**
* @author 表头 * @author ysj
*/ */
@Data @Data
public class TableHeadVo { public class TableHeadVo {

10
hzims-service/equipment/src/main/java/com/hnac/hzims/electric/controller/ElectricReportController.java

@ -2,6 +2,7 @@ package com.hnac.hzims.electric.controller;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.hnac.hzims.electric.service.IElectricReportService; import com.hnac.hzims.electric.service.IElectricReportService;
import com.hnac.hzims.electric.vo.ComprehensiveElectricVo;
import com.hnac.hzims.equipment.entity.EmAssociationEntity; import com.hnac.hzims.equipment.entity.EmAssociationEntity;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
@ -14,6 +15,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -35,4 +37,12 @@ public class ElectricReportController extends BladeController {
@RequestParam(value = "time") String time) { @RequestParam(value = "time") String time) {
return R.data(service.basics(deptId,type,time)); return R.data(service.basics(deptId,type,time));
} }
@GetMapping("/comprehensive")
@ApiOperationSupport(order = 1)
@ApiOperation(value = "综合报表", notes = "传入 deptId")
public R<List<ComprehensiveElectricVo>> comprehensive(@RequestParam(value = "deptId") Long deptId,
@RequestParam(value = "year") String year) {
return R.data(service.comprehensive(deptId,year));
}
} }

5
hzims-service/equipment/src/main/java/com/hnac/hzims/electric/service/IElectricReportService.java

@ -1,5 +1,8 @@
package com.hnac.hzims.electric.service; package com.hnac.hzims.electric.service;
import com.hnac.hzims.electric.vo.ComprehensiveElectricVo;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -9,4 +12,6 @@ public interface IElectricReportService {
Map<String, Object> basics(Long deptId, Long type,String time); Map<String, Object> basics(Long deptId, Long type,String time);
List<ComprehensiveElectricVo> comprehensive(Long deptId,String year);
} }

114
hzims-service/equipment/src/main/java/com/hnac/hzims/electric/service/impl/ElectricReportServiceImpl.java

@ -1,6 +1,9 @@
package com.hnac.hzims.electric.service.impl; package com.hnac.hzims.electric.service.impl;
import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hnac.hzims.common.logs.utils.StringUtils; import com.hnac.hzims.common.logs.utils.StringUtils;
import com.hnac.hzims.electric.entity.ThirtyEntity; import com.hnac.hzims.electric.entity.ThirtyEntity;
@ -8,17 +11,15 @@ import com.hnac.hzims.electric.entity.ThreeEntity;
import com.hnac.hzims.electric.service.IElectricReportService; import com.hnac.hzims.electric.service.IElectricReportService;
import com.hnac.hzims.electric.service.ThirtyService; import com.hnac.hzims.electric.service.ThirtyService;
import com.hnac.hzims.electric.service.ThreeService; import com.hnac.hzims.electric.service.ThreeService;
import com.hnac.hzims.electric.vo.ComprehensiveElectricVo;
import com.hnac.hzims.electric.vo.DeviceElectricVo; import com.hnac.hzims.electric.vo.DeviceElectricVo;
import com.hnac.hzims.electric.vo.TableHeadVo; import com.hnac.hzims.electric.vo.TableHeadVo;
import com.hnac.hzims.equipment.entity.EmInfoEntity; import com.hnac.hzims.equipment.vo.EminfoAndEmParamVo;
import com.hnac.hzims.equipment.service.IEmInfoService;
import com.hnac.hzims.operational.station.entity.StationEntity; import com.hnac.hzims.operational.station.entity.StationEntity;
import com.hnac.hzims.operational.station.feign.IStationClient; import com.hnac.hzims.operational.station.feign.IStationClient;
import com.hnac.hzims.operational.station.vo.StationsByDeptIdsParamVo;
import com.hnac.hzinfo.datasearch.analyse.IAnalyseDataSearchClient; import com.hnac.hzinfo.datasearch.analyse.IAnalyseDataSearchClient;
import com.hnac.hzinfo.datasearch.analyse.po.AnalyseCodeByAnalyseDataPO; import com.hnac.hzinfo.datasearch.analyse.po.AnalyseCodeByAnalyseDataPO;
import com.hnac.hzinfo.datasearch.analyse.po.AnalyzeDataConditionPO; import com.hnac.hzinfo.datasearch.analyse.po.AnalyzeDataConditionPO;
import com.hnac.hzinfo.datasearch.analyse.vo.AnalyseDataTaosVO;
import com.hnac.hzinfo.datasearch.analyse.vo.AnalyzeDataConditionVO; import com.hnac.hzinfo.datasearch.analyse.vo.AnalyzeDataConditionVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -26,9 +27,9 @@ import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil; import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.DateUtil; import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.ObjectUtil; import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.entity.Dept; import org.springblade.system.entity.Dept;
import org.springblade.system.feign.ISysClient; import org.springblade.system.feign.ISysClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -48,14 +49,16 @@ public class ElectricReportServiceImpl implements IElectricReportService {
private final ThirtyService thirtyService; private final ThirtyService thirtyService;
private final IEmInfoService deviceService;
private final ISysClient sysClient; private final ISysClient sysClient;
private final IStationClient stationClient; private final IStationClient stationClient;
private final IAnalyseDataSearchClient analyseDataSearchClient; private final IAnalyseDataSearchClient analyseDataSearchClient;
private final RedisTemplate redisTemplate;
public final static String DEVICE_CACHE_COFIG_FINAL = "hzims:equipment:emInfo:deviceCode.emInfoList";
/** /**
* 基础报表 * 基础报表
* @param deptId * @param deptId
@ -92,6 +95,57 @@ public class ElectricReportServiceImpl implements IElectricReportService {
} }
/** /**
* 综合报表
* @param deptId
* @return
*/
@Override
public List<ComprehensiveElectricVo> comprehensive(Long deptId,String year) {
// 查询站点
StationEntity param = new StationEntity();
param.setRefDept(deptId);
R<StationEntity> station = stationClient.getStationByCodeOrRedDept(param);
if(!station.isSuccess() || ObjectUtil.isEmpty(station.getData())){
return new ArrayList<>();
}
// 查询设备
List<EminfoAndEmParamVo> devices = JSONObject.parseObject(redisTemplate.opsForValue().get(DEVICE_CACHE_COFIG_FINAL).toString(), new TypeReference<List<EminfoAndEmParamVo>>() {});
if(CollectionUtil.isEmpty(devices)){
return new ArrayList<>();
}
// 设备装机容量
double installedCapacity = devices.stream().filter(device->device.getCreateDept().equals(deptId)).mapToDouble(EminfoAndEmParamVo::getInstalledCapacity).sum();
// 查询两年发电量
Calendar calendar = Calendar.getInstance();
calendar.setTime(DateUtil.parse(year,"yyyy"));
calendar.add(Calendar.YEAR,1);
Date end = calendar.getTime();
calendar.add(Calendar.YEAR,-2);
Date start = calendar.getTime();
List<ThreeEntity> threes = threeService.list(Wrappers.<ThreeEntity>lambdaQuery()
.eq(ThreeEntity::getStationId,station.getData().getCode())
.ge(ThreeEntity::getStrMonth, DateUtil.format(start,DateUtil.PATTERN_DATE))
.le(ThreeEntity::getStrMonth, DateUtil.format(end,DateUtil.PATTERN_DATE))
);
calendar.setTime(DateUtil.parse(year,"yyyy"));
calendar.add(Calendar.YEAR,1);
Date finish = calendar.getTime();
calendar.add(Calendar.YEAR,-1);
Date current = calendar.getTime();
while (current.compareTo(finish) < 0){
calendar.add(Calendar.MONTH,1);
current = calendar.getTime();
}
return null;
}
/**
* 确认机构级别 * 确认机构级别
* @param deptId * @param deptId
* @return * @return
@ -450,17 +504,17 @@ public class ElectricReportServiceImpl implements IElectricReportService {
// 日 // 日
if (type == 0) { if (type == 0) {
// 站点设备集合 // 站点设备集合
List<EmInfoEntity> devices = deviceService.list(Wrappers.<EmInfoEntity>lambdaQuery() List<EminfoAndEmParamVo> devices = JSONObject.parseObject(redisTemplate.opsForValue().get(DEVICE_CACHE_COFIG_FINAL).toString(), new TypeReference<List<EminfoAndEmParamVo>>() {});
.eq(EmInfoEntity::getCreateDept,station.getData().getRefDept())
.eq(EmInfoEntity::getEmType,2)
.eq(EmInfoEntity::getHomePageDisplay,1)
);
if(CollectionUtil.isEmpty(devices)){ if(CollectionUtil.isEmpty(devices)){
return new HashMap<>(); return new HashMap<>();
} }
List<EminfoAndEmParamVo> stationDevices = devices.stream().filter(device->device.getCreateDept().equals(station.getData().getRefDept())).collect(Collectors.toList());
if(CollectionUtil.isEmpty(stationDevices)){
return new HashMap<>();
}
Date date = DateUtil.parse(time,DateUtil.PATTERN_DATE); Date date = DateUtil.parse(time,DateUtil.PATTERN_DATE);
// 根据设备查询当日有功/无功电量 // 根据设备查询当日有功/无功电量
List<DeviceElectricVo> electrics = this.deviceElectrics(devices,date); List<DeviceElectricVo> electrics = this.deviceElectrics(stationDevices,date);
// 表头 // 表头
List<TableHeadVo> tableHeads = new ArrayList<>(); List<TableHeadVo> tableHeads = new ArrayList<>();
@ -475,7 +529,7 @@ public class ElectricReportServiceImpl implements IElectricReportService {
tableHeads.add(secondHead); tableHeads.add(secondHead);
// 根据设备分组 // 根据设备分组
devices.forEach(device->{ stationDevices.forEach(device->{
TableHeadVo tableHead = new TableHeadVo(); TableHeadVo tableHead = new TableHeadVo();
tableHead.setTableName(device.getName() + "发电量(kWh)"); tableHead.setTableName(device.getName() + "发电量(kWh)");
tableHead.setIsChildren(true); tableHead.setIsChildren(true);
@ -486,24 +540,25 @@ public class ElectricReportServiceImpl implements IElectricReportService {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH,1);
Date end = calendar.getTime(); Date end = calendar.getTime();
calendar.add(Calendar.HOUR_OF_DAY,-calendar.get(Calendar.HOUR_OF_DAY)); calendar.add(Calendar.DAY_OF_MONTH,-1);
Date start = calendar.getTime(); Date start = calendar.getTime();
List<List<Object>> tableDate = new ArrayList<>(); List<List<Object>> tableDate = new ArrayList<>();
while (start.compareTo(end) < 0){ while (start.compareTo(end) < 0){
List<Object> item = new ArrayList<>(); List<Object> item = new ArrayList<>();
String hours = DateUtil.format(start,"yyyy-MM-dd HH"); String hours = DateUtil.format(start,"yyyy-MM-dd HH");
item.add(start.getMonth() + 1 + "月"); item.add(start.getHours() + "时");
// 总计:有功、无功 // 总计:有功、无功
item.add(electrics.stream().filter(electric -> electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getGenerate).sum()); item.add(electrics.stream().filter(electric -> electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getGenerate).sum());
item.add(electrics.stream().filter(electric -> electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getReactiveGenerate).sum()); item.add(electrics.stream().filter(electric -> electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getReactiveGenerate).sum());
// 遍历机组 // 遍历机组
devices.stream().sorted(Comparator.comparing(EmInfoEntity::getEmIndex)).forEach(device->{ stationDevices.stream().sorted(Comparator.comparing(EminfoAndEmParamVo::getOrd)).forEach(device->{
item.add(electrics.stream().filter(electric -> electric.getDeviceCode().equals(device.getNumber()) && electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getGenerate).sum()); item.add(electrics.stream().filter(electric -> electric.getDeviceCode().equals(device.getEmCode()) && electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getGenerate).sum());
item.add(electrics.stream().filter(electric -> electric.getDeviceCode().equals(device.getNumber()) && electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getReactiveGenerate).sum()); item.add(electrics.stream().filter(electric -> electric.getDeviceCode().equals(device.getEmCode()) && electric.getStrTime().contains(hours)).mapToDouble(DeviceElectricVo::getReactiveGenerate).sum());
}); });
calendar.add(Calendar.DAY_OF_MONTH,1); calendar.add(Calendar.HOUR_OF_DAY,1);
start = calendar.getTime(); start = calendar.getTime();
tableDate.add(item); tableDate.add(item);
} }
@ -641,18 +696,19 @@ public class ElectricReportServiceImpl implements IElectricReportService {
* @param devices * @param devices
* @return * @return
*/ */
private List<DeviceElectricVo> deviceElectrics(List<EmInfoEntity> devices,Date date) { private List<DeviceElectricVo> deviceElectrics(List<EminfoAndEmParamVo> devices,Date date) {
List<DeviceElectricVo> electrics = new ArrayList<>(); List<DeviceElectricVo> electrics = new ArrayList<>();
devices.forEach(device->{ devices.forEach(device->{
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH,1);
Date endTime = calendar.getTime(); Date endTime = calendar.getTime();
LocalDateTime end = LocalDateTime.parse(DateUtil.format(new Date(), DateUtil.format(endTime,DateUtil.PATTERN_DATETIME)), DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME)); LocalDateTime end = LocalDateTime.parse(DateUtil.format(new Date(), DateUtil.format(endTime,DateUtil.PATTERN_DATETIME)), DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME));
calendar.add(Calendar.HOUR_OF_DAY,-calendar.get(Calendar.HOUR_OF_DAY)); calendar.add(Calendar.DAY_OF_MONTH,-1);
Date startTime = calendar.getTime(); Date startTime = calendar.getTime();
LocalDateTime start = LocalDateTime.parse(DateUtil.format(new Date(), DateUtil.format(startTime,DateUtil.PATTERN_DATETIME)), DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME)); LocalDateTime start = LocalDateTime.parse(DateUtil.format(new Date(), DateUtil.format(startTime,DateUtil.PATTERN_DATETIME)), DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME));
AnalyseCodeByAnalyseDataPO param = new AnalyseCodeByAnalyseDataPO(); AnalyseCodeByAnalyseDataPO param = new AnalyseCodeByAnalyseDataPO();
param.setDeviceCode(device.getNumber()); param.setDeviceCode(device.getEmCode());
List<AnalyzeDataConditionPO> conditions = new ArrayList<>(); List<AnalyzeDataConditionPO> conditions = new ArrayList<>();
// 有功电量 // 有功电量
AnalyzeDataConditionPO generate = new AnalyzeDataConditionPO(); AnalyzeDataConditionPO generate = new AnalyzeDataConditionPO();
@ -674,7 +730,8 @@ public class ElectricReportServiceImpl implements IElectricReportService {
reactive.setSignages("reactive_generation"); reactive.setSignages("reactive_generation");
reactive.setTimeInterval(1); reactive.setTimeInterval(1);
reactive.setBeginTime(start); reactive.setBeginTime(start);
reactive.setEndTime(end);conditions.add(reactive); reactive.setEndTime(end);
conditions.add(reactive);
param.setSignboardConditions(conditions); param.setSignboardConditions(conditions);
R<List<AnalyzeDataConditionVO>> result = analyseDataSearchClient.getAnalyzeDataByAnalyzeCodeAndSignages(param); R<List<AnalyzeDataConditionVO>> result = analyseDataSearchClient.getAnalyzeDataByAnalyzeCodeAndSignages(param);
if(!result.isSuccess() || ObjectUtil.isEmpty(result.getData())){ if(!result.isSuccess() || ObjectUtil.isEmpty(result.getData())){
@ -682,24 +739,25 @@ public class ElectricReportServiceImpl implements IElectricReportService {
} }
while (startTime.compareTo(endTime) < 0){ while (startTime.compareTo(endTime) < 0){
DeviceElectricVo electric = new DeviceElectricVo(); DeviceElectricVo electric = new DeviceElectricVo();
electric.setDeviceCode(device.getEmCode());
electric.setStrTime(DateUtil.format(startTime,"yyyy-MM-dd HH")); electric.setStrTime(DateUtil.format(startTime,"yyyy-MM-dd HH"));
electric.setTime(startTime.getHours()); electric.setTime(startTime.getHours());
if(ObjectUtil.isEmpty(result.getData().get(0)) || CollectionUtil.isEmpty(result.getData().get(0).getList())){ if(CollectionUtil.isNotEmpty(result.getData()) && ObjectUtil.isNotEmpty(result.getData().get(0)) && CollectionUtil.isNotEmpty(result.getData().get(0).getList())){
electric.setGenerate(result.getData().get(0).getList().stream().filter(o->o.getTs().contains(electric.getStrTime())).mapToDouble(val->{ electric.setGenerate(result.getData().get(0).getList().stream().filter(o->o.getTs().contains(electric.getStrTime())).mapToDouble(val->{
if(StringUtils.isEmpty(val.getVal())){ if(StringUtils.isEmpty(val.getVal())){
return 0.0; return 0.0;
} }
return Double.parseDouble(val.getVal()); return Double.parseDouble(val.getVal()) * device.getRideCount();
}).sum()); }).sum());
}else{ }else{
electric.setGenerate(0.0); electric.setGenerate(0.0);
} }
if(ObjectUtil.isEmpty(result.getData().get(1)) || CollectionUtil.isEmpty(result.getData().get(1).getList())){ if(CollectionUtil.isNotEmpty(result.getData()) && result.getData().size() > 1 && ObjectUtil.isNotEmpty(result.getData().get(1)) && CollectionUtil.isNotEmpty(result.getData().get(1).getList())){
electric.setReactiveGenerate(result.getData().get(1).getList().stream().filter(o->o.getTs().contains(electric.getStrTime())).mapToDouble(val->{ electric.setReactiveGenerate(result.getData().get(1).getList().stream().filter(o->o.getTs().contains(electric.getStrTime())).mapToDouble(val->{
if(StringUtils.isEmpty(val.getVal())){ if(StringUtils.isEmpty(val.getVal())){
return 0.0; return 0.0;
} }
return Double.parseDouble(val.getVal()); return Double.parseDouble(val.getVal()) * device.getRideCount();
}).sum()); }).sum());
}else{ }else{
electric.setReactiveGenerate(0.0); electric.setReactiveGenerate(0.0);

57
hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/constants/ErrorCode.java

@ -0,0 +1,57 @@
package com.hnac.hzims.bigmodel.zhipuai.constants;
import com.hnac.hzinfo.exception.HzServiceException;
import lombok.Getter;
import org.springblade.core.tool.api.IResultCode;
import org.springblade.core.tool.api.ResultCode;
/**
* @Author: ypj
* @Date: 2024/8/22 11:17
*/
@Getter
public enum ErrorCode implements IResultCode {
GET_DATA_FAILURE(1888000001, "获取数据失败"),
ANALYSIS_FAILURE(1888000002, "分析失败"),
STRATEGY_NOT_FOUND(1888000003, "策略未找到"),
GET_FILE_CONTENT_FAILURE(1888000004, "获取文件内容失败"),
REQUEST_TEXT_IS_EMPTY(1888000005, "交互文字内容不能为空"),
EMPTY_ANALYSIS_TYPE(1888000006, "识别类型为空"),
UNKNOWN_ANALYSIS_TYPE(1888000007, "未知的识别类型"),
NO_COMPARATOR(1888000008, "未获取到对比对象"),
NO_COMPARISON_TYPE(1888000009, "未获取到对比类型"),
GET_RESULT_FAIL(1888000010, "获取结果失败"),;
private final int code;
private final String msg;
ErrorCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public String getMessage() {
return this.msg;
}
public HzServiceException throwException() {
return new HzServiceException(this);
}
public static HzServiceException throwCommonException(String msg) {
return new HzServiceException(new IResultCode() {
@Override
public String getMessage() {
return msg;
}
@Override
public int getCode() {
return ResultCode.FAILURE.getCode();
}
});
}
}

16
hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/handler/ResultBooleanStrategy.java

@ -2,9 +2,9 @@ package com.hnac.hzims.bigmodel.zhipuai.handler;
import com.hnac.hzims.bigmodel.zhipuai.constants.BaseEnum; import com.hnac.hzims.bigmodel.zhipuai.constants.BaseEnum;
import com.hnac.hzims.bigmodel.zhipuai.constants.ComparisonType; import com.hnac.hzims.bigmodel.zhipuai.constants.ComparisonType;
import com.hnac.hzims.bigmodel.zhipuai.constants.ErrorCode;
import com.hnac.hzims.bigmodel.zhipuai.constants.ResultStrategyType; import com.hnac.hzims.bigmodel.zhipuai.constants.ResultStrategyType;
import com.hnac.hzims.bigmodel.zhipuai.entity.ZhipuAnalysisInfoEntity; import com.hnac.hzims.bigmodel.zhipuai.entity.ZhipuAnalysisInfoEntity;
import com.hnac.hzinfo.exception.HzServiceException;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.util.Objects; import java.util.Objects;
@ -23,18 +23,24 @@ public class ResultBooleanStrategy implements ResultStrategy<Boolean> {
public Boolean getResult(ZhipuAnalysisInfoEntity info, Object resultData) { public Boolean getResult(ZhipuAnalysisInfoEntity info, Object resultData) {
Object comparator = convertOriginalData(info.getResultCondition(), info.getResultType()); Object comparator = convertOriginalData(info.getResultCondition(), info.getResultType());
Assert.isTrue(Objects.nonNull(comparator), () -> { Assert.isTrue(Objects.nonNull(comparator), () -> {
throw new HzServiceException("没有获取到对比对象"); throw ErrorCode.NO_COMPARATOR.throwException();
}); });
ComparisonType comparisonType = BaseEnum.getInstance(info.getResultJudgeModel(), ComparisonType.class); ComparisonType comparisonType = BaseEnum.getInstance(info.getResultJudgeModel(), ComparisonType.class);
switch (comparisonType) { Assert.isTrue(Objects.nonNull(comparisonType), () -> {
throw ErrorCode.NO_COMPARISON_TYPE.throwException();
});
switch (Objects.requireNonNull(comparisonType)) {
case EQUAL: case EQUAL:
return comparator.equals(resultData); return comparator.equals(resultData);
case GREATER: case GREATER:
return ((Comparable) comparator).compareTo(resultData) < 0; if (comparator instanceof Comparable && resultData instanceof Comparable) {
return ((Comparable) comparator).compareTo((Comparable)resultData) < 0;
}
break;
case LESS: case LESS:
return ((Comparable) comparator).compareTo(resultData) > 0; return ((Comparable) comparator).compareTo(resultData) > 0;
} }
return null; throw ErrorCode.GET_RESULT_FAIL.throwException();
} }
} }

8
hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/handler/ZhipuAnalysisHandlerGlm4v.java

@ -1,6 +1,7 @@
package com.hnac.hzims.bigmodel.zhipuai.handler; package com.hnac.hzims.bigmodel.zhipuai.handler;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import com.hnac.hzims.bigmodel.zhipuai.constants.ErrorCode;
import com.hnac.hzinfo.exception.HzServiceException; import com.hnac.hzinfo.exception.HzServiceException;
import com.zhipu.oapi.Constants; import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest; import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
@ -58,14 +59,13 @@ public class ZhipuAnalysisHandlerGlm4v extends AbstractZhipuAnalysisHandler {
messages.add(chatMessage); messages.add(chatMessage);
String requestId = String.format(requestIdTemplate, System.currentTimeMillis()); String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
ChatCompletionRequest request = ChatCompletionRequest.builder() return ChatCompletionRequest.builder()
.model(getAnalysisModel()) .model(getAnalysisModel())
.stream(Boolean.FALSE) .stream(Boolean.FALSE)
.invokeMethod(Constants.invokeMethod) .invokeMethod(Constants.invokeMethod)
.messages(messages) .messages(messages)
.requestId(requestId) .requestId(requestId)
.build(); .build();
return request;
} }
@Override @Override
@ -73,7 +73,7 @@ public class ZhipuAnalysisHandlerGlm4v extends AbstractZhipuAnalysisHandler {
ModelApiResponse response = sendRequest(text, url); ModelApiResponse response = sendRequest(text, url);
log.info("get zhi pu ai response : {}", Optional.ofNullable(response).map(JsonUtil::toJson).orElse("null")); log.info("get zhi pu ai response : {}", Optional.ofNullable(response).map(JsonUtil::toJson).orElse("null"));
Assert.<HzServiceException>isTrue(Objects.nonNull(response) && response.isSuccess(), () -> { Assert.<HzServiceException>isTrue(Objects.nonNull(response) && response.isSuccess(), () -> {
throw new HzServiceException(response.getMsg()); throw ErrorCode.throwCommonException(Optional.ofNullable(response).map(ModelApiResponse::getMsg).orElse("没有收到大模型平台响应"));
}); });
try { try {
String resultJson = response.getData().getChoices().get(0).getMessage().getContent().toString(); String resultJson = response.getData().getChoices().get(0).getMessage().getContent().toString();
@ -81,7 +81,7 @@ public class ZhipuAnalysisHandlerGlm4v extends AbstractZhipuAnalysisHandler {
return resultJson; return resultJson;
} catch (Exception e) { } catch (Exception e) {
log.info("get data from response error", e); log.info("get data from response error", e);
throw new HzServiceException("获取数据失败"); throw ErrorCode.GET_DATA_FAILURE.throwException();
} }
} }

49
hzims-service/hzims-big-model/src/main/java/com/hnac/hzims/bigmodel/zhipuai/service/impl/ZhipuAnalysisServiceImpl.java

@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hnac.hzims.bigmodel.api.dto.BigModelAnalysisRequestDTO; import com.hnac.hzims.bigmodel.api.dto.BigModelAnalysisRequestDTO;
import com.hnac.hzims.bigmodel.api.dto.BigModelAnalysisResponseDTO; import com.hnac.hzims.bigmodel.api.dto.BigModelAnalysisResponseDTO;
import com.hnac.hzims.bigmodel.zhipuai.constants.BaseEnum; import com.hnac.hzims.bigmodel.zhipuai.constants.BaseEnum;
import com.hnac.hzims.bigmodel.zhipuai.constants.ErrorCode;
import com.hnac.hzims.bigmodel.zhipuai.constants.ResultStrategyType; import com.hnac.hzims.bigmodel.zhipuai.constants.ResultStrategyType;
import com.hnac.hzims.bigmodel.zhipuai.entity.ZhipuAnalysisInfoEntity; import com.hnac.hzims.bigmodel.zhipuai.entity.ZhipuAnalysisInfoEntity;
import com.hnac.hzims.bigmodel.zhipuai.handler.ResultStrategy; import com.hnac.hzims.bigmodel.zhipuai.handler.ResultStrategy;
@ -41,29 +42,29 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
private final ZhipuAnalysisInfoService infoService; private final ZhipuAnalysisInfoService infoService;
private final String multiQuestionBrief = "从给出的图片回答以下{}个问题\n"; private static final String MULTI_QUESTION_BRIEF = "从给出的图片回答以下{}个问题\n";
private final String multiQuestionPrefix = "第{}个问题,"; private static final String MULTI_QUESTION_PREFIX = "第{}个问题,";
private final String multiQuestionConstrains = "- 不要在输出中添加任何注释和思考过程和其他多余的内容,以JSON格式输出简单结果,{}结果只包含'是'或者'否'\n"; private static final String MULTI_QUESTION_CONSTRAINS = "- 不要在输出中添加任何注释和思考过程和其他多余的内容,以JSON格式输出简单结果,{}结果只包含'是'或者'否'\n";
private final String multiQuestionConstrainsList = "'{}'代表第{}个问题,"; private static final String MULTI_QUESTION_CONSTRAINS_LIST = "'{}'代表第{}个问题,";
@Override @Override
public ZhipuAnalysisFileResponse analysis(ZhipuAnalysisFileRequest request) { public ZhipuAnalysisFileResponse analysis(ZhipuAnalysisFileRequest request) {
Assert.isTrue(StringUtil.isNotBlank(request.getFilePath()) || StringUtil.isNotBlank(request.getUrl()), () -> { Assert.isTrue(StringUtil.isNotBlank(request.getFilePath()) || StringUtil.isNotBlank(request.getUrl()), () -> {
throw new HzServiceException("文件为空"); throw ErrorCode.GET_FILE_CONTENT_FAILURE.throwException();
}); });
ZhipuAnalysisFileResponse response = new ZhipuAnalysisFileResponse(); ZhipuAnalysisFileResponse response = new ZhipuAnalysisFileResponse();
ZhipuAnalysisInfoEntity info = getAnalysisInfo(request); ZhipuAnalysisInfoEntity info = getAnalysisInfo(request);
Assert.isTrue(Objects.nonNull(info), () -> { Assert.isTrue(Objects.nonNull(info), () -> {
throw new HzServiceException("没有找到对应的策略信息"); throw ErrorCode.STRATEGY_NOT_FOUND.throwException();
}); });
ZhipuAnalyser analyser = analysisFactory.getAnalysisStrategy(info.getModel()); ZhipuAnalyser analyser = analysisFactory.getAnalysisStrategy(info.getModel());
Assert.isTrue(StringUtil.isNotBlank(info.getRequestContent()), () -> { Assert.isTrue(StringUtil.isNotBlank(info.getRequestContent()), () -> {
throw new HzServiceException("智谱平台交互内容为空"); throw ErrorCode.REQUEST_TEXT_IS_EMPTY.throwException();
}); });
//拼接文字内容 //拼接文字内容
StringBuilder textBuilder = new StringBuilder(); StringBuilder textBuilder = new StringBuilder();
@ -78,13 +79,13 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
Object resultObject = analyser.getResultValue(analyser.getText(), info.getResultKey(), getSendUrl(request)); Object resultObject = analyser.getResultValue(analyser.getText(), info.getResultKey(), getSendUrl(request));
Assert.isTrue(Objects.nonNull(resultObject), () -> { Assert.isTrue(Objects.nonNull(resultObject), () -> {
throw new HzServiceException("智谱平台分析失败"); throw ErrorCode.ANALYSIS_FAILURE.throwException();
}); });
String resultStr = resultObject.toString(); String resultStr = resultObject.toString();
ResultStrategyType strategyType = BaseEnum.getInstance(info.getResultStrategy(), ResultStrategyType.class); ResultStrategyType strategyType = BaseEnum.getInstance(info.getResultStrategy(), ResultStrategyType.class);
Assert.isTrue(Objects.nonNull(strategyType), () -> { Assert.isTrue(Objects.nonNull(strategyType), () -> {
throw new HzServiceException("没有找到对应的结果数据解析策略"); throw ErrorCode.STRATEGY_NOT_FOUND.throwException();
}); });
ResultStrategy strategy = strategyType.getStrategy(); ResultStrategy strategy = strategyType.getStrategy();
@ -100,14 +101,14 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
if (StringUtil.isNotBlank(request.getUrl())) { if (StringUtil.isNotBlank(request.getUrl())) {
return request.getUrl(); return request.getUrl();
} }
if (StringUtil.isNotBlank(request.getFilePath())) { Assert.isTrue(StringUtil.isNotBlank(request.getFilePath()), () -> {
throw ErrorCode.GET_FILE_CONTENT_FAILURE.throwException();
});
try { try {
return FileUtil.getBase64(request.getFilePath()); return FileUtil.getBase64(request.getFilePath());
} catch (IOException e) { } catch (IOException e) {
throw new HzServiceException("获取文件内容失败"); throw ErrorCode.GET_FILE_CONTENT_FAILURE.throwException();
}
} }
return null;
} }
@Override @Override
@ -121,7 +122,7 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
.eq(StringUtil.isNotBlank(request.getCheckTypeSon()), ZhipuAnalysisInfoEntity::getCheckTypeSon, request.getCheckTypeSon()) .eq(StringUtil.isNotBlank(request.getCheckTypeSon()), ZhipuAnalysisInfoEntity::getCheckTypeSon, request.getCheckTypeSon())
.last("limit 1;")); .last("limit 1;"));
} }
log.info("the analysis information is {}", Optional.ofNullable(result).map(r -> JsonUtil.toJson(r)).orElse("null")); log.debug("the analysis information is {}", Optional.ofNullable(result).map(r -> JsonUtil.toJson(r)).orElse("null"));
return result; return result;
} }
@ -131,15 +132,15 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
BigModelAnalysisResponseDTO response = new BigModelAnalysisResponseDTO(); BigModelAnalysisResponseDTO response = new BigModelAnalysisResponseDTO();
try { try {
Assert.isTrue(StringUtil.isNotBlank(request.getUrl()), () -> { Assert.isTrue(StringUtil.isNotBlank(request.getUrl()), () -> {
throw new HzServiceException("文件为空"); throw ErrorCode.GET_FILE_CONTENT_FAILURE.throwException();
}); });
Assert.isTrue(CollectionUtil.isNotEmpty(request.getCodeList()) || CollectionUtil.isNotEmpty(request.getCheckTypeSonList()), () -> { Assert.isTrue(CollectionUtil.isNotEmpty(request.getCodeList()) || CollectionUtil.isNotEmpty(request.getCheckTypeSonList()), () -> {
throw new HzServiceException("识别类型为空"); throw ErrorCode.EMPTY_ANALYSIS_TYPE.throwException();
}); });
List<ZhipuAnalysisInfoEntity> infoList = infoService.list(Wrappers.<ZhipuAnalysisInfoEntity>lambdaQuery().in(CollectionUtil.isNotEmpty(request.getCodeList()), ZhipuAnalysisInfoEntity::getCode, request.getCodeList()) List<ZhipuAnalysisInfoEntity> infoList = infoService.list(Wrappers.<ZhipuAnalysisInfoEntity>lambdaQuery().in(CollectionUtil.isNotEmpty(request.getCodeList()), ZhipuAnalysisInfoEntity::getCode, request.getCodeList())
.in(CollectionUtil.isNotEmpty(request.getCheckTypeSonList()), ZhipuAnalysisInfoEntity::getCheckTypeSon, request.getCheckTypeSonList())); .in(CollectionUtil.isNotEmpty(request.getCheckTypeSonList()), ZhipuAnalysisInfoEntity::getCheckTypeSon, request.getCheckTypeSonList()));
Assert.isTrue(CollectionUtil.isNotEmpty(infoList), () -> { Assert.isTrue(CollectionUtil.isNotEmpty(infoList), () -> {
throw new HzServiceException("未知的识别类型"); throw ErrorCode.UNKNOWN_ANALYSIS_TYPE.throwException();
}); });
ZhipuAnalyser analyser = analysisFactory.getAnalysisStrategy(infoList.get(0).getModel()); ZhipuAnalyser analyser = analysisFactory.getAnalysisStrategy(infoList.get(0).getModel());
@ -148,7 +149,7 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
if (null == resultMap) { if (null == resultMap) {
response.setCode(ResultCode.FAILURE.getCode()); response.setCode(ResultCode.FAILURE.getCode());
response.setMsg("智谱大模型分析失败"); response.setMsg(ErrorCode.ANALYSIS_FAILURE.getMsg());
return response; return response;
} }
@ -184,9 +185,9 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
response.setMsg(e.getMessage()); response.setMsg(e.getMessage());
} else { } else {
response.setCode(ResultCode.FAILURE.getCode()); response.setCode(ResultCode.FAILURE.getCode());
response.setMsg("智谱大模型分析失败"); response.setMsg(ErrorCode.ANALYSIS_FAILURE.getMsg());
} }
log.error("智谱大模型分析失败", e); log.error(ErrorCode.ANALYSIS_FAILURE.getMessage(), e);
} }
return response; return response;
} }
@ -196,18 +197,18 @@ public class ZhipuAnalysisServiceImpl implements ZhipuAnalysisService {
StringBuilder titleBuilder = new StringBuilder(); StringBuilder titleBuilder = new StringBuilder();
StringBuilder formatBuilder = new StringBuilder(); StringBuilder formatBuilder = new StringBuilder();
stringBuilder.append(ZhipuAnalyser.QUESTION_PROFILE) stringBuilder.append(ZhipuAnalyser.QUESTION_PROFILE)
.append(StringUtil.format(multiQuestionBrief, infoList.size())); .append(StringUtil.format(MULTI_QUESTION_BRIEF, infoList.size()));
formatBuilder.append("{"); formatBuilder.append("{");
for (int index = 1; index <= infoList.size(); index++) { for (int index = 1; index <= infoList.size(); index++) {
ZhipuAnalysisInfoEntity infoEntity = infoList.get(index - 1); ZhipuAnalysisInfoEntity infoEntity = infoList.get(index - 1);
stringBuilder.append(StringUtil.format(multiQuestionPrefix, index)); stringBuilder.append(StringUtil.format(MULTI_QUESTION_PREFIX, index));
titleBuilder.append(StringUtil.format(multiQuestionConstrainsList, infoEntity.getResultKey(), index)); titleBuilder.append(StringUtil.format(MULTI_QUESTION_CONSTRAINS_LIST, infoEntity.getResultKey(), index));
formatBuilder.append(infoEntity.getRequestOutputFormat()).append(","); formatBuilder.append(infoEntity.getRequestOutputFormat()).append(",");
} }
formatBuilder.deleteCharAt(formatBuilder.length() - 1); formatBuilder.deleteCharAt(formatBuilder.length() - 1);
formatBuilder.append("}"); formatBuilder.append("}");
stringBuilder.append(ZhipuAnalyser.QUESTION_CONSTRAINS) stringBuilder.append(ZhipuAnalyser.QUESTION_CONSTRAINS)
.append(StringUtil.format(multiQuestionConstrains, titleBuilder.toString())) .append(StringUtil.format(MULTI_QUESTION_CONSTRAINS, titleBuilder.toString()))
.append(ZhipuAnalyser.QUESTION_OUTPUT_FORMAT).append(formatBuilder); .append(ZhipuAnalyser.QUESTION_OUTPUT_FORMAT).append(formatBuilder);
return stringBuilder.toString(); return stringBuilder.toString();
} }

Loading…
Cancel
Save