员工岗位与数据范围权限上线,企微群机器人接入与报价回执去重

- 新增员工岗位(InquiryStaffRole)实体、服务与后台页面,数据范围默认按岗位,看板由「仅本人」切换为岗位范围,补充业务负责人与角色说明迁移
- 新增企微群 webhook 通道、access_gate/staff_roles 鉴权与智价通/双 BOT 回复配置
- 报价回执增加去重防抖(quote_receipt_debounce),询价原文落库并补单测
- 同义词补陆运类型修正与地名通配 v2,更新种子生成脚本
- 空运/陆运/海运询价流程、报价单按需生成、转人工与多段处理调整
- 后台工单需求字段、BOT 显示名、站点标题与看板配套更新
This commit is contained in:
linmianxun
2026-12-04 20:16:28 +08:00
parent 069b08db7b
commit 9d7bc2b787
136 changed files with 11677 additions and 1339 deletions
@@ -0,0 +1,198 @@
package org.jeecg.modules.inquiry.controller;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.inquiry.support.InquiryDataScopeSupport;
import org.jeecg.modules.inquiry.support.InquiryStaffScopeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 账号管理列表:按员工数据范围过滤。
* <p>
* 原账号页直接走 Jeecg /sys/user/list,没有部门/上下级过滤。这里保持同样的展示
* 字段,但只返回当前登录人数据范围内(本人 + 下级 + 跨部门领导 + 本部门子树)
* 员工的账号。超管、无员工记录、data_scope=all 不过滤。
* <p>
* 只读列表;新增/编辑仍走 Jeecg /sys/user,页面权限另行控制。
*/
@RestController
@RequestMapping("/inquiry/account")
public class InquiryAccountController {
@Autowired
private DataSource dataSource;
@Autowired
private InquiryStaffScopeService staffScopeService;
@GetMapping("/list")
@RequiresPermissions("inquiry:account:view")
public Result<Map<String, Object>> list(@RequestParam(required = false) String keyword,
@RequestParam(required = false) Integer status,
@RequestParam(defaultValue = "1") Integer pageNo,
@RequestParam(defaultValue = "20") Integer pageSize) {
int page = pageNo == null || pageNo < 1 ? 1 : pageNo;
int size = pageSize == null || pageSize < 1 ? 20 : Math.min(pageSize, 200);
Set<String> visible = visibleWecomIdsOrNull();
String selfUsername = currentUsername();
StringBuilder where = new StringBuilder(" WHERE u.del_flag = 0");
List<Object> params = new ArrayList<>();
if (status != null && status > 0) {
where.append(" AND u.status = ?");
params.add(status);
}
String kw = StringUtils.trimToEmpty(keyword);
if (!kw.isEmpty()) {
where.append(" AND (u.username LIKE ? OR u.realname LIKE ? OR u.phone LIKE ?)");
String like = "%" + kw + "%";
params.add(like);
params.add(like);
params.add(like);
}
if (visible != null) {
where.append(" AND (");
boolean any = false;
if (!visible.isEmpty()) {
where.append("u.work_no IN (");
int i = 0;
for (String id : visible) {
if (i > 0) {
where.append(',');
}
where.append('?');
params.add(id);
i++;
}
where.append(")");
any = true;
}
if (StringUtils.isNotBlank(selfUsername)) {
if (any) {
where.append(" OR ");
}
where.append("u.username = ?");
params.add(selfUsername);
any = true;
}
if (!any) {
where.append("1 = 0");
}
where.append(")");
}
long total = 0L;
String countSql = "SELECT COUNT(*) FROM sys_user u" + where;
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(countSql)) {
bind(ps, params);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
total = rs.getLong(1);
}
}
} catch (Exception e) {
return Result.error("账号列表查询失败");
}
List<Map<String, Object>> records = new ArrayList<>();
String sql = "SELECT u.id, u.username, u.realname, u.work_no, u.phone, u.status, u.last_login_time"
+ " FROM sys_user u" + where
+ " ORDER BY u.create_time DESC LIMIT ? OFFSET ?";
List<Object> listParams = new ArrayList<>(params);
listParams.add(size);
listParams.add((page - 1) * size);
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
bind(ps, listParams);
try (ResultSet rs = ps.executeQuery()) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (rs.next()) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("id", rs.getString("id"));
row.put("username", rs.getString("username"));
row.put("realname", rs.getString("realname"));
row.put("workNo", rs.getString("work_no"));
row.put("phone", rs.getString("phone"));
row.put("status", rs.getInt("status"));
Timestamp ts = rs.getTimestamp("last_login_time");
row.put("lastLoginTime", ts == null ? null : fmt.format(ts));
records.add(row);
}
}
} catch (Exception e) {
return Result.error("账号列表查询失败");
}
long pages = size <= 0 ? 0 : (total + size - 1) / size;
Map<String, Object> body = new LinkedHashMap<>();
body.put("records", records);
body.put("total", total);
body.put("size", size);
body.put("current", page);
body.put("pages", pages);
// 前端据此隐藏“导出全部”按钮;导出接口本身未按范围过滤。
body.put("scoped", visible != null);
return Result.OK(body);
}
private void bind(PreparedStatement ps, List<Object> params) throws Exception {
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
}
/** 当前登录人的员工数据范围;null=不限制。 */
private Set<String> visibleWecomIdsOrNull() {
LoginUser login = currentLogin();
if (login == null || InquiryDataScopeSupport.isAdministrator(login)) {
return null;
}
String wecom = InquiryDataScopeSupport.wecomId(login);
if (StringUtils.isBlank(wecom)) {
return null;
}
InquiryStaffScopeService.Scope scope = staffScopeService.resolve(wecom);
if (scope == null || scope.isAll()) {
return null;
}
return new LinkedHashSet<>(scope.getVisibleWecomIds());
}
private String currentUsername() {
LoginUser login = currentLogin();
return login == null ? "" : StringUtils.trimToEmpty(login.getUsername());
}
private LoginUser currentLogin() {
try {
Object principal = SecurityUtils.getSubject().getPrincipal();
if (principal instanceof LoginUser) {
return (LoginUser) principal;
}
} catch (Exception ignored) {
// 无登录上下文
}
return null;
}
}
@@ -16,6 +16,8 @@ import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.inquiry.dto.StaffWecomSyncResult;
import org.jeecg.modules.inquiry.entity.InquiryStaffRole;
import org.jeecg.modules.inquiry.service.IInquiryStaffRoleService;
import org.jeecg.modules.inquiry.support.InquiryDataScopeSupport;
import org.jeecg.modules.inquiry.support.InquiryStaffScopeService;
import org.jeecg.modules.inquiry.wecom.WeComAddressBookClient;
import org.jeecg.modules.inquiry.wecom.WeComDepartment;
import org.springframework.beans.factory.annotation.Autowired;
@@ -23,11 +25,13 @@ import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 员工岗位管理 API。
@@ -45,6 +49,9 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
@Autowired
private IInquiryStaffRoleService staffRoleService;
@Autowired
private InquiryStaffScopeService staffScopeService;
@Autowired
private WeComAddressBookClient weComAddressBookClient;
@@ -57,6 +64,13 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
ROLE_LABEL.put("land", "产品·陆运");
}
/** 岗位展示顺序;与前端 tabs 一致。 */
private static final List<String> ROLE_ORDER = Arrays.asList("sales", "air", "sea", "land");
/** 数据范围可选值;默认 self_sub(本人及下级)。 */
private static final List<String> DATA_SCOPES =
Arrays.asList("self", "self_sub", "dept", "all");
@AutoLog(value = "员工岗位-分页列表")
@ApiOperation("分页列表")
@RequiresPermissions("inquiry:staff:list")
@@ -67,7 +81,9 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
HttpServletRequest req) {
QueryWrapper<InquiryStaffRole> qw = new QueryWrapper<>();
if (StringUtils.isNotBlank(query.getRoleCode())) {
qw.eq("role_code", query.getRoleCode());
// 多岗位:role_code 只存主岗位,role_codes 才是完整授权。
String role = query.getRoleCode().trim().toLowerCase();
qw.and(w -> w.eq("role_code", role).or().apply("FIND_IN_SET({0}, role_codes)", role));
}
if (StringUtils.isNotBlank(query.getStatus())) {
qw.eq("status", query.getStatus());
@@ -79,6 +95,15 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
if (StringUtils.isNotBlank(query.getRoutes())) {
qw.like("routes", query.getRoutes());
}
// 数据范围:非超管只能看自己数据范围内的人;无员工记录/超管不过滤。
Set<String> visible = visibleWecomIdsOrNull();
if (visible != null) {
if (visible.isEmpty()) {
qw.apply("1 = 0");
} else {
qw.in("wecom_id", visible);
}
}
qw.orderByDesc("create_time");
return Result.OK(staffRoleService.page(new Page<>(pageNo, pageSize), qw));
}
@@ -87,7 +112,7 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
@RequiresPermissions("inquiry:staff:list")
@GetMapping("/counts")
public Result<Map<String, Long>> counts() {
return Result.OK(staffRoleService.countByRole());
return Result.OK(staffRoleService.countByRole(visibleWecomIdsOrNull()));
}
@AutoLog(value = "员工岗位-新增")
@@ -112,27 +137,74 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
if (StringUtils.isBlank(body.getId())) {
return Result.error("id 不能为空");
}
InquiryStaffRole existing = staffRoleService.getById(body.getId());
if (existing == null) {
return Result.error("员工不存在");
}
assertVisible(existing);
// 兼容旧前端/旧调用方:新增字段未传(null)时保留原值;
// 显式传空串表示清空(如取消直属上级、手输部门后清掉 ID)。
if (body.getRoleCodes() == null) {
// 旧前端只传 roleCode:补回完整授权;新前端传了 roleCodes 就以它为准,
// 不再拼旧 roleCode,避免运营取消某个岗位后又被合并回来。
body.setRoleCodes(existing.getRoleCodes());
if (body.getRoleCode() == null) {
body.setRoleCode(existing.getRoleCode());
}
}
if (body.getDeptId() == null) {
body.setDeptId(existing.getDeptId());
}
if (body.getDeptPath() == null) {
body.setDeptPath(existing.getDeptPath());
}
if (body.getLeaderWecomId() == null) {
body.setLeaderWecomId(existing.getLeaderWecomId());
}
if (body.getBusinessLeaderWecomIds() == null) {
body.setBusinessLeaderWecomIds(existing.getBusinessLeaderWecomIds());
}
if (body.getAirRoutes() == null) {
body.setAirRoutes(existing.getAirRoutes());
}
if (body.getSeaRoutes() == null) {
body.setSeaRoutes(existing.getSeaRoutes());
}
if (body.getLandRoutes() == null) {
body.setLandRoutes(existing.getLandRoutes());
}
if (StringUtils.isBlank(body.getDataScope())) {
body.setDataScope(existing.getDataScope());
}
if (StringUtils.isBlank(body.getStatus())) {
body.setStatus(existing.getStatus());
}
normalize(body);
body.setUpdateTime(new Date());
// 销售岗位需把 is_leader 写成 NULL;updateById 默认跳过 null,故用 UpdateWrapper
if ("sales".equals(body.getRoleCode())) {
staffRoleService.lambdaUpdate()
.eq(InquiryStaffRole::getId, body.getId())
.set(InquiryStaffRole::getName, body.getName())
.set(InquiryStaffRole::getWecomId, body.getWecomId())
.set(InquiryStaffRole::getMobile, body.getMobile())
.set(InquiryStaffRole::getDepartName, body.getDepartName())
.set(InquiryStaffRole::getRoleCode, body.getRoleCode())
.set(InquiryStaffRole::getRoleLabel, body.getRoleLabel())
.set(InquiryStaffRole::getRoutes, "")
.set(InquiryStaffRole::getIsLeader, null)
.set(InquiryStaffRole::getNotifyEventException, body.getNotifyEventException())
.set(InquiryStaffRole::getStatus, body.getStatus())
.set(InquiryStaffRole::getUpdateTime, body.getUpdateTime())
.update();
} else {
staffRoleService.updateById(body);
}
// 用 UpdateWrapper 显式写 null:纯销售/航线岗位切换后必须能清空 is_leader。
staffRoleService.lambdaUpdate()
.eq(InquiryStaffRole::getId, body.getId())
.set(InquiryStaffRole::getName, body.getName())
.set(InquiryStaffRole::getWecomId, body.getWecomId())
.set(InquiryStaffRole::getMobile, body.getMobile())
.set(InquiryStaffRole::getDepartName, body.getDepartName())
.set(InquiryStaffRole::getDeptId, body.getDeptId())
.set(InquiryStaffRole::getDeptPath, body.getDeptPath())
.set(InquiryStaffRole::getLeaderWecomId, body.getLeaderWecomId())
.set(InquiryStaffRole::getBusinessLeaderWecomIds, body.getBusinessLeaderWecomIds())
.set(InquiryStaffRole::getRoleCode, body.getRoleCode())
.set(InquiryStaffRole::getRoleCodes, body.getRoleCodes())
.set(InquiryStaffRole::getRoleLabel, body.getRoleLabel())
.set(InquiryStaffRole::getRoutes, body.getRoutes())
.set(InquiryStaffRole::getAirRoutes, body.getAirRoutes())
.set(InquiryStaffRole::getSeaRoutes, body.getSeaRoutes())
.set(InquiryStaffRole::getLandRoutes, body.getLandRoutes())
.set(InquiryStaffRole::getIsLeader, body.getIsLeader())
.set(InquiryStaffRole::getDataScope, body.getDataScope())
.set(InquiryStaffRole::getNotifyEventException, body.getNotifyEventException())
.set(InquiryStaffRole::getStatus, body.getStatus())
.set(InquiryStaffRole::getUpdateTime, body.getUpdateTime())
.update();
return Result.OK("更新成功");
}
@@ -141,6 +213,7 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
@RequiresPermissions("inquiry:staff:disable")
@PostMapping("/disable")
public Result<String> disable(@RequestParam String id) {
assertVisible(staffRoleService.getById(id));
staffRoleService.disable(id);
return Result.OK("已停用");
}
@@ -154,6 +227,7 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
@RequiresPermissions("inquiry:staff:disable")
@PostMapping("/enable")
public Result<String> enable(@RequestParam String id) {
assertVisible(staffRoleService.getById(id));
staffRoleService.enable(id);
return Result.OK("已启用");
}
@@ -162,7 +236,9 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
@RequiresPermissions("inquiry:staff:list")
@GetMapping("/queryById")
public Result<InquiryStaffRole> queryById(@RequestParam String id) {
return Result.OK(staffRoleService.getById(id));
InquiryStaffRole row = staffRoleService.getById(id);
assertVisible(row);
return Result.OK(row);
}
/**
@@ -232,31 +308,183 @@ public class InquiryStaffRoleController extends JeecgController<InquiryStaffRole
return "system";
}
/**
* 当前登录人的员工数据范围;null=不限制(超管/无登录/无员工记录)。
* 空集合=范围内没有员工,列表应返回空。
*/
private Set<String> visibleWecomIdsOrNull() {
LoginUser login = currentLogin();
if (login == null || InquiryDataScopeSupport.isAdministrator(login)) {
return null;
}
String wecom = InquiryDataScopeSupport.wecomId(login);
if (StringUtils.isBlank(wecom)) {
return null;
}
InquiryStaffScopeService.Scope scope = staffScopeService.resolve(wecom);
if (scope == null || scope.isAll()) {
return null;
}
return scope.getVisibleWecomIds();
}
/** 员工是否在当前登录人的数据范围内;不限制时直接放行。 */
private void assertVisible(InquiryStaffRole row) {
Set<String> visible = visibleWecomIdsOrNull();
if (visible == null) {
return;
}
if (row == null || StringUtils.isBlank(row.getWecomId())
|| !visible.contains(row.getWecomId().trim())) {
throw new IllegalArgumentException("当前账号无权操作该员工");
}
}
private LoginUser currentLogin() {
try {
Object principal = SecurityUtils.getSubject().getPrincipal();
if (principal instanceof LoginUser) {
return (LoginUser) principal;
}
} catch (Exception ignored) {
// 无登录上下文
}
return null;
}
/**
* 校验并归一多岗位、数据范围。
* <p>
* roleCodes 是完整授权;roleCode/roleLabel 由它派生,避免旧页面看到空岗位。
* 只要含任一产品/航线岗,就必须维护负责人与负责线路(与旧项目 admin-staff 一致);
* 纯销售才清空这两项。
*/
private void normalize(InquiryStaffRole body) {
if (StringUtils.isBlank(body.getName()) || StringUtils.isBlank(body.getWecomId())) {
throw new IllegalArgumentException("姓名与企微 userid 不能为空");
}
if (StringUtils.isBlank(body.getRoleCode())) {
body.setRoleCode("sales");
List<String> roles = normalizeRoleList(body.getRoleCodes(), body.getRoleCode());
if (roles.isEmpty()) {
roles.add("sales");
}
if (StringUtils.isBlank(body.getRoleLabel())) {
body.setRoleLabel(ROLE_LABEL.getOrDefault(body.getRoleCode(), body.getRoleCode()));
body.setRoleCodes(String.join(",", roles));
body.setRoleCode(roles.get(0));
body.setRoleLabel(buildRoleLabel(roles));
// 业务/虚线汇报对象:多值、独立于行政直属上级;去掉空白和本人。
if (body.getBusinessLeaderWecomIds() != null) {
body.setBusinessLeaderWecomIds(
joinWecomIds(body.getBusinessLeaderWecomIds(), body.getWecomId()));
}
if (body.getNotifyEventException() == null) {
body.setNotifyEventException(0);
}
// 销售无负责人/线路;产品与航线须维护(与旧项目 admin-staff 一致)
String role = body.getRoleCode();
if ("sales".equals(role)) {
String scope = StringUtils.trimToEmpty(body.getDataScope());
// 旧前端/旧数据可能传 inherit;产品已删除该选项,统一按默认 self_sub 处理。
if (scope.isEmpty() || "inherit".equalsIgnoreCase(scope)) {
scope = "self_sub";
}
if (!DATA_SCOPES.contains(scope)) {
throw new IllegalArgumentException("数据范围只能是 self/self_sub/dept/all");
}
body.setDataScope(scope);
// 岗位被取消后清掉该岗位线路,避免残留线路在以后被误用;
// 岗位仍在而线路字段未传(旧前端)保持 null,让实体回退并集 routes。
if (!roles.contains("air")) {
body.setAirRoutes("");
}
if (!roles.contains("sea")) {
body.setSeaRoutes("");
}
if (!roles.contains("land")) {
body.setLandRoutes("");
}
boolean product = roles.contains("air") || roles.contains("sea") || roles.contains("land");
if (!product) {
body.setIsLeader(null);
body.setRoutes("");
} else if ("air".equals(role) || "sea".equals(role) || "land".equals(role)) {
} else {
if (body.getIsLeader() == null) {
throw new IllegalArgumentException("请选择是否负责人");
}
// 兼容只传按岗位线路的调用方:并集列为空时由三个岗位列拼出来。
if (StringUtils.isBlank(body.getRoutes())) {
List<String> union = new ArrayList<>();
if (roles.contains("air") && StringUtils.isNotBlank(body.getAirRoutes())) {
union.add(body.getAirRoutes());
}
if (roles.contains("sea") && StringUtils.isNotBlank(body.getSeaRoutes())) {
union.add(body.getSeaRoutes());
}
if (roles.contains("land") && StringUtils.isNotBlank(body.getLandRoutes())) {
union.add(body.getLandRoutes());
}
body.setRoutes(String.join(",", union));
}
if (StringUtils.isBlank(body.getRoutes())) {
throw new IllegalArgumentException("请选择负责线路");
}
// 新前端会按岗位拆分线路:勾了某岗位就必须有该岗位的线路。
// null 表示旧前端未传,保留并集回退,不做这项校验。
if (roles.contains("air") && body.getAirRoutes() != null
&& StringUtils.isBlank(body.getAirRoutes())) {
throw new IllegalArgumentException("请选择航线·空运负责线路");
}
if (roles.contains("sea") && body.getSeaRoutes() != null
&& StringUtils.isBlank(body.getSeaRoutes())) {
throw new IllegalArgumentException("请选择产品·海运负责线路");
}
if (roles.contains("land") && body.getLandRoutes() != null
&& StringUtils.isBlank(body.getLandRoutes())) {
throw new IllegalArgumentException("请选择产品·陆运负责线路");
}
}
}
/**
* 只留合法码,按固定顺序去重。
* <p>
* roleCodes 是完整授权,优先;只有它为空(旧前端)才退回 roleCode。
* 不把两者合并,避免取消某个岗位后旧主岗位又把它加回来。
*/
private List<String> normalizeRoleList(String roleCodes, String roleCode) {
String source = StringUtils.isNotBlank(roleCodes) ? roleCodes : StringUtils.defaultString(roleCode);
LinkedHashSet<String> input = new LinkedHashSet<>();
for (String part : source.split("[,,|\\s]+")) {
String code = StringUtils.trimToEmpty(part).toLowerCase();
if (ROLE_ORDER.contains(code)) {
input.add(code);
}
}
List<String> out = new ArrayList<>();
for (String code : ROLE_ORDER) {
if (input.contains(code)) {
out.add(code);
}
}
return out;
}
private String buildRoleLabel(List<String> roles) {
List<String> labels = new ArrayList<>();
for (String code : roles) {
labels.add(ROLE_LABEL.getOrDefault(code, code));
}
return String.join("、", labels);
}
/** 多值企微 userid 归一:逗号/中文逗号/空白分隔,去重去空,排除本人。 */
private String joinWecomIds(String raw, String self) {
if (StringUtils.isBlank(raw)) {
return "";
}
String selfId = StringUtils.trimToEmpty(self);
LinkedHashSet<String> ids = new LinkedHashSet<>();
for (String part : raw.split("[,,\\s]+")) {
String id = StringUtils.trimToEmpty(part);
if (!id.isEmpty() && !id.equals(selfId)) {
ids.add(id);
}
}
return String.join(",", ids);
}
}
@@ -156,6 +156,7 @@ public class InquiryWorkOrderController {
}
InquiryTicket row = workOrderService.getById(id);
if (row != null) {
InquiryDataScopeSupport.assertTicketVisible(row);
InquiryDataScopeSupport.assertTicketBizAllowed(row);
}
return Result.OK(row);
@@ -35,6 +35,13 @@ public class AgentTicketCreateRequest {
@ApiModelProperty("协同模式 auto/handoff")
private String collabMode;
/**
* 业务询价原始内容:销售 1v1 首条询价原话。
* 只做展示留档,不参与 TMS 查价、重单指纹或模板匹配。
*/
@ApiModelProperty("业务询价原始内容(销售首条询价原话,可选)")
private String inquiryRawText;
@ApiModelProperty("已确认查价字段(内部键)")
private Map<String, String> facts;
@@ -12,7 +12,11 @@ import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
/**
* 询价业务员工岗位,对应 inq_staff_role。
@@ -44,15 +48,64 @@ public class InquiryStaffRole implements Serializable {
@ApiModelProperty("部门")
private String departName;
@ApiModelProperty("角色码 sales/air/sea/land")
@ApiModelProperty("主岗位码 sales/air/sea/land(兼容旧逻辑,取 roleCodes 第一个)")
private String roleCode;
/**
* 全部岗位码,逗号分隔(sales/air/sea/land)。
* <p>
* 与 roleCode 的关系:roleCode 是主岗位,供旧页面/旧匹配逻辑展示;
* roleCodes 才是完整授权,智能体准入与按岗位匹配都读它。
* 旧数据未回填时,{@link #effectiveRoleCodes()} 会退回 roleCode。
*/
@ApiModelProperty("全部岗位码,逗号分隔 sales/air/sea/land")
private String roleCodes;
@ApiModelProperty("角色展示名")
private String roleLabel;
@ApiModelProperty("负责线路(逗号分隔;销售可空)")
@ApiModelProperty("负责线路(全部岗位并集,逗号分隔;销售可空)")
private String routes;
/**
* 按岗位拆分的负责线路。null=旧数据,回退 routes;空串=该岗位明确没有线路。
* 多岗位时避免空运三字码被海运按港口子串匹配误命中。
*/
@ApiModelProperty("航线·空运负责线路")
private String airRoutes;
@ApiModelProperty("产品·海运负责线路")
private String seaRoutes;
@ApiModelProperty("产品·陆运负责线路")
private String landRoutes;
@ApiModelProperty("企微部门ID")
private String deptId;
/** 企微部门 ID 路径,形如 /1/12/35/;用于本部门及以下的数据范围。 */
@ApiModelProperty("企微部门ID路径 /1/12/35/")
private String deptPath;
@ApiModelProperty("直属上级企微userid(行政上级,单人)")
private String leaderWecomId;
/**
* 业务/虚线汇报对象,多个企微 userid 逗号分隔。
* <p>
* 与 leaderWecomId 独立:Y 部门的 D 在业务上向 X 部门的 A 汇报,
* 但 A 不是 D 的行政上级、也不在行政上级链上时,D 的业务汇报对象写 A。
*/
@ApiModelProperty("业务/虚线汇报对象,多个企微userid逗号分隔")
private String businessLeaderWecomIds;
/**
* 数据范围:self=仅本人;self_sub=本人及下级(默认);
* dept=本部门及以下;all=全部(仍受角色业务线限制)。
*/
@ApiModelProperty("数据范围 self/self_sub/dept/all")
private String dataScope;
/**
* 是否线路/产品负责人。
* <p>
@@ -79,4 +132,96 @@ public class InquiryStaffRole implements Serializable {
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/** 合法业务岗位码;顺序即后台展示顺序。 */
public static final List<String> KNOWN_ROLE_CODES =
Arrays.asList("sales", "air", "sea", "land");
/**
* 完整岗位码集合:优先 roleCodes,旧数据退回 roleCode。
* <p>
* 只返回合法稳定码,去重保序;空串不返回。
*/
public List<String> effectiveRoleCodes() {
LinkedHashSet<String> out = new LinkedHashSet<>();
addRoleCodes(out, roleCodes);
// 只有 roleCodes 为空/全是非法码时才退回主岗位,避免“取消销售后 roleCode 残留”
// 把已取消的岗位又加回来。
if (out.isEmpty()) {
addRoleCodes(out, roleCode);
}
return new ArrayList<>(out);
}
/** 是否含某个岗位。大小写不敏感,非法码返回 false。 */
public boolean hasRole(String code) {
String want = code == null ? "" : code.trim().toLowerCase();
if (want.isEmpty() || !KNOWN_ROLE_CODES.contains(want)) {
return false;
}
return effectiveRoleCodes().contains(want);
}
/** 是否含产品/航线岗位(air/sea/land);销售不算。 */
public boolean hasProductRole() {
return hasRole("air") || hasRole("sea") || hasRole("land");
}
/**
* 业务/虚线汇报对象列表。去重保序,空串不返回。
* 与行政直属上级完全独立。
*/
public List<String> businessLeaderIds() {
LinkedHashSet<String> out = new LinkedHashSet<>();
String raw = businessLeaderWecomIds;
if (raw == null) {
return new ArrayList<>(out);
}
for (String part : raw.split("[,,\\s]+")) {
String id = part == null ? "" : part.trim();
if (!id.isEmpty()) {
out.add(id);
}
}
return new ArrayList<>(out);
}
/**
* 取某个岗位的负责线路。
* <p>
* 新数据按岗位拆分;旧数据对应列为 null 时回退并集 routes(仅当该岗位确实存在)。
* 返回空串表示该岗位没有线路,调用方不得再拿并集去猜。
*/
public String routesForRole(String code) {
String role = code == null ? "" : code.trim().toLowerCase();
if (!hasRole(role)) {
return "";
}
String specific;
if ("air".equals(role)) {
specific = airRoutes;
} else if ("sea".equals(role)) {
specific = seaRoutes;
} else if ("land".equals(role)) {
specific = landRoutes;
} else {
return "";
}
if (specific != null) {
return specific;
}
return hasRole(role) ? java.util.Objects.toString(routes, "") : "";
}
private static void addRoleCodes(LinkedHashSet<String> out, String raw) {
if (raw == null) {
return;
}
for (String part : raw.split("[,,|\\s]+")) {
String code = part == null ? "" : part.trim().toLowerCase();
if (!code.isEmpty() && KNOWN_ROLE_CODES.contains(code)) {
out.add(code);
}
}
}
}
@@ -216,6 +216,15 @@ public class InquiryTicket implements Serializable {
@ApiModelProperty("询价字段快照 JSON")
private String factsJson;
/**
* 业务询价原始内容:销售 1v1 首条询价原话。
* <p>
* 只做展示留档:群摘要「工单号」下方展示,后台工单详情同步展示。
* 不参与 TMS 查价、重单指纹或报价模板匹配,禁止混进 factsJson。
*/
@ApiModelProperty("业务询价原始内容(销售首条询价原话)")
private String inquiryRawText;
@ApiModelProperty("协同字段快照 JSON")
private String collabFactsJson;
@@ -16,6 +16,11 @@ public interface IInquiryStaffRoleService extends IService<InquiryStaffRole> {
*/
Map<String, Long> countByRole();
/**
* 按角色统计指定企微 userid 集合内的人数;null 表示不限制。
*/
Map<String, Long> countByRole(java.util.Collection<String> visibleWecomIds);
/**
* 停用员工(status=disabled),不物理删除。
*/
@@ -48,7 +48,8 @@ import java.util.stream.Collectors;
* 问号 tip 只写计算公式,禁止「本期无协同明细 / N单无勾选…」占位。
* 内部报价平均响应 = AVG(首次 PRODUCT 报价时间 − 分发时间),
* 分发=bind_collab_group/activate_air_group。
* 人员排名与工单列表同一套发起人解析(企微 id → 员工姓名),禁止只认库内空 sales_name。
* 人员排名三档:销售=陆/海/空询价发起人;产品=陆/海工单处理人;航线=空运工单处理人。
* 发起人解析与工单列表同一套(企微 id → 员工姓名),禁止只认库内空 sales_name。
* 成本趋势:近 7 日工单按线路聚合均价(成本价优先,缺省用销售价),非浏览器直连 TMS。
* 线程:只读查询,无写锁。
*/
@@ -96,8 +97,7 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
LambdaQueryWrapper<InquiryTicket> qw = new LambdaQueryWrapper<InquiryTicket>()
.ge(InquiryTicket::getCreateTime, from)
.le(InquiryTicket::getCreateTime, to);
InquiryDataScopeSupport.applySelfOnly(qw);
InquiryDataScopeSupport.applyRoleBizLines(qw);
InquiryDataScopeSupport.applyDataScope(qw);
List<InquiryTicket> tickets = ticketMapper.selectList(qw);
long total = tickets.size();
@@ -173,13 +173,12 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
}
}
// 产品/航线账号:人员排名只留智能体团队(航线+产品),不返回销售/用户。
// 人员排名三档:销售=询价发起人,产品=陆/海工单处理人,航线=空运工单处理人。
// 处理量必须按「协同群处理人」计,不能按发起销售计:否则 B 处理了 A 的单,
// B 的看板里永远没有自己的处理量(2026-11-21 产品反馈的 bug)。
// 产品/航线账号只留智能体团队(航线+产品),不返回销售/用户。
boolean agentTeamOnly = isProductOrRouteViewer(staffByWecom);
List<Map<String, Object>> rankings = agentTeamOnly
? buildHandlerRankings(tickets, staffByWecom)
: buildRankings(tickets, staffByWecom, staffByName, false);
List<Map<String, Object>> rankings = buildRankings(tickets, staffByWecom, staffByName, agentTeamOnly);
List<Map<String, Object>> costRoutes = buildCostRoutes(tickets, dayIndex, trendDates);
Map<String, Object> result = new LinkedHashMap<>();
@@ -197,10 +196,12 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
}
/**
* 当前登录人是否为产品/航线岗位(只能看智能体团队排名)。
* 当前登录人是否为纯产品/航线岗位(只能看智能体团队排名)。
* <p>
* 判定顺序:超管放行 → 员工表 wecom 岗位 air/sea/land → Jeecg 角色名含航线/产品/空运/海运/陆运。
* 纯「销售」角色不算。无登录上下文时不收窄(避免内部调用被误锁)。
* 多岗位改造后,「销售 + 航线/产品」的人仍然会自己发询价,不能只看团队排名,
* 否则销售排名被跳过、本人又没有处理人记录时会整页为空。
* 只有员工表里没有 sales、但含 air/sea/land 的人,才收成智能体团队排名。
* 员工表没记录时退回 Jeecg 角色名判断。
*/
private boolean isProductOrRouteViewer(Map<String, InquiryStaffRole> staffByWecom) {
org.jeecg.common.system.vo.LoginUser login = currentLoginUser();
@@ -214,10 +215,7 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
if (StringUtils.isNotBlank(wecom) && staffByWecom != null) {
InquiryStaffRole staff = staffByWecom.get(wecom.trim());
if (staff != null) {
String code = StringUtils.trimToEmpty(staff.getRoleCode());
if ("air".equals(code) || "sea".equals(code) || "land".equals(code)) {
return true;
}
return !staff.hasRole("sales") && staff.hasProductRole();
}
}
String username = StringUtils.trimToEmpty(login.getUsername());
@@ -323,158 +321,138 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
}
/**
* 产品/航线账号的人员排名:按「协同群处理人」计处理量,而不是按发起销售。
* 人员排名:销售 / 产品 / 航线 三个口径各自独立,不再用发起人岗位决定分组。
* <ul>
* <li>销售 = 陆/海/空询价的发起人(sales_wecom_id),按人合并</li>
* <li>产品 = 陆运/海运工单的处理人(collab_actor_ids 有互动的产品岗)</li>
* <li>航线 = 空运工单的处理人(collab_actor_ids 有互动的航线岗)</li>
* </ul>
* 处理人只认有互动的产品/航线岗成员:只被拉进群、没报价的人不算,
* 发起销售本人也不算。一张单多个处理人时每人各计 1 单。
* 多段联运/业务线缺失时回退按员工岗位归类。
* <p>
* 为什么单独一套:产品/航线通常不发起询价,只处理销售建的单;
* 如果仍按 salesWecomId 归属,B 处理了 A 的单,B 的处理量永远是 0。
* 口径与工单列表「处理人」列一致:只认 collab_actor_ids 里岗位为
* 航线(air)/产品(sea|land) 且有报价等互动的人,排除发起销售本人;
* 只被拉进群、没互动的人不计。一张单多个产品同时处理时每人各计 1 单。
* agentTeamOnly=true(产品/航线账号)时只返回产品/航线两档,不回销售:
* 否则 B 处理了 A 的单,B 的看板里永远没有自己的处理量。
* <p>
* 只读 tickets / inq_staff_role 快照,无副作用。
*/
private static List<Map<String, Object>> buildHandlerRankings(List<InquiryTicket> tickets,
Map<String, InquiryStaffRole> staffByWecom) {
class Acc {
InquiryStaffRole staff;
long volume;
}
Map<String, Acc> byWecom = new LinkedHashMap<String, Acc>();
for (InquiryTicket t : tickets) {
if (t == null) {
continue;
}
String salesId = StringUtils.trimToEmpty(t.getSalesWecomId());
Set<String> seen = new HashSet<String>();
for (String uid : InquiryCollabMemberSupport.parseMemberIds(t.getCollabActorIds())) {
if (StringUtils.isBlank(uid) || !seen.add(uid)) {
continue;
}
// 发起销售在群里但不算处理人
if (uid.equalsIgnoreCase(salesId)) {
continue;
}
InquiryStaffRole staff = staffByWecom.get(uid);
if (staff == null) {
continue;
}
String role = mapRankRole(staff.getRoleCode());
if (!"route".equals(role) && !"product".equals(role)) {
continue;
}
Acc acc = byWecom.get(uid);
if (acc == null) {
acc = new Acc();
acc.staff = staff;
byWecom.put(uid, acc);
}
acc.volume++;
}
}
Map<String, List<Acc>> grouped = new LinkedHashMap<String, List<Acc>>();
grouped.put("route", new ArrayList<Acc>());
grouped.put("product", new ArrayList<Acc>());
for (Acc acc : byWecom.values()) {
List<Acc> bucket = grouped.get(mapRankRole(acc.staff.getRoleCode()));
if (bucket != null) {
bucket.add(acc);
}
}
Comparator<Acc> byVolume = Comparator.comparingLong((Acc a) -> a.volume).reversed()
.thenComparing(a -> a.staff.getName(), Comparator.nullsLast(String::compareTo));
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
for (String roleKey : Arrays.asList("route", "product")) {
List<Acc> bucket = grouped.get(roleKey);
if (bucket == null || bucket.isEmpty()) {
continue;
}
bucket.stream().sorted(byVolume).limit(RANK_PER_ROLE).forEach(a -> {
Map<String, Object> row = new LinkedHashMap<String, Object>();
row.put("name", StringUtils.defaultIfBlank(a.staff.getName(), "-"));
row.put("role", roleKey);
row.put("dept", StringUtils.defaultIfBlank(a.staff.getDepartName(), "-"));
row.put("volumeNum", a.volume);
rows.add(row);
});
}
return rows;
}
/**
* 人员排名:与工单列表 enrichDisplayFields 同口径。
* 聚合键优先 salesWecomId(同人合并),展示名走 resolveSalesDisplayName。
*
* @param agentTeamOnly true 时只保留员工岗位为航线/产品的人(智能体团队),去掉销售与未绑定用户
*/
private static List<Map<String, Object>> buildRankings(List<InquiryTicket> tickets,
Map<String, InquiryStaffRole> staffByWecom,
Map<String, InquiryStaffRole> staffByName,
boolean agentTeamOnly) {
static List<Map<String, Object>> buildRankings(List<InquiryTicket> tickets,
Map<String, InquiryStaffRole> staffByWecom,
Map<String, InquiryStaffRole> staffByName,
boolean agentTeamOnly) {
class Acc {
String name;
String role;
/** 同一人的稳定聚合键:企微 userid 优先,其次员工企微,最后中文名。 */
String personKey;
InquiryStaffRole staff;
long volume;
}
Map<String, Acc> byKey = new LinkedHashMap<>();
// 销售:询价发起人,陆/海/空都算。兼航线/产品岗的发起人仍归销售档。
if (!agentTeamOnly) {
for (InquiryTicket t : tickets) {
if (t == null) {
continue;
}
String wecom = StringUtils.trimToEmpty(t.getSalesWecomId());
InquiryStaffRole staff = StringUtils.isNotBlank(wecom) ? staffByWecom.get(wecom) : null;
String staffName = staff != null ? staff.getName() : null;
String display = InquiryTicketDisplaySupport.resolveSalesDisplayName(
t.getSalesName(), t.getSalesWecomId(), staffName);
if (StringUtils.isBlank(display)) {
continue;
}
// 仅企微 userid、又无员工绑定时不当人名进榜(与列表「应显示中文名」一致)
if (staff == null && InquiryTicketDisplaySupport.looksLikeWecomUserId(display)) {
continue;
}
if (staff == null) {
staff = staffByName.get(display.trim());
}
String personKey;
if (StringUtils.isNotBlank(wecom)) {
personKey = wecom.trim().toLowerCase();
} else if (staff != null && StringUtils.isNotBlank(staff.getWecomId())) {
personKey = staff.getWecomId().trim().toLowerCase();
} else {
personKey = "n:" + display.trim().toLowerCase();
}
String key = "sales|" + (StringUtils.isNotBlank(wecom) ? "w:" + wecom : "n:" + display.trim());
Acc acc = byKey.get(key);
if (acc == null) {
acc = new Acc();
acc.name = display.trim();
acc.role = "sales";
acc.personKey = personKey;
acc.staff = staff;
byKey.put(key, acc);
}
acc.volume++;
if (StringUtils.isBlank(acc.personKey)) {
acc.personKey = personKey;
}
if (acc.staff == null && staff != null) {
acc.staff = staff;
}
// 有员工中文名时覆盖展示名,避免残留 userid
if (acc.staff != null && StringUtils.isNotBlank(acc.staff.getName())) {
acc.name = acc.staff.getName().trim();
}
}
}
// 产品/航线:按工单业务线取处理人。海运/陆运 → 产品,空运 → 航线。
for (InquiryTicket t : tickets) {
if (t == null) {
continue;
}
String wecom = StringUtils.trimToEmpty(t.getSalesWecomId());
InquiryStaffRole staff = StringUtils.isNotBlank(wecom) ? staffByWecom.get(wecom) : null;
String staffName = staff != null ? staff.getName() : null;
String display = InquiryTicketDisplaySupport.resolveSalesDisplayName(
t.getSalesName(), t.getSalesWecomId(), staffName);
if (StringUtils.isBlank(display)) {
List<String> actors = InquiryCollabMemberSupport.parseMemberIds(t.getCollabActorIds());
if (actors.isEmpty()) {
continue;
}
// 仅企微 userid、又无员工绑定时不当人名进榜(与列表「应显示中文名」一致)
if (staff == null && InquiryTicketDisplaySupport.looksLikeWecomUserId(display)) {
continue;
}
if (staff == null) {
staff = staffByName.get(display.trim());
}
String key = StringUtils.isNotBlank(wecom) ? "w:" + wecom : "n:" + display.trim();
Acc acc = byKey.get(key);
if (acc == null) {
acc = new Acc();
acc.name = display.trim();
acc.staff = staff;
acc.volume = 0L;
byKey.put(key, acc);
}
acc.volume++;
if (acc.staff == null && staff != null) {
acc.staff = staff;
}
// 有员工中文名时覆盖展示名,避免残留 userid
if (acc.staff != null && StringUtils.isNotBlank(acc.staff.getName())) {
acc.name = acc.staff.getName().trim();
String salesId = StringUtils.trimToEmpty(t.getSalesWecomId());
Set<String> seen = new HashSet<>();
for (String uid : actors) {
String id = StringUtils.trimToEmpty(uid);
// 发起销售在群里但不算处理人
if (id.isEmpty() || id.equalsIgnoreCase(salesId) || !seen.add(id)) {
continue;
}
InquiryStaffRole staff = staffByWecom.get(id);
// 只认产品/航线岗:销售岗或未绑定员工不进处理量榜
if (staff == null || !staff.hasProductRole() || StringUtils.isBlank(staff.getName())) {
continue;
}
String role = rankRoleForTicket(t, staff);
if (!"route".equals(role) && !"product".equals(role)) {
continue;
}
String key = role + "|" + id;
Acc acc = byKey.get(key);
if (acc == null) {
acc = new Acc();
acc.name = staff.getName().trim();
acc.role = role;
acc.personKey = id.trim().toLowerCase();
acc.staff = staff;
byKey.put(key, acc);
}
if (StringUtils.isBlank(acc.personKey)) {
acc.personKey = id.trim().toLowerCase();
}
acc.volume++;
}
}
// 按岗位分组各取 TopN,禁止全局 Top20 被销售占满导致「航线无人 / 产品只剩 1 人」
// 按档分组各取 TopN,禁止全局 Top20 被销售占满导致「航线无人 / 产品只剩 1 人」
Map<String, List<Acc>> grouped = new LinkedHashMap<>();
grouped.put("sales", new ArrayList<>());
grouped.put("route", new ArrayList<>());
grouped.put("product", new ArrayList<>());
for (Acc a : byKey.values()) {
if (agentTeamOnly) {
// 智能体团队:员工表航线(air)/产品(sea|land);销售与未绑定用户一律排除
if (a.staff == null) {
continue;
}
String rr = mapRankRole(a.staff.getRoleCode());
if (!"route".equals(rr) && !"product".equals(rr)) {
continue;
}
List<Acc> bucket = grouped.get(a.role);
if (bucket != null) {
bucket.add(a);
}
String role = a.staff != null ? mapRankRole(a.staff.getRoleCode()) : "sales";
List<Acc> bucket = grouped.get(role);
if (bucket == null) {
bucket = grouped.get("sales");
}
bucket.add(a);
}
Comparator<Acc> byVolume = Comparator.comparingLong((Acc a) -> a.volume).reversed()
.thenComparing(a -> a.name, Comparator.nullsLast(String::compareTo));
@@ -487,13 +465,10 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
bucket.stream().sorted(byVolume).limit(RANK_PER_ROLE).forEach(a -> {
Map<String, Object> row = new LinkedHashMap<>();
row.put("name", a.name);
if (a.staff != null) {
row.put("role", mapRankRole(a.staff.getRoleCode()));
row.put("dept", StringUtils.defaultIfBlank(a.staff.getDepartName(), "-"));
} else {
row.put("role", "sales");
row.put("dept", "-");
}
row.put("role", roleKey);
row.put("personKey", StringUtils.defaultString(a.personKey));
row.put("dept", a.staff != null
? StringUtils.defaultIfBlank(a.staff.getDepartName(), "-") : "-");
row.put("volumeNum", a.volume);
rows.add(row);
});
@@ -828,12 +803,37 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
return m;
}
/** 员工 roleCode → 看板筛选项 sales/route/product。 */
private static String mapRankRole(String roleCode) {
if ("air".equals(roleCode)) {
/**
* 排名分组岗位:按工单业务线优先——空运=航线,海运/陆运=产品。
* <p>
* 多段联运(MULTI)或业务线缺失时回退员工岗位:air→航线,sea/land→产品。
*/
static String rankRoleForTicket(InquiryTicket ticket, InquiryStaffRole staff) {
String line = ticket == null ? "" : StringUtils.trimToEmpty(ticket.getBusinessLine()).toUpperCase(Locale.ROOT);
if (line.contains("AIR") || line.contains("空运")) {
return "route";
}
if ("sea".equals(roleCode) || "land".equals(roleCode)) {
if (line.contains("SEA") || line.contains("LAND")
|| line.contains("海运") || line.contains("陆运")) {
return "product";
}
return mapRankRole(staff);
}
/**
* 员工多岗位 → 看板筛选项 sales/route/product。
* <p>
* 主岗位可能是销售,但这个人也兼航线/产品;优先按岗位集合归类,
* 否则销售+航线的人会被排行榜整条漏掉。air 优先归航线,sea/land 归产品。
*/
private static String mapRankRole(InquiryStaffRole staff) {
if (staff == null) {
return "sales";
}
if (staff.hasRole("air")) {
return "route";
}
if (staff.hasRole("sea") || staff.hasRole("land")) {
return "product";
}
return "sales";
@@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -42,11 +43,24 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
@Override
public Map<String, Long> countByRole() {
List<InquiryStaffRole> all = list();
return countByRole(null);
}
@Override
public Map<String, Long> countByRole(java.util.Collection<String> visibleWecomIds) {
List<InquiryStaffRole> all;
if (visibleWecomIds == null) {
all = list();
} else if (visibleWecomIds.isEmpty()) {
all = new ArrayList<>();
} else {
all = list(new QueryWrapper<InquiryStaffRole>()
.in("wecom_id", new ArrayList<>(visibleWecomIds)));
}
Map<String, Long> map = new HashMap<>();
map.put("all", (long) all.size());
for (String code : ROLE_CODES) {
long c = all.stream().filter(r -> code.equals(r.getRoleCode())).count();
long c = all.stream().filter(r -> r != null && r.hasRole(code)).count();
map.put(code, c);
}
return map;
@@ -109,7 +123,11 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
row.setName(StringUtils.defaultIfBlank(m.getName(), m.getUserid()));
row.setMobile(StringUtils.trimToNull(m.getMobile()));
row.setDepartName(StringUtils.trimToNull(m.getDepartmentName()));
row.setDeptId(StringUtils.trimToNull(m.getDepartmentId()));
row.setDeptPath(StringUtils.trimToNull(m.getDepartmentIdPath()));
row.setDataScope("self_sub");
row.setRoleCode(DEFAULT_ROLE);
row.setRoleCodes(DEFAULT_ROLE);
row.setRoleLabel(DEFAULT_ROLE_LABEL);
row.setNotifyEventException(0);
row.setStatus("active");
@@ -128,6 +146,17 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
if (StringUtils.isNotBlank(m.getDepartmentName())) {
existing.setDepartName(m.getDepartmentName());
}
// 部门 ID/路径随后台组织维护,但企微是最新事实源:同步时刷新。
// 直属上级与数据范围是运营配置,绝不覆盖。
if (StringUtils.isNotBlank(m.getDepartmentId())) {
existing.setDeptId(m.getDepartmentId());
}
if (StringUtils.isNotBlank(m.getDepartmentIdPath())) {
existing.setDeptPath(m.getDepartmentIdPath());
}
if (StringUtils.isBlank(existing.getRoleCodes())) {
existing.setRoleCodes(StringUtils.defaultIfBlank(existing.getRoleCode(), DEFAULT_ROLE));
}
existing.setUpdateBy(op);
existing.setUpdateTime(now);
updateById(existing);
@@ -154,7 +183,7 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
@Override
public List<Map<String, Object>> matchSeaStaff(String origin, String destination) {
List<InquiryStaffRole> rows = list(new QueryWrapper<InquiryStaffRole>()
.eq("role_code", "sea")
.and(w -> w.eq("role_code", "sea").or().apply("FIND_IN_SET('sea', role_codes)"))
.eq("status", "active"));
return org.jeecg.modules.inquiry.staff.SeaStaffMatcher.match(rows, origin, destination);
}
@@ -165,7 +194,7 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
@Override
public List<Map<String, Object>> matchLandStaff(String routeCategory) {
List<InquiryStaffRole> rows = list(new QueryWrapper<InquiryStaffRole>()
.eq("role_code", "land")
.and(w -> w.eq("role_code", "land").or().apply("FIND_IN_SET('land', role_codes)"))
.eq("status", "active"));
return org.jeecg.modules.inquiry.staff.LandStaffMatcher.match(rows, routeCategory);
}
@@ -178,20 +207,22 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
return out;
}
List<InquiryStaffRole> rows = list(new QueryWrapper<InquiryStaffRole>()
.eq("role_code", code)
.and(w -> w.eq("role_code", code).or().apply("FIND_IN_SET({0}, role_codes)", code))
.eq("status", "active"));
for (InquiryStaffRole row : rows) {
if (row == null || StringUtils.isBlank(row.getWecomId())) {
if (row == null || StringUtils.isBlank(row.getWecomId()) || !row.hasRole(code)) {
continue;
}
Map<String, Object> one = new HashMap<>();
one.put("name", row.getName());
one.put("wecomId", row.getWecomId());
one.put("roleCode", row.getRoleCode());
one.put("roleCodes", row.effectiveRoleCodes());
one.put("status", row.getStatus());
// 成交跟进按「是负责人 + 负责线路」匹配,缺这两项智能体对不上人。
one.put("isLeader", row.getIsLeader());
one.put("routes", StringUtils.defaultString(row.getRoutes()));
// 智能体按本岗位的线路匹配;多岗位时不能把别的岗位线路混进来。
one.put("routes", StringUtils.defaultString(row.routesForRole(code)));
out.add(one);
}
return out;
@@ -207,7 +238,12 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
out.put("name", row.getName());
out.put("wecomId", row.getWecomId());
out.put("roleCode", row.getRoleCode());
out.put("roleCodes", row.effectiveRoleCodes());
out.put("roleLabel", row.getRoleLabel());
out.put("status", row.getStatus());
out.put("deptId", row.getDeptId());
out.put("deptPath", row.getDeptPath());
out.put("dataScope", row.getDataScope());
return out;
}
@@ -229,7 +265,12 @@ public class InquiryStaffRoleServiceImpl extends ServiceImpl<InquiryStaffRoleMap
out.put("name", row.getName());
out.put("wecomId", row.getWecomId());
out.put("roleCode", row.getRoleCode());
out.put("roleCodes", row.effectiveRoleCodes());
out.put("roleLabel", row.getRoleLabel());
out.put("status", row.getStatus());
out.put("deptId", row.getDeptId());
out.put("deptPath", row.getDeptPath());
out.put("dataScope", row.getDataScope());
return out;
}
}
@@ -32,6 +32,7 @@ import org.jeecg.modules.inquiry.support.InquiryDataScopeSupport;
import org.jeecg.modules.inquiry.support.InquiryMultiSegmentSupport;
import org.jeecg.modules.inquiry.support.InquiryQuoteDisplaySupport;
import org.jeecg.modules.inquiry.support.InquiryQuoteFileSupport;
import org.jeecg.modules.inquiry.support.InquiryQuotedBySupport;
import org.jeecg.modules.inquiry.support.InquiryTicketDisplaySupport;
import org.jeecg.modules.inquiry.support.InquiryTicketFactsSupport;
import org.jeecg.modules.inquiry.support.InquiryTicketPriceSupport;
@@ -39,6 +40,7 @@ import org.jeecg.modules.inquiry.support.InquiryWorkOrderAttachmentStore;
import org.jeecg.modules.inquiry.support.InquiryWorkOrderExcelExport;
import org.jeecg.modules.inquiry.tms.InquiryTmsQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
@@ -84,6 +86,15 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
private InquiryTmsQueryService tmsQueryService;
@Autowired
private InquiryStaffRoleMapper staffRoleMapper;
/**
* 智能体销售门禁的服务端兜底开关。
* <p>
* 与智能体 AGENT_SALES_GATE_ENABLED 对齐:灰度期默认关,避免历史调用方/测试被拦;
* 打开后建单必须来自启用中的销售岗位,防止绕过智能体直接调接口。
*/
@Value("${inquiry.agent.sales-gate-enabled:false}")
private boolean agentSalesGateEnabled;
@Autowired
private InquiryExceptionNotifyMapper exceptionNotifyMapper;
@Autowired
@@ -94,7 +105,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
/** 智能体出单/系统附件落库标记;详情展示时解析成机器人显示名。 */
private static final String ATTACH_UPLOADER_AGENT = "agent";
/** 与智能体 bot_name 默认一致;库里 system.bot_display_name 优先。 */
private static final String DEFAULT_BOT_DISPLAY_NAME = "智价通AIQ";
private static final String DEFAULT_BOT_DISPLAY_NAME = "智价通";
@Override
public IPage<InquiryTicket> pageView(Page<InquiryTicket> page, Map<String, String> filters) {
@@ -182,9 +193,8 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (StringUtils.isNotBlank(dateTo)) {
qw.le(InquiryTicket::getCreateTime, dateTo + " 23:59:59");
}
// 与看板同源:只看自己,再按角色收海陆空。陆运中港看不到空运、海运工单。
InquiryDataScopeSupport.applySelfOnly(qw);
InquiryDataScopeSupport.applyRoleBizLines(qw);
// 与看板同源:先按员工组织范围(未配置则沿用只看自己),再按角色收海陆空。
InquiryDataScopeSupport.applyDataScope(qw);
qw.orderByDesc(InquiryTicket::getCreateTime);
return qw;
}
@@ -206,6 +216,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (ticket == null) {
throw new IllegalArgumentException("工单不存在: " + row.getWorkOrderNo());
}
InquiryDataScopeSupport.assertTicketVisible(ticket);
InquiryDataScopeSupport.assertTicketBizAllowed(ticket);
java.io.InputStream in = InquiryWorkOrderAttachmentStore.openStream(row.getObjectKey());
if (in == null) {
@@ -239,6 +250,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (ticket == null) {
throw new IllegalArgumentException("工单不存在: " + workOrderNo);
}
InquiryDataScopeSupport.assertTicketVisible(ticket);
InquiryDataScopeSupport.assertTicketBizAllowed(ticket);
enrichDisplayFields(Collections.singletonList(ticket));
List<InquiryQuote> quotes = quoteMapper.selectList(new LambdaQueryWrapper<InquiryQuote>()
@@ -259,6 +271,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
List<InquiryTicketStatusLog> timeline = statusLogMapper.selectList(new LambdaQueryWrapper<InquiryTicketStatusLog>()
.eq(InquiryTicketStatusLog::getWorkOrderNo, workOrderNo)
.orderByAsc(InquiryTicketStatusLog::getCreateTime));
fillQuotedByRemarks(timeline, quotes, ticket);
List<InquiryExceptionCase> exceptions = exceptionCaseMapper.selectList(new LambdaQueryWrapper<InquiryExceptionCase>()
.eq(InquiryExceptionCase::getWorkOrderNo, workOrderNo)
.orderByDesc(InquiryExceptionCase::getCreateTime));
@@ -277,7 +290,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
* <p>
* 真人上传:用 body 的 senderId/createBy。
* 智能体出单/系统落库:无真人 sender 时固定写 {@link #ATTACH_UPLOADER_AGENT},
* <b>禁止</b>用发起人冒充上传人(产品:智价通AIQ 上传须显示智价通AIQ)。
* <b>禁止</b>用发起人冒充上传人(产品:智价通 上传须显示智价通)。
* 副作用:无;只读 body。
*/
private static String resolveAttachmentUploader(Map<String, Object> body, InquiryTicket ticket) {
@@ -291,7 +304,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
}
/**
* 详情附件上传人展示:真人企微 id→姓名;agent/system/空→机器人显示名(智价通AIQ)。
* 详情附件上传人展示:真人企微 id→姓名;agent/system/空→机器人显示名(智价通)。
* 兼容错误回填:create_by 被写成发起人、但文件名是报价单时,仍按机器人显示。
* 副作用:只改内存中的 createBy,不写库。
*/
@@ -414,8 +427,8 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
ticket.getSalesName(), ticket.getSalesWecomId(), staffName));
InquiryTicketDisplaySupport.applyRequirementSummary(ticket);
List<InquiryQuote> quoteRows = quotesByNo.get(ticket.getWorkOrderNo());
// 空运未选舱的 TMS 备选:不进后台报价列,也不参与销售价汇总。
List<InquiryQuote> displayRows = filterOutPendingAirCabinQuotes(quoteRows);
// 空运未选舱 / 陆运未选线路的 TMS 备选:不进后台报价列,也不参与销售价汇总。
List<InquiryQuote> displayRows = filterOutPendingSelectionQuotes(quoteRows);
InquiryTicketPriceSupport.apply(ticket, displayRows);
if (displayRows != null) {
for (InquiryQuote q : displayRows) {
@@ -458,7 +471,9 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
}
List<InquiryStaffRole> staffRows = staffRoleMapper.selectList(new LambdaQueryWrapper<InquiryStaffRole>()
.in(InquiryStaffRole::getWecomId, new ArrayList<>(wecomIds))
.in(InquiryStaffRole::getRoleCode, Arrays.asList("air", "sea", "land"))
.and(w -> w.in(InquiryStaffRole::getRoleCode, Arrays.asList("air", "sea", "land"))
.or().apply("FIND_IN_SET('air', role_codes) OR FIND_IN_SET('sea', role_codes) "
+ "OR FIND_IN_SET('land', role_codes)"))
.eq(InquiryStaffRole::getStatus, "active"));
Map<String, String> result = new HashMap<>();
if (staffRows == null) {
@@ -486,7 +501,9 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
}
List<InquiryStaffRole> rows = staffRoleMapper.selectList(new LambdaQueryWrapper<InquiryStaffRole>()
.like(InquiryStaffRole::getName, keyword.trim())
.in(InquiryStaffRole::getRoleCode, Arrays.asList("air", "sea", "land"))
.and(w -> w.in(InquiryStaffRole::getRoleCode, Arrays.asList("air", "sea", "land"))
.or().apply("FIND_IN_SET('air', role_codes) OR FIND_IN_SET('sea', role_codes) "
+ "OR FIND_IN_SET('land', role_codes)"))
.eq(InquiryStaffRole::getStatus, "active"));
if (rows == null || rows.isEmpty()) {
return Collections.emptyList();
@@ -507,37 +524,49 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
/**
* 单票处理人姓名:按互动先后顺序,过滤发起销售,只留产品/航线岗。
* 只被拉进群没互动、或没建群 → 空列表(前端显示「—」)。
* <p>
* 销售兼产品/航线、自己报价时不直接丢掉:若除他之外没有别的处理人,
* 回退显示本人姓名。否则「销售=产品/航线同一人」的单子处理人整列为空,
* 后台看还是「没人处理」。
*/
private static List<String> resolveHandlers(InquiryTicket ticket, Map<String, String> handlerNameByWecom) {
static List<String> resolveHandlers(InquiryTicket ticket, Map<String, String> handlerNameByWecom) {
if (ticket == null || handlerNameByWecom == null || handlerNameByWecom.isEmpty()) {
return Collections.emptyList();
}
String salesId = StringUtils.trimToEmpty(ticket.getSalesWecomId());
List<String> names = new ArrayList<>();
Set<String> seen = new HashSet<>();
String salesHandlerName = null;
for (String uid : parseMemberIds(ticket.getCollabActorIds())) {
if (StringUtils.isBlank(uid)) {
continue;
}
String id = uid.trim();
if (id.equalsIgnoreCase(salesId) || seen.contains(id)) {
if (seen.contains(id)) {
continue;
}
String name = handlerNameByWecom.get(id);
if (StringUtils.isBlank(name)) {
continue;
}
names.add(name);
seen.add(id);
if (id.equalsIgnoreCase(salesId)) {
salesHandlerName = name;
continue;
}
names.add(name);
}
if (names.isEmpty() && StringUtils.isNotBlank(salesHandlerName)) {
names.add(salesHandlerName);
}
return names;
}
/**
* 列表/详情:丢掉空运「待选舱」TMS 行,避免未选舱却显示费用。
* 判定与 InquiryTmsQueryService.isAirCabinPendingSelection 对齐。
* 列表/详情:丢掉空运「待选舱」/ 陆运「待选线路」的 TMS 行,避免未选却显示费用。
* 判定与 InquiryTmsQueryService.isAirCabinPendingSelection / isLandRoutePendingSelection 对齐。
*/
static List<InquiryQuote> filterOutPendingAirCabinQuotes(List<InquiryQuote> rows) {
static List<InquiryQuote> filterOutPendingSelectionQuotes(List<InquiryQuote> rows) {
if (rows == null || rows.isEmpty()) {
return rows;
}
@@ -546,7 +575,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (q == null) {
continue;
}
if (isPendingAirCabinQuoteRow(q)) {
if (isPendingAirCabinQuoteRow(q) || isPendingLandRouteQuoteRow(q)) {
continue;
}
out.add(q);
@@ -554,6 +583,39 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
return out;
}
/**
* 「已报价」时间线补报价人(已报价,报价人:张三)。
* <p>
* 新数据在写流转时已带备注,这里只给上线前的历史行回填:
* 按与流转同一时刻落库的报价行判 TMS / 手工;手工报价用本单唯一处理人姓名,
* 多人互动时不猜具体是谁。只改响应内存,不回写库。
*/
private void fillQuotedByRemarks(List<InquiryTicketStatusLog> timeline,
List<InquiryQuote> quotes,
InquiryTicket ticket) {
if (timeline == null || timeline.isEmpty()) {
return;
}
List<String> handlers = ticket == null ? null : ticket.getHandlers();
String singleHandler = handlers != null && handlers.size() == 1
? StringUtils.trimToEmpty(handlers.get(0)) : "";
for (InquiryTicketStatusLog row : timeline) {
if (row == null || !TicketStatuses.QUOTED.equals(StringUtils.trimToEmpty(row.getToStatus()))) {
continue;
}
// 写流转时已带备注(报价人 / 销售调价说明等)的不覆盖。
if (StringUtils.isNotBlank(row.getRemark())) {
continue;
}
InquiryQuote hit = InquiryQuotedBySupport.nearestQuote(quotes, row.getCreateTime());
if (hit == null) {
continue;
}
row.setRemark(InquiryQuotedBySupport.remark(
InquiryQuotedBySupport.legacyName(hit, singleHandler)));
}
}
static boolean isPendingAirCabinQuoteRow(InquiryQuote q) {
if (q == null || StringUtils.isBlank(q.getPayloadJson())) {
return false;
@@ -589,6 +651,58 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
return false;
}
/**
* 陆运待选线路的 TMS 行:payload 打了 pending_land_route_pick,
* 或 landSegments 按 segmentSequence 分组多于 1 条且没有 selected_land_route。
* 与 InquiryTmsQueryService.isLandRoutePendingSelection 同口径,防止旧数据进列表。
*/
static boolean isPendingLandRouteQuoteRow(InquiryQuote q) {
if (q == null || StringUtils.isBlank(q.getPayloadJson())) {
return false;
}
try {
JSONObject obj = JSON.parseObject(q.getPayloadJson());
if (obj == null) {
return false;
}
if (obj.get("selected_land_route") != null || obj.get("selectedLandRoute") != null) {
return false;
}
if ("1".equals(StringUtils.trimToEmpty(obj.getString("pending_land_route_pick")))) {
return true;
}
Object raw = obj.get("landSegments");
if (raw == null) {
raw = obj.get("land_segments");
}
List<?> legs;
if (raw instanceof List) {
legs = (List<?>) raw;
} else if (raw instanceof String && ((String) raw).trim().startsWith("[")) {
legs = JSON.parseArray((String) raw);
} else {
return false;
}
if (legs == null) {
return false;
}
Set<String> seqs = new HashSet<>();
for (Object leg : legs) {
if (!(leg instanceof Map)) {
continue;
}
Object seq = ((Map<?, ?>) leg).get("segmentSequence");
if (seq == null) {
seq = ((Map<?, ?>) leg).get("segment_sequence");
}
seqs.add(seq == null ? "1" : String.valueOf(seq));
}
return seqs.size() > 1;
} catch (Exception ignored) {
return false;
}
}
/** 列表一次取出本页工单的报价记录,避免按单 N+1。 */
private Map<String, List<InquiryQuote>> loadQuotesByWorkOrder(List<InquiryTicket> tickets) {
List<String> nos = new ArrayList<>();
@@ -696,6 +810,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (ticket == null) {
throw new IllegalArgumentException("工单不存在: " + req.getWorkOrderNo());
}
InquiryDataScopeSupport.assertTicketVisible(ticket);
InquiryDataScopeSupport.assertTicketBizAllowed(ticket);
String from = ticket.getStatus();
String to = req.getToStatus().trim();
@@ -942,6 +1057,30 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
return "";
}
/**
* 智能体建单的服务端销售校验。
* <p>
* 智能体前端门禁可能被绕过(统一服务 token 直接调接口),这里按发起企微 userid
* 再查一次员工岗位。开关关闭时完全放行,保持旧调用方兼容。
*/
private void assertAgentSalesAllowed(String wecomId) {
if (!agentSalesGateEnabled) {
return;
}
String id = StringUtils.trimToEmpty(wecomId);
if (id.isEmpty()) {
throw new IllegalArgumentException("no_inquiry_permission");
}
InquiryStaffRole staff = staffRoleMapper.selectOne(new LambdaQueryWrapper<InquiryStaffRole>()
.eq(InquiryStaffRole::getWecomId, id)
.last("LIMIT 1"));
boolean active = staff != null && "active".equalsIgnoreCase(
StringUtils.defaultIfBlank(staff.getStatus(), "active"));
if (!active || !staff.hasRole("sales")) {
throw new IllegalArgumentException("no_inquiry_permission");
}
}
/**
* 智能体建单。
* <p>
@@ -954,6 +1093,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (req == null || StringUtils.isBlank(req.getSalesWecomId()) || StringUtils.isBlank(req.getBusinessLine())) {
throw new IllegalArgumentException("salesWecomId 与 businessLine 不能为空");
}
assertAgentSalesAllowed(req.getSalesWecomId());
// 每次出询价确认都新开一单,相同需求不复用未关闭工单。
Map<String, String> facts = scrubPlaceholderFacts(
req.getFacts() == null ? new HashMap<>() : new HashMap<>(req.getFacts()));
@@ -983,6 +1123,9 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
ticket.setFclLcl(StringUtils.trimToNull(facts.get("整柜或拼柜")));
ticket.setContainerSpec(StringUtils.trimToNull(facts.get("箱型箱量")));
ticket.setFactsJson(JSON.toJSONString(facts));
// 业务询价原始内容:销售 1v1 首条询价原话,只做展示留档;
// 不能塞进 facts,否则会进入 TMS 出站和模板匹配语料。
ticket.setInquiryRawText(StringUtils.trimToNull(req.getInquiryRawText()));
// 多段只带 segments_json:投影到列表列,否则后台起运/目的/品名全空。
boolean multiProjected = InquiryMultiSegmentSupport.projectTicketColumns(ticket, facts);
if (!multiProjected) {
@@ -1258,6 +1401,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (ticket == null) {
throw new IllegalArgumentException("工单不存在: " + req.getWorkOrderNo());
}
InquiryDataScopeSupport.assertTicketVisible(ticket);
InquiryDataScopeSupport.assertTicketBizAllowed(ticket);
return ticket;
}
@@ -1386,6 +1530,9 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
// 避免 7 种陆运业务靠关键词猜错表(中港整车/中港拼车名字互相包含)。
out.put("biz_type_label", StringUtils.defaultString(ticket.getBizTypeLabel()));
out.put("bizTypeLabel", StringUtils.defaultString(ticket.getBizTypeLabel()));
// 业务询价原始内容:群摘要和续办读单都要用;只展示,不参与查价。
out.put("inquiry_raw_text", StringUtils.defaultString(ticket.getInquiryRawText()));
out.put("inquiryRawText", StringUtils.defaultString(ticket.getInquiryRawText()));
String ticketSalesWecomId = StringUtils.defaultString(ticket.getSalesWecomId());
out.put("salesWecomId", ticketSalesWecomId);
out.put("sales_wecom_id", ticketSalesWecomId);
@@ -1694,6 +1841,9 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
out.put("collab_ended", ended);
out.put("status", StringUtils.defaultString(ticket.getStatus()));
out.put("business_line", StringUtils.defaultString(ticket.getBusinessLine()));
// 群摘要要展示销售首条询价原话;与 getForAgent 同一套字段名。
out.put("inquiry_raw_text", StringUtils.defaultString(ticket.getInquiryRawText()));
out.put("inquiryRawText", StringUtils.defaultString(ticket.getInquiryRawText()));
out.put("facts", parseFactsJson(ticket.getFactsJson()));
out.put("quote", latestQuotePayload(ticket.getWorkOrderNo()));
out.put("lost_reason", StringUtils.defaultString(ticket.getLostReason()));
@@ -1913,9 +2063,10 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
.orderByAsc(InquiryQuote::getCreateTime));
InquiryTicketPriceSupport.apply(ticket, quotes);
// 报价本身就算一次互动:把发送人记进处理人快照(系统自动价没有 sender,不记)。
rememberCollabActor(ticket, text(body,
String sender = text(body,
"senderWecomId", "sender_wecom_id", "senderId", "sender_id",
"operatorUserId", "operator_user_id", "operator"));
"operatorUserId", "operator_user_id", "operator");
rememberCollabActor(ticket, sender);
ticket.setUpdateTime(new Date());
updateById(ticket);
String from = ticket.getStatus();
@@ -1927,6 +2078,10 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
TicketTransitionRequest tr = new TicketTransitionRequest();
tr.setWorkOrderNo(no);
tr.setToStatus(to);
if (TicketStatuses.QUOTED.equals(to)) {
// 时间线「已报价」必须带报价人,否则后台对不上是谁给的价格。
tr.setRemark(InquiryQuotedBySupport.remark(quoterName(ticket, sender)));
}
transition(tr, "agent");
ticket = findByWorkOrderNo(no);
}
@@ -2128,6 +2283,23 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
return InquiryCollabMemberSupport.parseMemberIds(raw);
}
/**
* 本次报价人姓名:企微 userid 先查员工管理,再退回销售名,最后才用 userid。
* 没有 sender(系统代写、无登录态)时用机器人显示名,禁止空着让后台猜。
*/
private String quoterName(InquiryTicket ticket, String sender) {
String uid = StringUtils.trimToEmpty(sender);
if (uid.isEmpty()) {
return loadBotDisplayName();
}
String name = resolveStaffDisplayName(uid);
if (StringUtils.isBlank(name) && ticket != null
&& uid.equalsIgnoreCase(StringUtils.trimToEmpty(ticket.getSalesWecomId()))) {
name = StringUtils.trimToEmpty(ticket.getSalesName());
}
return StringUtils.defaultIfBlank(name, uid);
}
/**
* 记下本次真正操作工单的产品/航线:只增不减,同一人重复操作不重复记。
* <p>
@@ -2574,6 +2746,8 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
one.put("name", sales != null ? StringUtils.defaultString(sales.getName())
: StringUtils.defaultString(ticket.getSalesName()));
one.put("roleCode", sales != null ? StringUtils.defaultString(sales.getRoleCode()) : "sales");
one.put("roleCodes", sales != null ? sales.effectiveRoleCodes()
: Collections.singletonList("sales"));
one.put("notifyEventException", sales != null && sales.getNotifyEventException() != null
? sales.getNotifyEventException() : 0);
out.add(one);
@@ -2591,6 +2765,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
one.put("wecomId", uid);
one.put("name", StringUtils.defaultString(row.getName()));
one.put("roleCode", StringUtils.defaultString(row.getRoleCode()));
one.put("roleCodes", row.effectiveRoleCodes());
one.put("notifyEventException", row.getNotifyEventException() == null ? 0 : row.getNotifyEventException());
out.add(one);
seen.add(uid);
@@ -38,7 +38,7 @@ public final class LandStaffMatcher {
if (row == null) {
continue;
}
if (!"land".equalsIgnoreCase(StringUtils.trimToEmpty(row.getRoleCode()))) {
if (!row.hasRole("land")) {
continue;
}
if (!"active".equalsIgnoreCase(StringUtils.defaultIfBlank(row.getStatus(), "active"))) {
@@ -47,7 +47,8 @@ public final class LandStaffMatcher {
if (StringUtils.isBlank(row.getWecomId())) {
continue;
}
List<String> tokens = routeTokens(row.getRoutes());
// 只取陆运自己的线路。
List<String> tokens = routeTokens(row.routesForRole("land"));
// 陆运全线:跟海运全线一样,一条勾选覆盖全部线路类别
if (!tokens.contains("陆运全线") && !tokens.contains(want)) {
continue;
@@ -56,7 +57,7 @@ public final class LandStaffMatcher {
item.put("name", StringUtils.defaultString(row.getName()));
item.put("wecomId", row.getWecomId().trim());
item.put("roleCode", "land");
item.put("routes", StringUtils.defaultString(row.getRoutes()));
item.put("routes", StringUtils.defaultString(row.routesForRole("land")));
item.put("status", "active");
hits.add(item);
}
@@ -36,7 +36,7 @@ public final class SeaStaffMatcher {
if (row == null) {
continue;
}
if (!"sea".equalsIgnoreCase(StringUtils.trimToEmpty(row.getRoleCode()))) {
if (!row.hasRole("sea")) {
continue;
}
if (!"active".equalsIgnoreCase(StringUtils.defaultIfBlank(row.getStatus(), "active"))) {
@@ -45,7 +45,8 @@ public final class SeaStaffMatcher {
if (StringUtils.isBlank(row.getWecomId())) {
continue;
}
String routes = StringUtils.defaultString(row.getRoutes());
// 只取海运自己的线路,避免多岗位并集里的空运三字码误命中港口。
String routes = StringUtils.defaultString(row.routesForRole("sea"));
if (routes.contains("海运·全部线路") || routes.contains("海运全线")
|| (StringUtils.isNotBlank(from) && routes.contains(from))
|| (StringUtils.isNotBlank(to) && routes.contains(to))) {
@@ -1,10 +1,13 @@
package org.jeecg.modules.inquiry.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
import java.util.ArrayList;
@@ -16,9 +19,12 @@ import java.util.Set;
* <p>
* 只看自己:非超管且 {@code dashboardSelfOnly=true} →
* {@code salesWecomId = 工号}(我发起的)或 {@code createBy = 登录名},
* 或协同群成员 {@code collabMemberIds} 含本人企微 id(我作为处理人的)。
* 或协同参与者快照含本人企微 id(我作为处理人的)。
* 产品/航线账号通常不发起询价,只处理销售建的单;若只认发起销售,
* 他们的看板与工单列表会整页为空(2026-11-21 产品反馈的 bug)。
* 协同参与者 = {@code collab_member_ids}(被拉进群)或 {@code collab_actor_ids}
* (真有报价等互动)。空运群不写成员快照,只看 member_ids 会让空运处理人
* 看不到自己处理的单(2026-11-26 吴季林反馈的 bug)。
* 业务范围:先按空运/海运/陆运收窄;若 dataPerms 点了陆运线路叶子(如中港),
* 再按 facts「线路类别」收窄,禁止中港权限看到东南亚等其它陆运单。
* 看板与工单列表共用,避免只收一边。没有登录上下文时不限制(智能体内部调用)。
@@ -26,9 +32,207 @@ import java.util.Set;
*/
public final class InquiryDataScopeSupport {
/** 工单协同成员快照解析;只读,失败当未命中。 */
private static final ObjectMapper JSON = new ObjectMapper();
private InquiryDataScopeSupport() {
}
/**
* 统一数据范围入口:员工组织范围优先,未配置时完全沿用旧逻辑(只看自己 + 角色业务线)。
* <p>
* 为什么保留旧入口:查不到员工记录(账号未绑定企微/员工表异常)时才退回旧逻辑,
* 避免整页 500;正常员工一律走 self/self_sub/dept/all,dashboard_self_only 不再参与。
*/
public static void applyDataScope(LambdaQueryWrapper<InquiryTicket> qw) {
if (qw == null) {
return;
}
LoginUser login = currentLoginUser();
if (login == null) {
return;
}
if (isAdministrator(login)) {
return;
}
InquiryStaffScopeService.Scope scope = orgScope(login);
if (scope == null) {
applySelfOnly(qw);
} else {
applyOrgScope(qw, scope, login);
}
applyRoleBizLines(qw);
}
/**
* 详情/流转/附件/异常处理:列表里不该出现的工单,按编号打开也不给看。
* <p>
* 补上旧实现的缺口:applySelfOnly 只作用于列表/看板,详情等入口只校验了业务线,
* 知道单号的"只看自己"账号仍能打开别人的单。
*/
public static void assertTicketVisible(InquiryTicket ticket) {
if (ticket == null) {
return;
}
LoginUser login = currentLoginUser();
if (login == null || isAdministrator(login)) {
return;
}
InquiryStaffScopeService.Scope scope = orgScope(login);
if (scope == null) {
// 无员工记录/异常:沿用旧 dashboard_self_only
if (!Boolean.TRUE.equals(login.getDashboardSelfOnly())) {
return;
}
if (legacySelfVisible(ticket, login)) {
return;
}
throw new JeecgBootException("当前账号无权查看该询价工单");
}
if (scope.isAll()) {
return;
}
String self = StringUtils.trimToEmpty(scope.getSelfWecom());
String owner = StringUtils.trimToEmpty(ticket.getSalesWecomId());
Set<String> visible = scope.getVisibleWecomIds();
if (StringUtils.isNotBlank(owner) && visible != null && visible.contains(owner)) {
return;
}
if (StringUtils.isNotBlank(self) && self.equals(owner)) {
return;
}
String username = StringUtils.trimToEmpty(login.getUsername());
if (StringUtils.isNotBlank(username)
&& username.equals(StringUtils.trimToEmpty(ticket.getCreateBy()))) {
return;
}
// 被拉进群(member)或真有过报价等互动(actor)都算本人处理的单。
if (StringUtils.isNotBlank(self) && isCollabParticipant(ticket, self)) {
return;
}
throw new JeecgBootException("当前账号无权查看该询价工单");
}
private static void applyOrgScope(LambdaQueryWrapper<InquiryTicket> qw,
InquiryStaffScopeService.Scope scope,
LoginUser login) {
// all:只受角色业务线限制,不再按人收窄。
if (scope.isAll()) {
return;
}
String self = StringUtils.trimToEmpty(scope.getSelfWecom());
String username = StringUtils.trimToEmpty(login.getUsername());
Set<String> visible = scope.getVisibleWecomIds();
qw.and(w -> {
boolean any = false;
if (visible != null && !visible.isEmpty()) {
w.in(InquiryTicket::getSalesWecomId, visible);
any = true;
}
if (StringUtils.isNotBlank(username)) {
if (any) {
w.or();
}
w.eq(InquiryTicket::getCreateBy, username);
any = true;
}
if (StringUtils.isNotBlank(self)) {
if (any) {
w.or();
}
appendParticipantOr(w, self);
any = true;
}
if (!any) {
w.apply("1 = 0");
}
});
}
/** 旧「只看自己」口径:发起销售、创建人、协同参与者三选一。 */
private static boolean legacySelfVisible(InquiryTicket ticket, LoginUser login) {
String wecom = wecomId(login);
if (StringUtils.isNotBlank(wecom)
&& wecom.equals(StringUtils.trimToEmpty(ticket.getSalesWecomId()))) {
return true;
}
String username = StringUtils.trimToEmpty(login.getUsername());
if (StringUtils.isNotBlank(username)
&& username.equals(StringUtils.trimToEmpty(ticket.getCreateBy()))) {
return true;
}
return StringUtils.isNotBlank(wecom) && isCollabParticipant(ticket, wecom);
}
/**
* 协同参与者:被拉进群(member_ids)或真有过报价等互动(actor_ids)。
* <p>
* 空运协同群不写成员快照,处理人只落在 actor_ids;只看 member_ids
* 会让空运处理人看不到自己处理的单。
*/
static boolean isCollabParticipant(InquiryTicket ticket, String wecom) {
if (ticket == null) {
return false;
}
return isCollabMember(ticket.getCollabMemberIds(), wecom)
|| isCollabMember(ticket.getCollabActorIds(), wecom);
}
/**
* 往数据范围条件里追加「协同参与者含本人」:member OR actor。
* <p>
* 调用方负责在前一个条件后补 OR;本方法内部只在 member 与 actor 之间补 OR。
*/
static void appendParticipantOr(LambdaQueryWrapper<InquiryTicket> w, String wecom) {
w.apply("(CASE WHEN JSON_VALID(collab_member_ids) "
+ "THEN JSON_CONTAINS(collab_member_ids, JSON_QUOTE({0})) ELSE 0 END)", wecom);
w.or().apply("(CASE WHEN JSON_VALID(collab_actor_ids) "
+ "THEN JSON_CONTAINS(collab_actor_ids, JSON_QUOTE({0})) ELSE 0 END)", wecom);
}
/** collab_member_ids 是 JSON 数组;兼容历史脏数据(非 JSON / 逗号串)。 */
static boolean isCollabMember(String memberIdsJson, String wecom) {
String raw = StringUtils.trimToEmpty(memberIdsJson);
String target = StringUtils.trimToEmpty(wecom);
if (raw.isEmpty() || target.isEmpty()) {
return false;
}
try {
JsonNode node = JSON.readTree(raw);
if (node != null && node.isArray()) {
for (JsonNode one : node) {
if (one != null && target.equals(StringUtils.trimToEmpty(one.asText()))) {
return true;
}
}
return false;
}
} catch (Exception ignored) {
// 落到字符串兼容
}
for (String part : raw.split("[,,\\s\"\\[\\]]+")) {
if (target.equals(part.trim())) {
return true;
}
}
return false;
}
private static InquiryStaffScopeService.Scope orgScope(LoginUser login) {
try {
String wecom = wecomId(login);
if (StringUtils.isBlank(wecom)) {
return null;
}
InquiryStaffScopeService service =
SpringContextUtils.getBean(InquiryStaffScopeService.class);
return service == null ? null : service.resolve(wecom);
} catch (Exception e) {
// 员工表/容器暂不可用时退回现状,避免整页 500。
return null;
}
}
/**
* 按当前登录账号把「只看自己」条件叠到工单查询上。
*
@@ -52,7 +256,7 @@ public final class InquiryDataScopeSupport {
return;
}
String wecom = wecomId(login);
// 处理人口径:协同群成员快照里含本人企微 id。
// 处理人口径:协同参与者快照(成员或互动)里含本人企微 id。
// 用 CASE WHEN JSON_VALID 兜住历史脏数据,避免 JSON_CONTAINS 解析失败把整页打 500。
boolean handlerScope = StringUtils.isNotBlank(wecom);
qw.and(w -> {
@@ -72,8 +276,7 @@ public final class InquiryDataScopeSupport {
if (any) {
w.or();
}
w.apply("(CASE WHEN JSON_VALID(collab_member_ids) "
+ "THEN JSON_CONTAINS(collab_member_ids, JSON_QUOTE({0})) ELSE 0 END)", wecom);
appendParticipantOr(w, wecom);
any = true;
}
if (!any) {
@@ -272,7 +475,7 @@ public final class InquiryDataScopeSupport {
}
/** 超管:登录名 admin,或 Shiro 角色 admin/管理员。 */
private static boolean isAdministrator(LoginUser login) {
public static boolean isAdministrator(LoginUser login) {
if (login == null) {
return false;
}
@@ -0,0 +1,79 @@
package org.jeecg.modules.inquiry.support;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.inquiry.entity.InquiryQuote;
import java.util.Date;
import java.util.List;
/**
* 状态流转「已报价」行的报价方备注:已报价,报价方:张三。
* <p>
* 职责:统一时间线文案;历史行(上线前没写备注的「已报价」)按同一时刻落库的报价行回填。
* 为什么必须带人:后台只看「已报价」四个字,销售对不上是谁给的价格。
* 副作用:只算字符串,不写库。
*/
public final class InquiryQuotedBySupport {
/** 时间线备注前缀;前端据此把分隔符从「 · 」换成「,」。 */
public static final String PREFIX = "报价方:";
/** TMS 标准价:报价方是运价库,不能冒充成某个员工。 */
public static final String TMS_NAME = "TMS";
/** 历史手工报价找不到唯一报价人时的兜底:只说是产品侧,禁止编人名。 */
public static final String PRODUCT_FALLBACK = "产品";
/** 报价落库与六态流转在同一事务、正常同一秒;留余量兼容慢连接。 */
private static final long WINDOW_BEFORE_MS = 5000L;
private static final long WINDOW_AFTER_MS = 2000L;
private InquiryQuotedBySupport() {
}
/**
* 备注文案:报价方为空时退回「产品」,绝不出现「报价方:」后面空白。
*/
public static String remark(String quoter) {
String who = StringUtils.trimToEmpty(quoter);
return PREFIX + (who.isEmpty() ? PRODUCT_FALLBACK : who);
}
/**
* 历史行回填:取与流转时刻最近的报价行(同一事务落库,前后只差毫秒)。
* <p>
* 只认窗口内的行,避免把上一轮报价算到这一次「已报价」上。
*/
public static InquiryQuote nearestQuote(List<InquiryQuote> quotes, Date at) {
if (quotes == null || quotes.isEmpty() || at == null) {
return null;
}
long t = at.getTime();
InquiryQuote best = null;
long bestGap = Long.MAX_VALUE;
for (InquiryQuote q : quotes) {
if (q == null || q.getCreateTime() == null) {
continue;
}
long gap = q.getCreateTime().getTime() - t;
if (gap < -WINDOW_BEFORE_MS || gap > WINDOW_AFTER_MS) {
continue;
}
long abs = Math.abs(gap);
if (abs < bestGap) {
bestGap = abs;
best = q;
}
}
return best;
}
/**
* 历史行报价人:TMS 快照写 TMS;手工报价只在能确定唯一产品/航线人名时写名字,
* 多人互动时不猜具体是谁,统一写「产品」。
*/
public static String legacyName(InquiryQuote quote, String singleHandlerName) {
if (quote != null && InquiryQuoteDisplaySupport.isTms(quote.getSource(), quote.getSourceLabel())) {
return TMS_NAME;
}
String who = StringUtils.trimToEmpty(singleHandlerName);
return who.isEmpty() ? PRODUCT_FALLBACK : who;
}
}
@@ -99,15 +99,12 @@ public final class InquiryRoleBizScope {
}
Set<String> fromName = bizFromRoleName(role.getRoleName());
Set<String> fromPerms = bizFromDataPerms(role.getDescription());
// 角色名只指向一条业务线时,数据权限不再把别的业务线加进来。
// 「陆运中港」即使描述里误勾了海运/空运,报价模板也只出陆运。
if (fromName.size() == 1) {
anyScoped = true;
allowed.addAll(fromName);
continue;
}
// 数据权限是运营显式勾选的授权,与角色名取并集:
// 「海运领导」再勾「空运数据」= 同时看海运、空运;不再被角色名单独锁死。
// 未勾选数据权限时仍按角色名推断,兼容历史角色。
if (!fromPerms.isEmpty()) {
anyScoped = true;
allowed.addAll(fromName);
allowed.addAll(fromPerms);
continue;
}
@@ -0,0 +1,251 @@
package org.jeecg.modules.inquiry.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.inquiry.entity.InquiryStaffRole;
import org.jeecg.modules.inquiry.mapper.InquiryStaffRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 员工组织范围解析:直属上级链 + 本部门及以下。
* <p>
* 为什么按员工表(企微身份)而不是 sys_depart:
* 工单的发起人字段是 {@code sales_wecom_id},员工表才有完整的企微成员(生产 368 人);
* 后台账号通过 {@code sys_user.work_no} 映射到同一 userid。用企微部门 ID 路径做子树判断,
* MySQL 5.7 没有 CTE 也能用前缀匹配。
* <p>
* 数据范围取值:
* <ul>
* <li>{@code self}:仅本人(含本人处理的协同单);</li>
* <li>{@code self_sub}:本人 + 递归下级 + 跨部门领导链(默认);</li>
* <li>{@code dept}:本人 + 递归下级 + 跨部门领导链 + 本部门及以下;</li>
* <li>{@code all}:全部(仍受角色业务线限制)。</li>
* </ul>
* 历史 inherit/空值按 self_sub 处理;不再存在旧规则绕过。
* 线程:员工全量快照 30 秒缓存,读多写少;员工变更最迟 30 秒生效。
*/
@Service
public class InquiryStaffScopeService {
private static final long CACHE_TTL_MS = 30_000L;
@Autowired
private InquiryStaffRoleMapper staffRoleMapper;
private volatile Snapshot snapshot;
/**
* 解析某个企微 userid 的数据范围。
*
* @param wecomId 当前登录账号的 work_no
* @return null 表示查不到员工/异常,调用方退回旧规则;正常员工不会返回 null
*/
public Scope resolve(String wecomId) {
String self = StringUtils.trimToEmpty(wecomId);
if (self.isEmpty()) {
return null;
}
Snapshot snap = snapshot();
InquiryStaffRole me = snap.byWecom.get(self);
if (me == null) {
return null;
}
String mode = StringUtils.trimToEmpty(me.getDataScope());
// 产品已删除 inherit;历史空值/旧值一律按默认 self_sub 处理,避免旧规则绕过。
if (mode.isEmpty() || "inherit".equalsIgnoreCase(mode)) {
mode = "self_sub";
}
Scope scope = new Scope(mode.toLowerCase(), self);
if ("all".equals(scope.getMode())) {
return scope;
}
LinkedHashSet<String> visible = new LinkedHashSet<>();
visible.add(self);
if ("self_sub".equals(scope.getMode()) || "dept".equals(scope.getMode())) {
collectSubordinates(self, snap, visible);
// 业务/虚线汇报对象独立于行政上级链:Y 部门的 D 业务上向 X 部门的 A 汇报,
// A 不在 D 的行政链上,也要通过这条关系看到 D。
collectBusinessSubordinates(snap.businessReports, self, visible);
}
if ("dept".equals(scope.getMode())) {
collectDeptSubtree(me, snap, visible);
}
scope.setVisibleWecomIds(visible);
return scope;
}
/** 测试/员工保存后强制下次重新加载。 */
public void invalidate() {
snapshot = null;
}
private void collectSubordinates(String self, Snapshot snap, Set<String> out) {
// 员工量级很小(生产约 368),BFS 比递归 SQL 更稳;visited 防环。
Set<String> visited = new HashSet<>();
visited.add(self);
List<String> frontier = new ArrayList<>();
frontier.add(self);
for (int depth = 0; depth < 32 && !frontier.isEmpty(); depth++) {
List<String> next = new ArrayList<>();
for (String leader : frontier) {
for (String report : snap.reports.getOrDefault(leader, java.util.Collections.emptyList())) {
if (StringUtils.isBlank(report) || !visited.add(report)) {
continue;
}
out.add(report);
next.add(report);
}
}
frontier = next;
}
}
/**
* 业务/虚线汇报链:从 self 出发,按 business_leader_wecom_ids 递归收集。
* <p>
* 只走业务汇报关系,不串到被汇报人的行政下级;行政链由 collectSubordinates 单独处理。
* 防环:visited 集合 + 最多 32 层。
*/
static void collectBusinessSubordinates(Map<String, List<String>> businessReports,
String self,
Set<String> out) {
if (businessReports == null || businessReports.isEmpty() || StringUtils.isBlank(self)) {
return;
}
Set<String> visited = new HashSet<>();
visited.add(self);
List<String> frontier = new ArrayList<>();
frontier.add(self);
for (int depth = 0; depth < 32 && !frontier.isEmpty(); depth++) {
List<String> next = new ArrayList<>();
for (String leader : frontier) {
for (String report : businessReports.getOrDefault(
leader, java.util.Collections.emptyList())) {
if (StringUtils.isBlank(report) || !visited.add(report)) {
continue;
}
out.add(report);
next.add(report);
}
}
frontier = next;
}
}
private void collectDeptSubtree(InquiryStaffRole me, Snapshot snap, Set<String> out) {
String path = StringUtils.trimToEmpty(me.getDeptPath());
String deptId = StringUtils.trimToEmpty(me.getDeptId());
if (path.isEmpty() && deptId.isEmpty()) {
return;
}
for (InquiryStaffRole row : snap.rows) {
if (row == null || StringUtils.isBlank(row.getWecomId())) {
continue;
}
String rowPath = StringUtils.trimToEmpty(row.getDeptPath());
String rowDept = StringUtils.trimToEmpty(row.getDeptId());
boolean hit = false;
if (!path.isEmpty() && rowPath.startsWith(path)) {
hit = true;
} else if (!deptId.isEmpty() && deptId.equals(rowDept)) {
hit = true;
}
if (hit) {
out.add(row.getWecomId().trim());
}
}
}
private Snapshot snapshot() {
Snapshot current = snapshot;
if (current != null && System.currentTimeMillis() - current.loadedAtMs < CACHE_TTL_MS) {
return current;
}
synchronized (this) {
current = snapshot;
if (current != null && System.currentTimeMillis() - current.loadedAtMs < CACHE_TTL_MS) {
return current;
}
List<InquiryStaffRole> rows = staffRoleMapper.selectList(
new LambdaQueryWrapper<InquiryStaffRole>()
.eq(InquiryStaffRole::getStatus, "active"));
Snapshot loaded = new Snapshot();
loaded.loadedAtMs = System.currentTimeMillis();
loaded.rows = rows == null ? new ArrayList<>() : rows;
for (InquiryStaffRole row : loaded.rows) {
if (row == null || StringUtils.isBlank(row.getWecomId())) {
continue;
}
String wecom = row.getWecomId().trim();
loaded.byWecom.put(wecom, row);
String leader = StringUtils.trimToEmpty(row.getLeaderWecomId());
if (!leader.isEmpty()) {
loaded.reports.computeIfAbsent(leader, k -> new ArrayList<>()).add(wecom);
}
for (String bizLeader : row.businessLeaderIds()) {
if (!bizLeader.isEmpty() && !bizLeader.equals(wecom)) {
loaded.businessReports.computeIfAbsent(bizLeader, k -> new ArrayList<>()).add(wecom);
}
}
}
snapshot = loaded;
return loaded;
}
}
/** 一次请求/一次解析用的范围快照。 */
public static final class Scope {
private final String mode;
private final String selfWecom;
private Set<String> visibleWecomIds = new LinkedHashSet<>();
Scope(String mode, String selfWecom) {
this.mode = mode;
this.selfWecom = selfWecom;
}
public String getMode() {
return mode;
}
public String getSelfWecom() {
return selfWecom;
}
public Set<String> getVisibleWecomIds() {
return visibleWecomIds;
}
void setVisibleWecomIds(Set<String> visibleWecomIds) {
this.visibleWecomIds = visibleWecomIds;
}
/** 是否启用员工组织范围(正常员工恒为 true;仅旧值兜底)。 */
public boolean isOrgMode() {
return !"inherit".equals(mode);
}
public boolean isAll() {
return "all".equals(mode);
}
}
private static final class Snapshot {
long loadedAtMs;
List<InquiryStaffRole> rows = new ArrayList<>();
final Map<String, InquiryStaffRole> byWecom = new HashMap<>();
final Map<String, List<String>> reports = new HashMap<>();
/** 业务/虚线汇报:key=业务汇报对象,value=向其汇报的员工。 */
final Map<String, List<String>> businessReports = new HashMap<>();
}
}
@@ -11,6 +11,7 @@ import org.jeecg.modules.inquiry.entity.InquiryQuote;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
import org.jeecg.modules.inquiry.mapper.InquiryQuoteMapper;
import org.jeecg.modules.inquiry.service.IInquiryWorkOrderService;
import org.jeecg.modules.inquiry.support.InquiryQuotedBySupport;
import org.jeecg.modules.inquiry.support.InquiryTicketPriceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
@@ -269,6 +270,13 @@ public class InquiryTmsQueryService {
log.info("tms.quote skip frozen wo={} status={}", workOrderNo, ticket.getStatus());
return;
}
if (isLandRoutePendingSelection(quote)) {
// 陆运多条备选线路未选:严格按「选定后才存储」处理。
// 本次查价不落报价行、不迁状态;整包只留在智能体会话/H5 选线 token,
// 用户选定后由 replaceTmsQuote 首次写入该条报价。
log.info("tms.quote skip pending land routes wo={}", workOrderNo);
return;
}
boolean airPending = isAirCabinPendingSelection(quote);
InquiryQuote row = new InquiryQuote();
row.setTicketId(ticket.getId());
@@ -299,6 +307,8 @@ public class InquiryTmsQueryService {
TicketTransitionRequest tr = new TicketTransitionRequest();
tr.setWorkOrderNo(workOrderNo);
tr.setToStatus(TicketStatuses.QUOTED);
// 时间线「已报价」带报价人:TMS 标准价就是运价库给的,不能空着。
tr.setRemark(InquiryQuotedBySupport.remark(InquiryQuotedBySupport.TMS_NAME));
workOrderService.transition(tr, "agent");
}
}
@@ -383,6 +393,43 @@ public class InquiryTmsQueryService {
row.setPayloadJson(JSON.toJSONString(sanitized));
}
/**
* 陆运多条备选线路尚未选定:landSegments 按 segmentSequence 分组多于 1 条,
* 且没有 selected_land_route。多条只是候选,不是报价。
* 此时禁止迁已报价,也禁止后台展示各条线路成本。
*/
static boolean isLandRoutePendingSelection(Map<String, String> quote) {
if (quote == null || quote.isEmpty()) {
return false;
}
if (StringUtils.isNotBlank(firstText(
quote.get("selected_land_route"), quote.get("selectedLandRoute")))) {
return false;
}
if ("1".equals(StringUtils.trimToEmpty(quote.get("pending_land_route_pick")))) {
return true;
}
return countLandRoutes(quote) > 1;
}
/**
* landSegments 里不同 segmentSequence 的条数。
* 缺段号按一条算,避免「一条线路两段中转」被当成两条。
*/
static int countLandRoutes(Map<String, String> quote) {
if (quote == null) {
return 0;
}
List<Map<String, String>> rows = normalizeLandSegmentRows(quote.get("landSegments"));
if (rows.isEmpty()) {
rows = normalizeLandSegmentRows(quote.get("land_segments"));
}
Set<String> seqs = new HashSet<>();
for (Map<String, String> row : rows) {
seqs.add(firstText(row.get("segmentSequence"), "1"));
}
return seqs.size();
}
/**
* 把 TMS 规范化回包投影成智能体 quote。单测可直接调。
@@ -432,6 +479,27 @@ public class InquiryTmsQueryService {
if (StringUtils.isNotBlank(headerCurrency)) {
quote.put("currency", headerCurrency);
}
// TMS 汇率表原样透传给智能体:调价改外币明细时按它折算小计/合计。
// 禁止在这里换算金额,也禁止拿 rate 冒充税率(陆运 rate 是税率)。
Object fxRates = data.get("fxRates");
if (fxRates == null) {
fxRates = data.get("fx_rates");
}
if (fxRates == null && data.get("quote") instanceof Map) {
Map<?, ?> nestedQuote = (Map<?, ?>) data.get("quote");
fxRates = nestedQuote.get("fxRates");
if (fxRates == null) {
fxRates = nestedQuote.get("fx_rates");
}
}
if (fxRates != null) {
String fxJson = fxRates instanceof String
? String.valueOf(fxRates)
: JSON.toJSONString(fxRates);
if (StringUtils.isNotBlank(fxJson) && !"null".equalsIgnoreCase(fxJson)) {
quote.put("fxRates", fxJson);
}
}
if (StringUtils.isNotBlank(costMoney.amount)) {
quote.put("cost", costMoney.amount);
}
@@ -771,6 +839,13 @@ public class InquiryTmsQueryService {
}
Map<String, String> quote = stringifyQuote(incoming);
applyLandSegmentTotals(quote);
if (isLandRoutePendingSelection(quote)) {
// 多条备选线路不是报价:严格等到用户选定后才允许写入。
out.put("ok", false);
out.put("error", "land_route_pending");
out.put("status", ticket.getStatus());
return out;
}
boolean airPending = isAirCabinPendingSelection(quote)
|| TicketStatuses.INQUIRING.equals(StringUtils.trimToEmpty(toStatus));
InquiryQuote row = quoteMapper.selectOne(new LambdaQueryWrapper<InquiryQuote>()
@@ -813,6 +888,7 @@ public class InquiryTmsQueryService {
TicketTransitionRequest tr = new TicketTransitionRequest();
tr.setWorkOrderNo(workOrderNo);
tr.setToStatus(TicketStatuses.QUOTED);
tr.setRemark(InquiryQuotedBySupport.remark(InquiryQuotedBySupport.TMS_NAME));
workOrderService.transition(tr, "agent");
ticket.setStatus(TicketStatuses.QUOTED);
}
@@ -91,6 +91,7 @@ public class WeComAddressBookClient {
}
String token = getAccessToken();
Map<Integer, String> deptNames = loadDepartmentNames(token);
Map<Integer, String> deptIdPaths = loadDepartmentIdPaths(token);
String url = UriComponentsBuilder
.fromHttpUrl(trimBase(apiBase) + "/cgi-bin/user/list")
.queryParam("access_token", token)
@@ -120,8 +121,18 @@ public class WeComAddressBookClient {
}
String name = StringUtils.defaultIfBlank(u.getString("name"), userid);
String mobile = StringUtils.trimToEmpty(u.getString("mobile"));
String deptName = resolveDepartmentName(u.getJSONArray("department"), deptNames);
byUserid.put(userid, new WeComMember(userid, name, mobile, deptName, status));
JSONArray departmentIds = u.getJSONArray("department");
String deptName = resolveDepartmentName(departmentIds, deptNames);
String deptId = firstDepartmentId(departmentIds);
String deptIdPath = "";
if (!deptId.isEmpty()) {
try {
deptIdPath = StringUtils.defaultString(deptIdPaths.get(Integer.valueOf(deptId)));
} catch (NumberFormatException ignored) {
// 企微部门 ID 非数字时只保留名称,不影响同步
}
}
byUserid.put(userid, new WeComMember(userid, name, mobile, deptName, deptId, deptIdPath, status));
}
return new ArrayList<>(byUserid.values());
}
@@ -225,6 +236,64 @@ public class WeComAddressBookClient {
return String.join("/", names);
}
/** 取企微成员 department 数组的第一个部门 ID;无部门返回空串。 */
private String firstDepartmentId(JSONArray departmentIds) {
if (departmentIds == null || departmentIds.isEmpty()) {
return "";
}
int id = departmentIds.getIntValue(0);
return id > 0 ? String.valueOf(id) : "";
}
/**
* 部门 ID 路径:/1/12/35/。
* <p>
* 与名称 path 分开:名称会变、会重名,ID 路径稳定,适合做「本部门及以下」前缀匹配。
*/
private Map<Integer, String> loadDepartmentIdPaths(String token) {
String url = UriComponentsBuilder
.fromHttpUrl(trimBase(apiBase) + "/cgi-bin/department/list")
.queryParam("access_token", token)
.toUriString();
JSONObject body = getJson(url);
assertOk(body, "department/list");
Map<Integer, String> paths = new HashMap<>();
JSONArray list = body.getJSONArray("department");
if (list == null) {
return paths;
}
Map<Integer, Integer> parentById = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
JSONObject d = list.getJSONObject(i);
if (d == null) {
continue;
}
parentById.put(d.getIntValue("id"), d.getIntValue("parentid"));
}
for (Integer id : parentById.keySet()) {
List<Integer> chain = new ArrayList<>();
Integer cursor = id;
// 防环:最多 32 层
for (int depth = 0; depth < 32 && cursor != null && cursor > 0; depth++) {
chain.add(0, cursor);
Integer parent = parentById.get(cursor);
if (parent == null || parent <= 0 || parent.equals(cursor)) {
break;
}
cursor = parent;
}
StringBuilder sb = new StringBuilder();
for (Integer one : chain) {
sb.append('/').append(one);
}
if (sb.length() > 0) {
sb.append('/');
}
paths.put(id, sb.toString());
}
return paths;
}
private String getAccessToken() {
synchronized (tokenLock) {
long now = System.currentTimeMillis();
@@ -11,13 +11,20 @@ public class WeComMember {
private final String name;
private final String mobile;
private final String departmentName;
/** 主部门 ID(企微 department 数组第一个);用于组织数据范围。 */
private final String departmentId;
/** 主部门 ID 路径,如 /1/12/35/。 */
private final String departmentIdPath;
private final int status;
public WeComMember(String userid, String name, String mobile, String departmentName, int status) {
public WeComMember(String userid, String name, String mobile, String departmentName,
String departmentId, String departmentIdPath, int status) {
this.userid = userid;
this.name = name;
this.mobile = mobile;
this.departmentName = departmentName;
this.departmentId = departmentId;
this.departmentIdPath = departmentIdPath;
this.status = status;
}
@@ -37,6 +44,14 @@ public class WeComMember {
return departmentName;
}
public String getDepartmentId() {
return departmentId;
}
public String getDepartmentIdPath() {
return departmentIdPath;
}
public int getStatus() {
return status;
}
@@ -0,0 +1,23 @@
-- 机器人显示名拆成两类(2026-12-01 产品口径):
-- system.bot_display_name 空运群机器人 = 智价通AIQ(空运)
-- system.bot_product_display_name 产品群机器人 = 智价通(原账号)
-- 仅改 inquiry_robot.inq_bot_reply;可重复执行。
SET NAMES utf8mb4;
SET collation_connection = 'utf8mb4_general_ci';
UPDATE `inq_bot_reply`
SET `reply_text` = '智价通AIQ(空运)',
`update_by` = 'system',
`update_time` = NOW()
WHERE `reply_code` = 'system.bot_display_name';
SET @new_id := CONCAT('brv', LEFT(REPLACE(UUID(), '-', ''), 29));
INSERT INTO `inq_bot_reply`
(`id`,`category_code`,`category_title`,`reply_code`,`trigger_scene`,`reply_text`,`enabled`,`sort_no`,`create_by`,`create_time`)
SELECT @new_id,'system','系统配置','system.bot_product_display_name','产品群机器人显示名(@ 名)','智价通',1,35,'admin',NOW()
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `inq_bot_reply` WHERE `reply_code` = 'system.bot_product_display_name');
SELECT `reply_code`,`reply_text`,`enabled`
FROM `inq_bot_reply`
WHERE `reply_code` IN ('system.bot_display_name','system.bot_product_display_name');
@@ -0,0 +1,35 @@
-- 智价通迁到新手机号(18927433298)的成员账号(2026-11-29 产品口径)。
-- 只改 inquiry_robot.inq_bot_reply;可重复执行。
-- 变化点:
-- 1) 后台显示名 system.bot_display_name 改为「智价通」;
-- 2) 话术里硬编码的旧 @ 名「智价通AIQ / 智报通AIQ / 询价小助手」统一换成「智价通」。
-- 智能体侧已改为只认新名,旧名不再识别;历史会话里已存的旧 @ 不在这里回改。
-- 3) 智能体还会从员工管理读取「智价通」成员账号,建群时与存档席一起拉入群。
SET NAMES utf8mb4;
SET collation_connection = 'utf8mb4_general_ci';
UPDATE `inq_bot_reply`
SET `reply_text` = '智价通',
`update_by` = 'system',
`update_time` = NOW()
WHERE `reply_code` = 'system.bot_display_name';
UPDATE `inq_bot_reply`
SET `reply_text` = REPLACE(
REPLACE(
REPLACE(`reply_text`, '智价通AIQ', '智价通'),
'智报通AIQ', '智价通'),
'询价小助手', '智价通'),
`update_by` = 'system',
`update_time` = NOW()
WHERE `reply_text` LIKE '%智价通AIQ%'
OR `reply_text` LIKE '%智报通AIQ%'
OR `reply_text` LIKE '%询价小助手%';
-- 自检:显示名应恰好是「智价通」,且不应再残留旧 @ 名。
SELECT `reply_code`, `reply_text`
FROM `inq_bot_reply`
WHERE `reply_code` = 'system.bot_display_name'
OR `reply_text` LIKE '%智价通AIQ%'
OR `reply_text` LIKE '%智报通AIQ%'
OR `reply_text` LIKE '%询价小助手%';
@@ -0,0 +1,25 @@
-- 员工业务/虚线汇报对象:独立于行政直属上级
-- 库:inquiry_robot;可重复执行。
--
-- 背景:Y 部门的 D 在业务上向 X 部门的 A 汇报,但 A 不是 D 的行政上级,
-- 也不在 D 的行政上级链上。现有 leader_wecom_id 只能表达行政直属上级,
-- 因此新增多值的业务汇报对象,数据范围解析时单独并入。
-- 空/NULL=没有业务汇报对象;多个 userid 用英文逗号分隔。
SET NAMES utf8mb4;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'business_leader_wecom_ids'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN business_leader_wecom_ids VARCHAR(1000) NULL COMMENT ''业务/虚线汇报对象,多个企微userid逗号分隔'' AFTER leader_wecom_id',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SELECT id, name, wecom_id, role_codes, leader_wecom_id, business_leader_wecom_ids, data_scope
FROM inq_staff_role
ORDER BY create_time DESC
LIMIT 20;
@@ -0,0 +1,22 @@
-- 数据范围:删除“沿用现状”,默认改为“本人及下级”
-- 库:inquiry_robot;可重复执行。
--
-- 背景:产品确认不再提供 inherit(沿用现状)选项。
-- 现有 inherit 行统一迁移为 self_sub;列默认值同步改为 self_sub。
-- 影响:升级后所有员工按“本人 + 下级”计算,不再走旧的 dashboard_self_only 规则。
SET NAMES utf8mb4;
UPDATE inq_staff_role
SET data_scope = 'self_sub'
WHERE data_scope = 'inherit'
OR data_scope IS NULL
OR data_scope = '';
ALTER TABLE inq_staff_role
MODIFY COLUMN data_scope VARCHAR(20) NOT NULL DEFAULT 'self_sub'
COMMENT 'self/self_sub/dept/all';
SELECT data_scope, COUNT(*) AS n
FROM inq_staff_role
GROUP BY data_scope;
@@ -0,0 +1,176 @@
-- 员工管理:多角色 + 组织关系 + 数据范围
-- 库:inquiry_robot;可重复执行(按 information_schema 判断列/索引是否存在)。
--
-- 背景(2026-11-25 产品需求):
-- 1) 员工可同时是销售 / 航线 / 产品,智能体按任一岗位放行;
-- 2) 数据权限要支持「同部门上级看下级」「跨部门汇报」「角色业务线数据」;
-- 3) 数据范围按员工配置,默认 inherit 完全沿用现状,避免上线当天改变可见性。
--
-- 说明:
-- role_code 仍保留为「主岗位」,用于旧页面/旧逻辑展示;
-- role_codes 存全部岗位(逗号分隔稳定码 sales/air/sea/land)。
-- dept_path 为企微部门 ID 路径(/1/12/35/),用于 MySQL 5.7 无 CTE 情况下的子树判断。
SET NAMES utf8mb4;
-- 1) 多岗位
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'role_codes'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN role_codes VARCHAR(100) NULL COMMENT ''全部岗位,逗号分隔 sales/air/sea/land'' AFTER role_code',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- 2) 组织关系
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'dept_id'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN dept_id VARCHAR(64) NULL COMMENT ''企微部门ID'' AFTER depart_name',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'dept_path'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN dept_path VARCHAR(500) NULL COMMENT ''企微部门ID路径 /1/12/35/'' AFTER dept_id',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'leader_wecom_id'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN leader_wecom_id VARCHAR(64) NULL COMMENT ''直属上级企微userid,跨部门汇报也写这里'' AFTER dept_path',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'business_leader_wecom_ids'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN business_leader_wecom_ids VARCHAR(1000) NULL COMMENT ''业务/虚线汇报对象,多个企微userid逗号分隔'' AFTER leader_wecom_id',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- 3) 数据范围
-- self=仅本人;self_sub=本人及下级(默认);dept=本部门及以下;all=全部(仍受角色业务线限制)
-- 历史 inherit 由 migration_inq_staff_data_scope_default_v2.sql 迁移为 self_sub。
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'data_scope'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN data_scope VARCHAR(20) NOT NULL DEFAULT ''self_sub'' COMMENT ''self/self_sub/dept/all'' AFTER leader_wecom_id',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- 4) 按岗位分开的负责线路
-- 为什么:一个人同时是空运+海运时,routes 并集里的空运三字码(如 CGO-KUL)
-- 会被海运按起运/目的港做子串匹配误命中,拉错人。
-- NULL=旧数据,按 role_code 回退 routes;空串=该岗位明确没有线路。
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'air_routes'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN air_routes VARCHAR(1000) NULL COMMENT ''航线·空运负责线路'' AFTER routes',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'sea_routes'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN sea_routes VARCHAR(1000) NULL COMMENT ''产品·海运负责线路'' AFTER air_routes',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND column_name = 'land_routes'
);
SET @sql := IF(@has_col = 0,
'ALTER TABLE inq_staff_role ADD COLUMN land_routes VARCHAR(1000) NULL COMMENT ''产品·陆运负责线路'' AFTER sea_routes',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- 5) 回填多岗位,保证旧数据也能被新逻辑识别
UPDATE inq_staff_role
SET role_codes = role_code
WHERE (role_codes IS NULL OR role_codes = '')
AND role_code IS NOT NULL
AND role_code <> '';
-- 6) 单岗位旧数据的线路落到对应岗位列;多岗位新数据由前端按岗位拆分写入
UPDATE inq_staff_role
SET air_routes = routes
WHERE role_code = 'air'
AND air_routes IS NULL
AND (role_codes IS NULL OR role_codes = '' OR role_codes = role_code);
UPDATE inq_staff_role
SET sea_routes = routes
WHERE role_code = 'sea'
AND sea_routes IS NULL
AND (role_codes IS NULL OR role_codes = '' OR role_codes = role_code);
UPDATE inq_staff_role
SET land_routes = routes
WHERE role_code = 'land'
AND land_routes IS NULL
AND (role_codes IS NULL OR role_codes = '' OR role_codes = role_code);
-- 7) 索引(存在则跳过)
SET @has_idx := (
SELECT COUNT(*) FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND index_name = 'idx_isr_leader'
);
SET @sql := IF(@has_idx = 0,
'ALTER TABLE inq_staff_role ADD INDEX idx_isr_leader (leader_wecom_id)',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @has_idx := (
SELECT COUNT(*) FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = 'inq_staff_role'
AND index_name = 'idx_isr_dept'
);
SET @sql := IF(@has_idx = 0,
'ALTER TABLE inq_staff_role ADD INDEX idx_isr_dept (dept_id)',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SELECT id, name, wecom_id, role_code, role_codes, routes,
air_routes, sea_routes, land_routes,
dept_id, dept_path, leader_wecom_id, business_leader_wecom_ids, data_scope
FROM inq_staff_role
ORDER BY create_time DESC
LIMIT 20;
@@ -0,0 +1,211 @@
-- 修陆运类型同义词的 standard_value(显示值)。
--
-- 背景:
-- migration_inq_synonym_v1.sql 的首批种子把「运输类型」行的内部值写进了
-- standard_value(如 中亚整车 → standard_value='跨境整车'),后来 069b08d 才拆出
-- standard=产品标签(中港/中亚/中欧整车)、internal=跨境整车。
-- 但 v1 是 INSERT IGNORE,唯一键 (transport_mode, field_key, synonym_norm) 相同的
-- 旧行不会被新种子覆盖,线上仍读到 standard_value='跨境整车'。
-- 结果:中亚整车/中亚车/中亚运输/中欧整车/中欧车/中欧运输 的「陆运业务类型」
-- 认不回按钮,被“运输类型唯一命中”兜底成「东南亚整车」。
-- 中亚/中欧拼车(跨境集拼 + 中港/中亚/中欧)同样会错落成「东南亚拼车」。
--
-- 执行:mysql -h127.0.0.1 -u<user> -p -D inquiry_robot < migration_inq_synonym_land_type_fix_v1.sql
-- 只改 inquiry_robot.inq_synonym;不删行、不改 enabled/priority(IT 的启停保留)。
-- 幂等:先按 information_schema 补缺列(老库没有 internal_value/tms_value/tms_code),
-- 再按 group_code + field_key + synonym_norm 精确 UPDATE,重复执行结果一致。
-- 生效:智能体同义词缓存 60 秒内自动刷新,不用重启。
-- 手工改过的显示值会被本脚本覆盖回产品标签;如仍要特殊显示,执行后单独改。
SET NAMES utf8mb4;
-- ---------------------------------------------------------------------------
-- 0) 老库补列(新库已存在则跳过)
-- ---------------------------------------------------------------------------
SET @col := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'inq_synonym' AND COLUMN_NAME = 'internal_value'
);
SET @ddl := IF(@col = 0,
'ALTER TABLE `inq_synonym` ADD COLUMN `internal_value` varchar(128) NOT NULL DEFAULT '''' COMMENT ''系统内部合同值(流程/TMS判断)'' AFTER `standard_value`',
'DO 0');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @col := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'inq_synonym' AND COLUMN_NAME = 'tms_value'
);
SET @ddl := IF(@col = 0,
'ALTER TABLE `inq_synonym` ADD COLUMN `tms_value` varchar(128) NOT NULL DEFAULT '''' COMMENT ''TMS实际出站值,保持原语言'' AFTER `internal_value`',
'DO 0');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @col := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'inq_synonym' AND COLUMN_NAME = 'tms_code'
);
SET @ddl := IF(@col = 0,
'ALTER TABLE `inq_synonym` ADD COLUMN `tms_code` varchar(64) NULL COMMENT ''TMS代码/三字码/模板表头'' AFTER `tms_value`',
'DO 0');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------------------------------------------------------------------------
-- 1) G14 东南亚整车:standard=东南亚整车,internal/TMS=跨境整车;线路=东南亚
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '东南亚整车',
`internal_value` = '跨境整车',
`tms_value` = '跨境整车'
WHERE `group_code` = 'G14' AND `field_key` = '运输类型'
AND `synonym_norm` IN (
'东南亚整车', '跨境整车', '跨境车', '跨境专线整车', '跨境包车',
'中越整车', '中缅整车', '中老整车'
);
UPDATE `inq_synonym`
SET `standard_value` = '东南亚整车',
`internal_value` = '东南亚',
`tms_value` = '东南亚'
WHERE `group_code` = 'G14' AND `field_key` = '线路类别'
AND `synonym_norm` IN ('东南亚整车', '中越整车', '中缅整车', '中老整车');
-- ---------------------------------------------------------------------------
-- 2) G15 中港/中亚/中欧拼车:standard 统一产品标签;中港走中港零担/集拼,
-- 中亚/中欧仍走跨境集拼(TMS 与线路靠 routeCategory 区分)
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '中港/中亚/中欧拼车',
`internal_value` = '中港零担/集拼',
`tms_value` = '中港零担/集拼'
WHERE `group_code` = 'G15' AND `field_key` = '运输类型'
AND `synonym_norm` IN ('中港零担', '中港集拼', '中港拼车', '中港零担/集拼');
UPDATE `inq_synonym`
SET `standard_value` = '中港/中亚/中欧拼车',
`internal_value` = '跨境集拼',
`tms_value` = '跨境集拼'
WHERE `group_code` = 'G15' AND `field_key` = '运输类型'
AND `synonym_norm` IN (
'中亚零担', '中亚集拼', '中亚拼车', '中亚零担/集拼',
'中欧零担', '中欧集拼', '中欧拼车', '中欧零担/集拼'
);
UPDATE `inq_synonym`
SET `standard_value` = '中港/中亚/中欧拼车',
`internal_value` = '中港/中亚/中欧',
`tms_value` = '中港/中亚/中欧'
WHERE `group_code` = 'G15' AND `field_key` = '线路类别'
AND `synonym_norm` IN (
'中港零担', '中港集拼', '中港拼车', '中港零担/集拼',
'中亚零担', '中亚集拼', '中亚拼车', '中亚零担/集拼',
'中欧零担', '中欧集拼', '中欧拼车', '中欧零担/集拼'
);
-- ---------------------------------------------------------------------------
-- 3) G16 国内整车:standard=国内整车,internal/TMS=国内运输整车
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '国内整车',
`internal_value` = '国内运输整车',
`tms_value` = '国内运输整车'
WHERE `group_code` = 'G16' AND `field_key` = '运输类型'
AND `synonym_norm` IN ('国内运输整车', '国内整车', '国内包车', '国内专车');
-- ---------------------------------------------------------------------------
-- 4) G17 东南亚拼车:standard=东南亚拼车,internal/TMS=跨境集拼;线路=东南亚
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '东南亚拼车',
`internal_value` = '跨境集拼',
`tms_value` = '跨境集拼'
WHERE `group_code` = 'G17' AND `field_key` = '运输类型'
AND `synonym_norm` IN (
'东南亚拼车', '跨境集拼', '跨境拼车', '跨境零担', '跨境拼箱',
'中越拼车', '中越零担', '中越集拼',
'中缅拼车', '中缅零担', '中缅集拼',
'中老拼车', '中老零担', '中老集拼'
);
UPDATE `inq_synonym`
SET `standard_value` = '东南亚拼车',
`internal_value` = '东南亚',
`tms_value` = '东南亚'
WHERE `group_code` = 'G17' AND `field_key` = '线路类别'
AND `synonym_norm` IN (
'东南亚拼车',
'中越拼车', '中越零担', '中越集拼',
'中缅拼车', '中缅零担', '中缅集拼',
'中老拼车', '中老零担', '中老集拼'
);
-- ---------------------------------------------------------------------------
-- 5) G18 中港/中亚/中欧整车:standard 统一产品标签;中港走中港整车,
-- 中亚/中欧走跨境整车(本次报障的六个词)
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '中港/中亚/中欧整车',
`internal_value` = '中港整车',
`tms_value` = '中港整车'
WHERE `group_code` = 'G18' AND `field_key` = '运输类型'
AND `synonym_norm` IN ('中港整车', '中港车', '中港运输', '香港整车');
UPDATE `inq_synonym`
SET `standard_value` = '中港/中亚/中欧整车',
`internal_value` = '跨境整车',
`tms_value` = '跨境整车'
WHERE `group_code` = 'G18' AND `field_key` = '运输类型'
AND `synonym_norm` IN ('中亚整车', '中亚车', '中亚运输', '中欧整车', '中欧车', '中欧运输');
UPDATE `inq_synonym`
SET `standard_value` = '中港/中亚/中欧整车',
`internal_value` = '中港/中亚/中欧',
`tms_value` = '中港/中亚/中欧'
WHERE `group_code` = 'G18' AND `field_key` = '线路类别'
AND `synonym_norm` IN (
'中港整车', '中港车', '中港运输', '香港整车',
'中亚整车', '中亚车', '中亚运输', '中欧整车', '中欧车', '中欧运输'
);
-- ---------------------------------------------------------------------------
-- 6) G19 国内拼车:standard=国内拼车,internal/TMS=国内运输拼车
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '国内拼车',
`internal_value` = '国内运输拼车',
`tms_value` = '国内运输拼车'
WHERE `group_code` = 'G19' AND `field_key` = '运输类型'
AND `synonym_norm` IN ('国内运输拼车', '国内拼车', '国内零担', '国内配载', '国内拼货', '干线');
-- ---------------------------------------------------------------------------
-- 7) G20 国内城配/打包:standard=国内城配/打包;运输类型=国内运输拼车,
-- 线路=国内城配/拖车/打包
-- ---------------------------------------------------------------------------
UPDATE `inq_synonym`
SET `standard_value` = '国内城配/打包',
`internal_value` = '国内运输拼车',
`tms_value` = '国内运输拼车'
WHERE `group_code` = 'G20' AND `field_key` = '运输类型'
AND `synonym_norm` IN ('国内城配', '国内打包', '国内拖车');
UPDATE `inq_synonym`
SET `standard_value` = '国内城配/打包',
`internal_value` = '国内城配/拖车/打包',
`tms_value` = '国内城配/拖车/打包'
WHERE `group_code` = 'G20' AND `field_key` = '线路类别'
AND `synonym_norm` IN ('国内城配', '国内打包', '国内拖车');
-- ---------------------------------------------------------------------------
-- 8) 自检:应无「陆运类型的 standard_value 还是内部值」的残留
-- SELECT group_code, field_key, synonym_norm, standard_value, internal_value
-- FROM `inq_synonym`
-- WHERE group_code BETWEEN 'G14' AND 'G20' AND field_key IN ('运输类型','线路类别')
-- AND standard_value IN ('跨境整车','跨境集拼','中港整车','中港零担/集拼','国内运输整车',
-- '国内运输拼车','国内长途/零担','国内城配/拖车/打包','东南亚')
-- ORDER BY group_code, field_key, id;
-- ---------------------------------------------------------------------------
@@ -0,0 +1,18 @@
-- 补陆运通配符同义词:中*零担 / 中*集拼。
-- 背景:资料/同义词.xlsx 的「东南亚拼车」一行写了 中*拼车、中*零担、中*集拼,
-- 但 v1 种子只落了 中*拼车。销售写「陆运北京到北宁中*集拼6米8高栏」时
-- 运输类型/线路类别都认不到,补问卡会再问一遍业务类型。
-- 用法:已部署过 migration_inq_synonym_v1.sql 的库(测试/正服)单独执行本文件;
-- 全新建库直接跑 v1 即可(v1 已包含这 6 行)。
-- 幂等:INSERT IGNORE + uk_inq_synonym(transport_mode, field_key, synonym_norm),
-- 重复执行不会覆盖 IT 在后台改过的启用/停用。
SET NAMES utf8mb4;
INSERT IGNORE INTO `inq_synonym`
(`id`,`group_code`,`group_label`,`synonym_type`,`field_key`,`transport_mode`,`standard_value`,`internal_value`,`tms_value`,`tms_code`,`synonym`,`synonym_norm`,`match_type`,`requires_number`,`negative_words`,`unit_factor`,`unit_dimension`,`priority`,`enabled`,`rule_note`) VALUES
('synf7bb196eb9bb7','G17','陆运类型-东南亚拼车','VALUE','线路类别','LAND','东南亚拼车','东南亚','东南亚',NULL,'中*集拼','中*集拼','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn4b24ecd8ec232','G17','陆运类型-东南亚拼车','VALUE','线路类别','LAND','东南亚拼车','东南亚','东南亚',NULL,'中*零担','中*零担','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn53f1968969a90','G17','陆运类型-东南亚拼车','RULE','运输类型','ALL','','','',NULL,'中*集拼','中*集拼','RULE',0,NULL,NULL,NULL,104,0,'通配符并排除中港/中亚/中欧,需代码规则'),
('syn2665b2e629684','G17','陆运类型-东南亚拼车','VALUE','运输类型','LAND','东南亚拼车','跨境集拼','跨境集拼',NULL,'中*集拼','中*集拼','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn6e86b27e3321c','G17','陆运类型-东南亚拼车','RULE','运输类型','ALL','','','',NULL,'中*零担','中*零担','RULE',0,NULL,NULL,NULL,104,0,'通配符并排除中港/中亚/中欧,需代码规则'),
('syn478eba4837d2a','G17','陆运类型-东南亚拼车','VALUE','运输类型','LAND','东南亚拼车','跨境集拼','跨境集拼',NULL,'中*零担','中*零担','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车');
@@ -161,6 +161,8 @@ INSERT IGNORE INTO `inq_synonym`
('synf7baf471ffb44','G16','陆运类型-国内整车','VALUE','运输类型','ALL','国内整车','国内运输整车','国内运输整车',NULL,'国内包车','国内包车','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('synf5ed3c8153d56','G16','陆运类型-国内整车','VALUE','运输类型','ALL','国内整车','国内运输整车','国内运输整车',NULL,'国内整车','国内整车','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('syn7907fb7660701','G17','陆运类型-东南亚拼车','VALUE','线路类别','ALL','东南亚拼车','东南亚','东南亚',NULL,'东南亚拼车','东南亚拼车','EXACT',0,NULL,NULL,NULL,105,1,'销售已写明东南亚'),
('synf7bb196eb9bb7','G17','陆运类型-东南亚拼车','VALUE','线路类别','LAND','东南亚拼车','东南亚','东南亚',NULL,'中*集拼','中*集拼','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn4b24ecd8ec232','G17','陆运类型-东南亚拼车','VALUE','线路类别','LAND','东南亚拼车','东南亚','东南亚',NULL,'中*零担','中*零担','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn5e0415d76788a','G17','陆运类型-东南亚拼车','VALUE','线路类别','ALL','东南亚拼车','东南亚','东南亚',NULL,'中缅拼车','中缅拼车','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('synfd8b5c9cea78d','G17','陆运类型-东南亚拼车','VALUE','线路类别','ALL','东南亚拼车','东南亚','东南亚',NULL,'中缅集拼','中缅集拼','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('syn479f26c4ed60d','G17','陆运类型-东南亚拼车','VALUE','线路类别','ALL','东南亚拼车','东南亚','东南亚',NULL,'中缅零担','中缅零担','EXACT',0,NULL,NULL,NULL,104,1,NULL),
@@ -172,6 +174,10 @@ INSERT IGNORE INTO `inq_synonym`
('syncc9e9f33331d0','G17','陆运类型-东南亚拼车','VALUE','线路类别','ALL','东南亚拼车','东南亚','东南亚',NULL,'中越零担','中越零担','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('syn1d98a239f52f4','G17','陆运类型-东南亚拼车','VALUE','运输类型','ALL','东南亚拼车','跨境集拼','跨境集拼',NULL,'东南亚拼车','东南亚拼车','EXACT',0,NULL,NULL,NULL,105,1,NULL),
('syncf100e710edd2','G17','陆运类型-东南亚拼车','RULE','运输类型','ALL','','','',NULL,'中*拼车','中*拼车','RULE',0,NULL,NULL,NULL,104,0,'通配符并排除中港/中亚/中欧,需代码规则'),
('syn53f1968969a90','G17','陆运类型-东南亚拼车','RULE','运输类型','ALL','','','',NULL,'中*集拼','中*集拼','RULE',0,NULL,NULL,NULL,104,0,'通配符并排除中港/中亚/中欧,需代码规则'),
('syn2665b2e629684','G17','陆运类型-东南亚拼车','VALUE','运输类型','LAND','东南亚拼车','跨境集拼','跨境集拼',NULL,'中*集拼','中*集拼','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn6e86b27e3321c','G17','陆运类型-东南亚拼车','RULE','运输类型','ALL','','','',NULL,'中*零担','中*零担','RULE',0,NULL,NULL,NULL,104,0,'通配符并排除中港/中亚/中欧,需代码规则'),
('syn478eba4837d2a','G17','陆运类型-东南亚拼车','VALUE','运输类型','LAND','东南亚拼车','跨境集拼','跨境集拼',NULL,'中*零担','中*零担','EXACT',0,NULL,NULL,NULL,104,1,'通配符原文按东南亚拼车'),
('syn48c1d991afbcb','G17','陆运类型-东南亚拼车','VALUE','运输类型','ALL','东南亚拼车','跨境集拼','跨境集拼',NULL,'中缅拼车','中缅拼车','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('syn2230cfa33aed4','G17','陆运类型-东南亚拼车','VALUE','运输类型','ALL','东南亚拼车','跨境集拼','跨境集拼',NULL,'中缅集拼','中缅集拼','EXACT',0,NULL,NULL,NULL,104,1,NULL),
('synbc62a35aea835','G17','陆运类型-东南亚拼车','VALUE','运输类型','ALL','东南亚拼车','跨境集拼','跨境集拼',NULL,'中缅零担','中缅零担','EXACT',0,NULL,NULL,NULL,104,1,NULL),
@@ -0,0 +1,27 @@
-- sys_role.description 扩容:角色数据权限 [dataPerms:…] 保存勾选线路
-- 库:inquiry_robot(正服 / 测服各自执行);可重复执行。
--
-- 背景(2026-11-29):空运新增 8 条线路后,角色「数据权限」全选时
-- description 最长 = 280 字符([dataPerms:空运全线|…|东南亚]),
-- 原 varchar(255) 在 MySQL 严格模式下保存会报 Data too long,或非严格模式被截断,
-- 截断后 [dataPerms:…] 不闭合,角色业务线/线路解析会失效。
-- 这里只放宽长度,不改默认值、不改排序规则、不动已有数据。
SET NAMES utf8mb4;
SET @len := (
SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'sys_role'
AND column_name = 'description'
);
SET @sql := IF(@len IS NOT NULL AND @len < 512,
'ALTER TABLE sys_role MODIFY COLUMN description VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT ''说明''',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SELECT CHARACTER_MAXIMUM_LENGTH AS description_len
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'sys_role'
AND column_name = 'description';
@@ -0,0 +1,20 @@
-- 业务询价原始内容:销售 1v1 首条询价原话。
-- 群摘要「工单号」下方展示,后台询价工单详情同步展示;只做留档,不参与 TMS/模板。
-- 可重复执行:已有列则跳过。
SET NAMES utf8mb4;
SET @db := DATABASE();
SET @exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'inq_ticket' AND COLUMN_NAME = 'inquiry_raw_text'
);
SET @sql := IF(
@exists = 0,
'ALTER TABLE `inq_ticket` ADD COLUMN `inquiry_raw_text` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT ''业务询价原始内容(销售首条询价原话)'' AFTER `facts_json`',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,33 @@
-- 账号管理“只看自己数据”迁移到员工数据范围
-- 库:inquiry_robot;可重复执行。
--
-- 背景(2026-11-26):账号管理不再维护 dashboard_self_only,数据范围统一由
-- 员工管理的 inq_staff_role.data_scope 决定。
-- 迁移规则:原账号勾了“只看自己数据”,且能通过 work_no = wecom_id 对上员工,
-- 就把该员工的数据范围改为 self(仅本人),保持原有可见性。
-- 未对上员工/未勾选的账号不处理;dashboard_self_only 列保留但不删,供历史兼容。
SET NAMES utf8mb4;
SET @has_col := (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'sys_user'
AND column_name = 'dashboard_self_only'
);
SET @sql := IF(@has_col = 1,
'UPDATE inq_staff_role s JOIN sys_user u ON u.work_no = s.wecom_id SET s.data_scope = ''self'' WHERE u.dashboard_self_only = 1 AND u.work_no IS NOT NULL AND u.work_no <> ''''',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SELECT 'migrated' AS k, COUNT(*) AS n
FROM inq_staff_role s
JOIN sys_user u ON u.work_no = s.wecom_id
WHERE u.dashboard_self_only = 1;
SELECT s.wecom_id, s.name, s.data_scope, u.username, u.dashboard_self_only
FROM inq_staff_role s
JOIN sys_user u ON u.work_no = s.wecom_id
WHERE u.dashboard_self_only = 1
ORDER BY s.name
LIMIT 20;
@@ -0,0 +1,96 @@
package org.jeecg.modules.inquiry.entity;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 员工多岗位:roleCodes 是完整授权,roleCode 只做旧数据兜底。
*/
public class InquiryStaffRoleTest {
@Test
public void roleCodesAreAuthoritativeAndDeduped() {
InquiryStaffRole row = new InquiryStaffRole().setRoleCodes("sales, air,sales");
assertEquals(Arrays.asList("sales", "air"), row.effectiveRoleCodes());
assertTrue(row.hasRole("sales"));
assertTrue(row.hasRole("air"));
assertFalse(row.hasRole("sea"));
assertTrue(row.hasProductRole());
}
@Test
public void oldRowFallsBackToRoleCode() {
InquiryStaffRole row = new InquiryStaffRole().setRoleCode("sea");
assertEquals(Arrays.asList("sea"), row.effectiveRoleCodes());
assertTrue(row.hasProductRole());
}
@Test
public void stalePrimaryRoleDoesNotReAddRemovedRole() {
InquiryStaffRole row = new InquiryStaffRole().setRoleCode("sales").setRoleCodes("air");
assertEquals(Arrays.asList("air"), row.effectiveRoleCodes());
assertFalse(row.hasRole("sales"));
}
@Test
public void unknownCodesAreIgnored() {
InquiryStaffRole row = new InquiryStaffRole().setRoleCodes("sales,ceo,admin");
assertEquals(Arrays.asList("sales"), row.effectiveRoleCodes());
assertFalse(row.hasProductRole());
assertFalse(row.hasRole("admin"));
}
@Test
public void salesOnlyIsNotProduct() {
InquiryStaffRole row = new InquiryStaffRole().setRoleCodes("sales");
assertTrue(row.hasRole("sales"));
assertFalse(row.hasProductRole());
}
@Test
public void routesAreSplitPerRole() {
InquiryStaffRole row = new InquiryStaffRole()
.setRoleCodes("air,sea")
.setRoutes("CGO-KUL,海运全线")
.setAirRoutes("CGO-KUL")
.setSeaRoutes("海运全线");
assertEquals("CGO-KUL", row.routesForRole("air"));
assertEquals("海运全线", row.routesForRole("sea"));
assertEquals("", row.routesForRole("land"));
}
@Test
public void legacyNullRoleRoutesFallBackToUnionOnlyForThatRole() {
InquiryStaffRole air = new InquiryStaffRole().setRoleCodes("air").setRoutes("CGO-KUL");
assertEquals("CGO-KUL", air.routesForRole("air"));
// 没有 sea 岗位时不能把并集当成 sea 线路
assertEquals("", air.routesForRole("sea"));
}
@Test
public void explicitEmptyRoleRoutesDoNotFallBack() {
InquiryStaffRole row = new InquiryStaffRole()
.setRoleCodes("air,sea")
.setRoutes("CGO-KUL,海运全线")
.setAirRoutes("CGO-KUL")
.setSeaRoutes("");
assertEquals("", row.routesForRole("sea"));
}
@Test
public void businessLeaderIdsParseDedupeAndTrim() {
InquiryStaffRole row = new InquiryStaffRole()
.setBusinessLeaderWecomIds(" A, B,A ,, C ");
assertEquals(Arrays.asList("A", "B", "C"), row.businessLeaderIds());
}
@Test
public void businessLeaderIdsEmptyWhenNull() {
assertTrue(new InquiryStaffRole().businessLeaderIds().isEmpty());
}
}
@@ -1,10 +1,15 @@
package org.jeecg.modules.inquiry.service.impl;
import org.jeecg.modules.inquiry.entity.InquiryStaffRole;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 看板聚合辅助:金额解析与线路标签(不启 Spring)。
@@ -66,4 +71,81 @@ public class InquiryDashboardServiceImplTest {
Assert.assertFalse(InquiryDashboardServiceImpl.roleNameLooksProductOrRoute("销售"));
Assert.assertFalse(InquiryDashboardServiceImpl.roleNameLooksProductOrRoute(""));
}
@Test
public void rankRoleFollowsTicketBusinessLine() {
InquiryStaffRole airStaff = new InquiryStaffRole().setRoleCodes("air");
InquiryStaffRole productStaff = new InquiryStaffRole().setRoleCodes("sea,land");
Assert.assertEquals("route",
InquiryDashboardServiceImpl.rankRoleForTicket(ticket("AIR", "s1", ""), productStaff));
Assert.assertEquals("product",
InquiryDashboardServiceImpl.rankRoleForTicket(ticket("SEA", "s1", ""), airStaff));
Assert.assertEquals("product",
InquiryDashboardServiceImpl.rankRoleForTicket(ticket("LAND", "s1", ""), airStaff));
// 多段联运没有单一运输方式,回退员工岗位
Assert.assertEquals("route",
InquiryDashboardServiceImpl.rankRoleForTicket(ticket("MULTI", "s1", ""), airStaff));
Assert.assertEquals("product",
InquiryDashboardServiceImpl.rankRoleForTicket(ticket("MULTI", "s1", ""), productStaff));
}
@Test
public void rankingsSplitInitiatorsFromHandlers() {
InquiryStaffRole sales = new InquiryStaffRole()
.setName("销售甲").setWecomId("sales_a").setDepartName("销售部").setRoleCodes("sales");
InquiryStaffRole route = new InquiryStaffRole()
.setName("航线乙").setWecomId("air_b").setDepartName("航线部").setRoleCodes("air");
InquiryStaffRole product = new InquiryStaffRole()
.setName("产品丙").setWecomId("prod_c").setDepartName("产品部").setRoleCodes("sea,land");
Map<String, InquiryStaffRole> staffByWecom = new HashMap<>();
staffByWecom.put("sales_a", sales);
staffByWecom.put("air_b", route);
staffByWecom.put("prod_c", product);
Map<String, InquiryStaffRole> staffByName = new HashMap<>();
staffByName.put("销售甲", sales);
List<InquiryTicket> tickets = Arrays.asList(
ticket("SEA", "sales_a", "[\"prod_c\"]"),
ticket("LAND", "sales_a", "[\"prod_c\"]"),
ticket("AIR", "sales_a", "[\"air_b\"]"));
List<Map<String, Object>> rows = InquiryDashboardServiceImpl.buildRankings(
tickets, staffByWecom, staffByName, false);
// 销售 = 三张单的发起人
Assert.assertEquals(3L, volumeOf(rows, "sales", "销售甲"));
// 产品 = 两张陆海单的处理人
Assert.assertEquals(2L, volumeOf(rows, "product", "产品丙"));
// 航线 = 一张空运单的处理人
Assert.assertEquals(1L, volumeOf(rows, "route", "航线乙"));
// 发起人不会因为兼岗变成处理人
Assert.assertNull(volumeOf(rows, "product", "销售甲"));
Assert.assertNull(volumeOf(rows, "route", "销售甲"));
// 产品/航线账号视角:只返回智能体团队,不回销售
List<Map<String, Object>> teamRows = InquiryDashboardServiceImpl.buildRankings(
tickets, staffByWecom, staffByName, true);
Assert.assertNull(volumeOf(teamRows, "sales", "销售甲"));
Assert.assertEquals(2L, volumeOf(teamRows, "product", "产品丙"));
Assert.assertEquals(1L, volumeOf(teamRows, "route", "航线乙"));
}
private static InquiryTicket ticket(String businessLine, String salesWecomId, String actorIds) {
InquiryTicket t = new InquiryTicket();
t.setBusinessLine(businessLine);
t.setSalesWecomId(salesWecomId);
t.setCollabActorIds(actorIds);
return t;
}
private static Long volumeOf(List<Map<String, Object>> rows, String role, String name) {
for (Map<String, Object> row : rows) {
if (role.equals(row.get("role")) && name.equals(row.get("name"))) {
return ((Number) row.get("volumeNum")).longValue();
}
}
return null;
}
}
@@ -0,0 +1,67 @@
package org.jeecg.modules.inquiry.service.impl;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 工单「处理人」口径:销售兼产品/航线时不能把自己排除成空。
*/
public class InquiryWorkOrderHandlerTest {
/** 销售就是产品/航线本人,自己报价:处理人要显示本人,不能是「—」。 */
@Test
public void salesWhoAlsoHandledShowsSelf() {
InquiryTicket t = ticket("sales_dual", "[\"sales_dual\"]");
Map<String, String> names = new HashMap<>();
names.put("sales_dual", "罗小华");
List<String> handlers = InquiryWorkOrderServiceImpl.resolveHandlers(t, names);
Assert.assertEquals(Collections.singletonList("罗小华"), handlers);
}
/** 发起销售只是销售岗(不在产品/航线名册里):照旧不算处理人。 */
@Test
public void pureSalesInActorsIsIgnored() {
InquiryTicket t = ticket("sales_a", "[\"sales_a\", \"prod_c\"]");
Map<String, String> names = new HashMap<>();
names.put("prod_c", "产品丙");
Assert.assertEquals(Collections.singletonList("产品丙"),
InquiryWorkOrderServiceImpl.resolveHandlers(t, names));
}
/** 销售兼岗但有别的产品/航线处理过:只显示别人,本人不占处理人列。 */
@Test
public void salesDualRoleDoesNotCrowdOutOtherHandlers() {
InquiryTicket t = ticket("sales_dual", "[\"sales_dual\", \"prod_c\"]");
Map<String, String> names = new HashMap<>();
names.put("sales_dual", "罗小华");
names.put("prod_c", "产品丙");
Assert.assertEquals(Collections.singletonList("产品丙"),
InquiryWorkOrderServiceImpl.resolveHandlers(t, names));
}
/** 没有任何产品/航线互动:留空,前端显示「—」。 */
@Test
public void noInteractionLeavesEmpty() {
Assert.assertTrue(InquiryWorkOrderServiceImpl
.resolveHandlers(ticket("sales_a", null), Collections.emptyMap()).isEmpty());
Assert.assertTrue(InquiryWorkOrderServiceImpl
.resolveHandlers(ticket("sales_a", "[\"unknown\"]"), new HashMap<>()).isEmpty());
}
private static InquiryTicket ticket(String salesWecomId, String actorIds) {
InquiryTicket t = new InquiryTicket();
t.setSalesWecomId(salesWecomId);
t.setCollabActorIds(actorIds);
return t;
}
}
@@ -0,0 +1,44 @@
package org.jeecg.modules.inquiry.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
import org.junit.Assert;
import org.junit.Test;
/**
* 数据范围:处理人可见性(空运单只有互动快照、没有成员快照)。
*/
public class InquiryDataScopeSupportTest {
@Test
public void actorOnlyTicketCountsAsParticipant() {
InquiryTicket t = new InquiryTicket();
t.setCollabActorIds("[\"WuJiLin\"]");
Assert.assertTrue(InquiryDataScopeSupport.isCollabParticipant(t, "WuJiLin"));
Assert.assertFalse(InquiryDataScopeSupport.isCollabParticipant(t, "someone_else"));
}
@Test
public void emptySnapshotsAreNotParticipants() {
InquiryTicket t = new InquiryTicket();
Assert.assertFalse(InquiryDataScopeSupport.isCollabParticipant(t, "WuJiLin"));
t.setCollabActorIds("[]");
Assert.assertFalse(InquiryDataScopeSupport.isCollabParticipant(t, "WuJiLin"));
}
@Test
public void memberSnapshotStillCounts() {
InquiryTicket t = new InquiryTicket();
t.setCollabMemberIds("[\"WuJiLin\",\"AI001\"]");
Assert.assertTrue(InquiryDataScopeSupport.isCollabParticipant(t, "WuJiLin"));
}
@Test
public void participantScopeSqlChecksMemberAndActor() {
LambdaQueryWrapper<InquiryTicket> w = new LambdaQueryWrapper<>();
InquiryDataScopeSupport.appendParticipantOr(w, "WuJiLin");
String sql = String.valueOf(w.getSqlSegment()).toLowerCase();
Assert.assertTrue(sql, sql.contains("collab_member_ids"));
Assert.assertTrue(sql, sql.contains("collab_actor_ids"));
}
}
@@ -0,0 +1,70 @@
package org.jeecg.modules.inquiry.support;
import org.jeecg.modules.inquiry.entity.InquiryQuote;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* 「已报价」时间线报价方:文案固定,历史行按最近报价回填,多人时不猜人名。
*/
public class InquiryQuotedBySupportTest {
private static InquiryQuote quote(String source, long offsetMs, Date base) {
InquiryQuote q = new InquiryQuote();
q.setSource(source);
q.setCreateTime(new Date(base.getTime() + offsetMs));
return q;
}
@Test
public void remarkKeepsNameAndFallsBackToProduct() {
assertEquals("报价方:林绵勋", InquiryQuotedBySupport.remark("林绵勋"));
assertEquals("报价方:产品", InquiryQuotedBySupport.remark(" "));
assertEquals("报价方:产品", InquiryQuotedBySupport.remark(null));
}
@Test
public void nearestQuotePicksSameSecondRow() {
Date at = new Date(1_800_000_000_000L);
List<InquiryQuote> rows = new ArrayList<>();
rows.add(quote("TMS", -120_000L, at));
rows.add(quote("PRODUCT", 0L, at));
assertEquals("PRODUCT", InquiryQuotedBySupport.nearestQuote(rows, at).getSource());
}
@Test
public void nearestQuoteIgnoresRowsOutsideWindow() {
Date at = new Date(1_800_000_000_000L);
List<InquiryQuote> rows = new ArrayList<>();
rows.add(quote("PRODUCT", -60_000L, at));
assertNull(InquiryQuotedBySupport.nearestQuote(rows, at));
assertNull(InquiryQuotedBySupport.nearestQuote(null, at));
}
@Test
public void legacyNameSeparatesTmsFromManual() {
Date at = new Date(1_800_000_000_000L);
assertEquals("TMS", InquiryQuotedBySupport.legacyName(quote("TMS", 0L, at), "林绵勋"));
assertEquals("林绵勋", InquiryQuotedBySupport.legacyName(quote("PRODUCT", 0L, at), "林绵勋"));
// 多人互动:只写产品侧,不猜是谁报的。
assertEquals("产品", InquiryQuotedBySupport.legacyName(quote("PRODUCT", 0L, at), ""));
assertEquals("产品", InquiryQuotedBySupport.legacyName(null, ""));
}
@Test
public void windowCoversSlightClockSkew() {
Date at = new Date(1_800_000_000_000L);
List<InquiryQuote> rows = Arrays.asList(
quote("PRODUCT", 1_500L, at),
quote("PRODUCT", -4_000L, at));
// 两条都在窗口内时取更近的那条。
assertEquals(1_500L, InquiryQuotedBySupport.nearestQuote(rows, at).getCreateTime().getTime() - at.getTime());
}
}
@@ -34,12 +34,27 @@ public class InquiryRoleBizScopeTest {
assertEquals(Collections.singleton(InquiryRoleBizScope.LAND), allowed);
}
/**
* 2026-11-25 产品需求:显式勾选的数据权限与角色名取并集。
* 例:A 是海运领导,但运营给他勾了空运数据权限 → 海运 + 空运都可见。
* 陆运线路叶子仍由 resolveLandRoutes 单独收窄,不会因此看到其它陆运线路。
*/
@Test
public void namedLandRoleIgnoresExtraSeaAndAirDataPerms() {
public void namedLandRoleAddsExplicitExtraDataPerms() {
Set<String> allowed = InquiryRoleBizScope.resolve(false, Collections.singletonList(
new InquiryRoleBizScope.RoleSnap("陆运中港", "land_hk",
"[dataPerms:中港/中亚/中欧|海运全线|空运全线]")));
assertEquals(Collections.singleton(InquiryRoleBizScope.LAND), allowed);
assertEquals(new HashSet<String>(Arrays.asList(
InquiryRoleBizScope.LAND, InquiryRoleBizScope.SEA, InquiryRoleBizScope.AIR)), allowed);
}
@Test
public void seaLeaderWithAirDataPermSeesBothLines() {
Set<String> allowed = InquiryRoleBizScope.resolve(false, Collections.singletonList(
new InquiryRoleBizScope.RoleSnap("海运领导", "sea_leader",
"[dataPerms:空运全线]")));
assertEquals(new HashSet<String>(Arrays.asList(
InquiryRoleBizScope.SEA, InquiryRoleBizScope.AIR)), allowed);
}
@Test
@@ -120,7 +135,7 @@ public class InquiryRoleBizScopeTest {
public void landAllDataPermDoesNotRestrictLandRoutes() {
assertNull(InquiryRoleBizScope.resolveLandRoutes(false, Collections.singletonList(
new InquiryRoleBizScope.RoleSnap("陆运全线", "land_all",
"[dataPerms:陆运全线]")));
"[dataPerms:陆运全线]"))));
}
@Test
@@ -0,0 +1,53 @@
package org.jeecg.modules.inquiry.support;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 业务/虚线汇报链:独立于行政上级,递归收集,防环。
*/
public class InquiryStaffScopeServiceTest {
@Test
public void businessChainIsRecursive() {
Map<String, List<String>> reports = new HashMap<>();
reports.put("A", new ArrayList<>(Arrays.asList("D")));
reports.put("D", new ArrayList<>(Arrays.asList("E")));
Set<String> out = new LinkedHashSet<>();
InquiryStaffScopeService.collectBusinessSubordinates(reports, "A", out);
assertEquals(Arrays.asList("D", "E"), new ArrayList<>(out));
}
@Test
public void businessChainHandlesCycles() {
Map<String, List<String>> reports = new HashMap<>();
reports.put("A", new ArrayList<>(Arrays.asList("D")));
reports.put("D", new ArrayList<>(Arrays.asList("A")));
Set<String> out = new LinkedHashSet<>();
InquiryStaffScopeService.collectBusinessSubordinates(reports, "A", out);
assertEquals(Arrays.asList("D"), new ArrayList<>(out));
}
@Test
public void businessChainIsEmptyForUnknownLeaderOrBlankInput() {
Set<String> out = new LinkedHashSet<>();
InquiryStaffScopeService.collectBusinessSubordinates(new HashMap<>(), "A", out);
assertTrue(out.isEmpty());
InquiryStaffScopeService.collectBusinessSubordinates(null, "A", out);
assertTrue(out.isEmpty());
Map<String, List<String>> reports = new HashMap<>();
reports.put("A", new ArrayList<>(Arrays.asList("D")));
InquiryStaffScopeService.collectBusinessSubordinates(reports, "", out);
assertTrue(out.isEmpty());
}
}
@@ -7,6 +7,8 @@ import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 海运查价身份:不打真实 TMS。
@@ -164,6 +166,36 @@ public class InquiryTmsQueryServiceTest {
assertEquals("", InquiryTmsQueryService.tmsMissReasonText(null));
}
@Test
public void landMultiRouteIsPendingUntilSelected() {
// 多条 segmentSequence = 多条备选线路,未选前不能当已报价。
Map<String, String> multi = new HashMap<>();
multi.put("landSegments", "[{\"segmentSequence\":1,\"routeLegSequence\":1,\"costPrice\":3500},"
+ "{\"segmentSequence\":1,\"routeLegSequence\":2,\"costPrice\":3800},"
+ "{\"segmentSequence\":2,\"routeLegSequence\":1,\"costPrice\":3500},"
+ "{\"segmentSequence\":2,\"routeLegSequence\":2,\"costPrice\":3800}]");
assertTrue(InquiryTmsQueryService.isLandRoutePendingSelection(multi));
assertEquals(2, InquiryTmsQueryService.countLandRoutes(multi));
// 一条线路两段中转不是两条线路。
Map<String, String> single = new HashMap<>();
single.put("landSegments", "[{\"segmentSequence\":1,\"routeLegSequence\":1,\"costPrice\":3500},"
+ "{\"segmentSequence\":1,\"routeLegSequence\":2,\"costPrice\":3800}]");
assertFalse(InquiryTmsQueryService.isLandRoutePendingSelection(single));
assertEquals(1, InquiryTmsQueryService.countLandRoutes(single));
// 已选定线路后,即使还留着整包也按已选处理。
multi.put("selected_land_route", "{\"segmentSequence\":1}");
assertFalse(InquiryTmsQueryService.isLandRoutePendingSelection(multi));
}
@Test
public void landPendingMarkerWinsWithoutSegments() {
Map<String, String> quote = new HashMap<>();
quote.put("pending_land_route_pick", "1");
assertTrue(InquiryTmsQueryService.isLandRoutePendingSelection(quote));
}
@Test
public void airQueryAllowsBlankQuoteDate() {
// 空运没填报价日期也算出站齐套,不能再补成当天才放行。
@@ -220,6 +220,30 @@ public class TmsQuoteCurrencyTest {
assertEquals("", InquiryTmsQueryService.formatLandPercentRate(null));
}
/**
* TMS fxRates 原样透传给智能体:外币明细调价时按它折算小计/合计。
* 汇率只放顶层 fxRates,禁止混进陆运 route_rows 冒充税率。
*/
@Test
public void toAgentQuotePassesFxRates() {
Map<String, Object> rate = new LinkedHashMap<>();
rate.put("fromCurrency", "USD");
rate.put("toCurrency", "CNY");
rate.put("rate", "7.023");
Map<String, Object> data = new HashMap<>();
data.put("quoteFound", true);
data.put("currency", "CNY");
data.put("salePrice", "7023");
data.put("fxRates", Collections.singletonList(rate));
Map<String, Object> tms = new HashMap<>();
tms.put("tmsData", data);
Map<String, String> quote = InquiryTmsQueryService.toAgentQuote(tms);
assertTrue(quote.get("fxRates").contains("\"fromCurrency\":\"USD\""));
assertTrue(quote.get("fxRates").contains("\"toCurrency\":\"CNY\""));
assertTrue(quote.get("fxRates").contains("7.023"));
assertFalse(String.valueOf(quote.get("route_rows")).contains("7.023"));
}
/**
* 腿上燃油为空时,从同段 feeItems.fuelSurchargeRate 补到 route_rows,供出单侧栏写入。
*/
@@ -167,6 +167,9 @@ inquiry:
callback-token: ${AGENT_CALLBACK_TOKEN:}
biz-token: ${BIZ_API_TOKEN:}
parse-timeout-ms: ${QUOTE_TEMPLATE_PARSE_ENQUEUE_TIMEOUT_MS:8000}
# 销售门禁服务端兜底:与智能体 AGENT_SALES_GATE_ENABLED 同步打开。
# 关闭时建单不校验岗位,兼容历史调用方与单测。
sales-gate-enabled: ${AGENT_SALES_GATE_ENABLED:false}
logging:
level: