StaffAnalysisService.java 14.7 KB
package com.glsk.service;


import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
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.databind.ObjectMapper;
import com.glsk.component.HttpUtil;
import com.glsk.conf.ConfigurationManager;
import com.glsk.connection.MysqlConn;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 员工分析
 */
@Service
@Slf4j
public class StaffAnalysisService {
    final String HOST_URL = "https://glsx-bi-report.glsx.com.cn/staff/";

    // 字段描述
    final String BUSINESS_TYPE_DESC = "业务场景:quanyi/yanbao/qinggai其中一个,权益-quanyi 延保-yanbao 轻该-qinggai";
    final String QUERY_TYPE_DESC = "查询维度:day/week/month/self其中之一,日-day、周-week、月-month,自定义-self";
    final String RANK_FIELD_DESC = "排序字段:output/atv/yinliulv/zhuanhualv/shentoulv其中之一,产值-output、客单价-atv、引流率-yinliulv、转化率-zhuanhualv、渗透率-shentoulv";
    final String RANK_FIELD_TYPE_DESC = "升降序:asc/desc其中之一,升序-asc,desc-降序";

    @Autowired
    private HttpUtil httpUtil;


    @Tool(description = "获取门店内部员工列表")
    public String getStaffList(@ToolParam(description = "门店Id") String merchantid,
                               @ToolParam(description = BUSINESS_TYPE_DESC) String business_type,
                               @ToolParam(description = "员工Id过滤") String staffid,
                               @ToolParam(description = "员工名称过滤") String staffname

    ) {
        String method = "getStaffList";
        String url = HOST_URL + method;

        Map<String, Object> params = new HashMap<>();
        params.put("merchantid", merchantid);
        params.put("business_type", business_type);
        params.put("staffid", staffid);
        params.put("staffname", staffname);

        try {
            String response = httpUtil.doGet(url, params);
            log.info("返回成功: {}", response);
            return response;
        } catch (Exception e) {
            log.error("返回失败", e);
            throw new RuntimeException("返回失败", e);
        }
    }

    @Tool(description = "查询门店内部当前周期绩效完成情况")
    public String queryPerformanceFinishStatus(@ToolParam(description = "门店Id") String merchantid,
                               @ToolParam(description = BUSINESS_TYPE_DESC) String business_type,
                               @ToolParam(description = "员工Id过滤") String staffid,
                               @ToolParam(description = "开始时间") String startDay,
                               @ToolParam(description = "结束时间") String endDay

    ) {
        String method = "queryPerformanceFinishStatus";
        String url = HOST_URL + method;

        Map<String, Object> params = new HashMap<>();
        params.put("merchantid", merchantid);
        params.put("business_type", business_type);
        params.put("staffid", staffid);
        params.put("startDay", startDay);
        params.put("endDay", endDay);

        try {
            String response = httpUtil.doGet(url, params);
            log.info("返回成功: {}", response);
            return response;
        } catch (Exception e) {
            log.error("返回失败", e);
            throw new RuntimeException("返回失败", e);
        }
    }

    @Tool(description = "查询门店内部员工绩效情况")
    public String queryStaffOverview(@ToolParam(description = "门店Id") String merchantid,
                                     @ToolParam(description = "员工Id过滤") String staffid,
                                     @ToolParam(description = BUSINESS_TYPE_DESC) String business_type,
                                     @ToolParam(description = QUERY_TYPE_DESC) String queryType,
                                     @ToolParam(description = "开始时间") String startDay,
                                     @ToolParam(description = "结束时间") String endDay

    ) {
        String method = "queryStaffOverview";
        String url = HOST_URL + method;

        Map<String, Object> params = new HashMap<>();
        params.put("merchantid", merchantid);
        params.put("business_type", business_type);
        params.put("queryType", queryType);
        params.put("staffid", staffid);
        params.put("startDay", startDay);
        params.put("endDay", endDay);

        try {
            String response = httpUtil.doGet(url, params);
            log.info("返回成功: {}", response);
            return response;
        } catch (Exception e) {
            log.error("返回失败", e);
            throw new RuntimeException("返回失败", e);
        }
    }

    @Tool(description = "查询门店内部员工产值趋势")
    public String queryStaffOutputTrend(@ToolParam(description = "门店Id") String merchantid,
                                     @ToolParam(description = "员工Id过滤") String staffid,
                                     @ToolParam(description = BUSINESS_TYPE_DESC) String business_type,
                                     @ToolParam(description = QUERY_TYPE_DESC) String queryType,
                                     @ToolParam(description = "开始时间") String startDay,
                                     @ToolParam(description = "结束时间") String endDay

    ) {
        String method = "queryStaffOutputTrend";
        String url = HOST_URL + method;

        Map<String, Object> params = new HashMap<>();
        params.put("merchantid", merchantid);
        params.put("business_type", business_type);
        params.put("queryType", queryType);
        params.put("staffid", staffid);
        params.put("startDay", startDay);
        params.put("endDay", endDay);

        try {
            String response = httpUtil.doGet(url, params);
            log.info("返回成功: {}", response);
            return response;
        } catch (Exception e) {
            log.error("返回失败", e);
            throw new RuntimeException("返回失败", e);
        }
    }

    @Tool(description = "查询门店内员工周列表")
    public String getStaffWeekList(@ToolParam(description = "门店Id") String merchantid,
                                        @ToolParam(description = "员工Id过滤") String staffid,
                                        @ToolParam(description = BUSINESS_TYPE_DESC) String business_type

    ) {
        String method = "getStaffWeekList";
        String url = HOST_URL + method;

        Map<String, Object> params = new HashMap<>();
        params.put("merchantid", merchantid);
        params.put("business_type", business_type);
        params.put("staffid", staffid);
        try {
            String response = httpUtil.doGet(url, params);
            log.info("返回成功: {}", response);
            return response;
        } catch (Exception e) {
            log.error("返回失败", e);
            throw new RuntimeException("返回失败", e);
        }
    }


    @Tool(description = "对门店内员工进行战败分析")
    public String getStaffDefeatAnalysis(@ToolParam(description = "门店名称") String merchantName,
                                         @ToolParam(description = "员工名称") String staffName,
                                         @ToolParam(description = "开始时间 yyyy-MM-dd HH:mm:ss") String startTime,
                                         @ToolParam(description = "结束时间 yyyy-MM-dd HH:mm:ss") String endTime
    ) {
        String retContent = "";

        try {
            StringBuffer buffer = new StringBuffer();
            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, endTime);
            System.out.println(staffSql);
            ArrayList<ArrayList<String>> staffQuery = MysqlConn.executeQuery(connection, staffSql, 7);


            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"));


                GenerationResult result = callLLM(system, text, user);
                summaryBuff.append(String.format("业务类型:%s\n战败分析:%s\n", sbussinessType, result));
                System.out.println("result:\n" + result);
            }

            // 全局分析
            System.out.println("开始全局本分析....");
            GenerationResult result = callLLM(system, summaryBuff.toString(), user);
            retContent = result.getOutput().getChoices().get(0).getMessage().getContent();
            System.out.println("汇总后结果:\n" + retContent);
            connection.close();
            return retContent;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return retContent;
    }

    @NotNull
    private static GenerationResult callLLM(String system, String text, String user) throws NoApiKeyException, InputRequiredException {
        Constants.apiKey = "sk-48654db737cc4fdb91aad1f2af7562b8";
        Generation gen = new Generation();

        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;
        result = gen.call(param);
        return result;
    }

}