TeamSupervisorWeeklyReportService.java 12.3 KB
package com.glsk.service;


import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.GenerationUsage;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glsk.component.HttpUtil;
import com.glsk.conf.ConfigurationManager;
import com.glsk.connection.MysqlConn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;

/**
 * 督导对其团队成员的周度工作表现进行汇总、分析与指导
 */
@Service
@Slf4j
public class TeamSupervisorWeeklyReportService {

    @Tool(description = "根据门店员工名称获取上周基础分析报告")
    public String getLastWeekBasicAnalysisReportByEmployee(
            @ToolParam(description = "门店名称") String merchantName,
            @ToolParam(description = "员工名称") String staffName
    ) {
        try {
            StringBuffer buffer = new StringBuffer();

            // 获取上周时间范围
            LocalDate today = LocalDate.now();
            LocalDate thisMonday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDate lastMonday = thisMonday.minusDays(7);
            LocalDate lastSunday = lastMonday.plusDays(6);
            LocalDateTime startTime = lastMonday.atStartOfDay();
            LocalDateTime endTime = lastSunday.atTime(23, 59, 59);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            System.out.println("开始时间: " + startTime.format(formatter));
            System.out.println("结束时间: " + endTime.format(formatter));

            Connection connection = MysqlConn.getConnection(ConfigurationManager.getProperty("mysql.url.dj_smartcarlife"));

            // 1 基于员工上周战败录音,使用大模进行归因分析
            String staffSql = String.format("select \n" +
                    "rci.merchant_id,\n" +
                    "dclsmcd.merchant_name,\n" +
                    "rci.sales_name,\n" +
                    "case when rci.bussiness_type = 1 then '延保' when rci.bussiness_type = 2 then '轻改' else null end as bussiness_type,\n" +
                    "rci.reception_start_time,\n" +
                    "case when rci.reception_status = 0 then '战败' when rci.reception_status = 2 then '成交轻改' else null end as reception_status,\n" +
                    "t.detail_json\n" +
                    "from reception_customer_info rci\n" +
                    "left join dj_car_life_shop_merchant_config dclsmcd on rci.merchant_id = dclsmcd.merchant_id and dclsmcd.deleted_flag = 'N' and dclsmcd.merchant_name = '%s' \n" +
                    "left join \n" +
                    "(\n" +
                    "select \n" +
                    "ibr.reception_id,\n" +
                    "det.detail_json\n" +
                    "from inspection_badge_recordings ibr\n" +
                    "left join inspection_conversation_batch icb ON icb.file_url = ibr.recording_url and icb.deleted_flag = 'N'  \n" +
                    "left join inspection_conversation_detail_ext det on icb.id=det.batch_id and icb.deleted_flag = 'N' and det.detail_json is not null\n" +
                    "where ibr.reception_id is not null and ibr.deleted_flag = 'N' and det.detail_json is not null\n" +
                    ") t on rci.id = t.reception_id \n" +
                    "where  rci.deleted_flag = 'N' and rci.reception_status = 0 and rci.sales_name = '%s' and dclsmcd.merchant_name = '%s' \n" +
                    "and t.reception_id is not null and rci.reception_start_time BETWEEN '%s' and '%s'", merchantName, staffName, merchantName, startTime.format(formatter), endTime.format(formatter));
            System.out.println(staffSql);
            ArrayList<ArrayList<String>> staffQuery = MysqlConn.executeQuery(connection, staffSql, 7);

            Constants.apiKey = "sk-48654db737cc4fdb91aad1f2af7562b8";
            Generation gen = new Generation();

            String system = "你是一个话术质检专家,擅长对话中找出本次销售推销产品失败的原因。";
            String user = "【需求背景】\n" +
                    "上述<content></content>中的内容是汽车销售在交车给车主时顺便推销汽车延长保修服务(简称延保)和推销安心包产品的对话。\n" +
                    "\n" +
                    "【需求详情】\n" +
                    "根据对话内容,进行判断本次战败的原因分析,一般常见原因如下:\n" +
                    "1. 知识讲解类\n" +
                    "车功能知识不熟\n" +
                    "业务讲解不熟\n" +
                    "专业知识需强化\n" +
                    "产品知识需强化\n" +
                    "2.处理疑虑类\n" +
                    "客户疑虑处理能力不足\n" +
                    "疑虑处理较弱\n" +
                    "异议处理能力待提高\n" +
                    "异议处理能力需提高\n" +
                    "客户异议处理能力待提升\n" +
                    "3.逼单类\n" +
                    "逼单能力不足\n" +
                    "逼单能力有待提升\n" +
                    "逼单方式单一\n" +
                    "逼单积极性高 \n" +
                    "\n" +
                    "根据对话内容进行本次战败进行分析,需要简练的话语进行阐述。\n" +
                    "观察到的导致战败的具体现象,概括战败缘由。";

            StringBuffer summaryBuff = new StringBuffer();
            int index = 0;
            for(ArrayList<String> query : staffQuery) {
                System.out.println("开始第"+ ++index + "个录音文本分析....");

//                if (index < 3) continue;

                String sbussinessType = query.get(3);
                String detailJson = query.get(6);

                ObjectMapper mapper = new ObjectMapper();
                List<Map<String, Object>> items = mapper.readValue(
                        detailJson, mapper.getTypeFactory().constructCollectionType(List.class, Map.class)
                );
                String text = items.stream()
                        .map(item -> (String) item.get("content"))
                        .collect(Collectors.joining("\n"));

//                System.out.println(text);

                List<Message> messages = new ArrayList<>();
                Message systemMessage = Message.builder().role(Role.SYSTEM.getValue()).content(system).build();
                Message userMessage = Message.builder().role(Role.USER.getValue()).content(String.format("<content>\n%s\n</content>\n%s\n", text, user)).build();
                messages.add(systemMessage);
                messages.add(userMessage);
                QwenParam param = QwenParam.builder()
                            .model("qwen-plus")
                            .messages(messages)
                            .resultFormat(QwenParam.ResultFormat.MESSAGE)
                            .maxTokens(8192)
                            .temperature(0.01F)
                            .build();

                GenerationResult result = null;
                try {
                    result = gen.call(param);
                    summaryBuff.append(String.format("业务类型:%s\n战败分析:%s\n", sbussinessType, result));
                    System.out.println("result:\n" + result);
                } catch (NoApiKeyException e) {
                    throw new RuntimeException(e);
                } catch (InputRequiredException e) {
                    throw new RuntimeException(e);
                }
            }

            // 全局分析
            System.out.println("开始全局本分析....");
            List<Message> messages = new ArrayList<>();
            Message systemMessage = Message.builder().role(Role.SYSTEM.getValue()).content("你是一个总结高手,擅长根据概要进行汇总总结").build();
            Message userMessage = Message.builder().role(Role.USER.getValue()).content(String.format("<content>\n%s\n</content>\n%s\n", summaryBuff.toString(), "")).build();
            messages.add(systemMessage);
            messages.add(userMessage);
            QwenParam param = QwenParam.builder()
                    .model("qwen-plus")
                    .messages(messages)
                    .resultFormat(QwenParam.ResultFormat.MESSAGE)
                    .maxTokens(8192)
                    .temperature(0.01F)
                    .build();
            GenerationResult result = null;
            try {
                result = gen.call(param);
                String retContent = result.getOutput().getChoices().get(0).getMessage().getContent();
                System.out.println("汇总后结果:\n" + retContent);

            } catch (NoApiKeyException e) {
                throw new RuntimeException(e);
            } catch (InputRequiredException e) {
                throw new RuntimeException(e);
            }



            // 2 基于数据库获取员工上周触客率,成交率等基础信息

            String sql = String.format("select  \n" +
                    "light_change_conversion_rate,\n" +
                    "light_change_conversion_weekly_decline_rate,\n" +
                    "equity_conversion_rate,\n" +
                    "equity_conversion_weekly_decline_rate,\n" +
                    "extended_warranty_conversion_rate,\n" +
                    "extended_warranty_conversion_weekly_decline_rate,\n" +
                    "comfort_open_rate,\n" +
                    "large_set_open_rate\n" +
                    "from dj_smartcarlife.early_warning_staff_shop_weekly_report\n" +
                    "where start_date = '2025-10-20' and merchant_name = '%s' and staff_name = '%s'", merchantName, staffName);

            ArrayList<ArrayList<String>> executeQuery = MysqlConn.executeQuery(connection, sql, 8);

            buffer.append("门店:").append(merchantName).append(",员工:").append(staffName).append("本周工作表现情况如下:");
            for (ArrayList<String> query : executeQuery) {
                buffer.append("轻改转化率(%):").append(query.get(0)).append("\n");
                buffer.append("轻改转化率周环比(%):").append(query.get(1)).append("\n");
                buffer.append("权益转化率(%):").append(query.get(2)).append("\n");
                buffer.append("权益转化率周环比(%):").append(query.get(3)).append("\n");
                buffer.append("延保转化率(%):").append(query.get(4)).append("\n");
                buffer.append("延保转化率周环比(%):").append(query.get(5)).append("\n");
                buffer.append("安心包开口率(%):").append(query.get(6)).append("\n");
                buffer.append("大套餐开口率(%):").append(query.get(7)).append("\n");
            }
//            System.out.println(buffer.toString());
            connection.close();

            // 3 基于大模型进行策略推荐参考

            return buffer.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        TeamSupervisorWeeklyReportService teamSupervisorWeeklyReportService = new TeamSupervisorWeeklyReportService();
        String report = teamSupervisorWeeklyReportService.getLastWeekBasicAnalysisReportByEmployee("宜宾广信汽车销售有限公司", "谢疏");
        System.out.println(report);

    }
}