Commit 44b660e2 by 章家宝

feat:客户录音画像标签定时任务

1 parent f1154c72
......@@ -32,7 +32,7 @@
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>rpc-dj-mindworkplate-api</artifactId>
<version>5.6.1-SNAPSHOT</version>
<version>5.8.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.oreframework</groupId>
......
package cn.com.glsx.dj.strategy.config;
import cn.com.glsx.dj.mindworkplate.remote.InspectionCustomerTagRemote;
import cn.com.glsx.dj.mindworkplate.remote.MonitoringRemote;
import cn.com.glsx.dj.mindworkplate.remote.PadMessageBoxRemote;
import cn.com.glsx.dj.peanalysis.remote.BusinessSceneAnalysisRemote;
......@@ -91,4 +92,9 @@ public class DubboConfig {
return factory.builder(SceneRemote.class).check(check).version("1.0.0").timeout(timeout).build();
}
@Bean
public InspectionCustomerTagRemote inspectionCustomerTagRemote() {
return factory.builder(InspectionCustomerTagRemote.class).check(check).timeout(timeout).build();
}
}
package cn.com.glsx.dj.strategy.job;
import cn.com.glsx.dj.strategy.service.InspectionCustomerTagSyncService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* AI客户标签同步定时任务
* 每天凌晨2点执行,从mindworkplate服务同步昨天的录音客户标签数据
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/18
*/
@Slf4j
@Component
@ElasticJobConf(name = "CustomerTagSyncJob", cron = "0 0 2 * * ?",
description = "AI客户标签同步定时任务", overwrite = false)
public class InspectionCustomerTagJob implements SimpleJob {
@Autowired
private InspectionCustomerTagSyncService inspectionCustomerTagSyncService;
@Override
public void execute(ShardingContext shardingContext) {
log.info("AI客户标签同步定时任务开始执行");
try {
inspectionCustomerTagSyncService.syncCustomerTagFromInspection();
} catch (Exception e) {
log.error("AI客户标签同步定时任务执行异常", e);
}
log.info("AI客户标签同步定时任务执行结束");
}
}
......@@ -33,4 +33,33 @@ public interface CustomerTagProfileMapper extends OreMapper<CustomerTagProfile>
* @return 删除数量
*/
int deleteByPhoneAndCategoryCode(@Param("phone") String phone, @Param("categoryCode") String categoryCode);
/**
* 根据手机号和来源类型物理删除记录
*
* @param phone 手机号
* @param sourceType 来源类型
* @return 删除数量
*/
int deleteByPhoneAndSourceType(@Param("phone") String phone, @Param("sourceType") String sourceType);
/**
* 根据手机号、来源类型和维度代码列表物理删除记录
*
* @param phone 手机号
* @param sourceType 来源类型
* @param dimensionCodes 维度代码列表
* @return 删除数量
*/
int deleteByPhoneAndSourceTypeAndDimensionCodes(@Param("phone") String phone,
@Param("sourceType") String sourceType,
@Param("dimensionCodes") List<String> dimensionCodes);
/**
* 批量插入标签画像
*
* @param list 标签画像列表
* @return 插入数量
*/
int batchInsert(@Param("list") List<CustomerTagProfile> list);
}
......@@ -6,6 +6,7 @@ import cn.com.glsx.dj.strategy.enums.ArchiveTagEnum;
import cn.com.glsx.dj.strategy.mapper.CustomerTagProfileMapper;
import cn.com.glsx.dj.strategy.model.CustomerTagProfile;
import cn.com.glsx.dj.strategy.util.GopApiUtil;
import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -173,15 +174,6 @@ public class CustomerTagProfileService {
* @return DTO
*/
private CustomerProfileRespDTO convertToDTO(CustomerTagProfile profile) {
CustomerProfileRespDTO dto = new CustomerProfileRespDTO();
dto.setPhone(profile.getPhone());
dto.setCategoryCode(profile.getCategoryCode());
dto.setDimensionCode(profile.getDimensionCode());
dto.setEnumCode(profile.getEnumCode());
dto.setScoreBasis(profile.getScoreBasis());
dto.setScore(profile.getScore());
dto.setSourceType(profile.getSourceType());
dto.setCreateTime(profile.getCreateTime());
return dto;
return BeanUtil.copyProperties(profile, CustomerProfileRespDTO.class);
}
}
package cn.com.glsx.dj.strategy.service;
import cn.com.glsx.dj.mindworkplate.dto.InspectionCustomerTagDTO;
import cn.com.glsx.dj.mindworkplate.dto.InspectionCustomerTagPageRequestDTO;
import cn.com.glsx.dj.mindworkplate.remote.InspectionCustomerTagRemote;
import cn.com.glsx.dj.strategy.dto.TagCategoryDimensionQueryReqDTO;
import cn.com.glsx.dj.strategy.dto.TagCategoryDimensionRespDTO;
import cn.com.glsx.dj.strategy.dto.TagDimensionRespDTO;
import cn.com.glsx.dj.strategy.dto.TagEnumRespDTO;
import cn.com.glsx.dj.strategy.mapper.CustomerTagProfileMapper;
import cn.com.glsx.dj.strategy.model.CustomerTagProfile;
import cn.com.glsx.dj.strategy.model.TagDimension;
import cn.com.glsx.dj.strategy.model.TagEnum;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* 客户标签同步服务
* 从 AI 分析服务同步客户标签数据到客户标签画像表
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/18
*/
@Slf4j
@Service
public class InspectionCustomerTagSyncService {
private static final String SOURCE_TYPE_AI = "AI";
private static final int RESULT_FLAG_SUCCESS = 2;
private static final int PAGE_SIZE = 100;
private static final int BATCH_INSERT_SIZE = 500;
/**
* 行为标签分类代码
*/
private static final String CATEGORY_CODE_BEHAVIOR_TAG = "INIT_C2";
@Autowired
private InspectionCustomerTagRemote inspectionCustomerTagRemote;
@Autowired
private CustomerTagProfileMapper customerTagProfileMapper;
@Autowired
private TagCategoryService tagCategoryService;
/**
* 维度缓存:维度名称 -> 维度实体
* 使用 ConcurrentHashMap 保证线程安全
*/
private volatile Map<String, TagDimension> dimensionCache;
/**
* 枚举缓存:维度ID -> (枚举名称 -> 枚举实体)
*/
private volatile Map<Integer, Map<String, TagEnum>> enumCache;
/**
* 分类缓存:分类ID -> 分类代码
*/
private volatile Map<Integer, String> categoryCodeCache;
/**
* 同步昨天的 AI 客户标签数据
*/
public void syncCustomerTagFromInspection() {
log.info("AI客户标签同步任务开始执行");
try {
// 初始化维度和枚举缓存
initTagCache();
// 计算昨天的日期范围
Date yesterday = DateUtil.offsetDay(new Date(), -1);
String startTime = DateUtil.beginOfDay(yesterday).toString("yyyy-MM-dd HH:mm:ss");
String endTime = DateUtil.endOfDay(yesterday).toString("yyyy-MM-dd HH:mm:ss");
log.info("同步时间范围:{} - {}", startTime, endTime);
int pageNo = 1;
int totalProcessed = 0;
int totalInserted = 0;
while (true) {
// 分页获取数据
List<InspectionCustomerTagDTO> dataList = fetchCustomerTagData(startTime, endTime, pageNo);
if (CollectionUtils.isEmpty(dataList)) {
log.info("第 {} 页无数据,分页查询结束", pageNo);
break;
}
log.info("第 {} 页获取到 {} 条数据", pageNo, dataList.size());
// 处理每条数据
for (InspectionCustomerTagDTO data : dataList) {
try {
int inserted = processCustomerTagData(data);
totalInserted += inserted;
totalProcessed++;
} catch (Exception e) {
log.warn("处理客户标签数据失败,recordId={}, error={}",
data.getRecordId(), e.getMessage());
}
}
// 如果返回数据少于页大小,说明已经是最后一页
if (dataList.size() < PAGE_SIZE) {
break;
}
pageNo++;
}
log.info("AI客户标签同步任务执行完成,共处理 {} 条,插入 {} 条标签",
totalProcessed, totalInserted);
} finally {
// 清除缓存,确保下次任务执行时重新加载最新数据
clearTagCache();
}
}
/**
* 清除标签缓存
*/
private void clearTagCache() {
dimensionCache = null;
enumCache = null;
categoryCodeCache = null;
log.info("标签缓存已清除");
}
/**
* 初始化标签维度和枚举缓存
*/
private void initTagCache() {
if (dimensionCache == null) {
synchronized (this) {
if (dimensionCache == null) {
log.info("初始化标签维度和枚举缓存");
// 调用 TagCategoryService 获取行为标签分类下的所有维度和枚举
TagCategoryDimensionQueryReqDTO query = new TagCategoryDimensionQueryReqDTO();
query.setCategoryCode(CATEGORY_CODE_BEHAVIOR_TAG);
TagCategoryDimensionRespDTO categoryData = tagCategoryService.queryCategoryWithDimensions(query);
// 初始化分类代码缓存
categoryCodeCache = new ConcurrentHashMap<>();
categoryCodeCache.put(categoryData.getId(), categoryData.getCategoryCode());
// 初始化维度缓存和枚举缓存
dimensionCache = new ConcurrentHashMap<>();
enumCache = new ConcurrentHashMap<>();
List<TagDimensionRespDTO> dimensions = categoryData.getDimensions();
if (dimensions != null && !dimensions.isEmpty()) {
for (TagDimensionRespDTO dim : dimensions) {
// 维度名称 -> 维度信息
if (StrUtil.isNotBlank(dim.getDimensionName())) {
dimensionCache.put(dim.getDimensionName(), convertToDimensionEntity(dim));
}
// 维度ID -> (枚举名称 -> 枚举信息)
if (dim.getId() != null && dim.getEnums() != null) {
Map<String, TagEnum> enumNameMap = new ConcurrentHashMap<>();
for (TagEnumRespDTO e : dim.getEnums()) {
if (StrUtil.isNotBlank(e.getEnumName())) {
enumNameMap.put(e.getEnumName(), convertToEnumEntity(e));
}
}
enumCache.put(dim.getId(), enumNameMap);
}
}
}
log.info("加载 {} 个维度,{} 个维度的枚举值",
dimensionCache.size(), enumCache.size());
}
}
}
}
/**
* 将 TagDimensionRespDTO 转换为 TagDimension 实体
*
* @param dto DTO 对象
* @return 实体对象
*/
private TagDimension convertToDimensionEntity(TagDimensionRespDTO dto) {
TagDimension entity = new TagDimension();
entity.setId(dto.getId());
entity.setDimensionCode(dto.getDimensionCode());
entity.setDimensionName(dto.getDimensionName());
entity.setCategoryId(dto.getCategoryId());
return entity;
}
/**
* 将 TagEnumRespDTO 转换为 TagEnum 实体
*
* @param dto DTO 对象
* @return 实体对象
*/
private TagEnum convertToEnumEntity(TagEnumRespDTO dto) {
TagEnum entity = new TagEnum();
entity.setId(dto.getId());
entity.setEnumCode(dto.getEnumCode());
entity.setEnumName(dto.getEnumName());
entity.setDimensionId(dto.getDimensionId());
entity.setScore(dto.getScore());
return entity;
}
/**
* 分页获取客户标签数据
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param pageNo 页码
* @return 数据列表
*/
private List<InspectionCustomerTagDTO> fetchCustomerTagData(String startTime, String endTime, int pageNo) {
try {
RpcPagination<InspectionCustomerTagPageRequestDTO> request = new RpcPagination<>();
request.setPageNum(pageNo);
request.setPageSize(PAGE_SIZE);
InspectionCustomerTagPageRequestDTO condition = new InspectionCustomerTagPageRequestDTO();
condition.setStartTime(startTime);
condition.setEndTime(endTime);
condition.setResultFlag(RESULT_FLAG_SUCCESS);
request.setCondition(condition);
RpcResponse<RpcPagination<InspectionCustomerTagDTO>> response =
inspectionCustomerTagRemote.inspectionCustomerTagPage(request);
if (response == null || !response.isSuccess()) {
log.error("调用远程接口失败,response={}", response);
return null;
}
RpcPagination<InspectionCustomerTagDTO> result = response.getResult();
if (result == null || CollectionUtils.isEmpty(result.getList())) {
return null;
}
return result.getList();
} catch (Exception e) {
log.error("调用远程接口异常", e);
return null;
}
}
/**
* 处理单条客户标签数据
*
* @param data 客户标签数据
* @return 插入的标签数量
*/
@Transactional(rollbackFor = Exception.class)
public int processCustomerTagData(InspectionCustomerTagDTO data) {
String phone = data.getCustomerPhone();
String tagResult = data.getTagResult();
Integer recordId = data.getRecordId();
if (StrUtil.isBlank(phone) || StrUtil.isBlank(tagResult)) {
log.debug("手机号或标签结果为空,跳过处理,recordId={}", recordId);
return 0;
}
// 收集匹配到的维度代码
Set<String> matchedDimensionCodes = new HashSet<>();
// 解析标签 JSON
List<CustomerTagProfile> profileList = parseTagResult(phone, tagResult, recordId, matchedDimensionCodes);
if (CollectionUtils.isEmpty(profileList)) {
log.debug("解析标签结果为空,recordId={}", recordId);
return 0;
}
// 按维度删除该用户原有的 AI 来源标签(只删除匹配到的维度)
if (!matchedDimensionCodes.isEmpty()) {
List<String> dimensionCodeList = new ArrayList<>(matchedDimensionCodes);
customerTagProfileMapper.deleteByPhoneAndSourceTypeAndDimensionCodes(
phone, SOURCE_TYPE_AI, dimensionCodeList);
}
// 批量插入新标签
batchInsertProfiles(profileList);
return profileList.size();
}
/**
* 解析标签 JSON 结果
* 只保留与数据库中现有维度和枚举值匹配的标签
*
* @param phone 手机号
* @param tagResult 标签 JSON
* @param recordId 录音ID
* @param matchedDimensionCodes 收集匹配到的维度代码
* @return 标签画像列表
*/
private List<CustomerTagProfile> parseTagResult(String phone, String tagResult, Integer recordId,
Set<String> matchedDimensionCodes) {
List<CustomerTagProfile> result = new ArrayList<>();
try {
JSONObject root = JSONUtil.parseObj(tagResult);
JSONObject customerTag = root.getJSONObject("客户标签");
if (customerTag == null) {
log.warn("标签JSON格式不正确,缺少'客户标签'字段,recordId={}", recordId);
return result;
}
// 遍历所有类别(如:需求挖掘能力、异议处理能力、成交意识强度)
for (String categoryName : customerTag.keySet()) {
JSONObject category = customerTag.getJSONObject(categoryName);
if (category == null) {
continue;
}
// 遍历该类别下的所有维度
for (String dimensionName : category.keySet()) {
JSONObject dimension = category.getJSONObject(dimensionName);
if (dimension == null) {
continue;
}
// 匹配数据库中的维度
TagDimension matchedDimension = dimensionCache.get(dimensionName);
if (matchedDimension == null) {
log.debug("维度名称未匹配到数据库记录,跳过,dimensionName={}, recordId={}",
dimensionName, recordId);
continue;
}
// 收集匹配到的维度代码
matchedDimensionCodes.add(matchedDimension.getDimensionCode());
// 解析该维度下的标签值
parseDimensionTags(dimension, matchedDimension, phone, recordId, result);
}
}
} catch (Exception e) {
log.error("解析标签JSON失败,recordId={}, tagResult={}", recordId, tagResult, e);
}
return result;
}
/**
* 解析单个维度的标签值
*
* @param dimension 维度JSON
* @param matchedDimension 匹配到的维度实体
* @param phone 手机号
* @param recordId 录音ID
* @param result 结果列表
*/
private void parseDimensionTags(JSONObject dimension, TagDimension matchedDimension,
String phone, Integer recordId, List<CustomerTagProfile> result) {
Object tagValue = dimension.get("标签");
String basis = dimension.getStr("依据");
// 处理标签值(可能是字符串或数组)
List<String> tagValues = new ArrayList<>();
if (tagValue instanceof List) {
List<?> tagList = (List<?>) tagValue;
for (Object obj : tagList) {
if (obj != null) {
tagValues.add(String.valueOf(obj));
}
}
} else if (tagValue != null) {
tagValues.add(String.valueOf(tagValue));
}
// 遍历每个标签值,匹配枚举并创建画像
for (String enumName : tagValues) {
if (StrUtil.isBlank(enumName)) {
continue;
}
// 匹配数据库中的枚举值
TagEnum matchedEnum = matchEnumByName(matchedDimension.getId(), enumName);
if (matchedEnum == null) {
log.debug("枚举名称未匹配到数据库记录,跳过,dimensionName={}, enumName={}, recordId={}",
matchedDimension.getDimensionName(), enumName, recordId);
continue;
}
// 创建标签画像
createProfile(phone, matchedDimension, matchedEnum, basis, recordId, result);
}
}
/**
* 根据枚举名称匹配枚举值
*
* @param dimensionId 维度ID
* @param enumName 枚举名称
* @return 匹配到的枚举实体,未匹配返回null
*/
private TagEnum matchEnumByName(Integer dimensionId, String enumName) {
Map<String, TagEnum> enumNameMap = enumCache.get(dimensionId);
if (enumNameMap == null) {
return null;
}
return enumNameMap.get(enumName);
}
/**
* 创建标签画像实体
*
* @param phone 手机号
* @param matchedDimension 匹配到的维度
* @param matchedEnum 匹配到的枚举值
* @param scoreBasis 评分依据
* @param recordId 录音ID
* @param result 结果列表
*/
private void createProfile(String phone, TagDimension matchedDimension, TagEnum matchedEnum,
String scoreBasis, Integer recordId, List<CustomerTagProfile> result) {
CustomerTagProfile profile = new CustomerTagProfile();
profile.setPhone(phone);
profile.setCategoryCode(getCategoryCode(matchedDimension.getCategoryId()));
profile.setDimensionCode(matchedDimension.getDimensionCode());
profile.setEnumCode(matchedEnum.getEnumCode());
profile.setScoreBasis(scoreBasis);
profile.setScore(matchedEnum.getScore());
profile.setSourceType(SOURCE_TYPE_AI);
profile.setSourceRefId(String.valueOf(recordId));
profile.setDeletedFlag("N");
result.add(profile);
}
/**
* 根据分类ID获取分类代码
*
* @param categoryId 分类ID
* @return 分类代码
*/
private String getCategoryCode(Integer categoryId) {
if (categoryId == null) {
return null;
}
return categoryCodeCache.get(categoryId);
}
/**
* 批量插入标签画像
*
* @param profileList 标签画像列表
*/
private void batchInsertProfiles(List<CustomerTagProfile> profileList) {
if (CollectionUtils.isEmpty(profileList)) {
return;
}
// 分批插入
for (int i = 0; i < profileList.size(); i += BATCH_INSERT_SIZE) {
int end = Math.min(i + BATCH_INSERT_SIZE, profileList.size());
List<CustomerTagProfile> batch = profileList.subList(i, end);
customerTagProfileMapper.batchInsert(batch);
}
}
}
......@@ -167,6 +167,7 @@ public class GopApiUtil {
/**
* MD5加密(32位)
* 注意:使用平台默认编码,与 GopUtil 保持一致
*
* @param s 原字符串
* @return 加密后的字符串
......@@ -174,7 +175,7 @@ public class GopApiUtil {
private static String md5(String s) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
byte[] bytes = s.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
bytes = md.digest();
......
......@@ -40,4 +40,34 @@
AND category_code = #{categoryCode}
</delete>
<!-- 根据手机号和来源类型物理删除记录 -->
<delete id="deleteByPhoneAndSourceType">
DELETE FROM dj_car_life_customer_tag_profile
WHERE phone = #{phone}
AND source_type = #{sourceType}
</delete>
<!-- 根据手机号、来源类型和维度代码列表物理删除记录 -->
<delete id="deleteByPhoneAndSourceTypeAndDimensionCodes">
DELETE FROM dj_car_life_customer_tag_profile
WHERE phone = #{phone}
AND source_type = #{sourceType}
AND dimension_code IN
<foreach collection="dimensionCodes" item="dimensionCode" open="(" separator="," close=")">
#{dimensionCode}
</foreach>
</delete>
<!-- 批量插入标签画像 -->
<insert id="batchInsert">
INSERT INTO dj_car_life_customer_tag_profile
(phone, category_code, dimension_code, enum_code, score_basis, score, source_type, source_ref_id, create_time, update_time, deleted_flag)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.phone}, #{item.categoryCode}, #{item.dimensionCode}, #{item.enumCode},
#{item.scoreBasis}, #{item.score}, #{item.sourceType}, #{item.sourceRefId},
NOW(), NOW(), 'N')
</foreach>
</insert>
</mapper>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!