2 Commits 67da7aa6bd ... 08780d3818

Autor SHA1 Mensagem Data
  18118724055@163.com 08780d3818 Merge remote-tracking branch 'origin/master' 2 semanas atrás
  18118724055@163.com be8171b18b 客户分析模块python代码改java代码 2 semanas atrás
15 arquivos alterados com 696 adições e 1 exclusões
  1. 14 0
      java/storlead-api/src/main/resources/application.yml
  2. 41 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/config/CustomerAnalysisWorkflowProperties.java
  3. 15 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/constant/CustomerAnalysisConstants.java
  4. 15 1
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/controller/CustomerAiAnalysisController.java
  5. 54 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/dto/CustomerAnalysisSaveDTO.java
  6. 64 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/entity/CustomerAnalysisRecordEntity.java
  7. 9 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/mapper/CustomerAnalysisRecordEntityMapper.java
  8. 7 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/CustomerAnalysisRecordEntityService.java
  9. 15 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/CustomerAnalysisSaveService.java
  10. 12 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/CustomerAnalysisWorkflowService.java
  11. 16 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/CustomerAnalysisRecordEntityServiceImpl.java
  12. 207 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/CustomerAnalysisSaveServiceImpl.java
  13. 136 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/CustomerAnalysisWorkflowServiceImpl.java
  14. 65 0
      java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/task/CustomerAnalysisWorkflowTask.java
  15. 26 0
      java/storlead-sasa/storlead-trade/src/main/resources/sql/customer_analysis_record.sql

+ 14 - 0
java/storlead-api/src/main/resources/application.yml

@@ -133,6 +133,20 @@ storlead:
     renew-interval-ms: 10000
     thread-pool-size: 8
     default-timeout-sec: 300
+  # 客户分析工作流投递(对齐 schedule_workflow_job.py)
+  trade:
+    customer-analysis:
+      workflow:
+        enabled: true
+        url: http://192.168.1.77/v1/workflows/run
+        # Authorization Bearer token,勿提交真实密钥到公共仓库时可改配到 application-*.yml
+        api-key: app-3rhnhpC4DvVa2indhA2C4TVw
+        user: admin-schedule
+        response-mode: blocking
+        batch-size: 20
+        interval-ms: 10000
+        timeout-ms: 300000
+        stale-days: 30
 
 management:
   health:

+ 41 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/config/CustomerAnalysisWorkflowProperties.java

@@ -0,0 +1,41 @@
+package com.storlead.trade.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 客户分析工作流投递配置(对齐 Python schedule_workflow_job.py)。
+ */
+@Data
+@Component
+@ConfigurationProperties(prefix = "storlead.trade.customer-analysis.workflow")
+public class CustomerAnalysisWorkflowProperties {
+
+    /** 是否启用定时投递 */
+    private boolean enabled = true;
+
+    /** Dify / 工作流地址,如 http://xxx/v1/workflows/run */
+    private String url = "http://192.168.1.77/v1/workflows/run";
+
+    /** Authorization: Bearer {apiKey} */
+    private String apiKey = "";
+
+    /** 请求用户标识 */
+    private String user = "admin-schedule";
+
+    /** 响应模式:blocking / streaming */
+    private String responseMode = "blocking";
+
+    /** 每轮最多投递条数(防一次打爆下游) */
+    private int batchSize = 20;
+
+    /** HTTP 超时毫秒(Python 为 3000 秒,这里默认 5 分钟,可配) */
+    private long timeoutMs = 300_000L;
+
+    /** 调度间隔毫秒(对齐 Python every 10 seconds) */
+    private long intervalMs = 1000 * 60 * 60 * 2;
+
+    /** 超过多少天未更新视为过期重投(默认 30) */
+    private int staleDays = 30;
+}

+ 15 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/constant/CustomerAnalysisConstants.java

@@ -13,11 +13,26 @@ public final class CustomerAnalysisConstants {
      */
     public static final int ANALYSIS_STATUS_PENDING = -1;
 
+    /**
+     * 分析中(已投递工作流,等待回调写回)
+     */
+    public static final int ANALYSIS_STATUS_RUNNING = 0;
+
+    /**
+     * 分析成功
+     */
+    public static final int ANALYSIS_STATUS_SUCCESS = 1;
+
     /**
      * 无效客户(垃圾客户)标记
      */
     public static final int GARBAGE_CUSTOMER_YES = 1;
 
+    /**
+     * 超过该天数未更新则重新投递分析(对齐 schedule_workflow_job datediff > 30)
+     */
+    public static final int STALE_DAYS = 30;
+
     /**
      * 同一客户再次投递间隔天数
      */

+ 15 - 1
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/controller/CustomerAiAnalysisController.java

@@ -6,11 +6,12 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.storlead.framework.common.constant.CommonConstant;
 import com.storlead.framework.common.result.Result;
 import com.storlead.trade.dto.CustomerAnalysisResultDTO;
+import com.storlead.trade.dto.CustomerAnalysisSaveDTO;
 import com.storlead.trade.dto.CustomerSingleAnalysisRequestDTO;
 import com.storlead.trade.entity.CustomerAnalysisResultEntity;
-import com.storlead.trade.entity.SopEntity;
 import com.storlead.trade.service.CustomerAiAnalysisService;
 import com.storlead.trade.service.CustomerAnalysisResultEntityService;
+import com.storlead.trade.service.CustomerAnalysisSaveService;
 import com.storlead.trade.vo.CustomerAnalysisResultVO;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -38,6 +39,19 @@ public class CustomerAiAnalysisController {
     @Resource
     private CustomerAnalysisResultEntityService customerAnalysisResultEntityService;
 
+    @Resource
+    private CustomerAnalysisSaveService customerAnalysisSaveService;
+
+    /**
+     * 对齐 Python save_data_api:PUT /analysis/update。
+     * 先写 customer_analysis_record 流水,再按 customer_id upsert customer_analysis_result。
+     */
+    @RequestMapping(value = "/update", method = {RequestMethod.PUT, RequestMethod.POST})
+    @ApiOperation("按 customerId 更新或新增分析结果(并写流水)")
+    public Result<Object> updateOrInsert(@RequestBody CustomerAnalysisSaveDTO dto) {
+        return customerAnalysisSaveService.updateOrInsert(dto);
+    }
+
     @PostMapping("/single")
     @ApiOperation("单营销: 客户AI分析并保存结果")
     public Result<Object> analyzeSingle(@RequestBody CustomerSingleAnalysisRequestDTO request) {

+ 54 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/dto/CustomerAnalysisSaveDTO.java

@@ -0,0 +1,54 @@
+package com.storlead.trade.dto;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+/**
+ * 对齐 Python save_data_api:PUT /analysis/update 入参。
+ * <p>
+ * {@code coreTags}/{@code featureSnapshot} 可为 String,或 JSON 数组/对象(写入前序列化为字符串)。
+ */
+@Data
+@ApiModel("客户分析结果保存/更新")
+public class CustomerAnalysisSaveDTO {
+
+    @ApiModelProperty(value = "客户ID(必填)", required = true)
+    private Long customerId;
+
+    @ApiModelProperty(value = "分析场景")
+    private String analysisScene;
+
+    @ApiModelProperty(value = "分析状态")
+    private Integer analysisStatus;
+
+    @ApiModelProperty(value = "潜力分")
+    private Double potentialScore;
+
+    @ApiModelProperty(value = "客户等级")
+    private String customerLevel;
+
+    @ApiModelProperty(value = "置信度")
+    private Double confidence;
+
+    @ApiModelProperty(value = "优先级")
+    private Integer priority;
+
+    @ApiModelProperty(value = "核心标签(String 或 JSON 数组)")
+    private Object coreTags;
+
+    @ApiModelProperty(value = "分析摘要")
+    private String reasonSummary;
+
+    @ApiModelProperty(value = "特征快照(String 或 JSON 对象)")
+    private Object featureSnapshot;
+
+    @ApiModelProperty(value = "模型名称")
+    private String modelName;
+
+    @ApiModelProperty(value = "模型版本")
+    private String modelVersion;
+
+    @ApiModelProperty(value = "提示词版本")
+    private String promptVersion;
+}

+ 64 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/entity/CustomerAnalysisRecordEntity.java

@@ -0,0 +1,64 @@
+package com.storlead.trade.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.storlead.framework.mybatis.entity.TenantBaseField;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * 客户分析流水(每次 upsert 结果前先落一条历史)。
+ * 对应表:customer_analysis_record
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+@TableName("customer_analysis_record")
+@ApiModel(value = "CustomerAnalysisRecordEntity", description = "客户分析流水记录")
+public class CustomerAnalysisRecordEntity extends TenantBaseField {
+
+    @TableId(type = IdType.AUTO)
+    @ApiModelProperty(value = "主键ID")
+    private Long id;
+
+    @ApiModelProperty(value = "客户ID")
+    private Long customerId;
+
+    @ApiModelProperty(value = "分析场景")
+    private String analysisScene;
+
+    @ApiModelProperty(value = "分析状态")
+    private Integer analysisStatus;
+
+    @ApiModelProperty(value = "潜力分")
+    private Double potentialScore;
+
+    @ApiModelProperty(value = "客户等级")
+    private String customerLevel;
+
+    @ApiModelProperty(value = "置信度")
+    private Double confidence;
+
+    @ApiModelProperty(value = "优先级")
+    private Integer priority;
+
+    @ApiModelProperty(value = "核心标签(JSON 字符串)")
+    private String coreTags;
+
+    @ApiModelProperty(value = "分析摘要")
+    private String reasonSummary;
+
+    @ApiModelProperty(value = "特征快照(JSON 字符串)")
+    private String featureSnapshot;
+
+    @ApiModelProperty(value = "模型名称")
+    private String modelName;
+
+    @ApiModelProperty(value = "模型版本")
+    private String modelVersion;
+
+    @ApiModelProperty(value = "提示词版本")
+    private String promptVersion;
+}

+ 9 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/mapper/CustomerAnalysisRecordEntityMapper.java

@@ -0,0 +1,9 @@
+package com.storlead.trade.mapper;
+
+import com.storlead.trade.entity.CustomerAnalysisRecordEntity;
+import com.storlead.trade.mapper.support.TradeBaseMapper;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface CustomerAnalysisRecordEntityMapper extends TradeBaseMapper<CustomerAnalysisRecordEntity> {
+}

+ 7 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/CustomerAnalysisRecordEntityService.java

@@ -0,0 +1,7 @@
+package com.storlead.trade.service;
+
+import com.storlead.framework.mybatis.service.MyBaseService;
+import com.storlead.trade.entity.CustomerAnalysisRecordEntity;
+
+public interface CustomerAnalysisRecordEntityService extends MyBaseService<CustomerAnalysisRecordEntity> {
+}

+ 15 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/CustomerAnalysisSaveService.java

@@ -0,0 +1,15 @@
+package com.storlead.trade.service;
+
+import com.storlead.framework.common.result.Result;
+import com.storlead.trade.dto.CustomerAnalysisSaveDTO;
+
+/**
+ * 对齐 Python save_data_api:先写流水,再按 customer_id upsert 分析结果。
+ */
+public interface CustomerAnalysisSaveService {
+
+    /**
+     * @return result 中含 action(updated/inserted)、affected
+     */
+    Result<Object> updateOrInsert(CustomerAnalysisSaveDTO dto);
+}

+ 12 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/CustomerAnalysisWorkflowService.java

@@ -0,0 +1,12 @@
+package com.storlead.trade.service;
+
+/**
+ * 捞取待分析客户并投递到外部工作流(对齐 schedule_workflow_job.py)。
+ */
+public interface CustomerAnalysisWorkflowService {
+
+    /**
+     * @return 本轮成功发起调用的条数
+     */
+    int dispatchPending();
+}

+ 16 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/CustomerAnalysisRecordEntityServiceImpl.java

@@ -0,0 +1,16 @@
+package com.storlead.trade.service.impl;
+
+import com.baomidou.dynamic.datasource.annotation.DS;
+import com.storlead.framework.common.constant.DSConstants;
+import com.storlead.trade.entity.CustomerAnalysisRecordEntity;
+import com.storlead.trade.mapper.CustomerAnalysisRecordEntityMapper;
+import com.storlead.trade.service.CustomerAnalysisRecordEntityService;
+import com.storlead.trade.service.impl.support.TradeDataSourceServiceImpl;
+import org.springframework.stereotype.Service;
+
+@Service
+@DS(DSConstants.DATASOURCE_TRADE)
+public class CustomerAnalysisRecordEntityServiceImpl
+        extends TradeDataSourceServiceImpl<CustomerAnalysisRecordEntityMapper, CustomerAnalysisRecordEntity>
+        implements CustomerAnalysisRecordEntityService {
+}

+ 207 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/CustomerAnalysisSaveServiceImpl.java

@@ -0,0 +1,207 @@
+package com.storlead.trade.service.impl;
+
+import com.baomidou.dynamic.datasource.annotation.DS;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.storlead.framework.common.constant.CommonConstant;
+import com.storlead.framework.common.constant.DSConstants;
+import com.storlead.framework.common.result.Result;
+import com.storlead.trade.dto.CustomerAnalysisSaveDTO;
+import com.storlead.trade.entity.CustomerAnalysisRecordEntity;
+import com.storlead.trade.entity.CustomerAnalysisResultEntity;
+import com.storlead.trade.service.CustomerAnalysisRecordEntityService;
+import com.storlead.trade.service.CustomerAnalysisResultEntityService;
+import com.storlead.trade.service.CustomerAnalysisSaveService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.dao.DuplicateKeyException;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 对齐 Python save_data_api.py 的 /analysis/update 逻辑。
+ */
+@Slf4j
+@Service
+@DS(DSConstants.DATASOURCE_TRADE)
+public class CustomerAnalysisSaveServiceImpl implements CustomerAnalysisSaveService {
+
+    @Resource
+    private CustomerAnalysisResultEntityService resultService;
+    @Resource
+    private CustomerAnalysisRecordEntityService recordService;
+    @Resource
+    private ObjectMapper objectMapper;
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Object> updateOrInsert(CustomerAnalysisSaveDTO dto) {
+        if (dto == null || dto.getCustomerId() == null) {
+            return Result.error("Missing required field: customer_id");
+        }
+        if (!hasAnyUpdatableField(dto)) {
+            return Result.error("No valid fields to update");
+        }
+
+        String coreTags = serializeForMysql(dto.getCoreTags());
+        String featureSnapshot = serializeForMysql(dto.getFeatureSnapshot());
+
+        try {
+            // 1. 先写流水(对齐 Python 每次调用都 insert record)
+            CustomerAnalysisRecordEntity record = new CustomerAnalysisRecordEntity();
+            record.setCustomerId(dto.getCustomerId());
+            record.setAnalysisScene(dto.getAnalysisScene());
+            record.setAnalysisStatus(dto.getAnalysisStatus());
+            record.setPotentialScore(dto.getPotentialScore());
+            record.setCustomerLevel(dto.getCustomerLevel());
+            record.setConfidence(dto.getConfidence());
+            record.setPriority(dto.getPriority());
+            record.setCoreTags(coreTags);
+            record.setReasonSummary(dto.getReasonSummary());
+            record.setFeatureSnapshot(featureSnapshot);
+            record.setModelName(dto.getModelName());
+            record.setModelVersion(dto.getModelVersion());
+            record.setPromptVersion(dto.getPromptVersion());
+            record.setIsDelete(CommonConstant.DEL_FLAG_0);
+            recordService.save(record);
+
+            // 2. 按 customer_id 查结果表
+            CustomerAnalysisResultEntity existing = resultService.getOne(
+                    new LambdaQueryWrapper<CustomerAnalysisResultEntity>()
+                            .eq(CustomerAnalysisResultEntity::getCustomerId, dto.getCustomerId())
+                            .eq(CustomerAnalysisResultEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                            .orderByDesc(CustomerAnalysisResultEntity::getId)
+                            .last("limit 1"),
+                    false);
+
+            Map<String, Object> resp = new HashMap<>(4);
+            if (existing != null) {
+                LambdaUpdateWrapper<CustomerAnalysisResultEntity> uw = new LambdaUpdateWrapper<>();
+                uw.eq(CustomerAnalysisResultEntity::getId, existing.getId());
+                applyUpdateFields(uw, dto, coreTags, featureSnapshot);
+                uw.set(CustomerAnalysisResultEntity::getAnalysisTime, new Date());
+                boolean ok = resultService.update(uw);
+                resp.put("action", "updated");
+                resp.put("affected", ok ? 1 : 0);
+                resp.put("id", existing.getId());
+            } else {
+                CustomerAnalysisResultEntity insert = new CustomerAnalysisResultEntity();
+                insert.setCustomerId(dto.getCustomerId());
+                applyInsertFields(insert, dto, coreTags, featureSnapshot);
+                insert.setAnalysisTime(new Date());
+                insert.setIsDelete(CommonConstant.DEL_FLAG_0);
+                resultService.save(insert);
+                resp.put("action", "inserted");
+                resp.put("affected", 1);
+                resp.put("id", insert.getId());
+            }
+            return Result.result(resp);
+        } catch (DuplicateKeyException e) {
+            log.warn("customer analysis upsert duplicate, customerId={}", dto.getCustomerId(), e);
+            return Result.error("Duplicate entry: " + e.getMessage());
+        } catch (Exception e) {
+            log.error("customer analysis upsert error, customerId={}", dto.getCustomerId(), e);
+            throw e;
+        }
+    }
+
+    private static boolean hasAnyUpdatableField(CustomerAnalysisSaveDTO dto) {
+        return StringUtils.hasText(dto.getAnalysisScene())
+                || dto.getAnalysisStatus() != null
+                || dto.getPotentialScore() != null
+                || StringUtils.hasText(dto.getCustomerLevel())
+                || dto.getConfidence() != null
+                || dto.getPriority() != null
+                || dto.getCoreTags() != null
+                || StringUtils.hasText(dto.getReasonSummary())
+                || dto.getFeatureSnapshot() != null
+                || StringUtils.hasText(dto.getModelName())
+                || StringUtils.hasText(dto.getModelVersion())
+                || StringUtils.hasText(dto.getPromptVersion());
+    }
+
+    private void applyUpdateFields(LambdaUpdateWrapper<CustomerAnalysisResultEntity> uw,
+                                   CustomerAnalysisSaveDTO dto,
+                                   String coreTags,
+                                   String featureSnapshot) {
+        if (StringUtils.hasText(dto.getAnalysisScene())) {
+            uw.set(CustomerAnalysisResultEntity::getAnalysisScene, dto.getAnalysisScene());
+        }
+        if (dto.getAnalysisStatus() != null) {
+            uw.set(CustomerAnalysisResultEntity::getAnalysisStatus, dto.getAnalysisStatus());
+        }
+        if (dto.getPotentialScore() != null) {
+            uw.set(CustomerAnalysisResultEntity::getPotentialScore, dto.getPotentialScore());
+        }
+        if (StringUtils.hasText(dto.getCustomerLevel())) {
+            uw.set(CustomerAnalysisResultEntity::getCustomerLevel, dto.getCustomerLevel());
+        }
+        if (dto.getConfidence() != null) {
+            uw.set(CustomerAnalysisResultEntity::getConfidence, dto.getConfidence());
+        }
+        if (dto.getPriority() != null) {
+            uw.set(CustomerAnalysisResultEntity::getPriority, dto.getPriority());
+        }
+        if (dto.getCoreTags() != null) {
+            uw.set(CustomerAnalysisResultEntity::getCoreTags, coreTags);
+        }
+        if (StringUtils.hasText(dto.getReasonSummary())) {
+            uw.set(CustomerAnalysisResultEntity::getReasonSummary, dto.getReasonSummary());
+        }
+        if (dto.getFeatureSnapshot() != null) {
+            uw.set(CustomerAnalysisResultEntity::getFeatureSnapshot, featureSnapshot);
+        }
+        if (StringUtils.hasText(dto.getModelName())) {
+            uw.set(CustomerAnalysisResultEntity::getModelName, dto.getModelName());
+        }
+        if (StringUtils.hasText(dto.getModelVersion())) {
+            uw.set(CustomerAnalysisResultEntity::getModelVersion, dto.getModelVersion());
+        }
+        if (StringUtils.hasText(dto.getPromptVersion())) {
+            uw.set(CustomerAnalysisResultEntity::getPromptVersion, dto.getPromptVersion());
+        }
+    }
+
+    private void applyInsertFields(CustomerAnalysisResultEntity entity,
+                                   CustomerAnalysisSaveDTO dto,
+                                   String coreTags,
+                                   String featureSnapshot) {
+        entity.setAnalysisScene(dto.getAnalysisScene());
+        entity.setAnalysisStatus(dto.getAnalysisStatus());
+        entity.setPotentialScore(dto.getPotentialScore());
+        entity.setCustomerLevel(dto.getCustomerLevel());
+        entity.setConfidence(dto.getConfidence());
+        entity.setPriority(dto.getPriority());
+        entity.setCoreTags(coreTags);
+        entity.setReasonSummary(dto.getReasonSummary());
+        entity.setFeatureSnapshot(featureSnapshot);
+        entity.setModelName(dto.getModelName());
+        entity.setModelVersion(dto.getModelVersion());
+        entity.setPromptVersion(dto.getPromptVersion());
+    }
+
+    /** 对齐 Python serialize_for_mysql:dict/list → JSON 字符串 */
+    private String serializeForMysql(Object value) {
+        if (value == null) {
+            return null;
+        }
+        if (value instanceof String) {
+            return (String) value;
+        }
+        if (value instanceof Map || value instanceof Iterable || value.getClass().isArray()) {
+            try {
+                return objectMapper.writeValueAsString(value);
+            } catch (JsonProcessingException e) {
+                throw new IllegalArgumentException("字段无法序列化为 JSON: " + e.getMessage(), e);
+            }
+        }
+        return String.valueOf(value);
+    }
+}

+ 136 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/service/impl/CustomerAnalysisWorkflowServiceImpl.java

@@ -0,0 +1,136 @@
+package com.storlead.trade.service.impl;
+
+import com.baomidou.dynamic.datasource.annotation.DS;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.storlead.framework.common.constant.CommonConstant;
+import com.storlead.framework.common.constant.DSConstants;
+import com.storlead.trade.config.CustomerAnalysisWorkflowProperties;
+import com.storlead.trade.constant.CustomerAnalysisConstants;
+import com.storlead.trade.entity.CustomerAnalysisResultEntity;
+import com.storlead.trade.service.CustomerAnalysisResultEntityService;
+import com.storlead.trade.service.CustomerAnalysisWorkflowService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.client.SimpleClientHttpRequestFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
+import org.springframework.web.client.RestTemplate;
+
+import javax.annotation.Resource;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 对齐 Python schedule_workflow_job.py:
+ * 1) 查 status=-1 或 update_time 超过 N 天
+ * 2) 先把 status 置为 0
+ * 3) POST 工作流(blocking),结果由回调写回 /customer/analysis/update
+ */
+@Slf4j
+@Service
+@DS(DSConstants.DATASOURCE_TRADE)
+public class CustomerAnalysisWorkflowServiceImpl implements CustomerAnalysisWorkflowService {
+
+    @Resource
+    private CustomerAnalysisResultEntityService resultService;
+    @Resource
+    private CustomerAnalysisWorkflowProperties properties;
+
+    @Override
+    public int dispatchPending() {
+        if (!properties.isEnabled()) {
+            return 0;
+        }
+        if (!StringUtils.hasText(properties.getUrl())) {
+            log.warn("[CustomerAnalysisWorkflow] url 未配置,跳过");
+            return 0;
+        }
+
+        List<CustomerAnalysisResultEntity> pending = fetchPending();
+        if (CollectionUtils.isEmpty(pending)) {
+            return 0;
+        }
+
+        RestTemplate restTemplate = buildRestTemplate();
+        int ok = 0;
+        for (CustomerAnalysisResultEntity record : pending) {
+            try {
+                analyzeOne(restTemplate, record);
+                ok++;
+            } catch (Exception e) {
+                log.error("[CustomerAnalysisWorkflow] 分析失败 recordId={}, customerId={}: {}",
+                        record.getId(), record.getCustomerId(), e.getMessage(), e);
+            }
+        }
+        return ok;
+    }
+
+    private List<CustomerAnalysisResultEntity> fetchPending() {
+        Date staleBefore = daysAgo(properties.getStaleDays() > 0
+                ? properties.getStaleDays() : CustomerAnalysisConstants.STALE_DAYS);
+        int limit = Math.max(1, properties.getBatchSize());
+
+        return resultService.list(new LambdaQueryWrapper<CustomerAnalysisResultEntity>()
+                .select(CustomerAnalysisResultEntity::getId, CustomerAnalysisResultEntity::getCustomerId)
+                .eq(CustomerAnalysisResultEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                .and(w -> w.eq(CustomerAnalysisResultEntity::getAnalysisStatus,
+                                CustomerAnalysisConstants.ANALYSIS_STATUS_PENDING)
+                        .or()
+                        .lt(CustomerAnalysisResultEntity::getUpdateTime, staleBefore))
+                .isNotNull(CustomerAnalysisResultEntity::getCustomerId)
+                .orderByAsc(CustomerAnalysisResultEntity::getId)
+                .last("LIMIT " + limit));
+    }
+
+    private void analyzeOne(RestTemplate restTemplate, CustomerAnalysisResultEntity record) {
+        // 先置为分析中(对齐 Python update_status(..., 0))
+        resultService.update(new LambdaUpdateWrapper<CustomerAnalysisResultEntity>()
+                .eq(CustomerAnalysisResultEntity::getId, record.getId())
+                .set(CustomerAnalysisResultEntity::getAnalysisStatus,
+                        CustomerAnalysisConstants.ANALYSIS_STATUS_RUNNING)
+                .set(CustomerAnalysisResultEntity::getUpdateTime, new Date()));
+
+        Map<String, Object> inputs = new HashMap<>(2);
+        inputs.put("customer_id", record.getCustomerId());
+
+        Map<String, Object> payload = new LinkedHashMap<>(4);
+        payload.put("inputs", inputs);
+        payload.put("response_mode", properties.getResponseMode());
+        payload.put("user", properties.getUser());
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        if (StringUtils.hasText(properties.getApiKey())) {
+            String key = properties.getApiKey().trim();
+            headers.set(HttpHeaders.AUTHORIZATION,
+                    key.startsWith("Bearer ") ? key : "Bearer " + key);
+        }
+
+        log.info("[CustomerAnalysisWorkflow] 投递 recordId={}, customerId={}, url={}",
+                record.getId(), record.getCustomerId(), properties.getUrl());
+        restTemplate.postForEntity(properties.getUrl(), new HttpEntity<>(payload, headers), String.class);
+        log.info("[CustomerAnalysisWorkflow] done recordId={}", record.getId());
+    }
+
+    private RestTemplate buildRestTemplate() {
+        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
+        int timeout = (int) Math.min(Math.max(properties.getTimeoutMs(), 1000L), Integer.MAX_VALUE);
+        factory.setConnectTimeout(Math.min(timeout, 30_000));
+        factory.setReadTimeout(timeout);
+        return new RestTemplate(factory);
+    }
+
+    private static Date daysAgo(int days) {
+        Calendar c = Calendar.getInstance();
+        c.add(Calendar.DAY_OF_MONTH, -Math.max(days, 1));
+        return c.getTime();
+    }
+}

+ 65 - 0
java/storlead-sasa/storlead-trade/src/main/java/com/storlead/trade/task/CustomerAnalysisWorkflowTask.java

@@ -0,0 +1,65 @@
+package com.storlead.trade.task;
+
+import com.storlead.trade.config.CustomerAnalysisWorkflowProperties;
+import com.storlead.trade.service.CustomerAnalysisWorkflowService;
+import lombok.extern.slf4j.Slf4j;
+import org.redisson.api.RLock;
+import org.redisson.api.RedissonClient;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * 对齐 Python schedule_workflow_job.py:周期性捞取待分析客户并调用工作流。
+ * <p>
+ * 默认每 10 秒一轮(fixedDelay,上一轮结束后再等 interval);多实例用 Redis 锁防并发。
+ */
+@Slf4j
+@Component
+public class CustomerAnalysisWorkflowTask {
+
+    private static final String LOCK_KEY = "customer-analysis:workflow:dispatch:lock";
+
+    @Resource
+    private CustomerAnalysisWorkflowService customerAnalysisWorkflowService;
+    @Resource
+    private CustomerAnalysisWorkflowProperties properties;
+    @Resource
+    private RedissonClient redissonClient;
+
+    /**
+     * fixedDelayString 读取配置;未配时默认 10000ms。
+     */
+    @Scheduled(fixedDelayString = "${storlead.trade.customer-analysis.workflow.interval-ms:10000}")
+    public void run() {
+        if (!properties.isEnabled()) {
+            return;
+        }
+        RLock lock = redissonClient.getLock(LOCK_KEY);
+        boolean acquired = false;
+        try {
+            // 等 0:抢不到说明别的实例在跑;持锁最多 30 分钟防死锁
+            acquired = lock.tryLock(0, 30, TimeUnit.MINUTES);
+            if (!acquired) {
+                return;
+            }
+            long start = System.currentTimeMillis();
+            int count = customerAnalysisWorkflowService.dispatchPending();
+            if (count > 0) {
+                log.info("[CustomerAnalysisWorkflowTask] 本轮投递完成 count={}, cost={}ms",
+                        count, System.currentTimeMillis() - start);
+            }
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            log.warn("[CustomerAnalysisWorkflowTask] 获取锁被中断: {}", e.getMessage());
+        } catch (Exception e) {
+            log.error("[CustomerAnalysisWorkflowTask] 执行失败", e);
+        } finally {
+            if (acquired && lock.isHeldByCurrentThread()) {
+                lock.unlock();
+            }
+        }
+    }
+}

+ 26 - 0
java/storlead-sasa/storlead-trade/src/main/resources/sql/customer_analysis_record.sql

@@ -0,0 +1,26 @@
+-- trade 库:客户分析流水表(对齐 Python save_data_api 写入的 customer_analysis_record)
+CREATE TABLE IF NOT EXISTS `customer_analysis_record` (
+    `id`                BIGINT       NOT NULL AUTO_INCREMENT COMMENT '主键',
+    `customer_id`       BIGINT       DEFAULT NULL COMMENT '客户ID',
+    `analysis_scene`    VARCHAR(64)  DEFAULT NULL COMMENT '分析场景',
+    `analysis_status`   INT          DEFAULT NULL COMMENT '分析状态',
+    `potential_score`   DOUBLE       DEFAULT NULL COMMENT '潜力分',
+    `customer_level`    VARCHAR(32)  DEFAULT NULL COMMENT '客户等级',
+    `confidence`        DOUBLE       DEFAULT NULL COMMENT '置信度',
+    `priority`          INT          DEFAULT NULL COMMENT '优先级',
+    `core_tags`         TEXT         DEFAULT NULL COMMENT '核心标签 JSON',
+    `reason_summary`    TEXT         DEFAULT NULL COMMENT '分析摘要',
+    `feature_snapshot`  TEXT         DEFAULT NULL COMMENT '特征快照 JSON',
+    `model_name`        VARCHAR(128) DEFAULT NULL COMMENT '模型名称',
+    `model_version`     VARCHAR(64)  DEFAULT NULL COMMENT '模型版本',
+    `prompt_version`    VARCHAR(64)  DEFAULT NULL COMMENT '提示词版本',
+    `tenant_id`         BIGINT       DEFAULT NULL COMMENT '租户ID',
+    `create_by`         BIGINT       DEFAULT NULL,
+    `update_by`         BIGINT       DEFAULT NULL,
+    `create_time`       DATETIME     DEFAULT CURRENT_TIMESTAMP,
+    `update_time`       DATETIME     DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    `is_delete`         TINYINT      NOT NULL DEFAULT 0,
+    PRIMARY KEY (`id`),
+    KEY `idx_car_customer_id` (`customer_id`),
+    KEY `idx_car_create_time` (`create_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客户分析流水记录';