新增:查询页面快照并修复筛选选框闪烁

页面快照支持勾选查询条件、指标卡片、趋势、汇总表、不良构成和细分缺陷图,复制PNG或下载;增加取消、分阶段提示和等待超时恢复。

修复公共Select弹层准备帧被opacity覆盖导致的先闪出再展开,并取消查询字段原生label的重复点击转发。

同步已经验收上线的销售订单类型映射、排除筛选及预聚合,以及其线上权限、删除确认配套源码;保留既有公式编辑和名录编码修改。源码范围按发布清单冻结,不纳入本机数据、凭据及未发布工作。

验证:前后端独立源码构建通过;10项前端检查、4项订单分类单元测试通过;实际系统剪贴板粘贴PNG验证通过;线上配置及筛选结果与发布前一致,后端未重启。
This commit is contained in:
2026-11-04 00:15:32 +08:00
parent 54813accaa
commit c3354c1f64
106 changed files with 1678 additions and 353 deletions
@@ -30,10 +30,10 @@ public class ManagementController {
} }
@GetMapping("/tasks") @GetMapping("/tasks")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> tasks(@RequestParam(defaultValue = "50") int limit,@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> tasks(@RequestParam(defaultValue = "50") int limit,@AuthenticationPrincipal AppUserPrincipal actor) {
if (limit < 1 || limit > 200) throw new IllegalArgumentException("limit 必须为 1 到 200"); if (limit < 1 || limit > 200) throw new IllegalArgumentException("limit 必须为 1 到 200");
boolean all=actor.getRoleCodes().contains("SYSTEM_ADMIN")||actor.getRoleCodes().contains("SYSTEM_OPERATOR"); boolean all=actor.getRoleCodes().contains("SYSTEM_ADMIN");
List<Map<String, Object>> items = jdbc.query(""" List<Map<String, Object>> items = jdbc.query("""
SELECT id, task_type, status, stage, progress, processed, total, payload, result, SELECT id, task_type, status, stage, progress, processed, total, payload, result,
error_code, error_message, created_at, updated_at,retry_count,max_retries,next_retry_at,retry_parent_id,heartbeat_at error_code, error_message, created_at, updated_at,retry_count,max_retries,next_retry_at,retry_parent_id,heartbeat_at
@@ -44,10 +44,10 @@ public class ManagementController {
/** Read-only summaries; execution endpoints and their permissions remain independent. */ /** Read-only summaries; execution endpoints and their permissions remain independent. */
@GetMapping("/tasks/overview") @GetMapping("/tasks/overview")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> taskOverview(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> taskOverview(@AuthenticationPrincipal AppUserPrincipal actor) {
boolean allTasks=actor.getRoleCodes().contains("SYSTEM_ADMIN")||actor.getRoleCodes().contains("SYSTEM_OPERATOR"); boolean allTasks=actor.getRoleCodes().contains("SYSTEM_ADMIN");
boolean allWorkflows=actor.getRoleCodes().contains("SYSTEM_ADMIN")||actor.getRoleCodes().contains("DATA_PUBLISHER"); boolean allWorkflows=actor.getRoleCodes().contains("SYSTEM_ADMIN")||actor.getRoleCodes().contains("DATA_ADMIN");
String owner=actor.getId().toString(); String owner=actor.getId().toString();
List<Map<String,Object>> items=new java.util.ArrayList<>(jdbc.query(""" List<Map<String,Object>> items=new java.util.ArrayList<>(jdbc.query("""
SELECT id,task_type,status,stage,progress,processed,total,payload,error_code,error_message,created_at,updated_at SELECT id,task_type,status,stage,progress,processed,total,payload,error_code,error_message,created_at,updated_at
@@ -83,7 +83,7 @@ public class ManagementController {
} }
@GetMapping("/rules") @GetMapping("/rules")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER','QUALITY_VIEWER','BUSINESS_ANALYST','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> rules() { public Map<String, Object> rules() {
List<Map<String, Object>> items = jdbc.query(""" List<Map<String, Object>> items = jdbc.query("""
SELECT id, name, status, description, rule_definition, validation, row_version, created_at SELECT id, name, status, description, rule_definition, validation, row_version, created_at
@@ -104,7 +104,7 @@ public class ManagementController {
} }
@GetMapping("/mappings") @GetMapping("/mappings")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER','QUALITY_VIEWER','BUSINESS_ANALYST','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
@org.springframework.transaction.annotation.Transactional(readOnly = true) @org.springframework.transaction.annotation.Transactional(readOnly = true)
public Map<String, Object> mappings() { public Map<String, Object> mappings() {
List<Map<String, Object>> items = jdbc.query(""" List<Map<String, Object>> items = jdbc.query("""
@@ -142,7 +142,7 @@ public class ManagementController {
} }
@GetMapping("/audit") @GetMapping("/audit")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String, Object> audit(@RequestParam(defaultValue = "1") int page, public Map<String, Object> audit(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "50") int pageSize) { @RequestParam(defaultValue = "50") int pageSize) {
if (page < 1 || pageSize < 1 || pageSize > 200) throw new IllegalArgumentException("分页参数无效"); if (page < 1 || pageSize < 1 || pageSize > 200) throw new IllegalArgumentException("分页参数无效");
@@ -171,7 +171,7 @@ public class ManagementController {
public Map<String, Object> users() { public Map<String, Object> users() {
List<UserRow> users = jdbc.query(""" List<UserRow> users = jdbc.query("""
SELECT id, username, display_name, active, force_password_change, row_version, created_at SELECT id, username, display_name, active, force_password_change, row_version, created_at
FROM app_user ORDER BY username FROM app_user WHERE deleted_at IS NULL ORDER BY username
""", (rs, row) -> new UserRow(UUID.fromString(rs.getString("id")), rs.getString("username"), """, (rs, row) -> new UserRow(UUID.fromString(rs.getString("id")), rs.getString("username"),
rs.getString("display_name"), rs.getBoolean("active"), rs.getBoolean("force_password_change"), rs.getString("display_name"), rs.getBoolean("active"), rs.getBoolean("force_password_change"),
rs.getLong("row_version"), rs.getTimestamp("created_at").toInstant().toString())); rs.getLong("row_version"), rs.getTimestamp("created_at").toInstant().toString()));
@@ -21,6 +21,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -31,8 +32,6 @@ import org.springframework.web.server.ResponseStatusException;
@RestController @RestController
@RequestMapping("/api") @RequestMapping("/api")
public class ManagementMutationController { public class ManagementMutationController {
private static final Set<String> ROLES = Set.of("SYSTEM_ADMIN", "SYSTEM_OPERATOR", "DATA_MAINTAINER", "DATA_PUBLISHER",
"RULE_MAINTAINER", "QUALITY_VIEWER", "BUSINESS_ANALYST", "AUDIT_VIEWER");
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final JsonMapper json; private final JsonMapper json;
private final PasswordEncoder encoder; private final PasswordEncoder encoder;
@@ -93,7 +92,7 @@ public class ManagementMutationController {
if (!targetWillBeAdmin && (activeOtherAdmins == null || activeOtherAdmins == 0)) throw conflict("至少保留一个启用的系统管理员"); if (!targetWillBeAdmin && (activeOtherAdmins == null || activeOtherAdmins == 0)) throw conflict("至少保留一个启用的系统管理员");
int updated = jdbc.update(""" int updated = jdbc.update("""
UPDATE app_user SET display_name=?,active=?,force_password_change=?,row_version=row_version+1 UPDATE app_user SET display_name=?,active=?,force_password_change=?,row_version=row_version+1
WHERE id=? AND row_version=? WHERE id=? AND row_version=? AND deleted_at IS NULL
""", displayName, request.active(), request.forcePasswordChange(), userId.toString(), request.expectedRowVersion()); """, displayName, request.active(), request.forcePasswordChange(), userId.toString(), request.expectedRowVersion());
if (updated == 0) throw conflict("用户版本已变化,请刷新后重试"); if (updated == 0) throw conflict("用户版本已变化,请刷新后重试");
jdbc.update("DELETE FROM app_user_role WHERE user_id=?", userId.toString()); jdbc.update("DELETE FROM app_user_role WHERE user_id=?", userId.toString());
@@ -106,12 +105,45 @@ public class ManagementMutationController {
return user(userId.toString()); return user(userId.toString());
} }
@DeleteMapping("/users/{id}")
@PreAuthorize("hasRole('SYSTEM_ADMIN')")
@Transactional
public Map<String, Object> deleteUser(@PathVariable String id, @RequestBody UserDeleteRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) {
UUID userId = parseId(id);
if (request.expectedRowVersion() == null || request.expectedRowVersion() < 0) throw bad("expectedRowVersion 为必填");
if (userId.equals(actor.getId())) throw conflict("不能删除当前登录账号");
// Use the same lock order as account editing so concurrent changes cannot remove all administrators.
jdbc.query("""
SELECT u.id FROM app_user u JOIN app_user_role r ON r.user_id=u.id
WHERE u.active=TRUE AND r.role_code='SYSTEM_ADMIN' FOR UPDATE
""", (rs, row) -> rs.getString(1));
List<Map<String, Object>> targets = jdbc.query("""
SELECT username,row_version FROM app_user WHERE id=? AND deleted_at IS NULL FOR UPDATE
""", (rs, row) -> Map.<String, Object>of("username", rs.getString("username"), "rowVersion", rs.getLong("row_version")), userId.toString());
if (targets.isEmpty()) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在或已删除");
Map<String, Object> target = targets.getFirst();
if (((Number) target.get("rowVersion")).longValue() != request.expectedRowVersion()) throw conflict("用户版本已变化,请刷新后重试");
Integer otherAdmins = jdbc.queryForObject("""
SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id
WHERE u.active=TRUE AND r.role_code='SYSTEM_ADMIN' AND u.id<>?
""", Integer.class, userId.toString());
if (otherAdmins == null || otherAdmins == 0) throw conflict("至少保留一个启用的系统管理员");
jdbc.update("""
UPDATE app_user SET active=FALSE,deleted_at=CURRENT_TIMESTAMP(6),row_version=row_version+1
WHERE id=? AND row_version=? AND deleted_at IS NULL
""", userId.toString(), request.expectedRowVersion());
audit(actor.getId().toString(), "USER_DELETED", "app_user", userId.toString(),
Map.of("username", target.get("username"), "historyRetained", true));
return Map.of("deleted", true, "id", userId.toString());
}
@GetMapping("/rules/schema") @GetMapping("/rules/schema")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_ADMIN')")
public Map<String,Object> ruleSchema(){return cn.yunsheng.quality.ingestion.ConfigurableRuleEngine.schema();} public Map<String,Object> ruleSchema(){return cn.yunsheng.quality.ingestion.ConfigurableRuleEngine.schema();}
@PostMapping("/rules") @PostMapping("/rules")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
@Transactional @Transactional
public Map<String, Object> createRule(@RequestBody VersionDraft request, public Map<String, Object> createRule(@RequestBody VersionDraft request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -125,7 +157,7 @@ public class ManagementMutationController {
} }
@PutMapping("/rules/{id}") @PutMapping("/rules/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
@Transactional @Transactional
public Map<String, Object> updateRule(@PathVariable String id, @RequestBody VersionDraft request, public Map<String, Object> updateRule(@PathVariable String id, @RequestBody VersionDraft request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -142,7 +174,7 @@ public class ManagementMutationController {
} }
@PostMapping("/rules/{id}/validate") @PostMapping("/rules/{id}/validate")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
@Transactional @Transactional
public Map<String, Object> validateRule(@PathVariable String id, @RequestBody VersionAction request, public Map<String, Object> validateRule(@PathVariable String id, @RequestBody VersionAction request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -159,7 +191,7 @@ public class ManagementMutationController {
} }
@PostMapping("/rules/{id}/activate") @PostMapping("/rules/{id}/activate")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
@Transactional @Transactional
public Map<String, Object> activateRule(@PathVariable String id, @RequestBody VersionAction request, public Map<String, Object> activateRule(@PathVariable String id, @RequestBody VersionAction request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -186,7 +218,7 @@ public class ManagementMutationController {
} }
@PostMapping("/mappings") @PostMapping("/mappings")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
@Transactional @Transactional
public Map<String, Object> createMapping(@RequestBody VersionDraft request, public Map<String, Object> createMapping(@RequestBody VersionDraft request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -201,7 +233,7 @@ public class ManagementMutationController {
} }
@PutMapping("/mappings/{id}") @PutMapping("/mappings/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
@Transactional @Transactional
public Map<String, Object> updateMapping(@PathVariable String id, @RequestBody VersionDraft request, public Map<String, Object> updateMapping(@PathVariable String id, @RequestBody VersionDraft request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -219,7 +251,7 @@ public class ManagementMutationController {
} }
@PostMapping("/mappings/{id}/validate") @PostMapping("/mappings/{id}/validate")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
@Transactional @Transactional
public Map<String, Object> validateMapping(@PathVariable String id, @RequestBody VersionAction request, public Map<String, Object> validateMapping(@PathVariable String id, @RequestBody VersionAction request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -244,7 +276,7 @@ public class ManagementMutationController {
} }
@PostMapping("/mappings/{id}/activate") @PostMapping("/mappings/{id}/activate")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
@Transactional @Transactional
public Map<String, Object> activateMapping(@PathVariable String id, @RequestBody VersionAction request, public Map<String, Object> activateMapping(@PathVariable String id, @RequestBody VersionAction request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -314,10 +346,7 @@ public class ManagementMutationController {
} }
private List<String> validateRoles(List<String> values) { private List<String> validateRoles(List<String> values) {
if (values == null || values.isEmpty()) throw bad("至少选择一个角色"); return cn.yunsheng.quality.identity.AppRoles.validate(values);
List<String> roles = values.stream().distinct().sorted().toList();
if (!ROLES.containsAll(roles)) throw bad("包含不支持的角色");
return roles;
} }
private List<String> normalizeScopes(List<String> values, String kind) { private List<String> normalizeScopes(List<String> values, String kind) {
@@ -449,6 +478,7 @@ public class ManagementMutationController {
List<String> departments, List<String> groups) {} List<String> departments, List<String> groups) {}
public record UserUpdateRequest(String displayName, boolean active, boolean forcePasswordChange, List<String> roles, public record UserUpdateRequest(String displayName, boolean active, boolean forcePasswordChange, List<String> roles,
List<String> departments, List<String> groups, Long expectedRowVersion) {} List<String> departments, List<String> groups, Long expectedRowVersion) {}
public record UserDeleteRequest(Long expectedRowVersion) {}
public record VersionDraft(String id, String name, String description, Object definition, Long expectedRowVersion) {} public record VersionDraft(String id, String name, String description, Object definition, Long expectedRowVersion) {}
public record VersionAction(Long expectedRowVersion,Boolean confirmDifferences,String regressionRunId) { public record VersionAction(Long expectedRowVersion,Boolean confirmDifferences,String regressionRunId) {
public VersionAction(Long expectedRowVersion){this(expectedRowVersion,false,null);} public VersionAction(Long expectedRowVersion){this(expectedRowVersion,false,null);}
@@ -40,14 +40,14 @@ public class TaskActionController {
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> get(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> get(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor) {
authorize(id,actor); authorize(id,actor);
return Map.of("task", task(id)); return Map.of("task", task(id));
} }
@GetMapping("/{id}/issues") @GetMapping("/{id}/issues")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> issues(@PathVariable String id,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="100") int pageSize,@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> issues(@PathVariable String id,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="100") int pageSize,@AuthenticationPrincipal AppUserPrincipal actor) {
authorize(id,actor);access.requireDetail(actor);if(page<1||pageSize<1||pageSize>500)throw new IllegalArgumentException("分页参数无效"); authorize(id,actor);access.requireDetail(actor);if(page<1||pageSize<1||pageSize>500)throw new IllegalArgumentException("分页参数无效");
Map<String, Object> task = task(id); Map<String, Object> task = task(id);
@@ -72,14 +72,14 @@ public class TaskActionController {
} }
@PostMapping("/{id}/retry") @PostMapping("/{id}/retry")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> retry(@PathVariable String id, @RequestBody RetryRequest request, public Map<String, Object> retry(@PathVariable String id, @RequestBody RetryRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return retryService.retry(id,request.idempotencyKey(),request.expectedCurrentReleaseId(),actor); return retryService.retry(id,request.idempotencyKey(),request.expectedCurrentReleaseId(),actor);
} }
@PostMapping("/{id}/cancel") @PostMapping("/{id}/cancel")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
@Transactional @Transactional
public Map<String, Object> cancel(@PathVariable String id, @RequestBody CancelRequest request, public Map<String, Object> cancel(@PathVariable String id, @RequestBody CancelRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -123,7 +123,7 @@ public class TaskActionController {
if (rows.isEmpty()) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "任务不存在"); if (rows.isEmpty()) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "任务不存在");
return rows.getFirst(); return rows.getFirst();
} }
private void authorize(String id,AppUserPrincipal actor){String owner=jdbc.queryForObject("SELECT created_by FROM task WHERE id=?",String.class,id);if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!actor.getRoleCodes().contains("SYSTEM_OPERATOR")&&!java.util.Objects.equals(owner,actor.getId().toString()))throw new ResponseStatusException(HttpStatus.FORBIDDEN,"无权访问该任务");} private void authorize(String id,AppUserPrincipal actor){String owner=jdbc.queryForObject("SELECT created_by FROM task WHERE id=?",String.class,id);if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!java.util.Objects.equals(owner,actor.getId().toString()))throw new ResponseStatusException(HttpStatus.FORBIDDEN,"无权访问该任务");}
private Object parse(String value) { private Object parse(String value) {
if (value == null) return Map.of(); if (value == null) return Map.of();
@@ -20,7 +20,7 @@ public class AnalysisChangesController {
} }
@PostMapping("/changes") @PostMapping("/changes")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> query(@RequestBody Map<String, Object> body, public Map<String, Object> query(@RequestBody Map<String, Object> body,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return changes.query(body, actor); return changes.query(body, actor);
@@ -41,7 +41,7 @@ import tools.jackson.databind.json.JsonMapper;
/** AI never computes a KPI or changes data; every tool call uses the shared metric service and current identity. */ /** AI never computes a KPI or changes data; every tool call uses the shared metric service and current identity. */
@RestController @RestController
@RequestMapping("/api/analysis") @RequestMapping("/api/analysis")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public class AnalysisController { public class AnalysisController {
private final MetricsService metrics; private final MetricsService metrics;
private final AnalysisModelGateway model; private final AnalysisModelGateway model;
@@ -23,7 +23,7 @@ public class AnalysisFineDefectsController {
} }
@PostMapping @PostMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> query(@RequestBody(required = false) Map<String, Object> request, public Map<String, Object> query(@RequestBody(required = false) Map<String, Object> request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
governance.requireDetail(actor); governance.requireDetail(actor);
@@ -122,6 +122,7 @@ public class AnalysisFineDefectsService {
&& isAllowed(category.componentCode(), allowed)) componentCodes.add(category.componentCode()); && isAllowed(category.componentCode(), allowed)) componentCodes.add(category.componentCode());
} }
Aggregator aggregate = new Aggregator(request, visibleFields, categories, componentCodes, json); Aggregator aggregate = new Aggregator(request, visibleFields, categories, componentCodes, json);
Aggregator complement = exclusionComplement(request, input, releaseId, actor, allowed, visibleFields, categories, componentCodes, predicate, args);
if (rollups != null && request.dimension().equals("defect") && request.extraFilters().isEmpty() if (rollups != null && request.dimension().equals("defect") && request.extraFilters().isEmpty()
&& (!(input.get("columnFilters") instanceof List<?> filters) || filters.isEmpty()) && (!(input.get("columnFilters") instanceof List<?> filters) || filters.isEmpty())
&& rollups.read(aggregate, request, allowed, predicate.toString(), args)) { && rollups.read(aggregate, request, allowed, predicate.toString(), args)) {
@@ -150,7 +151,43 @@ public class AnalysisFineDefectsService {
} }
return null; return null;
}); });
return withScope(aggregate.response(request, release), scopeContext); if (complement != null) complement.subtract(aggregate);
return withScope((complement == null ? aggregate : complement).response(request, release), scopeContext);
}
/** Exact counters allow subtracting a small excluded set without rescanning all retained raw JSON. */
private Aggregator exclusionComplement(Request request, Map<String,Object> input, String releaseId, AppUserPrincipal actor,
Set<String> allowed, List<DefectField> fields, List<Category> categories, Set<String> components,
StringBuilder predicate, List<Object> args) {
String key = cn.yunsheng.quality.filters.SalesOrderTypes.EXCLUDE_KEY;
if (rollups == null || !request.dimension().equals("defect") || !request.extraFilters().keySet().equals(Set.of(key))
|| (input.get("columnFilters") instanceof List<?> filters && !filters.isEmpty())) return null;
var typed = new cn.yunsheng.quality.metrics.SalesOrderMetricRollups(jdbc);
if (!typed.ready(releaseId, request.extraFilters(), false, allowed)) return null;
var baseInput = new LinkedHashMap<>(input); baseInput.remove("extraFilters");
Request base = parse(baseInput, allowed);
var baseWhere = new StringBuilder(" WHERE rm.release_id = ?");
var baseArgs = new ArrayList<Object>(); baseArgs.add(releaseId);
appendScope(baseWhere, baseArgs, base, baseInput, releaseId, actor);
if (request.productSearch() != null) { baseWhere.append(" AND LOCATE(LOWER(?), LOWER(COALESCE(f.product,''))) > 0"); baseArgs.add(request.productSearch()); }
var countWhere = new StringBuilder(baseWhere); var countArgs = new ArrayList<>(baseArgs);
countWhere.append(" AND f.stage=?"); countArgs.add(request.stage());
typed.append(countWhere, countArgs, Map.of());
String countSql = "SELECT COALESCE(SUM(f.source_row_count),0) FROM release_member rm JOIN sales_order_metric_rollup f ON f.build_id=rm.transform_build_id";
Long total = jdbc.queryForObject(countSql+countWhere, Long.class, countArgs.toArray());
var retainedWhere = new StringBuilder(countWhere); var retainedArgs = new ArrayList<>(countArgs);
typed.append(retainedWhere, retainedArgs, request.extraFilters());
Long retained = jdbc.queryForObject(countSql+retainedWhere, Long.class, retainedArgs.toArray());
if (total == null || retained == null || total-retained > retained) return null;
var all = new Aggregator(request, fields, categories, components, json);
if (!rollups.read(all, request, allowed, baseWhere.toString(), baseArgs)) return null;
var selectedInput = new LinkedHashMap<>(input);
selectedInput.put("extraFilters",Map.of(cn.yunsheng.quality.filters.SalesOrderTypes.KEY,request.extraFilters().get(key)));
Request selected = parse(selectedInput, allowed);
predicate.setLength(0); predicate.append(" WHERE rm.release_id = ?"); args.clear(); args.add(releaseId);
appendScope(predicate, args, selected, selectedInput, releaseId, actor);
if (request.productSearch() != null) { predicate.append(" AND LOCATE(LOWER(?), LOWER(COALESCE(f.product,''))) > 0"); args.add(request.productSearch()); }
return all;
} }
private static boolean hasExtendedScope(Map<String, Object> input) { private static boolean hasExtendedScope(Map<String, Object> input) {
@@ -502,6 +539,19 @@ public class AnalysisFineDefectsService {
} }
} }
void subtract(Aggregator excluded) {
if (excluded.sourceRows > sourceRows) throw new IllegalStateException("排除行数超过来源行数");
sourceRows -= excluded.sourceRows;
for (var entry : excluded.fieldStats.entrySet()) subtractStats(fieldStats.get(entry.getKey()), entry.getValue());
for (var entry : excluded.componentStats.entrySet()) subtractStats(componentStats.get(entry.getKey()), entry.getValue());
excluded.expectedRows.forEach((key,value)->expectedRows.merge(key,-value,Long::sum));
excluded.expectedWeights.forEach((key,value)->expectedWeights.merge(key,value.negate(),BigDecimal::add));
}
private static void subtractStats(FieldStats total, FieldStats excluded) {
total.sum=total.sum.subtract(excluded.sum); total.presentRows-=excluded.presentRows;
total.missingRows-=excluded.missingRows; total.invalidRows-=excluded.invalidRows; total.negativeRows-=excluded.negativeRows;
}
Map<String, Object> response(Request request, Map<String, Object> release) { Map<String, Object> response(Request request, Map<String, Object> release) {
List<Map<String, Object>> rows = new ArrayList<>(request.dimension().equals("defect") ? defectRows() : productRows()); List<Map<String, Object>> rows = new ArrayList<>(request.dimension().equals("defect") ? defectRows() : productRows());
rows.sort(Comparator.<Map<String, Object>, BigDecimal>comparing(row -> (BigDecimal) row.get("weight"), rows.sort(Comparator.<Map<String, Object>, BigDecimal>comparing(row -> (BigDecimal) row.get("weight"),
@@ -18,7 +18,7 @@ public class AnalysisInvestigationController {
this.access = access; this.access = access;
} }
@PostMapping @PostMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String,Object> query(@RequestBody Map<String,Object> request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String,Object> query(@RequestBody Map<String,Object> request, @AuthenticationPrincipal AppUserPrincipal actor) {
// Bound service checks can lock their identity row; keep them outside the read-only scan transaction. // Bound service checks can lock their identity row; keep them outside the read-only scan transaction.
access.requireBoundAction("QUERY", "query.detail"); access.requireBoundAction("QUERY", "query.detail");
@@ -37,7 +37,7 @@ public class AnalysisReportService {
private static final int MAX_DUE_PLANS_PER_TICK = 10; private static final int MAX_DUE_PLANS_PER_TICK = 10;
private static final int MAX_REPORT_SUBMISSIONS_PER_TICK = 10; private static final int MAX_REPORT_SUBMISSIONS_PER_TICK = 10;
private static final long REPORT_LEASE_MINUTES = 5; private static final long REPORT_LEASE_MINUTES = 5;
private static final Set<String> READER_ROLES = Set.of("SYSTEM_ADMIN", "QUALITY_VIEWER", "BUSINESS_ANALYST"); private static final Set<String> READER_ROLES = Set.of("SYSTEM_ADMIN", "DATA_ADMIN", "USER");
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final AnalysisTurnService turns; private final AnalysisTurnService turns;
private final JdbcAppUserDetailsService users; private final JdbcAppUserDetailsService users;
@@ -17,7 +17,7 @@ import org.springframework.web.bind.annotation.RestController;
/** Periodic reports are exposed alongside the analysis turns they create. */ /** Periodic reports are exposed alongside the analysis turns they create. */
@RestController @RestController
@RequestMapping("/api/analysis") @RequestMapping("/api/analysis")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public class AnalysisReportsController { public class AnalysisReportsController {
private final AnalysisReportService reports; private final AnalysisReportService reports;
@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.*;
/** Authorized source schema and projected member lists; never accepts SQL. */ /** Authorized source schema and projected member lists; never accepts SQL. */
@RestController @RestController
@RequestMapping("/api/analysis/source") @RequestMapping("/api/analysis/source")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public class AnalysisSourceQueryController { public class AnalysisSourceQueryController {
private final SourceColumnQueries columns; private final SourceColumnQueries columns;
private final ReleaseService releases; private final ReleaseService releases;
@@ -11,7 +11,7 @@ import org.springframework.web.server.ResponseStatusException;
@RestController @RestController
@RequestMapping("/api/analysis/tools") @RequestMapping("/api/analysis/tools")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public class AnalysisToolsController { public class AnalysisToolsController {
private final AnalysisExplorationTools tools; private final AnalysisExplorationTools tools;
public AnalysisToolsController(AnalysisExplorationTools tools) { this.tools = tools; } public AnalysisToolsController(AnalysisExplorationTools tools) { this.tools = tools; }
@@ -17,7 +17,7 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/** Durable, cancellable AI turns; model tools are limited to server-side metrics queries. */ /** Durable, cancellable AI turns; model tools are limited to server-side metrics queries. */
@RestController @RestController
@RequestMapping("/api/analysis") @RequestMapping("/api/analysis")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public class AnalysisTurnsController { public class AnalysisTurnsController {
private final AnalysisTurnService turns; private final AnalysisTurnService turns;
public AnalysisTurnsController(AnalysisTurnService turns) { this.turns = turns; } public AnalysisTurnsController(AnalysisTurnService turns) { this.turns = turns; }
@@ -14,8 +14,10 @@ public final class AuthorizationFingerprint {
public static String of(AppUserPrincipal user, GovernanceAccessService governance) { public static String of(AppUserPrincipal user, GovernanceAccessService governance) {
Map<String, Object> policy = governance.policy(user.getId().toString()); Map<String, Object> policy = governance.policy(user.getId().toString());
List<String> roles = governance.fingerprintRoles(user);
if (roles == null || roles.isEmpty()) roles = user.getRoleCodes();
List<String> values = List.of( List<String> values = List.of(
String.join(",", user.getRoleCodes().stream().sorted().toList()), String.join(",", roles.stream().sorted().toList()),
String.join(",", user.getDepartments().stream().sorted().toList()), String.join(",", user.getDepartments().stream().sorted().toList()),
String.join(",", user.getGroups().stream().sorted().toList()), String.join(",", user.getGroups().stream().sorted().toList()),
String.join(",", governance.allowedFields(user).stream().sorted().toList()), String.join(",", governance.allowedFields(user).stream().sorted().toList()),
@@ -71,7 +71,7 @@ public class AnalyticsController {
return top(stage, dimension, category, releaseId, year, month, quarter, department, group, product, projectGroup, includeUnassigned, limit, extraFilters, null, actor); return top(stage, dimension, category, releaseId, year, month, quarter, department, group, product, projectGroup, includeUnassigned, limit, extraFilters, null, actor);
} }
@GetMapping("/top") @GetMapping("/top")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> top(@RequestParam String stage, public Map<String, Object> top(@RequestParam String stage,
@RequestParam(defaultValue = "category") String dimension, @RequestParam(defaultValue = "category") String dimension,
@RequestParam(required = false) String category, @RequestParam(required = false) String category,
@@ -209,7 +209,7 @@ public class AnalyticsController {
} }
@PostMapping("/compare") @PostMapping("/compare")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> compare(@RequestBody CompareRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> compare(@RequestBody CompareRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
requireQueryDetail(actor); requireQueryDetail(actor);
if (request == null || request.current() == null || request.comparison() == null) throw bad("current 与 comparison 两组条件必填"); if (request == null || request.current() == null || request.comparison() == null) throw bad("current 与 comparison 两组条件必填");
@@ -284,7 +284,7 @@ public class AnalyticsController {
/** Per-object impact for a single stage. Contributions are returned only for a complete, exclusive partition. */ /** Per-object impact for a single stage. Contributions are returned only for a complete, exclusive partition. */
@PostMapping("/impact") @PostMapping("/impact")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> impact(@RequestBody ImpactRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> impact(@RequestBody ImpactRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
requireQueryDetail(actor); requireQueryDetail(actor);
if (request == null || request.current() == null || request.comparison() == null) throw bad("current 与 comparison 两组条件必填"); if (request == null || request.current() == null || request.comparison() == null) throw bad("current 与 comparison 两组条件必填");
@@ -389,7 +389,7 @@ public class AnalyticsController {
} }
@PostMapping("/structure-decomposition") @PostMapping("/structure-decomposition")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> decompose(@RequestBody DecompositionRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> decompose(@RequestBody DecompositionRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
requireQueryDetail(actor); requireQueryDetail(actor);
if (request == null || request.current() == null || request.comparison() == null) throw bad("current 与 comparison 两组条件必填"); if (request == null || request.current() == null || request.comparison() == null) throw bad("current 与 comparison 两组条件必填");
@@ -40,7 +40,7 @@ public class ChecklistsController {
} }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> list(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> list(@AuthenticationPrincipal AppUserPrincipal actor) {
requireQueryDetail(actor); requireQueryDetail(actor);
List<Map<String, Object>> items = jdbc.query("SELECT id,title,row_version,created_at,updated_at FROM analysis_checklist WHERE owner_user_id=? ORDER BY updated_at DESC", List<Map<String, Object>> items = jdbc.query("SELECT id,title,row_version,created_at,updated_at FROM analysis_checklist WHERE owner_user_id=? ORDER BY updated_at DESC",
@@ -50,7 +50,7 @@ public class ChecklistsController {
} }
@PostMapping @PostMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> create(@RequestBody CreateRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> create(@RequestBody CreateRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
requireQueryDetail(actor); requireQueryDetail(actor);
if (request == null || request.title() == null || request.title().isBlank() || request.title().length() > 190) throw bad("核查清单名称无效"); if (request == null || request.title() == null || request.title().isBlank() || request.title().length() > 190) throw bad("核查清单名称无效");
@@ -60,7 +60,7 @@ public class ChecklistsController {
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> open(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> open(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) {
Checklist checklist = requireOwned(id, actor); Checklist checklist = requireOwned(id, actor);
requireQueryDetail(actor); requireQueryDetail(actor);
@@ -96,7 +96,7 @@ public class ChecklistsController {
} }
@PostMapping("/{id}/items") @PostMapping("/{id}/items")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> addItem(@PathVariable String id, @RequestBody ItemRequest request, public Map<String, Object> addItem(@PathVariable String id, @RequestBody ItemRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
if (request == null) throw bad("核查项内容必填"); if (request == null) throw bad("核查项内容必填");
@@ -139,7 +139,7 @@ public class ChecklistsController {
} }
@DeleteMapping("/{id}/items/{itemId}") @DeleteMapping("/{id}/items/{itemId}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> removeItem(@PathVariable String id, @PathVariable String itemId, public Map<String, Object> removeItem(@PathVariable String id, @PathVariable String itemId,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
requireQueryDetail(actor); requireQueryDetail(actor);
@@ -24,7 +24,7 @@ import org.springframework.web.server.ResponseStatusException;
/** Recipient ACLs are valid only while both users retain the authorization captured at grant time. */ /** Recipient ACLs are valid only while both users retain the authorization captured at grant time. */
@Service @Service
public class ComparisonViewSharingService { public class ComparisonViewSharingService {
private static final Set<String> VIEW_ROLES = Set.of("SYSTEM_ADMIN", "QUALITY_VIEWER", "BUSINESS_ANALYST"); private static final Set<String> VIEW_ROLES = Set.of("SYSTEM_ADMIN", "DATA_ADMIN", "USER");
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final GovernanceAccessService governance; private final GovernanceAccessService governance;
@@ -49,7 +49,7 @@ public class ComparisonViewSharingService {
SELECT DISTINCT u.id, u.username, u.display_name SELECT DISTINCT u.id, u.username, u.display_name
FROM app_user u JOIN app_user_role r ON r.user_id=u.id FROM app_user u JOIN app_user_role r ON r.user_id=u.id
WHERE u.active=TRUE AND u.id<>? WHERE u.active=TRUE AND u.id<>?
AND r.role_code IN ('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST') AND r.role_code IN ('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')
ORDER BY u.display_name, u.id ORDER BY u.display_name, u.id
""", (rs, n) -> new Candidate(rs.getString("id"), rs.getString("username"), rs.getString("display_name")), """, (rs, n) -> new Candidate(rs.getString("id"), rs.getString("username"), rs.getString("display_name")),
owner.getId().toString()); owner.getId().toString());
@@ -48,7 +48,7 @@ public class ComparisonViewsController {
} }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> list(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> list(@AuthenticationPrincipal AppUserPrincipal actor) {
actor = sharing.currentAuthorized(actor); actor = sharing.currentAuthorized(actor);
requireQueryDetail(actor); requireQueryDetail(actor);
@@ -64,7 +64,7 @@ public class ComparisonViewsController {
} }
@PostMapping @PostMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> create(@RequestBody ViewRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> create(@RequestBody ViewRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
actor = sharing.currentAuthorized(actor); actor = sharing.currentAuthorized(actor);
requireQueryDetail(actor); requireQueryDetail(actor);
@@ -76,7 +76,7 @@ public class ComparisonViewsController {
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> get(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> get(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) {
actor = sharing.currentAuthorized(actor); actor = sharing.currentAuthorized(actor);
requireQueryDetail(actor); requireQueryDetail(actor);
@@ -84,7 +84,7 @@ public class ComparisonViewsController {
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> update(@PathVariable String id, @RequestBody ViewRequest request, public Map<String, Object> update(@PathVariable String id, @RequestBody ViewRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
actor = sharing.currentAuthorized(actor); actor = sharing.currentAuthorized(actor);
@@ -100,7 +100,7 @@ public class ComparisonViewsController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> delete(@PathVariable String id, @RequestParam(required = false) Long expectedRowVersion, public Map<String, Object> delete(@PathVariable String id, @RequestParam(required = false) Long expectedRowVersion,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
actor = sharing.currentAuthorized(actor); actor = sharing.currentAuthorized(actor);
@@ -114,7 +114,7 @@ public class ComparisonViewsController {
} }
@PostMapping("/{id}/open") @PostMapping("/{id}/open")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> open(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> open(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) {
actor = sharing.currentAuthorized(actor); actor = sharing.currentAuthorized(actor);
requireQueryDetail(actor); requireQueryDetail(actor);
@@ -159,25 +159,25 @@ public class ComparisonViewsController {
} }
@GetMapping("/share-candidates") @GetMapping("/share-candidates")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> shareCandidates(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> shareCandidates(@AuthenticationPrincipal AppUserPrincipal actor) {
return Map.of("items", sharing.candidates(actor)); return Map.of("items", sharing.candidates(actor));
} }
@GetMapping("/shared") @GetMapping("/shared")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> sharedViews(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> sharedViews(@AuthenticationPrincipal AppUserPrincipal actor) {
return sharing.sharedViews(actor); return sharing.sharedViews(actor);
} }
@GetMapping("/{id}/shares") @GetMapping("/{id}/shares")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> shares(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> shares(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) {
return sharing.sharesForOwner(id, actor); return sharing.sharesForOwner(id, actor);
} }
@PostMapping("/{id}/shares") @PostMapping("/{id}/shares")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> share(@PathVariable String id, @RequestBody ShareRequest request, public Map<String, Object> share(@PathVariable String id, @RequestBody ShareRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return sharing.share(id, request == null ? null : request.recipientUserId(), return sharing.share(id, request == null ? null : request.recipientUserId(),
@@ -185,7 +185,7 @@ public class ComparisonViewsController {
} }
@DeleteMapping("/{id}/shares/{recipientUserId}") @DeleteMapping("/{id}/shares/{recipientUserId}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> revokeShare(@PathVariable String id, @PathVariable String recipientUserId, public Map<String, Object> revokeShare(@PathVariable String id, @PathVariable String recipientUserId,
@RequestParam Long expectedRowVersion, @RequestParam Long expectedRowVersion,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
@@ -25,8 +25,8 @@ import tools.jackson.databind.json.JsonMapper;
@RestController @RestController
@RequestMapping("/api/analytics") @RequestMapping("/api/analytics")
public class InspectionController { public class InspectionController {
private static final List<String> STRATEGY_ROLES = List.of("SYSTEM_ADMIN", "SYSTEM_OPERATOR"); private static final List<String> STRATEGY_ROLES = List.of("SYSTEM_ADMIN");
private static final List<String> RESULT_ROLES = List.of("SYSTEM_ADMIN", "SYSTEM_OPERATOR", "QUALITY_VIEWER", "BUSINESS_ANALYST"); private static final List<String> RESULT_ROLES = List.of("SYSTEM_ADMIN", "DATA_ADMIN", "USER");
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final JsonMapper json; private final JsonMapper json;
private final InspectionService inspections; private final InspectionService inspections;
@@ -37,11 +37,11 @@ public class InspectionController {
} }
@GetMapping("/inspection-strategies") @GetMapping("/inspection-strategies")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String, Object> strategies(@AuthenticationPrincipal AppUserPrincipal actor) { return inspections.strategies(actor); } public Map<String, Object> strategies(@AuthenticationPrincipal AppUserPrincipal actor) { return inspections.strategies(actor); }
@PostMapping("/inspection-strategies") @PostMapping("/inspection-strategies")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String, Object> create(@RequestBody StrategyRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> create(@RequestBody StrategyRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
if (request == null || request.name() == null || request.name().isBlank() || request.name().length() > 190) throw bad("巡检策略名称无效"); if (request == null || request.name() == null || request.name().isBlank() || request.name().length() > 190) throw bad("巡检策略名称无效");
Map<String, Object> config = validate(request.config()); Map<String, Object> config = validate(request.config());
@@ -52,11 +52,11 @@ public class InspectionController {
} }
@GetMapping("/inspection-strategies/{id}") @GetMapping("/inspection-strategies/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String, Object> get(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) { return getStrategy(id, actor); } public Map<String, Object> get(@PathVariable String id, @AuthenticationPrincipal AppUserPrincipal actor) { return getStrategy(id, actor); }
@PutMapping("/inspection-strategies/{id}") @PutMapping("/inspection-strategies/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String, Object> update(@PathVariable String id, @RequestBody StrategyRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> update(@PathVariable String id, @RequestBody StrategyRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
if (request == null || request.name() == null || request.name().isBlank() || request.name().length() > 190) throw bad("巡检策略名称无效"); if (request == null || request.name() == null || request.name().isBlank() || request.name().length() > 190) throw bad("巡检策略名称无效");
if (request.expectedRowVersion() == null) throw bad("缺少 expectedRowVersion"); if (request.expectedRowVersion() == null) throw bad("缺少 expectedRowVersion");
@@ -68,7 +68,7 @@ public class InspectionController {
} }
@GetMapping("/inspection-runs") @GetMapping("/inspection-runs")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> runs(@RequestParam(required = false) String releaseId, public Map<String, Object> runs(@RequestParam(required = false) String releaseId,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
requireResultAccess(actor); requireResultAccess(actor);
@@ -76,7 +76,7 @@ public class InspectionController {
} }
@PostMapping("/inspection-runs/run") @PostMapping("/inspection-runs/run")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> run(@RequestBody RunRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> run(@RequestBody RunRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
requireResultAccess(actor); requireResultAccess(actor);
if (request == null || request.releaseId() == null || request.releaseId().isBlank()) throw bad("releaseId 必填"); if (request == null || request.releaseId() == null || request.releaseId().isBlank()) throw bad("releaseId 必填");
@@ -95,7 +95,7 @@ public class InspectionController {
private void requireResultAccess(AppUserPrincipal actor) { private void requireResultAccess(AppUserPrincipal actor) {
if (actor == null || !actor.isEnabled()) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "账号已停用"); if (actor == null || !actor.isEnabled()) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "账号已停用");
governance.requireUserActivePolicy(actor); governance.requireUserActivePolicy(actor);
if (actor.getRoleCodes().stream().noneMatch(role -> role.equals("QUALITY_VIEWER") || role.equals("BUSINESS_ANALYST"))) if (actor.getRoleCodes().stream().noneMatch(RESULT_ROLES::contains))
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "巡检结果需要当前业务读取角色"); throw new ResponseStatusException(HttpStatus.FORBIDDEN, "巡检结果需要当前业务读取角色");
governance.requireDetail(actor); governance.requireDetail(actor);
} }
@@ -43,7 +43,7 @@ import tools.jackson.databind.json.JsonMapper;
/** Deterministic inspection over the trusted metrics service; no row data is sent to a model. */ /** Deterministic inspection over the trusted metrics service; no row data is sent to a model. */
@Service @Service
public class InspectionService { public class InspectionService {
private static final Set<String> BUSINESS_READ_ROLES = Set.of("QUALITY_VIEWER", "BUSINESS_ANALYST"); private static final Set<String> BUSINESS_READ_ROLES = Set.of("SYSTEM_ADMIN", "DATA_ADMIN", "USER");
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final JsonMapper json; private final JsonMapper json;
private final MetricsService metrics; private final MetricsService metrics;
@@ -31,7 +31,7 @@ public class TargetController {
} }
@GetMapping("/targets") @GetMapping("/targets")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> resolve(@RequestParam(required = false) String releaseId, public Map<String, Object> resolve(@RequestParam(required = false) String releaseId,
@RequestParam(defaultValue = "COMPOSITE_RATE") String metric, @RequestParam(defaultValue = "COMPOSITE_RATE") String metric,
@RequestParam(required = false) Integer year, @RequestParam(required = false) Integer year,
@@ -55,42 +55,42 @@ public class TargetController {
} }
@GetMapping({"/targets/versions", "/versions"}) @GetMapping({"/targets/versions", "/versions"})
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','BUSINESS_ANALYST','QUALITY_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> versions() { return targets.listVersions(); } public Map<String, Object> versions() { return targets.listVersions(); }
@GetMapping({"/targets/versions/{id}", "/versions/{id}"}) @GetMapping({"/targets/versions/{id}", "/versions/{id}"})
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> version(@PathVariable String id) { return targets.version(id); } public Map<String, Object> version(@PathVariable String id) { return targets.version(id); }
@PostMapping("/targets/versions") @PostMapping("/targets/versions")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> create(@RequestBody CreateRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> create(@RequestBody CreateRequest request, @AuthenticationPrincipal AppUserPrincipal actor) {
if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本名称必填"); if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本名称必填");
return targets.create(request.name(), actor); return targets.create(request.name(), actor);
} }
@PutMapping({"/targets/versions/{id}", "/versions/{id}"}) @PutMapping({"/targets/versions/{id}", "/versions/{id}"})
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> save(@PathVariable String id, @RequestBody TargetVersionService.SaveRequest request) { public Map<String, Object> save(@PathVariable String id, @RequestBody TargetVersionService.SaveRequest request) {
if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本内容必填"); if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本内容必填");
return targets.save(id, request); return targets.save(id, request);
} }
@PutMapping("/targets/current") @PutMapping("/targets/current")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> saveCurrent(@RequestBody TargetVersionService.SaveRequest request) { public Map<String, Object> saveCurrent(@RequestBody TargetVersionService.SaveRequest request) {
return targets.saveCurrent(request); return targets.saveCurrent(request);
} }
@PostMapping({"/targets/versions/{id}/validate", "/versions/{id}/validate"}) @PostMapping({"/targets/versions/{id}/validate", "/versions/{id}/validate"})
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> validate(@PathVariable String id, @RequestBody VersionAction request) { public Map<String, Object> validate(@PathVariable String id, @RequestBody VersionAction request) {
if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本行号必填"); if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本行号必填");
return targets.validateVersion(id, request.expectedRowVersion()); return targets.validateVersion(id, request.expectedRowVersion());
} }
@PostMapping({"/targets/versions/{id}/activate", "/versions/{id}/activate"}) @PostMapping({"/targets/versions/{id}/activate", "/versions/{id}/activate"})
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> activate(@PathVariable String id, @RequestBody VersionAction request, public Map<String, Object> activate(@PathVariable String id, @RequestBody VersionAction request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本行号必填"); if (request == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "目标版本行号必填");
@@ -39,6 +39,7 @@ public class WorkspaceStateController {
jdbc.queryForList("SELECT * FROM platform_metadata ORDER BY metadata_key"), jdbc.queryForList("SELECT * FROM platform_metadata ORDER BY metadata_key"),
jdbc.queryForList("SELECT id,row_version FROM target_version WHERE status='ACTIVE' ORDER BY id"), jdbc.queryForList("SELECT id,row_version FROM target_version WHERE status='ACTIVE' ORDER BY id"),
jdbc.queryForList("SELECT * FROM query_filter_field ORDER BY field_key"), jdbc.queryForList("SELECT * FROM query_filter_field ORDER BY field_key"),
jdbc.queryForList("SELECT * FROM sales_order_type_current ORDER BY dataset_id"),
jdbc.queryForList("SELECT id,row_version FROM service_identity ORDER BY id"), jdbc.queryForList("SELECT id,row_version FROM service_identity ORDER BY id"),
jdbc.queryForList("SELECT * FROM service_binding ORDER BY service_type"))); jdbc.queryForList("SELECT * FROM service_binding ORDER BY service_type")));
Map<String, String> result = new LinkedHashMap<>(); Map<String, String> result = new LinkedHashMap<>();
@@ -15,10 +15,10 @@ public class MetricDictionaryController {
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
public Map<String, Object> list() { return service.list(); } public Map<String, Object> list() { return service.list(); }
@GetMapping("/migration") @GetMapping("/migration")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER','BUSINESS_ANALYST','DATA_PUBLISHER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> migration() { return service.migration(); } public Map<String, Object> migration() { return service.migration(); }
@PutMapping("/{code}") @PutMapping("/{code}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String, Object> update(@PathVariable String code, @RequestBody MetricDictionaryService.Edit request, public Map<String, Object> update(@PathVariable String code, @RequestBody MetricDictionaryService.Edit request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.update(code, request, actor); return service.update(code, request, actor);
@@ -18,20 +18,20 @@ public class FilterFieldsController {
private final ReleaseService releases; private final ReleaseService releases;
public FilterFieldsController(JdbcTemplate jdbc,GovernanceAccessService governance,ReleaseService releases) { this.jdbc=jdbc;this.governance=governance;this.releases=releases; } public FilterFieldsController(JdbcTemplate jdbc,GovernanceAccessService governance,ReleaseService releases) { this.jdbc=jdbc;this.governance=governance;this.releases=releases; }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public List<QueryFilterFields.Field> list(@RequestParam(defaultValue="false") boolean manage,@AuthenticationPrincipal AppUserPrincipal actor) { public List<QueryFilterFields.Field> list(@RequestParam(defaultValue="false") boolean manage,@AuthenticationPrincipal AppUserPrincipal actor) {
governance.requireUserActivePolicy(actor); governance.requireUserActivePolicy(actor);
if(manage && actor.getRoleCodes().stream().anyMatch(r->Set.of("SYSTEM_ADMIN","DATA_MAINTAINER").contains(r)))return new QueryFilterFields(jdbc,governance).all(); if(manage && actor.getRoleCodes().stream().anyMatch(r->Set.of("SYSTEM_ADMIN", "DATA_ADMIN").contains(r)))return new QueryFilterFields(jdbc,governance).all();
return new QueryFilterFields(jdbc,governance).visible(actor); return new QueryFilterFields(jdbc,governance).visible(actor);
} }
@GetMapping("/options") @GetMapping("/options")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String,Object> options(@RequestParam String key,@RequestParam(required=false) String search,@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String,Object> options(@RequestParam String key,@RequestParam(required=false) String search,@RequestParam(required=false) String releaseId,@RequestParam(required=false) String stage,@AuthenticationPrincipal AppUserPrincipal actor) {
governance.requireUserActivePolicy(actor);governance.requireBoundAction("QUERY","query.aggregate"); governance.requireUserActivePolicy(actor);governance.requireBoundAction("QUERY","query.aggregate");
return new QueryFilterFields(jdbc,governance).options(key,search,releases.resolvePublishedRelease(null),actor); return new QueryFilterFields(jdbc,governance).options(key,search,releases.resolvePublishedRelease(releaseId),stage,actor);
} }
@GetMapping("/columns") @GetMapping("/columns")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,List<String>> columns(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String,List<String>> columns(@AuthenticationPrincipal AppUserPrincipal actor) {
governance.requireUserActivePolicy(actor); governance.requireUserActivePolicy(actor);
Map<String,List<String>> result=new LinkedHashMap<>(); Map<String,List<String>> result=new LinkedHashMap<>();
@@ -49,13 +49,14 @@ public class FilterFieldsController {
} }
@PutMapping @PutMapping
@Transactional @Transactional
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public List<QueryFilterFields.Field> save(@RequestBody List<QueryFilterFields.Field> fields,@AuthenticationPrincipal AppUserPrincipal actor) { public List<QueryFilterFields.Field> save(@RequestBody List<QueryFilterFields.Field> fields,@AuthenticationPrincipal AppUserPrincipal actor) {
governance.requireUserActivePolicy(actor); governance.requireUserActivePolicy(actor);
if(fields==null||fields.size()>20)throw QueryFilterFields.bad("最多配置20个筛选字段"); if(fields==null||fields.size()>20)throw QueryFilterFields.bad("最多配置20个筛选字段");
Set<String> keys=new HashSet<>(),labels=new HashSet<>(); Set<String> keys=new HashSet<>(),labels=new HashSet<>();
Set<String> allowed=governance.allowedFields(actor); Set<String> allowed=governance.allowedFields(actor);
for(var f:fields) { for(var f:fields) {
if(SalesOrderTypes.KEY.equals(f.key())||SalesOrderTypes.EXCLUDE_KEY.equals(f.key()))throw QueryFilterFields.bad("销售订单类型由对应表维护,请勿配置为原始列");
if(f.key()==null||!f.key().matches("[a-zA-Z][a-zA-Z0-9_]{0,63}")||!keys.add(f.key()))throw QueryFilterFields.bad("字段标识无效或重复"); if(f.key()==null||!f.key().matches("[a-zA-Z][a-zA-Z0-9_]{0,63}")||!keys.add(f.key()))throw QueryFilterFields.bad("字段标识无效或重复");
if(f.label()==null||f.label().isBlank()||f.label().length()>80||!labels.add(f.label()))throw QueryFilterFields.bad("名称为空、过长或重复"); if(f.label()==null||f.label().isBlank()||f.label().length()>80||!labels.add(f.label()))throw QueryFilterFields.bad("名称为空、过长或重复");
for(String column:List.of(f.blackColumn()==null?"":f.blackColumn(),f.brightColumn()==null?"":f.brightColumn())) { for(String column:List.of(f.blackColumn()==null?"":f.blackColumn(),f.brightColumn()==null?"":f.brightColumn())) {
@@ -23,7 +23,10 @@ public class QueryFilterFields {
} }
public List<Field> visible(AppUserPrincipal actor) { public List<Field> visible(AppUserPrincipal actor) {
Set<String> allowed=governance.allowedFields(actor); Set<String> allowed=governance.allowedFields(actor);
return all().stream().filter(Field::enabled).filter(f->allowed.contains("*") || (allowed.contains(f.blackColumn()) && allowed.contains(f.brightColumn()))).toList(); List<Field> fields=new ArrayList<>(all());
fields.removeIf(f->SalesOrderTypes.KEY.equals(f.key()));
fields.add(new Field(SalesOrderTypes.KEY,SalesOrderTypes.LABEL,"销售订单号","销售订单",true,true,-1));
return fields.stream().filter(Field::enabled).filter(f->allowed.contains("*") || (allowed.contains(f.blackColumn()) && allowed.contains(f.brightColumn()))).toList();
} }
public static Map<String,List<String>> parse(Object raw) { public static Map<String,List<String>> parse(Object raw) {
if(raw==null || "".equals(raw))return Map.of(); if(raw==null || "".equals(raw))return Map.of();
@@ -48,8 +51,13 @@ public class QueryFilterFields {
if(filters==null || filters.isEmpty())return; if(filters==null || filters.isEmpty())return;
Map<String,Field> fields=new HashMap<>(); visible(actor).forEach(f->fields.put(f.key(),f)); Map<String,Field> fields=new HashMap<>(); visible(actor).forEach(f->fields.put(f.key(),f));
for(var entry:filters.entrySet()) { for(var entry:filters.entrySet()) {
Field f=fields.get(entry.getKey()); boolean exclude=SalesOrderTypes.EXCLUDE_KEY.equals(entry.getKey());
Field f=fields.get(exclude?SalesOrderTypes.KEY:entry.getKey());
if(f==null)throw bad("筛选字段未启用或没有权限:"+entry.getKey()); if(f==null)throw bad("筛选字段未启用或没有权限:"+entry.getKey());
if(SalesOrderTypes.KEY.equals(f.key())) {
SalesOrderTypes.append(where,args,stage,entry.getValue(),SalesOrderTypes.version(jdbc),exclude);
continue;
}
boolean empty=entry.getValue().contains(EMPTY); boolean empty=entry.getValue().contains(EMPTY);
if(empty && !f.allowEmpty())throw bad(f.label()+"不允许筛选空值"); if(empty && !f.allowEmpty())throw bad(f.label()+"不允许筛选空值");
String column=stage.equals("black")?f.blackColumn():f.brightColumn(); String column=stage.equals("black")?f.blackColumn():f.brightColumn();
@@ -69,8 +77,13 @@ public class QueryFilterFields {
} }
} }
public Map<String,Object> options(String key,String search,String releaseId,AppUserPrincipal actor) { public Map<String,Object> options(String key,String search,String releaseId,AppUserPrincipal actor) {
return options(key,search,releaseId,null,actor);
}
public Map<String,Object> options(String key,String search,String releaseId,String selectedStage,AppUserPrincipal actor) {
Field field=visible(actor).stream().filter(f->f.key().equals(key)).findFirst().orElseThrow(()->bad("筛选字段未启用或没有权限")); Field field=visible(actor).stream().filter(f->f.key().equals(key)).findFirst().orElseThrow(()->bad("筛选字段未启用或没有权限"));
if(search!=null && search.length()>256)throw bad("搜索文本过长"); if(search!=null && search.length()>256)throw bad("搜索文本过长");
if(selectedStage!=null&&!List.of("black","bright").contains(selectedStage))throw bad("阶段无效");
if(SalesOrderTypes.KEY.equals(key))return salesOrderOptions(search,releaseId,selectedStage,actor);
List<Object> args=new ArrayList<>();List<String> selects=new ArrayList<>(); List<Object> args=new ArrayList<>();List<String> selects=new ArrayList<>();
for(String stage:List.of("black","bright")) { for(String stage:List.of("black","bright")) {
String column=stage.equals("black")?field.blackColumn():field.brightColumn(); String column=stage.equals("black")?field.blackColumn():field.brightColumn();
@@ -85,6 +98,25 @@ public class QueryFilterFields {
List<String> found=jdbc.query("SELECT DISTINCT value FROM ("+String.join(" UNION ALL ",selects)+") choices"+predicate+" ORDER BY value LIMIT 201",(rs,n)->rs.getString(1),args.toArray()); List<String> found=jdbc.query("SELECT DISTINCT value FROM ("+String.join(" UNION ALL ",selects)+") choices"+predicate+" ORDER BY value LIMIT 201",(rs,n)->rs.getString(1),args.toArray());
return Map.of("values",found.stream().limit(200).toList(),"hasMore",found.size()>200); return Map.of("values",found.stream().limit(200).toList(),"hasMore",found.size()>200);
} }
private Map<String,Object> salesOrderOptions(String search,String releaseId,String selectedStage,AppUserPrincipal actor) {
String version=SalesOrderTypes.version(jdbc);
if(releaseId==null||version.isBlank())return Map.of("values",List.of(),"hasMore",false,"versionId",version);
List<Object> args=new ArrayList<>();List<String> selects=new ArrayList<>();
for(String type:SalesOrderTypes.TYPES) {
if(search!=null&&!search.isBlank()&&!type.toLowerCase(Locale.ROOT).contains(search.toLowerCase(Locale.ROOT)))continue;
args.add(type);List<String> exists=new ArrayList<>();
for(String stage:selectedStage==null?List.of("black","bright"):List.of(selectedStage)) {
StringBuilder scope=new StringBuilder(" WHERE sot.version_id=? AND sot.order_type=? AND rm.release_id=?");
List<Object> scoped=new ArrayList<>(List.of(version,type,releaseId));
DataScope.append(scope,scoped,actor,"f.department COLLATE utf8mb4_0900_as_cs","f.group_name COLLATE utf8mb4_0900_as_cs");
exists.add("EXISTS (SELECT 1 FROM sales_order_type_entry sot JOIN fact_"+stage+" f ON f.sales_order_no=sot.order_no JOIN release_member rm ON f.build_id=rm.transform_build_id AND f.source_revision_id=rm.source_revision_id"+scope+")");
args.addAll(scoped);
}
selects.add("SELECT ? AS value WHERE "+String.join(" OR ",exists));
}
List<String> values=selects.isEmpty()?List.of():jdbc.query(String.join(" UNION ALL ",selects)+" ORDER BY value",(rs,n)->rs.getString(1),args.toArray());
return Map.of("values",values,"hasMore",false,"versionId",version);
}
public static String path(String column) { return "$."+JSON.writeValueAsString(column); } public static String path(String column) { return "$."+JSON.writeValueAsString(column); }
public static ResponseStatusException bad(String text) { return new ResponseStatusException(HttpStatus.BAD_REQUEST,text); } public static ResponseStatusException bad(String text) { return new ResponseStatusException(HttpStatus.BAD_REQUEST,text); }
} }
@@ -0,0 +1,27 @@
package cn.yunsheng.quality.filters;
import cn.yunsheng.quality.governance.GovernanceAccessService;
import cn.yunsheng.quality.identity.AppUserPrincipal;
import java.util.Map;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/sales-order-types")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class SalesOrderTypeController {
private final SalesOrderTypeService service;
private final GovernanceAccessService governance;
public SalesOrderTypeController(SalesOrderTypeService service,GovernanceAccessService governance) { this.service=service;this.governance=governance; }
private void authorize(AppUserPrincipal actor) {
governance.requireUserActivePolicy(actor);
if(!SalesOrderTypes.allowed(governance.allowedFields(actor)))throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"没有销售订单来源字段权限");
}
@GetMapping public Map<String,Object> status(@AuthenticationPrincipal AppUserPrincipal actor) { authorize(actor);return service.status(); }
@PostMapping("/preview") public Map<String,Object> preview(@RequestParam MultipartFile file,@RequestParam(defaultValue="MERGE") String mode,@AuthenticationPrincipal AppUserPrincipal actor) { authorize(actor);return service.preview(file,mode); }
@PostMapping("/import") public Map<String,Object> importFile(@RequestParam MultipartFile file,@RequestParam String mode,@RequestParam(defaultValue="") String expectedVersion,@RequestParam String sha256,@AuthenticationPrincipal AppUserPrincipal actor) { authorize(actor);return service.importFile(file,mode,expectedVersion,sha256,actor); }
public record Activation(String versionId,String expectedVersion) {}
@PostMapping("/activate") public Map<String,Object> activate(@RequestBody Activation input,@AuthenticationPrincipal AppUserPrincipal actor) { authorize(actor);return service.activate(input.versionId(),input.expectedVersion(),actor); }
}
@@ -0,0 +1,118 @@
package cn.yunsheng.quality.filters;
import cn.yunsheng.quality.identity.AppUserPrincipal;
import java.io.*;
import java.security.MessageDigest;
import java.util.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
@Service
public class SalesOrderTypeService {
private final JdbcTemplate jdbc;
public SalesOrderTypeService(JdbcTemplate jdbc) { this.jdbc=jdbc; }
record Input(String filename,String sha256,LinkedHashMap<String,String> rows) {}
static Input read(MultipartFile file) {
if(file==null||file.isEmpty())throw QueryFilterFields.bad("请选择销售订单对应表");
if(file.getSize()>50L*1024*1024)throw QueryFilterFields.bad("销售订单对应表最多50MB");
try {
byte[] bytes=file.getBytes();
LinkedHashMap<String,String> rows=new LinkedHashMap<>();
try(Workbook workbook=WorkbookFactory.create(new ByteArrayInputStream(bytes))) {
if(workbook.getNumberOfSheets()!=1)throw QueryFilterFields.bad("销售订单对应表请只保留一张工作表");
Sheet sheet=workbook.getSheetAt(0); Row header=sheet.getRow(0);
if(header==null)throw QueryFilterFields.bad("对应表缺少表头");
int order=-1,type=-1;
for(Cell cell:header) {
String label=new DataFormatter().formatCellValue(cell).trim();
if(List.of("销售订单编号","销售订单号","销售订单").contains(label))order=cell.getColumnIndex();
if("销售订单类型".equals(label))type=cell.getColumnIndex();
}
if(order<0||type<0)throw QueryFilterFields.bad("对应表需要“销售订单编号”和“销售订单类型”两列");
if(sheet.getLastRowNum()>500000)throw QueryFilterFields.bad("销售订单对应表最多50万行");
for(int index=1;index<=sheet.getLastRowNum();index++) {
Row row=sheet.getRow(index);if(row==null)continue;
String key=text(row.getCell(order),index+1),value=text(row.getCell(type),index+1);
if(key.isBlank()&&value.isBlank())continue;
if(key.isBlank()||key.length()>190)throw QueryFilterFields.bad("第"+(index+1)+"行订单号为空或超过190字");
if(!SalesOrderTypes.TYPES.contains(value))throw QueryFilterFields.bad("第"+(index+1)+"行销售订单类型不属于现有7类:"+value);
String previous=rows.putIfAbsent(key,value);
if(previous!=null&&!previous.equals(value))throw QueryFilterFields.bad("第"+(index+1)+"行订单号对应多个类型:"+key);
}
}
if(rows.isEmpty())throw QueryFilterFields.bad("对应表没有有效订单");
String filename=java.nio.file.Path.of(Objects.toString(file.getOriginalFilename(),"销售订单对应表.xlsx").replace('\\','/')).getFileName().toString();
if(filename.length()>255)throw QueryFilterFields.bad("文件名过长");
return new Input(filename,HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)),rows);
} catch(ResponseStatusException failure) { throw failure; }
catch(Exception failure) { throw QueryFilterFields.bad("无法读取对应表,请选择有效的Excel文件"); }
}
private static String text(Cell cell,int row) {
if(cell==null||cell.getCellType()==CellType.BLANK)return "";
if(cell.getCellType()!=CellType.STRING)throw QueryFilterFields.bad("第"+row+"行请使用文本保存订单号和类型,不使用数值或公式");
return cell.getStringCellValue().trim();
}
private String current(boolean lock) {
return jdbc.queryForObject("SELECT COALESCE(version_id,'') FROM sales_order_type_current WHERE dataset_id='quality'"+(lock?" FOR UPDATE":""),String.class);
}
private LinkedHashMap<String,String> entries(String version) {
LinkedHashMap<String,String> result=new LinkedHashMap<>();
if(version!=null&&!version.isBlank())jdbc.query("SELECT order_no,order_type FROM sales_order_type_entry WHERE version_id=? ORDER BY order_no",(org.springframework.jdbc.core.RowCallbackHandler)rs->result.put(rs.getString(1),rs.getString(2)),version);
return result;
}
private static void requireMode(String mode) {
if(!Set.of("MERGE","REPLACE").contains(mode))throw QueryFilterFields.bad("请选择增量更新或整表替换");
}
static Map<String,Object> summary(Map<String,String> before,Map<String,String> incoming,String mode) {
requireMode(mode);int added=0,updated=0,unchanged=0;
for(var row:incoming.entrySet()) {
if(!before.containsKey(row.getKey()))added++;
else if(!before.get(row.getKey()).equals(row.getValue()))updated++;
else unchanged++;
}
long removed="REPLACE".equals(mode)?before.keySet().stream().filter(key->!incoming.containsKey(key)).count():0;
return Map.of("added",added,"updated",updated,"unchanged",unchanged,"removed",removed,"imported",incoming.size(),"total","REPLACE".equals(mode)?incoming.size():before.size()+added);
}
@Transactional(readOnly=true)
public Map<String,Object> preview(MultipartFile file,String mode) {
requireMode(mode);Input input=read(file);String base=current(false);
return Map.of("sourceFile",input.filename(),"sha256",input.sha256(),"expectedVersion",base,"summary",summary(entries(base),input.rows(),mode));
}
@Transactional
public Map<String,Object> importFile(MultipartFile file,String mode,String expected,String sha256,AppUserPrincipal actor) {
requireMode(mode);Input input=read(file);
if(!input.sha256().equals(sha256))throw QueryFilterFields.bad("文件已变化,请重新预览");
String base=current(true);
if(!Objects.equals(base,expected))throw new ResponseStatusException(HttpStatus.CONFLICT,"对应关系已更新,请重新预览");
LinkedHashMap<String,String> before=entries(base),merged=new LinkedHashMap<>();
Map<String,Object> changes=summary(before,input.rows(),mode);
if("MERGE".equals(mode))merged.putAll(before);merged.putAll(input.rows());
String id=UUID.randomUUID().toString();
jdbc.update("INSERT INTO sales_order_type_version(id,source_file,source_sha256,import_mode,row_count,created_by) VALUES(?,?,?,?,?,?)",id,input.filename(),input.sha256(),mode,merged.size(),actor.getId().toString());
jdbc.batchUpdate("INSERT INTO sales_order_type_entry(version_id,order_no,order_type) VALUES(?,?,?)",new ArrayList<>(merged.entrySet()),500,(statement,row)->{statement.setString(1,id);statement.setString(2,row.getKey());statement.setString(3,row.getValue());});
new cn.yunsheng.quality.metrics.SalesOrderMetricRollups(jdbc).prepareCurrentRelease(id);
jdbc.update("UPDATE sales_order_type_current SET version_id=? WHERE dataset_id='quality'",id);
audit(actor,"SALES_ORDER_TYPE_IMPORT",id);
return Map.of("versionId",id,"summary",changes);
}
@Transactional
public Map<String,Object> activate(String id,String expected,AppUserPrincipal actor) {
if(!Objects.equals(current(true),expected))throw new ResponseStatusException(HttpStatus.CONFLICT,"对应关系已更新,请刷新后重试");
if(jdbc.queryForObject("SELECT COUNT(*) FROM sales_order_type_version WHERE id=?",Integer.class,id)!=1)throw QueryFilterFields.bad("对应关系版本不存在");
new cn.yunsheng.quality.metrics.SalesOrderMetricRollups(jdbc).prepareCurrentRelease(id);
jdbc.update("UPDATE sales_order_type_current SET version_id=? WHERE dataset_id='quality'",id);audit(actor,"SALES_ORDER_TYPE_RESTORE",id);
return Map.of("versionId",id);
}
public Map<String,Object> status() {
return Map.of("versionId",current(false),"versions",jdbc.queryForList("SELECT id,source_file AS sourceFile,row_count AS rowCount,import_mode AS importMode,created_at AS createdAt FROM sales_order_type_version ORDER BY created_at DESC LIMIT 30"),"types",SalesOrderTypes.TYPES);
}
private void audit(AppUserPrincipal actor,String action,String version) {
jdbc.update("INSERT INTO audit_event(actor_user_id,action_code,target_type,target_id,outcome,details) VALUES(?,?,'sales_order_type_version',?,'SUCCESS',JSON_OBJECT('versionId',?))",actor.getId().toString(),action,version,version);
}
}
@@ -0,0 +1,67 @@
package cn.yunsheng.quality.filters;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestAttributes;
/** A reference snapshot, independent of quality-data releases. Never changes raw source values. */
public final class SalesOrderTypes {
public static final String KEY = "salesOrderType";
public static final String EXCLUDE_KEY = "salesOrderTypeNotIn";
public static final String LABEL = "销售订单类型";
public static final List<String> TYPES = List.of("标准销售订单", "样品销售订单", "国内寄售补货订单", "备料销售订单", "内部研发销售订单", "免费补货订单", "外销寄售补货订单");
private static final String PIN = SalesOrderTypes.class.getName() + ".version";
private SalesOrderTypes() {}
public static boolean allowed(Set<String> fields) {
return fields.contains("*") || fields.containsAll(List.of("销售订单号", "销售订单"));
}
public static String column(String stage) {
return switch(stage) { case "black" -> "销售订单号"; case "bright" -> "销售订单"; default -> throw QueryFilterFields.bad("阶段无效"); };
}
public static String version(JdbcTemplate jdbc) {
RequestAttributes request = RequestContextHolder.getRequestAttributes();
if (request != null && request.getAttribute(PIN, RequestAttributes.SCOPE_REQUEST) instanceof String pinned) return pinned;
String version = jdbc.queryForObject("SELECT COALESCE(version_id,'') FROM sales_order_type_current WHERE dataset_id='quality'", String.class);
version = version == null ? "" : version;
if (request != null) request.setAttribute(PIN, version, RequestAttributes.SCOPE_REQUEST);
return version;
}
public static String expression(String stage, String version, List<Object> args) {
column(stage);args.add(version);
return "(SELECT sot.order_type FROM sales_order_type_entry sot WHERE sot.version_id=? AND sot.order_no="
+ "f.sales_order_no)";
}
public static void append(StringBuilder where,List<Object> args,String stage,List<String> selected,String version) {
append(where,args,stage,selected,version,false);
}
public static void append(StringBuilder where,List<Object> args,String stage,List<String> selected,String version,boolean exclude) {
List<String> types=selected.stream().filter(value->!QueryFilterFields.EMPTY.equals(value)).toList();
if(types.stream().anyMatch(value->!TYPES.contains(value)))throw QueryFilterFields.bad("销售订单类型无效");
if(selected.isEmpty())return;
if(exclude) {
column(stage);where.append(" AND (");
if(!types.isEmpty()) {
args.add(version);where.append("NOT EXISTS (SELECT 1 FROM sales_order_type_entry sot WHERE sot.version_id=? AND sot.order_no=f.sales_order_no AND sot.order_type IN (").append(String.join(",",Collections.nCopies(types.size(),"?"))).append("))");
args.addAll(types);
}
if(selected.contains(QueryFilterFields.EMPTY)) {
if(!types.isEmpty())where.append(" AND ");
args.add(version);where.append("EXISTS (SELECT 1 FROM sales_order_type_entry sot WHERE sot.version_id=? AND sot.order_no=f.sales_order_no)");
}
where.append(')');return;
}
where.append(" AND (");
if(!types.isEmpty()) {
column(stage);args.add(version);
where.append("EXISTS (SELECT 1 FROM sales_order_type_entry sot WHERE sot.version_id=? AND sot.order_no=f.sales_order_no AND sot.order_type IN (").append(String.join(",",Collections.nCopies(types.size(),"?"))).append("))");
args.addAll(types);
}
if(selected.contains(QueryFilterFields.EMPTY)) {
if(!types.isEmpty())where.append(" OR ");
args.add(version);where.append("NOT EXISTS (SELECT 1 FROM sales_order_type_entry sot WHERE sot.version_id=? AND sot.order_no=f.sales_order_no)");
}
where.append(')');
}
}
@@ -5,15 +5,15 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/governance") @RestController @RequestMapping("/api/governance")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','DATA_MAINTAINER','RULE_MAINTAINER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class CandidateAcceptanceController { public class CandidateAcceptanceController {
private final CandidateAcceptanceService service; private final CandidateAcceptanceService service;
public CandidateAcceptanceController(CandidateAcceptanceService service){this.service=service;} public CandidateAcceptanceController(CandidateAcceptanceService service){this.service=service;}
@GetMapping("/migration-baseline") public Map<String,Object> baseline(){return service.migrationBaseline();} @GetMapping("/migration-baseline") public Map<String,Object> baseline(){return service.migrationBaseline();}
@GetMapping("/releases/{id}/reconciliations") public Map<String,Object> list(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return service.list(id,actor);} @GetMapping("/releases/{id}/reconciliations") public Map<String,Object> list(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return service.list(id,actor);}
@GetMapping("/reconciliations/{id}") public Map<String,Object> detail(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return service.detail(id,actor);} @GetMapping("/reconciliations/{id}") public Map<String,Object> detail(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return service.detail(id,actor);}
@PostMapping("/releases/{id}/reconciliations") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','DATA_MAINTAINER','RULE_MAINTAINER')") @PostMapping("/releases/{id}/reconciliations") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> create(@PathVariable String id,@RequestBody CandidateAcceptanceService.ReconciliationRequest request,@AuthenticationPrincipal AppUserPrincipal actor){return service.create(id,request,actor);} public Map<String,Object> create(@PathVariable String id,@RequestBody CandidateAcceptanceService.ReconciliationRequest request,@AuthenticationPrincipal AppUserPrincipal actor){return service.create(id,request,actor);}
@PostMapping("/reconciliations/{id}/confirm") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER')") @PostMapping("/reconciliations/{id}/confirm") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> confirm(@PathVariable String id,@RequestBody CandidateAcceptanceService.Confirmation request,@AuthenticationPrincipal AppUserPrincipal actor){return service.confirm(id,request,actor);} public Map<String,Object> confirm(@PathVariable String id,@RequestBody CandidateAcceptanceService.Confirmation request,@AuthenticationPrincipal AppUserPrincipal actor){return service.confirm(id,request,actor);}
} }
@@ -32,7 +32,7 @@ public class CandidateAcceptanceService {
} }
} }
@Transactional public Map<String,Object> create(String releaseId,ReconciliationRequest request,AppUserPrincipal actor){ @Transactional public Map<String,Object> create(String releaseId,ReconciliationRequest request,AppUserPrincipal actor){
if(actor.getRoleCodes().stream().noneMatch(Set.of("SYSTEM_ADMIN","DATA_PUBLISHER","DATA_MAINTAINER","RULE_MAINTAINER")::contains))throw error(HttpStatus.FORBIDDEN,"当前角色不能执行候选验收"); if(actor.getRoleCodes().stream().noneMatch(Set.of("SYSTEM_ADMIN", "DATA_ADMIN")::contains))throw error(HttpStatus.FORBIDDEN,"当前角色不能执行候选验收");
requireRead(releaseId,actor);Map<String,Object> release=g.one("SELECT id,status,expected_current_release_id,complete,rule_version FROM data_release WHERE id=? FOR UPDATE",releaseId); requireRead(releaseId,actor);Map<String,Object> release=g.one("SELECT id,status,expected_current_release_id,complete,rule_version FROM data_release WHERE id=? FOR UPDATE",releaseId);
if(!"CANDIDATE".equals(release.get("status")))throw error(HttpStatus.CONFLICT,"只对候选版本创建基线验收"); if(!"CANDIDATE".equals(release.get("status")))throw error(HttpStatus.CONFLICT,"只对候选版本创建基线验收");
String baseline=request.baselineReleaseId()==null?(String)release.get("expectedCurrentReleaseId"):request.baselineReleaseId(); String baseline=request.baselineReleaseId()==null?(String)release.get("expectedCurrentReleaseId"):request.baselineReleaseId();
@@ -72,7 +72,7 @@ public class CandidateAcceptanceService {
public Map<String,Object> list(String releaseId,AppUserPrincipal actor){requireRead(releaseId,actor);return Map.of("items",g.rows("SELECT id,release_id,baseline_release_id,status,difference_hash,row_version,created_by,confirmed_by,confirmation_reason,created_at,confirmed_at FROM candidate_reconciliation WHERE release_id=? ORDER BY created_at DESC",releaseId),"acceptanceId",Objects.toString(g.jdbc.queryForObject("SELECT acceptance_id FROM data_release WHERE id=?",String.class,releaseId),""));} public Map<String,Object> list(String releaseId,AppUserPrincipal actor){requireRead(releaseId,actor);return Map.of("items",g.rows("SELECT id,release_id,baseline_release_id,status,difference_hash,row_version,created_by,confirmed_by,confirmation_reason,created_at,confirmed_at FROM candidate_reconciliation WHERE release_id=? ORDER BY created_at DESC",releaseId),"acceptanceId",Objects.toString(g.jdbc.queryForObject("SELECT acceptance_id FROM data_release WHERE id=?",String.class,releaseId),""));}
public Map<String,Object> detail(String id,AppUserPrincipal actor){Map<String,Object> row=g.one("SELECT * FROM candidate_reconciliation WHERE id=?",id);requireRead((String)row.get("releaseId"),actor);if(row.get("baselineReleaseId")!=null)requireRead((String)row.get("baselineReleaseId"),actor);requireTransitionRead(row,actor);row.put("request",decode(row.get("request")));row.put("publishReady",ready(row));return row;} public Map<String,Object> detail(String id,AppUserPrincipal actor){Map<String,Object> row=g.one("SELECT * FROM candidate_reconciliation WHERE id=?",id);requireRead((String)row.get("releaseId"),actor);if(row.get("baselineReleaseId")!=null)requireRead((String)row.get("baselineReleaseId"),actor);requireTransitionRead(row,actor);row.put("request",decode(row.get("request")));row.put("publishReady",ready(row));return row;}
@Transactional public Map<String,Object> confirm(String id,Confirmation request,AppUserPrincipal actor){ @Transactional public Map<String,Object> confirm(String id,Confirmation request,AppUserPrincipal actor){
if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!actor.getRoleCodes().contains("DATA_PUBLISHER"))throw error(HttpStatus.FORBIDDEN,"差异确认须由有范围权限的发布者执行"); if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!actor.getRoleCodes().contains("DATA_ADMIN"))throw error(HttpStatus.FORBIDDEN,"差异确认须由有范围权限的发布者执行");
Map<String,Object> row=g.one("SELECT * FROM candidate_reconciliation WHERE id=? FOR UPDATE",id);requireRead((String)row.get("releaseId"),actor);if(row.get("baselineReleaseId")!=null)requireRead((String)row.get("baselineReleaseId"),actor); Map<String,Object> row=g.one("SELECT * FROM candidate_reconciliation WHERE id=? FOR UPDATE",id);requireRead((String)row.get("releaseId"),actor);if(row.get("baselineReleaseId")!=null)requireRead((String)row.get("baselineReleaseId"),actor);
if(!"REVIEW_REQUIRED".equals(row.get("status"))||request.expectedRowVersion()==null||((Number)row.get("rowVersion")).longValue()!=request.expectedRowVersion()||!Objects.equals(row.get("differenceHash"),request.expectedDifferenceHash()))throw error(HttpStatus.CONFLICT,"仅可确认当前待审核的确切差异结果"); if(!"REVIEW_REQUIRED".equals(row.get("status"))||request.expectedRowVersion()==null||((Number)row.get("rowVersion")).longValue()!=request.expectedRowVersion()||!Objects.equals(row.get("differenceHash"),request.expectedDifferenceHash()))throw error(HttpStatus.CONFLICT,"仅可确认当前待审核的确切差异结果");
Map<String,Object> evidence=evidence(row);Object transitionHash=evidence.get("transitionDifferenceHash");if(transitionHash!=null&&!Objects.equals(transitionHash,request.expectedTransitionDifferenceHash()))throw error(HttpStatus.CONFLICT,"必须明确确认实际当前版本至候选的确切变更差异hash"); Map<String,Object> evidence=evidence(row);Object transitionHash=evidence.get("transitionDifferenceHash");if(transitionHash!=null&&!Objects.equals(transitionHash,request.expectedTransitionDifferenceHash()))throw error(HttpStatus.CONFLICT,"必须明确确认实际当前版本至候选的确切变更差异hash");
@@ -14,12 +14,15 @@ public class EffectiveAccessController {
Map<String,Object> out=new LinkedHashMap<>();out.put("userId",id);out.put("active",user.isEnabled());out.put("authorizationEffective",effective);out.put("roles",user.getRoleCodes());out.put("allowedActions",effective?actions:Set.of());out.put("departments",user.getRoleCodes().contains("SYSTEM_ADMIN")?List.of("*"):user.getDepartments());out.put("groups",user.getRoleCodes().contains("SYSTEM_ADMIN")?List.of("*"):user.getGroups());out.put("grantedDepartments",g.jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='DEPARTMENT' ORDER BY scope_value",(rs,n)->rs.getString(1),id));out.put("hierarchySource",g.rows("SELECT c.release_id,r.mapping_version FROM current_release c JOIN data_release r ON r.id=c.release_id WHERE c.dataset_id='quality'"));out.put("fieldPolicy",policy);out.put("validUntil",policy.get("validUntil"));out.put("scopeHash",GovernanceSupport.sha(g.encode(List.of(user.getRoleCodes(),user.getDepartments(),user.getGroups(),policy))));return out;} Map<String,Object> out=new LinkedHashMap<>();out.put("userId",id);out.put("active",user.isEnabled());out.put("authorizationEffective",effective);out.put("roles",user.getRoleCodes());out.put("allowedActions",effective?actions:Set.of());out.put("departments",user.getRoleCodes().contains("SYSTEM_ADMIN")?List.of("*"):user.getDepartments());out.put("groups",user.getRoleCodes().contains("SYSTEM_ADMIN")?List.of("*"):user.getGroups());out.put("grantedDepartments",g.jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='DEPARTMENT' ORDER BY scope_value",(rs,n)->rs.getString(1),id));out.put("hierarchySource",g.rows("SELECT c.release_id,r.mapping_version FROM current_release c JOIN data_release r ON r.id=c.release_id WHERE c.dataset_id='quality'"));out.put("fieldPolicy",policy);out.put("validUntil",policy.get("validUntil"));out.put("scopeHash",GovernanceSupport.sha(g.encode(List.of(user.getRoleCodes(),user.getDepartments(),user.getGroups(),policy))));return out;}
@GetMapping("/{id}/scope-preview")public Map<String,Object> preview(@PathVariable String id){AppUserPrincipal user=principal(id);Map<String,Object> effective=effective(id);String release=g.jdbc.queryForObject("SELECT release_id FROM current_release WHERE dataset_id='quality'",String.class);List<Map<String,Object>> counts=new ArrayList<>();for(String stage:List.of("black","bright")){String base="SELECT COUNT(*) FROM fact_"+stage+" f WHERE EXISTS(SELECT 1 FROM release_member rm WHERE rm.release_id=? AND rm.transform_build_id=f.build_id)";Long total=g.jdbc.queryForObject(base,Long.class,release);StringBuilder sql=new StringBuilder(base);List<Object> args=new ArrayList<>();args.add(release);DataScope.append(sql,args,user,"f.department","f.group_name");if(!Boolean.TRUE.equals(effective.get("authorizationEffective"))||!(effective.get("allowedActions") instanceof Collection<?> actions)||!actions.contains("query.aggregate"))sql.append(" AND 1=0");Long permitted=g.jdbc.queryForObject(sql.toString(),Long.class,args.toArray());counts.add(Map.of("stage",stage,"totalRows",total==null?0:total,"authorizedRows",permitted==null?0:permitted));}Map<String,Object> out=new LinkedHashMap<>(effective);out.put("releaseId",release);out.put("counts",counts);out.put("dataReturned",false);return out;} @GetMapping("/{id}/scope-preview")public Map<String,Object> preview(@PathVariable String id){AppUserPrincipal user=principal(id);Map<String,Object> effective=effective(id);String release=g.jdbc.queryForObject("SELECT release_id FROM current_release WHERE dataset_id='quality'",String.class);List<Map<String,Object>> counts=new ArrayList<>();for(String stage:List.of("black","bright")){String base="SELECT COUNT(*) FROM fact_"+stage+" f WHERE EXISTS(SELECT 1 FROM release_member rm WHERE rm.release_id=? AND rm.transform_build_id=f.build_id)";Long total=g.jdbc.queryForObject(base,Long.class,release);StringBuilder sql=new StringBuilder(base);List<Object> args=new ArrayList<>();args.add(release);DataScope.append(sql,args,user,"f.department","f.group_name");if(!Boolean.TRUE.equals(effective.get("authorizationEffective"))||!(effective.get("allowedActions") instanceof Collection<?> actions)||!actions.contains("query.aggregate"))sql.append(" AND 1=0");Long permitted=g.jdbc.queryForObject(sql.toString(),Long.class,args.toArray());counts.add(Map.of("stage",stage,"totalRows",total==null?0:total,"authorizedRows",permitted==null?0:permitted));}Map<String,Object> out=new LinkedHashMap<>(effective);out.put("releaseId",release);out.put("counts",counts);out.put("dataReturned",false);return out;}
private AppUserPrincipal principal(String id){String username=String.valueOf(g.one("SELECT username FROM app_user WHERE id=?",id).get("username"));return access.resolvePrincipal((AppUserPrincipal)users.loadUserByUsername(username));} private AppUserPrincipal principal(String id){String username=String.valueOf(g.one("SELECT username FROM app_user WHERE id=?",id).get("username"));return access.resolvePrincipal((AppUserPrincipal)users.loadUserByUsername(username));}
static Set<String> actions(List<String> roles){Set<String> out=new TreeSet<>();for(String role:roles)switch(role){ static Set<String> actions(List<String> roles) {
case "SYSTEM_ADMIN"->out.addAll(List.of("query.aggregate","query.detail","analysis.run","source.view","source.manage","source.receive","source.withdraw","source.evidence","source.download","import.run","import.retry","release.build","release.publish","release.rollback","rule.edit","rule.validate","rule.activate","mapping.edit","mapping.validate","mapping.activate","target.manage","cost.edit","task.view","task.retry","task.cancel","monitor.view","backup.manage","restore.isolated","iam.manage","service.manage","audit.view")); Set<String> out = new TreeSet<>();
case "QUALITY_VIEWER","BUSINESS_ANALYST"->out.addAll(List.of("query.aggregate","query.detail","analysis.run","source.view","source.evidence","source.download")); if (roles.size() != 1 || !cn.yunsheng.quality.identity.AppRoles.CODES.contains(roles.getFirst())) return out;
case "DATA_MAINTAINER"->out.addAll(List.of("source.view","source.manage","source.receive","source.withdraw","source.evidence","source.download","import.run","import.retry","mapping.edit","mapping.validate","mapping.activate","cost.edit","task.view","task.retry","task.cancel")); String role = roles.getFirst();
case "DATA_PUBLISHER"->out.addAll(List.of("source.view","source.evidence","source.download","release.build","release.publish","release.rollback","task.view")); out.addAll(List.of("query.aggregate", "query.detail", "analysis.run", "source.view", "source.evidence", "source.download", "rule.view", "mapping.view", "release.view", "metric.view", "inspection.run"));
case "RULE_MAINTAINER"->out.addAll(List.of("rule.edit","rule.validate","rule.activate","mapping.edit","mapping.validate","mapping.activate","target.manage","cost.edit")); if (Set.of("DATA_ADMIN", "SYSTEM_ADMIN").contains(role))
case "SYSTEM_OPERATOR"->out.addAll(List.of("task.view","task.cancel","monitor.view","backup.manage","restore.isolated")); out.addAll(List.of("source.manage", "source.receive", "source.withdraw", "import.run", "import.retry", "import.view", "release.build", "release.publish", "release.rollback", "mapping.edit", "mapping.validate", "mapping.activate", "target.manage", "cost.view", "cost.edit", "task.view", "task.retry", "task.cancel"));
case "AUDIT_VIEWER"->out.addAll(List.of("audit.view","source.evidence","source.download"));default->{}}if(roles.stream().anyMatch(Set.of("SYSTEM_ADMIN","QUALITY_VIEWER","BUSINESS_ANALYST","AUDIT_VIEWER")::contains))out.addAll(List.of("rule.view","mapping.view","release.view","metric.view"));if(roles.contains("RULE_MAINTAINER"))out.addAll(List.of("rule.view","mapping.view","cost.view","metric.view"));if(roles.contains("DATA_MAINTAINER"))out.addAll(List.of("mapping.view","cost.view","release.view","import.view"));if(roles.contains("DATA_PUBLISHER"))out.addAll(List.of("release.view","import.view"));return out;} if ("SYSTEM_ADMIN".equals(role))
out.addAll(List.of("rule.edit", "rule.validate", "rule.activate", "monitor.view", "backup.manage", "restore.isolated", "iam.manage", "service.manage", "audit.view", "inspection.manage"));
return out;
}
} }
@@ -19,6 +19,19 @@ public class GovernanceAccessService {
private final JsonMapper json; private final JsonMapper json;
public GovernanceAccessService(JdbcTemplate jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; } public GovernanceAccessService(JdbcTemplate jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; }
/** 角色改名沿用原指纹中的角色部分;实际角色改变后立即失效,不授予旧角色权限。 */
public List<String> fingerprintRoles(AppUserPrincipal user) {
List<String> current = user.getRoleCodes();
if (current.size() != 1 || !cn.yunsheng.quality.identity.AppRoles.CODES.contains(current.getFirst())) return current;
List<Map<String,Object>> anchors = jdbc.query("SELECT assigned_role,previous_roles FROM user_role_migration_anchor WHERE user_id=?",
(rs,n) -> Map.of("role",rs.getString(1),"previous",readList(rs.getString(2))),user.getId().toString());
if (anchors.isEmpty() || !current.getFirst().equals(anchors.getFirst().get("role"))) return current;
Object raw = anchors.getFirst().get("previous");
if (!(raw instanceof List<?> values) || values.isEmpty() || values.stream().anyMatch(v -> !(v instanceof String))) return current;
List<String> previous = values.stream().map(String.class::cast).distinct().sorted().toList();
return current.getFirst().equals(cn.yunsheng.quality.identity.AppRoles.migratedRole(previous)) ? previous : current;
}
public void requireDetail(AppUserPrincipal user) { public void requireDetail(AppUserPrincipal user) {
if (!Boolean.TRUE.equals(policy(user.getId().toString()).get("detailAllowed"))) denied("此身份仅允许汇总查询"); if (!Boolean.TRUE.equals(policy(user.getId().toString()).get("detailAllowed"))) denied("此身份仅允许汇总查询");
} }
@@ -3,7 +3,7 @@ import java.util.Map;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/governance") @RestController @RequestMapping("/api/governance")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','RULE_MAINTAINER','DATA_MAINTAINER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class GovernanceDependencyController { public class GovernanceDependencyController {
private final GovernanceDependencyService dependencies; private final GovernanceDependencyService dependencies;
private final GovernanceAccessService access; private final GovernanceAccessService access;
@@ -18,10 +18,10 @@ public class GovernanceIdentityController {
public GovernanceIdentityController(GovernanceSupport g,GovernanceAccessService access){this.g=g;this.access=access;} public GovernanceIdentityController(GovernanceSupport g,GovernanceAccessService access){this.g=g;this.access=access;}
@GetMapping("/users/{id}/access-policy") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @GetMapping("/users/{id}/access-policy") @PreAuthorize("hasRole('SYSTEM_ADMIN')")
public Map<String,Object> policy(@PathVariable String id){g.one("SELECT id FROM app_user WHERE id=?",id);return Map.of("policy",access.policy(id));} public Map<String,Object> policy(@PathVariable String id){g.one("SELECT id FROM app_user WHERE id=? AND deleted_at IS NULL",id);return Map.of("policy",access.policy(id));}
@PutMapping("/users/{id}/access-policy") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @Transactional @PutMapping("/users/{id}/access-policy") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @Transactional
public Map<String,Object> policy(@PathVariable String id,@RequestBody PolicyRequest r,@AuthenticationPrincipal AppUserPrincipal actor){ public Map<String,Object> policy(@PathVariable String id,@RequestBody PolicyRequest r,@AuthenticationPrincipal AppUserPrincipal actor){
g.one("SELECT id FROM app_user WHERE id=? FOR UPDATE",id);g.required(r.reason(),"理由"); g.one("SELECT id FROM app_user WHERE id=? AND deleted_at IS NULL FOR UPDATE",id);g.required(r.reason(),"理由");
if(r.allowedFields()!=null&&r.allowedFields().stream().anyMatch(Objects::isNull))throw error(HttpStatus.BAD_REQUEST,"字段清单无效"); if(r.allowedFields()!=null&&r.allowedFields().stream().anyMatch(Objects::isNull))throw error(HttpStatus.BAD_REQUEST,"字段清单无效");
List<String> fields=r.allowedFields()==null?List.of():r.allowedFields().stream().distinct().sorted().toList(); List<String> fields=r.allowedFields()==null?List.of():r.allowedFields().stream().distinct().sorted().toList();
if(fields.size()>300||fields.stream().anyMatch(f->f==null||f.isBlank()||f.length()>190)||fields.contains("*")&&fields.size()!=1)throw error(HttpStatus.BAD_REQUEST,"字段清单无效"); if(fields.size()>300||fields.stream().anyMatch(f->f==null||f.isBlank()||f.length()>190)||fields.contains("*")&&fields.size()!=1)throw error(HttpStatus.BAD_REQUEST,"字段清单无效");
@@ -33,7 +33,7 @@ public class GovernanceIdentityController {
g.jdbc.update("UPDATE user_access_policy SET valid_until=?,inherit_department_children=? WHERE user_id=?",expiry,r.inheritDepartmentChildren(),id); g.jdbc.update("UPDATE user_access_policy SET valid_until=?,inherit_department_children=? WHERE user_id=?",expiry,r.inheritDepartmentChildren(),id);
g.audit(actor.getId().toString(),"ACCESS_POLICY_CHANGED","app_user",id,Map.of("before",before,"after",access.policy(id),"reason",r.reason()));return policy(id); g.audit(actor.getId().toString(),"ACCESS_POLICY_CHANGED","app_user",id,Map.of("before",before,"after",access.policy(id),"reason",r.reason()));return policy(id);
} }
@GetMapping("/service-identities") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','AUDIT_VIEWER')") @GetMapping("/service-identities") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String,Object> identities(){return Map.of("items",g.rows("SELECT id,name,service_type,allowed_actions,credential_reference,credential_status,active,row_version,created_at,updated_at FROM service_identity ORDER BY name"),"allowedActions",ACTIONS,"serviceTypes",TYPE_ACTIONS.keySet());} public Map<String,Object> identities(){return Map.of("items",g.rows("SELECT id,name,service_type,allowed_actions,credential_reference,credential_status,active,row_version,created_at,updated_at FROM service_identity ORDER BY name"),"allowedActions",ACTIONS,"serviceTypes",TYPE_ACTIONS.keySet());}
@PostMapping("/service-identities") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @Transactional @PostMapping("/service-identities") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @Transactional
public Map<String,Object> create(@RequestBody IdentityRequest r,@AuthenticationPrincipal AppUserPrincipal actor){ public Map<String,Object> create(@RequestBody IdentityRequest r,@AuthenticationPrincipal AppUserPrincipal actor){
@@ -54,11 +54,11 @@ public class GovernanceIdentityController {
lock(id,r.expectedRowVersion());reference(r.credentialReference(),r.credentialStatus());g.required(r.reason(),"轮换理由"); lock(id,r.expectedRowVersion());reference(r.credentialReference(),r.credentialStatus());g.required(r.reason(),"轮换理由");
g.jdbc.update("UPDATE service_identity SET credential_reference=?,credential_status=?,active=IF(?='READY',active,FALSE),row_version=row_version+1 WHERE id=?",r.credentialReference(),r.credentialStatus(),r.credentialStatus(),id);rotation(id,r.credentialReference(),r.credentialStatus(),r.reason(),actor);return Map.of("identity",identity(id)); g.jdbc.update("UPDATE service_identity SET credential_reference=?,credential_status=?,active=IF(?='READY',active,FALSE),row_version=row_version+1 WHERE id=?",r.credentialReference(),r.credentialStatus(),r.credentialStatus(),id);rotation(id,r.credentialReference(),r.credentialStatus(),r.reason(),actor);return Map.of("identity",identity(id));
} }
@GetMapping("/service-identities/{id}/rotations") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','AUDIT_VIEWER')") @GetMapping("/service-identities/{id}/rotations") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String,Object> rotations(@PathVariable String id){return Map.of("items",g.rows("SELECT id,credential_reference,credential_status,reason,changed_by,created_at FROM service_credential_rotation WHERE service_identity_id=? ORDER BY id DESC",id));} public Map<String,Object> rotations(@PathVariable String id){return Map.of("items",g.rows("SELECT id,credential_reference,credential_status,reason,changed_by,created_at FROM service_credential_rotation WHERE service_identity_id=? ORDER BY id DESC",id));}
@PostMapping("/service-identities/{id}/authorize") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @PostMapping("/service-identities/{id}/authorize") @PreAuthorize("hasRole('SYSTEM_ADMIN')")
public Map<String,Object> authorize(@PathVariable String id,@RequestBody Map<String,String> r){access.requireServiceAction(id,r.get("action"));return Map.of("authorized",true,"identityId",id,"action",r.get("action"));} public Map<String,Object> authorize(@PathVariable String id,@RequestBody Map<String,String> r){access.requireServiceAction(id,r.get("action"));return Map.of("authorized",true,"identityId",id,"action",r.get("action"));}
@GetMapping("/service-bindings") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR')") @GetMapping("/service-bindings") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public Map<String,Object> bindings(){return Map.of("items",g.rows("SELECT service_type,service_identity_id,updated_at FROM service_binding"));} public Map<String,Object> bindings(){return Map.of("items",g.rows("SELECT service_type,service_identity_id,updated_at FROM service_binding"));}
@PutMapping("/service-bindings/{type}") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @Transactional @PutMapping("/service-bindings/{type}") @PreAuthorize("hasRole('SYSTEM_ADMIN')") @Transactional
public Map<String,Object> bind(@PathVariable String type,@RequestBody Map<String,String> r,@AuthenticationPrincipal AppUserPrincipal actor){ public Map<String,Object> bind(@PathVariable String type,@RequestBody Map<String,String> r,@AuthenticationPrincipal AppUserPrincipal actor){
@@ -8,7 +8,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import static cn.yunsheng.quality.governance.GovernanceSupport.error; import static cn.yunsheng.quality.governance.GovernanceSupport.error;
@RestController @RequestMapping("/api/governance") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR')") @RestController @RequestMapping("/api/governance") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN')")
public class GovernanceOperationsController { public class GovernanceOperationsController {
private final GovernanceOperationsService service;private final GovernanceSupport g; private final GovernanceOperationsService service;private final GovernanceSupport g;
public GovernanceOperationsController(GovernanceOperationsService service,GovernanceSupport g){this.service=service;this.g=g;} public GovernanceOperationsController(GovernanceOperationsService service,GovernanceSupport g){this.service=service;this.g=g;}
@@ -24,7 +24,7 @@ public class GovernanceOperationsController {
g.jdbc.update("UPDATE monitor_alert_policy SET queue_age_minutes=?,disk_free_bytes=?,backup_age_hours=?,quiet_period_minutes=?,severity_overrides=CAST(? AS JSON),silence_until=?,slow_request_millis=?,row_version=row_version+1,updated_by=? WHERE id='default'",r.queueAgeMinutes(),r.diskFreeBytes(),r.backupAgeHours(),r.quietPeriodMinutes(),g.encode(r.severityOverrides()),silence,slow,actor.getId().toString());g.audit(actor.getId().toString(),"MONITOR_ALERT_POLICY_CHANGED","monitor_alert_policy","default",Map.of("reason",r.reason(),"before",before,"after",service.alertPolicy()));return alertPolicy();} g.jdbc.update("UPDATE monitor_alert_policy SET queue_age_minutes=?,disk_free_bytes=?,backup_age_hours=?,quiet_period_minutes=?,severity_overrides=CAST(? AS JSON),silence_until=?,slow_request_millis=?,row_version=row_version+1,updated_by=? WHERE id='default'",r.queueAgeMinutes(),r.diskFreeBytes(),r.backupAgeHours(),r.quietPeriodMinutes(),g.encode(r.severityOverrides()),silence,slow,actor.getId().toString());g.audit(actor.getId().toString(),"MONITOR_ALERT_POLICY_CHANGED","monitor_alert_policy","default",Map.of("reason",r.reason(),"before",before,"after",service.alertPolicy()));return alertPolicy();}
@GetMapping("/backups")public Map<String,Object> backups(){return Map.of("items",service.backups(),"plan",g.one("SELECT * FROM backup_plan WHERE id='default'"),"liveRestoreEnabled",false);} @GetMapping("/backups")public Map<String,Object> backups(){return Map.of("items",service.backups(),"plan",g.one("SELECT * FROM backup_plan WHERE id='default'"),"liveRestoreEnabled",false);}
@GetMapping("/backups/latest") @GetMapping("/backups/latest")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> latestBackup(){ public Map<String,Object> latestBackup(){
Map<String,Object> latest=service.backups().stream().max(Comparator.comparing(b->String.valueOf(b.get("createdAt")))).orElse(Map.of()); Map<String,Object> latest=service.backups().stream().max(Comparator.comparing(b->String.valueOf(b.get("createdAt")))).orElse(Map.of());
Map<String,Object> safe=new LinkedHashMap<>(); Map<String,Object> safe=new LinkedHashMap<>();
@@ -77,7 +77,7 @@ public class GovernanceOperationsService {
g.jdbc.update("UPDATE task SET status='FAILED',stage='FAILED',error_code=?,error_message=?,result=CAST(? AS JSON),retry_count=retry_count+1,next_retry_at=IF(retry_count<max_retries,TIMESTAMPADD(SECOND,30*POW(2,retry_count),CURRENT_TIMESTAMP(6)),NULL),lease_expires_at=NULL WHERE id=? AND lease_token=?",failureCode,failureMessage,g.encode(details),id,token); g.jdbc.update("UPDATE task SET status='FAILED',stage='FAILED',error_code=?,error_message=?,result=CAST(? AS JSON),retry_count=retry_count+1,next_retry_at=IF(retry_count<max_retries,TIMESTAMPADD(SECOND,30*POW(2,retry_count),CURRENT_TIMESTAMP(6)),NULL),lease_expires_at=NULL WHERE id=? AND lease_token=?",failureCode,failureMessage,g.encode(details),id,token);
} }
} }
private void requireOperator(String user){Integer count=g.jdbc.queryForObject("SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id WHERE u.id=? AND u.active=TRUE AND r.role_code IN('SYSTEM_ADMIN','SYSTEM_OPERATOR') AND NOT EXISTS(SELECT 1 FROM user_access_policy p WHERE p.user_id=u.id AND p.valid_until<CURRENT_TIMESTAMP(6))",Integer.class,user);if(count==null||count==0)throw error(HttpStatus.FORBIDDEN,"运维授权失效");} private void requireOperator(String user){Integer count=g.jdbc.queryForObject("SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id WHERE u.id=? AND u.active=TRUE AND r.role_code IN('SYSTEM_ADMIN') AND NOT EXISTS(SELECT 1 FROM user_access_policy p WHERE p.user_id=u.id AND p.valid_until<CURRENT_TIMESTAMP(6))",Integer.class,user);if(count==null||count==0)throw error(HttpStatus.FORBIDDEN,"运维授权失效");}
private Map<String,Object> runBackup(String type,Map<String,Object> payload)throws Exception{ private Map<String,Object> runBackup(String type,Map<String,Object> payload)throws Exception{
Path script=root.resolve("scripts/backup.py").toRealPath();if(!script.startsWith(root)||!Files.isRegularFile(script))throw new IllegalStateException("Fixed backup script missing"); Path script=root.resolve("scripts/backup.py").toRealPath();if(!script.startsWith(root)||!Files.isRegularFile(script))throw new IllegalStateException("Fixed backup script missing");
List<String> command=new ArrayList<>(List.of("python3",script.toString(),"BACKUP_VERIFY".equals(type)?"verify":"create-and-verify"));Path selected=null; List<String> command=new ArrayList<>(List.of("python3",script.toString(),"BACKUP_VERIFY".equals(type)?"verify":"create-and-verify"));Path selected=null;
@@ -5,7 +5,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/governance/mapping-issues") @RestController @RequestMapping("/api/governance/mapping-issues")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER','DATA_MAINTAINER','RULE_MAINTAINER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class MappingIssueController { public class MappingIssueController {
private final MappingIssueService service; private final MappingIssueService service;
private final UnclassifiedSourceService unclassified; private final UnclassifiedSourceService unclassified;
@@ -19,8 +19,8 @@ public class MappingIssueController {
@GetMapping("/unclassified-projects") public Map<String,Object> unclassifiedProjects(@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="15") int pageSize,@RequestParam(required=false) String customerCode,@RequestParam(required=false) String businessGroup,@RequestParam(required=false) String department,@AuthenticationPrincipal AppUserPrincipal actor){return unclassified.listProjects(page,pageSize,customerCode,businessGroup,department,actor);} @GetMapping("/unclassified-projects") public Map<String,Object> unclassifiedProjects(@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="15") int pageSize,@RequestParam(required=false) String customerCode,@RequestParam(required=false) String businessGroup,@RequestParam(required=false) String department,@AuthenticationPrincipal AppUserPrincipal actor){return unclassified.listProjects(page,pageSize,customerCode,businessGroup,department,actor);}
@GetMapping public Map<String,Object> list(@RequestParam(required=false) String importRunId,@RequestParam(required=false) String status,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="50") int pageSize,@RequestParam(required=false) String mappingType,@RequestParam(required=false) String customerCode,@RequestParam(required=false) String businessGroup,@RequestParam(required=false) String department,@AuthenticationPrincipal AppUserPrincipal actor){return service.list(importRunId,status,page,pageSize,customerCode,businessGroup,department,mappingType,actor);} @GetMapping public Map<String,Object> list(@RequestParam(required=false) String importRunId,@RequestParam(required=false) String status,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="50") int pageSize,@RequestParam(required=false) String mappingType,@RequestParam(required=false) String customerCode,@RequestParam(required=false) String businessGroup,@RequestParam(required=false) String department,@AuthenticationPrincipal AppUserPrincipal actor){return service.list(importRunId,status,page,pageSize,customerCode,businessGroup,department,mappingType,actor);}
@GetMapping("/{id}") public Map<String,Object> detail(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return service.detail(id,actor);} @GetMapping("/{id}") public Map<String,Object> detail(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return service.detail(id,actor);}
@PostMapping("/{id}/resolve") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER')") @PostMapping("/{id}/resolve") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> resolve(@PathVariable String id,@RequestBody MappingIssueService.Resolution request,@AuthenticationPrincipal AppUserPrincipal actor){return service.resolve(id,request,actor);} public Map<String,Object> resolve(@PathVariable String id,@RequestBody MappingIssueService.Resolution request,@AuthenticationPrincipal AppUserPrincipal actor){return service.resolve(id,request,actor);}
@PostMapping("/{id}/revalidate") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PostMapping("/{id}/revalidate") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> revalidate(@PathVariable String id,@RequestBody MappingIssueService.Revalidation request,@AuthenticationPrincipal AppUserPrincipal actor){return service.revalidate(id,request,actor);} public Map<String,Object> revalidate(@PathVariable String id,@RequestBody MappingIssueService.Revalidation request,@AuthenticationPrincipal AppUserPrincipal actor){return service.revalidate(id,request,actor);}
} }
@@ -5,7 +5,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/governance") @RestController @RequestMapping("/api/governance")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','RULE_MAINTAINER','DATA_PUBLISHER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class RuleRegressionController { public class RuleRegressionController {
private final RuleRegressionService service; private final RuleRegressionService service;
public RuleRegressionController(RuleRegressionService service){this.service=service;} public RuleRegressionController(RuleRegressionService service){this.service=service;}
@@ -16,13 +16,13 @@ import static cn.yunsheng.quality.governance.GovernanceSupport.error;
public class SourceGovernanceController { public class SourceGovernanceController {
private final SourceGovernanceService service;private final GovernanceSupport g;private final GovernanceAccessService access;private final SourceScanner scanner; private final SourceGovernanceService service;private final GovernanceSupport g;private final GovernanceAccessService access;private final SourceScanner scanner;
public SourceGovernanceController(SourceGovernanceService service,GovernanceSupport g,GovernanceAccessService access,SourceScanner scanner){this.service=service;this.g=g;this.access=access;this.scanner=scanner;} public SourceGovernanceController(SourceGovernanceService service,GovernanceSupport g,GovernanceAccessService access,SourceScanner scanner){this.service=service;this.g=g;this.access=access;this.scanner=scanner;}
@GetMapping("/protocols") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','SYSTEM_OPERATOR')") @GetMapping("/protocols") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> protocols(){return service.protocols();} public Map<String,Object> protocols(){return service.protocols();}
@PostMapping("/protocols") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PostMapping("/protocols") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> protocol(@RequestBody SourceGovernanceService.ProtocolRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.protocol(r,actor);} public Map<String,Object> protocol(@RequestBody SourceGovernanceService.ProtocolRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.protocol(r,actor);}
@PostMapping("/sources/{id}/resolve") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PostMapping("/sources/{id}/resolve") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> resolve(@PathVariable String id,@RequestBody SourceGovernanceService.ResolveRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.resolve(id,r,actor);} public Map<String,Object> resolve(@PathVariable String id,@RequestBody SourceGovernanceService.ResolveRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.resolve(id,r,actor);}
@GetMapping("/sources/{id}/identity-preview") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @GetMapping("/sources/{id}/identity-preview") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> identityPreview(@PathVariable String id,@RequestParam(required=false) String protocolId){ public Map<String,Object> identityPreview(@PathVariable String id,@RequestParam(required=false) String protocolId){
Map<String,Object> candidate=g.one("SELECT id,source_file,sha256,file_size,status,protocol_id FROM source_candidate WHERE id=?",id);String selected=protocolId==null?(String)candidate.get("protocolId"):protocolId; Map<String,Object> candidate=g.one("SELECT id,source_file,sha256,file_size,status,protocol_id FROM source_candidate WHERE id=?",id);String selected=protocolId==null?(String)candidate.get("protocolId"):protocolId;
if(selected==null)return Map.of("candidate",candidate,"protocol",Map.of(),"overlaps",List.of(),"decisionRequired",true,"allowedDecisions",List.of("RETURN","REPLACE","LEGAL_SHARD")); if(selected==null)return Map.of("candidate",candidate,"protocol",Map.of(),"overlaps",List.of(),"decisionRequired",true,"allowedDecisions",List.of("RETURN","REPLACE","LEGAL_SHARD"));
@@ -30,23 +30,23 @@ public class SourceGovernanceController {
List<Map<String,Object>> overlaps=g.rows("SELECT d.id AS source_document_id,d.source_slot,d.source_mode,d.scope_code,r.id AS source_revision_id,r.sha256,r.source_file FROM release_member m JOIN source_document d ON d.id=m.source_document_id JOIN source_revision r ON r.id=m.source_revision_id WHERE m.release_id=(SELECT release_id FROM current_release WHERE dataset_id='quality') AND d.stage=? AND d.source_year=? AND d.source_month=?",protocol.get("stage"),protocol.get("sourceYear"),protocol.get("sourceMonth")).stream().filter(d->SourceIdentity.intersects((String)protocol.get("scopeCode"),(String)d.get("scopeCode"))).toList(); List<Map<String,Object>> overlaps=g.rows("SELECT d.id AS source_document_id,d.source_slot,d.source_mode,d.scope_code,r.id AS source_revision_id,r.sha256,r.source_file FROM release_member m JOIN source_document d ON d.id=m.source_document_id JOIN source_revision r ON r.id=m.source_revision_id WHERE m.release_id=(SELECT release_id FROM current_release WHERE dataset_id='quality') AND d.stage=? AND d.source_year=? AND d.source_month=?",protocol.get("stage"),protocol.get("sourceYear"),protocol.get("sourceMonth")).stream().filter(d->SourceIdentity.intersects((String)protocol.get("scopeCode"),(String)d.get("scopeCode"))).toList();
return Map.of("candidate",candidate,"protocol",protocol,"overlaps",overlaps,"decisionRequired",true,"sameContentHint",overlaps.stream().anyMatch(o->Objects.equals(o.get("sha256"),candidate.get("sha256"))),"allowedDecisions","SHARD_SNAPSHOT".equals(protocol.get("sourceMode"))?List.of("RETURN","REPLACE","LEGAL_SHARD"):List.of("RETURN","REPLACE")); return Map.of("candidate",candidate,"protocol",protocol,"overlaps",overlaps,"decisionRequired",true,"sameContentHint",overlaps.stream().anyMatch(o->Objects.equals(o.get("sha256"),candidate.get("sha256"))),"allowedDecisions","SHARD_SNAPSHOT".equals(protocol.get("sourceMode"))?List.of("RETURN","REPLACE","LEGAL_SHARD"):List.of("RETURN","REPLACE"));
} }
@GetMapping("/source-documents") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @GetMapping("/source-documents") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> documents(){return Map.of("items",g.rows("SELECT d.id,d.source_slot,d.stage,d.source_year,d.source_month,d.scope_code,d.source_file,d.source_mode,d.applicable,(SELECT COUNT(*) FROM source_revision r WHERE r.source_document_id=d.id) AS revision_count FROM source_document d ORDER BY d.source_year,d.source_month,d.stage"),"revisions",g.rows("SELECT r.id,r.source_document_id,r.sha256,r.source_file,r.file_size,r.status,r.received_at FROM source_revision r ORDER BY r.received_at DESC"));} public Map<String,Object> documents(){return Map.of("items",g.rows("SELECT d.id,d.source_slot,d.stage,d.source_year,d.source_month,d.scope_code,d.source_file,d.source_mode,d.applicable,(SELECT COUNT(*) FROM source_revision r WHERE r.source_document_id=d.id) AS revision_count FROM source_document d ORDER BY d.source_year,d.source_month,d.stage"),"revisions",g.rows("SELECT r.id,r.source_document_id,r.sha256,r.source_file,r.file_size,r.status,r.received_at FROM source_revision r ORDER BY r.received_at DESC"));}
@GetMapping("/coverage") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','SYSTEM_OPERATOR')") @GetMapping("/coverage") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> coverage(@RequestParam(required=false) String releaseId){return service.coverage(releaseId);} public Map<String,Object> coverage(@RequestParam(required=false) String releaseId){return service.coverage(releaseId);}
@GetMapping("/source-changes") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @GetMapping("/source-changes") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> changes(){return service.changes();} public Map<String,Object> changes(){return service.changes();}
@PostMapping("/source-changes") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PostMapping("/source-changes") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> request(@RequestBody SourceGovernanceService.ChangeRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.request(r,actor);} public Map<String,Object> request(@RequestBody SourceGovernanceService.ChangeRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.request(r,actor);}
@PostMapping("/source-changes/{id}/review") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER')") @PostMapping("/source-changes/{id}/review") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> review(@PathVariable String id,@RequestBody SourceGovernanceService.ReviewRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.review(id,r,actor);} public Map<String,Object> review(@PathVariable String id,@RequestBody SourceGovernanceService.ReviewRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.review(id,r,actor);}
@PostMapping("/source-changes/{id}/build") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER')") @PostMapping("/source-changes/{id}/build") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> build(@PathVariable String id,@RequestBody SourceGovernanceService.BuildRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.build(id,r,actor);} public Map<String,Object> build(@PathVariable String id,@RequestBody SourceGovernanceService.BuildRequest r,@AuthenticationPrincipal AppUserPrincipal actor){return service.build(id,r,actor);}
@GetMapping("/source-revisions/{id}/evidence") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','BUSINESS_ANALYST','QUALITY_VIEWER','AUDIT_VIEWER')") @Transactional @GetMapping("/source-revisions/{id}/evidence") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')") @Transactional
public Map<String,Object> evidence(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){access.requireEvidence(actor);authorizeRevision(id,actor);Map<String,Object> revision=g.one("SELECT id,source_document_id,sha256,source_file,file_size,status,parser_version,received_at FROM source_revision WHERE id=?",id); public Map<String,Object> evidence(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){access.requireEvidence(actor);authorizeRevision(id,actor);Map<String,Object> revision=g.one("SELECT id,source_document_id,sha256,source_file,file_size,status,parser_version,received_at FROM source_revision WHERE id=?",id);
g.audit(actor.getId().toString(),"SOURCE_EVIDENCE_READ","source_revision",id,Map.of());return Map.of("revision",revision,"builds",g.rows("SELECT id,parser_version,rule_version,mapping_version,status,row_count,rejected_count,component_summary FROM transform_build WHERE source_revision_id=?",id));} g.audit(actor.getId().toString(),"SOURCE_EVIDENCE_READ","source_revision",id,Map.of());return Map.of("revision",revision,"builds",g.rows("SELECT id,parser_version,rule_version,mapping_version,status,row_count,rejected_count,component_summary FROM transform_build WHERE source_revision_id=?",id));}
@GetMapping("/source-revisions/{id}/download") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','BUSINESS_ANALYST','QUALITY_VIEWER','AUDIT_VIEWER')") @Transactional @GetMapping("/source-revisions/{id}/download") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')") @Transactional
public ResponseEntity<byte[]> download(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){ public ResponseEntity<byte[]> download(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){
access.requireOriginalDownload(actor);authorizeRevision(id,actor);Map<String,Object> row=g.one("SELECT r.source_file,r.archive_path,r.file_size,r.sha256,d.stage FROM source_revision r JOIN source_document d ON d.id=r.source_document_id WHERE r.id=?",id); access.requireOriginalDownload(actor);authorizeRevision(id,actor);Map<String,Object> row=g.one("SELECT r.source_file,r.archive_path,r.file_size,r.sha256,d.stage FROM source_revision r JOIN source_document d ON d.id=r.source_document_id WHERE r.id=?",id);
try{Path path=Path.of(String.valueOf(row.get("archivePath")));if(Files.isSymbolicLink(path)||!Files.isRegularFile(path,LinkOption.NOFOLLOW_LINKS)||!path.toRealPath().startsWith(scanner.archiveRoot()))throw error(HttpStatus.CONFLICT,"归档文件不完整或位置无效"); try{Path path=Path.of(String.valueOf(row.get("archivePath")));if(Files.isSymbolicLink(path)||!Files.isRegularFile(path,LinkOption.NOFOLLOW_LINKS)||!path.toRealPath().startsWith(scanner.archiveRoot()))throw error(HttpStatus.CONFLICT,"归档文件不完整或位置无效");
@@ -18,9 +18,9 @@ public class TaskRetryService {
@SuppressWarnings("unchecked") public Map<String,Object> retry(String taskId,String key,String expectedCurrent,AppUserPrincipal actor){ @SuppressWarnings("unchecked") public Map<String,Object> retry(String taskId,String key,String expectedCurrent,AppUserPrincipal actor){
g.required(key,"幂等键");String runId=tx.execute(status->{Map<String,Object> task=g.one("SELECT * FROM task WHERE id=? FOR UPDATE",taskId); g.required(key,"幂等键");String runId=tx.execute(status->{Map<String,Object> task=g.one("SELECT * FROM task WHERE id=? FOR UPDATE",taskId);
boolean background=Set.of("RELEASE_POST_PUBLISH","BACKUP_CREATE_VERIFY","BACKUP_VERIFY").contains(String.valueOf(task.get("taskType"))); boolean background=Set.of("RELEASE_POST_PUBLISH","BACKUP_CREATE_VERIFY","BACKUP_VERIFY").contains(String.valueOf(task.get("taskType")));
if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!(background&&actor.getRoleCodes().contains("SYSTEM_OPERATOR"))&&!Objects.equals(task.get("createdBy"),actor.getId().toString()))throw error(HttpStatus.FORBIDDEN,"只能重试本人任务"); if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!(background&&actor.getRoleCodes().contains("SYSTEM_ADMIN"))&&!Objects.equals(task.get("createdBy"),actor.getId().toString()))throw error(HttpStatus.FORBIDDEN,"只能重试本人任务");
if(background){ if(background){
if(actor.getRoleCodes().stream().noneMatch(Set.of("SYSTEM_ADMIN","SYSTEM_OPERATOR")::contains))throw error(HttpStatus.FORBIDDEN,"后台运维任务需要运维授权"); if(actor.getRoleCodes().stream().noneMatch(Set.of("SYSTEM_ADMIN")::contains))throw error(HttpStatus.FORBIDDEN,"后台运维任务需要运维授权");
String requestKey="BACKGROUND_RETRY:"+GovernanceSupport.sha(key);List<Map<String,Object>> prior=g.rows("SELECT id,retry_parent_id,created_by FROM task WHERE idempotency_key=?",requestKey);if(!prior.isEmpty()){if(!Objects.equals(prior.getFirst().get("retryParentId"),taskId)||!Objects.equals(prior.getFirst().get("createdBy"),actor.getId().toString()))throw error(HttpStatus.CONFLICT,"幂等键已被使用");return "task:"+prior.getFirst().get("id");} String requestKey="BACKGROUND_RETRY:"+GovernanceSupport.sha(key);List<Map<String,Object>> prior=g.rows("SELECT id,retry_parent_id,created_by FROM task WHERE idempotency_key=?",requestKey);if(!prior.isEmpty()){if(!Objects.equals(prior.getFirst().get("retryParentId"),taskId)||!Objects.equals(prior.getFirst().get("createdBy"),actor.getId().toString()))throw error(HttpStatus.CONFLICT,"幂等键已被使用");return "task:"+prior.getFirst().get("id");}
if(!"FAILED".equals(task.get("status")))throw error(HttpStatus.CONFLICT,"只有失败任务可以重试"); if(!"FAILED".equals(task.get("status")))throw error(HttpStatus.CONFLICT,"只有失败任务可以重试");
String rootId=task.get("retryRootId")==null?taskId:String.valueOf(task.get("retryRootId"));Map<String,Object> root=rootId.equals(taskId)?task:g.one("SELECT retry_count,max_retries FROM task WHERE id=? FOR UPDATE",rootId);int count=((Number)root.get("retryCount")).intValue(),max=((Number)root.get("maxRetries")).intValue();if(count>=max)throw error(HttpStatus.CONFLICT,"此后台任务链已达重试上限"); String rootId=task.get("retryRootId")==null?taskId:String.valueOf(task.get("retryRootId"));Map<String,Object> root=rootId.equals(taskId)?task:g.one("SELECT retry_count,max_retries FROM task WHERE id=? FOR UPDATE",rootId);int count=((Number)root.get("retryCount")).intValue(),max=((Number)root.get("maxRetries")).intValue();if(count>=max)throw error(HttpStatus.CONFLICT,"此后台任务链已达重试上限");
@@ -35,10 +35,7 @@ public class AdminBootstrapRunner implements ApplicationRunner {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
jdbc.update("INSERT INTO app_user (id, username, display_name, password_hash, active) VALUES (?, ?, ?, ?, TRUE)", jdbc.update("INSERT INTO app_user (id, username, display_name, password_hash, active) VALUES (?, ?, ?, ?, TRUE)",
id.toString(), username, username, encoder.encode(password)); id.toString(), username, username, encoder.encode(password));
for (String role : new String[]{"SYSTEM_ADMIN", "QUALITY_VIEWER", "BUSINESS_ANALYST", "DATA_MAINTAINER", jdbc.update("INSERT INTO app_user_role (user_id, role_code) VALUES (?, 'SYSTEM_ADMIN')", id.toString());
"RULE_MAINTAINER", "DATA_PUBLISHER", "SYSTEM_OPERATOR", "AUDIT_VIEWER"}) {
jdbc.update("INSERT INTO app_user_role (user_id, role_code) VALUES (?, ?)", id.toString(), role);
}
jdbc.update("INSERT INTO app_user_scope (user_id, scope_type, scope_value) VALUES (?, 'DEPARTMENT', '质量中心')", id.toString()); jdbc.update("INSERT INTO app_user_scope (user_id, scope_type, scope_value) VALUES (?, 'DEPARTMENT', '质量中心')", id.toString());
} }
} }
@@ -0,0 +1,36 @@
package cn.yunsheng.quality.identity;
import java.util.List;
import java.util.Set;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.server.ResponseStatusException;
/** Exactly one assigned role; higher roles inherit lower operation permissions, never data scopes. */
public final class AppRoles {
public static final Set<String> CODES = Set.of("USER", "DATA_ADMIN", "SYSTEM_ADMIN");
private AppRoles() {}
public static String migratedRole(List<String> previous) {
if (previous.contains("SYSTEM_ADMIN")) return "SYSTEM_ADMIN";
if (previous.stream().anyMatch(Set.of("DATA_ADMIN", "DATA_MAINTAINER", "DATA_PUBLISHER", "RULE_MAINTAINER")::contains)) return "DATA_ADMIN";
if (previous.stream().anyMatch(Set.of("USER", "QUALITY_VIEWER", "BUSINESS_ANALYST", "SYSTEM_OPERATOR", "AUDIT_VIEWER")::contains)) return "USER";
return "";
}
public static List<String> validate(List<String> roles) {
if (roles == null || roles.size() != 1 || roles.getFirst() == null || !CODES.contains(roles.getFirst()))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请选择一个角色:用户、数据管理员或系统管理员");
return List.copyOf(roles);
}
public static List<SimpleGrantedAuthority> authorities(List<String> roles) {
if (roles == null || roles.size() != 1 || roles.getFirst() == null || !CODES.contains(roles.getFirst())) return List.of();
List<String> inherited = switch (roles.getFirst()) {
case "SYSTEM_ADMIN" -> List.of("SYSTEM_ADMIN", "DATA_ADMIN", "USER");
case "DATA_ADMIN" -> List.of("DATA_ADMIN", "USER");
default -> List.of("USER");
};
return inherited.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).toList();
}
}
@@ -1,10 +1,8 @@
package cn.yunsheng.quality.identity; package cn.yunsheng.quality.identity;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -32,7 +30,7 @@ public class JdbcAppUserDetailsService implements UserDetailsService {
(rs, row) -> rs.getString(1), user.id().toString()); (rs, row) -> rs.getString(1), user.id().toString());
List<String> departments = scopeValues(user.id(), "DEPARTMENT"); List<String> departments = scopeValues(user.id(), "DEPARTMENT");
List<String> groups = scopeValues(user.id(), "GROUP"); List<String> groups = scopeValues(user.id(), "GROUP");
var authorities = roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).toList(); var authorities = AppRoles.authorities(roles);
return new AppUserPrincipal(user.id(), user.username(), user.passwordHash(), user.displayName(), user.active(), return new AppUserPrincipal(user.id(), user.username(), user.passwordHash(), user.displayName(), user.active(),
user.forcePasswordChange(), roles, departments, groups, authorities); user.forcePasswordChange(), roles, departments, groups, authorities);
} }
@@ -21,7 +21,7 @@ public class ImportRunController {
public ImportRunController(ImportRunService service, ImportWorker worker) { this.service = service; this.worker = worker; } public ImportRunController(ImportRunService service, ImportWorker worker) { this.service = service; this.worker = worker; }
@PostMapping @PostMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> create(@Valid @RequestBody ImportRunService.CreateImportRequest request, public Map<String, Object> create(@Valid @RequestBody ImportRunService.CreateImportRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
try { try {
@@ -26,7 +26,7 @@ public class ImportRunReadController {
public ImportRunReadController(JdbcTemplate jdbc, JsonMapper json,cn.yunsheng.quality.governance.GovernanceAccessService access) { this.jdbc = jdbc; this.json = json;this.access=access; } public ImportRunReadController(JdbcTemplate jdbc, JsonMapper json,cn.yunsheng.quality.governance.GovernanceAccessService access) { this.jdbc = jdbc; this.json = json;this.access=access; }
@GetMapping("/{id}") @GetMapping("/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> get(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> get(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor) {
authorize(id,actor); authorize(id,actor);
List<Map<String, Object>> rows = jdbc.query(""" List<Map<String, Object>> rows = jdbc.query("""
@@ -46,7 +46,7 @@ public class ImportRunReadController {
} }
@GetMapping("/{id}/issues") @GetMapping("/{id}/issues")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER','DATA_PUBLISHER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> issues(@PathVariable String id, public Map<String, Object> issues(@PathVariable String id,
@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "50") int pageSize,@AuthenticationPrincipal AppUserPrincipal actor) { @RequestParam(defaultValue = "50") int pageSize,@AuthenticationPrincipal AppUserPrincipal actor) {
@@ -70,7 +70,7 @@ public class ImportRunReadController {
if(!access.hasFullFields(actor))items=items.stream().map(i->{i.remove("details");if(!access.allowedFields(actor).contains(String.valueOf(i.get("field")))){i.remove("field");i.put("message","字段受限:请联系有权维护者处理");}return i;}).toList(); if(!access.hasFullFields(actor))items=items.stream().map(i->{i.remove("details");if(!access.allowedFields(actor).contains(String.valueOf(i.get("field")))){i.remove("field");i.put("message","字段受限:请联系有权维护者处理");}return i;}).toList();
return Map.of("items", items, "total", total == null ? 0 : total, "page", page, "pageSize", pageSize); return Map.of("items", items, "total", total == null ? 0 : total, "page", page, "pageSize", pageSize);
} }
private void authorize(String id,AppUserPrincipal actor){List<String> owners=jdbc.query("SELECT created_by FROM import_run WHERE id=?",(rs,n)->rs.getString(1),id);if(owners.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"导入任务不存在");if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!actor.getRoleCodes().contains("SYSTEM_OPERATOR")&&!java.util.Objects.equals(owners.getFirst(),actor.getId().toString()))throw new ResponseStatusException(HttpStatus.FORBIDDEN,"无权访问该导入任务");} private void authorize(String id,AppUserPrincipal actor){List<String> owners=jdbc.query("SELECT created_by FROM import_run WHERE id=?",(rs,n)->rs.getString(1),id);if(owners.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"导入任务不存在");if(!actor.getRoleCodes().contains("SYSTEM_ADMIN")&&!java.util.Objects.equals(owners.getFirst(),actor.getId().toString()))throw new ResponseStatusException(HttpStatus.FORBIDDEN,"无权访问该导入任务");}
private Object readJson(String value) { private Object readJson(String value) {
if (value == null) return Map.of(); if (value == null) return Map.of();
@@ -53,7 +53,7 @@ public class ImportRunService {
private ImportRunView create(CreateImportRequest request, UUID actorId, int maximumSources) { private ImportRunView create(CreateImportRequest request, UUID actorId, int maximumSources) {
access.requireBoundAction("IMPORTER","import.run"); access.requireBoundAction("IMPORTER","import.run");
Integer active=jdbc.queryForObject("SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id WHERE u.id=? AND u.active=TRUE AND r.role_code IN('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')",Integer.class,actorId.toString()); Integer active=jdbc.queryForObject("SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id WHERE u.id=? AND u.active=TRUE AND r.role_code IN('SYSTEM_ADMIN', 'DATA_ADMIN')",Integer.class,actorId.toString());
if(active==null||active==0)throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"当前身份已不再具有导入/候选构建权限"); if(active==null||active==0)throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"当前身份已不再具有导入/候选构建权限");
if (request.sourceIds() == null || request.sourceIds().isEmpty() || request.sourceIds().size() > maximumSources) { if (request.sourceIds() == null || request.sourceIds().isEmpty() || request.sourceIds().size() > maximumSources) {
throw new IllegalArgumentException("请选择 1 到 " + maximumSources + " 个数据源"); throw new IllegalArgumentException("请选择 1 到 " + maximumSources + " 个数据源");
@@ -137,7 +137,7 @@ public class ImportRunService {
List<Boolean> active=jdbc.query("SELECT active FROM app_user WHERE id=? FOR UPDATE",(rs,n)->rs.getBoolean(1),actorId); List<Boolean> active=jdbc.query("SELECT active FROM app_user WHERE id=? FOR UPDATE",(rs,n)->rs.getBoolean(1),actorId);
if(active.isEmpty()||!active.getFirst())throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"提交人已停用"); if(active.isEmpty()||!active.getFirst())throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"提交人已停用");
List<String> roles=jdbc.query("SELECT role_code FROM app_user_role WHERE user_id=? FOR UPDATE",(rs,n)->rs.getString(1),actorId); List<String> roles=jdbc.query("SELECT role_code FROM app_user_role WHERE user_id=? FOR UPDATE",(rs,n)->rs.getString(1),actorId);
if(roles.stream().noneMatch(java.util.Set.of("SYSTEM_ADMIN","DATA_MAINTAINER","DATA_PUBLISHER")::contains))throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"提交人已无导入权限"); if(roles.stream().noneMatch(java.util.Set.of("SYSTEM_ADMIN", "DATA_ADMIN")::contains))throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.FORBIDDEN,"提交人已无导入权限");
List<String> departments=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='DEPARTMENT' FOR UPDATE",(rs,n)->rs.getString(1),actorId); List<String> departments=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='DEPARTMENT' FOR UPDATE",(rs,n)->rs.getString(1),actorId);
List<String> groups=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='GROUP' FOR UPDATE",(rs,n)->rs.getString(1),actorId); List<String> groups=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='GROUP' FOR UPDATE",(rs,n)->rs.getString(1),actorId);
var actor=new cn.yunsheng.quality.identity.AppUserPrincipal(UUID.fromString(actorId),actorId,"","",true,false,roles,departments,groups,List.of()); var actor=new cn.yunsheng.quality.identity.AppUserPrincipal(UUID.fromString(actorId),actorId,"","",true,false,roles,departments,groups,List.of());
@@ -67,7 +67,7 @@ public class ImportWorker {
if (runs.isEmpty()) throw new IllegalArgumentException("导入任务不存在"); if (runs.isEmpty()) throw new IllegalArgumentException("导入任务不存在");
RunRow run = runs.getFirst(); RunRow run = runs.getFirst();
if (List.of("COMPLETED", "FAILED", "CANCELLED").contains(run.status())) return getRun(runId); if (List.of("COMPLETED", "FAILED", "CANCELLED").contains(run.status())) return getRun(runId);
Integer authorized=jdbc.queryForObject("SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id WHERE u.id=? AND u.active=TRUE AND r.role_code IN('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')",Integer.class,run.createdBy()); Integer authorized=jdbc.queryForObject("SELECT COUNT(*) FROM app_user u JOIN app_user_role r ON r.user_id=u.id WHERE u.id=? AND u.active=TRUE AND r.role_code IN('SYSTEM_ADMIN', 'DATA_ADMIN')",Integer.class,run.createdBy());
if(authorized==null||authorized==0)return fail(runId,"AUTHORIZATION_REVOKED","提交人已停用或撤回导入权限,请由有效维护者重新提交"); if(authorized==null||authorized==0)return fail(runId,"AUTHORIZATION_REVOKED","提交人已停用或撤回导入权限,请由有效维护者重新提交");
String expectedPointer = run.expectedCurrentReleaseId(); String expectedPointer = run.expectedCurrentReleaseId();
String currentPointer = currentReleaseId(); String currentPointer = currentReleaseId();
@@ -455,7 +455,7 @@ public class ImportWorker {
} }
private boolean authorizedToSubmit(String actor,List<BuildMember> members){ private boolean authorizedToSubmit(String actor,List<BuildMember> members){
List<Boolean> enabled=jdbc.query("SELECT active FROM app_user WHERE id=? FOR UPDATE",(rs,n)->rs.getBoolean(1),actor);if(enabled.isEmpty()||!enabled.getFirst())return false; List<Boolean> enabled=jdbc.query("SELECT active FROM app_user WHERE id=? FOR UPDATE",(rs,n)->rs.getBoolean(1),actor);if(enabled.isEmpty()||!enabled.getFirst())return false;
List<String> roles=jdbc.query("SELECT role_code FROM app_user_role WHERE user_id=? FOR UPDATE",(rs,n)->rs.getString(1),actor);if(roles.stream().noneMatch(Set.of("SYSTEM_ADMIN","DATA_MAINTAINER","DATA_PUBLISHER")::contains))return false; List<String> roles=jdbc.query("SELECT role_code FROM app_user_role WHERE user_id=? FOR UPDATE",(rs,n)->rs.getString(1),actor);if(roles.stream().noneMatch(Set.of("SYSTEM_ADMIN", "DATA_ADMIN")::contains))return false;
List<java.sql.Timestamp> expiry=jdbc.query("SELECT valid_until FROM user_access_policy WHERE user_id=? FOR UPDATE",(rs,n)->rs.getTimestamp(1),actor);if(!expiry.isEmpty()&&expiry.getFirst()!=null&&expiry.getFirst().toInstant().isBefore(Instant.now()))return false; List<java.sql.Timestamp> expiry=jdbc.query("SELECT valid_until FROM user_access_policy WHERE user_id=? FOR UPDATE",(rs,n)->rs.getTimestamp(1),actor);if(!expiry.isEmpty()&&expiry.getFirst()!=null&&expiry.getFirst().toInstant().isBefore(Instant.now()))return false;
List<String> departments=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='DEPARTMENT' FOR UPDATE",(rs,n)->rs.getString(1),actor),groups=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='GROUP' FOR UPDATE",(rs,n)->rs.getString(1),actor); List<String> departments=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='DEPARTMENT' FOR UPDATE",(rs,n)->rs.getString(1),actor),groups=jdbc.query("SELECT scope_value FROM app_user_scope WHERE user_id=? AND scope_type='GROUP' FOR UPDATE",(rs,n)->rs.getString(1),actor);
cn.yunsheng.quality.identity.AppUserPrincipal user=access.resolvePrincipal(new cn.yunsheng.quality.identity.AppUserPrincipal(UUID.fromString(actor),actor,"","",true,false,roles,departments,groups,List.of())); cn.yunsheng.quality.identity.AppUserPrincipal user=access.resolvePrincipal(new cn.yunsheng.quality.identity.AppUserPrincipal(UUID.fromString(actor),actor,"","",true,false,roles,departments,groups,List.of()));
@@ -9,15 +9,15 @@ import org.springframework.web.multipart.MultipartFile;
@RestController @RestController
@RequestMapping("/api/master-data/workbooks") @RequestMapping("/api/master-data/workbooks")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class MasterDataWorkbookController { public class MasterDataWorkbookController {
private final MasterDataWorkbookService service; private final MasterDataWorkbookService service;
public MasterDataWorkbookController(MasterDataWorkbookService service) { this.service = service; } public MasterDataWorkbookController(MasterDataWorkbookService service) { this.service = service; }
@PostMapping("/preview") @PostMapping("/preview")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> preview(@RequestPart("file") MultipartFile file, @AuthenticationPrincipal AppUserPrincipal actor) { return service.preview(file, actor); } public Map<String, Object> preview(@RequestPart("file") MultipartFile file, @AuthenticationPrincipal AppUserPrincipal actor) { return service.preview(file, actor); }
@PostMapping("/prepare") @PostMapping("/prepare")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> prepareWorkbook(@RequestBody MasterDataWorkbookService.ImportRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { return service.prepareWorkbook(request, actor); } public Map<String, Object> prepareWorkbook(@RequestBody MasterDataWorkbookService.ImportRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { return service.prepareWorkbook(request, actor); }
@PostMapping("/import") @PostMapping("/import")
public Map<String, Object> importWorkbook(@RequestBody MasterDataWorkbookService.ImportRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { return service.importWorkbook(request, actor); } public Map<String, Object> importWorkbook(@RequestBody MasterDataWorkbookService.ImportRequest request, @AuthenticationPrincipal AppUserPrincipal actor) { return service.importWorkbook(request, actor); }
@@ -48,7 +48,7 @@ public class MetricsController {
return calculate(year,month,quarter,department,group,product,productSearch,projectGroup,view,includeUnassigned,releaseId,trendGranularity,rowLimit,rowOffset,rowOrder,extraFilters,exclusions,null,actor); return calculate(year,month,quarter,department,group,product,productSearch,projectGroup,view,includeUnassigned,releaseId,trendGranularity,rowLimit,rowOffset,rowOrder,extraFilters,exclusions,null,actor);
} }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public MetricsService.MetricSnapshot calculateHttp(@RequestParam(required = false) Integer year, public MetricsService.MetricSnapshot calculateHttp(@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month, @RequestParam(required = false) Integer month,
@RequestParam(required = false) Integer monthStart, @RequestParam(required = false) Integer monthStart,
@@ -78,7 +78,7 @@ public class MetricsController {
/** 轻量趋势接口:查询参数与正式指标接口一致,但只返回版本、上下文、趋势和覆盖信息。 */ /** 轻量趋势接口:查询参数与正式指标接口一致,但只返回版本、上下文、趋势和覆盖信息。 */
@GetMapping("/trend") @GetMapping("/trend")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public MetricsService.MetricTrendSnapshot trendHttp(@RequestParam(required = false) Integer year, public MetricsService.MetricTrendSnapshot trendHttp(@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month, @RequestParam(required = false) Integer month,
@RequestParam(required = false) Integer monthStart, @RequestParam(required = false) Integer monthStart,
@@ -49,6 +49,7 @@ public class MetricsRollupService {
jdbc.update(rollupInsertSql("fact_"+stage).replace("WHERE f.build_id=?","WHERE f.build_id=? AND ("+inserted+")"),insertArgs.toArray()); jdbc.update(rollupInsertSql("fact_"+stage).replace("WHERE f.build_id=?","WHERE f.build_id=? AND ("+inserted+")"),insertArgs.toArray());
} }
fineDefects.refreshGroups(build, keys); fineDefects.refreshGroups(build, keys);
new SalesOrderMetricRollups(jdbc).refreshCurrentBuild(build);
} }
/** Idempotently refreshes a completed build in the caller's transaction. */ /** Idempotently refreshes a completed build in the caller's transaction. */
@@ -70,6 +71,7 @@ public class MetricsRollupService {
(SELECT COUNT(*) FROM fact_bright WHERE build_id=?), CURRENT_TIMESTAMP(6) (SELECT COUNT(*) FROM fact_bright WHERE build_id=?), CURRENT_TIMESTAMP(6)
""", buildId, buildId, buildId); """, buildId, buildId, buildId);
fineDefects.refreshBuild(buildId); fineDefects.refreshBuild(buildId);
new SalesOrderMetricRollups(jdbc).refreshCurrentBuild(buildId);
} }
static String rollupInsertSql(String table) { static String rollupInsertSql(String table) {
@@ -111,21 +111,22 @@ public class MetricsService {
AppUserPrincipal actor, boolean hasUnrolledBuilds) { AppUserPrincipal actor, boolean hasUnrolledBuilds) {
Map<String, AggregateStats> periods = new TreeMap<>(); Map<String, AggregateStats> periods = new TreeMap<>();
boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty(); boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
if (!hasSourceFilters) { boolean salesRollup = salesOrderRollupReady(releaseId, query, actor);
aggregateTrendStage(periods, "black", releaseId, query, actor, false); if (!hasSourceFilters || salesRollup) {
aggregateTrendStage(periods, "bright", releaseId, query, actor, false); aggregateTrendStage(periods, "black", releaseId, query, actor, false, salesRollup);
aggregateTrendStage(periods, "bright", releaseId, query, actor, false, salesRollup);
} }
if (hasUnrolledBuilds || hasSourceFilters) { if (!salesRollup && (hasUnrolledBuilds || hasSourceFilters)) {
aggregateTrendStage(periods, "black", releaseId, query, actor, true); aggregateTrendStage(periods, "black", releaseId, query, actor, true, false);
aggregateTrendStage(periods, "bright", releaseId, query, actor, true); aggregateTrendStage(periods, "bright", releaseId, query, actor, true, false);
} }
return periods; return periods;
} }
private void aggregateTrendStage(Map<String, AggregateStats> periods, String stage, String releaseId, private void aggregateTrendStage(Map<String, AggregateStats> periods, String stage, String releaseId,
MetricsQuery query, AppUserPrincipal actor, boolean factFallback) { MetricsQuery query, AppUserPrincipal actor, boolean factFallback, boolean salesRollup) {
if (query.stage() != null && !query.stage().equals(stage)) return; if (query.stage() != null && !query.stage().equals(stage)) return;
String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : "metric_rollup"; String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : (salesRollup ? "sales_order_metric_rollup" : "metric_rollup");
StringBuilder where = new StringBuilder(" WHERE rm.release_id=?"); StringBuilder where = new StringBuilder(" WHERE rm.release_id=?");
List<Object> args = new ArrayList<>(); List<Object> args = new ArrayList<>();
args.add(releaseId); args.add(releaseId);
@@ -133,6 +134,7 @@ public class MetricsService {
if (factFallback && !hasSourceFilters) if (factFallback && !hasSourceFilters)
where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)"); where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)");
else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); } else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); }
if (salesRollup) new SalesOrderMetricRollups(jdbc).append(where, args, query.extraFilters());
appendTime(where, args, query); appendTime(where, args, query);
appendDimensions(where, args, query); appendDimensions(where, args, query);
appendExclusions(where, args, query); appendExclusions(where, args, query);
@@ -192,7 +194,7 @@ public class MetricsService {
if (actor == null) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "对账指标查询必须绑定当前有效用户"); if (actor == null) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "对账指标查询必须绑定当前有效用户");
governance.requireUserActivePolicy(actor); governance.requireUserActivePolicy(actor);
governance.requireBoundAction("QUERY", "query.aggregate"); governance.requireBoundAction("QUERY", "query.aggregate");
Set<String> allowedRoles = Set.of("DATA_MAINTAINER", "RULE_MAINTAINER", "DATA_PUBLISHER", "SYSTEM_ADMIN"); Set<String> allowedRoles = Set.of("DATA_ADMIN", "SYSTEM_ADMIN");
if (actor.getRoleCodes().stream().noneMatch(allowedRoles::contains)) if (actor.getRoleCodes().stream().noneMatch(allowedRoles::contains))
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前功能角色不允许执行候选基线对账"); throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前功能角色不允许执行候选基线对账");
validate(query); validate(query);
@@ -311,6 +313,12 @@ public class MetricsService {
return rawRows - (effectiveIncludeUnassigned(query) ? 0 : excludedBlankRows); return rawRows - (effectiveIncludeUnassigned(query) ? 0 : excludedBlankRows);
} }
private boolean salesOrderRollupReady(String release, MetricsQuery query, AppUserPrincipal actor) {
if (query.extraFilters().isEmpty() || !query.columnFilters().isEmpty()
|| !Set.of(cn.yunsheng.quality.filters.SalesOrderTypes.KEY, cn.yunsheng.quality.filters.SalesOrderTypes.EXCLUDE_KEY).containsAll(query.extraFilters().keySet())) return false;
return new SalesOrderMetricRollups(jdbc).ready(release, query.extraFilters(), false, governance.allowedFields(actor));
}
private boolean hasUnrolledBuilds(String releaseId) { private boolean hasUnrolledBuilds(String releaseId) {
Integer count = jdbc.queryForObject(""" Integer count = jdbc.queryForObject("""
SELECT COUNT(*) FROM release_member rm SELECT COUNT(*) FROM release_member rm
@@ -327,20 +335,24 @@ public class MetricsService {
private AggregateSet queryAggregates(String releaseId, MetricsQuery query, AppUserPrincipal actor, private AggregateSet queryAggregates(String releaseId, MetricsQuery query, AppUserPrincipal actor,
boolean hasUnrolledBuilds, Map<String, String> canonicalGroupDepartments) { boolean hasUnrolledBuilds, Map<String, String> canonicalGroupDepartments) {
AggregateSet result = new AggregateSet(); AggregateSet result = new AggregateSet();
if ((query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) aggregateStage(result, "black", query.view(), releaseId, query, actor, false, canonicalGroupDepartments); boolean salesRollup = salesOrderRollupReady(releaseId, query, actor);
if ((query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) aggregateStage(result, "bright", query.view(), releaseId, query, actor, false, canonicalGroupDepartments); boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
if (hasUnrolledBuilds || !(query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) { if (!hasSourceFilters || salesRollup) {
aggregateStage(result, "black", query.view(), releaseId, query, actor, true, canonicalGroupDepartments); aggregateStage(result, "black", query.view(), releaseId, query, actor, false, salesRollup, canonicalGroupDepartments);
aggregateStage(result, "bright", query.view(), releaseId, query, actor, true, canonicalGroupDepartments); aggregateStage(result, "bright", query.view(), releaseId, query, actor, false, salesRollup, canonicalGroupDepartments);
}
if (!salesRollup && (hasUnrolledBuilds || hasSourceFilters)) {
aggregateStage(result, "black", query.view(), releaseId, query, actor, true, false, canonicalGroupDepartments);
aggregateStage(result, "bright", query.view(), releaseId, query, actor, true, false, canonicalGroupDepartments);
} }
return result; return result;
} }
private void aggregateStage(AggregateSet result, String stage, String view, String releaseId, private void aggregateStage(AggregateSet result, String stage, String view, String releaseId,
MetricsQuery query, AppUserPrincipal actor, boolean factFallback, MetricsQuery query, AppUserPrincipal actor, boolean factFallback, boolean salesRollup,
Map<String, String> canonicalGroupDepartments) { Map<String, String> canonicalGroupDepartments) {
if(query.stage()!=null&&!query.stage().equals(stage))return; if(query.stage()!=null&&!query.stage().equals(stage))return;
String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : "metric_rollup"; String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : (salesRollup ? "sales_order_metric_rollup" : "metric_rollup");
String dimensionColumn = view.equals("overall") ? null : switch (view) { String dimensionColumn = view.equals("overall") ? null : switch (view) {
case "department" -> "f.department"; case "department" -> "f.department";
case "group" -> "f.group_name"; case "group" -> "f.group_name";
@@ -358,6 +370,7 @@ public class MetricsService {
args.add(releaseId); args.add(releaseId);
if (factFallback && (query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)"); if (factFallback && (query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)");
else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); } else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); }
if (salesRollup) new SalesOrderMetricRollups(jdbc).append(where, args, query.extraFilters());
appendTime(where, args, query); appendTime(where, args, query);
appendDimensions(where, args, query); appendDimensions(where, args, query);
appendExclusions(where, args, query); appendExclusions(where, args, query);
@@ -521,11 +534,15 @@ public class MetricsService {
Map<String, Object> queryCoverage(String releaseId, MetricsQuery query, AppUserPrincipal actor, boolean hasUnrolledBuilds) { Map<String, Object> queryCoverage(String releaseId, MetricsQuery query, AppUserPrincipal actor, boolean hasUnrolledBuilds) {
TreeMap<String, CoverageMonth> months = new TreeMap<>(); TreeMap<String, CoverageMonth> months = new TreeMap<>();
if ((query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) coverageStage(months, "black", releaseId, query, actor, false); boolean salesRollup = salesOrderRollupReady(releaseId, query, actor);
if ((query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) coverageStage(months, "bright", releaseId, query, actor, false); boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
if (hasUnrolledBuilds || !(query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) { if (!hasSourceFilters || salesRollup) {
coverageStage(months, "black", releaseId, query, actor, true); coverageStage(months, "black", releaseId, query, actor, false, salesRollup);
coverageStage(months, "bright", releaseId, query, actor, true); coverageStage(months, "bright", releaseId, query, actor, false, salesRollup);
}
if (!salesRollup && (hasUnrolledBuilds || hasSourceFilters)) {
coverageStage(months, "black", releaseId, query, actor, true, false);
coverageStage(months, "bright", releaseId, query, actor, true, false);
} }
long rawRows = 0, excludedBlank = 0, unmapped = 0, projectUnconfigured = 0; long rawRows = 0, excludedBlank = 0, unmapped = 0, projectUnconfigured = 0;
List<Map<String, Object>> sourceMonths = new ArrayList<>(); List<Map<String, Object>> sourceMonths = new ArrayList<>();
@@ -562,14 +579,15 @@ public class MetricsService {
} }
private void coverageStage(Map<String, CoverageMonth> months, String stage, String releaseId, private void coverageStage(Map<String, CoverageMonth> months, String stage, String releaseId,
MetricsQuery query, AppUserPrincipal actor, boolean factFallback) { MetricsQuery query, AppUserPrincipal actor, boolean factFallback, boolean salesRollup) {
if(query.stage()!=null&&!query.stage().equals(stage))return; if(query.stage()!=null&&!query.stage().equals(stage))return;
String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : "metric_rollup"; String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : (salesRollup ? "sales_order_metric_rollup" : "metric_rollup");
StringBuilder where = new StringBuilder(" WHERE rm.release_id=?"); StringBuilder where = new StringBuilder(" WHERE rm.release_id=?");
List<Object> args = new ArrayList<>(); List<Object> args = new ArrayList<>();
args.add(releaseId); args.add(releaseId);
if (factFallback && (query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)"); if (factFallback && (query.extraFilters().isEmpty() && query.columnFilters().isEmpty())) where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)");
else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); } else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); }
if (salesRollup) new SalesOrderMetricRollups(jdbc).append(where, args, query.extraFilters());
appendTime(where, args, query); appendTime(where, args, query);
appendDimensions(where, args, query); appendDimensions(where, args, query);
appendExclusions(where, args, query); appendExclusions(where, args, query);
@@ -765,6 +783,7 @@ public class MetricsService {
result.put("trendGranularity", query.trendGranularity()); result.put("trendGranularity", query.trendGranularity());
result.put("exclusions", query.exclusions()); result.put("exclusions", query.exclusions());
result.put("extraFilters", query.extraFilters()); result.put("extraFilters", query.extraFilters());
if(query.extraFilters().containsKey(cn.yunsheng.quality.filters.SalesOrderTypes.KEY)||query.extraFilters().containsKey(cn.yunsheng.quality.filters.SalesOrderTypes.EXCLUDE_KEY))result.put("salesOrderTypeVersionId",cn.yunsheng.quality.filters.SalesOrderTypes.version(jdbc));
if(query.stage()!=null)result.put("stage",query.stage()); if(query.stage()!=null)result.put("stage",query.stage());
if(!query.columnFilters().isEmpty())result.put("columnFilters",query.columnFilters()); if(!query.columnFilters().isEmpty())result.put("columnFilters",query.columnFilters());
return result; return result;
@@ -0,0 +1,18 @@
package cn.yunsheng.quality.metrics;
import cn.yunsheng.quality.filters.SalesOrderTypes;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class SalesOrderMetricBackfill implements ApplicationRunner {
private final JdbcTemplate jdbc;
public SalesOrderMetricBackfill(JdbcTemplate jdbc) { this.jdbc=jdbc; }
@Override @Transactional
public void run(ApplicationArguments args) {
new SalesOrderMetricRollups(jdbc).prepareCurrentRelease(SalesOrderTypes.version(jdbc));
}
}
@@ -0,0 +1,78 @@
package cn.yunsheng.quality.metrics;
import cn.yunsheng.quality.filters.QueryFilterFields;
import cn.yunsheng.quality.filters.SalesOrderTypes;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
/** Immutable aggregates keyed by both mapping version and source build. Missing snapshots use facts. */
public final class SalesOrderMetricRollups {
private final JdbcTemplate jdbc;
public SalesOrderMetricRollups(JdbcTemplate jdbc) { this.jdbc = jdbc; }
public void prepareCurrentRelease(String version) {
if (version == null || version.isBlank()) return;
for (String build : jdbc.queryForList("""
SELECT DISTINCT rm.transform_build_id FROM current_release cr
JOIN release_member rm ON rm.release_id=cr.release_id
WHERE cr.dataset_id='quality'
""", String.class)) prepareBuild(version, build);
}
public void refreshCurrentBuild(String build) {
jdbc.update("DELETE FROM sales_order_metric_rollup_build WHERE build_id=?", build);
jdbc.update("DELETE FROM sales_order_metric_rollup WHERE build_id=?", build);
prepareBuild(SalesOrderTypes.version(jdbc), build);
}
public void prepareBuild(String version, String build) {
if (version == null || version.isBlank()) return;
// The version row serializes preparers, including startup backfill and imports.
jdbc.queryForList("SELECT id FROM sales_order_type_version WHERE id=? FOR UPDATE", String.class, version);
if (Boolean.TRUE.equals(jdbc.queryForObject("SELECT COUNT(*)>0 FROM sales_order_metric_rollup_build WHERE version_id=? AND build_id=?", Boolean.class, version, build))) return;
jdbc.update("DELETE FROM sales_order_metric_rollup WHERE version_id=? AND build_id=?", version, build);
for (String stage : List.of("black", "bright")) {
String table = "fact_" + stage;
String sql = MetricsRollupService.rollupInsertSql(table)
.replace("INSERT INTO metric_rollup (", "INSERT INTO sales_order_metric_rollup (version_id, order_type,")
.replace("SELECT f.build_id, ?", "SELECT ?, COALESCE(sot.order_type,'__EMPTY__'), f.build_id, ?")
.replace("FROM " + table + " f", "FROM " + table + " f LEFT JOIN sales_order_type_entry sot ON sot.version_id=? AND sot.order_no=f.sales_order_no")
.replace("GROUP BY f.build_id,", "GROUP BY sot.order_type, f.build_id,");
jdbc.update(sql, version, stage, version, build);
}
jdbc.update("""
INSERT INTO sales_order_metric_rollup_build(version_id,build_id,source_row_count)
SELECT ?,?,COALESCE(SUM(source_row_count),0) FROM sales_order_metric_rollup WHERE version_id=? AND build_id=?
""", version, build, version, build);
}
public boolean ready(String release, Map<String,List<String>> filters, boolean hasColumnFilters, Set<String> allowed) {
if (hasColumnFilters || filters.isEmpty() || !Set.of(SalesOrderTypes.KEY,SalesOrderTypes.EXCLUDE_KEY).containsAll(filters.keySet())) return false;
if (!SalesOrderTypes.allowed(allowed)) throw QueryFilterFields.bad("没有查看销售订单类型的权限");
validate(filters);
String version = SalesOrderTypes.version(jdbc);
if (version.isBlank()) return false;
Integer missing = jdbc.queryForObject("""
SELECT COUNT(*) FROM release_member rm LEFT JOIN sales_order_metric_rollup_build rb
ON rb.build_id=rm.transform_build_id AND rb.version_id=?
WHERE rm.release_id=? AND rb.build_id IS NULL
""", Integer.class, version, release);
return missing != null && missing == 0;
}
static void validate(Map<String,List<String>> filters) {
for (var values : filters.values()) for (String value : values)
if (!SalesOrderTypes.TYPES.contains(value) && !QueryFilterFields.EMPTY.equals(value)) throw QueryFilterFields.bad("销售订单类型无效");
}
public void append(StringBuilder where, List<Object> args, Map<String,List<String>> filters) {
validate(filters);
where.append(" AND f.version_id=?"); args.add(SalesOrderTypes.version(jdbc));
for (var entry : filters.entrySet()) {
if (entry.getValue().isEmpty()) continue;
where.append(" AND f.order_type ").append(SalesOrderTypes.EXCLUDE_KEY.equals(entry.getKey()) ? "NOT IN (" : "IN (")
.append(String.join(",",Collections.nCopies(entry.getValue().size(),"?"))).append(')');
args.addAll(entry.getValue());
}
}
}
@@ -33,7 +33,7 @@ public class OptionsController {
/** Reference names support maintenance without granting aggregate-query or source-detail access. */ /** Reference names support maintenance without granting aggregate-query or source-detail access. */
@GetMapping("/reference-names") @GetMapping("/reference-names")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER','QUALITY_VIEWER','BUSINESS_ANALYST','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> referenceNames(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> referenceNames(@AuthenticationPrincipal AppUserPrincipal actor) {
Map<String, Object> available = options(null, actor); Map<String, Object> available = options(null, actor);
Map<String, Object> result = new LinkedHashMap<>(); Map<String, Object> result = new LinkedHashMap<>();
@@ -43,7 +43,7 @@ public class OptionsController {
} }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> options(@RequestParam(required = false) String releaseId, public Map<String, Object> options(@RequestParam(required = false) String releaseId,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
String selected = releases.resolvePublishedRelease(releaseId); String selected = releases.resolvePublishedRelease(releaseId);
@@ -3,6 +3,7 @@ package cn.yunsheng.quality.records;
import cn.yunsheng.quality.common.DataScope; import cn.yunsheng.quality.common.DataScope;
import cn.yunsheng.quality.common.ImmutableQueryCache; import cn.yunsheng.quality.common.ImmutableQueryCache;
import cn.yunsheng.quality.filters.QueryFilterFields; import cn.yunsheng.quality.filters.QueryFilterFields;
import cn.yunsheng.quality.filters.SalesOrderTypes;
import cn.yunsheng.quality.common.DepartmentLabels; import cn.yunsheng.quality.common.DepartmentLabels;
import cn.yunsheng.quality.common.SelectionValues; import cn.yunsheng.quality.common.SelectionValues;
import cn.yunsheng.quality.identity.AppUserPrincipal; import cn.yunsheng.quality.identity.AppUserPrincipal;
@@ -92,7 +93,7 @@ public class RecordController {
return recordsFiltered(stage,year,month,quarter,department,group,product,productSearch,projectGroup,includeUnassigned,releaseId,page,pageSize,field,search,sort,direction,columns,extraFilters,null,actor); return recordsFiltered(stage,year,month,quarter,department,group,product,productSearch,projectGroup,includeUnassigned,releaseId,page,pageSize,field,search,sort,direction,columns,extraFilters,null,actor);
} }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> recordsFiltered(@RequestParam String stage, public Map<String, Object> recordsFiltered(@RequestParam String stage,
@RequestParam(required = false) Integer year, @RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month, @RequestParam(required = false) Integer month,
@@ -187,17 +188,20 @@ public class RecordController {
} }
// Field permissions remain current on every request; no authorized row JSON is cached. // Field permissions remain current on every request; no authorized row JSON is cached.
Set<String> allowedFields = governance.allowedFields(actor); Set<String> allowedFields = governance.allowedFields(actor);
List<Object> rowArgs = new ArrayList<>(args); rowArgs.addAll(ids); List<Object> rowArgs = new ArrayList<>();
String orderTypeProjection=SalesOrderTypes.allowed(allowedFields)
? SalesOrderTypes.expression(stage,SalesOrderTypes.version(jdbc),rowArgs) : "NULL";
rowArgs.addAll(args); rowArgs.addAll(ids);
List<Map<String, Object>> fetched = ids.isEmpty() ? List.of() : jdbc.query(""" List<Map<String, Object>> fetched = ids.isEmpty() ? List.of() : jdbc.query("""
SELECT f.id, sr.id AS source_revision_id, sr.source_file, f.sheet_name, f.physical_row_no, f.month_key, SELECT f.id, sr.id AS source_revision_id, sr.source_file, f.sheet_name, f.physical_row_no, f.month_key,
f.department, f.group_name, f.project_group, f.product, f.qualified_weight, f.scrap_weight, f.department, f.group_name, f.project_group, f.product, f.qualified_weight, f.scrap_weight,
f.total_weight, f.raw_values, f.components f.total_weight, f.raw_values, f.components, %s AS sales_order_type
FROM release_member rm FROM release_member rm
JOIN source_revision sr ON sr.id = rm.source_revision_id JOIN source_revision sr ON sr.id = rm.source_revision_id
JOIN %s f ON f.build_id = rm.transform_build_id JOIN %s f ON f.build_id = rm.transform_build_id
%s %s
AND f.id IN (%s) AND f.id IN (%s)
""".formatted(fact, predicate, String.join(",", java.util.Collections.nCopies(ids.size(), "?"))), """.formatted(orderTypeProjection, fact, predicate, String.join(",", java.util.Collections.nCopies(ids.size(), "?"))),
(rs, row) -> mapRow(rs, stage, allowedFields, selectedColumns), rowArgs.toArray()); (rs, row) -> mapRow(rs, stage, allowedFields, selectedColumns), rowArgs.toArray());
Map<String, Map<String, Object>> byId = new LinkedHashMap<>(); Map<String, Map<String, Object>> byId = new LinkedHashMap<>();
fetched.forEach(row -> byId.put(String.valueOf(row.get("id")), row)); fetched.forEach(row -> byId.put(String.valueOf(row.get("id")), row));
@@ -210,7 +214,7 @@ public class RecordController {
return exportFiltered(year,month,quarter,department,group,product,productSearch,projectGroup,includeUnassigned,releaseId,extraFilters,null,null,actor); return exportFiltered(year,month,quarter,department,group,product,productSearch,projectGroup,includeUnassigned,releaseId,extraFilters,null,null,actor);
} }
@GetMapping("/export") @GetMapping("/export")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public ResponseEntity<StreamingResponseBody> exportFiltered(@RequestParam(required = false) Integer year, public ResponseEntity<StreamingResponseBody> exportFiltered(@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month, @RequestParam(required = false) Integer month,
@RequestParam(required = false) Integer quarter, @RequestParam(required = false) Integer quarter,
@@ -280,6 +284,7 @@ public class RecordController {
row.put("projectGroup", rs.getString("project_group")); row.put("projectGroup", rs.getString("project_group"));
row.put("group", rs.getString("group_name")); row.put("group", rs.getString("group_name"));
row.put("product", rs.getString("product")); row.put("product", rs.getString("product"));
if(SalesOrderTypes.allowed(allowedFields))row.put("salesOrderType",rs.getString("sales_order_type"));
Map<String, Object> visibleRaw = filterFields(readJson(rs.getString("raw_values")), allowedFields); Map<String, Object> visibleRaw = filterFields(readJson(rs.getString("raw_values")), allowedFields);
if (selectedColumns != null) { if (selectedColumns != null) {
Map<String, Object> selectedRaw = new LinkedHashMap<>(); Map<String, Object> selectedRaw = new LinkedHashMap<>();
@@ -2,6 +2,7 @@ package cn.yunsheng.quality.records;
import cn.yunsheng.quality.common.DataScope; import cn.yunsheng.quality.common.DataScope;
import cn.yunsheng.quality.filters.QueryFilterFields; import cn.yunsheng.quality.filters.QueryFilterFields;
import cn.yunsheng.quality.filters.SalesOrderTypes;
import cn.yunsheng.quality.common.DepartmentLabels; import cn.yunsheng.quality.common.DepartmentLabels;
import cn.yunsheng.quality.common.SelectionValues; import cn.yunsheng.quality.common.SelectionValues;
import cn.yunsheng.quality.governance.GovernanceAccessService; import cn.yunsheng.quality.governance.GovernanceAccessService;
@@ -119,10 +120,12 @@ public class RecordsWorkbookExportService {
projectGroup, includeUnassigned, "f.raw_values", actor, extraFilters, productSearch,columnFilters); projectGroup, includeUnassigned, "f.raw_values", actor, extraFilters, productSearch,columnFilters);
scan(rawScope, rs -> rawFields.addAll(visibleRaw(readJson(rs.getString(1)), allowedFields).keySet())); scan(rawScope, rs -> rawFields.addAll(visibleRaw(readJson(rs.getString(1)), allowedFields).keySet()));
} }
if (rawFields.size() + HEADER_COUNT > MAX_COLUMNS) boolean showOrderType=SalesOrderTypes.allowed(allowedFields);
if (rawFields.size() + HEADER_COUNT + (showOrderType?1:0) > MAX_COLUMNS)
throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE, "原始字段数量超过 Excel 单表列数上限"); throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE, "原始字段数量超过 Excel 单表列数上限");
List<String> headers = new ArrayList<>(FIXED_HEADERS); List<String> headers = new ArrayList<>(FIXED_HEADERS);
if(showOrderType)headers.add(SalesOrderTypes.LABEL);
headers.addAll(rawFields); headers.addAll(rawFields);
Row header = sheet.createRow(0); Row header = sheet.createRow(0);
for (int index = 0; index < headers.size(); index++) { for (int index = 0; index < headers.size(); index++) {
@@ -140,7 +143,7 @@ public class RecordsWorkbookExportService {
"sr.source_file, f.sheet_name, f.physical_row_no, sr.id AS source_revision_id, f.month_key, " + "sr.source_file, f.sheet_name, f.physical_row_no, sr.id AS source_revision_id, f.month_key, " +
"f.department, f.group_name, f.project_group, f.product, f.raw_values", actor, extraFilters, productSearch,columnFilters); "f.department, f.group_name, f.project_group, f.product, f.raw_values", actor, extraFilters, productSearch,columnFilters);
int[] rowIndex = {1}; int[] rowIndex = {1};
scan(rowScope, rs -> writeRow(sheet, rowIndex, rs, rawFields, allowedFields)); scan(rowScope, rs -> writeRow(sheet, rowIndex, rs, rawFields, allowedFields,showOrderType));
} }
private QueryScope queryScope(String fact, String releaseId, Integer year, Integer month, Integer quarter, private QueryScope queryScope(String fact, String releaseId, Integer year, Integer month, Integer quarter,
@@ -166,6 +169,11 @@ public class RecordsWorkbookExportService {
DataScope.append(predicate, args, actor, "f.department COLLATE utf8mb4_0900_as_cs", DataScope.append(predicate, args, actor, "f.department COLLATE utf8mb4_0900_as_cs",
"f.group_name COLLATE utf8mb4_0900_as_cs"); "f.group_name COLLATE utf8mb4_0900_as_cs");
String columns = select == null ? "f.raw_values" : select; String columns = select == null ? "f.raw_values" : select;
if(columns.startsWith("sr.source_file")&&SalesOrderTypes.allowed(governance.allowedFields(actor))) {
List<Object> projectionArgs=new ArrayList<>();
columns+=", "+SalesOrderTypes.expression(fact.equals("fact_black")?"black":"bright",SalesOrderTypes.version(jdbc),projectionArgs)+" AS sales_order_type";
projectionArgs.addAll(args);args=projectionArgs;
}
String sql = "SELECT " + columns + " FROM release_member rm " + String sql = "SELECT " + columns + " FROM release_member rm " +
"JOIN source_revision sr ON sr.id = rm.source_revision_id " + "JOIN source_revision sr ON sr.id = rm.source_revision_id " +
"JOIN " + fact + " f ON f.build_id = rm.transform_build_id " + predicate + "JOIN " + fact + " f ON f.build_id = rm.transform_build_id " + predicate +
@@ -184,7 +192,7 @@ public class RecordsWorkbookExportService {
} }
private void writeRow(Sheet sheet, int[] rowIndex, ResultSet rs, Set<String> rawFields, private void writeRow(Sheet sheet, int[] rowIndex, ResultSet rs, Set<String> rawFields,
Set<String> allowedFields) throws SQLException { Set<String> allowedFields,boolean showOrderType) throws SQLException {
if (rowIndex[0] >= MAX_ROWS) if (rowIndex[0] >= MAX_ROWS)
throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE, "明细超过 Excel 单工作表行数上限"); throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE, "明细超过 Excel 单工作表行数上限");
Row row = sheet.createRow(rowIndex[0]++); Row row = sheet.createRow(rowIndex[0]++);
@@ -201,6 +209,7 @@ public class RecordsWorkbookExportService {
Map<String, Object> raw = visibleRaw(readJson(rs.getString("raw_values")), allowedFields); Map<String, Object> raw = visibleRaw(readJson(rs.getString("raw_values")), allowedFields);
int index = HEADER_COUNT; int index = HEADER_COUNT;
if(showOrderType)writeText(row,index++,rs.getString("sales_order_type"));
for (String field : rawFields) { for (String field : rawFields) {
if (raw.containsKey(field)) writeText(row, index, valueText(raw.get(field))); if (raw.containsKey(field)) writeText(row, index, valueText(raw.get(field)));
index++; index++;
@@ -19,11 +19,11 @@ public class ReleaseController {
public ReleaseController(ReleaseService service) { this.service = service; } public ReleaseController(ReleaseService service) { this.service = service; }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST','DATA_MAINTAINER','DATA_PUBLISHER','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> list() { return service.list(); } public Map<String, Object> list() { return service.list(); }
@PostMapping("/{id}/publish") @PostMapping("/{id}/publish")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> publish(@PathVariable String id, @RequestBody ReleaseService.ReleaseActionRequest request, public Map<String, Object> publish(@PathVariable String id, @RequestBody ReleaseService.ReleaseActionRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.transition(id, "publish", request, actor); return service.transition(id, "publish", request, actor);
@@ -92,7 +92,7 @@ public class ReleaseService {
public Map<String, Object> transitionInTestWorkflow(String releaseId, String action, ReleaseActionRequest request, public Map<String, Object> transitionInTestWorkflow(String releaseId, String action, ReleaseActionRequest request,
AppUserPrincipal actor, boolean allowEmptyRelease) { AppUserPrincipal actor, boolean allowEmptyRelease) {
if (!testWorkflowMode) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "测试模式便捷工作流未启用"); if (!testWorkflowMode) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "测试模式便捷工作流未启用");
if (!actor.getRoleCodes().contains("SYSTEM_ADMIN") && !actor.getRoleCodes().contains("DATA_PUBLISHER")) if (!actor.getRoleCodes().contains("SYSTEM_ADMIN") && !actor.getRoleCodes().contains("DATA_ADMIN"))
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "自动更新报表需要发布者或系统管理员权限"); throw new ResponseStatusException(HttpStatus.FORBIDDEN, "自动更新报表需要发布者或系统管理员权限");
return transitionInternal(releaseId, action, request, actor, true, allowEmptyRelease); return transitionInternal(releaseId, action, request, actor, true, allowEmptyRelease);
} }
@@ -30,13 +30,13 @@ public class SourceController {
} }
@GetMapping @GetMapping
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> list() { public Map<String, Object> list() {
return Map.of("items", catalog.list()); return Map.of("items", catalog.list());
} }
@PostMapping("/scan") @PostMapping("/scan")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> scan() { public Map<String, Object> scan() {
access.requireBoundAction("RECEIVER","source.receive"); access.requireBoundAction("RECEIVER","source.receive");
List<SourceCatalogService.SourceView> items = catalog.scan(); List<SourceCatalogService.SourceView> items = catalog.scan();
@@ -44,7 +44,7 @@ public class SourceController {
} }
@PostMapping("/upload") @PostMapping("/upload")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> upload(@RequestPart("file") MultipartFile file) { public Map<String, Object> upload(@RequestPart("file") MultipartFile file) {
access.requireBoundAction("RECEIVER","source.receive"); access.requireBoundAction("RECEIVER","source.receive");
if (file.isEmpty()) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "文件为空"); if (file.isEmpty()) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "文件为空");
@@ -14,13 +14,13 @@ import org.springframework.web.server.ResponseStatusException;
public class SourceDeletionController { public class SourceDeletionController {
private final SourceDeletionService deletion; private final SourceDeletionService deletion;
public SourceDeletionController(SourceDeletionService deletion){this.deletion=deletion;} public SourceDeletionController(SourceDeletionService deletion){this.deletion=deletion;}
@GetMapping("/{id}/deletion-preview") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @GetMapping("/{id}/deletion-preview") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> preview(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return deletion.preview(id,actor);} public Map<String,Object> preview(@PathVariable String id,@AuthenticationPrincipal AppUserPrincipal actor){return deletion.preview(id,actor);}
@GetMapping("/deleted") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @GetMapping("/deleted") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> deleted(@AuthenticationPrincipal AppUserPrincipal actor){return deletion.deleted(actor);} public Map<String,Object> deleted(@AuthenticationPrincipal AppUserPrincipal actor){return deletion.deleted(actor);}
@PostMapping("/{id}/delete") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PostMapping("/{id}/delete") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> delete(@PathVariable String id,@RequestBody SourceDeletionService.DeleteRequest request,@AuthenticationPrincipal AppUserPrincipal actor){return deletion.delete(id,request,actor);} public Map<String,Object> delete(@PathVariable String id,@RequestBody SourceDeletionService.DeleteRequest request,@AuthenticationPrincipal AppUserPrincipal actor){return deletion.delete(id,request,actor);}
@PostMapping("/{id}/restore") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PostMapping("/{id}/restore") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String,Object> restore(@PathVariable String id,@RequestBody SourceDeletionService.RestoreRequest request,@AuthenticationPrincipal AppUserPrincipal actor){return deletion.restore(id,request,actor);} public Map<String,Object> restore(@PathVariable String id,@RequestBody SourceDeletionService.RestoreRequest request,@AuthenticationPrincipal AppUserPrincipal actor){return deletion.restore(id,request,actor);}
@ExceptionHandler(ConcurrencyFailureException.class) public org.springframework.http.ProblemDetail concurrent(){return org.springframework.http.ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,"来源正在发生并发操作,请刷新预览后重试");} @ExceptionHandler(ConcurrencyFailureException.class) public org.springframework.http.ProblemDetail concurrent(){return org.springframework.http.ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,"来源正在发生并发操作,请刷新预览后重试");}
} }
@@ -60,7 +60,7 @@ public class SourceDeletionService {
g.audit(actor.getId().toString(),"SOURCE_VISIBILITY_RESTORED","source_candidate",id,Map.of("reason",reason,"onlyVisibility",true,"physicalFilesRetained",true));return view(source(id,false),current,actor); g.audit(actor.getId().toString(),"SOURCE_VISIBILITY_RESTORED","source_candidate",id,Map.of("reason",reason,"onlyVisibility",true,"physicalFilesRetained",true));return view(source(id,false),current,actor);
} }
private Map<String,Object> view(Map<String,Object> row,String current,AppUserPrincipal actor){ private Map<String,Object> view(Map<String,Object> row,String current,AppUserPrincipal actor){
Map<String,Object> usage=currentUsage(row,current),change=change(row);boolean hidden=row.get("deletedAt")!=null,busy=busy(row),manage=has(actor,"SYSTEM_ADMIN","DATA_MAINTAINER"),publisher=has(actor,"SYSTEM_ADMIN","DATA_PUBLISHER"),receiver=receiverAllowed(); Map<String,Object> usage=currentUsage(row,current),change=change(row);boolean hidden=row.get("deletedAt")!=null,busy=busy(row),manage=has(actor,"SYSTEM_ADMIN", "DATA_ADMIN"),publisher=has(actor,"SYSTEM_ADMIN", "DATA_ADMIN"),receiver=receiverAllowed();
boolean buildScope=true;if(publisher&&activeChange(change,usage,current)&&"APPROVED".equals(change.get("status")))try{sourceAccess.requireReleaseSources(current,actor);}catch(ResponseStatusException denied){if(denied.getStatusCode()!=HttpStatus.FORBIDDEN)throw denied;buildScope=false;} boolean buildScope=true;if(publisher&&activeChange(change,usage,current)&&"APPROVED".equals(change.get("status")))try{sourceAccess.requireReleaseSources(current,actor);}catch(ResponseStatusException denied){if(denied.getStatusCode()!=HttpStatus.FORBIDDEN)throw denied;buildScope=false;}
boolean active=activeChange(change,usage,current),review=active&&"REQUESTED".equals(change.get("status"))&&publisher&&!busy,build=active&&"APPROVED".equals(change.get("status"))&&publisher&&buildScope&&!busy; boolean active=activeChange(change,usage,current),review=active&&"REQUESTED".equals(change.get("status"))&&publisher&&!busy,build=active&&"APPROVED".equals(change.get("status"))&&publisher&&buildScope&&!busy;
boolean canDelete=manage&&receiver&&!hidden&&!busy&&!active,canRestore=manage&&receiver&&hidden&&!busy; boolean canDelete=manage&&receiver&&!hidden&&!busy&&!active,canRestore=manage&&receiver&&hidden&&!busy;
@@ -71,7 +71,7 @@ public class SourceDeletionService {
Map<String,Object> out=new LinkedHashMap<>();out.put("source",source);out.put("currentReleaseId",current);out.put("currentUsage",usage);out.put("currentUsed",usage!=null);out.put("documentId",usage==null?null:usage.get("documentId"));out.put("revisionId",usage==null?null:usage.get("revisionId"));out.put("mode",usage==null?"HIDE_ONLY":"WITHDRAW_CURRENT");out.put("history",history);out.put("deleteVersion",row.get("deleteVersion"));out.put("hidden",hidden);out.put("changeRequest",change);out.put("nextAction",next);out.put("canDelete",canDelete);out.put("canRestore",canRestore);out.put("canReview",review);out.put("canBuild",build);out.put("actions",Map.of("canRequest",canDelete,"canReview",review,"canBuild",build));out.put("blockedReason",blocked);out.put("physicalFilesRetained",true);out.put("currentReleaseUnchanged",true);return out; Map<String,Object> out=new LinkedHashMap<>();out.put("source",source);out.put("currentReleaseId",current);out.put("currentUsage",usage);out.put("currentUsed",usage!=null);out.put("documentId",usage==null?null:usage.get("documentId"));out.put("revisionId",usage==null?null:usage.get("revisionId"));out.put("mode",usage==null?"HIDE_ONLY":"WITHDRAW_CURRENT");out.put("history",history);out.put("deleteVersion",row.get("deleteVersion"));out.put("hidden",hidden);out.put("changeRequest",change);out.put("nextAction",next);out.put("canDelete",canDelete);out.put("canRestore",canRestore);out.put("canReview",review);out.put("canBuild",build);out.put("actions",Map.of("canRequest",canDelete,"canReview",review,"canBuild",build));out.put("blockedReason",blocked);out.put("physicalFilesRetained",true);out.put("currentReleaseUnchanged",true);return out;
} }
private AppUserPrincipal principal(AppUserPrincipal actor){access.requireUserActivePolicy(actor);return access.resolvePrincipal(actor);} private AppUserPrincipal principal(AppUserPrincipal actor){access.requireUserActivePolicy(actor);return access.resolvePrincipal(actor);}
private void requireManage(AppUserPrincipal actor){if(!has(actor,"SYSTEM_ADMIN","DATA_MAINTAINER"))throw error(HttpStatus.FORBIDDEN,"只有数据维护者可以申请删除或恢复来源");} private void requireManage(AppUserPrincipal actor){if(!has(actor,"SYSTEM_ADMIN", "DATA_ADMIN"))throw error(HttpStatus.FORBIDDEN,"只有数据维护者可以申请删除或恢复来源");}
private boolean has(AppUserPrincipal actor,String...roles){return actor.getRoleCodes().stream().anyMatch(Set.of(roles)::contains);} private boolean has(AppUserPrincipal actor,String...roles){return actor.getRoleCodes().stream().anyMatch(Set.of(roles)::contains);}
private void authorize(Map<String,Object> source,AppUserPrincipal actor){ private void authorize(Map<String,Object> source,AppUserPrincipal actor){
List<Map<String,Object>> revisions=revisions(source);for(var revision:revisions)sourceAccess.requireSource((String)revision.get("sourceDocumentId"),(String)revision.get("id"),actor); List<Map<String,Object>> revisions=revisions(source);for(var revision:revisions)sourceAccess.requireSource((String)revision.get("sourceDocumentId"),(String)revision.get("id"),actor);
@@ -12,11 +12,11 @@ import org.springframework.web.server.ResponseStatusException;
@RestController @RestController
@RequestMapping("/api/sources") @RequestMapping("/api/sources")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public class SourceUploadController { public class SourceUploadController {
private final SourceUploadService uploads; private final SourceUploadService uploads;
public SourceUploadController(SourceUploadService uploads){this.uploads=uploads;} public SourceUploadController(SourceUploadService uploads){this.uploads=uploads;}
@GetMapping("/upload-options") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") public Map<String,Object> options(@AuthenticationPrincipal AppUserPrincipal actor){return uploads.options(actor);} @GetMapping("/upload-options") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')") public Map<String,Object> options(@AuthenticationPrincipal AppUserPrincipal actor){return uploads.options(actor);}
@PostMapping("/workbook-preview") public Map<String,Object> previewUpload(@RequestPart("file") MultipartFile file,@AuthenticationPrincipal AppUserPrincipal actor){try{return uploads.previewUpload(file,actor);}catch(IOException|IllegalArgumentException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage());}} @PostMapping("/workbook-preview") public Map<String,Object> previewUpload(@RequestPart("file") MultipartFile file,@AuthenticationPrincipal AppUserPrincipal actor){try{return uploads.previewUpload(file,actor);}catch(IOException|IllegalArgumentException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage());}}
@GetMapping("/workbook-preview/{id}") public Map<String,Object> preview(@PathVariable String id,@RequestParam(required=false) String sheetName,@RequestParam(defaultValue="1") int headerRow,@AuthenticationPrincipal AppUserPrincipal actor){try{return uploads.preview(id,sheetName,headerRow,actor);}catch(IOException|IllegalArgumentException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage());}} @GetMapping("/workbook-preview/{id}") public Map<String,Object> preview(@PathVariable String id,@RequestParam(required=false) String sheetName,@RequestParam(defaultValue="1") int headerRow,@AuthenticationPrincipal AppUserPrincipal actor){try{return uploads.preview(id,sheetName,headerRow,actor);}catch(IOException|IllegalArgumentException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage());}}
@PostMapping("/configure") public Map<String,Object> configure(@RequestBody SourceUploadService.ConfigureRequest request,@AuthenticationPrincipal AppUserPrincipal actor){try{return uploads.configure(request,actor);}catch(IOException|IllegalArgumentException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage());}} @PostMapping("/configure") public Map<String,Object> configure(@RequestBody SourceUploadService.ConfigureRequest request,@AuthenticationPrincipal AppUserPrincipal actor){try{return uploads.configure(request,actor);}catch(IOException|IllegalArgumentException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage());}}
@@ -19,61 +19,61 @@ public class DataWorkflowController {
public DataWorkflowController(DataWorkflowService service) { this.service = service; } public DataWorkflowController(DataWorkflowService service) { this.service = service; }
@GetMapping("/status") @GetMapping("/status")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','RULE_MAINTAINER','QUALITY_VIEWER','BUSINESS_ANALYST','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> status(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> status(@AuthenticationPrincipal AppUserPrincipal actor) {
return service.status(actor); return service.status(actor);
} }
@PostMapping("/apply") @PostMapping("/apply")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> apply(@RequestBody ApplyRequest request, public Map<String, Object> apply(@RequestBody ApplyRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.apply(request, actor); return service.apply(request, actor);
} }
@PostMapping("/recalculate") @PostMapping("/recalculate")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> recalculate(@AuthenticationPrincipal AppUserPrincipal actor) { public Map<String, Object> recalculate(@AuthenticationPrincipal AppUserPrincipal actor) {
return service.recalculate(actor); return service.recalculate(actor);
} }
@PostMapping("/import") @PostMapping("/import")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> importSources(@RequestBody ImportRequest request, public Map<String, Object> importSources(@RequestBody ImportRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.importSources(request, actor); return service.importSources(request, actor);
} }
@PostMapping("/publish/{releaseId}") @PostMapping("/publish/{releaseId}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> publish(@PathVariable String releaseId, public Map<String, Object> publish(@PathVariable String releaseId,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.publish(releaseId, actor); return service.publish(releaseId, actor);
} }
@PostMapping("/sources/{id}/delete") @PostMapping("/sources/{id}/delete")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> deleteSource(@PathVariable String id, public Map<String, Object> deleteSource(@PathVariable String id,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.deleteSource(id, actor); return service.deleteSource(id, actor);
} }
@PostMapping("/sources/delete-batch") @PostMapping("/sources/delete-batch")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> deleteSources(@RequestBody DeleteSourcesRequest request, public Map<String, Object> deleteSources(@RequestBody DeleteSourcesRequest request,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.deleteSources(request, actor); return service.deleteSources(request, actor);
} }
@PostMapping("/sources/{id}/restore") @PostMapping("/sources/{id}/restore")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN')")
public Map<String, Object> restoreSource(@PathVariable String id, public Map<String, Object> restoreSource(@PathVariable String id,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.restoreSource(id, actor); return service.restoreSource(id, actor);
} }
@GetMapping("/operations/{id}") @GetMapping("/operations/{id}")
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','RULE_MAINTAINER','QUALITY_VIEWER','BUSINESS_ANALYST','AUDIT_VIEWER')") @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'DATA_ADMIN', 'USER')")
public Map<String, Object> operation(@PathVariable String id, public Map<String, Object> operation(@PathVariable String id,
@AuthenticationPrincipal AppUserPrincipal actor) { @AuthenticationPrincipal AppUserPrincipal actor) {
return service.operation(id, actor); return service.operation(id, actor);
@@ -49,8 +49,8 @@ import tools.jackson.databind.json.JsonMapper;
@Service @Service
public class DataWorkflowService { public class DataWorkflowService {
private static final String DATASET = "quality"; private static final String DATASET = "quality";
private static final Set<String> WRITE_ROLES = Set.of("SYSTEM_ADMIN", "DATA_MAINTAINER", "DATA_PUBLISHER"); private static final Set<String> WRITE_ROLES = Set.of("SYSTEM_ADMIN", "DATA_ADMIN");
private static final Set<String> PUBLISH_ROLES = Set.of("SYSTEM_ADMIN", "DATA_PUBLISHER"); private static final Set<String> PUBLISH_ROLES = Set.of("SYSTEM_ADMIN", "DATA_ADMIN");
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final JsonMapper json; private final JsonMapper json;
private final ImportRunService imports; private final ImportRunService imports;
@@ -135,10 +135,10 @@ public class DataWorkflowService {
} }
static Map<String, Object> capabilities(boolean testMode, AppUserPrincipal actor) { static Map<String, Object> capabilities(boolean testMode, AppUserPrincipal actor) {
boolean publisher = hasRole(actor, "SYSTEM_ADMIN", "DATA_PUBLISHER"); boolean publisher = hasRole(actor, "SYSTEM_ADMIN", "DATA_ADMIN");
boolean manager = hasRole(actor, "SYSTEM_ADMIN", "DATA_MAINTAINER"); boolean manager = hasRole(actor, "SYSTEM_ADMIN", "DATA_ADMIN");
boolean mappingEditor = hasRole(actor, "SYSTEM_ADMIN", "DATA_MAINTAINER", "RULE_MAINTAINER"); boolean mappingEditor = hasRole(actor, "SYSTEM_ADMIN", "DATA_ADMIN");
boolean ruleEditor = hasRole(actor, "SYSTEM_ADMIN", "RULE_MAINTAINER"); boolean ruleEditor = hasRole(actor, "SYSTEM_ADMIN");
boolean canApplyMapping = testMode && publisher && mappingEditor; boolean canApplyMapping = testMode && publisher && mappingEditor;
boolean canApplyRule = testMode && publisher && ruleEditor; boolean canApplyRule = testMode && publisher && ruleEditor;
return Map.of( return Map.of(
@@ -147,8 +147,7 @@ public class DataWorkflowService {
"canApplyMapping", canApplyMapping, "canApplyMapping", canApplyMapping,
"canApplyRule", canApplyRule, "canApplyRule", canApplyRule,
"canRecalculate", testMode && publisher, "canRecalculate", testMode && publisher,
// Upload preview/configure is restricted to SYSTEM_ADMIN or DATA_MAINTAINER; // Data administrators can prepare and publish data; global rule changes stay system-only.
// the workflow import additionally requires DATA_PUBLISHER.
"canImport", testMode && publisher && manager, "canImport", testMode && publisher && manager,
"canPublish", testMode && publisher, "canPublish", testMode && publisher,
"canDeleteSource", testMode && manager, "canDeleteSource", testMode && manager,
@@ -172,6 +171,8 @@ public class DataWorkflowService {
requirePublisher(actor); requirePublisher(actor);
if (request == null || !Set.of("mapping", "rule").contains(request.kind())) if (request == null || !Set.of("mapping", "rule").contains(request.kind()))
throw bad("kind 须为 mapping 或 rule"); throw bad("kind 须为 mapping 或 rule");
if ("rule".equals(request.kind()) && !hasRole(actor, "SYSTEM_ADMIN"))
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "计算规则仅系统管理员可修改");
String name = configurationName(java.time.Instant.now()); String name = configurationName(java.time.Instant.now());
Map<String, Object> definition = asMap(request.definition()); Map<String, Object> definition = asMap(request.definition());
if (definition == null) throw bad("definition 须为 JSON 对象"); if (definition == null) throw bad("definition 须为 JSON 对象");
@@ -252,7 +253,7 @@ public class DataWorkflowService {
public Map<String, Object> operation(String id, AppUserPrincipal actor) { public Map<String, Object> operation(String id, AppUserPrincipal actor) {
access.requireUserActivePolicy(actor); access.requireUserActivePolicy(actor);
WorkflowOperation operation = findOperation(required(id, "操作编号不能为空")); WorkflowOperation operation = findOperation(required(id, "操作编号不能为空"));
if (!Objects.equals(operation.createdBy(), actor.getId().toString()) && !has(actor, "SYSTEM_ADMIN", "DATA_PUBLISHER")) if (!Objects.equals(operation.createdBy(), actor.getId().toString()) && !has(actor, "SYSTEM_ADMIN", "DATA_ADMIN"))
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "操作不存在"); throw new ResponseStatusException(HttpStatus.NOT_FOUND, "操作不存在");
return operationView(operation); return operationView(operation);
} }
@@ -936,6 +937,8 @@ public class DataWorkflowService {
private void authorizeOperation(WorkflowOperation operation, AppUserPrincipal actor) { private void authorizeOperation(WorkflowOperation operation, AppUserPrincipal actor) {
requireWrite(actor); requireWrite(actor);
if ("APPLY_RULE".equals(operation.type()) && !hasRole(actor, "SYSTEM_ADMIN"))
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "计算规则仅系统管理员可修改");
if (Set.of("PUBLISH", "APPLY_MAPPING", "APPLY_RULE", "IMPORT", "RECALCULATE", "RESTORE_SOURCE").contains(operation.type())) requirePublisher(actor); if (Set.of("PUBLISH", "APPLY_MAPPING", "APPLY_RULE", "IMPORT", "RECALCULATE", "RESTORE_SOURCE").contains(operation.type())) requirePublisher(actor);
if (Set.of("DELETE_SOURCE", "DELETE_SOURCES", "RESTORE_SOURCE").contains(operation.type())) requireManager(actor); if (Set.of("DELETE_SOURCE", "DELETE_SOURCES", "RESTORE_SOURCE").contains(operation.type())) requireManager(actor);
if ("DELETE_SOURCES".equals(operation.type())) { if ("DELETE_SOURCES".equals(operation.type())) {
@@ -965,7 +968,7 @@ public class DataWorkflowService {
private void requireManager(AppUserPrincipal actor) { private void requireManager(AppUserPrincipal actor) {
access.requireUserActivePolicy(actor); access.requireUserActivePolicy(actor);
if (!has(actor, "SYSTEM_ADMIN", "DATA_MAINTAINER")) if (!has(actor, "SYSTEM_ADMIN", "DATA_ADMIN"))
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前身份没有来源删除或恢复权限"); throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前身份没有来源删除或恢复权限");
} }
@@ -0,0 +1,2 @@
-- Retain user IDs and their historical references when login access is removed.
ALTER TABLE app_user ADD COLUMN deleted_at TIMESTAMP(6) NULL;
@@ -0,0 +1,37 @@
-- Preserve organization, group and field policies. Never promote auditors/operators to system administrators.
CREATE TEMPORARY TABLE user_role_migration AS
SELECT u.id AS user_id, u.active AS was_active,
JSON_ARRAYAGG(r.role_code) AS old_roles,
CASE
WHEN SUM(r.role_code='SYSTEM_ADMIN')>0 THEN 'SYSTEM_ADMIN'
WHEN SUM(r.role_code IN ('DATA_ADMIN','DATA_MAINTAINER','DATA_PUBLISHER','RULE_MAINTAINER'))>0 THEN 'DATA_ADMIN'
ELSE 'USER'
END AS new_role,
SUM(r.role_code IN ('SYSTEM_ADMIN','DATA_ADMIN','USER','DATA_MAINTAINER','DATA_PUBLISHER',
'RULE_MAINTAINER','QUALITY_VIEWER','BUSINESS_ANALYST','SYSTEM_OPERATOR','AUDIT_VIEWER')) AS recognized_count
FROM app_user u LEFT JOIN app_user_role r ON r.user_id=u.id GROUP BY u.id,u.active;
-- 只兼容角色改名产生的历史权限指纹,数据范围和访问策略仍逐次核验。
CREATE TABLE user_role_migration_anchor (
user_id CHAR(36) NOT NULL PRIMARY KEY,
assigned_role VARCHAR(64) NOT NULL,
previous_roles JSON NOT NULL,
FOREIGN KEY(user_id) REFERENCES app_user(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO user_role_migration_anchor(user_id,assigned_role,previous_roles)
SELECT user_id,new_role,old_roles FROM user_role_migration;
INSERT INTO audit_event(action_code,target_type,target_id,outcome,details)
SELECT 'USER_ROLE_MODEL_MIGRATED','app_user',user_id,'SUCCESS',
JSON_OBJECT('beforeRoles',old_roles,'afterRole',new_role,'dataScopeChanged',FALSE,
'reviewRequired',COALESCE(recognized_count,0)=0,'previousActive',was_active)
FROM user_role_migration;
DELETE FROM app_user_role;
INSERT INTO app_user_role(user_id,role_code) SELECT user_id,new_role FROM user_role_migration;
UPDATE app_user u JOIN user_role_migration m ON m.user_id=u.id
SET u.active=IF(COALESCE(m.recognized_count,0)=0,FALSE,u.active),u.row_version=u.row_version+1;
DROP TEMPORARY TABLE user_role_migration;
ALTER TABLE app_user_role ADD UNIQUE KEY uq_user_single_role(user_id),
ADD CONSTRAINT ck_user_role_code CHECK(role_code IN ('USER','DATA_ADMIN','SYSTEM_ADMIN'));
@@ -0,0 +1,25 @@
CREATE TABLE sales_order_type_version (
id CHAR(36) PRIMARY KEY,
source_file VARCHAR(255) NOT NULL,
source_sha256 CHAR(64) NOT NULL,
import_mode VARCHAR(16) NOT NULL,
row_count INT NOT NULL,
created_by CHAR(36) NOT NULL,
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_as_cs;
CREATE TABLE sales_order_type_entry (
version_id CHAR(36) NOT NULL,
order_no VARCHAR(190) NOT NULL,
order_type VARCHAR(80) NOT NULL,
PRIMARY KEY(version_id, order_no),
KEY ix_sales_order_type(version_id, order_type, order_no),
FOREIGN KEY(version_id) REFERENCES sales_order_type_version(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_as_cs;
CREATE TABLE sales_order_type_current (
dataset_id VARCHAR(64) PRIMARY KEY,
version_id CHAR(36),
FOREIGN KEY(version_id) REFERENCES sales_order_type_version(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_as_cs;
INSERT INTO sales_order_type_current(dataset_id) VALUES ('quality');
@@ -0,0 +1,11 @@
ALTER TABLE fact_black
ADD COLUMN sales_order_no VARCHAR(190) COLLATE utf8mb4_0900_as_cs
GENERATED ALWAYS AS (CASE WHEN JSON_TYPE(JSON_EXTRACT(raw_values,'$."销售订单号"'))='NULL' THEN NULL
ELSE NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(raw_values,'$."销售订单号"'))),'') END) VIRTUAL,
ADD INDEX ix_black_sales_order (sales_order_no,build_id);
ALTER TABLE fact_bright
ADD COLUMN sales_order_no VARCHAR(190) COLLATE utf8mb4_0900_as_cs
GENERATED ALWAYS AS (CASE WHEN JSON_TYPE(JSON_EXTRACT(raw_values,'$."销售订单"'))='NULL' THEN NULL
ELSE NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(raw_values,'$."销售订单"'))),'') END) VIRTUAL,
ADD INDEX ix_bright_sales_order (sales_order_no,build_id);
@@ -0,0 +1,12 @@
CREATE TABLE sales_order_metric_rollup LIKE metric_rollup;
ALTER TABLE sales_order_metric_rollup
ADD COLUMN version_id CHAR(36) NOT NULL,
ADD COLUMN order_type VARCHAR(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_as_cs NOT NULL,
ADD KEY ix_sales_metric_version_build (version_id, build_id, stage, order_type, month_key);
CREATE TABLE sales_order_metric_rollup_build (
version_id CHAR(36) NOT NULL,
build_id CHAR(36) NOT NULL,
source_row_count BIGINT NOT NULL,
PRIMARY KEY (version_id, build_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
@@ -0,0 +1,49 @@
package cn.yunsheng.quality.filters;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.util.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.server.ResponseStatusException;
class SalesOrderTypeServiceTest {
static MockMultipartFile workbook(String[]... rows) throws Exception {
try(var book=new XSSFWorkbook();var out=new ByteArrayOutputStream()) {
var sheet=book.createSheet("销售订单");var header=sheet.createRow(0);
header.createCell(0).setCellValue("销售订单编号");header.createCell(1).setCellValue("销售订单类型");
for(int i=0;i<rows.length;i++){var row=sheet.createRow(i+1);row.createCell(0).setCellValue(rows[i][0]);row.createCell(1).setCellValue(rows[i][1]);}
book.write(out);return new MockMultipartFile("file","订单.xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",out.toByteArray());
}
}
@Test void exactTextKeysKeepLeadingZerosAndIdenticalDuplicatesAreDeduplicated() throws Exception {
var input=SalesOrderTypeService.read(workbook(new String[]{" 000123 ","标准销售订单"},new String[]{"000123","标准销售订单"},new String[]{"123","样品销售订单"}));
assertEquals(Map.of("000123","标准销售订单","123","样品销售订单"),input.rows());
assertEquals(64,input.sha256().length());
}
@Test void conflictsEmptyTypesAndUnapprovedCategoriesAreRejected() throws Exception {
var conflict=workbook(new String[]{"A","标准销售订单"},new String[]{"A","样品销售订单"});
assertThrows(ResponseStatusException.class,()->SalesOrderTypeService.read(conflict));
for(String type:List.of("","0","新品","代工销售订单")) {
var file=workbook(new String[]{"A",type});
assertThrows(ResponseStatusException.class,()->SalesOrderTypeService.read(file));
}
}
@Test void mergePreservesUnlistedOrdersAndReplaceReportsRemovals() {
var old=Map.of("A","标准销售订单","B","样品销售订单");
var incoming=Map.of("A","备料销售订单","C","内部研发销售订单");
var merge=SalesOrderTypeService.summary(old,incoming,"MERGE");
assertEquals(1,merge.get("added"));assertEquals(1,merge.get("updated"));assertEquals(3,merge.get("total"));assertEquals(0L,merge.get("removed"));
var replace=SalesOrderTypeService.summary(old,incoming,"REPLACE");
assertEquals(2,replace.get("total"));assertEquals(1L,replace.get("removed"));
}
@Test void derivedFilterBindsEverythingAndRejectsUnknownTypes() {
var args=new ArrayList<Object>();var where=new StringBuilder();
SalesOrderTypes.append(where,args,"bright",List.of("标准销售订单",QueryFilterFields.EMPTY),"snapshot-a");
assertFalse(where.toString().contains("标准销售订单"));
assertEquals(List.of("snapshot-a","标准销售订单","snapshot-a"),args);
assertTrue(where.toString().contains("NOT EXISTS"));
assertThrows(ResponseStatusException.class,()->SalesOrderTypes.append(new StringBuilder(),new ArrayList<>(),"black",List.of("unknown"),"v"));
}
}
@@ -0,0 +1,100 @@
package cn.yunsheng.quality.filters;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import cn.yunsheng.quality.governance.GovernanceAccessService;
import cn.yunsheng.quality.identity.AppUserPrincipal;
import java.util.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ResponseStatusException;
@EnabledIfEnvironmentVariable(named="QUALITY_SOURCE_COLUMN_TEST_CREATE_DATABASE",matches="true")
class SalesOrderTypesMySqlTest {
JdbcTemplate jdbc,admin;String database;
GovernanceAccessService governance=mock(GovernanceAccessService.class);
AppUserPrincipal actor=mock(AppUserPrincipal.class);
@BeforeEach void setup() throws Exception {
String url=System.getenv("QUALITY_SOURCE_COLUMN_TEST_MYSQL_SERVER_URL");
assertTrue(url.startsWith("jdbc:mysql://127.0.0.1:")&&url.contains("/?"));
String user=System.getenv("QUALITY_SOURCE_COLUMN_TEST_MYSQL_USER"),password=System.getenv("QUALITY_SOURCE_COLUMN_TEST_MYSQL_PASSWORD");
admin=new JdbcTemplate(new DriverManagerDataSource(url,user,password));database="quality_sales_type_test_"+UUID.randomUUID().toString().replace("-","");
admin.execute("CREATE DATABASE "+database+" CHARACTER SET utf8mb4");
var source=new DriverManagerDataSource(url.replaceFirst("/\\?","/"+database+"?"),user,password);jdbc=new JdbcTemplate(source);
try(var connection=source.getConnection()){ScriptUtils.executeSqlScript(connection,new ClassPathResource("db/migration/V39__sales_order_types.sql"));}
jdbc.execute("CREATE TABLE query_filter_field(field_key VARCHAR(64),label VARCHAR(80),black_column VARCHAR(160),bright_column VARCHAR(160),enabled BOOLEAN,allow_empty BOOLEAN,sort_order INT)");
jdbc.execute("CREATE TABLE current_release(dataset_id VARCHAR(40),release_id VARCHAR(40))");
jdbc.execute("CREATE TABLE release_member(release_id VARCHAR(40),transform_build_id VARCHAR(40),source_revision_id VARCHAR(40))");
for(String stage:List.of("black","bright"))jdbc.execute("CREATE TABLE fact_"+stage+"(id INT,build_id VARCHAR(40),source_revision_id VARCHAR(40),department VARCHAR(190),group_name VARCHAR(190),raw_values JSON)");
try(var connection=source.getConnection()){ScriptUtils.executeSqlScript(connection,new ClassPathResource("db/migration/V40__sales_order_fact_indexes.sql"));}
jdbc.execute("CREATE TABLE audit_event(actor_user_id VARCHAR(40),action_code VARCHAR(64),target_type VARCHAR(64),target_id VARCHAR(40),outcome VARCHAR(40),details JSON)");
when(actor.getId()).thenReturn(UUID.randomUUID());when(actor.getDepartments()).thenReturn(List.of("*"));when(actor.getGroups()).thenReturn(List.of());
when(governance.allowedFields(actor)).thenReturn(Set.of("*"));
jdbc.update("INSERT INTO release_member VALUES('release','black-build','black-rev'),('release','bright-build','bright-rev')");
jdbc.update("INSERT INTO fact_black(id,build_id,source_revision_id,department,group_name,raw_values) VALUES(1,'black-build','black-rev','部门A','组A',JSON_OBJECT('销售订单号','0001')),(2,'black-build','black-rev','部门A','组A',JSON_OBJECT('销售订单号','absent')),(3,'black-build','black-rev','部门A','组A',JSON_OBJECT('销售订单号',NULL))");
jdbc.update("INSERT INTO fact_bright(id,build_id,source_revision_id,department,group_name,raw_values) VALUES(4,'bright-build','bright-rev','部门A','组A',JSON_OBJECT('销售订单','0001'))");
}
@AfterEach void cleanup(){RequestContextHolder.resetRequestAttributes();if(database!=null)admin.execute("DROP DATABASE "+database);}
Map<String,Object> load(String key,String type,String mode) throws Exception {
var service=new SalesOrderTypeService(jdbc);var file=SalesOrderTypeServiceTest.workbook(new String[]{key,type});var preview=service.preview(file,mode);
return service.importFile(file,mode,(String)preview.get("expectedVersion"),(String)preview.get("sha256"),actor);
}
List<Integer> ids(String stage,List<String> values) {
var args=new ArrayList<Object>();var where=new StringBuilder(" WHERE 1=1");
new QueryFilterFields(jdbc,governance).append(where,args,stage,Map.of(SalesOrderTypes.KEY,values),actor);
return jdbc.queryForList("SELECT f.id FROM fact_"+stage+" f"+where+" ORDER BY f.id",Integer.class,args.toArray());
}
@Test void matchesBothStageHeadersTreatsMissingAndNullAsUnmatchedAndPreservesCardinality() throws Exception {
load("0001","标准销售订单","MERGE");
assertEquals(List.of(1),ids("black",List.of("标准销售订单")));
assertEquals(List.of(4),ids("bright",List.of("标准销售订单")));
assertEquals(List.of(2,3),ids("black",List.of(QueryFilterFields.EMPTY)));
assertEquals(List.of(1,2,3),ids("black",List.of("标准销售订单",QueryFilterFields.EMPTY)));
assertEquals(List.of("标准销售订单"),new QueryFilterFields(jdbc,governance).options(SalesOrderTypes.KEY,null,"release",actor).get("values"));
when(governance.allowedFields(actor)).thenReturn(Set.of("销售订单号"));
assertThrows(ResponseStatusException.class,()->ids("black",List.of("标准销售订单")));
assertThrows(ResponseStatusException.class,()->new QueryFilterFields(jdbc,governance).options(SalesOrderTypes.KEY,null,"release",actor));
}
@Test void pinsSnapshotWithinRequestAndSubsequentRequestsUseNewVersion() throws Exception {
var first=load("0001","标准销售订单","MERGE");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
assertEquals(first.get("versionId"),SalesOrderTypes.version(jdbc));
load("0001","样品销售订单","MERGE");
assertEquals(List.of(1),ids("black",List.of("标准销售订单")));
RequestContextHolder.resetRequestAttributes();
assertEquals(List.of(1),ids("black",List.of("样品销售订单")));
assertEquals(List.of(),ids("black",List.of("标准销售订单")));
}
@Test void optionsNeverExposeTypesFromOtherDepartments() throws Exception {
load("0001","标准销售订单","MERGE");load("hidden","内部研发销售订单","MERGE");
jdbc.update("INSERT INTO fact_black(id,build_id,source_revision_id,department,group_name,raw_values) VALUES(5,'black-build','black-rev','部门B','组B',JSON_OBJECT('销售订单号','hidden'))");
when(actor.getDepartments()).thenReturn(List.of("部门A"));
assertEquals(List.of("标准销售订单"),new QueryFilterFields(jdbc,governance).options(SalesOrderTypes.KEY,null,"release",actor).get("values"));
}
@Test void exclusionKeepsUnmatchedRowsUnlessTheyAreExplicitlyExcluded() throws Exception {
load("0001","标准销售订单","MERGE");
for(var selection:List.of(List.of("标准销售订单"),List.of(QueryFilterFields.EMPTY),List.of("标准销售订单",QueryFilterFields.EMPTY))) {
var args=new ArrayList<Object>();var where=new StringBuilder(" WHERE 1=1");
new QueryFilterFields(jdbc,governance).append(where,args,"black",Map.of(SalesOrderTypes.EXCLUDE_KEY,selection),actor);
var found=jdbc.queryForList("SELECT f.id FROM fact_black f"+where+" ORDER BY f.id",Integer.class,args.toArray());
assertEquals(selection.size()==2?List.of():selection.contains(QueryFilterFields.EMPTY)?List.of(1):List.of(2,3),found);
}
}
@Test void mergeReplaceStalePreviewAndRestoreRetainHistoricalSnapshots() throws Exception {
var first=load("0001","标准销售订单","MERGE");load("0002","样品销售订单","MERGE");
assertEquals(2,jdbc.queryForObject("SELECT COUNT(*) FROM sales_order_type_entry WHERE version_id=(SELECT version_id FROM sales_order_type_current)",Integer.class));
var service=new SalesOrderTypeService(jdbc);var file=SalesOrderTypeServiceTest.workbook(new String[]{"0003","备料销售订单"});var stale=service.preview(file,"MERGE");
var replaced=load("0004","内部研发销售订单","REPLACE");
assertThrows(ResponseStatusException.class,()->service.importFile(file,"MERGE",(String)stale.get("expectedVersion"),(String)stale.get("sha256"),actor));
assertEquals(1,jdbc.queryForObject("SELECT COUNT(*) FROM sales_order_type_entry WHERE version_id=(SELECT version_id FROM sales_order_type_current)",Integer.class));
service.activate((String)first.get("versionId"),(String)replaced.get("versionId"),actor);
assertEquals(List.of(1),ids("black",List.of("标准销售订单")));
}
}
@@ -0,0 +1,96 @@
package cn.yunsheng.quality.metrics;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import cn.yunsheng.quality.filters.SalesOrderTypes;
import cn.yunsheng.quality.governance.GovernanceAccessService;
import cn.yunsheng.quality.identity.AppUserPrincipal;
import java.util.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.web.server.ResponseStatusException;
import tools.jackson.databind.json.JsonMapper;
@EnabledIfEnvironmentVariable(named="QUALITY_SOURCE_COLUMN_TEST_CREATE_DATABASE",matches="true")
class SalesOrderMetricRollupsMySqlTest {
JdbcTemplate jdbc,admin; String database;
final String build=UUID.randomUUID().toString(),version=UUID.randomUUID().toString(),release=UUID.randomUUID().toString();
final GovernanceAccessService governance=mock(GovernanceAccessService.class);
final AppUserPrincipal actor=mock(AppUserPrincipal.class);
final JsonMapper json=JsonMapper.builder().build();
MetricsService metrics; SalesOrderMetricRollups rollups;
@BeforeEach void setup() throws Exception {
String url=System.getenv("QUALITY_SOURCE_COLUMN_TEST_MYSQL_SERVER_URL");
assertTrue(url.startsWith("jdbc:mysql://127.0.0.1:")&&url.contains("/?"));
String user=System.getenv("QUALITY_SOURCE_COLUMN_TEST_MYSQL_USER"),password=System.getenv("QUALITY_SOURCE_COLUMN_TEST_MYSQL_PASSWORD");
admin=new JdbcTemplate(new DriverManagerDataSource(url,user,password));
database="quality_sales_metric_test_"+UUID.randomUUID().toString().replace("-","");
admin.execute("CREATE DATABASE "+database+" CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci");
var source=new DriverManagerDataSource(url.replaceFirst("/\\?","/"+database+"?"),user,password);jdbc=new JdbcTemplate(source);
jdbc.execute("CREATE TABLE transform_build(id CHAR(36) PRIMARY KEY)");
jdbc.execute("CREATE TABLE data_release(id CHAR(36),name VARCHAR(100),status VARCHAR(32),rule_version VARCHAR(100))");
jdbc.execute("CREATE TABLE release_member(release_id CHAR(36),transform_build_id CHAR(36))");
jdbc.execute("CREATE TABLE current_release(dataset_id VARCHAR(40),release_id CHAR(36))");
jdbc.execute("CREATE TABLE query_filter_field(field_key VARCHAR(64),label VARCHAR(80),black_column VARCHAR(160),bright_column VARCHAR(160),enabled BOOLEAN,allow_empty BOOLEAN,sort_order INT)");
for(String stage:List.of("black","bright")) jdbc.execute("CREATE TABLE fact_"+stage+"(id BIGINT AUTO_INCREMENT PRIMARY KEY,build_id CHAR(36),month_key CHAR(7),department VARCHAR(190),group_name VARCHAR(190),project_group VARCHAR(190),product VARCHAR(190),qualified_weight DECIMAL(38,8),scrap_weight DECIMAL(38,8),total_weight DECIMAL(38,8),raw_values JSON,components JSON)");
for(String migration:List.of("V16__metric_rollups.sql","V39__sales_order_types.sql","V40__sales_order_fact_indexes.sql","V41__sales_order_metric_rollups.sql")) try(var connection=source.getConnection()) { ScriptUtils.executeSqlScript(connection,new ClassPathResource("db/migration/"+migration)); }
jdbc.update("INSERT INTO transform_build VALUES(?)",build);
jdbc.update("INSERT INTO data_release VALUES(?,'test','PUBLISHED',NULL)",release);
jdbc.update("INSERT INTO release_member VALUES(?,?)",release,build);
jdbc.update("INSERT INTO current_release VALUES('quality',?)",release);
jdbc.update("INSERT INTO sales_order_type_version(id,source_file,source_sha256,import_mode,row_count,created_by) VALUES(?,'fixture',?,'REPLACE',7,'test')",version,"0".repeat(64));
jdbc.update("UPDATE sales_order_type_current SET version_id=?",version);
for(int i=0;i<7;i++) jdbc.update("INSERT INTO sales_order_type_entry VALUES(?,?,?)",version,"order-"+i,SalesOrderTypes.TYPES.get(i));
for(String stage:List.of("black","bright")) for(int i=0;i<11;i++) {
String order=i<7?"order-"+i:i==7?"absent":i==8?null:"order-0";
jdbc.update("INSERT INTO fact_"+stage+"(build_id,month_key,department,group_name,project_group,product,qualified_weight,scrap_weight,total_weight,raw_values,components) VALUES(?,?,?,?,?,?,?,?,?,JSON_OBJECT(?,?),CAST(? AS JSON))",build,i%2==0?"2026-01":"2026-02",i==10?"Other":"A",i==9?null:i%3==0?"g":"G",i%2==0?"Project":"project","P"+i%2,i%3==0?null:i-3,i%4==0?null:0,i%5==0?null:10,SalesOrderTypes.column(stage),order,json.writeValueAsString(i%3==0?Map.of("categoryMappingStatus","unmapped"):Map.of("black_responsibility_scrap",i-4,"projectGroupStatus","unmapped")));
}
when(governance.allowedFields(actor)).thenReturn(Set.of("*"));when(actor.getDepartments()).thenReturn(List.of("*"));when(actor.getGroups()).thenReturn(List.of());
metrics=new MetricsService(jdbc,governance);rollups=new SalesOrderMetricRollups(jdbc);
}
@AfterEach void cleanup(){if(database!=null)admin.execute("DROP DATABASE "+database);}
Object normalized(Object value){return json.readValue(json.writeValueAsString(value),Object.class);}
MetricsService.MetricsQuery query(String view, boolean blanks, Map<String,List<String>> filters){return new MetricsService.MetricsQuery(2026,null,null,null,null,null,null,view,blanks,release,"month",Map.of(),filters);}
@Test void aggregatesAndCoverageMatchFactsForNullsZerosNegativeWeightsAllTypesAndComplements() {
for(var filterKey:List.of(SalesOrderTypes.KEY,SalesOrderTypes.EXCLUDE_KEY)) for(var type:SalesOrderTypes.TYPES) {
for(String view:List.of("overall","group","product")) {
var query=query(view,false,Map.of(filterKey,List.of(type)));
jdbc.update("DELETE FROM sales_order_metric_rollup_build");
var raw=metrics.calculate(query,actor);var rawTrend=metrics.calculateTrend(query,actor);
rollups.prepareBuild(version,build);
assertTrue(rollups.ready(release,query.extraFilters(),false,Set.of("*")));
assertEquals(normalized(raw),normalized(metrics.calculate(query,actor)),filterKey+type+view);
assertEquals(normalized(rawTrend),normalized(metrics.calculateTrend(query,actor)));
}
}
for(var filter:List.of(Map.of(SalesOrderTypes.EXCLUDE_KEY,List.of("__EMPTY__")),Map.of(SalesOrderTypes.KEY,List.of("__EMPTY__","标准销售订单")),Map.of(SalesOrderTypes.KEY,List.of("标准销售订单","样品销售订单"),SalesOrderTypes.EXCLUDE_KEY,List.of("样品销售订单")))) {
var query=query("department",true,filter).withMonthRange(1,1).withStage("black").withProductSearch("P");
jdbc.update("DELETE FROM sales_order_metric_rollup_build");var raw=metrics.calculate(query,actor);
rollups.prepareBuild(version,build);assertEquals(normalized(raw),normalized(metrics.calculate(query,actor)));
}
}
@Test void permissionsIncompleteSnapshotsVersionChangesAndFutureBuildRefreshStaySafe() {
var query=query("overall",true,Map.of(SalesOrderTypes.EXCLUDE_KEY,List.of("样品销售订单")));
assertFalse(rollups.ready(release,query.extraFilters(),false,Set.of("*")));
rollups.prepareCurrentRelease(version);
when(actor.getDepartments()).thenReturn(List.of("A"));var rawFiltered=metrics.calculate(query,actor);
jdbc.update("DELETE FROM sales_order_metric_rollup_build");assertEquals(normalized(rawFiltered),normalized(metrics.calculate(query,actor)));
rollups.prepareBuild(version,build);
when(governance.allowedFields(actor)).thenReturn(Set.of("销售订单号"));assertThrows(ResponseStatusException.class,()->metrics.calculate(query,actor));
when(governance.allowedFields(actor)).thenReturn(Set.of("*"));
String next=UUID.randomUUID().toString();jdbc.update("INSERT INTO sales_order_type_version SELECT ?,'next',source_sha256,import_mode,row_count,created_by,created_at FROM sales_order_type_version WHERE id=?",next,version);
jdbc.update("INSERT INTO sales_order_type_entry SELECT ?,order_no,'样品销售订单' FROM sales_order_type_entry WHERE version_id=?",next,version);
jdbc.update("UPDATE sales_order_type_current SET version_id=?",next);
assertFalse(rollups.ready(release,query.extraFilters(),false,Set.of("*")));
var raw=metrics.calculate(query,actor);rollups.prepareCurrentRelease(next);assertEquals(normalized(raw),normalized(metrics.calculate(query,actor)));
jdbc.update("UPDATE fact_black SET total_weight=111 WHERE sales_order_no='order-0'");
rollups.refreshCurrentBuild(build);assertFalse(rollups.ready(release,query.extraFilters(),true,Set.of("*")));
assertEquals(0,jdbc.queryForObject("SELECT COUNT(*) FROM sales_order_metric_rollup_build WHERE version_id=?",Integer.class,version));
}
}
+7 -6
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { import {
Alert, App, Button, Empty, Form, Input, InputNumber, Modal, Popconfirm, Alert, App, Button, Empty, Form, Input, InputNumber, Modal, Popconfirm,
@@ -200,6 +201,7 @@ export function M01Insights({ query, onUnauthorized }: { query: QueryParams; onU
} }
export function M02SavedViews({ query, view, onUnauthorized, onApply }: { query: QueryParams; view: ViewKind; onUnauthorized: (error: unknown) => boolean; onApply: (context: Partial<QueryParams>) => void }) { export function M02SavedViews({ query, view, onUnauthorized, onApply }: { query: QueryParams; view: ViewKind; onUnauthorized: (error: unknown) => boolean; onApply: (context: Partial<QueryParams>) => void }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const { message } = App.useApp();
const [items, setItems] = useState<Row[]>([]); const [items, setItems] = useState<Row[]>([]);
const [sharedItems, setSharedItems] = useState<Row[]>([]); const [sharedItems, setSharedItems] = useState<Row[]>([]);
@@ -293,7 +295,7 @@ export function M02SavedViews({ query, view, onUnauthorized, onApply }: { query:
{ title: '视图名称', dataIndex: 'name', key: 'name', width: 210 }, { title: '视图名称', dataIndex: 'name', key: 'name', width: 210 },
{ title: '分组维度', key: 'groupBy', width: 140, render: (_, row) => text(record(row.definition).groupBy, '总体') }, { title: '分组维度', key: 'groupBy', width: 140, render: (_, row) => text(record(row.definition).groupBy, '总体') },
{ title: '数据范围', key: 'dataScope', width: 180, render: () => '打开时使用当前数据' }, { title: '数据范围', key: 'dataScope', width: 180, render: () => '打开时使用当前数据' },
{ title: '操作', key: 'actions', width: 250, render: (_, row) => <span className="completion-actions"><Button type="link" loading={busyId === String(row.id)} onClick={() => void open(row)}>打开</Button><Button type="link" onClick={() => void manageShares(row)}>共享</Button><Popconfirm title="删除此个人比较视图?" onConfirm={() => void remove(row)}><Button type="link" danger loading={busyId === String(row.id)}>删除</Button></Popconfirm></span> }, { title: '操作', key: 'actions', width: 250, render: (_, row) => <span className="completion-actions"><Button type="link" loading={busyId === String(row.id)} onClick={() => void open(row)}>打开</Button><Button type="link" onClick={() => void manageShares(row)}>共享</Button><Button type="link" danger loading={busyId === String(row.id)} onClick={()=>confirmDelete({title:`删除个人视图“${text(row.name || row.title,"当前视图")}”?`,description:"确认后立即删除此个人比较视图,原始业务数据保留。",onConfirm:()=>remove(row)})}>删除</Button></span> },
]; ];
const sharedColumns: ColumnsType<Row> = [ const sharedColumns: ColumnsType<Row> = [
{ title: '视图名称', dataIndex: 'name', key: 'name', width: 230 }, { title: '视图名称', dataIndex: 'name', key: 'name', width: 230 },
@@ -336,6 +338,7 @@ export function M02SavedViews({ query, view, onUnauthorized, onApply }: { query:
} }
export function ScrapAnalyticsPanel({ query, onUnauthorized }: { query: QueryParams; onUnauthorized: (error: unknown) => boolean }) { export function ScrapAnalyticsPanel({ query, onUnauthorized }: { query: QueryParams; onUnauthorized: (error: unknown) => boolean }) {
const confirmDelete = useDeleteConfirmation();
const [stage, setStage] = useState<Stage>('black'); const [stage, setStage] = useState<Stage>('black');
const [dimension, setDimension] = useState('category'); const [dimension, setDimension] = useState('category');
const [limit, setLimit] = useState(10); const [limit, setLimit] = useState(10);
@@ -493,7 +496,7 @@ export function ScrapAnalyticsPanel({ query, onUnauthorized }: { query: QueryPar
{ title: '阶段 / 对象', dataIndex: 'subject', key: 'subject', width: 260, render: value => typeof value === 'string' ? value : (() => { const subject = record(value); return `${subject.stage === 'black' ? '黑片' : subject.stage === 'bright' ? '亮片' : '—'} · ${text(subject.label)}`; })() }, { title: '阶段 / 对象', dataIndex: 'subject', key: 'subject', width: 260, render: value => typeof value === 'string' ? value : (() => { const subject = record(value); return `${subject.stage === 'black' ? '黑片' : subject.stage === 'bright' ? '亮片' : '—'} · ${text(subject.label)}`; })() },
{ title: '重算综合率', key: 'snapshot', align: 'right', width: 130, render: (_, row) => { const summary = record(record(row.metricSnapshot || row.snapshot).summary); return pct(summary.compositeRate); } }, { title: '重算综合率', key: 'snapshot', align: 'right', width: 130, render: (_, row) => { const summary = record(record(row.metricSnapshot || row.snapshot).summary); return pct(summary.compositeRate); } },
{ title: '证据状态', key: 'evidence', width: 125, render: (_, row) => row.evidenceAvailable === false ? <Tag color="gold">当前不可见</Tag> : <Tag color="green">已重新授权</Tag> }, { title: '证据状态', key: 'evidence', width: 125, render: (_, row) => row.evidenceAvailable === false ? <Tag color="gold">当前不可见</Tag> : <Tag color="green">已重新授权</Tag> },
{ title: '操作', key: 'remove', width: 90, render: (_, row) => <Button type="link" danger loading={checklistBusy} onClick={() => void removeChecklistItem(row)}>移除</Button> }, { title: '操作', key: 'remove', width: 90, render: (_, row) => <Button type="link" danger loading={checklistBusy} onClick={() => confirmDelete({title:`移除核查证据“${text(row.title || row.label || row.name || row.objectKey,"当前证据")}”?`,description:"仅从核查清单中移除这项证据,原始业务数据保留;确认后立即生效。",confirmText:"确认移除",onConfirm:()=>removeChecklistItem(row)})}>移除</Button> },
]; ];
const impactRows = list(impactResult?.groups); const impactRows = list(impactResult?.groups);
const impactColumns: ColumnsType<Row> = [ const impactColumns: ColumnsType<Row> = [
@@ -541,6 +544,7 @@ export function ScrapAnalyticsPanel({ query, onUnauthorized }: { query: QueryPar
} }
export function TargetVersionAdmin({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { export function TargetVersionAdmin({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const { message } = App.useApp();
const [items, setItems] = useState<Row[]>([]); const [items, setItems] = useState<Row[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -583,10 +587,7 @@ export function TargetVersionAdmin({ onUnauthorized }: { onUnauthorized: (error:
? { ...item, values: { ...record(item.values), [String(year)]: value } } ? { ...item, values: { ...record(item.values), [String(year)]: value } }
: item)); : item));
}; };
const removeRow = (row: Row) => { const removeRow = (row: Row) => confirmDelete({title:`删除“${dimensionKeys.map(key=>String(row[key]||'')).filter(Boolean).join(' / ') || '总体'}”的目标行?`,description:`将移除当前编辑内容中“${metricOptions.find(item=>item.value===row.metric)?.label || '所选指标'}”及其各年度目标,保存目标后生效。`,onConfirm:()=>{const key=String(row.editorKey || '');setTargetRows(current=>current.filter(item=>String(item.editorKey || '')!==key));}});
const key = String(row.editorKey || '');
setTargetRows(current => current.filter(item => String(item.editorKey || '') !== key));
};
const isScopeRow = (row: Row) => row.editorScope === true; const isScopeRow = (row: Row) => row.editorScope === true;
const overallRows = targetRows.filter(row => !isScopeRow(row)); const overallRows = targetRows.filter(row => !isScopeRow(row));
const scopeRows = targetRows.filter(isScopeRow); const scopeRows = targetRows.filter(isScopeRow);
+18 -3
View File
@@ -8,6 +8,7 @@ import { pageUsesResources } from './resourceInvalidation';
import type { AuthUser, QueryParams } from './types'; import type { AuthUser, QueryParams } from './types';
import type { PageKey } from './QualityWorkspace'; import type { PageKey } from './QualityWorkspace';
import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache'; import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache';
import { canAccessWorkspacePage } from './userRoles';
const loadQueryPage = () => import('./QueryPage'); const loadQueryPage = () => import('./QueryPage');
const loadStageProductPage = () => import('./StageProductPage'); const loadStageProductPage = () => import('./StageProductPage');
@@ -129,10 +130,24 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => { const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
if (next === 'imports') next = 'sources'; if (next === 'imports') next = 'sources';
if (next === requested.current && !query && !resultRef) return; if (next === requested.current && !query && !resultRef) return;
let navigationQuery:Partial<QueryParams>|undefined=query;
if(!query&&!resultRef&&QUERY_PAGES.includes(current.current)&&QUERY_PAGES.includes(next)) {
const source=readQueryLocation(entries.current.get(current.current)?.search||location.search);
const destination=readQueryLocation(entries.current.get(next)?.search||'');
const sourceKey=Object.hasOwn(source.extraFilters||{},'salesOrderTypeNotIn')?'salesOrderTypeNotIn':'salesOrderType';
const destinationKey=Object.hasOwn(destination.extraFilters||{},'salesOrderTypeNotIn')?'salesOrderTypeNotIn':'salesOrderType';
const selected=source.extraFilters?.[sourceKey];
if(sourceKey!==destinationKey||JSON.stringify(selected||[])!==JSON.stringify(destination.extraFilters?.[destinationKey]||[])) {
const extraFilters={...destination.extraFilters};
delete extraFilters.salesOrderType;delete extraFilters.salesOrderTypeNotIn;
if(selected?.length||sourceKey==='salesOrderTypeNotIn')extraFilters[sourceKey]=[...(selected||[])];
navigationQuery={...destination,extraFilters};
}
}
const params = new URLSearchParams({ page: next }); const params = new URLSearchParams({ page: next });
if (query) params.set('context', encode({ query, ...(resultRef ? { resultRef } : {}) })); if (navigationQuery) params.set('context', encode({ query:navigationQuery, ...(resultRef ? { resultRef } : {}) }));
const cached = entries.current.get(next); const cached = entries.current.get(next);
void enter(next, query || resultRef || !cached ? `?${params}` : cached.search, Boolean(query || resultRef) || !retained(next)); void enter(next, navigationQuery || resultRef || !cached ? `?${params}` : cached.search, Boolean(navigationQuery || resultRef) || !retained(next));
}; };
useImperativeHandle(ref, () => ({ navigate, syncLocation: () => { useImperativeHandle(ref, () => ({ navigate, syncLocation: () => {
const next = new URLSearchParams(location.search).get('page') as PageKey || 'overall'; const next = new URLSearchParams(location.search).get('page') as PageKey || 'overall';
@@ -171,7 +186,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}> return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey: refreshKey + (entry.revision || 0), currentReleaseId: revisions.current?.currentReleaseId, authRevision: revisions.current?.authRevision, dataRevision: revisions.current?.dataRevision, onLocationChange: search => { entry.search = search; } }}> <PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey: refreshKey + (entry.revision || 0), currentReleaseId: revisions.current?.currentReleaseId, authRevision: revisions.current?.authRevision, dataRevision: revisions.current?.dataRevision, onLocationChange: search => { entry.search = search; } }}>
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}> <Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
{name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />} {!canAccessWorkspacePage(user, name) ? <Alert type="info" showIcon message="当前角色没有此页面的访问权限" action={<Button onClick={() => navigate('overall')}>返回质量查询</Button>} /> : name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
</Suspense> </Suspense>
</PageCacheContext.Provider> </PageCacheContext.Provider>
</div>; </div>;
+3 -1
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { useContext, useRef, useState, type ReactNode } from 'react'; import { useContext, useRef, useState, type ReactNode } from 'react';
import { Alert, App, AutoComplete, Button, Input, Modal, Select, Space, Tag } from 'antd'; import { Alert, App, AutoComplete, Button, Input, Modal, Select, Space, Tag } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'; import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
@@ -13,6 +14,7 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
onUnauthorized: (error: unknown)=>boolean; onUnauthorized: (error: unknown)=>boolean;
}) { }) {
const context=useContext(MappingEditorContext); const context=useContext(MappingEditorContext);
const confirmDelete = useDeleteConfirmation();
const {message}=App.useApp(); const {message}=App.useApp();
const [selection,setSelection]=useState<ClassificationSelection|null>(null); const [selection,setSelection]=useState<ClassificationSelection|null>(null);
const [conditions,setConditions]=useState<ClassificationCondition[]>([]); const [conditions,setConditions]=useState<ClassificationCondition[]>([]);
@@ -66,7 +68,7 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
options={[{value:'EQUALS',label:'等于'},{value:'IS_BLANK',label:'为空'}]} onChange={operator=>{setConditions(conditions.map(c=>c===condition?{...c,operator,value:operator==='IS_BLANK'?'':c.value}:c));resetPreview();setBusy(false);}}/> options={[{value:'EQUALS',label:'等于'},{value:'IS_BLANK',label:'为空'}]} onChange={operator=>{setConditions(conditions.map(c=>c===condition?{...c,operator,value:operator==='IS_BLANK'?'':c.value}:c));resetPreview();setBusy(false);}}/>
<Input aria-label={`${labels[condition.field]}匹配值`} disabled={condition.operator==='IS_BLANK'} value={condition.value} maxLength={200} <Input aria-label={`${labels[condition.field]}匹配值`} disabled={condition.operator==='IS_BLANK'} value={condition.value} maxLength={200}
placeholder={condition.operator==='IS_BLANK'?'空值':'填写匹配值'} onChange={e=>{setConditions(conditions.map(c=>c===condition?{...c,value:e.target.value}:c));resetPreview();setBusy(false);}}/> placeholder={condition.operator==='IS_BLANK'?'空值':'填写匹配值'} onChange={e=>{setConditions(conditions.map(c=>c===condition?{...c,value:e.target.value}:c));resetPreview();setBusy(false);}}/>
<Button aria-label={`移除${labels[condition.field]}条件`} icon={<DeleteOutlined/>} disabled={conditions.length===1} onClick={()=>{setConditions(conditions.filter(c=>c!==condition));resetPreview();setBusy(false);}}>移除</Button> <Button aria-label={`移除${labels[condition.field]}条件`} icon={<DeleteOutlined/>} disabled={conditions.length===1} onClick={()=>confirmDelete({title:`移除“${labels[condition.field]}”条件?`,description:"将从当前分类规则中移除此条件,保存分类规则后生效。",confirmText:"确认移除",onConfirm:()=>{setConditions(conditions.filter(c=>c!==condition));resetPreview();setBusy(false);}})}>移除</Button>
</div>)}</div></>} </div>)}</div></>}
<label className="classification-target">{project?'项目组':'业务分组'}<AutoComplete aria-label={project?'目标项目组':'目标业务分组'} value={target} maxLength={160} options={(project?context?.projectGroups??[]:context?.groups??[]).map(value=>({value}))} <label className="classification-target">{project?'项目组':'业务分组'}<AutoComplete aria-label={project?'目标项目组':'目标业务分组'} value={target} maxLength={160} options={(project?context?.projectGroups??[]:context?.groups??[]).map(value=>({value}))}
filterOption={(input,option)=>String(option?.value).includes(input)} placeholder={project?'选择项目组':'选择业务分组'} onChange={value=>{setTarget(value);resetPreview();setBusy(false);}}/></label> filterOption={(input,option)=>String(option?.value).includes(input)} placeholder={project?'选择项目组':'选择业务分组'} onChange={value=>{setTarget(value);resetPreview();setBusy(false);}}/></label>
+24 -13
View File
@@ -6,9 +6,11 @@ import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { api } from './api'; import { api } from './api';
import type { FilterField } from './types'; import type { FilterField } from './types';
import { readableSelectPopup } from './readableSelectPopup'; import { readableSelectPopup } from './readableSelectPopup';
import { salesOrderTypeSelection,updateSalesOrderTypeSelection } from './salesOrderTypes';
import './sales-order-types.css';
function FieldSelect({ field, value, onChange, onUnauthorized }: { field: FilterField; value: string[]; onChange: (values: string[]) => void; onUnauthorized: (error: unknown) => boolean }) { export function FilterFieldSelect({ field, value, onChange, onUnauthorized,releaseId,stage,exclude,onExclude }: { field: FilterField; value: string[]; onChange: (values: string[]) => void; onUnauthorized: (error: unknown) => boolean;releaseId?:string;stage?:'black'|'bright';exclude?:boolean;onExclude?:(exclude:boolean)=>void }) {
const { active } = usePageCache(); const { active,refreshKey } = usePageCache();
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [choices, setChoices] = useState<string[]>([]); const [choices, setChoices] = useState<string[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -22,26 +24,35 @@ function FieldSelect({ field, value, onChange, onUnauthorized }: { field: Filter
const current = ++generation.current, controller = new AbortController(); const current = ++generation.current, controller = new AbortController();
setLoading(true); setChoices([]); setError(''); setLoading(true); setChoices([]); setError('');
const timer = window.setTimeout(() => { const timer = window.setTimeout(() => {
api.filterFieldOptions(field.key, search, controller.signal).then(result => { api.filterFieldOptions(field.key, search, controller.signal,releaseId,stage).then(result => {
if (generation.current !== current) return; if (generation.current !== current) return;
setChoices(result.values); setHasMore(result.hasMore); setChoices(result.values); setHasMore(result.hasMore);
}).catch(e => { if (generation.current === current && !onUnauthorized(e)) setError(e.message || '选项加载失败'); }) }).catch(e => { if (generation.current === current && !onUnauthorized(e)) setError(e.message || '选项加载失败'); })
.finally(() => { if (generation.current === current) setLoading(false); }); .finally(() => { if (generation.current === current) setLoading(false); });
}, search ? 250 : 0); }, search ? 250 : 0);
return () => { window.clearTimeout(timer); controller.abort(); generation.current++; }; return () => { window.clearTimeout(timer); controller.abort(); generation.current++; };
}, [active, field.key, search, revision, onUnauthorized]); }, [active, field.key, search, revision, onUnauthorized,releaseId,stage,refreshKey]);
return <label className="query-field query-extra-field"><span>{field.label}</span><Select mode="multiple" allowClear showSearch aria-label={field.label} const selection=<Select className={onExclude?'sales-order-type-values':undefined} mode="multiple" allowClear showSearch aria-label={field.label}
{...readableSelectPopup} maxTagCount="responsive" value={value} loading={showLoading} filterOption={false} searchValue={search} onSearch={setSearch} {...readableSelectPopup} maxTagCount="responsive" value={value} loading={showLoading} filterOption={false} searchValue={search} onSearch={setSearch}
onChange={values => { onChange(values); setSearch(''); }} placeholder="全部" onChange={values => { onChange(values); setSearch(''); }} placeholder={onExclude&&exclude?'选择要排除的类型':'全部'}
options={[...new Set([...choices, ...value.filter(v => v !== '__EMPTY__')])].map(v => ({ label: v, value: v })).concat(field.allowEmpty ? [{ label: '空值', value: '__EMPTY__' }] : [])} options={[...new Set([...choices, ...value.filter(v => v !== '__EMPTY__')])].map(v => ({ label: v, value: v })).concat(field.allowEmpty ? [{ label: field.key==='salesOrderType'?'未匹配':'空值', value: '__EMPTY__' }] : [])}
notFoundContent={showLoading ? <Spin size="small" /> : error ? <Button size="small" onClick={() => setRevision(n => n + 1)}>加载失败,重试</Button> : '暂无匹配项'} notFoundContent={showLoading ? <Spin size="small" /> : error ? <Button size="small" onClick={() => setRevision(n => n + 1)}>加载失败,重试</Button> : '暂无匹配项'}
popupRender={menu => <>{menu}{hasMore && <div className="query-options-hint">选项较多,请输入关键字查找</div>}{error && <div role="alert" className="query-options-hint">{error}</div>}</>} popupRender={menu => <>{menu}{hasMore && <div className="query-options-hint">选项较多,请输入关键字查找</div>}{error && <div role="alert" className="query-options-hint">{error}</div>}</>}
/></label>; />;
// A label can associate with only one input. With two Selects it forwards box clicks to the mode input.
const FieldContainer='div';
return <FieldContainer className={`query-field query-extra-field${onExclude?' sales-order-type-field':''}`} role="group" aria-label={field.label}><span>{field.label}</span>{onExclude?<div className="sales-order-type-controls"><Select className="sales-order-type-mode" aria-label="销售订单类型筛选方式" value={exclude?'exclude':'include'} options={[{label:'包含',value:'include'},{label:'排除',value:'exclude'}]} onChange={value=>onExclude(value==='exclude')}/>{selection}</div>:selection}</FieldContainer>;
} }
export function ExtraQueryFilters({ projectGroup, projectGroups, onProjectGroup, value, onChange, onUnauthorized }: { export function SalesOrderTypeSelect({filters,onChange,...props}:{field:FilterField;filters:Record<string,string[]>;onChange:(filters:Record<string,string[]>)=>void;onUnauthorized:(error:unknown)=>boolean;releaseId?:string;stage?:'black'|'bright'}) {
const {exclude,values}=salesOrderTypeSelection(filters);
return <FilterFieldSelect {...props} value={values} exclude={exclude} onExclude={next=>onChange(updateSalesOrderTypeSelection(filters,next,values))} onChange={next=>onChange(updateSalesOrderTypeSelection(filters,exclude,next))}/>;
}
export function ExtraQueryFilters({ projectGroup, projectGroups, onProjectGroup, value, onChange, onUnauthorized,releaseId }: {
projectGroup: string[]; projectGroups?: string[]; onProjectGroup: (values: string[]) => void; projectGroup: string[]; projectGroups?: string[]; onProjectGroup: (values: string[]) => void;
value: Record<string, string[]>; onChange: (value: Record<string, string[]>) => void; onUnauthorized: (error: unknown) => boolean; value: Record<string, string[]>; onChange: (value: Record<string, string[]>) => void; onUnauthorized: (error: unknown) => boolean;
releaseId?:string;
}) { }) {
const { active } = usePageCache(); const { active } = usePageCache();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -56,16 +67,16 @@ export function ExtraQueryFilters({ projectGroup, projectGroups, onProjectGroup,
return () => { alive = false; controller.abort(); }; return () => { alive = false; controller.abort(); };
}, [active, open, revision, onUnauthorized]); }, [active, open, revision, onUnauthorized]);
const count = (projectGroup.length ? 1 : 0) + Object.values(value).filter(v => v.length).length; const count = (projectGroup.length ? 1 : 0) + Object.values(value).filter(v => v.length).length;
const summary = [projectGroup.length ? `项目组:${projectGroup.map(v => v === '__UNASSIGNED__' ? '未分类' : v).join('、')}` : '', ...Object.entries(value).filter(([, values]) => values.length).map(([key, values]) => `${fields.find(f => f.key === key)?.label || key}:${values.map(v => v === '__EMPTY__' ? '空值' : v).join('、')}`)].filter(Boolean).join(';'); const summary = [projectGroup.length ? `项目组:${projectGroup.map(v => v === '__UNASSIGNED__' ? '未分类' : v).join('、')}` : '', ...Object.entries(value).filter(([, values]) => values.length).map(([key, values]) => `${key==='salesOrderTypeNotIn'?'销售订单类型(排除)':fields.find(f => f.key === key)?.label || key}:${values.map(v => v === '__EMPTY__' ? key.startsWith('salesOrderType')?'未匹配':'空值' : v).join('、')}`)].filter(Boolean).join(';');
return <> return <>
<div className="query-more-toggle" title={summary || undefined}><Button type="text" size="small" icon={open ? <UpOutlined /> : <DownOutlined />} aria-expanded={open} onClick={() => setOpen(v => !v)}>更多筛选{count ? `(已选 ${count} 项)` : ''}</Button> <div className="query-more-toggle" title={summary || undefined}><Button type="text" size="small" icon={open ? <UpOutlined /> : <DownOutlined />} aria-expanded={open} onClick={() => setOpen(v => !v)}>更多筛选{count ? `(已选 ${count} 项)` : ''}</Button>
{count > 0 && <Button type="link" size="small" onClick={() => { onProjectGroup([]); onChange({}); }}>清除</Button>} {count > 0 && <Button type="link" size="small" onClick={() => { onProjectGroup([]); onChange({}); }}>清除</Button>}
</div> </div>
{open && error && <Alert className="query-extra-error" type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重试</Button>} />} {open && error && <Alert className="query-extra-error" type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重试</Button>} />}
{open && <div className="query-extra-fields"> {open && <div className="query-extra-fields">
{projectGroups && <label className="query-field query-extra-field"><span>项目组</span><Select aria-label="项目组" mode="multiple" maxTagCount="responsive" allowClear showSearch optionFilterProp="label" {...readableSelectPopup} value={projectGroup} onChange={onProjectGroup} placeholder="全部" options={[...projectGroups.map(v => ({ label: v, value: v })), { label: '未分类', value: '__UNASSIGNED__' }]} /></label>} {projectGroups && <div role="group" className="query-field query-extra-field"><span>项目组</span><Select aria-label="项目组" mode="multiple" maxTagCount="responsive" allowClear showSearch optionFilterProp="label" {...readableSelectPopup} value={projectGroup} onChange={onProjectGroup} placeholder="全部" options={[...projectGroups.map(v => ({ label: v, value: v })), { label: '未分类', value: '__UNASSIGNED__' }]} /></div>}
{fields.map(field => <FieldSelect key={field.key} field={field} value={value[field.key] || []} onUnauthorized={onUnauthorized} onChange={values => { const next = { ...value }; if (values.length) next[field.key] = values; else delete next[field.key]; onChange(next); }} />)} {fields.map(field => field.key==='salesOrderType'?<SalesOrderTypeSelect key={field.key} field={field} releaseId={releaseId} filters={value} onUnauthorized={onUnauthorized} onChange={onChange}/>:<FilterFieldSelect key={field.key} field={field} releaseId={releaseId} value={value[field.key] || []} onUnauthorized={onUnauthorized} onChange={values => { const next = { ...value }; if (values.length) next[field.key] = values; else delete next[field.key]; onChange(next); }} />)}
{Object.keys(value).filter(key => !fields.some(f => f.key === key)).map(key => <Alert key={key} type="warning" message={`筛选字段 ${key} 当前不可用,请清除后继续查询。`} />)} {Object.keys(value).filter(key => !fields.some(f => f.key === (key==='salesOrderTypeNotIn'?'salesOrderType':key))).map(key => <Alert key={key} type="warning" message={`筛选字段 ${key} 当前不可用,请清除后继续查询。`} />)}
</div>} </div>}
</>; </>;
} }
+5 -1
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions'; import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Alert, App, Button, Checkbox, Input, Select, Space } from 'antd'; import { Alert, App, Button, Checkbox, Input, Select, Space } from 'antd';
@@ -5,8 +6,10 @@ import { QualityTable as Table } from './QualityTable';
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import { api } from './api'; import { api } from './api';
import type { FilterField } from './types'; import type { FilterField } from './types';
import { SalesOrderTypeSettings } from './SalesOrderTypeSettings';
export function FilterFieldSettings({ canManage, onUnauthorized }: { canManage: boolean; onUnauthorized: (error: unknown) => boolean }) { export function FilterFieldSettings({ canManage, onUnauthorized }: { canManage: boolean; onUnauthorized: (error: unknown) => boolean }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const { message } = App.useApp();
const [fields, setFields] = useState<FilterField[]>([]); const [fields, setFields] = useState<FilterField[]>([]);
const [columns, setColumns] = useState<{ black: string[]; bright: string[] }>({ black: [], bright: [] }); const [columns, setColumns] = useState<{ black: string[]; bright: string[] }>({ black: [], bright: [] });
@@ -38,7 +41,8 @@ export function FilterFieldSettings({ canManage, onUnauthorized }: { canManage:
...(['black', 'bright'] as const).map(stage => ({ title: stage === 'black' ? '黑片来源列' : '亮片来源列', key: stage, width: 240, render: (_: unknown, f: FilterField) => <Select size="small" aria-label={`${stage === 'black' ? '黑片' : '亮片'}来源列 ${f.key}`} showSearch optionFilterProp="label" style={{ width: '100%' }} value={f[stage === 'black' ? 'blackColumn' : 'brightColumn'] || undefined} disabled={!canManage || saving} placeholder="选择来源列" options={[...new Set([...columns[stage], f[stage === 'black' ? 'blackColumn' : 'brightColumn']].filter(Boolean))].map(v => ({ label: v, value: v }))} onChange={v => update(f.key, { [stage === 'black' ? 'blackColumn' : 'brightColumn']: v })} /> })), ...(['black', 'bright'] as const).map(stage => ({ title: stage === 'black' ? '黑片来源列' : '亮片来源列', key: stage, width: 240, render: (_: unknown, f: FilterField) => <Select size="small" aria-label={`${stage === 'black' ? '黑片' : '亮片'}来源列 ${f.key}`} showSearch optionFilterProp="label" style={{ width: '100%' }} value={f[stage === 'black' ? 'blackColumn' : 'brightColumn'] || undefined} disabled={!canManage || saving} placeholder="选择来源列" options={[...new Set([...columns[stage], f[stage === 'black' ? 'blackColumn' : 'brightColumn']].filter(Boolean))].map(v => ({ label: v, value: v }))} onChange={v => update(f.key, { [stage === 'black' ? 'blackColumn' : 'brightColumn']: v })} /> })),
{ title: '允许空值', key: 'empty', width: 100, render: (_, f) => <Checkbox aria-label={`允许空值 ${f.label || f.key}`} checked={f.allowEmpty} disabled={!canManage || saving} onChange={e => update(f.key, { allowEmpty: e.target.checked })} /> }, { title: '允许空值', key: 'empty', width: 100, render: (_, f) => <Checkbox aria-label={`允许空值 ${f.label || f.key}`} checked={f.allowEmpty} disabled={!canManage || saving} onChange={e => update(f.key, { allowEmpty: e.target.checked })} /> },
{ title: '启用', key: 'enabled', width: 80, render: (_, f) => <Checkbox aria-label={`启用 ${f.label || f.key}`} checked={f.enabled} disabled={!canManage || saving} onChange={e => update(f.key, { enabled: e.target.checked })} /> }, { title: '启用', key: 'enabled', width: 80, render: (_, f) => <Checkbox aria-label={`启用 ${f.label || f.key}`} checked={f.enabled} disabled={!canManage || saving} onChange={e => update(f.key, { enabled: e.target.checked })} /> },
...(canManage ? [{ title: '操作', key: 'actions', width: 80, render: (_: unknown, f: FilterField) => <Button size="small" type="link" danger disabled={saving} onClick={() => { setFields(items => items.filter(item => item.key !== f.key)); setDirty(true); }}>移除</Button> }] : []), ...(canManage ? [{ title: '操作', key: 'actions', width: 80, render: (_: unknown, f: FilterField) => <Button size="small" type="link" danger disabled={saving} onClick={() => confirmDelete({title:`移除查询字段“${f.label || f.key}”?`,description:"只移除查询字段配置,不删除原始数据。保存设置后生效。",confirmText:"确认移除",onConfirm:()=>{setFields(items => items.filter(item => item.key !== f.key));setDirty(true);}})}>移除</Button> }] : []),
]} /> ]} />
{canManage&&<SalesOrderTypeSettings onUnauthorized={onUnauthorized}/>}
</section>; </section>;
} }
+9 -9
View File
@@ -71,8 +71,8 @@ function analysisDeepLink(sessionId: string, turnId: string): string {
function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp(); const { message } = App.useApp();
const { active } = usePageCache(); const { active } = usePageCache();
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const canManage = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const canRun = user.roles.some(role => ['QUALITY_VIEWER', 'BUSINESS_ANALYST'].includes(role)); const canRun = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN', 'USER'].includes(role));
const [strategies, setStrategies] = useState<Row[]>([]); const [strategies, setStrategies] = useState<Row[]>([]);
const [releaseId, setReleaseId] = useState(''); const [releaseId, setReleaseId] = useState('');
const [runs, setRuns] = useState<Row[]>([]); const [runs, setRuns] = useState<Row[]>([]);
@@ -215,7 +215,7 @@ function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onU
{error && <ErrorPanel title={"巡检数据读取或执行失败"} error={strategiesLoaded ? `${error};以下为上次成功读取的策略。` : error} onRetry={() => { void load(); if (releaseId) void loadRuns(releaseId); }} />} {error && <ErrorPanel title={"巡检数据读取或执行失败"} error={strategiesLoaded ? `${error};以下为上次成功读取的策略。` : error} onRetry={() => { void load(); if (releaseId) void loadRuns(releaseId); }} />}
{loading && !strategiesLoaded ? <div className="completion-loading"><Spin />读取巡检策略…</div> : strategiesLoaded && canManage ? strategies.length ? <Table size="small" bordered columns={strategyColumns} dataSource={strategies} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : <Empty description="服务端当前没有已登记的巡检策略" /> : null} {loading && !strategiesLoaded ? <div className="completion-loading"><Spin />读取巡检策略…</div> : strategiesLoaded && canManage ? strategies.length ? <Table size="small" bordered columns={strategyColumns} dataSource={strategies} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : <Empty description="服务端当前没有已登记的巡检策略" /> : null}
<div className="completion-filter-row">{canRun && <Button type="primary" loading={running} disabled={!releaseId} onClick={() => void run()}>对当前数据执行巡检</Button>}</div> <div className="completion-filter-row">{canRun && <Button type="primary" loading={running} disabled={!releaseId} onClick={() => void run()}>对当前数据执行巡检</Button>}</div>
{!canRun && <Alert showIcon type="info" message="当前账号不能执行巡检" description="运行和结果查看需要服务端授权的质量查看或业务分析角色及明细查询权限。" />} {!canRun && <Alert showIcon type="info" message="当前账号不能执行巡检" description="执行和查看巡检需要用户权限及明细访问授权。" />}
{canRun && (runsLoaded ? runs.length ? <Table size="small" bordered columns={runColumns} dataSource={runs} rowKey={row => String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1120 }} /> : <Empty description={releaseId ? '当前数据尚无巡检运行记录' : '当前还没有可巡检的数据'} /> : runRead.busy ? <div className="completion-loading"><Spin />读取巡检运行记录…</div> : null)} {canRun && (runsLoaded ? runs.length ? <Table size="small" bordered columns={runColumns} dataSource={runs} rowKey={row => String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1120 }} /> : <Empty description={releaseId ? '当前数据尚无巡检运行记录' : '当前还没有可巡检的数据'} /> : runRead.busy ? <div className="completion-loading"><Spin />读取巡检运行记录…</div> : null)}
<Modal className="management-modal" open={editing !== null} title={editing?.id ? `编辑巡检策略 · ${text(editing.name)}` : '新建巡检策略'} okText="保存策略" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()} width={Math.min(820, window.innerWidth - 24)}> <Modal className="management-modal" open={editing !== null} title={editing?.id ? `编辑巡检策略 · ${text(editing.name)}` : '新建巡检策略'} okText="保存策略" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()} width={Math.min(820, window.innerWidth - 24)}>
<Form form={form} layout="vertical"><Form.Item name="name" label="策略名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={100} /></Form.Item><Form.Item name="active" label="启用策略" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><h3>巡检规则</h3><div className="governance-form-grid">{booleanFields.map(([key, label]) => <Form.Item key={key} name={key} label={label} valuePropName="checked"><Switch /></Form.Item>)}{metricFields.map(field => <Form.Item key={field.key} name={field.key} label={field.label} rules={[{ required: true }]}><InputNumber min={field.min} max={field.max} step={field.step} style={{ width: '100%' }} /></Form.Item>)}</div><p className="completion-note">阈值范围由服务端校验;保存后对后续巡检生效。</p></Form><Alert showIcon type="info" message="受控 AI 下钻" description="启用后仅为巡检发现创建绑定当前用户、当前数据与授权范围的持久化分析轮次;模型不接收业务数据行或业务数值。最多选择 1–3 项。" /> <Form form={form} layout="vertical"><Form.Item name="name" label="策略名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={100} /></Form.Item><Form.Item name="active" label="启用策略" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><h3>巡检规则</h3><div className="governance-form-grid">{booleanFields.map(([key, label]) => <Form.Item key={key} name={key} label={label} valuePropName="checked"><Switch /></Form.Item>)}{metricFields.map(field => <Form.Item key={field.key} name={field.key} label={field.label} rules={[{ required: true }]}><InputNumber min={field.min} max={field.max} step={field.step} style={{ width: '100%' }} /></Form.Item>)}</div><p className="completion-note">阈值范围由服务端校验;保存后对后续巡检生效。</p></Form><Alert showIcon type="info" message="受控 AI 下钻" description="启用后仅为巡检发现创建绑定当前用户、当前数据与授权范围的持久化分析轮次;模型不接收业务数据行或业务数值。最多选择 1–3 项。" />
@@ -276,9 +276,9 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }
const [resolveForm] = Form.useForm<Row>(); const [resolveForm] = Form.useForm<Row>();
const [tab, setTab] = useState('coverage'); const [tab, setTab] = useState('coverage');
const tabRef = useRef(tab); tabRef.current = tab; const tabRef = useRef(tab); tabRef.current = tab;
const canMaintain = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role)); const canMaintain = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const canReview = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_PUBLISHER'].includes(role)); const canReview = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const canDownload = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER', 'BUSINESS_ANALYST', 'QUALITY_VIEWER', 'AUDIT_VIEWER'].includes(role)); const canDownload = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN', 'USER'].includes(role));
const stage = Form.useWatch('stage', protocolForm); const stage = Form.useWatch('stage', protocolForm);
const changeType = Form.useWatch('type', changeForm); const changeType = Form.useWatch('type', changeForm);
const resolveDecision = Form.useWatch('decision', resolveForm); const resolveDecision = Form.useWatch('decision', resolveForm);
@@ -524,7 +524,7 @@ export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { us
const [error, setError] = useState(''); const [error, setError] = useState('');
const [planOpen, setPlanOpen] = useState(false); const [planOpen, setPlanOpen] = useState(false);
const [form] = Form.useForm<Row>(); const [form] = Form.useForm<Row>();
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const canManage = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const load = useCallback(() => read.run(async () => { try { setData(await api.governanceBackups()); setLoaded(true); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '备份状态读取失败'); } }), [onUnauthorized, read.run]); const load = useCallback(() => read.run(async () => { try { setData(await api.governanceBackups()); setLoaded(true); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '备份状态读取失败'); } }), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]); useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
useMaintenanceRefresh(load); useMaintenanceRefresh(load);
@@ -582,7 +582,7 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
const [policyError, setPolicyError] = useState(''); const [policyError, setPolicyError] = useState('');
const [policyForm] = Form.useForm<Row>(); const [policyForm] = Form.useForm<Row>();
const actionLock = useRef(false); const actionLock = useRef(false);
const canRefresh = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const canRefresh = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const load = useCallback(() => read.run(async () => { const load = useCallback(() => read.run(async () => {
try { setData(await api.governanceMonitor()); setLoaded(true); setError(''); } try { setData(await api.governanceMonitor()); setLoaded(true); setError(''); }
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '运行监控读取失败'); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '运行监控读取失败'); }
@@ -696,7 +696,7 @@ export function ServiceIdentityPanel({ user, onUnauthorized }: { user: AuthUser;
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '服务身份读取失败'); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '服务身份读取失败'); }
}), [identityRead.run, onUnauthorized]); }), [identityRead.run, onUnauthorized]);
const loadBindings = useCallback(() => bindingRead.run(async () => { const loadBindings = useCallback(() => bindingRead.run(async () => {
const canReadBindings = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const canReadBindings = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
if (!canReadBindings) { setBindings([]); setBindingLoaded(true); return; } if (!canReadBindings) { setBindings([]); setBindingLoaded(true); return; }
try { setBindings(collectionItems(await api.serviceBindings())); setBindingLoaded(true); setBindingError(''); } try { setBindings(collectionItems(await api.serviceBindings())); setBindingLoaded(true); setBindingError(''); }
catch (value) { if (!onUnauthorized(value)) setBindingError(value instanceof Error ? value.message : '服务绑定读取失败'); } catch (value) { if (!onUnauthorized(value)) setBindingError(value instanceof Error ? value.message : '服务绑定读取失败'); }
+38 -33
View File
@@ -2,6 +2,7 @@ import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
import { MappingEditorContext } from './MappingEditorContext'; import { MappingEditorContext } from './MappingEditorContext';
import { ClassificationRuleEditor } from './ClassificationRuleEditor'; import { ClassificationRuleEditor } from './ClassificationRuleEditor';
import { ManagementSections } from './ManagementSections'; import { ManagementSections } from './ManagementSections';
import { ROLE_LABELS, ROLE_DESCRIPTIONS, USER_ROLE_OPTIONS } from './userRoles';
import type { ClassificationSelection } from './classificationMaintenance'; import type { ClassificationSelection } from './classificationMaintenance';
import { TasksMonitorPage } from './TasksMonitorPage'; import { TasksMonitorPage } from './TasksMonitorPage';
import { configurationDateTime, currentConfigurationName } from './configurationName'; import { configurationDateTime, currentConfigurationName } from './configurationName';
@@ -153,17 +154,6 @@ function decodeAnalysisLinkContext(encoded: string | null): AnalysisLinkContext
} }
} }
const ROLE_LABELS: Record<string, string> = {
AUDIT_VIEWER: '审计查看',
BUSINESS_ANALYST: '业务分析',
DATA_MAINTAINER: '数据维护',
DATA_PUBLISHER: '数据发布',
QUALITY_VIEWER: '质量查看',
RULE_MAINTAINER: '规则维护',
SYSTEM_ADMIN: '系统管理',
SYSTEM_OPERATOR: '运行维护',
};
function shownRole(value: unknown): string { function shownRole(value: unknown): string {
const role = String(value ?? ''); const role = String(value ?? '');
return ROLE_LABELS[role] ?? role; return ROLE_LABELS[role] ?? role;
@@ -238,7 +228,7 @@ function RulesWorkspace({ user, onUnauthorized, onNavigate }: Omit<ManagementPag
const editFormula = (code: string) => { setFocusMetric({ code: METRIC_KEYS[code] || code, request: Date.now() }); setSection('settings'); }; const editFormula = (code: string) => { setFocusMetric({ code: METRIC_KEYS[code] || code, request: Date.now() }); setSection('settings'); };
return <ManagementSections selectedKey={section} onSelect={setSection} items={[ return <ManagementSections selectedKey={section} onSelect={setSection} items={[
{ key: 'dictionary', label: '指标说明', children: <MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} onEditFormula={editFormula} /> }, { key: 'dictionary', label: '指标说明', children: <MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} onEditFormula={editFormula} /> },
...(user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)) ? [{ key: 'targets', label: '质量目标', children: <QualityTargetsPanel onUnauthorized={onUnauthorized} /> }] : []), { key: 'targets', label: '质量目标', children: <QualityTargetsPanel onUnauthorized={onUnauthorized} /> },
{ key: 'settings', label: '计算设置', children: <ConfigManagementPage kind="rules" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} focusMetric={focusMetric} /> }, { key: 'settings', label: '计算设置', children: <ConfigManagementPage kind="rules" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} focusMetric={focusMetric} /> },
]} />; ]} />;
} }
@@ -249,7 +239,7 @@ function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: Mana
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />; if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />; if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
if (page === 'rules') return <RulesWorkspace user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />; if (page === 'rules') return <RulesWorkspace user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
if (page === 'masterData') return <ManagementSections items={[{ key: 'catalog', label: '基础名录', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'filters', label: '查询字段', children: <FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />; if (page === 'masterData') return <ManagementSections items={[{ key: 'catalog', label: '基础名录', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'filters', label: '查询字段', children: <FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />;
if (page === 'mappings') return <MappingMaintenancePage user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />; if (page === 'mappings') return <MappingMaintenancePage user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = { const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = {
imports: { endpoint: 'imports', title: '导入与校验记录', subtitle: '接收后的来源文件及其校验任务状态。' }, imports: { endpoint: 'imports', title: '导入与校验记录', subtitle: '接收后的来源文件及其校验任务状态。' },
@@ -454,8 +444,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系'; const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系';
const testMode = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST'; const testMode = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
const canManage = user.roles.some(role => isRules const canManage = user.roles.some(role => isRules
? ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role) ? ['SYSTEM_ADMIN'].includes(role)
: ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'RULE_MAINTAINER'].includes(role)); : ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const canApplyWorkflow = (isRules ? workflowStatus?.capabilities?.canApplyRule : workflowStatus?.capabilities?.canApplyMapping) ?? workflowStatus?.capabilities?.canApply ?? canManage; const canApplyWorkflow = (isRules ? workflowStatus?.capabilities?.canApplyRule : workflowStatus?.capabilities?.canApplyMapping) ?? workflowStatus?.capabilities?.canApply ?? canManage;
const workflowMappingBase = workflowStatus?.activeMapping const workflowMappingBase = workflowStatus?.activeMapping
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping } ? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
@@ -651,7 +641,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
</div>} </div>}
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />} {error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />} {isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
{!canApplyWorkflow && <Alert showIcon type="info" message="当前账号可查看配置;保存和更新报表需要发布权限。" />} {!canApplyWorkflow && <Alert showIcon type="info" message={isRules ? '计算规则由系统管理员维护,当前账号可查看。' : '当前账号可查看配置;维护数据需要数据管理员权限。'} />}
{workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />} {workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}</strong></div>{workflowOperation.busy ? <Spin size="small" /> : <Progress percent={String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : 'success'} />}</section>} {workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}</strong></div>{workflowOperation.busy ? <Spin size="small" /> : <Progress percent={String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : 'success'} />}</section>}
</>; </>;
@@ -761,7 +751,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
} }
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) { function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
const canEdit=user.roles.some(role=>['SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER'].includes(role)); const canEdit=user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
return <ConfigManagementPage kind="mappings" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} extraSections={[ return <ConfigManagementPage kind="mappings" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} extraSections={[
{key:'groups',label:'业务分组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><UnclassifiedSourcesPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>}, {key:'groups',label:'业务分组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><UnclassifiedSourcesPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>},
{key:'projects',label:'项目组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><MappingIssueResolutionPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>}, {key:'projects',label:'项目组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><MappingIssueResolutionPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>},
@@ -843,7 +833,7 @@ function MetricDictionaryPanel({ user, onUnauthorized, onEditFormula }: { user:
const [editing, setEditing] = useState<Record<string, unknown> | null>(null); const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null); const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null);
const [form] = Form.useForm<{ name: string; aliases: string; description: string; reason: string }>(); const [form] = Form.useForm<{ name: string; aliases: string; description: string; reason: string }>();
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)); const canManage = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const load = useCallback(() => read.run(async () => { const load = useCallback(() => read.run(async () => {
try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); } try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); }
@@ -914,8 +904,8 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
const [issuesRunId, setIssuesRunId] = useState(''); const [issuesRunId, setIssuesRunId] = useState('');
const [busyId, setBusyId] = useState(''); const [busyId, setBusyId] = useState('');
const actionLock = useRef(false); const actionLock = useRef(false);
const canRetry = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role)); const canRetry = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const canCancel = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'SYSTEM_OPERATOR'].includes(role)); const canCancel = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const runIdOf = (row: Record<string, unknown>) => { const runIdOf = (row: Record<string, unknown>) => {
const payload = row.payload && typeof row.payload === 'object' ? row.payload as Record<string, unknown> : {}; const payload = row.payload && typeof row.payload === 'object' ? row.payload as Record<string, unknown> : {};
return String(row.importRunId || payload.importRunId || ''); return String(row.importRunId || payload.importRunId || '');
@@ -1745,7 +1735,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) }, { key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
], onClick: ({ key }) => { ], onClick: ({ key }) => {
if (key === 'rename') { setRenameTarget(item); setRenameTitle(String(item.title || '')); } if (key === 'rename') { setRenameTarget(item); setRenameTitle(String(item.title || '')); }
else if (key === 'delete') modal.confirm({ title: '删除此会话及其分析记录?', content: '删除后无法恢复', okText: '删除', cancelText: '取消', okButtonProps: { danger: true }, onOk: () => deleteSession(String(item.id)) }); else if (key === 'delete') modal.confirm({ className:'management-modal deletion-confirmation', title: `删除会话“${String(item.title || '未命名会话')}”?`, content: '此会话及其分析记录将被删除,删除后无法恢复。', okText: '确认删除', cancelText: '取消', autoFocusButton:'cancel', maskClosable:false, okButtonProps: { danger: true }, onOk: () => deleteSession(String(item.id)) });
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null} } }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null}
</aside> </aside>
<section className="panel analysis-chat-panel"> <section className="panel analysis-chat-panel">
@@ -1881,8 +1871,8 @@ function isObjectRecord(value: unknown): value is Record<string, unknown> {
function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const canManageUsers = user.roles.includes('SYSTEM_ADMIN'); const canManageUsers = user.roles.includes('SYSTEM_ADMIN');
const canReadAudit = user.roles.some(role => ['SYSTEM_ADMIN', 'AUDIT_VIEWER'].includes(role)); const canReadAudit = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const canViewServiceIdentities = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR', 'AUDIT_VIEWER'].includes(role)); const canViewServiceIdentities = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const defaultTab = canManageUsers ? 'users' : canReadAudit ? 'audit' : canViewServiceIdentities ? 'services' : ''; const defaultTab = canManageUsers ? 'users' : canReadAudit ? 'audit' : canViewServiceIdentities ? 'services' : '';
const [activeTab] = useState(defaultTab); const [activeTab] = useState(defaultTab);
const tabs = [ const tabs = [
@@ -1894,7 +1884,7 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized:
return <div className="management-page"> return <div className="management-page">
<PageHeader title="权限与审计" /> <PageHeader title="权限与审计" />
{tabs.length > 0 ? <ManagementSections initialKey={activeTab} items={[...tabs, { key: 'summary', label: '当前授权', children: <section className="panel access-summary"><div><span>当前账号</span><strong>{user.displayName || user.username}</strong>{user.displayName && user.displayName !== user.username && <small>{user.username}</small>}</div><div><span>角色</span><strong>{user.roles.length} 项</strong><small className="role-list role-summary-list">{user.roles.length ? user.roles.map((role, index) => <span key={`${role}-${index}`}>{shownRole(role)}</span>) : '服务端未返回角色'}</small></div><div><span>授权产业部</span><strong>{user.departments.length ? user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') : '未返回范围'}</strong></div><div><span>授权分组</span><strong>{user.groups.length ? user.groups.join('、') : user.roles.includes('SYSTEM_ADMIN') ? '未限制' : '未返回范围'}</strong></div></section> }]} /> : <Alert showIcon type="info" message="当前账号没有用户管理或审计记录读取权限" />} {tabs.length > 0 ? <ManagementSections initialKey={activeTab} items={[...tabs, { key: 'summary', label: '当前授权', children: <section className="panel access-summary"><div><span>当前账号</span><strong>{user.displayName || user.username}</strong>{user.displayName && user.displayName !== user.username && <small>{user.username}</small>}</div><div><span>角色</span><strong>{shownRole(user.roles[0])}</strong></div><div><span>授权产业部</span><strong>{user.departments.length ? user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') : '未返回范围'}</strong></div><div><span>授权分组</span><strong>{user.groups.length ? user.groups.join('、') : user.roles.includes('SYSTEM_ADMIN') ? '未限制' : '未返回范围'}</strong></div></section> }]} /> : <Alert showIcon type="info" message="当前账号没有用户管理或审计记录读取权限" />}
</div>; </div>;
} }
@@ -1921,8 +1911,6 @@ function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => b
</div>; </div>;
} }
const ROLE_OPTIONS = ['SYSTEM_ADMIN', 'QUALITY_VIEWER', 'BUSINESS_ANALYST', 'DATA_MAINTAINER', 'RULE_MAINTAINER', 'DATA_PUBLISHER', 'SYSTEM_OPERATOR', 'AUDIT_VIEWER'];
function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp(); const { message } = App.useApp();
const { active } = usePageCache(); const { active } = usePageCache();
@@ -1936,7 +1924,9 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
const [error, setError] = useState(''); const [error, setError] = useState('');
const saveLock = useRef(false); const saveLock = useRef(false);
const [editing, setEditing] = useState<Record<string, unknown> | null>(null); const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
const [form] = Form.useForm<{ username: string; displayName: string; password: string; active: boolean; forcePasswordChange: boolean; roles: string[]; departments: string[]; groups: string[] }>(); const [form] = Form.useForm<{ username: string; displayName: string; password: string; active: boolean; forcePasswordChange: boolean; role: string; departments: string[]; groups: string[] }>();
const selectedRole = Form.useWatch('role', form);
const [deleting, setDeleting] = useState<Record<string, unknown> | null>(null);
const canManage = user.roles.includes('SYSTEM_ADMIN'); const canManage = user.roles.includes('SYSTEM_ADMIN');
const load = useCallback(() => read.run(async () => { const load = useCallback(() => read.run(async () => {
@@ -1960,7 +1950,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
form.setFieldsValue({ form.setFieldsValue({
username: String(record?.username || ''), displayName: String(record?.displayName || ''), password: '', username: String(record?.username || ''), displayName: String(record?.displayName || ''), password: '',
active: record?.active !== false, forcePasswordChange: record?.forcePasswordChange === true, active: record?.active !== false, forcePasswordChange: record?.forcePasswordChange === true,
roles: Array.isArray(record?.roles) ? record.roles.map(String) : [], role: Array.isArray(record?.roles) ? String(record.roles[0] || 'USER') : 'USER',
departments: Array.isArray(record?.departments) ? record.departments.map(String) : [], departments: Array.isArray(record?.departments) ? record.departments.map(String) : [],
groups: Array.isArray(record?.groups) ? record.groups.map(String) : [], groups: Array.isArray(record?.groups) ? record.groups.map(String) : [],
}); });
@@ -1973,9 +1963,9 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
setBusy(true); setBusy(true);
const id = String(editing?.id || ''); const id = String(editing?.id || '');
if (id) { if (id) {
await api.updateUser(id, { displayName: values.displayName.trim(), active: values.active, forcePasswordChange: values.forcePasswordChange, roles: values.roles, departments: values.departments, groups: values.groups, expectedRowVersion: Number(editing?.rowVersion || 0) }); await api.updateUser(id, { displayName: values.displayName.trim(), active: values.active, forcePasswordChange: values.forcePasswordChange, roles: [values.role], departments: values.departments, groups: values.groups, expectedRowVersion: Number(editing?.rowVersion || 0) });
} else { } else {
await api.createUser({ username: values.username.trim(), displayName: values.displayName.trim(), password: values.password, roles: values.roles, departments: values.departments, groups: values.groups }); await api.createUser({ username: values.username.trim(), displayName: values.displayName.trim(), password: values.password, roles: [values.role], departments: values.departments, groups: values.groups });
} }
message.success(id ? '用户权限已更新' : '用户已创建'); message.success(id ? '用户权限已更新' : '用户已创建');
setEditing(null); form.resetFields(); await load(); setEditing(null); form.resetFields(); await load();
@@ -1986,6 +1976,18 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
} finally { saveLock.current = false; setBusy(false); } } finally { saveLock.current = false; setBusy(false); }
}; };
const removeUser = async () => {
if (!deleting || saveLock.current) return;
saveLock.current = true; setBusy(true);
try {
await api.deleteUser(String(deleting.id), Number(deleting.rowVersion));
setDeleting(null); message.success('账号已删除,历史记录已保留'); await load();
} catch (value) {
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && [404, 409].includes(value.status)) { setDeleting(null); await load(); }
} finally { saveLock.current = false; setBusy(false); }
};
const columns: ColumnsType<Record<string, unknown>> = [ const columns: ColumnsType<Record<string, unknown>> = [
{ title: '账号', dataIndex: 'username', key: 'username', fixed: 'left', width: 170 }, { title: '账号', dataIndex: 'username', key: 'username', fixed: 'left', width: 170 },
{ title: '显示名称', dataIndex: 'displayName', key: 'displayName', width: 180 }, { title: '显示名称', dataIndex: 'displayName', key: 'displayName', width: 180 },
@@ -1993,18 +1995,21 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
{ title: '角色', dataIndex: 'roles', key: 'roles', width: 250, render: value => Array.isArray(value) ? value.length ? <span className="role-list">{value.map((role, index) => <span key={`${String(role)}-${index}`}>{shownRole(role)}</span>)}</span> : '—' : '—' }, { title: '角色', dataIndex: 'roles', key: 'roles', width: 250, render: value => Array.isArray(value) ? value.length ? <span className="role-list">{value.map((role, index) => <span key={`${String(role)}-${index}`}>{shownRole(role)}</span>)}</span> : '—' : '—' },
{ title: '授权产业部', dataIndex: 'departments', key: 'departments', width: 230, render: value => Array.isArray(value) ? value.map(item => shownDepartment(String(item))).join('、') || '未限制' : '—' }, { title: '授权产业部', dataIndex: 'departments', key: 'departments', width: 230, render: value => Array.isArray(value) ? value.map(item => shownDepartment(String(item))).join('、') || '未限制' : '—' },
{ title: '授权分组', dataIndex: 'groups', key: 'groups', width: 180, render: value => Array.isArray(value) ? value.join('、') || '未限制' : '—' }, { title: '授权分组', dataIndex: 'groups', key: 'groups', width: 180, render: value => Array.isArray(value) ? value.join('、') || '未限制' : '—' },
{ title: '操作', key: 'actions', fixed: 'right', width: 110, align: 'center', render: (_, row) => canManage ? <Button type="link" onClick={() => openEditor(row)}>编辑授权</Button> : <span className="muted-dash">权限不足</span> }, { title: '操作', key: 'actions', fixed: 'right', width: 180, align: 'center', render: (_, row) => canManage ? <><Button type="link" disabled={busy} onClick={() => openEditor(row)}>编辑授权</Button><Button type="link" danger disabled={busy || row.id === user.id} title={row.id === user.id ? '不能删除当前登录账号' : undefined} onClick={() => setDeleting(row)}>删除</Button></> : <span className="muted-dash">权限不足</span> },
]; ];
return <div className="resource-tab"> return <div className="resource-tab">
{error && <Alert type="error" showIcon message="用户清单读取失败" description={usersLoaded || optionsLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />} {error && <Alert type="error" showIcon message="用户清单读取失败" description={usersLoaded || optionsLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
<div className="resource-toolbar"><strong>用户清单</strong><span>{users.length} 个账号</span>{canManage && <Button type="primary" onClick={() => openEditor()}>新建用户</Button>}<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div> <div className="resource-toolbar"><strong>用户清单</strong><span>{users.length} 个账号</span>{canManage && <Button type="primary" onClick={() => openEditor()}>新建用户</Button>}<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
{loading && !usersLoaded ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : usersLoaded ? users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" /> : null} {loading && !usersLoaded ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : usersLoaded ? users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1280 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" /> : null}
<Modal className="management-modal" open={Boolean(deleting)} title={`删除账号 ${String(deleting?.username || '')}`} okText="删除账号" cancelText="取消" okButtonProps={{ danger: true }} confirmLoading={busy} cancelButtonProps={{ disabled: busy }} closable={!busy} maskClosable={!busy} onCancel={() => { if (!busy) setDeleting(null); }} onOk={() => void removeUser()}>
<p>删除后,该账号将无法登录,并从用户清单移除。已有业务数据和操作记录会保留。</p>
</Modal>
<Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑用户授权' : '新建用户'} width={700} confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}> <Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑用户授权' : '新建用户'} width={700} confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
<Alert className="user-management-note" showIcon type="info" message="需至少保留一个启用的系统管理员;未配置产业部的非管理员账号可能没有业务数据访问范围。" /> <Alert className="user-management-note" showIcon type="info" message="需至少保留一个启用的系统管理员;未配置产业部的非管理员账号可能没有业务数据访问范围。" />
<Form form={form} layout="vertical"> <Form form={form} layout="vertical">
{!editing?.id && <><Form.Item name="username" label="登录账号" rules={[{ required: true, whitespace: true, message: '请填写登录账号' }]}><Input autoComplete="off" /></Form.Item><Form.Item name="password" label="初始密码" rules={[{ required: true, min: 6, message: '初始密码至少6位' }]}><Input.Password autoComplete="new-password" /></Form.Item></>} {!editing?.id && <><Form.Item name="username" label="登录账号" rules={[{ required: true, whitespace: true, message: '请填写登录账号' }]}><Input autoComplete="off" /></Form.Item><Form.Item name="password" label="初始密码" rules={[{ required: true, min: 6, message: '初始密码至少6位' }]}><Input.Password autoComplete="new-password" /></Form.Item></>}
<Form.Item name="displayName" label="显示名称" rules={[{ required: true, whitespace: true, message: '请填写显示名称' }]}><Input /></Form.Item> <Form.Item name="displayName" label="显示名称" rules={[{ required: true, whitespace: true, message: '请填写显示名称' }]}><Input /></Form.Item>
<Form.Item name="roles" label="角色" rules={[{ required: true, message: '至少选择一个角色' }]}><Select mode="multiple" options={ROLE_OPTIONS.map(value => ({ label: shownRole(value), value }))} /></Form.Item> <Form.Item name="role" label="角色" extra={ROLE_DESCRIPTIONS[selectedRole]} rules={[{ required: true, message: '请选择一个角色' }]}><Select options={USER_ROLE_OPTIONS} /></Form.Item>
<Form.Item name="departments" label="授权产业部"><Select {...readableSelectPopup} mode="multiple" options={departments.map(value => ({ label: shownDepartment(value), value }))} placeholder="选择数据范围;空范围可能无法读取业务数据" /></Form.Item> <Form.Item name="departments" label="授权产业部"><Select {...readableSelectPopup} mode="multiple" options={departments.map(value => ({ label: shownDepartment(value), value }))} placeholder="选择数据范围;空范围可能无法读取业务数据" /></Form.Item>
<Form.Item name="groups" label="授权业务分组"><Select {...readableSelectPopup} mode="multiple" options={groups.map(value => ({ label: value, value }))} placeholder="选择可访问的业务分组" /></Form.Item> <Form.Item name="groups" label="授权业务分组"><Select {...readableSelectPopup} mode="multiple" options={groups.map(value => ({ label: value, value }))} placeholder="选择可访问的业务分组" /></Form.Item>
{Boolean(editing?.id) && <div className="user-access-toggles"><Form.Item name="active" label="账号状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><Form.Item name="forcePasswordChange" label="下次登录修改密码" valuePropName="checked"><Switch /></Form.Item></div>} {Boolean(editing?.id) && <div className="user-access-toggles"><Form.Item name="active" label="账号状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><Form.Item name="forcePasswordChange" label="下次登录修改密码" valuePropName="checked"><Switch /></Form.Item></div>}
+16 -8
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { configurationDateTime } from './configurationName'; import { configurationDateTime } from './configurationName';
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd'; import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd';
@@ -52,6 +53,7 @@ export type PendingSourceDeletion = { ids: string[]; releaseId: string | null };
type SourceDraft = { id: string; file: File; workbook: WorkbookPreview; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'ADD' | 'REPLACE'; targetId: string; scopeCode: string }; type SourceDraft = { id: string; file: File; workbook: WorkbookPreview; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'ADD' | 'REPLACE'; targetId: string; scopeCode: string };
function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { options: SourceUploadOptions; workflowStatus: DataWorkflowStatus; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) { function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { options: SourceUploadOptions; workflowStatus: DataWorkflowStatus; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const { message } = App.useApp();
const input = useRef<HTMLInputElement>(null); const input = useRef<HTMLInputElement>(null);
const configured = useRef(new Map<string, { signature: string; sourceId: string }>()); const configured = useRef(new Map<string, { signature: string; sourceId: string }>());
@@ -84,7 +86,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
const duplicateSlots = new Set(slots).size !== slots.length; const duplicateSlots = new Set(slots).size !== slots.length;
const canImport = hasImportCapability && drafts.length > 0 && drafts.every(draftReady) && !duplicateSlots && !pendingDeletion.ids.length; const canImport = hasImportCapability && drafts.length > 0 && drafts.every(draftReady) && !duplicateSlots && !pendingDeletion.ids.length;
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }; const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
const removeDraft = (id: string) => { setDrafts(previous => previous.filter(item => item.id !== id)); configured.current.delete(id); }; const removeDraft = (id: string) => confirmDelete({title:`移除文件“${drafts.find(item=>item.id===id)?.workbook.sourceFile || "选中的文件"}”?`,description:"仅从本次导入列表移除,此文件的字段对应设置也将移除。电脑上的原文件及已接收来源保留。",confirmText:"确认移除",onConfirm:()=>{setDrafts(previous => previous.filter(item => item.id !== id));configured.current.delete(id);}});
const readFiles = async (files: File[]) => { const readFiles = async (files: File[]) => {
if (!files.length || importBusy || actionLock.current) return; if (!files.length || importBusy || actionLock.current) return;
actionLock.current = true; actionLock.current = true;
@@ -136,13 +138,18 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds })); await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); } } catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
}; };
const recalculate = async () => { const performRecalculation = async () => {
if (actionLock.current) return; actionLock.current = true; if (actionLock.current) return; actionLock.current = true;
setError(''); setError('');
try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); } try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); }
catch (value) { reportError(value); } catch (value) { reportError(value); }
finally { actionLock.current = false; } finally { actionLock.current = false; }
}; };
const recalculate = () => {
if (actionLock.current) return;
if (!pendingDeletion.ids.length) return performRecalculation();
confirmDelete({title:`删除 ${pendingDeletion.ids.length} 个来源并更新报表?`,description:<><p>将从当前查询结果移除以下来源并更新报表,原文件和处理记录保留。</p><ul>{pendingDeletion.ids.slice(0,10).map((id,index)=><li key={id}>{options.targets.find(item=>item.documentId===id)?.sourceFile || `第 ${index+1} 个待删除来源`}</li>)}</ul>{pendingDeletion.ids.length>10&&<p>另有 {pendingDeletion.ids.length-10} 个待删除来源。</p>}</>,confirmText:'确认删除并更新',onConfirm:performRecalculation});
};
return <div className="nc-simplified-intake"> return <div className="nc-simplified-intake">
<section className="panel nc-simple-upload-panel"> <section className="panel nc-simple-upload-panel">
<div className="nc-simple-upload-heading"><div><span className="nc-eyebrow">测试数据维护</span><h2>导入来源并更新报表</h2><p>支持一次选择多个 Excel 文件,分别核对年月与阶段后统一导入。</p></div><div className="nc-simple-upload-actions">{workflowStatus.capabilities?.canRecalculate !== false && <Button icon={<ReloadOutlined />} disabled={importBusy} loading={recalcOperation.busy} onClick={() => void recalculate()}>{pendingDeletion.ids.length ? `更新报表(${pendingDeletion.ids.length}项删除)` : '更新报表'}</Button>}</div></div> <div className="nc-simple-upload-heading"><div><span className="nc-eyebrow">测试数据维护</span><h2>导入来源并更新报表</h2><p>支持一次选择多个 Excel 文件,分别核对年月与阶段后统一导入。</p></div><div className="nc-simple-upload-actions">{workflowStatus.capabilities?.canRecalculate !== false && <Button icon={<ReloadOutlined />} disabled={importBusy} loading={recalcOperation.busy} onClick={() => void recalculate()}>{pendingDeletion.ids.length ? `更新报表(${pendingDeletion.ids.length}项删除)` : '更新报表'}</Button>}</div></div>
@@ -207,8 +214,8 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
const optionsAttempted = useRef(false); const optionsAttempted = useRef(false);
const candidatesAttempted = useRef(false); const candidatesAttempted = useRef(false);
const [resumeId, setResumeId] = useState(''); const [resumeId, setResumeId] = useState('');
const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER']); const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']); const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
const loadOptions = useCallback(() => optionsRead.run(async () => { const loadOptions = useCallback(() => optionsRead.run(async () => {
try { setOptions(await api.sourceUploadOptions()); setOptionError(''); } try { setOptions(await api.sourceUploadOptions()); setOptionError(''); }
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); } catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
@@ -249,6 +256,7 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
} }
export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; sourcesLoaded: boolean; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) { export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; sourcesLoaded: boolean; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const { message } = App.useApp();
const { active } = usePageCache(); const { active } = usePageCache();
const [showDeleted, setShowDeleted] = useState(false); const [showDeleted, setShowDeleted] = useState(false);
@@ -262,7 +270,7 @@ export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendin
const [deletedError, setDeletedError] = useState(''); const [deletedError, setDeletedError] = useState('');
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false); const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
const [selected, setSelected] = useState<{ id: string; restore: boolean } | null>(() => { const id = new URLSearchParams(window.location.search).get('sourceDeleteId'); return id ? { id, restore: false } : null; }); const [selected, setSelected] = useState<{ id: string; restore: boolean } | null>(() => { const id = new URLSearchParams(window.location.search).get('sourceDeleteId'); return id ? { id, restore: false } : null; });
const canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER']); const canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
const loadDeleted = useCallback(() => deletedRead.run(async () => { const loadDeleted = useCallback(() => deletedRead.run(async () => {
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); } try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); }
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); } catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
@@ -311,7 +319,7 @@ export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendin
const onCurrentRelease = currentSourceIds?.includes(row.id) ?? false; const onCurrentRelease = currentSourceIds?.includes(row.id) ?? false;
const permitted = !simplified || (showDeleted ? workflowStatus?.capabilities?.canRestoreSource !== false : currentSourceIds !== null && workflowStatus?.capabilities?.canDeleteSource !== false && (!onCurrentRelease || workflowStatus?.capabilities?.canDeleteCurrentSource !== false)); const permitted = !simplified || (showDeleted ? workflowStatus?.capabilities?.canRestoreSource !== false : currentSourceIds !== null && workflowStatus?.capabilities?.canDeleteSource !== false && (!onCurrentRelease || workflowStatus?.capabilities?.canDeleteCurrentSource !== false));
if (!workflowStatusLoaded || !canOperate || !permitted) return null; if (!workflowStatusLoaded || !canOperate || !permitted) return null;
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => simplified ? showDeleted ? void runSourceOperation(row.id, true) : onToggleDelete(row.id) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>; return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => {if(!simplified){setSelected({id:row.id,restore:showDeleted});return;}if(showDeleted){void runSourceOperation(row.id,true);return;}if(pendingIds.includes(row.id)){onToggleDelete(row.id);return;}confirmDelete({title:`删除来源“${row.sourceFile}”?`,description:"将标记为待删除,当前报表暂不改变。点击“更新报表”后才生效,原文件和处理记录保留。",confirmText:"标记删除",onConfirm:()=>onToggleDelete(row.id)});}}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
} }, } },
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null} ]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null}
</section> </section>
@@ -334,7 +342,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
const request = preview?.changeRequest; const requestStatus = String(request?.status || ''); const request = preview?.changeRequest; const requestStatus = String(request?.status || '');
const isRequested = preview?.nextAction === 'REVIEW_WITHDRAWAL'; const isApproved = preview?.nextAction === 'BUILD_WITHDRAWAL_CANDIDATE'; const isBuilt = preview?.nextAction === 'RECONCILE_CANDIDATE'; const isRequested = preview?.nextAction === 'REVIEW_WITHDRAWAL'; const isApproved = preview?.nextAction === 'BUILD_WITHDRAWAL_CANDIDATE'; const isBuilt = preview?.nextAction === 'RECONCILE_CANDIDATE';
const withdrawing = preview?.mode === 'WITHDRAW_CURRENT' || isRequested || isApproved || isBuilt; const withdrawing = preview?.mode === 'WITHDRAW_CURRENT' || isRequested || isApproved || isBuilt;
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']); const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
const canReview = preview?.canReview ?? canPublish; const canBuild = preview?.canBuild ?? canPublish; const canReview = preview?.canReview ?? canPublish; const canBuild = preview?.canBuild ?? canPublish;
const awaitingTask = preview?.nextAction === 'WAIT_FOR_TASK'; const awaitingTask = preview?.nextAction === 'WAIT_FOR_TASK';
const canStart = Boolean(preview?.canDelete && !awaitingTask && !preview.hidden && !isRequested && !isApproved && !isBuilt); const canStart = Boolean(preview?.canDelete && !awaitingTask && !preview.hidden && !isRequested && !isApproved && !isBuilt);
@@ -422,7 +430,7 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
const [differenceReason, setDifferenceReason] = useState(''); const [confirmDifferences, setConfirmDifferences] = useState(false); const [publishConfirmed, setPublishConfirmed] = useState(false); const [published, setPublished] = useState(false); const [differenceReason, setDifferenceReason] = useState(''); const [confirmDifferences, setConfirmDifferences] = useState(false); const [publishConfirmed, setPublishConfirmed] = useState(false); const [published, setPublished] = useState(false);
const target = options.targets.find(item => item.documentId === targetId); const fields = options.fields[stage] || []; const target = options.targets.find(item => item.documentId === targetId); const fields = options.fields[stage] || [];
const headers = workbook?.preview.headers || []; const missingFields = fields.filter(field => field.required && !fieldMap[field.name]); const duplicateColumns = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size; const headers = workbook?.preview.headers || []; const missingFields = fields.filter(field => field.required && !fieldMap[field.name]); const duplicateColumns = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']); const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_ADMIN']);
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]); const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => { const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => {
if (!activeRef.current || !isCurrent()) return false; if (!activeRef.current || !isCurrent()) return false;
+1 -5
View File
@@ -2,14 +2,10 @@ import { useEffect, useRef, useState } from 'react';
import { Alert, App, Button, Descriptions, Form, Input, Modal, Tabs } from 'antd'; import { Alert, App, Button, Descriptions, Form, Input, Modal, Tabs } from 'antd';
import { api } from './api'; import { api } from './api';
import type { AuthUser } from './types'; import type { AuthUser } from './types';
import { ROLE_LABELS as roles } from './userRoles';
export type AccountTab = 'profile' | 'password'; export type AccountTab = 'profile' | 'password';
type PasswordValues = { currentPassword: string; newPassword: string; confirmation: string }; type PasswordValues = { currentPassword: string; newPassword: string; confirmation: string };
const roles: Record<string, string> = {
DATA_MAINTAINER: '数据维护', DATA_PUBLISHER: '数据发布', QUALITY_VIEWER: '质量查看',
RULE_MAINTAINER: '规则维护', SYSTEM_ADMIN: '系统管理', SYSTEM_OPERATOR: '运行维护',
BUSINESS_ANALYST: '业务分析', AUDIT_VIEWER: '审计查看',
};
export default function PersonalAccount({ user, tab, onClose, onUserChange, onUnauthorized, onLogout }: { export default function PersonalAccount({ user, tab, onClose, onUserChange, onUnauthorized, onLogout }: {
user: AuthUser; tab: AccountTab | null; onClose: () => void; user: AuthUser; tab: AccountTab | null; onClose: () => void;
+4 -2
View File
@@ -1,5 +1,6 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Popconfirm, Select, Spin } from 'antd'; import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Select, Spin } from 'antd';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons'; import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { CompactManagementTables, QualityTable as Table } from './QualityTable'; import { CompactManagementTables, QualityTable as Table } from './QualityTable';
import { ApiError, api } from './api'; import { ApiError, api } from './api';
@@ -15,6 +16,7 @@ const targetInput=(row:Row)=>Object.fromEntries(['metric','periodType','year','p
type TargetForm={year:number;metric:string;scope:string;department?:string;group?:string;product?:string;projectGroup?:string;value:number|null;inherit:boolean}; type TargetForm={year:number;metric:string;scope:string;department?:string;group?:string;product?:string;projectGroup?:string;value:number|null;inherit:boolean};
export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unknown)=>boolean}){ export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unknown)=>boolean}){
const confirmDelete = useDeleteConfirmation();
const {message}=App.useApp();const [version,setVersion]=useState<Row|null>(null),[targets,setTargets]=useState<Row[]>([]),[references,setReferences]=useState<Row>({}); const {message}=App.useApp();const [version,setVersion]=useState<Row|null>(null),[targets,setTargets]=useState<Row[]>([]),[references,setReferences]=useState<Row>({});
const [loading,setLoading]=useState(true),[error,setError]=useState(''),[saving,setSaving]=useState(false),[editing,setEditing]=useState<Row|null>(null); const [loading,setLoading]=useState(true),[error,setError]=useState(''),[saving,setSaving]=useState(false),[editing,setEditing]=useState<Row|null>(null);
const [year,setYear]=useState(new Date().getFullYear()),[metric,setMetric]=useState('COMPOSITE_RATE'); const [year,setYear]=useState(new Date().getFullYear()),[metric,setMetric]=useState('COMPOSITE_RATE');
@@ -81,7 +83,7 @@ export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unkn
{loading&&!version?<div className="loading-panel"><Spin/>读取质量目标…</div>:version?<Table size="small" bordered rowKey="key" pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:780}} dataSource={tableRows} columns={[ {loading&&!version?<div className="loading-panel"><Spin/>读取质量目标…</div>:version?<Table size="small" bordered rowKey="key" pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:780}} dataSource={tableRows} columns={[
{title:'年度',dataIndex:'year',width:90},{title:'适用范围',dataIndex:'scopeName',width:270},{title:'指标',dataIndex:'metric',width:225,render:v=>METRIC_NAMES[String(v)]||String(v)}, {title:'年度',dataIndex:'year',width:90},{title:'适用范围',dataIndex:'scopeName',width:270},{title:'指标',dataIndex:'metric',width:225,render:v=>METRIC_NAMES[String(v)]||String(v)},
{title:'目标值',dataIndex:'displayValue',width:120,render:percent},{title:'目标来源',width:150,render:(_,row)=>row.inherited?String(row.inheritSource||'沿用总体目标'):row.exists?'单独设置':'未设置'}, {title:'目标值',dataIndex:'displayValue',width:120,render:percent},{title:'目标来源',width:150,render:(_,row)=>row.inherited?String(row.inheritSource||'沿用总体目标'):row.exists?'单独设置':'未设置'},
{title:'操作',width:185,render:(_,row)=><span className="task-actions"><Button type="link" onClick={()=>open(row)}>{row.inherited?'设置覆盖':'编辑'}</Button>{Boolean(row.exists)&&Object.keys(dimensions(row.dimensions)).length>0&&<Popconfirm title="删除该范围的单独目标?" onConfirm={()=>persist(targets.filter(item=>String(item.periodType).toUpperCase()!=='YEAR'||identity(item)!==identity(row)))}><Button type="link" danger disabled={saving}>删除覆盖值</Button></Popconfirm>}</span>}, {title:'操作',width:185,render:(_,row)=><span className="task-actions"><Button type="link" onClick={()=>open(row)}>{row.inherited?'设置覆盖':'编辑'}</Button>{Boolean(row.exists)&&Object.keys(dimensions(row.dimensions)).length>0&&<Button type="link" danger disabled={saving} onClick={()=>confirmDelete({title:`删除“${String(row.scopeName)}”的单独目标?`,description:`确认后立即生效,该范围将改为沿用上级或总体目标。${row.year}年其他范围的目标不变。`,onConfirm:()=>persist(targets.filter(item=>String(item.periodType).toUpperCase()!=='YEAR'||identity(item)!==identity(row)))})}>删除覆盖值</Button>}</span>},
]}/>:!loading&&!error?<Empty description="当前没有启用的质量目标"/>:null} ]}/>:!loading&&!error?<Empty description="当前没有启用的质量目标"/>:null}
<Modal className="management-modal" open={Boolean(editing)} title={editing?.inherited?'设置范围目标':editing?.newRecord?'新增质量目标':'编辑质量目标'} okText="保存目标" confirmLoading={saving} onCancel={()=>setEditing(null)} onOk={()=>void save()} width={640}> <Modal className="management-modal" open={Boolean(editing)} title={editing?.inherited?'设置范围目标':editing?.newRecord?'新增质量目标':'编辑质量目标'} okText="保存目标" confirmLoading={saving} onCancel={()=>setEditing(null)} onOk={()=>void save()} width={640}>
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="year" label="年度" rules={[{required:true}]}><InputNumber min={2000} max={2100} precision={0} style={{width:'100%'}}/></Form.Item><Form.Item name="metric" label="指标" rules={[{required:true}]}><Select {...readableSelectPopup} options={Object.entries(METRIC_NAMES).map(([value,label])=>({value,label}))}/></Form.Item></div> <Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="year" label="年度" rules={[{required:true}]}><InputNumber min={2000} max={2100} precision={0} style={{width:'100%'}}/></Form.Item><Form.Item name="metric" label="指标" rules={[{required:true}]}><Select {...readableSelectPopup} options={Object.entries(METRIC_NAMES).map(([value,label])=>({value,label}))}/></Form.Item></div>
+4 -2
View File
@@ -1,3 +1,4 @@
import { canAccessWorkspacePage } from './userRoles';
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { import {
Alert, Alert,
@@ -187,6 +188,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
if (sessionLoading) return <div className="screen-state"><Spin indicator={<LoadingOutlined spin />} /> <span>正在连接质量数据分析平台…</span></div>; if (sessionLoading) return <div className="screen-state"><Spin indicator={<LoadingOutlined spin />} /> <span>正在连接质量数据分析平台…</span></div>;
if (sessionError) return <div className="screen-state"><div className="state-card"><strong>服务暂不可用</strong><p>{sessionError}</p><Button onClick={() => window.location.reload()}>重新连接</Button></div></div>; if (sessionError) return <div className="screen-state"><div className="state-card"><strong>服务暂不可用</strong><p>{sessionError}</p><Button onClick={() => window.location.reload()}>重新连接</Button></div></div>;
if (!user) return <LoginPage onSuccess={setUser} />; if (!user) return <LoginPage onSuccess={setUser} />;
const visibleNavGroups = navGroups.map(group => ({ ...group, items: group.items.filter(([key]) => canAccessWorkspacePage(user, key)) })).filter(group => group.items.length);
return ( return (
<div className={`app-shell${sidebarCollapsed ? ' sidebar-collapsed' : ''}`}> <div className={`app-shell${sidebarCollapsed ? ' sidebar-collapsed' : ''}`}>
@@ -196,7 +198,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
<span className="brand-copy">质量数据分析平台</span> <span className="brand-copy">质量数据分析平台</span>
</button> </button>
<nav className="side-navigation" aria-label="主导航"> <nav className="side-navigation" aria-label="主导航">
{navGroups.map(group => ( {visibleNavGroups.map(group => (
<div className="nav-group" key={group.label}> <div className="nav-group" key={group.label}>
<div className="nav-group-label">{group.label}</div> <div className="nav-group-label">{group.label}</div>
{group.items.map(([key, label, Icon]) => ( {group.items.map(([key, label, Icon]) => (
@@ -255,7 +257,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
<div className="mobile-brand"> <div className="mobile-brand">
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span><strong>质量数据分析平台</strong> <span className="brand-mark" aria-hidden="true"><i /><i /><i /></span><strong>质量数据分析平台</strong>
<Select<PageKey> {...readableSelectPopup} aria-label="页面导航" value={page} onChange={value => navigate(value)} options={[ <Select<PageKey> {...readableSelectPopup} aria-label="页面导航" value={page} onChange={value => navigate(value)} options={[
...navGroups.map(group => ({ label: group.label, options: group.items.map(([value, label]) => ({ value, label })) })), ...visibleNavGroups.map(group => ({ label: group.label, options: group.items.map(([value, label]) => ({ value, label })) })),
]} /> ]} />
<Button type="text" icon={<UserOutlined />} aria-label="打开个人账户" onClick={() => setAccountTab('profile')} /> <Button type="text" icon={<UserOutlined />} aria-label="打开个人账户" onClick={() => setAccountTab('profile')} />
</div> </div>
+34 -18
View File
@@ -1,3 +1,4 @@
import { QuerySnapshotButton } from './QuerySnapshotButton';
import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope'; import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope';
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion'; import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
import { trendBarPalette } from './trendBarPalette'; import { trendBarPalette } from './trendBarPalette';
@@ -432,7 +433,7 @@ export default function QueryPage({ page, onUnauthorized }: {
useEffect(() => { useEffect(() => {
if (!active) return; if (!active) return;
const url = new URL(window.location.href); const url = new URL(window.location.href);
if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || '')) return; if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || 'overall')) return;
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryForLocation(queryParams, initialQuery.releaseId) })); const bytes = new TextEncoder().encode(JSON.stringify({ query: queryForLocation(queryParams, initialQuery.releaseId) }));
let binary = ''; let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte); for (const byte of bytes) binary += String.fromCharCode(byte);
@@ -615,7 +616,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const years = (options?.years || []).map(value => { const numeric = Number(String(value).match(/\d{4}/)?.[0]); return { label: `${numeric}年`, value: numeric }; }).filter(item => Number.isFinite(item.value)); const years = (options?.years || []).map(value => { const numeric = Number(String(value).match(/\d{4}/)?.[0]); return { label: `${numeric}年`, value: numeric }; }).filter(item => Number.isFinite(item.value));
const filterSelect = (label: string, value: string[], choices: string[] | undefined, change: (value: string[]) => void, allowUnassigned = true) => ( const filterSelect = (label: string, value: string[], choices: string[] | undefined, change: (value: string[]) => void, allowUnassigned = true) => (
<label className="query-field query-primary-field" key={label}> <div role="group" className="query-field query-primary-field" key={label}>
<span>{label}</span> <span>{label}</span>
<Select <Select
maxTagCount="responsive" maxTagCount="responsive"
@@ -630,7 +631,7 @@ export default function QueryPage({ page, onUnauthorized }: {
onChange={change} onChange={change}
aria-label={label} aria-label={label}
/> />
</label> </div>
); );
const activeDefectData = trendObject const activeDefectData = trendObject
@@ -706,7 +707,7 @@ export default function QueryPage({ page, onUnauthorized }: {
return ( return (
<div className="query-page"> <div className="query-page">
{optionsError && <Alert showIcon type="error" message="查询选项加载失败" description={optionsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => { setOptionsLoading(true); api.options().then(result => { setOptions(result); setOptionsError(''); }).catch(e => { if (!onUnauthorized(e)) setOptionsError(chooseError(e)); }).finally(() => setOptionsLoading(false)); }}>重试</Button>} />} {optionsError && <Alert showIcon type="error" message="查询选项加载失败" description={optionsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => { setOptionsLoading(true); api.options().then(result => { setOptions(result); setOptionsError(''); }).catch(e => { if (!onUnauthorized(e)) setOptionsError(chooseError(e)); }).finally(() => setOptionsLoading(false)); }}>重试</Button>} />}
<section className="query-toolbar panel" aria-label="查询条件"> <section className="query-toolbar panel" data-snapshot-module="filters" aria-label="查询条件">
<Segmented <Segmented
value={period} value={period}
options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]} options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]}
@@ -727,15 +728,15 @@ export default function QueryPage({ page, onUnauthorized }: {
}} }}
aria-label="统计周期" aria-label="统计周期"
/> />
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={value => { automaticPeriod.current = false; setYear(value); }} loading={optionsLoading} /></label> <div role="group" className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={value => { automaticPeriod.current = false; setYear(value); }} loading={optionsLoading} /></div>
{period === 'month' && <label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={value => { automaticPeriod.current = false; setMonth(value); }} /></label>} {period === 'month' && <div role="group" className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={value => { automaticPeriod.current = false; setMonth(value); }} /></div>}
{period === 'quarter' && <label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={value => { automaticPeriod.current = false; setQuarter(value); }} /></label>} {period === 'quarter' && <div role="group" className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={value => { automaticPeriod.current = false; setQuarter(value); }} /></div>}
{filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })} {filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })}
{filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)} {filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)}
{filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)} {filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)}
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} /> <ExtraQueryFilters key={queryRevision} releaseId={queryParams.releaseId} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
<div className="query-toolbar-tail"> <div className="query-toolbar-tail"><QuerySnapshotButton title={drilledProduct ? `${drilledProduct} · 产品质量查询` : page === 'overall' ? '总体合格率' : `${scopeName}质量查询`} queryKey={JSON.stringify([queryParams,trendMode,trendObject,trendStage,trendGranularity,rateBasis,fullFields,defectDisplay,queryRevision])} disabled={queryBusy || summaryBusy || !summaryMetricsData} onUnauthorized={onUnauthorized} />
<span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span> <span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button> <Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
</div> </div>
@@ -747,7 +748,7 @@ export default function QueryPage({ page, onUnauthorized }: {
{currentMetricsError && <Alert showIcon type="error" message={data ? "更新失败,当前显示上次结果" : "质量指标查询失败"} description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />} {currentMetricsError && <Alert showIcon type="error" message={data ? "更新失败,当前显示上次结果" : "质量指标查询失败"} description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />} {drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}> <section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} data-snapshot-module="metrics" aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div> <div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
<MetricCard primary label="综合合格率" value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} /> <MetricCard primary label="综合合格率" value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} /> <MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
@@ -832,7 +833,7 @@ export default function QueryPage({ page, onUnauthorized }: {
{defectsRefreshing && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>} {defectsRefreshing && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
</div> </div>
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />} {trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
<div className="defect-stage-grid" inert={!activeDefectData}> <div className="defect-stage-grid" data-snapshot-module="defects" inert={!activeDefectData}>
{(['black', 'bright'] as const).map(stage => { {(['black', 'bright'] as const).map(stage => {
const items = stage === 'black' ? blackDefectItems : brightDefectItems; const items = stage === 'black' ? blackDefectItems : brightDefectItems;
return <section className="defect-stage-column" key={stage} aria-label={`${stage === 'black' ? '黑片' : '亮片'}不良构成`}> return <section className="defect-stage-column" key={stage} aria-label={`${stage === 'black' ? '黑片' : '亮片'}不良构成`}>
@@ -921,7 +922,14 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
...(query.includeUnassigned ? { includeUnassigned: true } : {}), ...(query.includeUnassigned ? { includeUnassigned: true } : {}),
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]); }), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]);
const fineQueryKey = JSON.stringify(fineQuery); const fineQueryKey = JSON.stringify(fineQuery);
const visible = useResourceVisibility(container, active); const [snapshotRequested, setSnapshotRequested] = useState(false);
useEffect(() => {
const root = container.current?.closest('.query-page');
const request = (event: Event) => { if (active && (event as CustomEvent<{modules:string[]}>).detail?.modules.includes('pareto')) setSnapshotRequested(true); };
root?.addEventListener('quality:query-snapshot', request);
return () => root?.removeEventListener('quality:query-snapshot', request);
}, [active]);
const visible = useResourceVisibility(container, active) || snapshotRequested;
const showLoading = useDelayedIndicator(loading); const showLoading = useDelayedIndicator(loading);
useEffect(() => { useEffect(() => {
@@ -1043,7 +1051,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false }); instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false });
}, [items, totalWeight, themeRevision, active]); }, [items, totalWeight, themeRevision, active]);
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}> return <section className="defect-pareto-section" data-snapshot-module="pareto" data-snapshot-ready={error ? 'error' : responses && !loading && !pending ? 'true' : 'false'} aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{showLoading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div> <div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{showLoading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />} {error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />} {!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
@@ -1179,7 +1187,14 @@ function trendBarWidth(chartWidth: number, count: number): number {
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) { export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
const { active } = usePageCache(); const { active } = usePageCache();
const container = useRef<HTMLDivElement>(null); const container = useRef<HTMLDivElement>(null);
const visible = useResourceVisibility(container, active); const [snapshotRequested, setSnapshotRequested] = useState(false);
useEffect(() => {
const root = container.current?.closest('.query-page');
const request = (event: Event) => { if (active && (event as CustomEvent<{modules:string[]}>).detail?.modules.includes('trend')) setSnapshotRequested(true); };
root?.addEventListener('quality:query-snapshot', request);
return () => root?.removeEventListener('quality:query-snapshot', request);
}, [active]);
const visible = useResourceVisibility(container, active) || snapshotRequested;
const chart = useRef<ReturnType<typeof echarts.init> | null>(null); const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
const onMonthRef = useRef(onMonth); const onMonthRef = useRef(onMonth);
const rowsRef = useRef(rows); const rowsRef = useRef(rows);
@@ -1557,6 +1572,7 @@ export function RecordsDrawer({
<BusinessValue value={raw} /> <BusinessValue value={raw} />
</details>; </details>;
} }, } },
...(retainedResult?.rows.some(record=>Object.hasOwn(record,'salesOrderType'))?[{title:'销售订单类型',dataIndex:'salesOrderType',key:'salesOrderType',width:170,render:(value:string|null)=>value||'未匹配'}]:[]),
{ title: '工作表', dataIndex: 'sheet', key: 'sheet', width: 120 }, { title: '工作表', dataIndex: 'sheet', key: 'sheet', width: 120 },
{ title: '行号', dataIndex: 'rowNumber', key: 'rowNumber', align: 'right', width: 85 }, { title: '行号', dataIndex: 'rowNumber', key: 'rowNumber', align: 'right', width: 85 },
{ title: '月份', dataIndex: 'month', key: 'month', align: 'center', width: 100, render: value => { { title: '月份', dataIndex: 'month', key: 'month', align: 'center', width: 100, render: value => {
@@ -1574,14 +1590,14 @@ export function RecordsDrawer({
return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose> return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose>
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} disabled={fetching || !result || !!error} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div> <div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} disabled={fetching || !result || !!error} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
<div className="record-query-tools"> <div className="record-query-tools">
<label><span>字段检索</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></label> <div role="group"><span>字段检索</span><Select aria-label="字段检索" {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></div>
<Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} /> <Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
<label><span>显示列</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" placeholder="默认显示前 8 个字段" value={selectedColumns} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setSelectedColumns(value); setPage(1); }} /></label> <div role="group"><span>显示列</span><Select aria-label="显示列" {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" placeholder="默认显示前 8 个字段" value={selectedColumns} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setSelectedColumns(value); setPage(1); }} /></div>
<label><span>排序字段</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="默认顺序" value={sort} options={[ <div role="group"><span>排序字段</span><Select aria-label="排序字段" {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="默认顺序" value={sort} options={[
{ label: '月份', value: 'month' }, { label: '来源文件', value: 'sourceFile' }, { label: '工作表', value: 'sheet' }, { label: '行号', value: 'rowNumber' }, { label: '月份', value: 'month' }, { label: '来源文件', value: 'sourceFile' }, { label: '工作表', value: 'sheet' }, { label: '行号', value: 'rowNumber' },
{ label: '产业部', value: 'department' }, { label: '业务分组', value: 'group' }, { label: '项目组', value: 'projectGroup' }, { label: '产品', value: 'product' }, { label: '产业部', value: 'department' }, { label: '业务分组', value: 'group' }, { label: '项目组', value: 'projectGroup' }, { label: '产品', value: 'product' },
...(field ? [{ label: `原始字段:${field}`, value: 'rawField' }] : []), ...(field ? [{ label: `原始字段:${field}`, value: 'rawField' }] : []),
]} onChange={value => { setSort(value); setPage(1); }} /></label> ]} onChange={value => { setSort(value); setPage(1); }} /></div>
<Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" /> <Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
</div> </div>
{error && <Alert type="error" showIcon message={retainedResult ? "更新失败,当前显示上次结果" : "来源明细加载失败"} description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />} {error && <Alert type="error" showIcon message={retainedResult ? "更新失败,当前显示上次结果" : "来源明细加载失败"} description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
+4 -4
View File
@@ -16,7 +16,7 @@ export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGra
scopeName: string; stageSwitch?: ReactNode; children: ReactNode; scopeName: string; stageSwitch?: ReactNode; children: ReactNode;
}) { }) {
const periodName = granularity === 'month' ? '月度' : granularity === 'quarter' ? '季度' : '年度'; const periodName = granularity === 'month' ? '月度' : granularity === 'quarter' ? '季度' : '年度';
return <section className="panel section-panel trend-panel" ref={panelRef} id={id}> return <section className="panel section-panel trend-panel" data-snapshot-module="trend" ref={panelRef} id={id}>
<div className="section-heading-row trend-heading-row"> <div className="section-heading-row trend-heading-row">
<div className="section-heading"><h2>{periodName}变化趋势</h2></div> <div className="section-heading"><h2>{periodName}变化趋势</h2></div>
<Segmented value={mode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${periodName}数据`, value: 'data' }]} onChange={onMode} aria-label="趋势视图" /> <Segmented value={mode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${periodName}数据`, value: 'data' }]} onChange={onMode} aria-label="趋势视图" />
@@ -24,8 +24,8 @@ export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGra
<div className="trend-controls"> <div className="trend-controls">
{mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />} {mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />}
{mode === 'data' && <Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整指标', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="趋势字段显示" />} {mode === 'data' && <Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整指标', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="趋势字段显示" />}
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></label> <div role="group" className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></div>
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></label> <div role="group" className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></div>
{mode !== 'data' && stageSwitch} {mode !== 'data' && stageSwitch}
</div> </div>
{children} {children}
@@ -38,7 +38,7 @@ export function QueryTablePanel({ heading, busy, search, onSearchChange, onSearc
fullFields: boolean; onFullFields: (value: boolean) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void; fullFields: boolean; onFullFields: (value: boolean) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
returnControls?: ReactNode; exporting: boolean; exportDisabled: boolean; onExport: () => void; children: ReactNode; returnControls?: ReactNode; exporting: boolean; exportDisabled: boolean; onExport: () => void; children: ReactNode;
}) { }) {
return <section className="panel section-panel table-panel"> return <section className="panel section-panel table-panel" data-snapshot-module="table" aria-busy={busy}>
<div className="section-heading-row"> <div className="section-heading-row">
{heading} {heading}
<div className="table-tools"> <div className="table-tools">
+80
View File
@@ -0,0 +1,80 @@
import { useEffect, useRef, useState } from 'react';
import { Alert, App, Button, Checkbox, Modal, Space } from 'antd';
import { CameraOutlined, CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import { api } from './api';
import { usePageCache } from './pageCache';
import { captureQuerySnapshot, parseSnapshotModules, QUERY_SNAPSHOT_MODULES, snapshotFilename, snapshotTask, type QuerySnapshotModule } from './querySnapshot';
import './query-snapshot.css';
const STORAGE = 'quality-query-snapshot-modules-v1';
function savedModules() {
try { const value = localStorage.getItem(STORAGE); return parseSnapshotModules(value ? JSON.parse(value) : undefined); }
catch { return parseSnapshotModules(undefined); }
}
export function QuerySnapshotButton({ title, queryKey, disabled, onUnauthorized }: { title: string; queryKey: string; disabled?: boolean; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const { authRevision, dataRevision } = usePageCache();
const host = useRef<HTMLSpanElement>(null), alive = useRef(true), version = useRef(queryKey);
version.current = queryKey;
const [open, setOpen] = useState(false), [selected, setSelected] = useState<QuerySnapshotModule[]>(savedModules);
const [available, setAvailable] = useState<QuerySnapshotModule[]>([]), [busy, setBusy] = useState(false), [error, setError] = useState(''), [progress, setProgress] = useState('');
const job = useRef<AbortController | null>(null);
const cached = useRef<{ key: string; blob: Blob } | null>(null);
useEffect(() => { alive.current = true; setBusy(false); return () => { alive.current = false; job.current?.abort(); }; }, []);
const show = () => {
const root = host.current?.closest<HTMLElement>('.query-page'); if (!root) return;
const available = QUERY_SNAPSHOT_MODULES.filter(module => root.querySelector(`[data-snapshot-module="${module.key}"]`)).map(module => module.key);
cached.current = null;
setAvailable(available); setError(''); setOpen(true);
};
const chosen = selected.filter(key => available.includes(key));
const change = (values: QuerySnapshotModule[]) => { setSelected(values); try { localStorage.setItem(STORAGE, JSON.stringify(values)); } catch { /* In-memory selection remains usable. */ } };
const exportImage = async (copy: boolean) => {
if (!chosen.length || busy) return;
const root = host.current?.closest<HTMLElement>('.query-page'); if (!root) return;
const requestedVersion = version.current, controller = new AbortController();
job.current = controller;
const cancelled = () => controller.signal.aborted || !alive.current || version.current !== requestedVersion;
const cacheKey = JSON.stringify([requestedVersion, chosen, document.documentElement.dataset.workspaceTheme]);
setBusy(true); setError(''); setProgress('正在核对当前查询…');
const prepare = async () => {
const state = await api.workspaceState();
if ((authRevision && state.authRevision !== authRevision) || (dataRevision && state.dataRevision !== dataRevision)) throw new Error('页面数据或权限已更新,请刷新后生成快照');
if (cancelled()) throw new Error('已取消生成快照');
if (cached.current?.key === cacheKey) return cached.current.blob;
const blob = await captureQuerySnapshot(root, chosen, title, cancelled, controller.signal, text => { if (!cancelled()) setProgress(text); });
if (!cancelled()) cached.current = { key: cacheKey, blob };
return blob;
};
try {
if (copy) {
if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') throw new Error('此浏览器暂不支持复制图片,请使用下载图片');
const image = await snapshotTask(prepare(), controller.signal, 45000, '生成图片超时,请减少模块后重试');
if (cancelled()) return;
setProgress('图片已生成,正在写入剪贴板…');
const nativeWriting = navigator.clipboard.write([new ClipboardItem({ 'image/png': image })]);
await snapshotTask(nativeWriting, controller.signal, 8000, '剪贴板响应超时,图片已生成,可直接点击下载图片');
} else {
const blob = await snapshotTask(prepare(), controller.signal, 45000, '生成图片超时,请减少模块后重试'); if (cancelled()) return;
const url = URL.createObjectURL(blob), link = document.createElement('a');
link.href = url; link.download = snapshotFilename(title); document.body.append(link); link.click(); link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
if (!cancelled()) { message.success(copy ? '图片已复制到剪贴板' : '图片已开始下载'); setOpen(false); }
} catch (value) {
if (!controller.signal.aborted && alive.current && !onUnauthorized(value)) setError(value instanceof Error ? value.name === 'NotAllowedError' ? '浏览器未允许复制图片,请使用下载图片' : value.message : '图片生成失败,请重试');
} finally { controller.abort(); if (job.current === controller) { job.current = null; if (alive.current) setBusy(false); } }
};
return <span ref={host} className="query-snapshot-controls">
<Button icon={<CameraOutlined />} disabled={disabled} onClick={show}>页面快照</Button>
<Modal title="页面快照" open={open} width={470} onCancel={() => { job.current?.abort(); setOpen(false); }} closable mask={{ closable: !busy }}
footer={<Space>{busy && <Button onClick={() => { job.current?.abort(); setBusy(false); setProgress(''); }}>取消生成</Button>}<Button icon={<DownloadOutlined />} disabled={!chosen.length} onClick={() => void exportImage(false)} loading={busy}>下载图片</Button><Button type="primary" icon={<CopyOutlined />} disabled={!chosen.length} onClick={() => void exportImage(true)} loading={busy}>复制到剪贴板</Button></Space>}>
<Checkbox checked={chosen.length === available.length && available.length > 0} indeterminate={chosen.length > 0 && chosen.length < available.length} disabled={busy} onChange={event => change(event.target.checked ? available : [])}>全选</Checkbox>
<Checkbox.Group className="query-snapshot-modules" value={chosen} disabled={busy} options={QUERY_SNAPSHOT_MODULES.filter(module => available.includes(module.key)).map(module => ({ label: module.label, value: module.key }))} onChange={values => change(values as QuerySnapshotModule[])} />
<p className="query-snapshot-note">汇总表按当前分页和显示列生成。</p>
{busy && <p role="status">{progress}</p>}
{error && <Alert showIcon type="error" message={error} />}
</Modal>
</span>;
}
+3 -1
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { Alert, Button, Form, Input, Modal, Select } from 'antd'; import { Alert, Button, Form, Input, Modal, Select } from 'antd';
import { ArrowDownOutlined, ArrowUpOutlined, PlusOutlined } from '@ant-design/icons'; import { ArrowDownOutlined, ArrowUpOutlined, PlusOutlined } from '@ant-design/icons';
@@ -13,6 +14,7 @@ const missingLabels: Record<string, string> = { PROPAGATE:'任一输入缺失,
const outcomeLabels: Record<string, string> = { ONE:'取1', ZERO:'取0', NULL:'保留空白', ERROR:'停止并报错' }; const outcomeLabels: Record<string, string> = { ONE:'取1', ZERO:'取0', NULL:'保留空白', ERROR:'停止并报错' };
export function ResultFormulaModal({ result, existing, schema, availableTargets, onCancel, onApply }: Props) { export function ResultFormulaModal({ result, existing, schema, availableTargets, onCancel, onApply }: Props) {
const confirmDelete = useDeleteConfirmation();
const [draft, setDraft] = useState<ResultFormula>(() => structuredClone(result)); const [draft, setDraft] = useState<ResultFormula>(() => structuredClone(result));
const [error, setError] = useState(''); const [error, setError] = useState('');
const errorHost = useRef<HTMLDivElement>(null); const errorHost = useRef<HTMLDivElement>(null);
@@ -69,7 +71,7 @@ export function ResultFormulaModal({ result, existing, schema, availableTargets,
{branchIndexes.length === 0 && baseFormula} {branchIndexes.length === 0 && baseFormula}
{(branchIndexes.length > 0) && <p className="result-priority-hint">{draft.rules.some(rule=>rule.otherwiseFormula !== undefined) ? '已设置其他情况取值,最终取值以完整公式为准。' : '条件同时满足时,上方分支优先。'}</p>} {(branchIndexes.length > 0) && <p className="result-priority-hint">{draft.rules.some(rule=>rule.otherwiseFormula !== undefined) ? '已设置其他情况取值,最终取值以完整公式为准。' : '条件同时满足时,上方分支优先。'}</p>}
{branchIndexes.map((index, position) => { const rule=draft.rules[index], when=obj(rule.when); return <section className="result-condition-branch" key={index}> {branchIndexes.map((index, position) => { const rule=draft.rules[index], when=obj(rule.when); return <section className="result-condition-branch" key={index}>
<div className="result-branch-heading"><strong>条件 {position + 1}</strong><span className="task-actions"><Button size="small" type="text" aria-label={`条件${position+1}提高优先级`} icon={<ArrowUpOutlined/>} disabled={position===0} onClick={()=>moveBranch(index,-1)}/><Button size="small" type="text" aria-label={`条件${position+1}降低优先级`} icon={<ArrowDownOutlined/>} disabled={position===branchIndexes.length-1} onClick={()=>moveBranch(index,1)}/><Button size="small" type="link" danger onClick={()=>remove(index)}>移除</Button></span></div> <div className="result-branch-heading"><strong>条件 {position + 1}</strong><span className="task-actions"><Button size="small" type="text" aria-label={`条件${position+1}提高优先级`} icon={<ArrowUpOutlined/>} disabled={position===0} onClick={()=>moveBranch(index,-1)}/><Button size="small" type="text" aria-label={`条件${position+1}降低优先级`} icon={<ArrowDownOutlined/>} disabled={position===branchIndexes.length-1} onClick={()=>moveBranch(index,1)}/><Button size="small" type="link" danger onClick={()=>confirmDelete({title:`移除条件 ${position + 1}?`,description:"将从当前结果公式中移除此条件分支,点击“应用修改”后更新编辑内容,保存并更新报表后生效。",confirmText:"确认移除",onConfirm:()=>remove(index)})}>移除</Button></span></div>
<div className="result-condition-fields"> <div className="result-condition-fields">
<Form.Item label="条件字段" htmlFor={`result-field-${index}`}><Select id={`result-field-${index}`} {...readableSelectPopup} value={String(when.field || '')} options={Object.entries(fields).map(([value,name])=>({value,label:String(name)}))} onChange={field=>condition(index,{field})}/></Form.Item> <Form.Item label="条件字段" htmlFor={`result-field-${index}`}><Select id={`result-field-${index}`} {...readableSelectPopup} value={String(when.field || '')} options={Object.entries(fields).map(([value,name])=>({value,label:String(name)}))} onChange={field=>condition(index,{field})}/></Form.Item>
<Form.Item label="判断方式" htmlFor={`result-operator-${index}`}><Select id={`result-operator-${index}`} value={String(when.operator || '')} options={strings(schema.conditionOperators).map(value=>({value,label:conditionOperators[value]||value}))} onChange={operator=>condition(index,{operator})}/></Form.Item> <Form.Item label="判断方式" htmlFor={`result-operator-${index}`}><Select id={`result-operator-${index}`} value={String(when.operator || '')} options={strings(schema.conditionOperators).map(value=>({value,label:conditionOperators[value]||value}))} onChange={operator=>condition(index,{operator})}/></Form.Item>
+4 -2
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Alert, Button, Checkbox, Collapse, Dropdown, Form, Input, Modal, Select, Tabs } from 'antd'; import { Alert, Button, Checkbox, Collapse, Dropdown, Form, Input, Modal, Select, Tabs } from 'antd';
import { MoreOutlined, PlusOutlined } from '@ant-design/icons'; import { MoreOutlined, PlusOutlined } from '@ant-design/icons';
@@ -16,6 +17,7 @@ const nullLabels: Record<string, string> = { PROPAGATE:'任一输入缺失,运
const resultLabels = (rate: boolean): Record<string, string> => ({ ONE: rate ? '按100%处理' : '取1', ZERO: rate ? '按0%处理' : '取0', NULL:'保留空白', ERROR:'停止并报错' }); const resultLabels = (rate: boolean): Record<string, string> => ({ ONE: rate ? '按100%处理' : '取1', ZERO: rate ? '按0%处理' : '取0', NULL:'保留空白', ERROR:'停止并报错' });
export function RuleSettingsEditor({ value, onChange, schema, schemaError, showWorkbookActions = true, focusMetric, readOnly = false }: Props) { export function RuleSettingsEditor({ value, onChange, schema, schemaError, showWorkbookActions = true, focusMetric, readOnly = false }: Props) {
const confirmDelete = useDeleteConfirmation();
const [tab, setTab] = useState('black'); const [tab, setTab] = useState('black');
const [sourceEdit, setSourceEdit] = useState<{ stage: string; alias: string; header: string } | null>(null); const [sourceEdit, setSourceEdit] = useState<{ stage: string; alias: string; header: string } | null>(null);
const [sourceForm] = Form.useForm<{ header: string }>(); const [sourceForm] = Form.useForm<{ header: string }>();
@@ -67,10 +69,10 @@ export function RuleSettingsEditor({ value, onChange, schema, schemaError, showW
const next = planResultMove(value, result.stage, result.target, direction, schema); const next = planResultMove(value, result.stage, result.target, direction, schema);
if (next.definition) { onChange(next.definition); setOrderError(''); } else setOrderError(next.reason || '该调整会破坏计算依赖'); if (next.definition) { onChange(next.definition); setOrderError(''); } else setOrderError(next.reason || '该调整会破坏计算依赖');
}; };
const remove = (result: ResultFormula) => { const remove = (result: ResultFormula) => confirmDelete({ title:`移除“${label(result.target)}”的完整公式?`, description:`将移除此结果的全部取值及 ${result.rules.filter(rule=>rule.when).length} 个条件分支,保存并更新报表后生效。`, confirmText:"确认移除", onConfirm:() => {
const next = replaceResultFormula(value, result, []), issue = newResultIssue(value, next, schema); const next = replaceResultFormula(value, result, []), issue = newResultIssue(value, next, schema);
if (issue) setOrderError(issue); else { onChange(next); setOrderError(''); } if (issue) setOrderError(issue); else { onChange(next); setOrderError(''); }
}; }});
const rowColumns = [ const rowColumns = [
{ title:'执行顺序', key:'sequence', width:90, render:(_: unknown, _row: ResultFormula, position: number) => position + 1 }, { title:'执行顺序', key:'sequence', width:90, render:(_: unknown, _row: ResultFormula, position: number) => position + 1 },
{ title:'计算结果', dataIndex:'target', width:200, render:label }, { title:'计算结果', dataIndex:'target', width:200, render:label },
+45
View File
@@ -0,0 +1,45 @@
import { useEffect,useRef,useState } from 'react';
import { Alert,App,Button,Modal,Select,Space,Table } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { api } from './api';
import type { SalesOrderTypePreview,SalesOrderTypeStatus,SalesOrderTypeVersion } from './salesOrderTypes';
export function SalesOrderTypeSettings({onUnauthorized}:{onUnauthorized:(error:unknown)=>boolean}) {
const {message,modal}=App.useApp();
const [status,setStatus]=useState<SalesOrderTypeStatus>();
const [error,setError]=useState('');const [busy,setBusy]=useState(false);
const [open,setOpen]=useState(false);const [history,setHistory]=useState(false);
const [file,setFile]=useState<File>();const [mode,setMode]=useState<'MERGE'|'REPLACE'>('MERGE');
const [preview,setPreview]=useState<SalesOrderTypePreview>();
const input=useRef<HTMLInputElement>(null);const generation=useRef(0);
const failure=(e:unknown)=>{if(!onUnauthorized(e))setError(e instanceof Error?e.message:'操作失败');};
const load=()=>api.salesOrderTypeStatus().then(setStatus);
useEffect(()=>{let alive=true;api.salesOrderTypeStatus().then(value=>{if(alive)setStatus(value);}).catch(e=>{if(alive&&!onUnauthorized(e))setError(e instanceof Error?e.message:'对应表读取失败');});return()=>{alive=false;generation.current++;};},[onUnauthorized]);
const current=status?.versions.find(version=>version.id===status.versionId);
const inspect=async()=>{
if(!file)return;const revision=++generation.current;setBusy(true);setError('');setPreview(undefined);
try{const result=await api.salesOrderTypePreview(file,mode);if(revision===generation.current)setPreview(result);}
catch(e){if(revision===generation.current)failure(e);}finally{if(revision===generation.current)setBusy(false);}
};
const commit=async()=>{
if(!file||!preview)return;setBusy(true);setError('');
try{await api.importSalesOrderTypes(file,mode,preview.expectedVersion,preview.sha256);await load();setOpen(false);setPreview(undefined);message.success('销售订单类型对应表已更新');}
catch(e){failure(e);setPreview(undefined);}finally{setBusy(false);}
};
const restore=(version:SalesOrderTypeVersion)=>modal.confirm({title:'恢复此销售订单对应表?',content:'历史质量数据的后续查询将采用此版本的对应关系。',okText:'恢复',onOk:async()=>{setBusy(true);try{await api.activateSalesOrderTypes(version.id,status?.versionId||'');await load();setHistory(false);message.success('对应表已恢复');}catch(e){failure(e);throw e;}finally{setBusy(false);}}});
return <section className="sales-order-type-settings" style={{marginTop:24}}>
<div className="section-heading-row"><strong>销售订单类型对应</strong><Space><Button size="small" disabled={busy||!status?.versions.length} onClick={()=>setHistory(true)}>历史版本</Button><Button size="small" icon={<UploadOutlined/>} disabled={busy} onClick={()=>{setFile(undefined);setPreview(undefined);setError('');setOpen(true);}}>导入对应表</Button></Space></div>
<p>{current?`${current.rowCount.toLocaleString('zh-CN')} 个订单 · ${current.sourceFile}`:'尚未导入销售订单类型对应表'}</p>
{error&&!open&&<Alert showIcon type="error" message={error}/>}
<Modal open={open} title="导入销售订单类型对应表" onCancel={()=>{if(!busy){generation.current++;setOpen(false);}}} maskClosable={!busy} closable={!busy} footer={<Space><Button disabled={busy} onClick={()=>setOpen(false)}>取消</Button>{preview?<Button type="primary" loading={busy} onClick={()=>void commit()}>确认导入</Button>:<Button type="primary" loading={busy} disabled={!file} onClick={()=>void inspect()}>预览</Button>}</Space>}>
<Space direction="vertical" style={{width:'100%'}}>
{error&&<Alert showIcon type="error" message={error}/>}
<Select aria-label="销售订单对应表导入方式" value={mode} disabled={busy} style={{width:'100%'}} options={[{label:'增量更新',value:'MERGE'},{label:'整表替换',value:'REPLACE'}]} onChange={value=>{setMode(value);setPreview(undefined);}}/>
<input ref={input} type="file" accept=".xlsx,.xls" aria-label="销售订单对应表文件" disabled={busy} onChange={event=>{setFile(event.target.files?.[0]);setPreview(undefined);}}/>
{mode==='REPLACE'&&<Alert type="warning" message="整表替换会移除未在本次文件中出现的订单对应关系。"/>}
{preview&&<><p>导入 {preview.summary.imported.toLocaleString('zh-CN')} 个订单,生效后共 {preview.summary.total.toLocaleString('zh-CN')} 个。</p><Space wrap><span>新增 {preview.summary.added}</span><span>变更 {preview.summary.updated}</span><span>不变 {preview.summary.unchanged}</span><span>移除 {preview.summary.removed}</span></Space></>}
</Space>
</Modal>
<Modal open={history} title="销售订单对应表历史版本" footer={null} onCancel={()=>setHistory(false)} width={760}><Table size="small" rowKey="id" dataSource={status?.versions||[]} pagination={{pageSize:6}} columns={[{title:'来源文件',dataIndex:'sourceFile'},{title:'订单数',dataIndex:'rowCount',render:(n:number)=>n.toLocaleString('zh-CN')},{title:'导入时间',dataIndex:'createdAt',render:(value:string)=>new Date(value).toLocaleString('zh-CN')},{title:'操作',render:(_,version:SalesOrderTypeVersion)=>version.id===status?.versionId?'当前版本':<Button size="small" disabled={busy} onClick={()=>restore(version)}>恢复</Button>}]}/></Modal>
</section>;
}
+23 -16
View File
@@ -1,3 +1,4 @@
import { QuerySnapshotButton } from './QuerySnapshotButton';
import { loadedQueryScope, queryForLocation } from './queryLoadingScope'; import { loadedQueryScope, queryForLocation } from './queryLoadingScope';
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion'; import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
import { queryScrapWeight } from './queryMetricValues'; import { queryScrapWeight } from './queryMetricValues';
@@ -7,6 +8,8 @@ import { ArrowLeftOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import { api, decodeQueryValueList, encodeQueryValueList } from './api'; import { api, decodeQueryValueList, encodeQueryValueList } from './api';
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, TrendTable, fullYearTrend, queryFromLocation } from './QueryPage'; import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, TrendTable, fullYearTrend, queryFromLocation } from './QueryPage';
import { StageSourceFilters } from './StageSourceFilters'; import { StageSourceFilters } from './StageSourceFilters';
import { SalesOrderTypeSelect } from './ExtraQueryFilters';
import { salesOrderTypeSelection } from './salesOrderTypes';
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery'; import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
import { usePageCache } from './pageCache'; import { usePageCache } from './pageCache';
import { useDelayedIndicator } from './useDelayedBusy'; import { useDelayedIndicator } from './useDelayedBusy';
@@ -14,7 +17,7 @@ import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } fro
import { readableSelectPopup } from './readableSelectPopup'; import { readableSelectPopup } from './readableSelectPopup';
import { readableMetricFormula } from './publicDataDisplay'; import { readableMetricFormula } from './publicDataDisplay';
import { defaultFullMetricFields } from './metricColumnPlan'; import { defaultFullMetricFields } from './metricColumnPlan';
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage, TrendResponse } from './types'; import type { FilterField, MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage, TrendResponse } from './types';
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels'; import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection'; import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
import './stage-product.css'; import './stage-product.css';
@@ -30,6 +33,8 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup)); const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const [appliedSearch,setAppliedSearch]=useState(initial.productSearch||'');const includeUnassigned=true; const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const [appliedSearch,setAppliedSearch]=useState(initial.productSearch||'');const includeUnassigned=true;
const [moreFiltersOpen,setMoreFiltersOpen]=useState(false); const [moreFiltersOpen,setMoreFiltersOpen]=useState(false);
const [extraFilters,setExtraFilters]=useState<Record<string,string[]>>(initial.extraFilters||{});
const [extraFields,setExtraFields]=useState<FilterField[]>([]);
const [options,setOptions]=useState<OptionsResponse|null>(null);const [catalog,setCatalog]=useState<{releaseId:string;sourceFields:SourceColumnField[]}|null>(null);const [supportError,setSupportError]=useState('');const [supportLoading,setSupportLoading]=useState(true); const [options,setOptions]=useState<OptionsResponse|null>(null);const [catalog,setCatalog]=useState<{releaseId:string;sourceFields:SourceColumnField[]}|null>(null);const [supportError,setSupportError]=useState('');const [supportLoading,setSupportLoading]=useState(true);
const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null); const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight'); const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight');
@@ -44,7 +49,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const loadSupport=useCallback(async()=>{ const loadSupport=useCallback(async()=>{
const generation=++supportGeneration.current;supportController.current?.abort();const controller=new AbortController();supportController.current=controller; const generation=++supportGeneration.current;supportController.current?.abort();const controller=new AbortController();supportController.current=controller;
setSupportLoading(true);setSupportError(''); setSupportLoading(true);setSupportError('');
try{const [choices,source]=await Promise.all([api.options(controller.signal),api.sourceColumnCatalog(initial.releaseId||currentReleaseId||undefined,controller.signal)]);if(generation!==supportGeneration.current)return;if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);} try{const [choices,source,filterFields]=await Promise.all([api.options(controller.signal),api.sourceColumnCatalog(initial.releaseId||currentReleaseId||undefined,controller.signal),api.filterFields(false,controller.signal)]);if(generation!==supportGeneration.current)return;if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);setExtraFields(filterFields.filter(field=>field.key==='salesOrderType'));}
catch(error){if(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');} catch(error){if(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
finally{if(generation===supportGeneration.current)setSupportLoading(false);} finally{if(generation===supportGeneration.current)setSupportLoading(false);}
},[onUnauthorized,initial.releaseId,currentReleaseId]); },[onUnauthorized,initial.releaseId,currentReleaseId]);
@@ -52,8 +57,8 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]); const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]); const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]);
const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]); const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]);
useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters]); useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters,extraFilters]);
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:initial.releaseId||currentReleaseId||catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters,initial.releaseId,currentReleaseId]); const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,extraFilters,view:'product',trendGranularity:'month',releaseId:initial.releaseId||currentReleaseId||catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters,extraFilters,initial.releaseId,currentReleaseId]);
// Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit. // Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit.
useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]); useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]);
const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:''; const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:'';
@@ -78,15 +83,16 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const submit=()=>{automaticPeriod.current=false;setAppliedSearch(search.trim());setDrilledProduct('');setRevision(v=>v+1);}; const submit=()=>{automaticPeriod.current=false;setAppliedSearch(search.trim());setDrilledProduct('');setRevision(v=>v+1);};
const setTrendObject=(value?:string)=>{const selected=value||'';setDrilledProduct('');setSearch(selected);setAppliedSearch(selected);}; const setTrendObject=(value?:string)=>{const selected=value||'';setDrilledProduct('');setSearch(selected);setAppliedSearch(selected);};
const returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);setTrendMode('production');}; const returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);setTrendMode('production');};
const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);}; const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setExtraFilters({});setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);};
const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||'')); const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||''));
const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[]; const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[];
const trendOptions=useMemo(()=>[...products.map(value=>({label:value,value})),...(drilledProduct==='__UNASSIGNED__'?[{label:'未分类',value:drilledProduct}]:[])],[products,drilledProduct]); const trendOptions=useMemo(()=>[...products.map(value=>({label:value,value})),...(drilledProduct==='__UNASSIGNED__'?[{label:'未分类',value:drilledProduct}]:[])],[products,drilledProduct]);
const trendObject=drilledProduct||exactProductSearch; const trendObject=drilledProduct||exactProductSearch;
const drilledLabel=drilledProduct==='__UNASSIGNED__'?'未分类':drilledProduct; const drilledLabel=drilledProduct==='__UNASSIGNED__'?'未分类':drilledProduct;
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void,extra=false)=><label className={`query-field ${extra?'query-extra-field':'query-primary-field'}`}><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>; const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void,extra=false)=><div role="group" className={`query-field ${extra?'query-extra-field':'query-primary-field'}`}><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></div>;
const moreFilterCount=(projectGroup.length?1:0)+sourceFilters.length; const moreFilterCount=(projectGroup.length?1:0)+sourceFilters.length+Object.values(extraFilters).filter(values=>values.length).length;
const moreFilterSummary=[projectGroup.length?`项目组:${projectGroup.map(v=>v==='__UNASSIGNED__'?'未分类':v).join('、')}`:'',...sourceFilters.map(rule=>fields.find(field=>field.key===rule.field)?.label||rule.field)].filter(Boolean).join(';'); const salesSelection=salesOrderTypeSelection(extraFilters);
const moreFilterSummary=[salesSelection.values.length?`销售订单类型${salesSelection.exclude?'(排除)':''}:`+salesSelection.values.map(value=>value==='__EMPTY__'?'未匹配':value).join('、'):'',projectGroup.length?`项目组:${projectGroup.map(v=>v==='__UNASSIGNED__'?'未分类':v).join('、')}`:'',...sourceFilters.map(rule=>fields.find(field=>field.key===rule.field)?.label||rule.field)].filter(Boolean).join(';');
const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null); const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]); const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey); const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey);
@@ -99,26 +105,27 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap'; const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
return <div className="query-page stage-product-page"> return <div className="query-page stage-product-page">
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>} {supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}> <section className="query-toolbar panel" data-snapshot-module="filters" aria-label={`${label}汇总条件`}>
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/> <Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label> <div role="group" className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></div>
{period==='month'&&<label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${String(i+1).padStart(2,'0')}月`,value:i+1}))}/></label>} {period==='month'&&<div role="group" className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${String(i+1).padStart(2,'0')}月`,value:i+1}))}/></div>}
{period==='quarter'&&<label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>} {period==='quarter'&&<div role="group" className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></div>}
{select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})} {select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})}
{select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})} {select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})}
{select('产品',product,products,setProduct)} {select('产品',product,products,setProduct)}
<div className="query-more-toggle" title={moreFilterSummary||undefined}> <div className="query-more-toggle" title={moreFilterSummary||undefined}>
<Button type="text" size="small" icon={moreFiltersOpen?<UpOutlined/>:<DownOutlined/>} aria-expanded={moreFiltersOpen} aria-controls={`stage-more-filters-${stage}`} onClick={()=>setMoreFiltersOpen(open=>!open)}>更多筛选{moreFilterCount?`(已选 ${moreFilterCount} 项)`:''}</Button> <Button type="text" size="small" icon={moreFiltersOpen?<UpOutlined/>:<DownOutlined/>} aria-expanded={moreFiltersOpen} aria-controls={`stage-more-filters-${stage}`} onClick={()=>setMoreFiltersOpen(open=>!open)}>更多筛选{moreFilterCount?`(已选 ${moreFilterCount} 项)`:''}</Button>
{moreFilterCount>0&&<Button type="link" size="small" onClick={()=>{setProjectGroup([]);setSourceFilters([]);}}>清除</Button>} {moreFilterCount>0&&<Button type="link" size="small" onClick={()=>{setProjectGroup([]);setSourceFilters([]);setExtraFilters({});}}>清除</Button>}
</div> </div>
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy?'busy':queryFailed?'failed':''}`}><i/>{queryBusy?'正在查询':queryFailed?'查询失败':'查询完成'}</span><Button type="default" onClick={reset}>重置</Button></div> <div className="query-toolbar-tail"><QuerySnapshotButton title={`${label}汇总`} queryKey={JSON.stringify([draft,trendMode,trendObject,trendGranularity,rateBasis,fullFields,defectDisplay,revision])} disabled={queryBusy || !current} onUnauthorized={onUnauthorized} /><span className={`query-status ${queryBusy?'busy':queryFailed?'failed':''}`}><i/>{queryBusy?'正在查询':queryFailed?'查询失败':'查询完成'}</span><Button type="default" onClick={reset}>重置</Button></div>
{moreFiltersOpen&&<div className="query-extra-fields" id={`stage-more-filters-${stage}`}> {moreFiltersOpen&&<div className="query-extra-fields" id={`stage-more-filters-${stage}`}>
{extraFields.map(field=><SalesOrderTypeSelect key={field.key} field={field} filters={extraFilters} releaseId={draft.releaseId} stage={stage} onUnauthorized={onUnauthorized} onChange={setExtraFilters}/>)}
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup,true)} {options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup,true)}
{catalog&&<StageSourceFilters stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>} {catalog&&<StageSourceFilters stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
</div>} </div>}
</section> </section>
{error&&<Alert showIcon type="error" message={response?"更新失败,当前显示上次结果":"查询失败"} description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>} {error&&<Alert showIcon type="error" message={response?"更新失败,当前显示上次结果":"查询失败"} description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
<section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}> <section className="metric-strip stage-metric-strip" data-snapshot-module="metrics" aria-label="质量指标" aria-busy={loading} inert={!current}>
{stage==='bright'&&<div className="rate-basis-control"><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>} {stage==='bright'&&<div className="rate-basis-control"><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>}
<MetricCard primary stage={stage} label={`${label}合格率`} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/> <MetricCard primary stage={stage} label={`${label}合格率`} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/>
<MetricCard label="合格重量" value={`${weight(summary?.qualifiedWeight)} kg`} onClick={()=>openDetail(null,stage)}/> <MetricCard label="合格重量" value={`${weight(summary?.qualifiedWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
@@ -155,7 +162,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
<section className="panel section-panel defects-panel" aria-busy={loading||!current}> <section className="panel section-panel defects-panel" aria-busy={loading||!current}>
<div className="section-heading-row"><SectionHeading title="不良具体构成"/></div> <div className="section-heading-row"><SectionHeading title="不良具体构成"/></div>
<div className="stage-defect-comparison"> <div className="stage-defect-comparison">
<section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}> <section className="defect-stage-column" data-snapshot-module="defects" inert={!current||loading} aria-label={`${label}不良构成`}>
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3> <h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
{displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>} {displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
</section> </section>
+2 -2
View File
@@ -16,8 +16,8 @@ function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:S
if(!active)return; if(!active)return;
const generation=++current.current,controller=new AbortController();setBusy(true);setError('');setChoices([]); const generation=++current.current,controller=new AbortController();setBusy(true);setError('');setChoices([]);
const timer=window.setTimeout(()=>{ const timer=window.setTimeout(()=>{
const {year,month,quarter,department,group,product,projectGroup,includeUnassigned,columnFilters,releaseId}=query; const {year,month,quarter,department,group,product,projectGroup,includeUnassigned,columnFilters,releaseId,extraFilters}=query;
void api.sourceColumnValues({releaseId,period:{year,...(month?{month}:{}),...(quarter?{quarter}:{})},filters:{...(department?{department}:{}),...(group?{group}:{}),...(product?{product}:{}),...(projectGroup?{projectGroup}:{}),includeUnassigned:!!includeUnassigned,columnFilters:(columnFilters||[]).filter(rule=>rule.field!==field.key)},field:field.key,stages:[stage],search,limit:50,offset:0},controller.signal) void api.sourceColumnValues({releaseId,period:{year,...(month?{month}:{}),...(quarter?{quarter}:{})},filters:{...(department?{department}:{}),...(group?{group}:{}),...(product?{product}:{}),...(projectGroup?{projectGroup}:{}),...(extraFilters?{extraFilters}:{}),includeUnassigned:!!includeUnassigned,columnFilters:(columnFilters||[]).filter(rule=>rule.field!==field.key)},field:field.key,stages:[stage],search,limit:50,offset:0},controller.signal)
.then(result=>{if(current.current!==generation)return;setChoices(result.values.filter((v):v is string=>typeof v==='string'));setMore(result.hasMore===true||(result.total??0)>50);}) .then(result=>{if(current.current!==generation)return;setChoices(result.values.filter((v):v is string=>typeof v==='string'));setMore(result.hasMore===true||(result.total??0)>50);})
.catch(failure=>{if(controller.signal.aborted||current.current!==generation)return;if(!onUnauthorized(failure))setError(failure instanceof Error?failure.message:'选项读取失败');}) .catch(failure=>{if(controller.signal.aborted||current.current!==generation)return;if(!onUnauthorized(failure))setError(failure instanceof Error?failure.message:'选项读取失败');})
.finally(()=>{if(current.current===generation)setBusy(false);}); .finally(()=>{if(current.current===generation)setBusy(false);});
+8 -4
View File
@@ -1,3 +1,4 @@
import { useDeleteConfirmation } from './useDeleteConfirmation';
import { newMasterDataCode } from './masterDataIdentity'; import { newMasterDataCode } from './masterDataIdentity';
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions'; import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
import { matchRuleConflicts } from './classificationMaintenance'; import { matchRuleConflicts } from './classificationMaintenance';
@@ -145,6 +146,7 @@ function BatchImport({ open, title, columns, existing, writeTarget = '草稿', o
} }
export function MappingDefinitionEditor({ value, onChange, simplified = false, readOnly = false }: DefinitionProps & { simplified?: boolean; readOnly?: boolean }) { export function MappingDefinitionEditor({ value, onChange, simplified = false, readOnly = false }: DefinitionProps & { simplified?: boolean; readOnly?: boolean }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const { message } = App.useApp();
const [kind, setKind] = useState<MappingKind>('categoryLookup'); const [search, setSearch] = useState(''); const [status, setStatus] = useState('all'); const [kind, setKind] = useState<MappingKind>('categoryLookup'); const [search, setSearch] = useState(''); const [status, setStatus] = useState('all');
const [editing, setEditing] = useState<MappingRow | null>(null); const [newRow, setNewRow] = useState(false); const [importing, setImporting] = useState(false); const [editError, setEditError] = useState(''); const [editing, setEditing] = useState<MappingRow | null>(null); const [newRow, setNewRow] = useState(false); const [importing, setImporting] = useState(false); const [editError, setEditError] = useState('');
@@ -158,7 +160,7 @@ export function MappingDefinitionEditor({ value, onChange, simplified = false, r
...(info.secondary ? [{ title: info.secondary, dataIndex: 'secondary', key: 'secondary', width: 180 }] : []), ...(info.secondary ? [{ title: info.secondary, dataIndex: 'secondary', key: 'secondary', width: 180 }] : []),
{ title: info.target, dataIndex: 'target', key: 'target', width: 220, render: target => target === null ? <span className="structured-config-muted">未配置</span> : target }, { title: info.target, dataIndex: 'target', key: 'target', width: 220, render: target => target === null ? <span className="structured-config-muted">未配置</span> : target },
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> }, { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> },
...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MappingRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMappingRows(value, kind, rows.map(item => item.key === row.key ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => onChange(setMappingRows(value, kind, rows.filter(item => item.key !== row.key)))}>删除</Button></span> }] : []), ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MappingRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMappingRows(value, kind, rows.map(item => item.key === row.key ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => confirmDelete({title:`删除这条${info.label}?`,description:`来源“${row.source}”对应“${row.target}”。删除后需保存并更新报表才生效。`,onConfirm:()=>onChange(setMappingRows(value, kind, rows.filter(item => item.key !== row.key)))})}>删除</Button></span> }] : []),
]; ];
const headers = [info.source, ...(info.secondary ? [info.secondary] : []), info.target, '启用']; const headers = [info.source, ...(info.secondary ? [info.secondary] : []), info.target, '启用'];
return <div className="structured-config-editor"> return <div className="structured-config-editor">
@@ -209,6 +211,7 @@ const metadataOptions = (value: unknown, fallback: MatchOption[]): MatchOption[]
: fallback; : fallback;
export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly = false }: DefinitionProps & { metadata?: MatchMetadata | null; readOnly?: boolean }) { export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly = false }: DefinitionProps & { metadata?: MatchMetadata | null; readOnly?: boolean }) {
const confirmDelete = useDeleteConfirmation();
const [editing, setEditing] = useState<MatchRule | null>(null); const [editing, setEditing] = useState<MatchRule | null>(null);
const [search,setSearch]=useState(''); const [search,setSearch]=useState('');
const [error, setError] = useState(''); const [error, setError] = useState('');
@@ -249,7 +252,7 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
{ title: '匹配条件', width: 410, render: (_, row) => <span className="structured-match-readable">{readableRule(row)}</span> }, { title: '匹配条件', width: 410, render: (_, row) => <span className="structured-match-readable">{readableRule(row)}</span> },
{ title: '阶段', dataIndex: 'stage', width: 104, render: stage => labelFor(stages, String(stage)) }, { title: '阶段', dataIndex: 'stage', width: 104, render: stage => labelFor(stages, String(stage)) },
{ title: '状态', dataIndex: 'enabled', width: 84, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> }, { title: '状态', dataIndex: 'enabled', width: 84, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> },
...(!readOnly ? [{ title: '操作', width: 150, render: (_: unknown, row: MatchRule) => <span className="task-actions"><Button type="link" onClick={() => open(row)}>编辑</Button><Button type="link" onClick={() => commit(rules.map(item => item.id === row.id ? { ...item, enabled: !item.enabled } : item))}>{row.enabled ? '停用' : '启用'}</Button><Button type="link" danger onClick={() => commit(rules.filter(item => item.id !== row.id))}>删除</Button></span> }] : []), ...(!readOnly ? [{ title: '操作', width: 150, render: (_: unknown, row: MatchRule) => <span className="task-actions"><Button type="link" onClick={() => open(row)}>编辑</Button><Button type="link" onClick={() => commit(rules.map(item => item.id === row.id ? { ...item, enabled: !item.enabled } : item))}>{row.enabled ? '停用' : '启用'}</Button><Button type="link" danger onClick={() => confirmDelete({title:`删除匹配规则“${row.name || "未命名规则"}”?`,description:"将移除这条规则及其匹配条件,保存并更新报表后生效。",onConfirm:()=>commit(rules.filter(item => item.id !== row.id))})}>删除</Button></span> }] : []),
]} locale={{ emptyText: '还没有条件匹配规则' }} /> ]} locale={{ emptyText: '还没有条件匹配规则' }} />
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={editing?.id ? '编辑条件匹配规则' : '新增条件匹配规则'} width={860} okText="保存规则" onCancel={() => setEditing(null)} onOk={() => { <Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={editing?.id ? '编辑条件匹配规则' : '新增条件匹配规则'} width={860} okText="保存规则" onCancel={() => setEditing(null)} onOk={() => {
if (!editing) return; if (!editing) return;
@@ -267,7 +270,7 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
{ title: '字段', width: 250, render: (_, condition, index) => <AutoComplete value={condition.field} options={fields} style={{ width: '100%' }} filterOption={(input, option) => String(option?.label || '').toLowerCase().includes(input.toLowerCase())} placeholder="选择或输入字段" onChange={field => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, field } : row) })} /> }, { title: '字段', width: 250, render: (_, condition, index) => <AutoComplete value={condition.field} options={fields} style={{ width: '100%' }} filterOption={(input, option) => String(option?.label || '').toLowerCase().includes(input.toLowerCase())} placeholder="选择或输入字段" onChange={field => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, field } : row) })} /> },
{ title: '判断方式', width: 180, render: (_, condition, index) => <Select {...readableSelectPopup} value={condition.operator} options={operators} style={{ width: '100%' }} onChange={operator => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, operator, ...(operatorDescription(operator) ? {} : { value: undefined }) } : row) })} /> }, { title: '判断方式', width: 180, render: (_, condition, index) => <Select {...readableSelectPopup} value={condition.operator} options={operators} style={{ width: '100%' }} onChange={operator => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, operator, ...(operatorDescription(operator) ? {} : { value: undefined }) } : row) })} /> },
{ title: '判断值', render: (_, condition, index) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? <span className="structured-config-muted">无需填写</span> : <Input value={condition.value} onChange={event => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, value: event.target.value } : row) })} /> }, { title: '判断值', render: (_, condition, index) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? <span className="structured-config-muted">无需填写</span> : <Input value={condition.value} onChange={event => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, value: event.target.value } : row) })} /> },
{ title: '', width: 82, render: (_, __, index) => <Button type="link" danger disabled={editing.conditions.length <= 1} onClick={() => setEditing({ ...editing, conditions: editing.conditions.filter((__, rowIndex) => rowIndex !== index) })}>移除</Button> }, { title: '', width: 82, render: (_, __, index) => <Button type="link" danger disabled={editing.conditions.length <= 1} onClick={() => confirmDelete({title:`移除条件 ${index + 1}?`,description:"将从当前匹配规则中移除此条件,保存规则后生效。",confirmText:"确认移除",onConfirm:()=>setEditing({ ...editing, conditions: editing.conditions.filter((__, rowIndex) => rowIndex !== index) })})}>移除</Button> },
]} /> ]} />
<Form.Item label="处理范围"><Switch checked={editing.onlyUnclassified===true} disabled={!['group','projectGroup'].includes(editing.target) || rules.some(rule=>rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/></Form.Item><div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} disabled={editing.onlyUnclassified===true} onChange={target => setEditing({ ...editing, target })} /></Form.Item><Form.Item label="匹配结果" required><Input value={editing.value} maxLength={190} onChange={event => setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" /></Form.Item></div> <Form.Item label="处理范围"><Switch checked={editing.onlyUnclassified===true} disabled={!['group','projectGroup'].includes(editing.target) || rules.some(rule=>rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/></Form.Item><div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} disabled={editing.onlyUnclassified===true} onChange={target => setEditing({ ...editing, target })} /></Form.Item><Form.Item label="匹配结果" required><Input value={editing.value} maxLength={190} onChange={event => setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" /></Form.Item></div>
{error && <Alert showIcon type="error" message={error} />} {error && <Alert showIcon type="error" message={error} />}
@@ -277,6 +280,7 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
} }
export function MasterDataDefinitionEditor({ value, onChange, publishedNames, simplified = false, readOnly = false }: DefinitionProps & { publishedNames?: Partial<Record<MasterKind, string[]>> & { groupDepartments?: Record<string, string | null> }; simplified?: boolean; readOnly?: boolean }) { export function MasterDataDefinitionEditor({ value, onChange, publishedNames, simplified = false, readOnly = false }: DefinitionProps & { publishedNames?: Partial<Record<MasterKind, string[]>> & { groupDepartments?: Record<string, string | null> }; simplified?: boolean; readOnly?: boolean }) {
const confirmDelete = useDeleteConfirmation();
const { message } = App.useApp(); const [kind, setKind] = useState<MasterKind>('departments'); const [search, setSearch] = useState(''); const { message } = App.useApp(); const [kind, setKind] = useState<MasterKind>('departments'); const [search, setSearch] = useState('');
const [editing, setEditing] = useState<MasterRow | null>(null); const [originalCode, setOriginalCode] = useState<string | null>(null); const [error, setError] = useState(''); const [importing, setImporting] = useState(false); const [editing, setEditing] = useState<MasterRow | null>(null); const [originalCode, setOriginalCode] = useState<string | null>(null); const [error, setError] = useState(''); const [importing, setImporting] = useState(false);
const [departmentAtOpen, setDepartmentAtOpen] = useState<{ value: string } | null>(null); const [departmentAtOpen, setDepartmentAtOpen] = useState<{ value: string } | null>(null);
@@ -298,7 +302,7 @@ export function MasterDataDefinitionEditor({ value, onChange, publishedNames, si
onChange(next); message.success(count ? `已从当前配置及对应值载入 ${count} 个名称,请核对后保存` : '现有名称均已在名录中'); onChange(next); message.success(count ? `已从当前配置及对应值载入 ${count} 个名称,请核对后保存` : '现有名称均已在名录中');
}; };
const departments = masterRows(value, 'departments'); const departments = masterRows(value, 'departments');
const columns: ColumnsType<MasterRow> = [{ title: '名称', dataIndex: 'name', key: 'name', width: 300 }, ...(kind === 'groups' ? [{ title: '所属产业部', key: 'department', width: 220, render: (_: unknown, row: MasterRow) => { const department = departmentFor(row); const parent = departments.find(item => item.name === department); return department ? `${department}${parent && !parent.enabled ? '(已停用)' : ''}` : <span className="structured-config-muted">未设置</span>; } }] : []), { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> }, ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MasterRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMasterRows(value, kind, rows.map(item => item.code === row.code ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => onChange(setMasterRows(value, kind, rows.filter(item => item.code !== row.code)))}>删除</Button></span> }] : [])]; const columns: ColumnsType<MasterRow> = [{ title: '名称', dataIndex: 'name', key: 'name', width: 300 }, ...(kind === 'groups' ? [{ title: '所属产业部', key: 'department', width: 220, render: (_: unknown, row: MasterRow) => { const department = departmentFor(row); const parent = departments.find(item => item.name === department); return department ? `${department}${parent && !parent.enabled ? '(已停用)' : ''}` : <span className="structured-config-muted">未设置</span>; } }] : []), { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> }, ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MasterRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMasterRows(value, kind, rows.map(item => item.code === row.code ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => confirmDelete({title:`删除${masterLabels[kind]}“${row.name}”?`,description:"将从当前名录移除,保存并更新报表后生效。请确认相关对应关系不再使用此项。",onConfirm:()=>onChange(setMasterRows(value, kind, rows.filter(item => item.code !== row.code)))})}>删除</Button></span> }] : [])];
const csvHeaders = kind === 'groups' ? ['名称', '启用', '所属产业部'] : ['名称', '启用']; const csvHeaders = kind === 'groups' ? ['名称', '启用', '所属产业部'] : ['名称', '启用'];
const departmentValue = Form.useWatch('department', form); const departmentValue = Form.useWatch('department', form);
const selectedDepartment = typeof departmentValue === 'string' ? departmentValue : ''; const selectedDepartment = typeof departmentValue === 'string' ? departmentValue : '';
+2 -2
View File
@@ -26,7 +26,7 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
const loading = sectionLoading(); const loading = sectionLoading();
const [filter,setFilter]=useState('all'); const [selected,setSelected]=useState<MonitorRow|null>(null); const [filter,setFilter]=useState('all'); const [selected,setSelected]=useState<MonitorRow|null>(null);
const actionInFlight = useRef(false); const actionInFlight = useRef(false);
const canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role)); const canManage=user.roles.some(role=>['SYSTEM_ADMIN'].includes(role));
function sectionLoading() { return section === 'tasks' ? taskBusy.busy : backupBusy.busy; } function sectionLoading() { return section === 'tasks' ? taskBusy.busy : backupBusy.busy; }
const loadTasks=useCallback(()=>taskBusy.run(async()=>{ const loadTasks=useCallback(()=>taskBusy.run(async()=>{
try { const value=await api.taskOverview();setItems(value.items);setTaskError('');setTasksLoaded(true); } try { const value=await api.taskOverview();setItems(value.items);setTaskError('');setTasksLoaded(true); }
@@ -74,6 +74,6 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
</> }, </> },
...(canManage ? [{ key:'monitor', label:'运行监控与告警', children:<OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized}/> },{ key:'backups', label:'备份管理', children:<BackupOperationsPanel user={user} onUnauthorized={onUnauthorized}/> }] : []), ...(canManage ? [{ key:'monitor', label:'运行监控与告警', children:<OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized}/> },{ key:'backups', label:'备份管理', children:<BackupOperationsPanel user={user} onUnauthorized={onUnauthorized}/> }] : []),
]} /> ]} />
<Drawer open={!!selected} title="任务详情" width={Math.min(620,window.innerWidth)} onClose={()=>setSelected(null)}>{selected&&<dl className="nc-form-grid"><dt>任务</dt><dd>{monitorLabel(selected.type,'后台任务')}</dd><dt>状态</dt><dd>{monitorLabel(selected.status)}</dd><dt>阶段</dt><dd>{monitorLabel(selected.stage,monitorLabel(selected.status))}</dd>{Number(selected.total)>0&&<><dt>已处理 / 总数</dt><dd>{String(selected.processed??0)} / {String(selected.total)}</dd></>}<dt>提交时间</dt><dd>{configurationDateTime(selected.createdAt)}</dd>{isFailed(selected)&&<><dt>失败原因</dt><dd style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{taskFailure(selected)}</dd></>}<dt>任务编号</dt><dd style={{overflowWrap:'anywhere'}}>{String(selected.id)}</dd></dl>}{selected?.sourceKind==='TASK'&&<div className="completion-actions">{selected.status==='FAILED'&&!!selected.importRunId&&user.roles.some(role=>['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))&&<Button loading={busy} onClick={()=>void runAction(selected,'retry')}>重试导入</Button>}{selected.status==='QUEUED'&&user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER'].includes(role))&&<Button danger loading={busy} onClick={()=>void runAction(selected,'cancel')}>取消排队任务</Button>}</div>}{selected?.sourceKind==='ANALYSIS'&&!!selected.sessionId&&<Button href={`?page=analysis&sessionId=${encodeURIComponent(String(selected.sessionId))}&turnId=${encodeURIComponent(String(selected.id))}`}>查看分析记录</Button>}</Drawer> <Drawer open={!!selected} title="任务详情" width={Math.min(620,window.innerWidth)} onClose={()=>setSelected(null)}>{selected&&<dl className="nc-form-grid"><dt>任务</dt><dd>{monitorLabel(selected.type,'后台任务')}</dd><dt>状态</dt><dd>{monitorLabel(selected.status)}</dd><dt>阶段</dt><dd>{monitorLabel(selected.stage,monitorLabel(selected.status))}</dd>{Number(selected.total)>0&&<><dt>已处理 / 总数</dt><dd>{String(selected.processed??0)} / {String(selected.total)}</dd></>}<dt>提交时间</dt><dd>{configurationDateTime(selected.createdAt)}</dd>{isFailed(selected)&&<><dt>失败原因</dt><dd style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{taskFailure(selected)}</dd></>}<dt>任务编号</dt><dd style={{overflowWrap:'anywhere'}}>{String(selected.id)}</dd></dl>}{selected?.sourceKind==='TASK'&&<div className="completion-actions">{selected.status==='FAILED'&&!!selected.importRunId&&user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))&&<Button loading={busy} onClick={()=>void runAction(selected,'retry')}>重试导入</Button>}{selected.status==='QUEUED'&&user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))&&<Button danger loading={busy} onClick={()=>void runAction(selected,'cancel')}>取消排队任务</Button>}</div>}{selected?.sourceKind==='ANALYSIS'&&!!selected.sessionId&&<Button href={`?page=analysis&sessionId=${encodeURIComponent(String(selected.sessionId))}&turnId=${encodeURIComponent(String(selected.id))}`}>查看分析记录</Button>}</Drawer>
</>; </>;
} }
+17 -1
View File
@@ -1,6 +1,7 @@
import { WORKSPACE_INVALIDATED } from './pageCache'; import { WORKSPACE_INVALIDATED } from './pageCache';
import { consumeEventStream, type StreamEvent } from './eventStream'; import { consumeEventStream, type StreamEvent } from './eventStream';
import { publicErrorMessage } from './publicDataDisplay'; import { publicErrorMessage } from './publicDataDisplay';
import type { SalesOrderTypePreview,SalesOrderTypeStatus } from './salesOrderTypes';
import { import {
clearReadCache, clearReadCache,
configureRequestScope, configureRequestScope,
@@ -205,11 +206,22 @@ async function mutateForm<T>(path: string, body: FormData): Promise<T> {
} }
export const api = { export const api = {
salesOrderTypeStatus() { return request<SalesOrderTypeStatus>('/api/sales-order-types'); },
async salesOrderTypePreview(file:File,mode:string) {
const body=new FormData();body.append('file',file);body.append('mode',mode);
const token=csrfToken??await refreshCsrf();
return request<SalesOrderTypePreview>('/api/sales-order-types/preview',{method:'POST',headers:{'X-XSRF-TOKEN':token},body},900_000);
},
importSalesOrderTypes(file:File,mode:string,expectedVersion:string,sha256:string) {
const body=new FormData();body.append('file',file);body.append('mode',mode);body.append('expectedVersion',expectedVersion);body.append('sha256',sha256);
return mutateForm<{versionId:string}>('/api/sales-order-types/import',body);
},
activateSalesOrderTypes(versionId:string,expectedVersion:string) { return mutate<{versionId:string}>('/api/sales-order-types/activate',{versionId,expectedVersion}); },
sourceColumnCatalog(releaseId?: string, signal?: AbortSignal) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`, { signal }); }, sourceColumnCatalog(releaseId?: string, signal?: AbortSignal) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`, { signal }); },
sourceColumnValues(body: Record<string,unknown>, signal?: AbortSignal) { return queryPost<{values:Array<string|null>;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); }, sourceColumnValues(body: Record<string,unknown>, signal?: AbortSignal) { return queryPost<{values:Array<string|null>;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); },
workspaceState() { return request<{ authRevision: string; dataRevision: string; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); }, workspaceState() { return request<{ authRevision: string; dataRevision: string; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); },
filterFields(manage = false, signal?: AbortSignal) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`, { signal }); }, filterFields(manage = false, signal?: AbortSignal) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`, { signal }); },
filterFieldOptions(key: string, search = '', signal?: AbortSignal) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`, { signal }); }, filterFieldOptions(key: string, search = '', signal?: AbortSignal,releaseId?:string,stage?:string) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search,releaseId,stage})}`, { signal }); },
filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); }, filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); },
saveFilterFields(fields: FilterField[]) { return mutate<FilterField[]>('/api/filter-fields', fields, 'PUT'); }, saveFilterFields(fields: FilterField[]) { return mutate<FilterField[]>('/api/filter-fields', fields, 'PUT'); },
refreshCsrf, refreshCsrf,
@@ -452,6 +464,9 @@ export const api = {
updateUser(id: string, body: Record<string, unknown>) { updateUser(id: string, body: Record<string, unknown>) {
return mutate<unknown>(`/api/users/${encodeURIComponent(id)}`, body, 'PUT'); return mutate<unknown>(`/api/users/${encodeURIComponent(id)}`, body, 'PUT');
}, },
deleteUser(id: string, expectedRowVersion: number) {
return mutate<{ deleted: boolean; id: string }>(`/api/users/${encodeURIComponent(id)}`, { expectedRowVersion }, 'DELETE');
},
analysis(body: { query: string; sessionId?: string; context?: Record<string, unknown> }) { analysis(body: { query: string; sessionId?: string; context?: Record<string, unknown> }) {
return mutate<unknown>('/api/analysis', body); return mutate<unknown>('/api/analysis', body);
}, },
@@ -778,6 +793,7 @@ function isImmutableRead(path: string): boolean {
function requestResourceTags(path: string): string[] { function requestResourceTags(path: string): string[] {
const pathname = requestPath(path); const pathname = requestPath(path);
if(pathname.startsWith('/api/sales-order-types'))return ['configuration','metrics','trend','records','options','catalog','query'];
if (pathname.startsWith('/api/metrics')) return ['metrics', 'trend', 'query']; if (pathname.startsWith('/api/metrics')) return ['metrics', 'trend', 'query'];
if (pathname.startsWith('/api/options')) return ['options', 'query']; if (pathname.startsWith('/api/options')) return ['options', 'query'];
if (pathname.startsWith('/api/filter-fields') || pathname === '/api/analysis/source/catalog') return ['options', 'catalog', 'configuration']; if (pathname.startsWith('/api/filter-fields') || pathname === '/api/analysis/source/catalog') return ['options', 'catalog', 'configuration'];
+2
View File
@@ -658,3 +658,5 @@
@media(max-width:760px) { @media(max-width:760px) {
.page-view:is([data-page="rules"],[data-page="mappings"],[data-page="masterData"],[data-page="tasks"],[data-page="access"]) .panel { padding-inline: 12px; } .page-view:is([data-page="rules"],[data-page="mappings"],[data-page="masterData"],[data-page="tasks"],[data-page="access"]) .panel { padding-inline: 12px; }
} }
.deletion-confirmation :is(.ant-modal-title,.ant-modal-confirm-title,.ant-modal-confirm-content){overflow-wrap:anywhere}
+1 -2
View File
@@ -17,7 +17,6 @@
background: var(--surface, #fff) !important; background: var(--surface, #fff) !important;
border: 1px solid var(--line); border: 1px solid var(--line);
box-shadow: 0 6px 18px rgba(18, 30, 52, .18); box-shadow: 0 6px 18px rgba(18, 30, 52, .18);
opacity: 1;
} }
.source-records-drawer .ant-table-tbody > tr > td { padding: 8px 9px; vertical-align: top; } .source-records-drawer .ant-table-tbody > tr > td { padding: 8px 9px; vertical-align: top; }
.source-fields summary { width: fit-content; color: var(--blue-dark); cursor: pointer; font-size: 12px; } .source-fields summary { width: fit-content; color: var(--blue-dark); cursor: pointer; font-size: 12px; }
@@ -41,7 +40,7 @@
display: grid; grid-template-columns: minmax(170px, .85fr) minmax(180px, 1fr) minmax(220px, 1.3fr) minmax(160px, .8fr) auto; display: grid; grid-template-columns: minmax(170px, .85fr) minmax(180px, 1fr) minmax(220px, 1.3fr) minmax(160px, .8fr) auto;
gap: 10px; align-items: end; margin: 10px 0 14px; gap: 10px; align-items: end; margin: 10px 0 14px;
} }
.record-query-tools > label { display: grid; gap: 5px; color: var(--ink-muted); font-size: 11px; } .record-query-tools > :is(label,[role="group"]) { display: grid; gap: 5px; color: var(--ink-muted); font-size: 11px; }
.record-query-tools .ant-select { width: 100%; } .record-query-tools .ant-select { width: 100%; }
.record-query-tools .ant-segmented { align-self: end; } .record-query-tools .ant-segmented { align-self: end; }
.record-query-tools + .ant-alert { margin-bottom: 12px; } .record-query-tools + .ant-alert { margin-bottom: 12px; }
+11
View File
@@ -0,0 +1,11 @@
.query-snapshot-controls { display:inline-flex; }
.query-snapshot-modules { display:grid; grid-template-columns:1fr 1fr; gap:14px 18px; width:100%; margin-top:20px; }
.query-snapshot-note { color:var(--ink-muted); margin:20px 0 4px; }
.query-snapshot-capture { box-sizing:border-box; gap:12px; overflow:visible; }
.query-snapshot-heading { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:4px 0 8px; color:var(--ink); }
.query-snapshot-heading strong { font-size:20px; }
.query-snapshot-heading span { color:var(--ink-muted); font-size:12px; }
.query-snapshot-capture > * { flex-shrink:0; }
.query-snapshot-capture .query-snapshot-filter-summary { width:100%; flex-basis:100%; color:var(--ink); white-space:normal; overflow-wrap:anywhere; }
.query-snapshot-capture .query-snapshot-defect-module { background:var(--surface); border:1px solid var(--line); padding:16px; border-radius:var(--panel-radius,4px); }
.query-snapshot-capture :is(.ant-btn,.object-drilldown,.table-value,.header-link) { cursor:default; }
+124
View File
@@ -0,0 +1,124 @@
export const QUERY_SNAPSHOT_MODULES = [
{ key: 'filters', label: '查询条件' }, { key: 'metrics', label: '指标卡片' },
{ key: 'trend', label: '变化趋势' }, { key: 'table', label: '汇总表' },
{ key: 'defects', label: '不良构成' }, { key: 'pareto', label: '细分缺陷柏拉图' },
] as const;
export type QuerySnapshotModule = typeof QUERY_SNAPSHOT_MODULES[number]['key'];
const KEYS = new Set<string>(QUERY_SNAPSHOT_MODULES.map(module => module.key));
export function parseSnapshotModules(raw: unknown): QuerySnapshotModule[] {
if (!Array.isArray(raw)) return QUERY_SNAPSHOT_MODULES.map(module => module.key);
return QUERY_SNAPSHOT_MODULES.filter(module => raw.includes(module.key) && KEYS.has(module.key)).map(module => module.key);
}
export function snapshotImageSize(width: number, height: number) {
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) throw new Error('页面尺寸无效,请重试');
const pixelRatio = Math.min(2, 16384 / width, 16384 / height, Math.sqrt(32_000_000 / (width * height)));
if (pixelRatio < 1) throw new Error('所选内容过长,请减少模块或汇总表每页条数');
return { width: Math.ceil(width), height: Math.ceil(height), pixelRatio };
}
export function snapshotFilename(title: string, date = new Date()) {
const stamp = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}-${String(date.getHours()).padStart(2, '0')}${String(date.getMinutes()).padStart(2, '0')}${String(date.getSeconds()).padStart(2, '0')}`;
return `${title.replace(/[\\/:*?"<>|]/g, '_')}-页面快照-${stamp}.png`;
}
export function snapshotModuleElements(root: HTMLElement, selected: QuerySnapshotModule[]) {
return QUERY_SNAPSHOT_MODULES.filter(module => selected.includes(module.key)).map(module => {
const node = root.querySelector<HTMLElement>(`[data-snapshot-module="${module.key}"]`);
if (!node || !node.offsetWidth) throw new Error(`当前页面没有可导出的“${module.label}”`);
return { ...module, node };
});
}
export function snapshotTask<T>(task: Promise<T>, signal: AbortSignal, timeoutMs: number, timeoutMessage: string): Promise<T> {
return new Promise((resolve, reject) => {
let settled = false;
const abort = () => finish(() => reject(new Error('已取消生成快照')));
const timer = setTimeout(() => finish(() => reject(new Error(timeoutMessage))), timeoutMs);
function finish(done: () => void) { if (settled) return; settled = true; clearTimeout(timer); signal.removeEventListener('abort', abort); done(); }
task.then(value => finish(() => resolve(value)), error => finish(() => reject(error)));
if (signal.aborted) abort();
else signal.addEventListener('abort', abort, { once: true });
});
}
/** Clone the selected modules only; never hide or reflow the live query page. */
export async function captureQuerySnapshot(root: HTMLElement, selected: QuerySnapshotModule[], title: string, cancelled: () => boolean, signal: AbortSignal, progress: (message: string) => void): Promise<Blob> {
if (!selected.length) throw new Error('请至少选择一个模块');
const check = () => { if (cancelled() || !root.isConnected || !root.offsetWidth) throw new Error('查询页面已变化,请重新生成快照'); };
check();
root.dispatchEvent(new CustomEvent('quality:query-snapshot', { detail: { modules: selected } }));
const modules = snapshotModuleElements(root, selected);
progress('正在等待所选模块加载完成…');
const started = performance.now();
let previous = '', stableSince = performance.now();
while (true) {
check();
const failed = modules.find(({ node }) => node.dataset.snapshotReady === 'error');
if (failed) throw new Error(`“${failed.label}”读取失败,请重试后生成快照`);
const busy = modules.some(({ node }) => node.dataset.snapshotReady === 'false' || node.matches('[aria-busy="true"],[inert]') || node.querySelector('[aria-busy="true"],[inert]'));
const signature = modules.map(({ node }) => node.innerHTML).join('');
if (signature !== previous || busy) { previous = signature; stableSince = performance.now(); }
if (!busy && performance.now() - stableSince >= 250) break;
if (performance.now() - started > 30_000) throw new Error('所选模块仍在更新,请等待查询完成后重试');
await new Promise(resolve => setTimeout(resolve, 80));
}
await snapshotTask(root.ownerDocument.fonts.ready, signal, 5000, '字体尚未加载完成,请稍后重试');
progress('正在生成图片…');
check();
const frame = document.createElement('div');
frame.className = `${root.className} query-snapshot-capture`;
frame.setAttribute('aria-hidden', 'true');
frame.inert = true;
Object.assign(frame.style, { position: 'fixed', left: '-100000px', top: '0', width: `${root.offsetWidth + 32}px`, padding: '16px', margin: '0', zIndex: '-1', pointerEvents: 'none', background: getComputedStyle(document.documentElement).backgroundColor });
const heading = document.createElement('header');
heading.className = 'query-snapshot-heading';
const name = document.createElement('strong'); name.textContent = title;
const time = document.createElement('span'); time.textContent = new Date().toLocaleString('zh-CN');
heading.append(name, time); frame.append(heading);
try {
for (const { key, node } of modules) {
const clone = node.cloneNode(true) as HTMLElement;
clone.removeAttribute('inert'); clone.removeAttribute('aria-busy');
// Canvas-based renderers need their pixels copied; SVG charts already clone losslessly.
const canvases = [...node.querySelectorAll('canvas')];
[...clone.querySelectorAll('canvas')].forEach((canvas, index) => {
const image = document.createElement('img'); image.src = canvases[index].toDataURL();
image.style.cssText = canvas.style.cssText; image.width = canvases[index].width; image.height = canvases[index].height;
canvas.replaceWith(image);
});
const sourceInputs = [...node.querySelectorAll<HTMLInputElement>('input')];
[...clone.querySelectorAll<HTMLInputElement>('input')].forEach((input, index) => {
input.value = sourceInputs[index].value; input.setAttribute('value', input.value); input.checked = sourceInputs[index].checked;
});
// Preserve the current horizontal table viewport in the rasterizer's non-scrolling clone.
const sourceScrollers = [...node.querySelectorAll<HTMLElement>('.ant-table-content,.ant-table-body')];
[...clone.querySelectorAll<HTMLElement>('.ant-table-content,.ant-table-body')].forEach((scroll, index) => {
const original = sourceScrollers[index];
if (original.scrollLeft && scroll.firstElementChild) {
scroll.style.overflow = 'hidden';
(scroll.firstElementChild as HTMLElement).style.transform = `translateX(-${original.scrollLeft}px)`;
}
});
if (key === 'filters') {
const more = node.querySelector<HTMLElement>('.query-more-toggle');
if (more?.title && more.querySelector('[aria-expanded="false"]')) {
const summary = document.createElement('div'); summary.className = 'query-snapshot-filter-summary'; summary.textContent = more.title; clone.append(summary);
}
}
clone.querySelectorAll('.query-snapshot-controls,.query-toolbar-tail,.query-status,.query-more-toggle,.query-export-button,.ant-select-dropdown,.ant-table-filter-trigger,.ant-tooltip,.mobile-scroll-hint').forEach(element => element.remove());
if (key === 'defects' || key === 'pareto') clone.classList.add('query-snapshot-defect-module');
frame.append(clone);
}
root.append(frame);
await snapshotTask(Promise.all([...frame.querySelectorAll('img')].map(image => image.decode().catch(() => undefined))), signal, 5000, '图片资源读取超时,请重试');
check();
const size = snapshotImageSize(frame.offsetWidth, frame.scrollHeight);
const { toBlob } = await snapshotTask(import('html-to-image'), signal, 10000, '图片组件加载超时,请重试');
const blob = await snapshotTask(toBlob(frame, { ...size, skipAutoScale: true, skipFonts: true, backgroundColor: frame.style.background, style: { position: 'static', left: '0', top: '0', zIndex: 'auto', pointerEvents: 'none' } }), signal, 15000, '图片生成超时,请减少模块后重试');
check();
if (!blob || blob.size < 100) throw new Error('图片生成失败,请重试');
return blob;
} finally { frame.remove(); }
}
+5
View File
@@ -0,0 +1,5 @@
.sales-order-type-controls { display:flex; gap:6px; flex:1; min-width:0; }
.sales-order-type-controls > .sales-order-type-mode { flex:0 0 78px; width:78px; min-width:78px; }
.sales-order-type-controls > .sales-order-type-values { flex:1; min-width:0; width:0; }
.query-extra-field.sales-order-type-field { min-width:340px; }
@media(max-width:600px) { .query-extra-field.sales-order-type-field { min-width:0; } }
+22
View File
@@ -0,0 +1,22 @@
export interface SalesOrderTypeVersion {
id:string; sourceFile:string; rowCount:number; importMode:string; createdAt:string;
}
export interface SalesOrderTypeStatus {
versionId:string; versions:SalesOrderTypeVersion[]; types:string[];
}
export interface SalesOrderTypePreview {
sourceFile:string; sha256:string; expectedVersion:string;
summary:{added:number;updated:number;unchanged:number;removed:number;imported:number;total:number};
}
export const SALES_ORDER_TYPE='salesOrderType';
export const SALES_ORDER_TYPE_EXCLUDED='salesOrderTypeNotIn';
export function salesOrderTypeSelection(filters:Record<string,string[]>) {
const exclude=Object.hasOwn(filters,SALES_ORDER_TYPE_EXCLUDED);
return {exclude,values:filters[exclude?SALES_ORDER_TYPE_EXCLUDED:SALES_ORDER_TYPE]||[]};
}
export function updateSalesOrderTypeSelection(filters:Record<string,string[]>,exclude:boolean,values:string[]) {
const next={...filters};delete next[SALES_ORDER_TYPE];delete next[SALES_ORDER_TYPE_EXCLUDED];
if(values.length||exclude)next[exclude?SALES_ORDER_TYPE_EXCLUDED:SALES_ORDER_TYPE]=[...values];
return next;
}

Some files were not shown because too many files have changed in this diff Show More