Browse Source

feat(train-backend): M3 评价四层与晋升域落地

- EvalService:客户评价(only-after-confirmed+uk幂等)/机构绩效(requireOrgOrTeacher)/培训考核(双达标触发证书)/四层汇总(mine,权重归一)/adminList 真分页
- PromotionService:apply(达标同事务晋升+勋章)/records 履历/unlockCheck 闸口/saveRule(conditions 唯一口径)/ruleEnable/reject(StateGuard 终裁)/scanAndGrant 周期评定
- PromotionScanManager:@Scheduled 每日04:30 + 手动补跑 /api/admin/promotion/scan
- 最小闭环:AdminPractitionerController /approve(pending→approved,解锁闸口前提)
- RoleGuard.requireOrgOrTeacher;application.yml 新增 promotion-scan-cron
liaoxg 2 days ago
parent
commit
f1dc175136

+ 108 - 0
train-backend/src/main/java/com/train/controller/EvalController.java

@@ -0,0 +1,108 @@
+package com.train.controller;
+
+import com.train.common.Result;
+import com.train.service.EvalService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 评价线 Controller(用户/公网侧)
+ *
+ * - E1 submit:客户服务评价(★only-after-confirmed,uk(order_id) 幂等),必须本人(worker)
+ * - E2 org / E3 training:机构绩效 / 培训考核成绩(Service 内 RoleGuard.requireOrgOrTeacher)
+ * - E4 mine:四层评价汇总 + 综合评级
+ */
+@Tag(name = "评价", description = "客户服务评价 / 机构绩效 / 培训考核 / 综合评级")
+@RestController
+@RequestMapping("/api/eval")
+public class EvalController {
+
+    @Resource
+    private EvalService evalService;
+
+    /**
+     * 客户服务评价(★only-after-confirmed)
+     * body: {orderId, score(1-5), comment?}
+     */
+    @Operation(summary = "客户服务评价(订单确认后)")
+    @PostMapping("/submit")
+    public Result<Map<String, Object>> submit(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long orderId = toLong(body == null ? null : body.get("orderId"));
+        Integer score = toInt(body == null ? null : body.get("score"));
+        String comment = body == null || body.get("comment") == null ? null : body.get("comment").toString().trim();
+        return evalService.submitClient(userId, orderId, score, comment);
+    }
+
+    /**
+     * 机构绩效评价
+     * body: {userId(被评), score(1-100), dimension?, comment?}
+     */
+    @Operation(summary = "机构绩效评价")
+    @PostMapping("/org")
+    public Result<Map<String, Object>> org(
+            @RequestAttribute("userId") Long operatorId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long targetUserId = toLong(body == null ? null : body.get("userId"));
+        Integer score = toInt(body == null ? null : body.get("score"));
+        String dimension = body == null || body.get("dimension") == null ? null : body.get("dimension").toString().trim();
+        String comment = body == null || body.get("comment") == null ? null : body.get("comment").toString().trim();
+        return evalService.submitOrg(operatorId, targetUserId, score, dimension, comment);
+    }
+
+    /**
+     * 培训考核成绩(双达标自动触发证书)
+     * body: {userId(被评), examScore(0-100), creditHours?(分钟)}
+     */
+    @Operation(summary = "培训考核成绩(双达标触发证书)")
+    @PostMapping("/training")
+    public Result<Map<String, Object>> training(
+            @RequestAttribute("userId") Long operatorId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long targetUserId = toLong(body == null ? null : body.get("userId"));
+        Integer examScore = toInt(body == null ? null : body.get("examScore"));
+        Integer creditHours = toInt(body == null ? null : body.get("creditHours"));
+        return evalService.submitTraining(operatorId, targetUserId, examScore, creditHours);
+    }
+
+    /**
+     * 我的四层评价汇总
+     * 出参: {client:{avg,count}, org:{avg,count}, training:{avg,count,creditTotal,passCount}, composite}
+     */
+    @Operation(summary = "我的四层评价汇总")
+    @PostMapping("/mine")
+    public Result<Map<String, Object>> mine(@RequestAttribute("userId") Long userId) {
+        return evalService.mine(userId);
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Long.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private Integer toInt(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Integer.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 82 - 0
train-backend/src/main/java/com/train/controller/PromotionController.java

@@ -0,0 +1,82 @@
+package com.train.controller;
+
+import com.train.common.Result;
+import com.train.service.PromotionService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 晋升 Controller(用户侧)
+ *
+ * - apply:提交晋升断言(达标同事务晋升 + 勋章;未达标落 evaluated 缺口)
+ * - records:我的晋升履历(mustOwn,真分页)
+ * - unlock:解锁判定(派单资质闸口,只读)
+ */
+@Tag(name = "晋升", description = "晋升断言 / 晋升记录 / 解锁判定")
+@RestController
+@RequestMapping("/api/promotion")
+public class PromotionController {
+
+    @Resource
+    private PromotionService promotionService;
+
+    /**
+     * 提交晋升断言
+     * body: {authLevel: T1/T2/T3/T4}
+     * 出参: {eligible, promoted?, authLevel, unmet:[{metric,label,current,threshold}], recordId?, message?}
+     */
+    @Operation(summary = "提交晋升断言")
+    @PostMapping("/apply")
+    public Result<Map<String, Object>> apply(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        String authLevel = body == null || body.get("authLevel") == null ? null : body.get("authLevel").toString();
+        return promotionService.apply(userId, authLevel);
+    }
+
+    /**
+     * 我的晋升记录(mustOwn,真分页)
+     * body: {page?, size?}
+     */
+    @Operation(summary = "我的晋升记录")
+    @PostMapping("/records")
+    public Result<Map<String, Object>> records(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Integer page = toInt(body == null ? null : body.get("page"));
+        Integer size = toInt(body == null ? null : body.get("size"));
+        return promotionService.records(userId, page, size);
+    }
+
+    /**
+     * 解锁判定(派单资质闸口,只读)
+     * body: {serviceType?}
+     * 出参: {allowed, reason, authLevel}
+     */
+    @Operation(summary = "解锁判定(闸口)")
+    @PostMapping("/unlock")
+    public Result<Map<String, Object>> unlock(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        return promotionService.unlockCheck(userId, body);
+    }
+
+    private Integer toInt(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Integer.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 41 - 0
train-backend/src/main/java/com/train/controller/admin/AdminEvalController.java

@@ -0,0 +1,41 @@
+package com.train.controller.admin;
+
+import com.train.common.Result;
+import com.train.service.EvalService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 管理端-评价 Controller(评价记录视角)。
+ *
+ * 权限:仅 admin(Service 层 RoleGuard.requireAdminRole)。
+ * - list:按类型/被评人分页查看评价记录
+ */
+@Tag(name = "管理端-评价", description = "评价记录管理视角")
+@RestController
+@RequestMapping("/api/admin/eval")
+public class AdminEvalController {
+
+    @Resource
+    private EvalService evalService;
+
+    /**
+     * 评价记录分页(admin 视角)
+     * body: {evalType?: client|org|training, userId?, page?, size?}
+     */
+    @Operation(summary = "评价记录列表(分页)")
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        return evalService.adminList(null, isAdmin, body);
+    }
+}

+ 26 - 0
train-backend/src/main/java/com/train/controller/admin/AdminPractitionerController.java

@@ -35,4 +35,30 @@ public class AdminPractitionerController {
             @RequestBody(required = false) Map<String, Object> body) {
         return practitionerService.adminList(userId, isAdmin, body);
     }
+
+    /**
+     * 档案资质审批(pending→approved;幂等)
+     * body: {userId}
+     * 出参: {userId, status, approvedAt}
+     */
+    @Operation(summary = "档案资质审批")
+    @PostMapping("/approve")
+    public Result<Map<String, Object>> approve(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long targetUserId = body == null || body.get("userId") == null ? null : toLong(body.get("userId"));
+        return practitionerService.approveProfile(adminId, isAdmin, targetUserId);
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Long.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
 }

+ 128 - 0
train-backend/src/main/java/com/train/controller/admin/AdminPromotionController.java

@@ -0,0 +1,128 @@
+package com.train.controller.admin;
+
+import com.train.common.Result;
+import com.train.service.PromotionService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 管理端-晋升 Controller(规则配置 / 启停 / 否决 / 手动评定)。
+ *
+ * 权限:仅 admin(Service 层 RoleGuard.requireAdminRole)。
+ * - rule/save:conditions JSON 唯一执行口径(单条件回填冗余列,多条件置 NULL)
+ * - rule/list:规则列表(真分页)
+ * - rule/enable:启停(P2-S1 可启停)
+ * - reject:机构线下否决(evaluated→rejected,StateGuard 终裁)
+ * - scan:手动触发周期评定(与 @Scheduled 共用)
+ */
+@Tag(name = "管理端-晋升", description = "规则配置 / 启停 / 否决 / 手动评定")
+@RestController
+@RequestMapping("/api/admin/promotion")
+public class AdminPromotionController {
+
+    @Resource
+    private PromotionService promotionService;
+
+    /**
+     * 保存晋升规则
+     * body: {name, authLevel, enabled?, conditions:[{metric,op,value}]}
+     */
+    @Operation(summary = "保存晋升规则")
+    @PostMapping("/rule/save")
+    public Result<Map<String, Object>> ruleSave(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        return promotionService.saveRule(isAdmin, body);
+    }
+
+    /**
+     * 规则列表(真分页)
+     * body: {page?, size?}
+     */
+    @Operation(summary = "晋升规则列表")
+    @PostMapping("/rule/list")
+    public Result<Map<String, Object>> ruleList(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Integer page = toInt(body == null ? null : body.get("page"));
+        Integer size = toInt(body == null ? null : body.get("size"));
+        return promotionService.ruleList(isAdmin, page, size);
+    }
+
+    /**
+     * 规则启停
+     * body: {ruleId, enabled}
+     */
+    @Operation(summary = "晋升规则启停")
+    @PostMapping("/rule/enable")
+    public Result<Map<String, Object>> ruleEnable(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long ruleId = toLong(body == null ? null : body.get("ruleId"));
+        Boolean enabled = body == null || body.get("enabled") == null ? null : toBool(body.get("enabled"));
+        return promotionService.ruleEnable(isAdmin, ruleId, enabled);
+    }
+
+    /**
+     * 机构线下否决(evaluated→rejected)
+     * body: {recordId, reason?}
+     */
+    @Operation(summary = "晋升记录否决")
+    @PostMapping("/reject")
+    public Result<Map<String, Object>> reject(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long recordId = toLong(body == null ? null : body.get("recordId"));
+        String reason = body == null || body.get("reason") == null ? null : body.get("reason").toString().trim();
+        return promotionService.rejectRecord(isAdmin, recordId, reason);
+    }
+
+    /**
+     * 手动触发周期评定
+     * 出参: {processed, granted}
+     */
+    @Operation(summary = "手动触发晋升评定")
+    @PostMapping("/scan")
+    public Result<Map<String, Object>> scan(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin) {
+        return promotionService.scanAndGrant(isAdmin);
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Long.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private Integer toInt(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Integer.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private Boolean toBool(Object v) {
+        if (v == null) {
+            return null;
+        }
+        String s = v.toString().trim().toLowerCase();
+        return "true".equals(s) || "1".equals(s) || "yes".equals(s);
+    }
+}

+ 34 - 0
train-backend/src/main/java/com/train/service/EvalService.java

@@ -0,0 +1,34 @@
+package com.train.service;
+
+import com.train.common.Result;
+
+import java.util.Map;
+
+/**
+ * 四层评价服务(M3 评价晋升域)
+ *
+ * 四层:E1 客户服务评价 / E2 机构绩效考核 / E3 培训考核成绩 / E4 综合评级沉淀。
+ * - E1 ★only-after-confirmed:order.status==confirmed 且 userId==order.worker_id;uk(order_id) 幂等 once-per-order
+ * - E2/E3:RoleGuard.requireOrgOrTeacher(任一机构 active 成员 或 平台 teacher/assistant)
+ * - E4 综合评级聚合:默认权重 客户40/机构30/培训30,按「有数据层」归一;幂等重算覆盖写 profile.rating(不累加)
+ * - 学时一律分钟整数;评分禁浮点(int)
+ */
+public interface EvalService {
+
+    /** E1 客户服务评价(★only-after-confirmed;uk(order_id) 幂等) */
+    Result<Map<String, Object>> submitClient(Long userId, Long orderId, Integer score, String comment);
+
+    /** E2 机构绩效评价(requireOrgOrTeacher;score 1-100) */
+    Result<Map<String, Object>> submitOrg(Long operatorId, Long targetUserId, Integer score,
+                                          String dimension, String comment);
+
+    /** E3 培训考核成绩(requireOrgOrTeacher;examScore 0-100;双达标自动触发 CertService 发证) */
+    Result<Map<String, Object>> submitTraining(Long operatorId, Long targetUserId,
+                                               Integer examScore, Integer creditHours);
+
+    /** E4 我的四层评价汇总 + 综合评级(幂等重算覆盖写 profile.rating) */
+    Result<Map<String, Object>> mine(Long userId);
+
+    /** admin:评价记录分页视角(requireAdmin) */
+    Result<Map<String, Object>> adminList(Long operatorId, Boolean isAdmin, Map<String, Object> body);
+}

+ 10 - 0
train-backend/src/main/java/com/train/service/PractitionerService.java

@@ -37,4 +37,14 @@ public interface PractitionerService {
 
     /** 懒建档:按 user_id 查档案,不存在则创建默认档案(幂等,供各域复用) */
     TrainPractitionerProfile ensureProfile(Long userId);
+
+    /**
+     * 档案资质审批(仅 admin):pending→approved,置 approved_by/approved_at。
+     * 幂等:已 approved 返回既有状态不报错。用于晋升解锁闸口前置(profile.status=approved 资质生效)。
+     *
+     * @param operatorId   操作人(admin token 注入 adminId)
+     * @param isAdmin      管理后台 token 注入
+     * @param targetUserId 被审批档案 owner=train_user.id
+     */
+    Result<Map<String, Object>> approveProfile(Long operatorId, Boolean isAdmin, Long targetUserId);
 }

+ 34 - 0
train-backend/src/main/java/com/train/service/PromotionScanManager.java

@@ -0,0 +1,34 @@
+package com.train.service;
+
+import com.train.common.Result;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+
+/**
+ * 晋升周期评定调度(@Scheduled,全量候选 × 启用规则;逐条 @Transactional 幂等)。
+ *
+ * - 与学时到期扫描错峰:默认每日 04:30(task.promotion-scan-cron 可配)
+ * - 与手动补跑端点 /api/admin/promotion/scan 共用同一 PromotionService.scanAndGrant 逻辑(不另写)
+ * - 重跑安全:evaluateAndRecord 对「目标等级 ≤ 当前等级」幂等跳过,不重复晋升
+ */
+@Slf4j
+@Component
+public class PromotionScanManager {
+
+    @Resource
+    private PromotionService promotionService;
+
+    /** 每日 04:30 全量评定(已认证用户向更高等级冲击),手动补跑可随时触发 */
+    @Scheduled(cron = "${task.promotion-scan-cron:0 30 4 * * ?}")
+    public void scheduledScan() {
+        try {
+            Result<?> r = promotionService.scanAndGrant(Boolean.TRUE);
+            log.info("晋升周期评定扫描完成: code={}, message={}", r.getCode(), r.getMessage());
+        } catch (Exception e) {
+            log.error("晋升周期评定扫描异常: err={}", e.getMessage(), e);
+        }
+    }
+}

+ 45 - 0
train-backend/src/main/java/com/train/service/PromotionService.java

@@ -0,0 +1,45 @@
+package com.train.service;
+
+import com.train.common.Result;
+
+import java.util.Map;
+
+/**
+ * 晋升域服务(M3 评价晋升域)
+ *
+ * - 规则以 train_promotion_rule.conditions JSON 为唯一执行口径(多条件 AND),metric/operator/value 仅展示冗余
+ * - 状态机(对齐 train_promotion_record.status 值域 evaluated/promoted/rejected):
+ *   达标 → 记录 status=promoted(同事务真实晋升,终态);未达标 → status=evaluated + pass=0 + unmet;
+ *   机构否决 → status=rejected(终态,重新发起=新记录)
+ * - 认证升级原子:记录(status=promoted) + profile.auth_level + 勋章(lec_t1~t4) 同事务(@Transactional)
+ * - 解锁判定 unlockCheck 只读(派单资质闸口:profile.status=approved 且 auth_level 已认证)
+ */
+public interface PromotionService {
+
+    /** 用户提交晋升断言(达标同事务晋升;未达标落 evaluated 记录缺口) */
+    Result<Map<String, Object>> apply(Long userId, String authLevel);
+
+    /** 内部事务方法:按规则评定并落记录(apply 与 scan 共用;经 @Lazy 自注入代理保证事务) */
+    Result<Map<String, Object>> evaluateAndRecord(Long userId, Long ruleId);
+
+    /** 解锁判定(派单资质闸口,只读) */
+    Result<Map<String, Object>> unlockCheck(Long userId, Map<String, Object> body);
+
+    /** 我的晋升记录(mustOwn,真分页) */
+    Result<Map<String, Object>> records(Long userId, Integer page, Integer size);
+
+    /** admin:保存规则(conditions 一致性写:单条件回填冗余列,多条件置 NULL) */
+    Result<Map<String, Object>> saveRule(Boolean isAdmin, Map<String, Object> body);
+
+    /** admin:规则列表(真分页) */
+    Result<Map<String, Object>> ruleList(Boolean isAdmin, Integer page, Integer size);
+
+    /** admin:规则启停(P2-S1 可启停) */
+    Result<Map<String, Object>> ruleEnable(Boolean isAdmin, Long ruleId, Boolean enabled);
+
+    /** admin:机构线下否决(evaluated→rejected,StateGuard 终裁) */
+    Result<Map<String, Object>> rejectRecord(Boolean isAdmin, Long recordId, String reason);
+
+    /** admin:手动触发周期评定(与 @Scheduled 共用),返回 {processed, granted} */
+    Result<Map<String, Object>> scanAndGrant(Boolean isAdmin);
+}

+ 31 - 0
train-backend/src/main/java/com/train/service/RoleGuard.java

@@ -3,8 +3,10 @@ package com.train.service;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.train.entity.TrainOrgMember;
 import com.train.entity.TrainServiceOrder;
+import com.train.entity.TrainUser;
 import com.train.mapper.TrainOrgMemberMapper;
 import com.train.mapper.TrainServiceOrderMapper;
+import com.train.mapper.TrainUserMapper;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Component;
 
@@ -35,6 +37,9 @@ public class RoleGuard {
     @Resource
     private TrainServiceOrderMapper trainServiceOrderMapper;
 
+    @Resource
+    private TrainUserMapper trainUserMapper;
+
     /**
      * 校验 userId 是 orgId 的成员(任意角色,active 未删除)。合法返回 null,越权返回中文 message。
      */
@@ -110,4 +115,30 @@ public class RoleGuard {
     public String requireAdminRole(Boolean isAdmin) {
         return Boolean.TRUE.equals(isAdmin) ? null : "需要管理员权限";
     }
+
+    /**
+     * 校验 userId 有「评价/考核」操作权(E2 机构绩效 / E3 培训考核成绩):
+     * ① 任一机构 active 成员(任意角色:org_admin/dispatcher/lecturer/mentor),或
+     * ② 平台角色 ∈ {teacher, assistant}(TrainUser.role)。
+     * 合法返回 null,越权返回中文 message。
+     */
+    public String requireOrgOrTeacher(Long userId) {
+        if (userId == null) {
+            return "参数不完整";
+        }
+        Long orgCnt = trainOrgMemberMapper.selectCount(
+                new LambdaQueryWrapper<TrainOrgMember>()
+                        .eq(TrainOrgMember::getUserId, userId)
+                        .eq(TrainOrgMember::getStatus, MEMBER_STATUS_ACTIVE)
+                        .eq(TrainOrgMember::getDeleted, 0));
+        if (orgCnt != null && orgCnt > 0) {
+            return null;
+        }
+        TrainUser u = trainUserMapper.selectById(userId);
+        if (u != null && u.getRole() != null
+                && ("teacher".equals(u.getRole()) || "assistant".equals(u.getRole()))) {
+            return null;
+        }
+        return "无评价/考核权限";
+    }
 }

+ 409 - 0
train-backend/src/main/java/com/train/service/impl/EvalServiceImpl.java

@@ -0,0 +1,409 @@
+package com.train.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.train.common.Result;
+import com.train.entity.TrainEvalRecord;
+import com.train.entity.TrainPractitionerProfile;
+import com.train.entity.TrainServiceOrder;
+import com.train.mapper.TrainEvalRecordMapper;
+import com.train.mapper.TrainPractitionerProfileMapper;
+import com.train.mapper.TrainServiceOrderMapper;
+import com.train.service.CertService;
+import com.train.service.EvalService;
+import com.train.service.PractitionerService;
+import com.train.service.RoleGuard;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 四层评价实现。
+ *
+ * 关键口径:
+ * - E1 客户评价:order.confirmed 强前置 + uk(order_id) 幂等(重复返回已评价,不报错)
+ * - E4 综合评级:聚合 client(1-5星)/org(1-100)/training(0-100) 三层,默认权重 40/30/30,
+ *   按「有数据层」归一至 0-5.00;幂等重算覆盖写 practitioner_profile.rating(不累加)
+ * - E3 双达标(成绩≥60 且 学时≥8h=480分钟)自动触发 CertService.issue(自带 6 项验收 + 幂等发号)
+ * - 评价记录 status=valid 有效;删除软删
+ */
+@Slf4j
+@Service
+public class EvalServiceImpl implements EvalService {
+
+    private static final String ET_CLIENT = "client";
+    private static final String ET_ORG = "org";
+    private static final String ET_TRAINING = "training";
+    private static final String ST_VALID = "valid";
+    private static final String O_CONFIRMED = "confirmed";
+    /** 培训双达标:成绩及格线(分) */
+    private static final int TRAIN_EXAM_PASS = 60;
+    /** 培训双达标:学时达标线(分钟,8h=480) */
+    private static final int TRAIN_CREDIT_PASS = 480;
+
+    @Resource
+    private TrainEvalRecordMapper trainEvalRecordMapper;
+    @Resource
+    private TrainServiceOrderMapper trainServiceOrderMapper;
+    @Resource
+    private TrainPractitionerProfileMapper trainPractitionerProfileMapper;
+    @Resource
+    private PractitionerService practitionerService;
+    @Resource
+    private CertService certService;
+    @Resource
+    private RoleGuard roleGuard;
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Map<String, Object>> submitClient(Long userId, Long orderId, Integer score, String comment) {
+        if (userId == null || orderId == null || score == null) {
+            return Result.error("参数不完整");
+        }
+        if (score < 1 || score > 5) {
+            return Result.error("评分须为1-5星");
+        }
+        TrainServiceOrder order = trainServiceOrderMapper.selectById(orderId);
+        if (order == null) {
+            return Result.error("工单不存在或不属于您");
+        }
+        // 目标必须为本人(worker)
+        if (order.getWorkerId() == null || !order.getWorkerId().equals(userId)) {
+            return Result.error("工单不存在或不属于您");
+        }
+        if (!O_CONFIRMED.equals(order.getStatus())) {
+            return Result.error("工单未确认,暂不可评价");
+        }
+        // 幂等:uk(order_id) once-per-order
+        TrainEvalRecord exist = selectByOrderId(orderId);
+        if (exist != null) {
+            return Result.success(evalVO(exist));
+        }
+        TrainEvalRecord r = new TrainEvalRecord();
+        r.setEvalType(ET_CLIENT);
+        r.setOrderId(orderId);
+        r.setUserId(order.getWorkerId());
+        r.setScorerId(userId);
+        r.setScore(score);
+        r.setDimension("service");
+        r.setComment(comment);
+        r.setStatus(ST_VALID);
+        r.setDeleted(0);
+        try {
+            trainEvalRecordMapper.insert(r);
+        } catch (Exception e) {
+            // uk(order_id) 并发冲突 → 幂等返回已评价
+            TrainEvalRecord dup = selectByOrderId(orderId);
+            if (dup != null) {
+                return Result.success(evalVO(dup));
+            }
+            log.warn("客户评价插入失败: orderId={}, err={}", orderId, e.getMessage());
+            return Result.error("评价提交失败,请重试");
+        }
+        // 综合评级幂等重算覆盖(重算写,不累加)
+        recalcRating(order.getWorkerId());
+        return Result.success(evalVO(r));
+    }
+
+    @Override
+    public Result<Map<String, Object>> submitOrg(Long operatorId, Long targetUserId, Integer score,
+                                                 String dimension, String comment) {
+        String noAuth = roleGuard.requireOrgOrTeacher(operatorId);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (targetUserId == null || score == null) {
+            return Result.error("参数不完整");
+        }
+        if (score < 1 || score > 100) {
+            return Result.error("机构绩效评分范围1-100");
+        }
+        TrainEvalRecord r = new TrainEvalRecord();
+        r.setEvalType(ET_ORG);
+        r.setUserId(targetUserId);
+        r.setScorerId(operatorId);
+        r.setScore(score);
+        r.setDimension(dimension);
+        r.setComment(comment);
+        r.setStatus(ST_VALID);
+        r.setDeleted(0);
+        trainEvalRecordMapper.insert(r);
+        recalcRating(targetUserId);
+        return Result.success(evalVO(r));
+    }
+
+    @Override
+    public Result<Map<String, Object>> submitTraining(Long operatorId, Long targetUserId,
+                                                      Integer examScore, Integer creditHours) {
+        String noAuth = roleGuard.requireOrgOrTeacher(operatorId);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (targetUserId == null || examScore == null) {
+            return Result.error("参数不完整");
+        }
+        if (examScore < 0 || examScore > 100) {
+            return Result.error("考核成绩范围0-100");
+        }
+        int credits = creditHours == null ? 0 : creditHours;
+        TrainEvalRecord r = new TrainEvalRecord();
+        r.setEvalType(ET_TRAINING);
+        r.setUserId(targetUserId);
+        r.setScorerId(operatorId);
+        r.setScore(examScore);
+        r.setExtra("{\"examScore\":" + examScore + ",\"creditHours\":" + credits + "}");
+        r.setStatus(ST_VALID);
+        r.setDeleted(0);
+        trainEvalRecordMapper.insert(r);
+        recalcRating(targetUserId);
+        // 双达标(成绩+学时)自动触发完课证书:CertService.issue 自带 6 项验收 + 幂等发号
+        Map<String, Object> cert = new HashMap<>();
+        cert.put("triggered", false);
+        if (examScore >= TRAIN_EXAM_PASS && credits >= TRAIN_CREDIT_PASS) {
+            Map<String, Object> issue = certService.issue(targetUserId);
+            cert = new HashMap<>(issue);
+            cert.put("triggered", true);
+        }
+        Map<String, Object> vo = evalVO(r);
+        vo.put("cert", cert);
+        return Result.success(vo);
+    }
+
+    @Override
+    public Result<Map<String, Object>> mine(Long userId) {
+        if (userId == null) {
+            return Result.error("需要登录");
+        }
+        Map<String, Object> data = aggregate(userId);
+        // 综合评级幂等重算覆盖(重算写,不累加)
+        Object comp = data.get("composite");
+        if (comp instanceof Number) {
+            recalcRating(userId);
+        }
+        return Result.success(data);
+    }
+
+    @Override
+    public Result<Map<String, Object>> adminList(Long operatorId, Boolean isAdmin, Map<String, Object> body) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        int page = body == null || body.get("page") == null ? 1 : toInt(body.get("page"));
+        int size = body == null || body.get("size") == null ? 20 : Math.min(toInt(body.get("size")), 100);
+        if (page < 1) {
+            page = 1;
+        }
+        if (size < 1) {
+            size = 20;
+        }
+        int offset = (page - 1) * size;
+        LambdaQueryWrapper<TrainEvalRecord> q = new LambdaQueryWrapper<TrainEvalRecord>()
+                .eq(TrainEvalRecord::getDeleted, 0)
+                .orderByDesc(TrainEvalRecord::getCreatedAt);
+        String evalType = body == null || body.get("evalType") == null ? null : str(body.get("evalType"));
+        Long userId = body == null || body.get("userId") == null ? null : toLong(body.get("userId"));
+        if (evalType != null && !evalType.trim().isEmpty()) {
+            q.eq(TrainEvalRecord::getEvalType, evalType.trim());
+        }
+        if (userId != null) {
+            q.eq(TrainEvalRecord::getUserId, userId);
+        }
+        Long total = trainEvalRecordMapper.selectCount(q);
+        List<TrainEvalRecord> list = trainEvalRecordMapper.selectList(q.last("LIMIT " + offset + "," + size));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainEvalRecord r : list) {
+            rows.add(evalVO(r));
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("total", total == null ? 0 : total);
+        data.put("page", page);
+        data.put("size", size);
+        data.put("list", rows);
+        return Result.success(data);
+    }
+
+    // ============ 内部 ============
+
+    /** 四层聚合:client/org/training 均值 + composite(归一至 0-5.00) */
+    private Map<String, Object> aggregate(Long userId) {
+        List<TrainEvalRecord> client = listByType(userId, ET_CLIENT);
+        List<TrainEvalRecord> org = listByType(userId, ET_ORG);
+        List<TrainEvalRecord> training = listByType(userId, ET_TRAINING);
+        Map<String, Object> clientM = stats(client);
+        Map<String, Object> orgM = stats(org);
+        Map<String, Object> trainingM = trainingStats(training);
+        // 默认权重 40/30/30,按「有数据层」归一(仅对有评价数据的层加权,避免新用户被 0 拉低)
+        double w = 0, acc = 0;
+        double clientCount = clientM.get("count") == null ? 0 : ((Number) clientM.get("count")).doubleValue();
+        double orgCount = orgM.get("count") == null ? 0 : ((Number) orgM.get("count")).doubleValue();
+        double trainingCount = trainingM.get("count") == null ? 0 : ((Number) trainingM.get("count")).doubleValue();
+        if (clientCount > 0) {
+            acc += 0.4 * (num(clientM.get("avg")) / 5.0);
+            w += 0.4;
+        }
+        if (orgCount > 0) {
+            acc += 0.3 * (num(orgM.get("avg")) / 100.0);
+            w += 0.3;
+        }
+        if (trainingCount > 0) {
+            acc += 0.3 * (num(trainingM.get("avg")) / 100.0);
+            w += 0.3;
+        }
+        double composite = w > 0 ? round2(acc / w * 5) : 0.0;
+        Map<String, Object> data = new HashMap<>();
+        data.put("client", clientM);
+        data.put("org", orgM);
+        data.put("training", trainingM);
+        data.put("composite", composite);
+        return data;
+    }
+
+    /** 幂等重算覆盖写 profile.rating(重算不累加) */
+    private void recalcRating(Long userId) {
+        if (userId == null) {
+            return;
+        }
+        Map<String, Object> data = aggregate(userId);
+        Object comp = data.get("composite");
+        if (!(comp instanceof Number)) {
+            return;
+        }
+        TrainPractitionerProfile p = practitionerService.ensureProfile(userId);
+        if (p == null) {
+            return;
+        }
+        p.setRating(((Number) comp).doubleValue());
+        p.setUpdatedAt(new Date());
+        trainPractitionerProfileMapper.updateById(p);
+    }
+
+    private List<TrainEvalRecord> listByType(Long userId, String evalType) {
+        return trainEvalRecordMapper.selectList(
+                new LambdaQueryWrapper<TrainEvalRecord>()
+                        .eq(TrainEvalRecord::getUserId, userId)
+                        .eq(TrainEvalRecord::getEvalType, evalType)
+                        .eq(TrainEvalRecord::getStatus, ST_VALID)
+                        .eq(TrainEvalRecord::getDeleted, 0)
+                        .orderByDesc(TrainEvalRecord::getCreatedAt));
+    }
+
+    private Map<String, Object> stats(List<TrainEvalRecord> list) {
+        Map<String, Object> m = new HashMap<>();
+        int count = list == null ? 0 : list.size();
+        double sum = 0;
+        if (list != null) {
+            for (TrainEvalRecord r : list) {
+                sum += r.getScore() == null ? 0 : r.getScore();
+            }
+        }
+        m.put("count", count);
+        m.put("avg", count > 0 ? round2(sum / count) : 0.0);
+        return m;
+    }
+
+    private Map<String, Object> trainingStats(List<TrainEvalRecord> list) {
+        Map<String, Object> m = stats(list);
+        int creditTotal = 0;
+        int passCount = 0;
+        if (list != null) {
+            for (TrainEvalRecord r : list) {
+                int s = r.getScore() == null ? 0 : r.getScore();
+                if (s >= TRAIN_EXAM_PASS) {
+                    passCount++;
+                }
+                creditTotal += creditFromExtra(r.getExtra());
+            }
+        }
+        m.put("creditTotal", creditTotal); // 分钟
+        m.put("passCount", passCount);
+        return m;
+    }
+
+    private int creditFromExtra(String extra) {
+        if (extra == null || extra.isEmpty()) {
+            return 0;
+        }
+        int idx = extra.indexOf("creditHours");
+        if (idx < 0) {
+            return 0;
+        }
+        int c = extra.indexOf(':', idx);
+        int end = extra.indexOf(',', c);
+        if (end < 0) {
+            end = extra.indexOf('}', c);
+        }
+        if (c < 0 || end < 0) {
+            return 0;
+        }
+        try {
+            return Integer.parseInt(extra.substring(c + 1, end).trim());
+        } catch (NumberFormatException e) {
+            return 0;
+        }
+    }
+
+    private TrainEvalRecord selectByOrderId(Long orderId) {
+        return trainEvalRecordMapper.selectOne(
+                new LambdaQueryWrapper<TrainEvalRecord>()
+                        .eq(TrainEvalRecord::getOrderId, orderId)
+                        .eq(TrainEvalRecord::getDeleted, 0)
+                        .last("LIMIT 1"));
+    }
+
+    private Map<String, Object> evalVO(TrainEvalRecord r) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("evalId", r.getId());
+        m.put("evalType", r.getEvalType());
+        m.put("orderId", r.getOrderId());
+        m.put("userId", r.getUserId());
+        m.put("scorerId", r.getScorerId());
+        m.put("score", r.getScore() == null ? 0 : r.getScore());
+        m.put("dimension", r.getDimension());
+        m.put("comment", r.getComment());
+        m.put("extra", r.getExtra());
+        m.put("status", r.getStatus());
+        m.put("createdAt", r.getCreatedAt());
+        return m;
+    }
+
+    private double num(Object v) {
+        return v instanceof Number ? ((Number) v).doubleValue() : 0.0;
+    }
+
+    private double round2(double v) {
+        return Math.round(v * 100.0) / 100.0;
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Long.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private Integer toInt(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Integer.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private String str(Object v) {
+        return v == null ? null : v.toString().trim();
+    }
+}

+ 27 - 0
train-backend/src/main/java/com/train/service/impl/PractitionerServiceImpl.java

@@ -214,6 +214,33 @@ public class PractitionerServiceImpl implements PractitionerService {
         return p;
     }
 
+    @Override
+    public Result<Map<String, Object>> approveProfile(Long operatorId, Boolean isAdmin, Long targetUserId) {
+        if (!Boolean.TRUE.equals(isAdmin)) {
+            return Result.error("需要管理员权限");
+        }
+        if (targetUserId == null) {
+            return Result.error("参数不完整");
+        }
+        TrainPractitionerProfile p = selectByUserId(targetUserId);
+        if (p == null) {
+            return Result.error("档案不存在");
+        }
+        // 幂等:已 approved 直接返回既有状态
+        if (!"approved".equals(p.getStatus())) {
+            p.setStatus("approved");
+            p.setApprovedBy(operatorId);
+            p.setApprovedAt(new Date());
+            p.setUpdatedAt(new Date());
+            trainPractitionerProfileMapper.updateById(p);
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("userId", targetUserId);
+        data.put("status", p.getStatus());
+        data.put("approvedAt", p.getApprovedAt());
+        return Result.success(data);
+    }
+
     // ---------- 内部工具 ----------
 
     private LambdaQueryWrapper<TrainPractitionerProfile> baseWrapper(String keyword, String level,

+ 713 - 0
train-backend/src/main/java/com/train/service/impl/PromotionServiceImpl.java

@@ -0,0 +1,713 @@
+package com.train.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.train.common.Result;
+import com.train.common.StateGuard;
+import com.train.entity.TrainCreditLedger;
+import com.train.entity.TrainEvalRecord;
+import com.train.entity.TrainPractitionerProfile;
+import com.train.entity.TrainPromotionRecord;
+import com.train.entity.TrainPromotionRule;
+import com.train.entity.TrainServiceOrder;
+import com.train.mapper.TrainCreditLedgerMapper;
+import com.train.mapper.TrainEvalRecordMapper;
+import com.train.mapper.TrainPractitionerProfileMapper;
+import com.train.mapper.TrainPromotionRecordMapper;
+import com.train.mapper.TrainPromotionRuleMapper;
+import com.train.mapper.TrainServiceOrderMapper;
+import com.train.service.BadgeService;
+import com.train.service.PractitionerService;
+import com.train.service.PromotionService;
+import com.train.service.RoleGuard;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 晋升域实现。
+ *
+ * 关键口径:
+ * - conditions JSON 为唯一执行口径(多条件 AND 判定);metric/operator/value 仅展示冗余(保存时一致性写)
+ * - 状态机:达标 → promoted(同事务:记录 + profile.auth_level + 勋章 lec_tX);未达标 → evaluated + pass=0 + unmet;
+ *   机构否决 → rejected(StateGuard 终裁;重新发起=新记录)
+ * - 认证升级原子性:self.evaluateAndRecord 经 @Lazy 自注入代理调用,保证单条 @Transactional 生效
+ * - metric 取值口径:serve_count/order_count=已确认工单数;rating=profile.rating*100(0-500);
+ *   theory_hours/total_hours/credit_hours=台账 effective 分钟聚合;exam_score=最近一次培训考核成绩
+ */
+@Slf4j
+@Service
+public class PromotionServiceImpl implements PromotionService {
+
+    private static final String LV_NONE = "none";
+    private static final List<String> LV_ORDER = Arrays.asList("none", "T1", "T2", "T3", "T4");
+
+    private static final String PR_EVALUATED = "evaluated";
+    private static final String PR_PROMOTED = "promoted";
+    private static final String PR_REJECTED = "rejected";
+
+    private static final String ST_EFFECTIVE = "effective";
+    private static final String CAT_THEORY = "theory";
+    private static final String ET_TRAINING = "training";
+    private static final String ST_VALID = "valid";
+    private static final String O_CONFIRMED = "confirmed";
+    private static final String BADGE_PREFIX = "lec_t";
+
+    private static final Set<String> ALLOWED_METRICS = new HashSet<>(Arrays.asList(
+            "serve_count", "order_count", "rating", "theory_hours", "total_hours", "credit_hours", "exam_score"));
+    private static final Set<String> ALLOWED_OPS = new HashSet<>(Arrays.asList(
+            ">=", ">", "==", "<=", "<", "ge", "gt", "eq", "le", "lt"));
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    @Resource
+    private TrainPromotionRuleMapper trainPromotionRuleMapper;
+    @Resource
+    private TrainPromotionRecordMapper trainPromotionRecordMapper;
+    @Resource
+    private TrainPractitionerProfileMapper trainPractitionerProfileMapper;
+    @Resource
+    private TrainServiceOrderMapper trainServiceOrderMapper;
+    @Resource
+    private TrainCreditLedgerMapper trainCreditLedgerMapper;
+    @Resource
+    private TrainEvalRecordMapper trainEvalRecordMapper;
+    @Resource
+    private PractitionerService practitionerService;
+    @Resource
+    private BadgeService badgeService;
+    @Resource
+    private RoleGuard roleGuard;
+    /** 自注入代理:绕过 self-invocation,使 evaluateAndRecord 的 @Transactional 生效(@Lazy 避免初始化循环) */
+    @Lazy
+    @Resource
+    private PromotionService self;
+
+    @Override
+    public Result<Map<String, Object>> apply(Long userId, String authLevel) {
+        if (userId == null || authLevel == null || authLevel.trim().isEmpty()) {
+            return Result.error("参数不完整");
+        }
+        String lv = authLevel.trim().toUpperCase();
+        int target = levelIndex(lv);
+        if (target < 1) {
+            return Result.error("目标认证等级不正确");
+        }
+        TrainPractitionerProfile p = practitionerService.ensureProfile(userId);
+        if (p == null) {
+            return Result.error("档案不存在");
+        }
+        int cur = levelIndex(normLevel(p.getAuthLevel()));
+        if (cur >= target) {
+            return Result.success(promptMap("当前已是该认证等级", lv));
+        }
+        TrainPromotionRule rule = enabledRule(lv);
+        if (rule == null) {
+            return Result.error("未配置该等级的晋升规则");
+        }
+        return self.evaluateAndRecord(userId, rule.getId());
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Map<String, Object>> evaluateAndRecord(Long userId, Long ruleId) {
+        if (userId == null || ruleId == null) {
+            return Result.error("参数不完整");
+        }
+        TrainPromotionRule rule = trainPromotionRuleMapper.selectById(ruleId);
+        if (rule == null || (rule.getDeleted() != null && rule.getDeleted() == 1)) {
+            return Result.error("规则不存在");
+        }
+        // 并发幂等:目标等级 ≤ 当前等级 → 不重复晋升(不落记录)
+        TrainPractitionerProfile p = selectProfileByUserId(userId);
+        int cur = levelIndex(normLevel(p == null ? null : p.getAuthLevel()));
+        int target = levelIndex(rule.getAuthLevel());
+        if (p != null && cur >= target) {
+            return Result.success(promptMap("当前已是该认证等级", rule.getAuthLevel()));
+        }
+        // conditions 逐条 AND 判定
+        List<Map<String, Object>> conds = parseConditions(rule.getConditions());
+        if (conds == null) {
+            return Result.error("规则达标条件配置错误");
+        }
+        List<Map<String, Object>> unmet = new ArrayList<>();
+        for (Map<String, Object> c : conds) {
+            String metric = c == null ? null : str(c.get("metric"));
+            String op = normOp(c == null ? null : str(c.get("op")));
+            Long value = toLong(c == null ? null : c.get("value"));
+            if (metric == null || op == null || value == null) {
+                return Result.error("规则达标条件配置错误");
+            }
+            long current = metricValue(userId, metric);
+            if (!compare(current, op, value.longValue())) {
+                Map<String, Object> u = new HashMap<>();
+                u.put("metric", metric);
+                u.put("label", metricLabel(metric));
+                u.put("current", current);
+                u.put("threshold", value);
+                unmet.add(u);
+            }
+        }
+        Date now = new Date();
+        TrainPromotionRecord rec = new TrainPromotionRecord();
+        rec.setUserId(userId);
+        rec.setAuthLevel(rule.getAuthLevel());
+        rec.setRuleId(rule.getId());
+        rec.setAppliedAt(now);
+        rec.setDeleted(0);
+        if (unmet.isEmpty()) {
+            // 达标 → 同事务真实晋升(记录 + profile.auth_level + 勋章)
+            rec.setPass(1);
+            rec.setStatus(PR_PROMOTED);
+            rec.setPromotedAt(now);
+            trainPromotionRecordMapper.insert(rec);
+            TrainPractitionerProfile pp = p != null ? p : practitionerService.ensureProfile(userId);
+            if (pp != null) {
+                pp.setAuthLevel(rule.getAuthLevel());
+                pp.setUpdatedAt(now);
+                trainPractitionerProfileMapper.updateById(pp);
+            }
+            badgeService.grantBadge(userId, BADGE_PREFIX + rule.getAuthLevel(), 0L, "讲师认证晋升 " + rule.getAuthLevel());
+            Map<String, Object> data = new HashMap<>();
+            data.put("eligible", true);
+            data.put("promoted", true);
+            data.put("authLevel", rule.getAuthLevel());
+            data.put("unmet", new ArrayList<>());
+            data.put("recordId", rec.getId());
+            return Result.success(data);
+        } else {
+            // 未达标 → evaluated 记录缺口(不发生状态迁移)
+            rec.setPass(0);
+            rec.setStatus(PR_EVALUATED);
+            rec.setUnmet(writeJson(unmet));
+            trainPromotionRecordMapper.insert(rec);
+            Map<String, Object> data = new HashMap<>();
+            data.put("eligible", false);
+            data.put("promoted", false);
+            data.put("authLevel", rule.getAuthLevel());
+            data.put("unmet", unmet);
+            data.put("recordId", rec.getId());
+            return Result.success(data);
+        }
+    }
+
+    @Override
+    public Result<Map<String, Object>> unlockCheck(Long userId, Map<String, Object> body) {
+        if (userId == null) {
+            return Result.error("需要登录");
+        }
+        TrainPractitionerProfile p = selectProfileByUserId(userId);
+        Map<String, Object> data = new HashMap<>();
+        if (p == null) {
+            data.put("allowed", false);
+            data.put("reason", "档案不存在");
+            data.put("authLevel", null);
+            return Result.success(data);
+        }
+        data.put("authLevel", p.getAuthLevel());
+        if (p.getStatus() == null || !"approved".equals(p.getStatus())) {
+            data.put("allowed", false);
+            data.put("reason", "资质未生效");
+            return Result.success(data);
+        }
+        if (levelIndex(normLevel(p.getAuthLevel())) < 1) {
+            data.put("allowed", false);
+            data.put("reason", "未认证");
+            return Result.success(data);
+        }
+        data.put("allowed", true);
+        data.put("reason", "资质已生效,认证等级 " + p.getAuthLevel());
+        return Result.success(data);
+    }
+
+    @Override
+    public Result<Map<String, Object>> records(Long userId, Integer page, Integer size) {
+        if (userId == null) {
+            return Result.error("需要登录");
+        }
+        int p = page == null || page < 1 ? 1 : page;
+        int s = size == null || size < 1 ? 20 : Math.min(size, 100);
+        int offset = (p - 1) * s;
+        LambdaQueryWrapper<TrainPromotionRecord> q = new LambdaQueryWrapper<TrainPromotionRecord>()
+                .eq(TrainPromotionRecord::getUserId, userId)
+                .eq(TrainPromotionRecord::getDeleted, 0)
+                .orderByDesc(TrainPromotionRecord::getAppliedAt);
+        Long total = trainPromotionRecordMapper.selectCount(q);
+        List<TrainPromotionRecord> list = trainPromotionRecordMapper.selectList(q.last("LIMIT " + offset + "," + s));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainPromotionRecord r : list) {
+            rows.add(recordVO(r));
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("total", total == null ? 0 : total);
+        data.put("page", p);
+        data.put("size", s);
+        data.put("list", rows);
+        return Result.success(data);
+    }
+
+    @Override
+    public Result<Map<String, Object>> saveRule(Boolean isAdmin, Map<String, Object> body) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (body == null) {
+            return Result.error("参数不完整");
+        }
+        String name = str(body.get("name"));
+        String authLevel = body.get("authLevel") == null ? null : str(body.get("authLevel")).toUpperCase();
+        if (name == null || name.isEmpty()) {
+            return Result.error("规则名称必填");
+        }
+        if (levelIndex(authLevel) < 1) {
+            return Result.error("目标认证等级不正确");
+        }
+        List<Map<String, Object>> conds = normalizeConditions(body.get("conditions"));
+        if (conds == null || conds.isEmpty()) {
+            return Result.error("达标条件不能为空");
+        }
+        TrainPromotionRule rule = new TrainPromotionRule();
+        rule.setName(name);
+        rule.setAuthLevel(authLevel);
+        rule.setConditions(writeJson(conds));
+        // 一致性写:单条件回填展示冗余列;多条件置 NULL(语义=「多条件,看 conditions」)
+        if (conds.size() == 1) {
+            Map<String, Object> only = conds.get(0);
+            rule.setMetric(str(only.get("metric")));
+            rule.setOperator(str(only.get("op")));
+            rule.setValue(toLong(only.get("value")) == null ? null : toLong(only.get("value")).intValue());
+        }
+        Object en = body.get("enabled");
+        int enabledFlag = (en == null) ? 1 : (parseBool(en) ? 1 : 0); // 缺省启用
+        rule.setEnabled(enabledFlag);
+        rule.setVersion(1);
+        rule.setDeleted(0);
+        trainPromotionRuleMapper.insert(rule);
+        Map<String, Object> data = new HashMap<>();
+        data.put("ruleId", rule.getId());
+        data.put("authLevel", authLevel);
+        return Result.success(data);
+    }
+
+    @Override
+    public Result<Map<String, Object>> ruleList(Boolean isAdmin, Integer page, Integer size) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        int p = page == null || page < 1 ? 1 : page;
+        int s = size == null || size < 1 ? 20 : Math.min(size, 100);
+        int offset = (p - 1) * s;
+        LambdaQueryWrapper<TrainPromotionRule> q = new LambdaQueryWrapper<TrainPromotionRule>()
+                .eq(TrainPromotionRule::getDeleted, 0)
+                .orderByAsc(TrainPromotionRule::getAuthLevel)
+                .orderByDesc(TrainPromotionRule::getVersion);
+        Long total = trainPromotionRuleMapper.selectCount(q);
+        List<TrainPromotionRule> list = trainPromotionRuleMapper.selectList(q.last("LIMIT " + offset + "," + s));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainPromotionRule r : list) {
+            rows.add(ruleVO(r));
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("total", total == null ? 0 : total);
+        data.put("page", p);
+        data.put("size", s);
+        data.put("list", rows);
+        return Result.success(data);
+    }
+
+    @Override
+    public Result<Map<String, Object>> ruleEnable(Boolean isAdmin, Long ruleId, Boolean enabled) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (ruleId == null || enabled == null) {
+            return Result.error("参数不完整");
+        }
+        TrainPromotionRule rule = trainPromotionRuleMapper.selectById(ruleId);
+        if (rule == null) {
+            return Result.error("规则不存在");
+        }
+        rule.setEnabled(Boolean.TRUE.equals(enabled) ? 1 : 0);
+        rule.setUpdatedAt(new Date());
+        trainPromotionRuleMapper.updateById(rule);
+        Map<String, Object> data = new HashMap<>();
+        data.put("ruleId", ruleId);
+        data.put("enabled", rule.getEnabled());
+        return Result.success(data);
+    }
+
+    @Override
+    public Result<Map<String, Object>> rejectRecord(Boolean isAdmin, Long recordId, String reason) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (recordId == null) {
+            return Result.error("参数不完整");
+        }
+        TrainPromotionRecord rec = trainPromotionRecordMapper.selectById(recordId);
+        if (rec == null || (rec.getDeleted() != null && rec.getDeleted() == 1)) {
+            return Result.error("晋升记录不存在");
+        }
+        String err = StateGuard.checkPromotion(rec.getStatus(), PR_REJECTED);
+        if (err != null) {
+            return Result.error(err);
+        }
+        rec.setStatus(PR_REJECTED);
+        rec.setUpdatedAt(new Date());
+        trainPromotionRecordMapper.updateById(rec);
+        log.info("晋升记录机构否决: recordId={}, userId={}, authLevel={}, reason={}",
+                recordId, rec.getUserId(), rec.getAuthLevel(), reason);
+        return Result.success(recordVO(rec));
+    }
+
+    @Override
+    public Result<Map<String, Object>> scanAndGrant(Boolean isAdmin) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        int processed = 0;
+        int granted = 0;
+        List<TrainPractitionerProfile> profiles = trainPractitionerProfileMapper.selectList(
+                new LambdaQueryWrapper<TrainPractitionerProfile>()
+                        .eq(TrainPractitionerProfile::getDeleted, 0));
+        List<TrainPromotionRule> rules = trainPromotionRuleMapper.selectList(
+                new LambdaQueryWrapper<TrainPromotionRule>()
+                        .eq(TrainPromotionRule::getEnabled, 1)
+                        .eq(TrainPromotionRule::getDeleted, 0)
+                        .orderByAsc(TrainPromotionRule::getId));
+        for (TrainPractitionerProfile p : profiles) {
+            int cur = levelIndex(normLevel(p.getAuthLevel()));
+            for (TrainPromotionRule r : rules) {
+                int target = levelIndex(r.getAuthLevel());
+                if (target <= cur) {
+                    continue;
+                }
+                processed++;
+                try {
+                    Result<Map<String, Object>> res = self.evaluateAndRecord(p.getUserId(), r.getId());
+                    if (res != null && res.getData() != null
+                            && Boolean.TRUE.equals(res.getData().get("promoted"))) {
+                        granted++;
+                    }
+                } catch (Exception e) {
+                    log.warn("晋升评定异常跳过: userId={}, ruleId={}, err={}", p.getUserId(), r.getId(), e.getMessage());
+                }
+            }
+        }
+        log.info("晋升周期评定完成: processed={}, granted={}", processed, granted);
+        Map<String, Object> data = new HashMap<>();
+        data.put("processed", processed);
+        data.put("granted", granted);
+        return Result.success(data);
+    }
+
+    // ============ 内部工具 ============
+
+    private TrainPromotionRule enabledRule(String authLevel) {
+        return trainPromotionRuleMapper.selectOne(
+                new LambdaQueryWrapper<TrainPromotionRule>()
+                        .eq(TrainPromotionRule::getAuthLevel, authLevel)
+                        .eq(TrainPromotionRule::getEnabled, 1)
+                        .eq(TrainPromotionRule::getDeleted, 0)
+                        .orderByDesc(TrainPromotionRule::getVersion)
+                        .last("LIMIT 1"));
+    }
+
+    private TrainPractitionerProfile selectProfileByUserId(Long userId) {
+        return trainPractitionerProfileMapper.selectOne(
+                new LambdaQueryWrapper<TrainPractitionerProfile>()
+                        .eq(TrainPractitionerProfile::getUserId, userId)
+                        .last("LIMIT 1"));
+    }
+
+    /** 指标当前值(数值口径:serve_count=确认工单数;rating=评分*100 0-500;学时=effective 分钟) */
+    private long metricValue(Long userId, String metric) {
+        if (userId == null) {
+            return -1L;
+        }
+        if ("serve_count".equals(metric) || "order_count".equals(metric)) {
+            Long c = trainServiceOrderMapper.selectCount(
+                    new LambdaQueryWrapper<TrainServiceOrder>()
+                            .eq(TrainServiceOrder::getWorkerId, userId)
+                            .eq(TrainServiceOrder::getStatus, O_CONFIRMED));
+            return c == null ? 0 : c;
+        }
+        if ("rating".equals(metric)) {
+            TrainPractitionerProfile p = selectProfileByUserId(userId);
+            double rating = p == null || p.getRating() == null ? 0 : p.getRating();
+            return Math.round(rating * 100); // 0-500
+        }
+        if ("theory_hours".equals(metric)) {
+            return sumLedger(userId, CAT_THEORY);
+        }
+        if ("total_hours".equals(metric) || "credit_hours".equals(metric)) {
+            return sumLedger(userId, null);
+        }
+        if ("exam_score".equals(metric)) {
+            TrainEvalRecord e = trainEvalRecordMapper.selectOne(
+                    new LambdaQueryWrapper<TrainEvalRecord>()
+                            .eq(TrainEvalRecord::getUserId, userId)
+                            .eq(TrainEvalRecord::getEvalType, ET_TRAINING)
+                            .eq(TrainEvalRecord::getStatus, ST_VALID)
+                            .eq(TrainEvalRecord::getDeleted, 0)
+                            .orderByDesc(TrainEvalRecord::getCreatedAt)
+                            .last("LIMIT 1"));
+            return e == null || e.getScore() == null ? 0 : e.getScore();
+        }
+        return -1L;
+    }
+
+    private long sumLedger(Long userId, String category) {
+        LambdaQueryWrapper<TrainCreditLedger> q = new LambdaQueryWrapper<TrainCreditLedger>()
+                .eq(TrainCreditLedger::getUserId, userId)
+                .eq(TrainCreditLedger::getStatus, ST_EFFECTIVE)
+                .eq(TrainCreditLedger::getDeleted, 0);
+        if (category != null) {
+            q.eq(TrainCreditLedger::getSourceCategory, category);
+        }
+        List<TrainCreditLedger> list = trainCreditLedgerMapper.selectList(q);
+        long sum = 0;
+        for (TrainCreditLedger l : list) {
+            sum += l.getHours() == null ? 0 : l.getHours();
+        }
+        return sum;
+    }
+
+    private boolean compare(long current, String op, long value) {
+        switch (op) {
+            case ">=":
+                return current >= value;
+            case ">":
+                return current > value;
+            case "==":
+                return current == value;
+            case "<=":
+                return current <= value;
+            case "<":
+                return current < value;
+            default:
+                return false;
+        }
+    }
+
+    /** 遍历校验并归一 conditions(op 归一为符号) */
+    private List<Map<String, Object>> normalizeConditions(Object obj) {
+        List<Map<String, Object>> conds;
+        try {
+            if (obj instanceof String) {
+                conds = objectMapper.readValue((String) obj, new TypeReference<List<Map<String, Object>>>() {
+                });
+            } else if (obj instanceof List) {
+                conds = new ArrayList<>();
+                for (Object o : (List<?>) obj) {
+                    if (o instanceof Map) {
+                        @SuppressWarnings("unchecked")
+                        Map<String, Object> m = (Map<String, Object>) o;
+                        conds.add(m);
+                    }
+                }
+            } else {
+                return null;
+            }
+        } catch (Exception e) {
+            return null;
+        }
+        if (conds == null || conds.isEmpty()) {
+            return null;
+        }
+        List<Map<String, Object>> norm = new ArrayList<>();
+        for (Map<String, Object> c : conds) {
+            String metric = str(c.get("metric"));
+            String op = normOp(str(c.get("op")));
+            Long value = toLong(c.get("value"));
+            if (metric == null || !ALLOWED_METRICS.contains(metric) || op == null || value == null || value < 0) {
+                return null;
+            }
+            Map<String, Object> one = new HashMap<>();
+            one.put("metric", metric);
+            one.put("op", op);
+            one.put("value", value);
+            norm.add(one);
+        }
+        return norm;
+    }
+
+    private List<Map<String, Object>> parseConditions(String json) {
+        if (json == null || json.trim().isEmpty()) {
+            return null;
+        }
+        try {
+            return objectMapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {
+            });
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private String writeJson(Object o) {
+        try {
+            return objectMapper.writeValueAsString(o);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /** op 规整为符号比较符(兼容 ge/gt/eq/le/lt) */
+    private String normOp(String op) {
+        if (op == null) {
+            return null;
+        }
+        String o = op.trim();
+        if (">=".equals(o) || "ge".equalsIgnoreCase(o)) {
+            return ">=";
+        }
+        if (">".equals(o) || "gt".equalsIgnoreCase(o)) {
+            return ">";
+        }
+        if ("==".equals(o) || "eq".equalsIgnoreCase(o)) {
+            return "==";
+        }
+        if ("<=".equals(o) || "le".equalsIgnoreCase(o)) {
+            return "<=";
+        }
+        if ("<".equals(o) || "lt".equalsIgnoreCase(o)) {
+            return "<";
+        }
+        return null;
+    }
+
+    private String metricLabel(String metric) {
+        switch (metric) {
+            case "serve_count":
+            case "order_count":
+                return "接单量";
+            case "rating":
+                return "综合评分";
+            case "theory_hours":
+                return "理论学时";
+            case "total_hours":
+            case "credit_hours":
+                return "总学时";
+            case "exam_score":
+                return "考核成绩";
+            default:
+                return metric;
+        }
+    }
+
+    private int levelIndex(String lv) {
+        int idx = LV_ORDER.indexOf(lv);
+        return idx < 0 ? -1 : idx;
+    }
+
+    private String normLevel(String lv) {
+        if (lv == null || lv.trim().isEmpty()) {
+            return LV_NONE;
+        }
+        String u = lv.trim().toUpperCase();
+        return LV_ORDER.contains(u) ? u : LV_NONE;
+    }
+
+    private Map<String, Object> promptMap(String message, String authLevel) {
+        Map<String, Object> data = new HashMap<>();
+        data.put("eligible", false);
+        data.put("promoted", false);
+        data.put("authLevel", authLevel);
+        data.put("message", message);
+        data.put("unmet", new ArrayList<>());
+        return data;
+    }
+
+    private Map<String, Object> recordVO(TrainPromotionRecord r) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("recordId", r.getId());
+        m.put("id", r.getId()); // 兼容键:履历项 id(与 recordId 同值)
+        m.put("userId", r.getUserId());
+        m.put("authLevel", r.getAuthLevel());
+        m.put("title", (r.getAuthLevel() == null ? "" : r.getAuthLevel()) + " 讲师认证"); // 兼容键:展示标题
+        m.put("ruleId", r.getRuleId());
+        m.put("pass", r.getPass() != null && r.getPass() == 1);
+        m.put("unmet", parseUnmet(r.getUnmet()));
+        m.put("status", r.getStatus());
+        m.put("time", r.getAppliedAt()); // 兼容键:ISO 时间(与 appliedAt 同值)
+        m.put("desc", r.getStatus());    // 兼容键:状态文案(值域同 status)
+        m.put("appliedAt", r.getAppliedAt());
+        m.put("promotedAt", r.getPromotedAt());
+        m.put("createdAt", r.getCreatedAt());
+        return m;
+    }
+
+    private List<Map<String, Object>> parseUnmet(String json) {
+        if (json == null || json.trim().isEmpty()) {
+            return new ArrayList<>();
+        }
+        try {
+            return objectMapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {
+            });
+        } catch (Exception e) {
+            return new ArrayList<>();
+        }
+    }
+
+    private Map<String, Object> ruleVO(TrainPromotionRule r) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("ruleId", r.getId());
+        m.put("name", r.getName());
+        m.put("authLevel", r.getAuthLevel());
+        m.put("metric", r.getMetric());
+        m.put("operator", r.getOperator());
+        m.put("value", r.getValue());
+        m.put("conditions", parseConditions(r.getConditions()));
+        m.put("enabled", r.getEnabled() != null && r.getEnabled() == 1);
+        m.put("version", r.getVersion());
+        m.put("createdAt", r.getCreatedAt());
+        return m;
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            String s = v.toString().trim();
+            if (s.startsWith("+")) {
+                s = s.substring(1);
+            }
+            return Long.valueOf(s);
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private String str(Object v) {
+        return v == null ? null : v.toString().trim();
+    }
+
+    private boolean parseBool(Object v) {
+        if (v == null) {
+            return false;
+        }
+        if (v instanceof Boolean) {
+            return (Boolean) v;
+        }
+        String s = v.toString().trim().toLowerCase();
+        return "true".equals(s) || "1".equals(s) || "yes".equals(s);
+    }
+}

+ 2 - 0
train-backend/src/main/resources/application.yml

@@ -118,6 +118,8 @@ cfc:
 task:
   # 学时到期生效扫描 cron(默认每晚 04:00)
   credit-scan-cron: "${TASK_CREDIT_SCAN_CRON:0 0 4 * * ?}"
+  # 晋升规则周期评定扫描 cron(默认每日 04:30;与学时扫描错峰)
+  promotion-scan-cron: "${TASK_PROMOTION_SCAN_CRON:0 30 4 * * ?}"
 
 # Admin 登录配置
 admin: