package com.train.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.train.common.Result; import com.train.entity.TrainEvidencePack; import com.train.entity.TrainOrgMember; import com.train.mapper.TrainEvidencePackMapper; import com.train.mapper.TrainOrgMemberMapper; import com.train.service.EvidenceExportTask; import com.train.service.EvidenceService; import com.train.service.RoleGuard; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 证据包导出实现(M4)。 * * 归属解析规则: * - org 用户:默认导出「所属机构」范围(多个机构取第一个);管理员必须显式 body.orgId * - 非机构用户:个人范围(org_id=null,按 userId 过滤本人数据) */ @Slf4j @Service public class EvidenceServiceImpl implements EvidenceService { private static final String TYPE_TRAINING = "training"; private static final String TYPE_ORDER = "order"; private static final String ST_PENDING = "pending"; private static final String ST_FAILED = "failed"; private static final String ST_DONE = "done"; /** 契约错误码(对齐契约级单测,勿改名) */ private static final Integer C_SAME_KEY_DIFF_PAYLOAD = 4092; private static final Integer C_VERSION_CONFLICT = 422; private static final Integer C_NOT_FOUND = 404; private static final Integer C_FORBIDDEN = 403; @Resource private TrainEvidencePackMapper trainEvidencePackMapper; @Resource private TrainOrgMemberMapper trainOrgMemberMapper; @Resource private EvidenceExportTask evidenceExportTask; @Resource private RoleGuard roleGuard; /** * 导出请求幂等登记(进程内,按 userId+key 命名空间)。 * 异步导出请求在生成完成前需要可重放:同键同载荷复用原任务,同键异载荷 C4092。 */ private final ConcurrentHashMap idemCache = new ConcurrentHashMap<>(); @Override public Result> export(Long userId, Boolean isAdmin, Map body) { if (body == null || body.get("type") == null) { return Result.error("参数不完整:缺少 type"); } String type = body.get("type").toString().trim().toLowerCase(); if (!TYPE_TRAINING.equals(type) && !TYPE_ORDER.equals(type)) { return Result.error("type 仅支持 training/order"); } // 归属解析:显式指定他机构而非成员 → C403,禁止静默降级为个人范围 ScopeResolution resolution = resolveScope(userId, isAdmin, body); if (resolution.denied()) { return Result.error(C_FORBIDDEN, resolution.reason); } Long orgId = resolution.orgId; Map scope = new HashMap<>(); scope.put("type", type); if (orgId != null) { scope.put("orgId", orgId); } else { scope.put("scope", "mine"); } if (body.get("cohortId") != null) { scope.put("cohortId", body.get("cohortId")); } if (body.get("orderId") != null) { scope.put("orderId", body.get("orderId")); } String payload = payloadFingerprint(scope); // 幂等契约(body.key / body.replay 为 proxy 字符串契约,勿改名): // 同键同载荷重放 → 复用原任务;同键异载荷 → C4092,禁止静默新建第二条任务 String key = str(body.get("key")); boolean keyed = key != null && !key.trim().isEmpty(); String idemKey = keyed ? (userId + ":" + key.trim()) : null; if (keyed) { IdemRecord existing = idemCache.get(idemKey); if (existing != null) { if (!payload.equals(existing.payload)) { return Result.error(C_SAME_KEY_DIFF_PAYLOAD, "幂等键 " + key + " 载荷不一致,禁止新建导出任务"); } return Result.success(existing.data()); } } TrainEvidencePack pack = new TrainEvidencePack(); pack.setTaskNo(genTaskNo()); pack.setOrgUserId(userId); pack.setOrgId(orgId); pack.setType(type); pack.setScopeJson(scope.toString()); pack.setStatus(ST_PENDING); pack.setProgress(0); pack.setVersion(0L); pack.setCreatedAt(new Date()); pack.setUpdatedAt(new Date()); try { trainEvidencePackMapper.insert(pack); } catch (Exception e) { log.error("证据包任务创建失败: err={}", e.getMessage()); return Result.error("导出任务创建失败,请重试"); } Map data = new HashMap<>(); data.put("taskNo", pack.getTaskNo()); data.put("id", pack.getId()); data.put("status", ST_PENDING); if (keyed) { idemCache.putIfAbsent(idemKey, new IdemRecord(payload, data)); } // 异步生成(EvidenceExportTask @Async;失败由任务内兜底置 failed,不阻塞接口) evidenceExportTask.processExport(pack.getId()); return Result.success(data); } @Override public Result> status(Long userId, Boolean isAdmin, Map body) { if (body == null || body.get("taskNo") == null) { return Result.error("参数不完整:缺少 taskNo"); } String taskNo = body.get("taskNo").toString().trim(); TrainEvidencePack pack = trainEvidencePackMapper.selectOne( new LambdaQueryWrapper() .eq(TrainEvidencePack::getTaskNo, taskNo) .last("LIMIT 1")); if (pack == null) { return Result.error(C_NOT_FOUND, "导出任务不存在"); } // mustOwn:非 admin 只能查自己的任务 if (!Boolean.TRUE.equals(isAdmin) && userId != null && pack.getOrgUserId() != null && !userId.equals(pack.getOrgUserId())) { return Result.error(C_FORBIDDEN, "无权查看该导出任务"); } Map data = new HashMap<>(); data.put("taskNo", pack.getTaskNo()); data.put("id", pack.getId()); data.put("type", pack.getType()); data.put("status", pack.getStatus()); data.put("progress", pack.getProgress() == null ? 0 : pack.getProgress()); data.put("fileUrl", pack.getFileUrl()); data.put("error", pack.getError()); data.put("expireAt", pack.getExpireAt()); data.put("createdAt", pack.getCreatedAt()); return Result.success(data); } @Override public Result> adminList(Long userId, Boolean isAdmin, Map body) { if (!Boolean.TRUE.equals(isAdmin)) { return Result.error(C_FORBIDDEN, "需要管理员权限"); } int page = body == null ? 1 : toInt(body.get("page"), 1); int size = body == null ? 20 : toInt(body.get("size"), 20); if (page < 1) { page = 1; } if (size < 1) { size = 20; } if (size > 100) { size = 100; } String type = body == null ? null : str(body.get("type")); String status = body == null ? null : str(body.get("status")); LambdaQueryWrapper qw = new LambdaQueryWrapper<>(); if (type != null && !type.trim().isEmpty()) { qw.eq(TrainEvidencePack::getType, type.trim()); } if (status != null && !status.trim().isEmpty()) { qw.eq(TrainEvidencePack::getStatus, status.trim()); } Long total = trainEvidencePackMapper.selectCount(qw); if (total == null) { total = 0L; } int offset = (page - 1) * size; qw.orderByDesc(TrainEvidencePack::getCreatedAt).last("LIMIT " + offset + "," + size); List list = trainEvidencePackMapper.selectList(qw); Map result = new HashMap<>(); result.put("total", total); result.put("page", page); result.put("size", size); result.put("list", list); return Result.success(result); } @Override public Result retry(Long userId, Boolean isAdmin, Map body) { if (!Boolean.TRUE.equals(isAdmin)) { return Result.error(C_FORBIDDEN, "需要管理员权限"); } if (body == null || body.get("taskNo") == null) { return Result.error("参数不完整:缺少 taskNo"); } String taskNo = body.get("taskNo").toString().trim(); TrainEvidencePack pack = trainEvidencePackMapper.selectOne( new LambdaQueryWrapper() .eq(TrainEvidencePack::getTaskNo, taskNo) .last("LIMIT 1")); if (pack == null) { return Result.error(C_NOT_FOUND, "导出任务不存在"); } if (!ST_FAILED.equals(pack.getStatus()) && !ST_DONE.equals(pack.getStatus())) { return Result.error("当前状态不可重跑(仅 failed/done 可重新导出)"); } // 复位为 pending 后走同一 @Async 触发入口(EvidenceExportTask.processExport 以 pending 为门槛, // 内部 setProcessing 会推进到 processing;若直接置 processing 则该入口会跳过处理) pack.setStatus(ST_PENDING); pack.setProgress(0); pack.setError(null); pack.setFileUrl(null); pack.setVersion(pack.getVersion() == null ? 1L : pack.getVersion() + 1L); pack.setUpdatedAt(new Date()); int affected = trainEvidencePackMapper.updateById(pack); if (affected <= 0) { // 乐观锁冲突/并发丢失更新:影响 0 行,必须让调用方感知 C422,不得静默成功 return Result.error(C_VERSION_CONFLICT, "导出任务已被其他请求更新,请重试"); } evidenceExportTask.processExport(pack.getId()); return Result.success(true); } // ==================== 内部 ==================== private ScopeResolution resolveScope(Long userId, Boolean isAdmin, Map body) { Object orgIdObj = body.get("orgId"); if (orgIdObj != null) { Long orgId = toLong(orgIdObj); if (orgId == null) { return ScopeResolution.allow(null); // 非法 orgId:退化为个人范围(兼容既有行为) } if (Boolean.TRUE.equals(isAdmin)) { return ScopeResolution.allow(orgId); // admin 可导出任意机构 } // 显式导出他机构证据必须校验成员权;越权返回 C403,绝不静默降级为个人范围 String noAuth = roleGuard.requireOrgMemberAt(userId, orgId); if (noAuth != null) { return ScopeResolution.deny(noAuth); } return ScopeResolution.allow(orgId); } if (Boolean.TRUE.equals(isAdmin)) { return ScopeResolution.allow(null); } // 默认取发起人首个 active 机构 List members = trainOrgMemberMapper.selectList( new LambdaQueryWrapper() .eq(TrainOrgMember::getUserId, userId) .eq(TrainOrgMember::getStatus, "active") .eq(TrainOrgMember::getDeleted, 0) .orderByAsc(TrainOrgMember::getId)); if (members != null && !members.isEmpty()) { return ScopeResolution.allow(members.get(0).getOrgId()); } return ScopeResolution.allow(null); // 非机构用户 → 个人范围 } /** 稳定载荷指纹:HashMap.toString() 顺序不保证,按固定字段拼接供 C4092 判定。 */ private String payloadFingerprint(Map scope) { return str(scope.get("type")) + "|" + str(scope.get("orgId")) + "|" + str(scope.get("scope")) + "|" + str(scope.get("cohortId")) + "|" + str(scope.get("orderId")); } /** 归属解析结果:orgId 或越权原因(二选一)。 */ private static final class ScopeResolution { private final Long orgId; private final String reason; private ScopeResolution(Long orgId, String reason) { this.orgId = orgId; this.reason = reason; } static ScopeResolution allow(Long orgId) { return new ScopeResolution(orgId, null); } static ScopeResolution deny(String reason) { return new ScopeResolution(null, reason); } boolean denied() { return reason != null; } } /** 幂等登记:记录首次请求的载荷指纹与返回体,供 replay 原样复用。 */ private static final class IdemRecord { private final String payload; private final Map data; IdemRecord(String payload, Map data) { this.payload = payload; this.data = new HashMap<>(data); } Map data() { return new HashMap<>(data); } } private String genTaskNo() { return "EV" + new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (int) (Math.random() * 9000 + 1000); } private Long toLong(Object v) { if (v == null) { return null; } try { return Long.valueOf(v.toString().trim()); } catch (NumberFormatException e) { return null; } } private int toInt(Object v, int def) { if (v == null) { return def; } try { return Integer.parseInt(v.toString().trim()); } catch (NumberFormatException e) { return def; } } private String str(Object v) { return v == null ? null : v.toString(); } }