Compare commits
2
Commits
b73240b2db
...
cf8e25a30d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf8e25a30d | ||
|
|
b711327c8e |
@@ -115,3 +115,10 @@
|
|||||||
- 各级返回按钮统一为带左箭头的“返回上一级”,沿用原有父级路径,使用主题色描边与浅底;Excel 导出使用实色主按钮,两者统一加粗。
|
- 各级返回按钮统一为带左箭头的“返回上一级”,沿用原有父级路径,使用主题色描边与浅底;Excel 导出使用实色主按钮,两者统一加粗。
|
||||||
- 趋势数据表取消底部分页统计与月份汇总链接,直接展示已返回的期间;保留月份行的筛选操作。各查询页删除“点击期间筛选”类提示。
|
- 趋势数据表取消底部分页统计与月份汇总链接,直接展示已返回的期间;保留月份行的筛选操作。各查询页删除“点击期间筛选”类提示。
|
||||||
- 本地实测三级返回、月份行筛选及六主题按钮效果;主汇总表分页和 Excel 导出行为保持原有方式。
|
- 本地实测三级返回、月份行筛选及六主题按钮效果;主汇总表分页和 Excel 导出行为保持原有方式。
|
||||||
|
|
||||||
|
## 2026-11-02:全系统统一加载(用户批准方案)
|
||||||
|
|
||||||
|
- 维持现有布局、主题及 280/520 毫秒过渡;150 毫秒后显示区域加载提示。首次失败、更新失败、成功空结果分别呈现,更新时保留已生效范围的结果。
|
||||||
|
- 更新中的旧范围结果不能钻取、查看明细或导出;区域独立重试。任务使用真实阶段,写入即时忙碌并防重复,不显示虚构百分比或新增常驻说明。
|
||||||
|
- 返回页面保留筛选、页码、滚动位置及表格高度;隐藏页面和未选管理页签不主动刷新。业务分页、全范围搜索排序和导出不变。
|
||||||
|
- 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import cn.yunsheng.quality.identity.AppUserPrincipal;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.util.HexFormat;
|
import java.util.HexFormat;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
@@ -26,14 +27,25 @@ public class WorkspaceStateController {
|
|||||||
var policy = jdbc.queryForList("SELECT detail_allowed,evidence_allowed,original_download_allowed,CAST(allowed_fields AS CHAR) AS allowed_fields,valid_until,inherit_department_children,row_version FROM user_access_policy WHERE user_id=?", actor.getId().toString());
|
var policy = jdbc.queryForList("SELECT detail_allowed,evidence_allowed,original_download_allowed,CAST(allowed_fields AS CHAR) AS allowed_fields,valid_until,inherit_department_children,row_version FROM user_access_policy WHERE user_id=?", actor.getId().toString());
|
||||||
String auth = digest(List.of(actor.getId(), actor.getRoleCodes().stream().sorted().toList(),
|
String auth = digest(List.of(actor.getId(), actor.getRoleCodes().stream().sorted().toList(),
|
||||||
actor.getDepartments().stream().sorted().toList(), actor.getGroups().stream().sorted().toList(), policy));
|
actor.getDepartments().stream().sorted().toList(), actor.getGroups().stream().sorted().toList(), policy));
|
||||||
|
var currentRelease = jdbc.queryForList("SELECT * FROM current_release ORDER BY dataset_id");
|
||||||
|
String currentReleaseId = currentRelease.stream()
|
||||||
|
.filter(row -> "quality".equals(String.valueOf(row.get("dataset_id"))))
|
||||||
|
.map(row -> row.get("release_id"))
|
||||||
|
.filter(java.util.Objects::nonNull)
|
||||||
|
.map(String::valueOf)
|
||||||
|
.findFirst().orElse(null);
|
||||||
String data = digest(List.of(
|
String data = digest(List.of(
|
||||||
jdbc.queryForList("SELECT * FROM current_release ORDER BY dataset_id"),
|
currentRelease,
|
||||||
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 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")));
|
||||||
return Map.of("authRevision", auth, "dataRevision", data);
|
Map<String, String> result = new LinkedHashMap<>();
|
||||||
|
result.put("authRevision", auth);
|
||||||
|
result.put("dataRevision", data);
|
||||||
|
result.put("currentReleaseId", currentReleaseId);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
private static String digest(Object value) {
|
private static String digest(Object value) {
|
||||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.toString().getBytes(StandardCharsets.UTF_8))); }
|
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.toString().getBytes(StandardCharsets.UTF_8))); }
|
||||||
|
|||||||
@@ -76,6 +76,37 @@ public class MetricsController {
|
|||||||
extraFilters, exclusions, columnFilters, stage, actor);
|
extraFilters, exclusions, columnFilters, stage, actor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 轻量趋势接口:查询参数与正式指标接口一致,但只返回版本、上下文、趋势和覆盖信息。 */
|
||||||
|
@GetMapping("/trend")
|
||||||
|
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')")
|
||||||
|
public MetricsService.MetricTrendSnapshot trendHttp(@RequestParam(required = false) Integer year,
|
||||||
|
@RequestParam(required = false) Integer month,
|
||||||
|
@RequestParam(required = false) Integer monthStart,
|
||||||
|
@RequestParam(required = false) Integer monthEnd,
|
||||||
|
@RequestParam(required = false) String quarter,
|
||||||
|
@RequestParam(required = false) String department,
|
||||||
|
@RequestParam(required = false) String group,
|
||||||
|
@RequestParam(required = false) String product,
|
||||||
|
@RequestParam(required = false) String productSearch,
|
||||||
|
@RequestParam(required = false) String projectGroup,
|
||||||
|
@RequestParam(defaultValue = "overall") String view,
|
||||||
|
@RequestParam(defaultValue = "true") boolean includeUnassigned,
|
||||||
|
@RequestParam(required = false) String releaseId,
|
||||||
|
@RequestParam(defaultValue = "month") String trendGranularity,
|
||||||
|
@RequestParam(required = false) String extraFilters,
|
||||||
|
@RequestParam(required = false) String exclusions,
|
||||||
|
@RequestParam(required = false) String columnFilters,
|
||||||
|
@RequestParam(required = false) String stage,
|
||||||
|
@AuthenticationPrincipal AppUserPrincipal actor) {
|
||||||
|
Integer quarterNumber = parseQuarter(quarter);
|
||||||
|
MetricsService.MetricsQuery query = new MetricsService.MetricsQuery(year, month, quarterNumber, department,
|
||||||
|
group, product, projectGroup, view, includeUnassigned, releaseId, trendGranularity,
|
||||||
|
parseExclusions(exclusions));
|
||||||
|
query = query.withMonthRange(monthStart, monthEnd).withExtraFilters(extraFilters)
|
||||||
|
.withProductSearch(productSearch).withColumnFilters(columnFilters).withStage(stage);
|
||||||
|
return responseAccess.visibleTrend(metrics.calculateTrend(query, actor), actor);
|
||||||
|
}
|
||||||
|
|
||||||
/** Existing direct callers retain the pre-range controller signature. */
|
/** Existing direct callers retain the pre-range controller signature. */
|
||||||
public MetricsService.MetricSnapshot calculate(Integer year, Integer month, String quarter,
|
public MetricsService.MetricSnapshot calculate(Integer year, Integer month, String quarter,
|
||||||
String department, String group, String product, String productSearch,
|
String department, String group, String product, String productSearch,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import cn.yunsheng.quality.identity.AppUserPrincipal;
|
|||||||
import cn.yunsheng.quality.metrics.MetricsService.DefectRow;
|
import cn.yunsheng.quality.metrics.MetricsService.DefectRow;
|
||||||
import cn.yunsheng.quality.metrics.MetricsService.MetricRow;
|
import cn.yunsheng.quality.metrics.MetricsService.MetricRow;
|
||||||
import cn.yunsheng.quality.metrics.MetricsService.MetricSnapshot;
|
import cn.yunsheng.quality.metrics.MetricsService.MetricSnapshot;
|
||||||
|
import cn.yunsheng.quality.metrics.MetricsService.MetricTrendSnapshot;
|
||||||
import cn.yunsheng.quality.metrics.MetricsService.MetricStage;
|
import cn.yunsheng.quality.metrics.MetricsService.MetricStage;
|
||||||
import cn.yunsheng.quality.metrics.MetricsService.TrendMetricRow;
|
import cn.yunsheng.quality.metrics.MetricsService.TrendMetricRow;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -30,6 +31,25 @@ public class MetricsResponseAccess {
|
|||||||
return new MetricSnapshot(filtered.release(), filtered.context(), hideDefects(filtered.summary()), List.of(), List.of(), defects, filtered.coverage());
|
return new MetricSnapshot(filtered.release(), filtered.context(), hideDefects(filtered.summary()), List.of(), List.of(), defects, filtered.coverage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 趋势查询沿用明细授权和指标字段可见性边界。 */
|
||||||
|
public MetricTrendSnapshot visibleTrend(MetricTrendSnapshot snapshot, AppUserPrincipal actor) {
|
||||||
|
governance.requireUserActivePolicy(actor);
|
||||||
|
if (!Boolean.TRUE.equals(governance.policy(actor.getId().toString()).get("detailAllowed")))
|
||||||
|
return new MetricTrendSnapshot(snapshot.release(), snapshot.context(), List.of(), snapshot.coverage());
|
||||||
|
governance.requireBoundAction("QUERY", "query.detail");
|
||||||
|
Set<String> allowed = governance.allowedFields(actor);
|
||||||
|
List<TrendMetricRow> trend = allowed.contains("*") ? snapshot.trend()
|
||||||
|
: snapshot.trend().stream().map(row -> restrictTrend(row, allowed)).toList();
|
||||||
|
return new MetricTrendSnapshot(snapshot.release(), snapshot.context(), trend, snapshot.coverage());
|
||||||
|
}
|
||||||
|
|
||||||
|
private TrendMetricRow restrictTrend(TrendMetricRow row, Set<String> allowed) {
|
||||||
|
return new TrendMetricRow(row.month(), row.key(), row.label(), row.department(), row.group(), row.product(),
|
||||||
|
row.projectGroup(), row.compositeRate(), restrictDefects(row.black(), "black", allowed),
|
||||||
|
restrictDefects(row.bright(), "bright", allowed), row.coverage(),
|
||||||
|
row.compositeRateWithoutHeadquartersScrap(), row.period(), row.periodLabel(), row.granularity());
|
||||||
|
}
|
||||||
|
|
||||||
private MetricRow hideDefects(MetricRow row) {
|
private MetricRow hideDefects(MetricRow row) {
|
||||||
return new MetricRow(row.key(), row.label(), row.department(), row.group(), row.product(), row.projectGroup(), row.compositeRate(),
|
return new MetricRow(row.key(), row.label(), row.department(), row.group(), row.product(), row.projectGroup(), row.compositeRate(),
|
||||||
hideDefects(row.black()), hideDefects(row.bright()), row.coverage(), row.compositeRateWithoutHeadquartersScrap());
|
hideDefects(row.black()), hideDefects(row.bright()), row.coverage(), row.compositeRateWithoutHeadquartersScrap());
|
||||||
|
|||||||
@@ -71,6 +71,113 @@ public class MetricsService {
|
|||||||
return calculateForRelease(query, actor, release);
|
return calculateForRelease(query, actor, release);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 只按时间桶生成趋势,不构造总体摘要或产品/分组维度行。 */
|
||||||
|
public MetricTrendSnapshot calculateTrend(MetricsQuery query, AppUserPrincipal actor) {
|
||||||
|
if (actor == null) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "指标查询必须绑定当前有效用户");
|
||||||
|
governance.requireUserActivePolicy(actor);
|
||||||
|
governance.requireBoundAction("QUERY", "query.aggregate");
|
||||||
|
validate(query);
|
||||||
|
String releaseId = query.releaseId() == null || query.releaseId().isBlank()
|
||||||
|
? currentReleaseId() : query.releaseId();
|
||||||
|
if (releaseId == null) return emptyTrendSnapshot(query);
|
||||||
|
ReleaseInfo release = release(releaseId, actor);
|
||||||
|
return withConsistentSnapshot(() -> calculateTrendForReleaseSnapshot(query, actor, release));
|
||||||
|
}
|
||||||
|
|
||||||
|
private MetricTrendSnapshot calculateTrendForReleaseSnapshot(MetricsQuery query, AppUserPrincipal actor,
|
||||||
|
ReleaseInfo release) {
|
||||||
|
boolean hasUnrolledBuilds = hasUnrolledBuilds(release.id());
|
||||||
|
Map<String, AggregateStats> periods = queryTrendAggregates(release.id(), query, actor, hasUnrolledBuilds);
|
||||||
|
String ruleVersion = jdbc.queryForObject("SELECT rule_version FROM data_release WHERE id=?", String.class, release.id());
|
||||||
|
ConfigurableRuleEngine rules = rulesForVersion(ruleVersion);
|
||||||
|
List<TrendMetricRow> trend = trendRows(periods, query.trendGranularity()).stream().map(row -> {
|
||||||
|
MetricRow adjusted = rules.applyMetrics(new MetricRow(row.key(), row.label(), row.department(), row.group(),
|
||||||
|
row.product(), row.projectGroup(), row.compositeRate(), row.black(), row.bright(), row.coverage(),
|
||||||
|
row.compositeRateWithoutHeadquartersScrap()));
|
||||||
|
return new TrendMetricRow(row.month(), adjusted.key(), adjusted.label(), adjusted.department(), adjusted.group(),
|
||||||
|
adjusted.product(), adjusted.projectGroup(), adjusted.compositeRate(), adjusted.black(), adjusted.bright(),
|
||||||
|
adjusted.coverage(), adjusted.compositeRateWithoutHeadquartersScrap(), row.period(), row.periodLabel(),
|
||||||
|
row.granularity());
|
||||||
|
}).toList();
|
||||||
|
Map<String, Object> coverage = queryCoverage(release.id(), query, actor, hasUnrolledBuilds);
|
||||||
|
Map<String, Object> context = context(query, query.includeUnassigned());
|
||||||
|
context.put("ruleVersionId", ruleVersion == null ? BusinessRowMapper.RULE_VERSION : ruleVersion);
|
||||||
|
context.put("calculationRules", rules.calculationRules());
|
||||||
|
context.put("metricFormulaDescriptions", rules.formulaDescriptions());
|
||||||
|
return new MetricTrendSnapshot(release.asMap(), context, trend, coverage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, AggregateStats> queryTrendAggregates(String releaseId, MetricsQuery query,
|
||||||
|
AppUserPrincipal actor, boolean hasUnrolledBuilds) {
|
||||||
|
Map<String, AggregateStats> periods = new TreeMap<>();
|
||||||
|
boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
|
||||||
|
if (!hasSourceFilters) {
|
||||||
|
aggregateTrendStage(periods, "black", releaseId, query, actor, false);
|
||||||
|
aggregateTrendStage(periods, "bright", releaseId, query, actor, false);
|
||||||
|
}
|
||||||
|
if (hasUnrolledBuilds || hasSourceFilters) {
|
||||||
|
aggregateTrendStage(periods, "black", releaseId, query, actor, true);
|
||||||
|
aggregateTrendStage(periods, "bright", releaseId, query, actor, true);
|
||||||
|
}
|
||||||
|
return periods;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void aggregateTrendStage(Map<String, AggregateStats> periods, String stage, String releaseId,
|
||||||
|
MetricsQuery query, AppUserPrincipal actor, boolean factFallback) {
|
||||||
|
if (query.stage() != null && !query.stage().equals(stage)) return;
|
||||||
|
String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : "metric_rollup";
|
||||||
|
StringBuilder where = new StringBuilder(" WHERE rm.release_id=?");
|
||||||
|
List<Object> args = new ArrayList<>();
|
||||||
|
args.add(releaseId);
|
||||||
|
boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
|
||||||
|
if (factFallback && !hasSourceFilters)
|
||||||
|
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); }
|
||||||
|
appendTime(where, args, query);
|
||||||
|
appendDimensions(where, args, query);
|
||||||
|
appendExclusions(where, args, query);
|
||||||
|
if (factFallback) {
|
||||||
|
new QueryFilterFields(jdbc, governance).append(where, args, stage, query.extraFilters(), actor);
|
||||||
|
if (!query.columnFilters().isEmpty())
|
||||||
|
new SourceColumnQueries(jdbc, governance, JsonMapper.builder().build())
|
||||||
|
.append(where, args, stage, query.columnFilters(), releaseId, actor);
|
||||||
|
}
|
||||||
|
DataScope.append(where, args, actor, "f.department COLLATE utf8mb4_0900_as_cs",
|
||||||
|
"f.group_name COLLATE utf8mb4_0900_as_cs");
|
||||||
|
if (!effectiveIncludeUnassigned(query)) where.append(" AND (f.group_name IS NOT NULL AND f.group_name<>'')");
|
||||||
|
|
||||||
|
String countExpression = factFallback ? "COUNT(*)" : "SUM(f.source_row_count)";
|
||||||
|
String sql = """
|
||||||
|
SELECT %s AS trend_period,
|
||||||
|
SUM(f.qualified_weight) AS qualified_weight,
|
||||||
|
SUM(f.scrap_weight) AS scrap_weight,
|
||||||
|
SUM(f.total_weight) AS total_weight,
|
||||||
|
%s AS black_responsibility_scrap,
|
||||||
|
%s AS black_material_scrap,
|
||||||
|
%s AS black_external_scrap,
|
||||||
|
%s AS bright_headquarters_scrap,
|
||||||
|
%s AS bright_plating_scrap,
|
||||||
|
%s AS bright_material_scrap,
|
||||||
|
%s AS bright_processing_scrap,
|
||||||
|
%s AS bright_diffusion_scrap,
|
||||||
|
%s AS row_count
|
||||||
|
FROM release_member rm JOIN %s f ON f.build_id=rm.transform_build_id
|
||||||
|
%s
|
||||||
|
GROUP BY trend_period
|
||||||
|
ORDER BY trend_period
|
||||||
|
""".formatted(trendBucketExpression(query.trendGranularity()),
|
||||||
|
componentSum("black_responsibility_scrap"), componentSum("black_material_scrap"),
|
||||||
|
componentSum("black_external_scrap"), componentSum("bright_headquarters_scrap"),
|
||||||
|
componentSum("bright_plating_scrap"), componentSum("bright_material_scrap"),
|
||||||
|
componentSum("bright_processing_scrap"), componentSum("bright_diffusion_scrap"),
|
||||||
|
countExpression, table, where);
|
||||||
|
jdbc.query(sql, (RowCallbackHandler) rs -> {
|
||||||
|
String period = rs.getString("trend_period");
|
||||||
|
AggregateStats stats = new AggregateStats().read(rs, stage);
|
||||||
|
periods.computeIfAbsent(period, ignored -> new AggregateStats()).merge(stage, stats);
|
||||||
|
}, args.toArray());
|
||||||
|
}
|
||||||
|
|
||||||
/** Candidate and historical release path reserved for the explicit governance reconciliation flow. */
|
/** Candidate and historical release path reserved for the explicit governance reconciliation flow. */
|
||||||
public MetricSnapshot calculateCandidateForGovernance(MetricsQuery query, AppUserPrincipal actor) {
|
public MetricSnapshot calculateCandidateForGovernance(MetricsQuery query, AppUserPrincipal actor) {
|
||||||
return withGovernanceSnapshot(() -> calculateForGovernance(query, actor, true));
|
return withGovernanceSnapshot(() -> calculateForGovernance(query, actor, true));
|
||||||
@@ -393,8 +500,12 @@ public class MetricsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private List<TrendMetricRow> trendRows(AggregateSet aggregates, String granularity) {
|
private List<TrendMetricRow> trendRows(AggregateSet aggregates, String granularity) {
|
||||||
|
return trendRows(aggregates.periods(), granularity);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<TrendMetricRow> trendRows(Map<String, AggregateStats> periods, String granularity) {
|
||||||
List<TrendMetricRow> trend = new ArrayList<>();
|
List<TrendMetricRow> trend = new ArrayList<>();
|
||||||
aggregates.periods().forEach((period, stats) -> {
|
periods.forEach((period, stats) -> {
|
||||||
String label = switch (granularity) {
|
String label = switch (granularity) {
|
||||||
case "quarter" -> period.replace("-Q", "年第") + "季度";
|
case "quarter" -> period.replace("-Q", "年第") + "季度";
|
||||||
case "year" -> period + "年";
|
case "year" -> period + "年";
|
||||||
@@ -688,6 +799,12 @@ public class MetricsService {
|
|||||||
Map.of("black", empty.black().defects(), "bright", empty.bright().defects()), coverage);
|
Map.of("black", empty.black().defects(), "bright", empty.bright().defects()), coverage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private MetricTrendSnapshot emptyTrendSnapshot(MetricsQuery query) {
|
||||||
|
Map<String, Object> coverage = Map.of("rawRows", 0, "includedRows", 0, "excludedBlankRows", 0,
|
||||||
|
"unmappedRows", 0, "projectGroupUnconfiguredRows", 0, "missingStages", List.of(), "sourceMonths", List.of());
|
||||||
|
return new MetricTrendSnapshot(null, context(query, query.includeUnassigned()), List.of(), coverage);
|
||||||
|
}
|
||||||
|
|
||||||
void validate(MetricsQuery query) {
|
void validate(MetricsQuery query) {
|
||||||
if (query.year() != null && (query.year() < 2000 || query.year() > 2100)) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "年份无效");
|
if (query.year() != null && (query.year() < 2000 || query.year() > 2100)) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "年份无效");
|
||||||
if (query.month() != null && (query.month() < 1 || query.month() > 12)) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "月份无效");
|
if (query.month() != null && (query.month() < 1 || query.month() > 12)) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "月份无效");
|
||||||
@@ -831,6 +948,8 @@ public class MetricsService {
|
|||||||
public record MetricSnapshot(Map<String, Object> release, Map<String, Object> context, MetricRow summary,
|
public record MetricSnapshot(Map<String, Object> release, Map<String, Object> context, MetricRow summary,
|
||||||
List<MetricRow> rows, List<TrendMetricRow> trend, Map<String, Object> defects,
|
List<MetricRow> rows, List<TrendMetricRow> trend, Map<String, Object> defects,
|
||||||
Map<String, Object> coverage) {}
|
Map<String, Object> coverage) {}
|
||||||
|
public record MetricTrendSnapshot(Map<String, Object> release, Map<String, Object> context,
|
||||||
|
List<TrendMetricRow> trend, Map<String, Object> coverage) {}
|
||||||
public record ComparisonSnapshots(MetricSnapshot current, MetricSnapshot comparison) {}
|
public record ComparisonSnapshots(MetricSnapshot current, MetricSnapshot comparison) {}
|
||||||
|
|
||||||
private record Fact(String stage, String month, String department, String group, String projectGroup, String product,
|
private record Fact(String stage, String month, String department, String group, String projectGroup, String product,
|
||||||
|
|||||||
@@ -2,6 +2,13 @@ server:
|
|||||||
address: 127.0.0.1
|
address: 127.0.0.1
|
||||||
port: ${PORT:5281}
|
port: ${PORT:5281}
|
||||||
shutdown: graceful
|
shutdown: graceful
|
||||||
|
# 只压缩较大的 JSON 响应;SSE、表格和压缩包不在类型白名单中。
|
||||||
|
compression:
|
||||||
|
enabled: true
|
||||||
|
min-response-size: 1KB
|
||||||
|
mime-types:
|
||||||
|
- application/json
|
||||||
|
- application/problem+json
|
||||||
servlet:
|
servlet:
|
||||||
session:
|
session:
|
||||||
cookie:
|
cookie:
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ class WorkspaceStateControllerTest {
|
|||||||
when(jdbc.queryForList(contains("user_access_policy"), any(Object[].class))).thenReturn(List.of(Map.of("allowed_fields","private-field")));
|
when(jdbc.queryForList(contains("user_access_policy"), any(Object[].class))).thenReturn(List.of(Map.of("allowed_fields","private-field")));
|
||||||
var first = controller.state(actor(List.of("A","B")));
|
var first = controller.state(actor(List.of("A","B")));
|
||||||
assertEquals(first, controller.state(actor(List.of("B","A"))));
|
assertEquals(first, controller.state(actor(List.of("B","A"))));
|
||||||
assertTrue(first.values().stream().allMatch(value -> value.matches("[a-f0-9]{64}")));
|
assertTrue(first.get("authRevision").matches("[a-f0-9]{64}"));
|
||||||
|
assertTrue(first.get("dataRevision").matches("[a-f0-9]{64}"));
|
||||||
|
assertNull(first.get("currentReleaseId"));
|
||||||
assertFalse(first.toString().contains("private-field"));
|
assertFalse(first.toString().contains("private-field"));
|
||||||
verify(access,times(2)).requireUserActivePolicy(any());
|
verify(access,times(2)).requireUserActivePolicy(any());
|
||||||
}
|
}
|
||||||
@@ -41,4 +43,17 @@ class WorkspaceStateControllerTest {
|
|||||||
assertThrows(IllegalStateException.class,()->controller.state(actor));
|
assertThrows(IllegalStateException.class,()->controller.state(actor));
|
||||||
verifyNoInteractions(jdbc);
|
verifyNoInteractions(jdbc);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test void currentReleaseIdMatchesTheReleaseSnapshotIncludedInDataRevision() {
|
||||||
|
String query = "SELECT * FROM current_release ORDER BY dataset_id";
|
||||||
|
when(jdbc.queryForList(query)).thenReturn(List.of(Map.of("dataset_id", "quality", "release_id", "release-a")))
|
||||||
|
.thenReturn(List.of(Map.of("dataset_id", "quality", "release_id", "release-b")));
|
||||||
|
var first = controller.state(actor(List.of("A")));
|
||||||
|
var second = controller.state(actor(List.of("A")));
|
||||||
|
assertEquals("release-a", first.get("currentReleaseId"));
|
||||||
|
assertEquals("release-b", second.get("currentReleaseId"));
|
||||||
|
assertNotEquals(first.get("dataRevision"), second.get("dataRevision"));
|
||||||
|
verify(jdbc, times(2)).queryForList(query);
|
||||||
|
verify(access, times(2)).requireUserActivePolicy(any());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,4 +66,22 @@ class MetricsResponseAccessTest {
|
|||||||
when(governance.allowedFields(actor)).thenReturn(Set.of("*"));
|
when(governance.allowedFields(actor)).thenReturn(Set.of("*"));
|
||||||
assertSame(source, new MetricsResponseAccess(governance).visible(source, actor));
|
assertSame(source, new MetricsResponseAccess(governance).visible(source, actor));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test void lightweightTrendStillHonorsDetailAndMetricFieldPermissions() {
|
||||||
|
var trend = new MetricTrendSnapshot(Map.of("id", "release-a"), Map.of("view", "product"),
|
||||||
|
source.trend(), Map.of("rawRows", 10));
|
||||||
|
when(governance.policy(actor.getId().toString())).thenReturn(Map.of("detailAllowed", true));
|
||||||
|
when(governance.allowedFields(actor)).thenReturn(Set.of("black_total_weight"));
|
||||||
|
MetricTrendSnapshot visible = new MetricsResponseAccess(governance).visibleTrend(trend, actor);
|
||||||
|
assertEquals(1, visible.trend().size());
|
||||||
|
assertNull(visible.trend().getFirst().black().qualifiedWeight());
|
||||||
|
assertNull(visible.trend().getFirst().black().scrapWeight());
|
||||||
|
assertEquals(stage.totalWeight(), visible.trend().getFirst().black().totalWeight());
|
||||||
|
|
||||||
|
clearInvocations(governance);
|
||||||
|
when(governance.policy(actor.getId().toString())).thenReturn(Map.of("detailAllowed", false));
|
||||||
|
MetricTrendSnapshot aggregateOnly = new MetricsResponseAccess(governance).visibleTrend(trend, actor);
|
||||||
|
assertTrue(aggregateOnly.trend().isEmpty());
|
||||||
|
verify(governance, never()).requireBoundAction("QUERY", "query.detail");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package cn.yunsheng.quality.metrics;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import cn.yunsheng.quality.identity.AppUserPrincipal;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
class MetricsTrendControllerTest {
|
||||||
|
@Test void trendRouteCarriesEveryPeriodFilterStageExclusionAndSourceFilterIntoMetrics() {
|
||||||
|
MetricsService metrics = mock(MetricsService.class);
|
||||||
|
MetricsResponseAccess access = mock(MetricsResponseAccess.class);
|
||||||
|
AppUserPrincipal actor = new AppUserPrincipal(UUID.randomUUID(), "trend", "unused", "趋势", true, false,
|
||||||
|
List.of("QUALITY_VIEWER"), List.of("D"), List.of("G"), List.of());
|
||||||
|
MetricsService.MetricTrendSnapshot response = new MetricsService.MetricTrendSnapshot(
|
||||||
|
Map.of(), Map.of(), List.of(), Map.of());
|
||||||
|
when(metrics.calculateTrend(any(), eq(actor))).thenReturn(response);
|
||||||
|
when(access.visibleTrend(response, actor)).thenReturn(response);
|
||||||
|
|
||||||
|
MetricsService.MetricTrendSnapshot actual = new MetricsController(metrics, access).trendHttp(
|
||||||
|
2026, null, 3, 9, null, "D", "G", "P", "18X15", "PG", "product", false,
|
||||||
|
"release-a", "quarter", "{\"customerCode\":[\"000123\"]}",
|
||||||
|
"{\"product\":[\"P2\"]}",
|
||||||
|
"[{\"field\":\"src_any\",\"stages\":[\"black\"],\"operator\":\"in\",\"values\":[\"000123\"]}]",
|
||||||
|
"black", actor);
|
||||||
|
|
||||||
|
assertEquals(response, actual);
|
||||||
|
ArgumentCaptor<MetricsService.MetricsQuery> query = ArgumentCaptor.forClass(MetricsService.MetricsQuery.class);
|
||||||
|
verify(metrics).calculateTrend(query.capture(), eq(actor));
|
||||||
|
MetricsService.MetricsQuery value = query.getValue();
|
||||||
|
assertEquals(2026, value.year());
|
||||||
|
assertEquals(3, value.monthStart());
|
||||||
|
assertEquals(9, value.monthEnd());
|
||||||
|
assertEquals("D", value.department());
|
||||||
|
assertEquals("G", value.group());
|
||||||
|
assertEquals("P", value.product());
|
||||||
|
assertEquals("18X15", value.productSearch());
|
||||||
|
assertEquals("PG", value.projectGroup());
|
||||||
|
assertEquals("product", value.view());
|
||||||
|
assertEquals("quarter", value.trendGranularity());
|
||||||
|
assertEquals("black", value.stage());
|
||||||
|
assertEquals(Map.of("product", List.of("P2")), value.exclusions());
|
||||||
|
assertEquals(Map.of("customerCode", List.of("000123")), value.extraFilters());
|
||||||
|
assertEquals("src_any", value.columnFilters().getFirst().get("field"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package cn.yunsheng.quality.metrics;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import cn.yunsheng.quality.governance.GovernanceAccessService;
|
||||||
|
import cn.yunsheng.quality.identity.AppUserPrincipal;
|
||||||
|
import cn.yunsheng.quality.ingestion.BusinessRowMapper;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.jdbc.core.RowCallbackHandler;
|
||||||
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
|
|
||||||
|
class MetricsTrendServiceTest {
|
||||||
|
private static final String RELEASE = "release-trend";
|
||||||
|
private final AppUserPrincipal actor = new AppUserPrincipal(UUID.randomUUID(), "trend-reader", "unused", "趋势读者",
|
||||||
|
true, false, List.of("SYSTEM_ADMIN"), List.of("*"), List.of("*"), List.of());
|
||||||
|
|
||||||
|
@Test void directTrendMatchesFullMetricsTrendWithoutBuildingProductGroups() {
|
||||||
|
JdbcTemplate jdbc = jdbc(true, true);
|
||||||
|
MetricsService service = new MetricsService(jdbc, mock(GovernanceAccessService.class));
|
||||||
|
var query = new MetricsService.MetricsQuery(2026, null, null, null, null, null, null,
|
||||||
|
"product", true, RELEASE, "month", Map.of());
|
||||||
|
|
||||||
|
MetricsService.MetricSnapshot full = service.calculate(query, actor);
|
||||||
|
MetricsService.MetricTrendSnapshot trend = service.calculateTrend(query, actor);
|
||||||
|
|
||||||
|
assertEquals(full.trend(), trend.trend());
|
||||||
|
assertEquals(full.coverage(), trend.coverage());
|
||||||
|
assertEquals("release-trend", trend.release().get("id"));
|
||||||
|
assertNull(trend.trend().getFirst().product());
|
||||||
|
assertNull(trend.trend().getFirst().group());
|
||||||
|
assertEquals(List.of("release", "context", "trend", "coverage"),
|
||||||
|
Arrays.stream(MetricsService.MetricTrendSnapshot.class.getRecordComponents())
|
||||||
|
.map(java.lang.reflect.RecordComponent::getName).toList());
|
||||||
|
|
||||||
|
List<String> trendSql = capturedSql(jdbc).stream()
|
||||||
|
.filter(sql -> sql.contains("GROUP BY trend_period") && !sql.contains("GROUP BY trend_period,"))
|
||||||
|
.toList();
|
||||||
|
assertFalse(trendSql.isEmpty());
|
||||||
|
assertTrue(trendSql.stream().allMatch(sql -> !sql.contains("bucket_key") && !sql.contains("f.product")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void rangeStageAndFiltersReachOnlyTheRequestedTrendAndCoverageQueries() {
|
||||||
|
JdbcTemplate jdbc = jdbc(true, true);
|
||||||
|
MetricsService service = new MetricsService(jdbc, mock(GovernanceAccessService.class));
|
||||||
|
var query = new MetricsService.MetricsQuery(2026, null, null, null, null, null, null,
|
||||||
|
"product", true, RELEASE, "month", Map.of("product", List.of("excluded-product")))
|
||||||
|
.withMonthRange(3, 5).withProductSearch("18X15").withStage("black");
|
||||||
|
|
||||||
|
MetricsService.MetricTrendSnapshot result = service.calculateTrend(query, actor);
|
||||||
|
|
||||||
|
assertEquals("black", result.context().get("stage"));
|
||||||
|
assertEquals(3, result.context().get("monthStart"));
|
||||||
|
assertEquals(5, result.context().get("monthEnd"));
|
||||||
|
List<String> sql = capturedSql(jdbc);
|
||||||
|
List<String> trendSql = sql.stream().filter(value -> value.contains("GROUP BY trend_period")).toList();
|
||||||
|
assertEquals(1, trendSql.size());
|
||||||
|
assertTrue(trendSql.getFirst().contains("f.month_key BETWEEN ? AND ?"));
|
||||||
|
assertTrue(trendSql.getFirst().contains("LOCATE(LOWER(?), LOWER(COALESCE(f.product,''))) > 0"));
|
||||||
|
assertTrue(trendSql.getFirst().contains("f.product COLLATE utf8mb4_0900_as_cs"));
|
||||||
|
assertTrue(trendSql.getFirst().contains("f.stage=?"));
|
||||||
|
assertFalse(trendSql.getFirst().contains("JOIN fact_bright"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void emptyPeriodReturnsAnEmptyTrendAndZeroCoverage() {
|
||||||
|
JdbcTemplate jdbc = jdbc(false, false);
|
||||||
|
MetricsService service = new MetricsService(jdbc, mock(GovernanceAccessService.class));
|
||||||
|
var query = new MetricsService.MetricsQuery(2026, 3, null, null, null, null, null,
|
||||||
|
"overall", true, RELEASE, "month", Map.of());
|
||||||
|
|
||||||
|
MetricsService.MetricTrendSnapshot result = service.calculateTrend(query, actor);
|
||||||
|
|
||||||
|
assertTrue(result.trend().isEmpty());
|
||||||
|
assertEquals(0L, result.coverage().get("rawRows"));
|
||||||
|
assertEquals(0L, result.coverage().get("includedRows"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JdbcTemplate jdbc(boolean emitAggregates, boolean emitCoverage) {
|
||||||
|
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||||
|
when(jdbc.queryForObject(contains("metric_rollup_build"), eq(Integer.class), any(Object[].class))).thenReturn(0);
|
||||||
|
when(jdbc.queryForObject("SELECT rule_version FROM data_release WHERE id=?", String.class, RELEASE))
|
||||||
|
.thenReturn(BusinessRowMapper.RULE_VERSION);
|
||||||
|
when(jdbc.query(eq("SELECT id,name,status FROM data_release WHERE id=?"), any(RowMapper.class), eq(RELEASE)))
|
||||||
|
.thenAnswer(invocation -> {
|
||||||
|
RowMapper<?> mapper = invocation.getArgument(1);
|
||||||
|
ResultSet row = mock(ResultSet.class);
|
||||||
|
when(row.getString(1)).thenReturn(RELEASE);
|
||||||
|
when(row.getString(2)).thenReturn("Trend fixture");
|
||||||
|
when(row.getString(3)).thenReturn("PUBLISHED");
|
||||||
|
return List.of(mapper.mapRow(row, 0));
|
||||||
|
});
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
String sql = invocation.getArgument(0);
|
||||||
|
RowCallbackHandler callback = invocation.getArgument(1);
|
||||||
|
Object[] invocationArgs = invocation.getArguments();
|
||||||
|
Object[] args = Arrays.copyOfRange(invocationArgs, 2, invocationArgs.length);
|
||||||
|
if (sql.contains("SELECT f.month_key,")) {
|
||||||
|
if (emitCoverage) emitCoverageRow(callback, sql, args);
|
||||||
|
} else if (emitAggregates) {
|
||||||
|
emitAggregateRows(callback, sql, args);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}).when(jdbc).query(anyString(), any(RowCallbackHandler.class), any(Object[].class));
|
||||||
|
return jdbc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void emitCoverageRow(RowCallbackHandler callback, String sql, Object[] args) throws Exception {
|
||||||
|
String stage = stage(sql, args);
|
||||||
|
ResultSet row = mock(ResultSet.class);
|
||||||
|
when(row.getString("month_key")).thenReturn("2026-03");
|
||||||
|
when(row.getLong("row_count")).thenReturn(2L);
|
||||||
|
when(row.getLong("excluded_blank_rows")).thenReturn(0L);
|
||||||
|
when(row.getLong("unmapped_rows")).thenReturn(0L);
|
||||||
|
when(row.getLong("project_unconfigured_rows")).thenReturn(0L);
|
||||||
|
callback.processRow(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void emitAggregateRows(RowCallbackHandler callback, String sql, Object[] args) throws Exception {
|
||||||
|
String stage = stage(sql, args);
|
||||||
|
List<Contribution> contributions = stage.equals("black")
|
||||||
|
? List.of(new Contribution("P1", "90", "10", "100", "2"),
|
||||||
|
new Contribution("P2", "40", "10", "50", "1"))
|
||||||
|
: List.of(new Contribution("P1", "8", "2", "10", "1"),
|
||||||
|
new Contribution("P2", "9", "1", "10", "0"));
|
||||||
|
if (!sql.contains("AS bucket_key")) {
|
||||||
|
BigDecimal good = contributions.stream().map(Contribution::good).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||||
|
BigDecimal scrap = contributions.stream().map(Contribution::scrap).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||||
|
BigDecimal total = contributions.stream().map(Contribution::total).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||||
|
BigDecimal component = contributions.stream().map(Contribution::component).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||||
|
emitAggregateRow(callback, stage, null, good, scrap, total, component, 2L);
|
||||||
|
} else {
|
||||||
|
for (Contribution contribution : contributions)
|
||||||
|
emitAggregateRow(callback, stage, contribution.key(), contribution.good(), contribution.scrap(),
|
||||||
|
contribution.total(), contribution.component(), 1L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void emitAggregateRow(RowCallbackHandler callback, String stage, String key, BigDecimal good,
|
||||||
|
BigDecimal scrap, BigDecimal total, BigDecimal component, long count)
|
||||||
|
throws Exception {
|
||||||
|
ResultSet row = mock(ResultSet.class);
|
||||||
|
when(row.getString("trend_period")).thenReturn("2026-03");
|
||||||
|
if (key != null) when(row.getString("bucket_key")).thenReturn(key);
|
||||||
|
when(row.getLong("row_count")).thenReturn(count);
|
||||||
|
when(row.getBigDecimal("qualified_weight")).thenReturn(good);
|
||||||
|
when(row.getBigDecimal("scrap_weight")).thenReturn(scrap);
|
||||||
|
when(row.getBigDecimal("total_weight")).thenReturn(total);
|
||||||
|
for (String column : List.of("black_responsibility_scrap", "black_material_scrap", "black_external_scrap",
|
||||||
|
"bright_headquarters_scrap", "bright_plating_scrap", "bright_material_scrap",
|
||||||
|
"bright_processing_scrap", "bright_diffusion_scrap"))
|
||||||
|
when(row.getBigDecimal(column)).thenReturn(BigDecimal.ZERO);
|
||||||
|
when(row.getBigDecimal(stage.equals("black") ? "black_responsibility_scrap" : "bright_plating_scrap"))
|
||||||
|
.thenReturn(component);
|
||||||
|
callback.processRow(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String stage(String sql, Object[] args) {
|
||||||
|
if (sql.contains("JOIN fact_black f")) return "black";
|
||||||
|
if (sql.contains("JOIN fact_bright f")) return "bright";
|
||||||
|
for (Object value : args) if ("black".equals(value) || "bright".equals(value)) return String.valueOf(value);
|
||||||
|
return "black";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> capturedSql(JdbcTemplate jdbc) {
|
||||||
|
var details = mockingDetails(jdbc).getInvocations();
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
for (var invocation : details) {
|
||||||
|
if (invocation.getMethod().getName().equals("query") && invocation.getArguments().length > 0
|
||||||
|
&& invocation.getArguments()[0] instanceof String sql) result.add(sql);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Contribution(String key, String goodText, String scrapText, String totalText, String componentText) {
|
||||||
|
BigDecimal good() { return new BigDecimal(goodText); }
|
||||||
|
BigDecimal scrap() { return new BigDecimal(scrapText); }
|
||||||
|
BigDecimal total() { return new BigDecimal(totalText); }
|
||||||
|
BigDecimal component() { return new BigDecimal(componentText); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,7 +61,12 @@ server {
|
|||||||
proxy_cookie_flags XSRF-TOKEN secure samesite=strict;
|
proxy_cookie_flags XSRF-TOKEN secure samesite=strict;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 静态文本压缩只在站点根目录启用;API 的 SSE 代理缓冲仍保持关闭。
|
||||||
location / {
|
location / {
|
||||||
|
gzip on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_types text/plain text/css application/javascript application/json image/svg+xml application/xml;
|
||||||
try_files $uri $uri/ /index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# 全系统统一加载实现与验收
|
||||||
|
|
||||||
|
## 范围与约束
|
||||||
|
|
||||||
|
六类查询、来源明细、数据接入、规则、对应关系、基础数据、权限审计、任务监控、智能分析和导出共用现有 api.ts 的请求协调层。保留现有布局、主题、计算公式和来源数据;保留完整下载及前端分页、全范围搜索排序、Excel 全量导出。
|
||||||
|
|
||||||
|
## 实现契约
|
||||||
|
|
||||||
|
- GET 同键合并、最多 4 个在途读取;订阅者独立取消,最后一个退出才取消底层请求。身份、授权和版本变化中止旧读取,旧响应不得提交或导出。
|
||||||
|
- 会话内存 LRU 上限 32 MiB;按用户、权限、数据发布及规范化参数隔离,不持久化业务结果。工作区校验合并,按资源失效,隐藏页面和未选管理页签不主动刷新。
|
||||||
|
- 工作区授权变化立即撤下旧结果;工作区本身 403 同样阻断,恢复后重新核实身份并重建页面。单资源 403 仅触发重验,避免重复预读循环。
|
||||||
|
- 普通读取 30 秒、身份/连接校验 8 秒,预算覆盖正文读取;只读网络失败和 502/503/504 最多延迟 1 秒重试一次。写入、上传、任务提交不自动重发。文件传输 900 秒;模型事件流不套普通查询超时。
|
||||||
|
- 首次加载保留框架,150 毫秒后才显示忙碌;更新保留成功结果并标注其期间。首次错误有重试,更新错误保留旧结果并阻断旧范围的明细、钻取和导出;只有成功的空结果显示空态。
|
||||||
|
- 页面返回保留筛选、页码及滚动位置;表格按查询条件识别分页范围,缓存读取的新对象不重置分页。隐藏时保留表格已知高度,避免返回时滚动被临时零高度夹紧。
|
||||||
|
- 轮询按上次请求完成后排下一轮:任务 15 秒、活动操作 2 秒、分析会话 5 秒;隐藏暂停、返回立即核对。已知任务编号继续恢复,未保存输入保留。
|
||||||
|
- 保留 280 毫秒页面淡化、520 毫秒数值/图表过渡及减少动态效果设置;图表接近可见区域才初始化,不良构成按需读取。
|
||||||
|
- GET /api/metrics/trend 直接按期间聚合,返回 release/context/trend/coverage,不计算或返回产品完整表。汇总与趋势绑定同一 release 并行读取;原 /api/metrics 契约保留。
|
||||||
|
- 后端对超过 1 KiB 的 JSON/problem+json 开 gzip;Nginx 仅补静态文本压缩,保留 HTTPS、事件流不缓冲及 900 秒代理时限。Excel、压缩包、SSE 不参与 JSON 压缩。
|
||||||
|
- 诊断仅保存类别、耗时、字节、状态、重试次数;不记录业务正文、凭据及完整查询地址。
|
||||||
|
|
||||||
|
## 验证证据
|
||||||
|
|
||||||
|
隔离当前发布快照,关闭分析及报告后台写入;原接口与轻量趋势 36 组对照通过,覆盖维度、月/季/年、黑片/亮片、期间、产品选择/排除及来源字段。趋势最大解压 JSON 17,286 字节;原产品接口 7,485,818 字节,gzip 后 1,381,397 字节。
|
||||||
|
|
||||||
|
真实 Chrome、1440×900、10 Mbps、100 毫秒延迟、4 倍 CPU 降速、禁用浏览器缓存,每类独立冷加载 20 次。计时从导航开始,到趋势响应正文完成且非忙碌 SVG 的首个绘制帧:
|
||||||
|
|
||||||
|
| 页面 | 次数 | 趋势可见 P95 | 最大原始趋势响应 |
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
| 产品 | 20 | 1,762.8 ms | 17,251 B |
|
||||||
|
| 黑片 | 20 | 1,996.4 ms | 11,856 B |
|
||||||
|
| 亮片 | 20 | 1,899.1 ms | 13,276 B |
|
||||||
|
|
||||||
|
黑片最慢单次为 2,026.4 ms,P95 仍小于 2 秒。该单次从导航到请求开始 1,732.4 ms;请求至正文结束 141.1 ms(其中首字节前 135.5 ms,包含模拟往返与服务端等待,未冒充独立服务端耗时);正文结束到可见帧 152.9 ms。性能数据是隔离快照的实验结果,不承诺所有设备或完整表格首屏都在 2 秒内。
|
||||||
|
|
||||||
|
真实返回验收:亮片第 2 页、scrollY=939.5,切产品再返回后页码与 scrollY 不变;返回期间指标/趋势底层请求数量不增加。六查询视图及桌面/390×844 手机六主题均有图表,无页面横向溢出。首次趋势失败显示错误和重试,汇总表仍可读,重试后恢复。竞态、共享取消、权限变更、首错/更新错、轮询与任务恢复由行为回归覆盖。
|
||||||
|
|
||||||
|
完整记录保存在本机 output/unified-loading-20261102:interface-comparison.json、browser-performance.json、cache-navigation.json、visual-checks.json、query-smoke.json 和截图。
|
||||||
|
|
||||||
|
## 发布与回退
|
||||||
|
|
||||||
|
一次集成发布:验证和冻结源码/产物 → 同步 Gitea → 备份实际运行 JAR、前端真实目标和 Nginx 配置 → 确认无活动任务 → 启动兼容旧前端的新后端 → 合并静态压缩配置并验证 Nginx → 原子切换新前端 → HTTPS/资源哈希/真实页面验收。
|
||||||
|
|
||||||
|
回退使用发布时捕获的实际运行 JAR 路径及 SHA、旧前端目录、原 Nginx 配置,不能依据陈旧 manifest 推断后端。保留旧哈希资源供已打开浏览器继续加载。无需数据库结构迁移,不恢复或重写业务数据。
|
||||||
@@ -4,6 +4,7 @@ import { Alert, App, Button, Form, Input, Modal, Select, Spin, Switch, Tag } fro
|
|||||||
import { SettingOutlined } from '@ant-design/icons';
|
import { SettingOutlined } from '@ant-design/icons';
|
||||||
import { api } from './api';
|
import { api } from './api';
|
||||||
import { effectiveThinkingEffort, supportsThinkingEffort } from './analysisThinking';
|
import { effectiveThinkingEffort, supportsThinkingEffort } from './analysisThinking';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
|
|
||||||
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean; thinkingEnabled: boolean; thinkingEffort: string };
|
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean; thinkingEnabled: boolean; thinkingEffort: string };
|
||||||
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; thinkingEnabled: boolean; thinkingEffort: string; profiles: AnalysisModelProfile[] };
|
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; thinkingEnabled: boolean; thinkingEffort: string; profiles: AnalysisModelProfile[] };
|
||||||
@@ -19,6 +20,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
|||||||
useEffect(() => { if (!effortSupported) form.setFieldValue('thinkingEffort', 'auto'); }, [effortSupported, form]);
|
useEffect(() => { if (!effortSupported) form.setFieldValue('thinkingEffort', 'auto'); }, [effortSupported, form]);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const showLoading = useDelayedIndicator(loading, 150);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [testing, setTesting] = useState(false);
|
const [testing, setTesting] = useState(false);
|
||||||
const [settings, setSettings] = useState<AnalysisModelSettings>();
|
const [settings, setSettings] = useState<AnalysisModelSettings>();
|
||||||
@@ -26,10 +28,11 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
|||||||
const selectedProfile = settings?.profiles.find(profile => profile.id === profileId);
|
const selectedProfile = settings?.profiles.find(profile => profile.id === profileId);
|
||||||
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
|
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
|
||||||
const sequence = useRef(0);
|
const sequence = useRef(0);
|
||||||
|
const submitLock = useRef(false);
|
||||||
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
|
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
const current = ++sequence.current;
|
const current = ++sequence.current;
|
||||||
setOpen(true); setLoading(true); setSettings(undefined); setProfileId(undefined); setNotice(undefined); form.resetFields();
|
setOpen(true); setLoading(true); setNotice(undefined);
|
||||||
try {
|
try {
|
||||||
const value = await api.analysisSettings();
|
const value = await api.analysisSettings();
|
||||||
if (sequence.current !== current) return;
|
if (sequence.current !== current) return;
|
||||||
@@ -39,9 +42,10 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
|||||||
} finally { if (sequence.current === current) setLoading(false); }
|
} finally { if (sequence.current === current) setLoading(false); }
|
||||||
};
|
};
|
||||||
const submit = async (test: boolean) => {
|
const submit = async (test: boolean) => {
|
||||||
if (!settings) return;
|
if (!settings || submitLock.current) return;
|
||||||
let values: AnalysisModelSettingsInput;
|
let values: AnalysisModelSettingsInput;
|
||||||
try { values = await form.validateFields(); } catch { return; }
|
try { values = await form.validateFields(); } catch { return; }
|
||||||
|
submitLock.current = true;
|
||||||
const current = sequence.current;
|
const current = sequence.current;
|
||||||
setNotice(undefined); test ? setTesting(true) : setSaving(true);
|
setNotice(undefined); test ? setTesting(true) : setSaving(true);
|
||||||
try {
|
try {
|
||||||
@@ -57,7 +61,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
|
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
|
||||||
} finally { if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
} finally { submitLock.current = false; if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
||||||
};
|
};
|
||||||
return <>
|
return <>
|
||||||
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
|
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
|
||||||
@@ -66,7 +70,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
|||||||
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
|
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
|
||||||
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
|
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
|
||||||
</>}>
|
</>}>
|
||||||
{loading ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
{showLoading && !settings ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
||||||
{settings && <div style={{ marginBottom: 20 }}>
|
{settings && <div style={{ marginBottom: 20 }}>
|
||||||
<div style={{ marginBottom: 8 }}>选择配置 <Tag color="blue">当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}</Tag></div>
|
<div style={{ marginBottom: 8 }}>选择配置 <Tag color="blue">当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}</Tag></div>
|
||||||
<div style={{ display: 'flex', gap: 8 }}>
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './ana
|
|||||||
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||||
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
|
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
|
||||||
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
|
|
||||||
type Row = Record<string, unknown>;
|
type Row = Record<string, unknown>;
|
||||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||||
@@ -219,6 +220,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
|||||||
}) {
|
}) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [exporting, setExporting] = useState(false);
|
const [exporting, setExporting] = useState(false);
|
||||||
|
const showExporting = useDelayedIndicator(exporting, 150);
|
||||||
const [progress, setProgress] = useState('');
|
const [progress, setProgress] = useState('');
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [stamp, setStamp] = useState('');
|
const [stamp, setStamp] = useState('');
|
||||||
@@ -239,6 +241,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
|||||||
const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown });
|
const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown });
|
||||||
currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown };
|
currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown };
|
||||||
const visualReport = useReportVisualImages(turn, open);
|
const visualReport = useReportVisualImages(turn, open);
|
||||||
|
const showVisualLoading = useDelayedIndicator(visualReport.loading, 150);
|
||||||
const safeHtml = useMemo(() => {
|
const safeHtml = useMemo(() => {
|
||||||
if (parseServerReadingSummary(reportTurn)) return '';
|
if (parseServerReadingSummary(reportTurn)) return '';
|
||||||
if (!reportHtml?.trim()) return '';
|
if (!reportHtml?.trim()) return '';
|
||||||
@@ -358,10 +361,10 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
|||||||
: <Button disabled={disabled} onClick={() => void saveHtml()}>下载 HTML</Button>}
|
: <Button disabled={disabled} onClick={() => void saveHtml()}>下载 HTML</Button>}
|
||||||
{prepared
|
{prepared
|
||||||
? <Button type="primary" disabled={disabled} onClick={() => void downloadPrepared(prepared, 'image')}>下载长图</Button>
|
? <Button type="primary" disabled={disabled} onClick={() => void downloadPrepared(prepared, 'image')}>下载长图</Button>
|
||||||
: <Button type="primary" loading={exporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
: <Button type="primary" loading={showExporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||||
</>}>
|
</>}>
|
||||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
{showVisualLoading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||||
{progress && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
{progress && (!exporting || showExporting) && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||||
{error && <Alert className="analysis-report-export-error" type="error" showIcon title={error} closable onClose={() => setError('')} />}
|
{error && <Alert className="analysis-report-export-error" type="error" showIcon title={error} closable onClose={() => setError('')} />}
|
||||||
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
||||||
{visualReport.authorizationError && visualReport.authorizationError !== error && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
{visualReport.authorizationError && visualReport.authorizationError !== error && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { Alert, Button, Select, Switch, Tag } from 'antd';
|
import { Alert, Button, Select, Switch, Tag } from 'antd';
|
||||||
import { api } from './api';
|
import { api } from './api';
|
||||||
|
import { usePageCache, useMaintenanceRefresh } from './pageCache';
|
||||||
|
import { useDelayedBusy } from './useDelayedBusy';
|
||||||
|
|
||||||
const labels: Record<string, string> = { MONTH: '月报', QUARTER: '季报', YEAR: '年报' };
|
const labels: Record<string, string> = { MONTH: '月报', QUARTER: '季报', YEAR: '年报' };
|
||||||
export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }: {
|
export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }: {
|
||||||
@@ -10,15 +12,26 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
|||||||
const [plans, setPlans] = useState<Record<string, unknown>[]>([]);
|
const [plans, setPlans] = useState<Record<string, unknown>[]>([]);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [reportsLoaded, setReportsLoaded] = useState(false);
|
||||||
|
const [plansLoaded, setPlansLoaded] = useState(false);
|
||||||
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
const { active } = usePageCache();
|
||||||
|
const read = useDelayedBusy();
|
||||||
|
const actionInFlight = useRef(false);
|
||||||
const [runDay, setRunDay] = useState(1);
|
const [runDay, setRunDay] = useState(1);
|
||||||
const load = async () => {
|
const load = useCallback(() => read.run(async () => {
|
||||||
try {
|
const [history, savedPlans] = await Promise.allSettled([api.analysisReports(), api.analysisReportPlans()]);
|
||||||
const [history, savedPlans] = await Promise.all([api.analysisReports(), api.analysisReportPlans()]);
|
const errors: string[] = [];
|
||||||
setReports(history.items || []); setPlans(savedPlans.items || []);
|
if (history.status === 'fulfilled') { setReports(history.value.items || []); setReportsLoaded(true); }
|
||||||
} catch (value) { setError(value instanceof Error ? value.message : '报告读取失败'); }
|
else errors.push(`报告列表:${history.reason instanceof Error ? history.reason.message : '读取失败'}`);
|
||||||
};
|
if (savedPlans.status === 'fulfilled') { setPlans(savedPlans.value.items || []); setPlansLoaded(true); }
|
||||||
useEffect(() => { void load(); }, []);
|
else errors.push(`自动计划:${savedPlans.reason instanceof Error ? savedPlans.reason.message : '读取失败'}`);
|
||||||
|
setError(errors.join(';'));
|
||||||
|
}), [read.run]);
|
||||||
|
useEffect(() => { if (active && expanded && (!reportsLoaded || !plansLoaded)) void load(); }, [active, expanded, reportsLoaded, plansLoaded, load]);
|
||||||
|
useMaintenanceRefresh(() => { if (expanded) void load(); });
|
||||||
const generate = async () => {
|
const generate = async () => {
|
||||||
|
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||||
setBusy(true); setError('');
|
setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
const response = await api.createAnalysisReport({ periodType, periodKey });
|
const response = await api.createAnalysisReport({ periodType, periodKey });
|
||||||
@@ -27,9 +40,10 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
|||||||
if (typeof sessionId === 'string' && typeof turnId === 'string') onOpen(sessionId, turnId);
|
if (typeof sessionId === 'string' && typeof turnId === 'string') onOpen(sessionId, turnId);
|
||||||
else setError('报告已登记,正在准备分析任务,请稍后刷新列表。');
|
else setError('报告已登记,正在准备分析任务,请稍后刷新列表。');
|
||||||
} catch (value) { setError(value instanceof Error ? value.message : '报告生成失败'); }
|
} catch (value) { setError(value instanceof Error ? value.message : '报告生成失败'); }
|
||||||
finally { setBusy(false); }
|
finally { actionInFlight.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const toggle = async (type: string, enabled: boolean) => {
|
const toggle = async (type: string, enabled: boolean) => {
|
||||||
|
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||||
setBusy(true); setError('');
|
setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
const found = plans.find(plan => plan.periodType === type || plan.reportType === type);
|
const found = plans.find(plan => plan.periodType === type || plan.reportType === type);
|
||||||
@@ -38,24 +52,27 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
|||||||
else await api.createAnalysisReportPlan(body);
|
else await api.createAnalysisReportPlan(body);
|
||||||
await load();
|
await load();
|
||||||
} catch (value) { setError(value instanceof Error ? value.message : '报告计划保存失败'); }
|
} catch (value) { setError(value instanceof Error ? value.message : '报告计划保存失败'); }
|
||||||
finally { setBusy(false); }
|
finally { actionInFlight.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const saveDay = async () => {
|
const saveDay = async () => {
|
||||||
|
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||||
setBusy(true); setError('');
|
setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
await Promise.all(plans.map(plan => api.updateAnalysisReportPlan(String(plan.id), { runDay, runHour: 9 })));
|
await Promise.all(plans.map(plan => api.updateAnalysisReportPlan(String(plan.id), { runDay, runHour: 9 })));
|
||||||
await load();
|
await load();
|
||||||
} catch (value) { setError(value instanceof Error ? value.message : '执行日期保存失败'); }
|
} catch (value) { setError(value instanceof Error ? value.message : '执行日期保存失败'); }
|
||||||
finally { setBusy(false); }
|
finally { actionInFlight.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
return <details className="analysis-reports"><summary>月报、季报与年报</summary>
|
return <details className="analysis-reports" onToggle={event => setExpanded(event.currentTarget.open)}><summary>月报、季报与年报</summary>
|
||||||
<p>报告使用统一指标与同一分析任务,包含期间比较、趋势和异常追查。自动计划在本机服务运行时执行。</p>
|
<p>报告使用统一指标与同一分析任务,包含期间比较、趋势和异常追查。自动计划在本机服务运行时执行。</p>
|
||||||
{error && <Alert type="warning" showIcon message={error} />}
|
{error && <Alert type="error" showIcon message="报告信息读取失败" description={reportsLoaded || plansLoaded ? `${error};成功读取的内容仍保留。` : error} action={!reportsLoaded || !plansLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||||
|
{read.busy && !reportsLoaded && !plansLoaded && <div className="loading-panel">正在读取报告与自动计划…</div>}
|
||||||
<div className="ai-actions"><span>{periodKey} · {labels[periodType]} · 总体范围</span><Button disabled={disabled || busy} loading={busy} onClick={() => void generate()}>生成本期{labels[periodType]}</Button><Button disabled={busy} onClick={() => void load()}>刷新报告</Button></div>
|
<div className="ai-actions"><span>{periodKey} · {labels[periodType]} · 总体范围</span><Button disabled={disabled || busy} loading={busy} onClick={() => void generate()}>生成本期{labels[periodType]}</Button><Button disabled={busy} onClick={() => void load()}>刷新报告</Button></div>
|
||||||
<div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
{plansLoaded && <div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
||||||
{Object.entries(labels).map(([type, label]) => { const plan = plans.find(item => item.periodType === type || item.reportType === type); return <label key={type}>{label} <Switch aria-label={`自动${label}`} disabled={busy} checked={plan?.enabled === true} onChange={value => void toggle(type, value)} /></label>; })}
|
{Object.entries(labels).map(([type, label]) => { const plan = plans.find(item => item.periodType === type || item.reportType === type); return <label key={type}>{label} <Switch aria-label={`自动${label}`} disabled={busy} checked={plan?.enabled === true} onChange={value => void toggle(type, value)} /></label>; })}
|
||||||
<Button size="small" disabled={busy || !plans.length} onClick={() => void saveDay()}>保存执行日期</Button>
|
<Button size="small" disabled={busy || !plans.length} onClick={() => void saveDay()}>保存执行日期</Button>
|
||||||
</div>
|
</div>}
|
||||||
{reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
{reportsLoaded && reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
||||||
|
{reportsLoaded && !reports.length && <p className="completion-note">当前没有已生成的报告。</p>}
|
||||||
</details>;
|
</details>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
visualUnitLabel,
|
visualUnitLabel,
|
||||||
} from './analysisVisualsModel';
|
} from './analysisVisualsModel';
|
||||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
||||||
import './analysis-visuals.css';
|
import './analysis-visuals.css';
|
||||||
|
|
||||||
@@ -126,9 +127,11 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
|||||||
const [nearViewport, setNearViewport] = useState(false);
|
const [nearViewport, setNearViewport] = useState(false);
|
||||||
const [chartReady, setChartReady] = useState(false);
|
const [chartReady, setChartReady] = useState(false);
|
||||||
const [chartLoading, setChartLoading] = useState(false);
|
const [chartLoading, setChartLoading] = useState(false);
|
||||||
|
const showChartLoading = useDelayedIndicator(chartLoading, 150);
|
||||||
const [chartError, setChartError] = useState('');
|
const [chartError, setChartError] = useState('');
|
||||||
const [dataOpen, setDataOpen] = useState(false);
|
const [dataOpen, setDataOpen] = useState(false);
|
||||||
const [exporting, setExporting] = useState(false);
|
const [exporting, setExporting] = useState(false);
|
||||||
|
const showExporting = useDelayedIndicator(exporting, 150);
|
||||||
const [exportError, setExportError] = useState('');
|
const [exportError, setExportError] = useState('');
|
||||||
const [themeRevision, setThemeRevision] = useState(0);
|
const [themeRevision, setThemeRevision] = useState(0);
|
||||||
const [renderAttempt, setRenderAttempt] = useState(0);
|
const [renderAttempt, setRenderAttempt] = useState(0);
|
||||||
@@ -312,9 +315,9 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
|||||||
<Button size="small" icon={<TableOutlined />} onClick={openData}>查看数据</Button>
|
<Button size="small" icon={<TableOutlined />} onClick={openData}>查看数据</Button>
|
||||||
<Dropdown
|
<Dropdown
|
||||||
trigger={['click']}
|
trigger={['click']}
|
||||||
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: exporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: showExporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
||||||
>
|
>
|
||||||
<Button size="small" aria-label="更多图表操作" icon={exporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
<Button size="small" aria-label="更多图表操作" icon={showExporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -337,7 +340,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
|||||||
style={visual.type === 'heatmap' ? { minWidth: Math.max(380, visual.categories.length * 62 + 160) }
|
style={visual.type === 'heatmap' ? { minWidth: Math.max(380, visual.categories.length * 62 + 160) }
|
||||||
: visual.type === 'pareto' ? { minWidth: Math.max(600, visual.categories.length * 90 + 180) } : undefined} />
|
: visual.type === 'pareto' ? { minWidth: Math.max(600, visual.categories.length * 90 + 180) } : undefined} />
|
||||||
{!nearViewport && <div className="analysis-visual-placeholder">图表将在进入视口时加载</div>}
|
{!nearViewport && <div className="analysis-visual-placeholder">图表将在进入视口时加载</div>}
|
||||||
{nearViewport && chartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
{nearViewport && showChartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||||||
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}
|
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}
|
||||||
<Button size="small" loading={retrying || chartLoading} onKeyDown={event => event.stopPropagation()}
|
<Button size="small" loading={retrying || chartLoading} onKeyDown={event => event.stopPropagation()}
|
||||||
onClick={event => { event.stopPropagation(); void retryChart(); }}>重试图表</Button>
|
onClick={event => { event.stopPropagation(); void retryChart(); }}>重试图表</Button>
|
||||||
|
|||||||
@@ -1,19 +1,29 @@
|
|||||||
|
import { readQueryLocation } from './queryLoadingScope';
|
||||||
import { flushSync } from 'react-dom';
|
import { flushSync } from 'react-dom';
|
||||||
import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition';
|
import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition';
|
||||||
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
||||||
import { Alert, Button, Spin } from 'antd';
|
import { Alert, Button, Spin } from 'antd';
|
||||||
import { api } from './api';
|
import { api, configureRequestScope, resetRequestScope } from './api';
|
||||||
|
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';
|
||||||
|
|
||||||
const QueryPage = lazy(() => import('./QueryPage'));
|
const loadQueryPage = () => import('./QueryPage');
|
||||||
const StageProductPage = lazy(() => import('./StageProductPage'));
|
const loadStageProductPage = () => import('./StageProductPage');
|
||||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
const loadManagementPages = () => import('./ManagementPages');
|
||||||
|
const QueryPage = lazy(loadQueryPage);
|
||||||
|
const StageProductPage = lazy(loadStageProductPage);
|
||||||
|
const ManagementPages = lazy(loadManagementPages);
|
||||||
|
|
||||||
|
export function preloadWorkspacePage(page: PageKey): Promise<unknown> {
|
||||||
|
return page === 'blackProduct' || page === 'brightProduct' ? loadStageProductPage()
|
||||||
|
: QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages();
|
||||||
|
}
|
||||||
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
|
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
|
||||||
const retained = (_page: PageKey) => true;
|
const retained = (_page: PageKey) => true;
|
||||||
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number };
|
type Entry = { initialSearch: string; search: string; key: number; scroll: number; revision?: number };
|
||||||
export type WorkspaceNavigation = { navigate: (page: PageKey, query?: QueryParams, resultRef?: ResultRef) => void; syncLocation: () => void };
|
export type WorkspaceNavigation = { navigate: (page: PageKey, query?: QueryParams, resultRef?: ResultRef) => void; syncLocation: () => void };
|
||||||
function encode(value: unknown) {
|
function encode(value: unknown) {
|
||||||
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
||||||
@@ -23,10 +33,12 @@ function encode(value: unknown) {
|
|||||||
export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||||
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
|
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
|
||||||
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
|
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
|
||||||
|
const userRef = useRef(user);
|
||||||
|
userRef.current = user;
|
||||||
const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]]));
|
const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]]));
|
||||||
const requested = useRef(page);
|
const requested = useRef(page);
|
||||||
const current = useRef(page), generation = useRef(0), key = useRef(0);
|
const current = useRef(page), generation = useRef(0), key = useRef(0);
|
||||||
const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null);
|
const revisions = useRef<{ authRevision: string; dataRevision: string; currentReleaseId: string | null } | null>(null);
|
||||||
const validation = useRef<Promise<boolean> | null>(null);
|
const validation = useRef<Promise<boolean> | null>(null);
|
||||||
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
|
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
|
||||||
const [ready, setReady] = useState(false), [error, setError] = useState('');
|
const [ready, setReady] = useState(false), [error, setError] = useState('');
|
||||||
@@ -38,28 +50,47 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
|||||||
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||||
busy => { if (alive.current) setNavigationBusy(busy); },
|
busy => { if (alive.current) setNavigationBusy(busy); },
|
||||||
);
|
);
|
||||||
const validate = () => {
|
const validate = (warmVisibleOptions = false) => {
|
||||||
if (validation.current) return validation.current;
|
if (validation.current) return validation.current;
|
||||||
const epoch = generation.current;
|
const epoch = generation.current;
|
||||||
const request = (async () => {
|
const request = (async () => {
|
||||||
try {
|
try {
|
||||||
const state = await api.workspaceState();
|
const state = await api.workspaceState();
|
||||||
if (!alive.current || generation.current !== epoch) return false;
|
if (!alive.current || generation.current !== epoch) return false;
|
||||||
if (revisions.current && state.authRevision !== revisions.current.authRevision) {
|
configureRequestScope({ userId: userRef.current.id, ...state });
|
||||||
|
if ((revisions.current && state.authRevision !== revisions.current.authRevision) || entries.current.size === 0) {
|
||||||
|
// 已知授权变化时立即撤下旧结果,不能等待身份读取成功才清除。
|
||||||
|
setReady(false);
|
||||||
|
entries.current.clear();
|
||||||
|
render(value => value + 1);
|
||||||
const latest = await api.me();
|
const latest = await api.me();
|
||||||
if (!alive.current || generation.current !== epoch) return false;
|
if (!alive.current || generation.current !== epoch) return false;
|
||||||
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
|
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
|
||||||
transitions.current?.cancel(); requested.current = current.current;
|
transitions.current?.cancel(); requested.current = current.current;
|
||||||
|
userRef.current = latest;
|
||||||
|
configureRequestScope({ userId: latest.id, ...state });
|
||||||
onUserChange(latest); entries.current.clear();
|
onUserChange(latest); entries.current.clear();
|
||||||
entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 });
|
entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 });
|
||||||
render(value => value + 1);
|
render(value => value + 1);
|
||||||
}
|
}
|
||||||
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
|
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
|
||||||
revisions.current = state;
|
revisions.current = state;
|
||||||
|
render(value => value + 1);
|
||||||
setError('');
|
setError('');
|
||||||
|
// The visible query needs these options; start their shared read before its code mounts.
|
||||||
|
if (warmVisibleOptions && QUERY_PAGES.includes(requested.current)) {
|
||||||
|
void api.options().catch(() => {});
|
||||||
|
if (requested.current === 'blackProduct' || requested.current === 'brightProduct') {
|
||||||
|
const explicitRelease = readQueryLocation(entries.current.get(requested.current)?.initialSearch || '').releaseId;
|
||||||
|
void api.sourceColumnCatalog(explicitRelease || state.currentReleaseId || undefined).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
setReady(true);
|
setReady(true);
|
||||||
return true;
|
return true;
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
|
if (alive.current && generation.current === epoch && value && typeof value === 'object' && 'status' in value && value.status === 403) {
|
||||||
|
setReady(false); entries.current.clear(); resetRequestScope();
|
||||||
|
}
|
||||||
if (alive.current && generation.current === epoch && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
|
if (alive.current && generation.current === epoch && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -79,6 +110,11 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
|||||||
const entry = entries.current.get(next)!;
|
const entry = entries.current.get(next)!;
|
||||||
requested.current = next;
|
requested.current = next;
|
||||||
transitions.current!.run(async signal => {
|
transitions.current!.run(async signal => {
|
||||||
|
// 先核实权限与版本,再让已保留页面重新订阅,避免旧版本内容先闪出。
|
||||||
|
if (!await validate(true) || signal.aborted) {
|
||||||
|
if (!signal.aborted && requested.current === next) requested.current = current.current;
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!alive.current || entries.current.get(next) !== entry) return;
|
if (!alive.current || entries.current.get(next) !== entry) return;
|
||||||
// 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
|
// 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
|
||||||
flushSync(() => {
|
flushSync(() => {
|
||||||
@@ -86,8 +122,8 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
|||||||
current.current = next; onPageChange(next); render(value => value + 1);
|
current.current = next; onPageChange(next); render(value => value + 1);
|
||||||
});
|
});
|
||||||
window.scrollTo(0, entry.scroll);
|
window.scrollTo(0, entry.scroll);
|
||||||
void validate();
|
|
||||||
await waitForWorkspaceContent(() => document.querySelector(`.page-view[data-page="${next}"]`), signal);
|
await waitForWorkspaceContent(() => document.querySelector(`.page-view[data-page="${next}"]`), signal);
|
||||||
|
if (!signal.aborted && current.current === next && entries.current.get(next) === entry) window.scrollTo(0, entry.scroll);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
|
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
|
||||||
@@ -105,10 +141,22 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
|||||||
} }));
|
} }));
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
alive.current = true;
|
alive.current = true;
|
||||||
void validate();
|
configureRequestScope({ userId: userRef.current.id, authRevision: null, dataRevision: null, currentReleaseId: null });
|
||||||
const invalidate = () => setRefreshKey(value => value + 1);
|
void validate(true);
|
||||||
|
const invalidate = (event: Event) => {
|
||||||
|
const resources = (event as CustomEvent<{ resources?: string[] }>).detail?.resources;
|
||||||
|
for (const [name, entry] of entries.current) {
|
||||||
|
if (pageUsesResources(name, resources)) entry.revision = (entry.revision || 0) + 1;
|
||||||
|
}
|
||||||
|
render(value => value + 1);
|
||||||
|
void validate();
|
||||||
|
};
|
||||||
|
const foreground = () => { if (document.visibilityState === 'visible') void validate(); };
|
||||||
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
||||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
window.addEventListener('quality-permission-recheck', foreground);
|
||||||
|
window.addEventListener('focus', foreground);
|
||||||
|
document.addEventListener('visibilitychange', foreground);
|
||||||
|
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; resetRequestScope(); window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); window.removeEventListener('quality-permission-recheck', foreground); window.removeEventListener('focus', foreground); document.removeEventListener('visibilitychange', foreground); };
|
||||||
}, []);
|
}, []);
|
||||||
const activeEntryKey = entries.current.get(page)?.key;
|
const activeEntryKey = entries.current.get(page)?.key;
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
@@ -121,7 +169,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
|||||||
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
||||||
const active = name === page;
|
const active = name === page;
|
||||||
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, 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} />}
|
{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>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { usePageCache } from './pageCache';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Alert, Button, Select, Spin } from 'antd';
|
import { Alert, Button, Select, Spin } from 'antd';
|
||||||
import { DownOutlined, UpOutlined } from '@ant-design/icons';
|
import { DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||||
@@ -6,6 +8,7 @@ import type { FilterField } from './types';
|
|||||||
import { readableSelectPopup } from './readableSelectPopup';
|
import { readableSelectPopup } from './readableSelectPopup';
|
||||||
|
|
||||||
function FieldSelect({ field, value, onChange, onUnauthorized }: { field: FilterField; value: string[]; onChange: (values: string[]) => void; onUnauthorized: (error: unknown) => boolean }) {
|
function FieldSelect({ field, value, onChange, onUnauthorized }: { field: FilterField; value: string[]; onChange: (values: string[]) => void; onUnauthorized: (error: unknown) => boolean }) {
|
||||||
|
const { active } = 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);
|
||||||
@@ -13,23 +16,25 @@ function FieldSelect({ field, value, onChange, onUnauthorized }: { field: Filter
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [revision, setRevision] = useState(0);
|
const [revision, setRevision] = useState(0);
|
||||||
const generation = useRef(0);
|
const generation = useRef(0);
|
||||||
|
const showLoading = useDelayedIndicator(loading);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const current = ++generation.current;
|
if (!active) return;
|
||||||
|
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).then(result => {
|
api.filterFieldOptions(field.key, search, controller.signal).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); generation.current++; };
|
return () => { window.clearTimeout(timer); controller.abort(); generation.current++; };
|
||||||
}, [field.key, search, revision, onUnauthorized]);
|
}, [active, field.key, search, revision, onUnauthorized]);
|
||||||
return <label className="query-field query-extra-field"><span>{field.label}</span><Select mode="multiple" allowClear showSearch aria-label={field.label}
|
return <label className="query-field query-extra-field"><span>{field.label}</span><Select mode="multiple" allowClear showSearch aria-label={field.label}
|
||||||
{...readableSelectPopup} maxTagCount="responsive" value={value} loading={loading} 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="全部"
|
||||||
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: '空值', value: '__EMPTY__' }] : [])}
|
||||||
notFoundContent={loading ? <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>;
|
/></label>;
|
||||||
}
|
}
|
||||||
@@ -38,22 +43,25 @@ export function ExtraQueryFilters({ projectGroup, projectGroups, onProjectGroup,
|
|||||||
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;
|
||||||
}) {
|
}) {
|
||||||
|
const { active } = usePageCache();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [fields, setFields] = useState<FilterField[]>([]);
|
const [fields, setFields] = useState<FilterField[]>([]);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [revision, setRevision] = useState(0);
|
const [revision, setRevision] = useState(0);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!active || !open) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
api.filterFields().then(result => { if (alive) { setFields(result); setError(''); } }).catch(e => { if (alive && !onUnauthorized(e)) setError(e.message || '筛选字段加载失败'); });
|
const controller = new AbortController();
|
||||||
return () => { alive = false; };
|
api.filterFields(false, controller.signal).then(result => { if (alive) { setFields(result); setError(''); } }).catch(e => { if (alive && !onUnauthorized(e)) setError(e.message || '筛选字段加载失败'); });
|
||||||
}, [revision, onUnauthorized]);
|
return () => { alive = false; controller.abort(); };
|
||||||
|
}, [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]) => `${fields.find(f => f.key === key)?.label || key}:${values.map(v => v === '__EMPTY__' ? '空值' : 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>
|
||||||
{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 && <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>}
|
||||||
{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 => <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); }} />)}
|
||||||
|
|||||||
+289
-139
File diff suppressed because one or more lines are too long
+238
-154
@@ -65,6 +65,9 @@ import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, Source
|
|||||||
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
|
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
|
||||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||||
import { ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
import { ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||||
|
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
|
||||||
|
import { useVisiblePolling } from './useVisiblePolling';
|
||||||
|
import { importIssuePageKey, matchesImportIssuePage } from './importLifecycleGuards';
|
||||||
|
|
||||||
function apiMessage(error: unknown): string {
|
function apiMessage(error: unknown): string {
|
||||||
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
|
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
|
||||||
@@ -248,9 +251,12 @@ function PageHeader({ actions }: { title: string; description?: string; actions?
|
|||||||
}
|
}
|
||||||
|
|
||||||
function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
|
function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
|
||||||
|
const { active } = usePageCache();
|
||||||
const [sources, setSources] = useState<SourceItem[]>([]);
|
const [sources, setSources] = useState<SourceItem[]>([]);
|
||||||
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
|
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [sourcesLoaded, setSourcesLoaded] = useState(false);
|
||||||
|
const [releaseLoaded, setReleaseLoaded] = useState(false);
|
||||||
|
const sourceRead = useDelayedBusy();
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [maintenanceBusy, setMaintenanceBusy] = useState(false);
|
const [maintenanceBusy, setMaintenanceBusy] = useState(false);
|
||||||
const [historyOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
|
const [historyOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
|
||||||
@@ -268,64 +274,85 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
|
|||||||
? { ...previous, ids: previous.ids.filter(value => value !== id) }
|
? { ...previous, ids: previous.ids.filter(value => value !== id) }
|
||||||
: previous.ids.length >= 50 ? previous : { ids: [...previous.ids, id], releaseId: previous.ids.length ? previous.releaseId : currentReleaseId });
|
: previous.ids.length >= 50 ? previous : { ids: [...previous.ids, id], releaseId: previous.ids.length ? previous.releaseId : currentReleaseId });
|
||||||
|
|
||||||
const load = async () => {
|
const load = useCallback(() => sourceRead.run(async () => {
|
||||||
setLoading(true);
|
const failures: string[] = [];
|
||||||
try {
|
const [sourceResult, releaseResult] = await Promise.allSettled([api.sources(), api.releases()]);
|
||||||
const [sourceResult, releaseResult] = await Promise.all([api.sources(), api.releases()]);
|
if (sourceResult.status === 'fulfilled') { setSources(collectionItems(sourceResult.value)); setSourcesLoaded(true); }
|
||||||
setSources(collectionItems(sourceResult)); setCurrentReleaseId(releaseResult.currentReleaseId ?? null); setError('');
|
else if (!onUnauthorized(sourceResult.reason)) failures.push(`来源清单:${apiMessage(sourceResult.reason)}`);
|
||||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
if (releaseResult.status === 'fulfilled') { setCurrentReleaseId(releaseResult.value.currentReleaseId ?? null); setReleaseLoaded(true); }
|
||||||
finally { setLoading(false); }
|
else if (!onUnauthorized(releaseResult.reason)) failures.push(`当前发布版本:${apiMessage(releaseResult.reason)}`);
|
||||||
};
|
setError(failures.join(';'));
|
||||||
useEffect(() => { void load(); }, []);
|
}), [onUnauthorized, sourceRead.run]);
|
||||||
|
useEffect(() => { if (active && (!sourcesLoaded || !releaseLoaded)) void load(); }, [active, sourcesLoaded, releaseLoaded, load]);
|
||||||
useMaintenanceRefresh(load);
|
useMaintenanceRefresh(load);
|
||||||
return <div className="management-page">
|
return <div className="management-page">
|
||||||
{error && <Alert showIcon type="error" message="来源清单读取失败" description={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
{error && <Alert showIcon type="error" message="来源信息读取失败" description={sourcesLoaded || releaseLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||||
<ManagementSections initialKey={historyOpen ? 'history' : 'intake'} items={[
|
<ManagementSections initialKey={historyOpen ? 'history' : 'intake'} items={[
|
||||||
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||||
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} loading={loading} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} sourcesLoaded={sourcesLoaded} loading={sourceRead.busy} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||||
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} onUnauthorized={onUnauthorized} /> },
|
||||||
{ key: 'audit', label: '来源审计', children: <SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
{ key: 'audit', label: '来源审计', children: <SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
||||||
]} />
|
]} />
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ImportHistoryPanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
|
function ImportHistoryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||||
const { active } = usePageCache();
|
const { active } = usePageCache();
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const read = useDelayedBusy();
|
||||||
|
const loading = read.busy;
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(() => read.run(async () => {
|
||||||
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setError(''); }
|
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setLoaded(true); setError(''); }
|
||||||
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||||
finally { setLoading(false); }
|
}), [onUnauthorized, read.run]);
|
||||||
}, [onUnauthorized]);
|
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
|
||||||
useEffect(() => { void load(); }, [load, currentReleaseId]);
|
useVisiblePolling(load, 2000, active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase())));
|
||||||
useEffect(() => { if (active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))) { const timer = window.setTimeout(() => void load(), 2000); return () => window.clearTimeout(timer); } }, [items, load, active]);
|
useMaintenanceRefresh(load);
|
||||||
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span></div>
|
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button></div>
|
||||||
{error && <Alert showIcon type="error" message="导入记录读取失败" description={error} action={<Button onClick={() => void load()}>重试</Button>} />}
|
{error && <Alert showIcon type="error" message="导入记录读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={<Button onClick={() => void load()}>重试</Button>} />}
|
||||||
{loading ? <Spin /> : <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
{loading && !loaded ? <Spin /> : loaded && <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||||
</section>;
|
</section>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) {
|
function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) {
|
||||||
|
const { active } = usePageCache();
|
||||||
const [result, setResult] = useState<Collection | null>(null);
|
const [result, setResult] = useState<Collection | null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loadedRunId, setLoadedRunId] = useState('');
|
||||||
|
const [loadedPage, setLoadedPage] = useState(0);
|
||||||
|
const read = useDelayedBusy();
|
||||||
|
const loading = read.busy;
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
const activeRef = useRef(active); activeRef.current = active;
|
||||||
|
const requestGeneration = useRef(0);
|
||||||
|
const requestRef = useRef<{ key: string; promise: Promise<void> } | null>(null);
|
||||||
|
const load = useCallback(() => {
|
||||||
|
if (!active || !runId) return Promise.resolve();
|
||||||
|
const key = importIssuePageKey(runId, page);
|
||||||
|
if (requestRef.current?.key === key) return requestRef.current.promise;
|
||||||
|
const generation = ++requestGeneration.current;
|
||||||
|
const promise = read.run(async () => {
|
||||||
|
try {
|
||||||
|
const value = await api.importIssues(runId, page, TABLE_PAGE_SIZE);
|
||||||
|
if (generation !== requestGeneration.current || !activeRef.current) return;
|
||||||
|
setResult(value); setLoadedRunId(runId); setLoadedPage(page); setError('');
|
||||||
|
} catch (value) { if (generation === requestGeneration.current && activeRef.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||||
|
}).finally(() => { if (requestRef.current?.promise === promise) requestRef.current = null; });
|
||||||
|
requestRef.current = { key, promise };
|
||||||
|
return promise;
|
||||||
|
}, [active, onUnauthorized, page, read.run, runId]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!runId) return;
|
if (active && runId && (loadedRunId !== runId || loadedPage !== page)) void load();
|
||||||
let alive = true;
|
}, [active, loadedPage, loadedRunId, load, page, runId]);
|
||||||
setLoading(true);
|
const items = loadedRunId === runId ? unwrapItems(result).items : [];
|
||||||
api.importIssues(runId, page, TABLE_PAGE_SIZE).then(value => { if (alive) { setResult(value); setError(''); } })
|
const hasSameRunResult = loadedRunId === runId && loadedPage > 0;
|
||||||
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); })
|
const pageMatches = hasSameRunResult && matchesImportIssuePage(loadedRunId, loadedPage, runId, page);
|
||||||
.finally(() => { if (alive) setLoading(false); });
|
|
||||||
return () => { alive = false; };
|
|
||||||
}, [runId, page, onUnauthorized]);
|
|
||||||
const items = unwrapItems(result).items;
|
|
||||||
return <Drawer className="management-drawer" open={Boolean(runId)} title="导入校验问题" width={Math.min(900, window.innerWidth)} onClose={onClose}>
|
return <Drawer className="management-drawer" open={Boolean(runId)} title="导入校验问题" width={Math.min(900, window.innerWidth)} onClose={onClose}>
|
||||||
{error && <Alert showIcon type="error" message="问题清单读取失败" description={error} />}
|
{error && <Alert showIcon type="error" message="问题清单读取失败" description={pageMatches ? `${error};第 ${page} 页的上次成功结果仍保留。` : hasSameRunResult ? `${error};以下仍显示第 ${loadedPage} 页上次成功结果。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||||
{loading ? <div className="loading-panel"><Spin />正在读取问题行…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
|
{loading && !hasSameRunResult ? <div className="loading-panel"><Spin />正在读取问题行…</div> : hasSameRunResult ? <><DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />{!pageMatches && loading && <div className="completion-note"><Spin size="small" /> 正在读取第 {page} 页,暂时保留第 {loadedPage} 页结果。</div>}</> : null}
|
||||||
{result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
|
{hasSameRunResult && result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={pageMatches ? page : loadedPage} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
|
||||||
</Drawer>;
|
</Drawer>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,27 +360,30 @@ function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized
|
|||||||
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
|
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const { active } = usePageCache();
|
||||||
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const read = useDelayedBusy();
|
||||||
|
const loading = read.busy;
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [metadata, setMetadata] = useState<{ total?: number; page?: number; pageSize?: number }>({});
|
const [metadata, setMetadata] = useState<{ total?: number; page?: number; pageSize?: number }>({});
|
||||||
const load = async () => {
|
const load = useCallback(() => read.run(async () => {
|
||||||
setLoading(true);
|
|
||||||
try {
|
try {
|
||||||
const result = await api.tasks();
|
const result = await api.tasks();
|
||||||
const normalized = unwrapItems(result);
|
const normalized = unwrapItems(result);
|
||||||
setItems(endpoint === 'imports' ? normalized.items.filter(item => String(item.type).toUpperCase() === 'IMPORT') : normalized.items);
|
setItems(endpoint === 'imports' ? normalized.items.filter(item => String(item.type).toUpperCase() === 'IMPORT') : normalized.items);
|
||||||
setMetadata({ total: normalized.total, page: normalized.page, pageSize: normalized.pageSize });
|
setMetadata({ total: normalized.total, page: normalized.page, pageSize: normalized.pageSize });
|
||||||
setError('');
|
setError(''); setLoaded(true);
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
if (!onUnauthorized(value)) setError(apiMessage(value));
|
if (!onUnauthorized(value)) setError(apiMessage(value));
|
||||||
} finally { setLoading(false); }
|
}
|
||||||
};
|
}), [endpoint, onUnauthorized, read.run]);
|
||||||
useEffect(() => { void load(); }, [endpoint]);
|
useEffect(() => { if (active && !loaded) void load(); }, [active, endpoint, loaded, load]);
|
||||||
|
useVisiblePolling(load, endpoint === 'imports' ? 2000 : 15000, active && loaded && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status || '').toUpperCase())));
|
||||||
return <div className="management-page">
|
return <div className="management-page">
|
||||||
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
|
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>} />
|
||||||
{error && <Alert type="error" showIcon message="列表读取失败" description={error} />}
|
{error && <Alert type="error" showIcon message="列表读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={!loaded ? <Button onClick={() => void load()}>重试</Button> : undefined} />}
|
||||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
|
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
|
||||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
{loading && !loaded ? <div className="loading-panel"><Spin />正在读取…</div> : loaded && <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||||
</section>
|
</section>
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
@@ -373,10 +403,14 @@ type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'pr
|
|||||||
|
|
||||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections }: { extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections }: { extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
|
const { active: pageActive } = usePageCache();
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [itemsLoaded, setItemsLoaded] = useState(false);
|
||||||
|
const itemRead = useDelayedBusy();
|
||||||
|
const loading = itemRead.busy;
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [busyId, setBusyId] = useState('');
|
const [busyId, setBusyId] = useState('');
|
||||||
|
const actionLock = useRef(false);
|
||||||
const [drafting, setDrafting] = useState<Record<string, unknown> | null>(null);
|
const [drafting, setDrafting] = useState<Record<string, unknown> | null>(null);
|
||||||
const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null);
|
const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null);
|
||||||
const [impactOpen, setImpactOpen] = useState(false);
|
const [impactOpen, setImpactOpen] = useState(false);
|
||||||
@@ -399,6 +433,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
const [differenceConfirmed, setDifferenceConfirmed] = useState(false);
|
const [differenceConfirmed, setDifferenceConfirmed] = useState(false);
|
||||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||||
|
const [workflowStatusError, setWorkflowStatusError] = useState('');
|
||||||
|
const statusRead = useDelayedBusy();
|
||||||
|
const supportRequested = useRef(false);
|
||||||
const isRules = kind === 'rules';
|
const isRules = kind === 'rules';
|
||||||
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';
|
||||||
@@ -410,31 +447,37 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
|
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
|
||||||
: items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
|
: items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
|
||||||
|
|
||||||
const load = async (silent = false) => {
|
const load = useCallback((silent = false) => {
|
||||||
if(!silent)setLoading(true);
|
const read = async () => {
|
||||||
try {
|
try {
|
||||||
const result = isRules ? await api.rules() : await api.mappings();
|
const result = isRules ? await api.rules() : await api.mappings();
|
||||||
setItems(collectionItems(result)); setError('');
|
setItems(collectionItems(result)); setItemsLoaded(true); setError('');
|
||||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||||
finally { setLoading(false); }
|
};
|
||||||
};
|
return silent ? read() : itemRead.run(read);
|
||||||
const loadEditorSupport = async () => {
|
}, [isRules, itemRead.run, onUnauthorized]);
|
||||||
|
const loadEditorSupport = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
if (isRules) { setRuleSchema(await api.ruleSchema()); setRuleSchemaError(''); }
|
if (isRules) { setRuleSchema(await api.ruleSchema()); setRuleSchemaError(''); }
|
||||||
else {const [names,metadata]=await Promise.all([api.referenceNames(),api.classificationMetadata()]);setPublishedNames(names);setMatchMetadata(metadata);}
|
else {
|
||||||
|
const [names, metadata] = await Promise.allSettled([api.referenceNames(), api.classificationMetadata()]);
|
||||||
|
if (names.status === 'fulfilled') setPublishedNames(names.value);
|
||||||
|
if (metadata.status === 'fulfilled') setMatchMetadata(metadata.value);
|
||||||
|
const errors = [names, metadata].flatMap((result, index) => result.status === 'rejected' && !onUnauthorized(result.reason) ? [`${index === 0 ? '发布名录' : '对应关系元数据'}:${apiMessage(result.reason)}`] : []);
|
||||||
|
if (errors.length) setError(errors.join(';'));
|
||||||
|
}
|
||||||
} catch (value) { if (!onUnauthorized(value)) { if (isRules) setRuleSchemaError(apiMessage(value)); else setError(`当前发布名录读取失败:${apiMessage(value)}`); } }
|
} catch (value) { if (!onUnauthorized(value)) { if (isRules) setRuleSchemaError(apiMessage(value)); else setError(`当前发布名录读取失败:${apiMessage(value)}`); } }
|
||||||
};
|
}, [isRules, onUnauthorized]);
|
||||||
const refreshWorkflowStatus = async () => {
|
const refreshWorkflowStatus = useCallback(() => statusRead.run(async () => {
|
||||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
|
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
|
||||||
catch { setWorkflowStatus(null); }
|
catch (value) { if (!onUnauthorized(value)) setWorkflowStatusError(apiMessage(value)); }
|
||||||
finally { setWorkflowStatusLoaded(true); }
|
}), [onUnauthorized, statusRead.run]);
|
||||||
};
|
|
||||||
const workflowOperation = useDataWorkflowOperation(isRules ? 'apply-rule' : 'apply-mapping', () => {
|
const workflowOperation = useDataWorkflowOperation(isRules ? 'apply-rule' : 'apply-mapping', () => {
|
||||||
void load(); void refreshWorkflowStatus();
|
void load(); void refreshWorkflowStatus();
|
||||||
});
|
});
|
||||||
useEffect(() => { void load(); }, [kind]);
|
useEffect(() => { if (pageActive && !itemsLoaded) void load(); }, [pageActive, itemsLoaded, load]);
|
||||||
useEffect(() => { void loadEditorSupport(); }, [isRules]);
|
useEffect(() => { if (pageActive && !supportRequested.current) { supportRequested.current = true; void loadEditorSupport(); } }, [pageActive, loadEditorSupport]);
|
||||||
useEffect(() => { void refreshWorkflowStatus(); }, [kind]);
|
useEffect(() => { if (pageActive && !workflowStatusLoaded && !workflowStatusError) void refreshWorkflowStatus(); }, [pageActive, workflowStatusLoaded, workflowStatusError, refreshWorkflowStatus]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!workflowStatus) return;
|
if (!workflowStatus) return;
|
||||||
const active = (isRules ? workflowStatus.activeRule : workflowStatus.activeMapping) as { id?: string; name?: string; description?: string; definition?: Record<string, unknown> } | null | undefined;
|
const active = (isRules ? workflowStatus.activeRule : workflowStatus.activeMapping) as { id?: string; name?: string; description?: string; definition?: Record<string, unknown> } | null | undefined;
|
||||||
@@ -445,8 +488,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
|
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
|
||||||
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
|
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
|
||||||
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
||||||
form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
if (!drafting) form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
||||||
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema]);
|
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema, drafting, form]);
|
||||||
|
|
||||||
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
|
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
|
||||||
if (!isRules) return;
|
if (!isRules) return;
|
||||||
@@ -486,6 +529,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
};
|
};
|
||||||
|
|
||||||
const saveDraft = async () => {
|
const saveDraft = async () => {
|
||||||
|
if (actionLock.current) return; actionLock.current = true;
|
||||||
try {
|
try {
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
const body: Record<string, unknown> = { name: values.name.trim(), definition: isRules ? draftDefinition : { ...draftDefinition, maintenanceNote: values.description?.trim() || '' } };
|
const body: Record<string, unknown> = { name: values.name.trim(), definition: isRules ? draftDefinition : { ...draftDefinition, maintenanceNote: values.description?.trim() || '' } };
|
||||||
@@ -504,11 +548,11 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||||
if (value instanceof ApiError && value.status === 409) await load();
|
if (value instanceof ApiError && value.status === 409) await load();
|
||||||
} finally { setBusyId(''); }
|
} finally { actionLock.current = false; setBusyId(''); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const runAction = async (item: Record<string, unknown>, action: 'validate' | 'activate', confirmDifferences = false) => {
|
const runAction = async (item: Record<string, unknown>, action: 'validate' | 'activate', confirmDifferences = false) => {
|
||||||
const id = String(item.id || ''); if (!id) return;
|
const id = String(item.id || ''); if (!id || actionLock.current) return; actionLock.current = true;
|
||||||
setBusyId(id);
|
setBusyId(id);
|
||||||
try {
|
try {
|
||||||
const result = isRules
|
const result = isRules
|
||||||
@@ -522,7 +566,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
if (action === 'activate') setDifferenceItem(null);
|
if (action === 'activate') setDifferenceItem(null);
|
||||||
await load();
|
await load();
|
||||||
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); }
|
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); }
|
||||||
finally { setBusyId(''); }
|
finally { actionLock.current = false; setBusyId(''); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const showImpact = async (item: Record<string, unknown>) => {
|
const showImpact = async (item: Record<string, unknown>) => {
|
||||||
@@ -566,6 +610,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
};
|
};
|
||||||
const classificationBusy=classificationUpdates.jobs.some(job=>!['failed','completed'].includes(job.status));
|
const classificationBusy=classificationUpdates.jobs.some(job=>!['failed','completed'].includes(job.status));
|
||||||
const applyCurrent = async () => {
|
const applyCurrent = async () => {
|
||||||
|
if (actionLock.current) return; actionLock.current = true;
|
||||||
try {
|
try {
|
||||||
await form.validateFields();
|
await form.validateFields();
|
||||||
const values = form.getFieldsValue(true);
|
const values = form.getFieldsValue(true);
|
||||||
@@ -574,17 +619,18 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||||
}
|
}
|
||||||
|
finally { actionLock.current = false; }
|
||||||
};
|
};
|
||||||
|
|
||||||
useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); });
|
useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); });
|
||||||
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
|
if (!workflowStatusLoaded) return <div className="management-page">{statusRead.busy ? <div className="loading-panel"><Spin />正在读取当前维护模式…</div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void refreshWorkflowStatus()}>重试</Button>} /> : null}</div>;
|
||||||
if (testMode) {
|
if (testMode) {
|
||||||
const notices = <>
|
const notices = <>
|
||||||
{kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&<div className="classification-queue-status" role="status">
|
{kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&<div className="classification-queue-status" role="status">
|
||||||
{classificationBusy&&<span><Spin size="small"/> 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条</span>}
|
{classificationBusy&&<span><Spin size="small"/> 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条</span>}
|
||||||
{classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=><Alert key={job.id} type="error" showIcon message={`${job.target}:${job.error}`} action={<><Button size="small" onClick={()=>classificationUpdates.queue.retry(job.id)}>重试</Button>{job.status==='failed'&&<Button size="small" onClick={()=>classificationUpdates.queue.dismiss(job.id)}>关闭</Button>}</>}/>)}
|
{classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=><Alert key={job.id} type="error" showIcon message={`${job.target}:${job.error}`} action={<><Button size="small" onClick={()=>classificationUpdates.queue.retry(job.id)}>重试</Button>{job.status==='failed'&&<Button size="small" onClick={()=>classificationUpdates.queue.dismiss(job.id)}>关闭</Button>}</>}/>)}
|
||||||
</div>}
|
</div>}
|
||||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
|
{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="当前账号可查看配置;保存和更新报表需要发布权限。" />}
|
||||||
{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} />}
|
||||||
@@ -621,10 +667,10 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
{canManage && <Button type={isRules ? 'primary' : 'default'} disabled={loading || (isRules && !ruleSchema) || (kind === 'masterData' && !publishedNames)} onClick={() => openDraft()}>从启用版新建草稿</Button>}
|
{canManage && <Button type={isRules ? 'primary' : 'default'} disabled={loading || (isRules && !ruleSchema) || (kind === 'masterData' && !publishedNames)} onClick={() => openDraft()}>从启用版新建草稿</Button>}
|
||||||
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadEditorSupport(); }}>刷新</Button>
|
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadEditorSupport(); }}>刷新</Button>
|
||||||
</>} />
|
</>} />
|
||||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
|
{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} />}
|
||||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}记录</strong><span>{items.length} 个服务端记录</span></div>
|
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}记录</strong><span>{items.length} 个服务端记录</span></div>
|
||||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" />}
|
{loading && !itemsLoaded ? <div className="loading-panel"><Spin />正在读取…</div> : itemsLoaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" /> : null}
|
||||||
</section>
|
</section>
|
||||||
<Alert showIcon type="info" message="变更先保存为草稿" description="保存后在清单中校验并启用;启用后重新计算、核对并发布,查询结果才采用新配置。" action={!isRules ? <Button onClick={() => onNavigate('sources')}>前往重新计算</Button> : undefined} />
|
<Alert showIcon type="info" message="变更先保存为草稿" description="保存后在清单中校验并启用;启用后重新计算、核对并发布,查询结果才采用新配置。" action={!isRules ? <Button onClick={() => onNavigate('sources')}>前往重新计算</Button> : undefined} />
|
||||||
<Modal className="management-modal structured-config-modal" open={Boolean(drafting)} title={drafting?.id ? `编辑${title}草稿` : `新建${title}草稿`} width={1120} okText="保存草稿" confirmLoading={Boolean(busyId)} onCancel={() => setDrafting(null)} onOk={() => void saveDraft()}>
|
<Modal className="management-modal structured-config-modal" open={Boolean(drafting)} title={drafting?.id ? `编辑${title}草稿` : `新建${title}草稿`} width={1120} okText="保存草稿" confirmLoading={Boolean(busyId)} onCancel={() => setDrafting(null)} onOk={() => void saveDraft()}>
|
||||||
@@ -691,7 +737,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
|||||||
<details className="completion-technical-detail"><summary>影响预览技术字段</summary><pre className="json-result">{publicJson(impact)}</pre></details>
|
<details className="completion-technical-detail"><summary>影响预览技术字段</summary><pre className="json-result">{publicJson(impact)}</pre></details>
|
||||||
</> : <div className="completion-loading"><Spin />由服务端重新核对配置依赖…</div>}</Drawer>
|
</> : <div className="completion-loading"><Spin />由服务端重新核对配置依赖…</div>}</Drawer>
|
||||||
</div>;
|
</div>;
|
||||||
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
|
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{if(actionLock.current)return;actionLock.current=true;setBusyId('editor-new');void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));}).finally(()=>{actionLock.current=false;setBusyId('');});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
|
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
|
||||||
@@ -767,24 +813,23 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
|||||||
|
|
||||||
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
|
const { active } = usePageCache();
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const read = useDelayedBusy(); const loading = read.busy;
|
||||||
const [dictionaryError, setDictionaryError] = useState('');
|
const [dictionaryError, setDictionaryError] = useState('');
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
const savingRef = useRef(false);
|
||||||
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', 'RULE_MAINTAINER'].includes(role));
|
||||||
|
|
||||||
const load = async () => {
|
const load = useCallback(() => read.run(async () => {
|
||||||
setLoading(true);
|
try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); }
|
||||||
try {
|
catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
|
||||||
const result = await api.metricDictionary();
|
}), [onUnauthorized, read.run]);
|
||||||
setItems(collectionItems(result)); setDictionaryError('');
|
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
|
||||||
} catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
|
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
useEffect(() => { void load(); }, []);
|
|
||||||
|
|
||||||
const openEditor = (item: Record<string, unknown>) => {
|
const openEditor = (item: Record<string, unknown>) => {
|
||||||
setEditing(item);
|
setEditing(item);
|
||||||
@@ -795,7 +840,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
if (!editing) return;
|
if (!editing || savingRef.current) return; savingRef.current = true;
|
||||||
try {
|
try {
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
const code = String(editing.code || '');
|
const code = String(editing.code || '');
|
||||||
@@ -813,7 +858,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
|||||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||||
if (value instanceof ApiError && value.status === 409) await load();
|
if (value instanceof ApiError && value.status === 409) await load();
|
||||||
} finally { setSaving(false); }
|
} finally { savingRef.current = false; setSaving(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns: ColumnsType<Record<string, unknown>> = [
|
const columns: ColumnsType<Record<string, unknown>> = [
|
||||||
@@ -828,8 +873,8 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
|||||||
useMaintenanceRefresh(load);
|
useMaintenanceRefresh(load);
|
||||||
return <section className="panel section-panel completion-tools">
|
return <section className="panel section-panel completion-tools">
|
||||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
|
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
|
||||||
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={dictionaryError} />}
|
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={loaded ? `${dictionaryError};以下为上次成功读取的结果。` : dictionaryError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||||
{loading ? <div className="loading-panel"><Spin />读取术语定义…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" />}
|
{loading && !loaded ? <div className="loading-panel"><Spin />读取术语定义…</div> : loaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" /> : null}
|
||||||
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="公式来自当前查询数据所绑定的计算规则;编辑术语不会改变计算结果。" />
|
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="公式来自当前查询数据所绑定的计算规则;编辑术语不会改变计算结果。" />
|
||||||
<Modal className="management-modal" open={Boolean(editing)} title={`编辑术语 · ${String(editing?.code || '')}`} okText="保存术语" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
|
<Modal className="management-modal" open={Boolean(editing)} title={`编辑术语 · ${String(editing?.code || '')}`} okText="保存术语" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
|
||||||
<Form form={form} layout="vertical">
|
<Form form={form} layout="vertical">
|
||||||
@@ -851,6 +896,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
|||||||
const [selected, setSelected] = useState<Record<string, unknown> | null>(null);
|
const [selected, setSelected] = useState<Record<string, unknown> | null>(null);
|
||||||
const [issuesRunId, setIssuesRunId] = useState('');
|
const [issuesRunId, setIssuesRunId] = useState('');
|
||||||
const [busyId, setBusyId] = useState('');
|
const [busyId, setBusyId] = useState('');
|
||||||
|
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_MAINTAINER'].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_MAINTAINER', 'SYSTEM_OPERATOR'].includes(role));
|
||||||
const runIdOf = (row: Record<string, unknown>) => {
|
const runIdOf = (row: Record<string, unknown>) => {
|
||||||
@@ -859,6 +905,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
|||||||
};
|
};
|
||||||
const retry = async (row: Record<string, unknown>) => {
|
const retry = async (row: Record<string, unknown>) => {
|
||||||
const id = String(row.id || ''); if (!id) return;
|
const id = String(row.id || ''); if (!id) return;
|
||||||
|
if (actionLock.current) return; actionLock.current = true;
|
||||||
setBusyId(id);
|
setBusyId(id);
|
||||||
try {
|
try {
|
||||||
const releases = await api.releases();
|
const releases = await api.releases();
|
||||||
@@ -869,16 +916,17 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
|||||||
else message.success(`任务重试完成:${toText(run.status || '已更新')}`);
|
else message.success(`任务重试完成:${toText(run.status || '已更新')}`);
|
||||||
onRefresh();
|
onRefresh();
|
||||||
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
|
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
|
||||||
finally { setBusyId(''); }
|
finally { actionLock.current = false; setBusyId(''); }
|
||||||
};
|
};
|
||||||
const cancel = async (row: Record<string, unknown>) => {
|
const cancel = async (row: Record<string, unknown>) => {
|
||||||
const id = String(row.id || ''); if (!id) return;
|
const id = String(row.id || ''); if (!id) return;
|
||||||
|
if (actionLock.current) return; actionLock.current = true;
|
||||||
setBusyId(id);
|
setBusyId(id);
|
||||||
try {
|
try {
|
||||||
await api.cancelTask(id, { expectedStatus: String(row.status || '') });
|
await api.cancelTask(id, { expectedStatus: String(row.status || '') });
|
||||||
message.success('已取消排队任务'); onRefresh();
|
message.success('已取消排队任务'); onRefresh();
|
||||||
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
|
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
|
||||||
finally { setBusyId(''); }
|
finally { actionLock.current = false; setBusyId(''); }
|
||||||
};
|
};
|
||||||
const importState = (value: unknown) => ({ COMPLETED: '导入完成', SUCCEEDED: '导入完成', FAILED: '导入失败', ERROR: '导入失败', RUNNING: '正在导入', QUEUED: '等待导入', CANCELLED: '已取消' }[String(value).toUpperCase()] || toText(value));
|
const importState = (value: unknown) => ({ COMPLETED: '导入完成', SUCCEEDED: '导入完成', FAILED: '导入失败', ERROR: '导入失败', RUNNING: '正在导入', QUEUED: '等待导入', CANCELLED: '已取消' }[String(value).toUpperCase()] || toText(value));
|
||||||
const columns: ColumnsType<Record<string, unknown>> = [
|
const columns: ColumnsType<Record<string, unknown>> = [
|
||||||
@@ -894,8 +942,8 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
|||||||
{ title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => <span className="task-actions">
|
{ title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => <span className="task-actions">
|
||||||
<Button type="link" onClick={() => setSelected(row)}>详情</Button>
|
<Button type="link" onClick={() => setSelected(row)}>详情</Button>
|
||||||
{importOnly && runIdOf(row) && <Button type="link" onClick={() => setIssuesRunId(runIdOf(row))}>校验问题</Button>}
|
{importOnly && runIdOf(row) && <Button type="link" onClick={() => setIssuesRunId(runIdOf(row))}>校验问题</Button>}
|
||||||
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
|
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
|
||||||
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
|
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
|
||||||
</span> },
|
</span> },
|
||||||
];
|
];
|
||||||
return <>
|
return <>
|
||||||
@@ -913,6 +961,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
const [renameTarget, setRenameTarget] = useState<Record<string, unknown> | null>(null);
|
const [renameTarget, setRenameTarget] = useState<Record<string, unknown> | null>(null);
|
||||||
const [renameTitle, setRenameTitle] = useState('');
|
const [renameTitle, setRenameTitle] = useState('');
|
||||||
const [renaming, setRenaming] = useState(false);
|
const [renaming, setRenaming] = useState(false);
|
||||||
|
const sessionMutationLock = useRef(false);
|
||||||
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
|
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
|
||||||
const activePage = useRef(active); activePage.current = active;
|
const activePage = useRef(active); activePage.current = active;
|
||||||
const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
|
const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
|
||||||
@@ -924,9 +973,16 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
const [sessionReadOnly, setSessionReadOnly] = useState(false);
|
const [sessionReadOnly, setSessionReadOnly] = useState(false);
|
||||||
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
|
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
|
||||||
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
|
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
|
||||||
|
const [sessionsLoaded, setSessionsLoaded] = useState(false);
|
||||||
|
const sessionReadRequest = useRef<Promise<void> | null>(null);
|
||||||
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
|
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
|
||||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||||
const [historyLoading, setHistoryLoading] = useState(true);
|
const [historyLoading, setHistoryLoading] = useState(true);
|
||||||
|
const showHistoryLoading = useDelayedIndicator(historyLoading && active, 150);
|
||||||
|
const optionsRead = useDelayedBusy();
|
||||||
|
const [optionsError, setOptionsError] = useState('');
|
||||||
|
const optionsRequestStarted = useRef(false);
|
||||||
|
const restoreStarted = useRef(false);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [queuedFollowup, setQueuedFollowup] = useState('');
|
const [queuedFollowup, setQueuedFollowup] = useState('');
|
||||||
const [stopping, setStopping] = useState(false);
|
const [stopping, setStopping] = useState(false);
|
||||||
@@ -1052,22 +1108,33 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
}, [lastTurn, busy, turns, sessionId, active]);
|
}, [lastTurn, busy, turns, sessionId, active]);
|
||||||
|
|
||||||
const loadSessions = async () => {
|
const loadSessions = async () => {
|
||||||
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); }
|
if (!mounted.current || !active || document.visibilityState !== 'visible') return;
|
||||||
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
if (sessionReadRequest.current) return sessionReadRequest.current;
|
||||||
|
const request = (async () => {
|
||||||
|
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setError(''); } }
|
||||||
|
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||||
|
})();
|
||||||
|
sessionReadRequest.current = request;
|
||||||
|
try { await request; }
|
||||||
|
finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; }
|
||||||
};
|
};
|
||||||
|
const retrySessions = async () => { setHistoryLoading(true); await loadSessions(); if (mounted.current) setHistoryLoading(false); };
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
if (!active || optionsRequestStarted.current) return;
|
||||||
api.options().then(value => { if (alive) setOptions(value); })
|
optionsRequestStarted.current = true;
|
||||||
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); });
|
void optionsRead.run(async () => {
|
||||||
return () => { alive = false; };
|
try { const value = await api.options(); if (mounted.current) { setOptions(value); setOptionsError(''); } }
|
||||||
}, []);
|
catch (value) { if (mounted.current && !onUnauthorized(value)) setOptionsError(apiMessage(value)); }
|
||||||
|
});
|
||||||
|
}, [active, onUnauthorized, optionsRead.run]);
|
||||||
|
|
||||||
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
|
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
|
||||||
|
useVisiblePolling(loadSessions, 5000, active && hasBackgroundTurns);
|
||||||
|
const wasActive = useRef(active);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hasBackgroundTurns) return;
|
if (active && !wasActive.current && hasBackgroundTurns) void loadSessions();
|
||||||
const timer = window.setInterval(() => void loadSessions(), 5000);
|
wasActive.current = active;
|
||||||
return () => window.clearInterval(timer);
|
}, [active, hasBackgroundTurns]);
|
||||||
}, [hasBackgroundTurns]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!initialLink.present || initialSessionId || initialTurnId || !options || userSelectionMade.current) return;
|
if (!initialLink.present || initialSessionId || initialTurnId || !options || userSelectionMade.current) return;
|
||||||
@@ -1229,6 +1296,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
};
|
};
|
||||||
|
|
||||||
const deleteSession = async (id: string) => {
|
const deleteSession = async (id: string) => {
|
||||||
|
if (sessionMutationLock.current) return; sessionMutationLock.current = true;
|
||||||
const generation = navigationGeneration.current;
|
const generation = navigationGeneration.current;
|
||||||
try {
|
try {
|
||||||
await api.deleteAnalysisSession(id);
|
await api.deleteAnalysisSession(id);
|
||||||
@@ -1237,17 +1305,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
message.success('会话已删除');
|
message.success('会话已删除');
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除会话失败');
|
if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除会话失败');
|
||||||
}
|
} finally { sessionMutationLock.current = false; }
|
||||||
};
|
};
|
||||||
|
|
||||||
const renameSession = async () => {
|
const renameSession = async () => {
|
||||||
if (!renameTarget || !renameTitle.trim() || renaming) return;
|
if (!renameTarget || !renameTitle.trim() || sessionMutationLock.current) return; sessionMutationLock.current = true;
|
||||||
setRenaming(true);
|
setRenaming(true);
|
||||||
try {
|
try {
|
||||||
await api.renameAnalysisSession(String(renameTarget.id), renameTitle.trim());
|
await api.renameAnalysisSession(String(renameTarget.id), renameTitle.trim());
|
||||||
setRenameTarget(null); await loadSessions(); message.success('会话已重命名');
|
setRenameTarget(null); await loadSessions(); message.success('会话已重命名');
|
||||||
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); }
|
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); }
|
||||||
finally { setRenaming(false); }
|
finally { sessionMutationLock.current = false; setRenaming(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
|
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
|
||||||
@@ -1367,31 +1435,36 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!active || restoreStarted.current) return;
|
||||||
|
restoreStarted.current = true;
|
||||||
mounted.current = true;
|
mounted.current = true;
|
||||||
let cancelled = false;
|
|
||||||
const restore = async () => {
|
const restore = async () => {
|
||||||
const requestedAt = navigationGeneration.current;
|
const requestedAt = navigationGeneration.current;
|
||||||
setHistoryLoading(true);
|
setHistoryLoading(true);
|
||||||
try {
|
try {
|
||||||
const items = collectionItems(await api.analysisSessions());
|
const items = collectionItems(await api.analysisSessions());
|
||||||
if (cancelled || requestedAt !== navigationGeneration.current) return;
|
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
|
||||||
setSessions(items);
|
setSessions(items);
|
||||||
|
setSessionsLoaded(true);
|
||||||
let linkedSession = initialSessionId;
|
let linkedSession = initialSessionId;
|
||||||
if (initialTurnId) {
|
if (initialTurnId) {
|
||||||
const linkedTurn = await api.analysisTurn(initialTurnId);
|
const linkedTurn = await api.analysisTurn(initialTurnId);
|
||||||
if (cancelled || requestedAt !== navigationGeneration.current) return;
|
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
|
||||||
const turnSession = String(linkedTurn.sessionId || '');
|
const turnSession = String(linkedTurn.sessionId || '');
|
||||||
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
|
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
|
||||||
linkedSession ||= turnSession;
|
linkedSession ||= turnSession;
|
||||||
}
|
}
|
||||||
if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items);
|
if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items);
|
||||||
if (!cancelled && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
|
if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
|
||||||
} catch (value) { if (!cancelled && !onUnauthorized(value)) setError(apiMessage(value)); }
|
} catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||||
finally { if (!cancelled && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
|
finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
|
||||||
};
|
};
|
||||||
void restore();
|
void restore();
|
||||||
|
}, [active]);
|
||||||
|
useEffect(() => {
|
||||||
|
mounted.current = true;
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true; mounted.current = false;
|
mounted.current = false;
|
||||||
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
|
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
|
||||||
// Unsubscribe from updates only. The accepted server task continues independently.
|
// Unsubscribe from updates only. The accepted server task continues independently.
|
||||||
streamController.current?.abort(); streamController.current = null;
|
streamController.current?.abort(); streamController.current = null;
|
||||||
@@ -1589,17 +1662,19 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
|||||||
|
|
||||||
return <div className="management-page analysis-simple-page">
|
return <div className="management-page analysis-simple-page">
|
||||||
<PageHeader title="智能分析" />
|
<PageHeader title="智能分析" />
|
||||||
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>} />}
|
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />}
|
||||||
|
{optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />}
|
||||||
|
{!options && optionsRead.busy && <div className="loading-panel compact"><Spin />读取分析选项…</div>}
|
||||||
<div className="analysis-workspace">
|
<div className="analysis-workspace">
|
||||||
<aside className="panel analysis-session-panel">
|
<aside className="panel analysis-session-panel">
|
||||||
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
|
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
|
||||||
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
|
{showHistoryLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
|
||||||
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
|
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
|
||||||
{ 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({ title: '删除此会话及其分析记录?', content: '删除后无法恢复', okText: '删除', cancelText: '取消', 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="暂无历史会话" />}
|
} }}><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">
|
||||||
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
|
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
|
||||||
@@ -1758,23 +1833,24 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized:
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||||
|
const { active } = usePageCache();
|
||||||
const [result, setResult] = useState<Collection | null>(null);
|
const [result, setResult] = useState<Collection | null>(null);
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loadedPage, setLoadedPage] = useState(0);
|
||||||
|
const read = useDelayedBusy(); const loading = read.busy;
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const load = async (nextPage = page) => {
|
const load = useCallback((nextPage = page) => read.run(async () => {
|
||||||
setLoading(true);
|
try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setLoadedPage(nextPage); setError(''); }
|
||||||
try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setError(''); }
|
|
||||||
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||||
finally { setLoading(false); }
|
}), [onUnauthorized, page, read.run]);
|
||||||
};
|
useEffect(() => { if (active && loadedPage !== page) void load(page); }, [active, loadedPage, page, load]);
|
||||||
useEffect(() => { void load(page); }, [page]);
|
useMaintenanceRefresh(() => { void load(page); });
|
||||||
const items = unwrapItems(result).items;
|
const items = unwrapItems(result).items;
|
||||||
const total = result?.total ?? items.length;
|
const total = result?.total ?? items.length;
|
||||||
return <div className="resource-tab">
|
return <div className="resource-tab">
|
||||||
{error && <Alert type="error" showIcon message="审计记录读取失败" description={error} />}
|
{error && <Alert type="error" showIcon message="审计记录读取失败" description={loadedPage ? `${error};当前仍显示第 ${loadedPage} 页上次成功结果。` : error} action={!loadedPage ? <Button size="small" onClick={() => void load(page)}>重试</Button> : undefined} />}
|
||||||
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} onClick={() => void load(page)}>刷新</Button></div>
|
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load(page)}>刷新</Button></div>
|
||||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
|
{loading && loadedPage !== page ? <div className="loading-panel"><Spin />正在读取…</div> : result && <DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />}
|
||||||
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条`} onChange={setPage} />}
|
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条`} onChange={setPage} />}
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
@@ -1783,29 +1859,35 @@ const ROLE_OPTIONS = ['SYSTEM_ADMIN', 'QUALITY_VIEWER', 'BUSINESS_ANALYST', 'DAT
|
|||||||
|
|
||||||
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 [users, setUsers] = useState<Record<string, unknown>[]>([]);
|
const [users, setUsers] = useState<Record<string, unknown>[]>([]);
|
||||||
const [departments, setDepartments] = useState<string[]>([]);
|
const [departments, setDepartments] = useState<string[]>([]);
|
||||||
const [groups, setGroups] = useState<string[]>([]);
|
const [groups, setGroups] = useState<string[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [usersLoaded, setUsersLoaded] = useState(false);
|
||||||
|
const [optionsLoaded, setOptionsLoaded] = useState(false);
|
||||||
|
const read = useDelayedBusy(); const loading = read.busy;
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
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; roles: string[]; departments: string[]; groups: string[] }>();
|
||||||
const canManage = user.roles.includes('SYSTEM_ADMIN');
|
const canManage = user.roles.includes('SYSTEM_ADMIN');
|
||||||
|
|
||||||
const load = async () => {
|
const load = useCallback(() => read.run(async () => {
|
||||||
setLoading(true);
|
const [userResult, optionsResult] = await Promise.allSettled([api.users(), api.options()]);
|
||||||
try {
|
const failures: string[] = [];
|
||||||
const [userResult, optionsResult] = await Promise.all([api.users(), api.options()]);
|
let rows = users;
|
||||||
const rows = collectionItems(userResult);
|
if (userResult.status === 'fulfilled') { rows = collectionItems(userResult.value); setUsers(rows); setUsersLoaded(true); }
|
||||||
setUsers(rows);
|
else if (!onUnauthorized(userResult.reason)) failures.push(`用户清单:${apiMessage(userResult.reason)}`);
|
||||||
setDepartments(Array.from(new Set([...(optionsResult.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
|
if (optionsResult.status === 'fulfilled') {
|
||||||
setGroups(Array.from(new Set([...(optionsResult.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
|
setDepartments(Array.from(new Set([...(optionsResult.value.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
|
||||||
setError('');
|
setGroups(Array.from(new Set([...(optionsResult.value.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
|
||||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
setOptionsLoaded(true);
|
||||||
finally { setLoading(false); }
|
} else if (!onUnauthorized(optionsResult.reason)) failures.push(`授权选项:${apiMessage(optionsResult.reason)}`);
|
||||||
};
|
setError(failures.join(';'));
|
||||||
useEffect(() => { void load(); }, []);
|
}), [onUnauthorized, read.run, users]);
|
||||||
|
useEffect(() => { if (active && !usersLoaded) void load(); }, [active, usersLoaded, load]);
|
||||||
|
useMaintenanceRefresh(load);
|
||||||
|
|
||||||
const openEditor = (record?: Record<string, unknown>) => {
|
const openEditor = (record?: Record<string, unknown>) => {
|
||||||
setEditing(record || {});
|
setEditing(record || {});
|
||||||
@@ -1819,6 +1901,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
|||||||
};
|
};
|
||||||
|
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
|
if (saveLock.current) return; saveLock.current = true;
|
||||||
try {
|
try {
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
@@ -1834,7 +1917,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
|||||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||||
if (value instanceof ApiError && value.status === 409) await load();
|
if (value instanceof ApiError && value.status === 409) await load();
|
||||||
} finally { setBusy(false); }
|
} finally { saveLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns: ColumnsType<Record<string, unknown>> = [
|
const columns: ColumnsType<Record<string, unknown>> = [
|
||||||
@@ -1847,9 +1930,9 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
|||||||
{ 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: 110, align: 'center', render: (_, row) => canManage ? <Button type="link" onClick={() => openEditor(row)}>编辑授权</Button> : <span className="muted-dash">权限不足</span> },
|
||||||
];
|
];
|
||||||
return <div className="resource-tab">
|
return <div className="resource-tab">
|
||||||
{error && <Alert type="error" showIcon message="用户清单读取失败" description={error} />}
|
{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 ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : 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="服务端当前没有用户" />}
|
{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}
|
||||||
<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">
|
||||||
@@ -1865,21 +1948,22 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
|||||||
}
|
}
|
||||||
|
|
||||||
function BasisPage({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
function BasisPage({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||||
|
const { active } = usePageCache();
|
||||||
const [rules, setRules] = useState<Record<string, unknown>[]>([]);
|
const [rules, setRules] = useState<Record<string, unknown>[]>([]);
|
||||||
const [ruleError, setRuleError] = useState('');
|
const [ruleError, setRuleError] = useState('');
|
||||||
const [loading, setLoading] = useState(true);
|
const [loaded, setLoaded] = useState(false);
|
||||||
const load = async () => {
|
const read = useDelayedBusy(); const loading = read.busy;
|
||||||
setLoading(true);
|
const load = useCallback(() => read.run(async () => {
|
||||||
try { setRules(unwrapItems(await api.rules()).items); setRuleError(''); }
|
try { setRules(unwrapItems(await api.rules()).items); setLoaded(true); setRuleError(''); }
|
||||||
catch (value) { if (!onUnauthorized(value)) setRuleError(apiMessage(value)); }
|
catch (value) { if (!onUnauthorized(value)) setRuleError(apiMessage(value)); }
|
||||||
finally { setLoading(false); }
|
}), [onUnauthorized, read.run]);
|
||||||
};
|
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
|
||||||
useEffect(() => { void load(); }, []);
|
useMaintenanceRefresh(load);
|
||||||
return <div className="management-page">
|
return <div className="management-page">
|
||||||
<PageHeader title="数据与计算依据" description="综合合格率沿用正式指标服务结果;计算规则由服务端统一维护。" actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
|
<PageHeader title="数据与计算依据" description="综合合格率沿用正式指标服务结果;计算规则由服务端统一维护。" actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
|
||||||
<Alert showIcon type="info" message="综合合格率 = 同一筛选条件下黑片合格率 × 亮片合格率" description="此处说明业务口径。前端只展示服务端正式返回的指标,不用浏览器数据重算或替代正式结果。" />
|
<Alert showIcon type="info" message="综合合格率 = 同一筛选条件下黑片合格率 × 亮片合格率" description="此处说明业务口径。前端只展示服务端正式返回的指标,不用浏览器数据重算或替代正式结果。" />
|
||||||
<div className="basis-grid">
|
<div className="basis-grid">
|
||||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" message={ruleError} />}{loading ? <div className="loading-panel"><Spin /></div> : <DynamicTable items={rules} />}</section>
|
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" showIcon message="指标规则读取失败" description={loaded ? `${ruleError};下方保留上次成功结果。` : ruleError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}{loading && !loaded ? <div className="loading-panel"><Spin /></div> : loaded && <DynamicTable items={rules} />}</section>
|
||||||
</div>
|
</div>
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import { PageCacheContext, usePageCache } from './pageCache';
|
|||||||
|
|
||||||
export function ManagementSections({ items, initialKey, onSelect }: { items: { key: string; label: ReactNode; children: ReactNode }[]; initialKey?: string; onSelect?: (key: string) => void }) {
|
export function ManagementSections({ items, initialKey, onSelect }: { items: { key: string; label: ReactNode; children: ReactNode }[]; initialKey?: string; onSelect?: (key: string) => void }) {
|
||||||
const cache = usePageCache();
|
const cache = usePageCache();
|
||||||
const [selected, setSelected] = useState(initialKey ?? items[0]?.key);
|
const initialSelected = initialKey && items.some(item => item.key === initialKey) ? initialKey : items[0]?.key;
|
||||||
|
const [selected, setSelected] = useState(initialSelected);
|
||||||
const activeKey = items.some(item => item.key === selected) ? selected : items[0]?.key;
|
const activeKey = items.some(item => item.key === selected) ? selected : items[0]?.key;
|
||||||
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{item.children}</PageCacheContext.Provider> }))} />;
|
const [visited, setVisited] = useState(() => new Set(activeKey ? [activeKey] : []));
|
||||||
|
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); setVisited(previous => new Set(previous).add(key)); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{visited.has(item.key) ? item.children : null}</PageCacheContext.Provider> }))} />;
|
||||||
}
|
}
|
||||||
|
|||||||
+182
-94
@@ -1,5 +1,5 @@
|
|||||||
import { configurationDateTime } from './configurationName';
|
import { configurationDateTime } from './configurationName';
|
||||||
import { 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';
|
||||||
import { QualityTable as Table } from './QualityTable';
|
import { QualityTable as Table } from './QualityTable';
|
||||||
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
||||||
@@ -9,6 +9,10 @@ import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, D
|
|||||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||||
import { detectSourceWorkbook } from './sourceWorkbookDetection';
|
import { detectSourceWorkbook } from './sourceWorkbookDetection';
|
||||||
import { readableSelectPopup } from './readableSelectPopup';
|
import { readableSelectPopup } from './readableSelectPopup';
|
||||||
|
import { usePageCache } from './pageCache';
|
||||||
|
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
|
||||||
|
import { useVisiblePolling } from './useVisiblePolling';
|
||||||
|
import { runImportPollFollowup } from './importLifecycleGuards';
|
||||||
import './no-code-data-workflow.css';
|
import './no-code-data-workflow.css';
|
||||||
|
|
||||||
type Row = Record<string, unknown>;
|
type Row = Record<string, unknown>;
|
||||||
@@ -56,6 +60,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
|||||||
const [activeId, setActiveId] = useState('');
|
const [activeId, setActiveId] = useState('');
|
||||||
const [reading, setReading] = useState<{ done: number; total: number } | null>(null);
|
const [reading, setReading] = useState<{ done: number; total: number } | null>(null);
|
||||||
const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||||
|
const actionLock = useRef(false);
|
||||||
const uploadOperation = useDataWorkflowOperation('source-import', () => { setDrafts([]); setActiveId(''); configured.current.clear(); consumed.current.clear(); onRefresh(); message.success('所选来源已统一导入,报表已更新'); });
|
const uploadOperation = useDataWorkflowOperation('source-import', () => { setDrafts([]); setActiveId(''); configured.current.clear(); consumed.current.clear(); onRefresh(); message.success('所选来源已统一导入,报表已更新'); });
|
||||||
const recalcOperation = useDataWorkflowOperation('recalculate', value => { if (Array.isArray(value.sourceIds)) onDeleted(value.sourceIds.map(String)); onRefresh(); message.success('报表已更新'); });
|
const recalcOperation = useDataWorkflowOperation('recalculate', value => { if (Array.isArray(value.sourceIds)) onDeleted(value.sourceIds.map(String)); onRefresh(); message.success('报表已更新'); });
|
||||||
const active = drafts.find(item => item.id === activeId) || drafts[0];
|
const active = drafts.find(item => item.id === activeId) || drafts[0];
|
||||||
@@ -81,8 +86,9 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
|||||||
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) => { 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) return;
|
if (!files.length || importBusy || actionLock.current) return;
|
||||||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); if (input.current) input.current.value = ''; return; }
|
actionLock.current = true;
|
||||||
|
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); actionLock.current = false; if (input.current) input.current.value = ''; return; }
|
||||||
setBusy(true); setError(''); const failures: string[] = [];
|
setBusy(true); setError(''); const failures: string[] = [];
|
||||||
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
|
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
|
||||||
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
|
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
|
||||||
@@ -102,19 +108,19 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
|||||||
setReading({ done: Math.min(index + 2, selected.length), total: selected.length });
|
setReading({ done: Math.min(index + 2, selected.length), total: selected.length });
|
||||||
}
|
}
|
||||||
if (failures.length) setError(`以下文件未加入导入列表,可重新选择:${failures.join(';')}`);
|
if (failures.length) setError(`以下文件未加入导入列表,可重新选择:${failures.join(';')}`);
|
||||||
setReading(null); setBusy(false); if (input.current) input.current.value = '';
|
setReading(null); actionLock.current = false; setBusy(false); if (input.current) input.current.value = '';
|
||||||
};
|
};
|
||||||
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||||
if (!workbook) return; setBusy(true); setError('');
|
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
||||||
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||||
const previous = preferredMap || fieldMap;
|
const previous = preferredMap || fieldMap;
|
||||||
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
||||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const importAndUpdate = async () => {
|
const importAndUpdate = async () => {
|
||||||
if (!canImport || importBusy) return; setBusy(true); setError('');
|
if (!canImport || importBusy || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
const sourceIds: string[] = [];
|
const sourceIds: string[] = [];
|
||||||
for (const draft of drafts) {
|
for (const draft of drafts) {
|
||||||
@@ -128,12 +134,14 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
|||||||
consumed.current.add(uploadId); configured.current.set(draft.id, { signature, sourceId: result.source.id }); sourceIds.push(result.source.id);
|
consumed.current.add(uploadId); configured.current.set(draft.id, { signature, sourceId: result.source.id }); sourceIds.push(result.source.id);
|
||||||
}
|
}
|
||||||
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
|
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
|
||||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const recalculate = async () => {
|
const recalculate = async () => {
|
||||||
|
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; }
|
||||||
};
|
};
|
||||||
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">
|
||||||
@@ -183,33 +191,46 @@ function ValidationNotice({ value }: { value: unknown }) {
|
|||||||
|
|
||||||
export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
|
const { active } = usePageCache();
|
||||||
const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null);
|
const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null);
|
||||||
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||||
|
const [workflowStatusError, setWorkflowStatusError] = useState('');
|
||||||
|
const statusRead = useDelayedBusy();
|
||||||
|
const optionsRead = useDelayedBusy();
|
||||||
|
const candidatesRead = useDelayedBusy();
|
||||||
const [optionError, setOptionError] = useState('');
|
const [optionError, setOptionError] = useState('');
|
||||||
|
const [candidateError, setCandidateError] = useState('');
|
||||||
const [candidates, setCandidates] = useState<Row[]>([]);
|
const [candidates, setCandidates] = useState<Row[]>([]);
|
||||||
|
const [candidatesLoaded, setCandidatesLoaded] = useState(false);
|
||||||
|
const optionsAttempted = 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_MAINTAINER']);
|
||||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||||
const loadOptions = 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)); }
|
||||||
};
|
}), [onUnauthorized, optionsRead.run]);
|
||||||
const loadWorkflowStatus = async () => {
|
const loadWorkflowStatus = useCallback(() => statusRead.run(async () => {
|
||||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
|
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
|
||||||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatus(null); }
|
catch (error) { if (!onUnauthorized(error)) setWorkflowStatusError(failure(error)); }
|
||||||
finally { setWorkflowStatusLoaded(true); }
|
}), [onUnauthorized, statusRead.run]);
|
||||||
};
|
const loadCandidates = useCallback(() => candidatesRead.run(async () => {
|
||||||
const loadCandidates = async () => {
|
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); setCandidatesLoaded(true); setCandidateError(''); }
|
||||||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); }
|
catch (error) { if (!onUnauthorized(error)) setCandidateError(failure(error)); }
|
||||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
}), [candidatesRead.run, onUnauthorized]);
|
||||||
};
|
useEffect(() => {
|
||||||
useEffect(() => { void loadOptions(); void loadCandidates(); void loadWorkflowStatus(); }, [currentReleaseId, sources]);
|
if (!active) return;
|
||||||
|
if (!options && !optionsAttempted.current) { optionsAttempted.current = true; void loadOptions(); }
|
||||||
|
if (!candidatesLoaded && !candidatesAttempted.current) { candidatesAttempted.current = true; void loadCandidates(); }
|
||||||
|
if (!workflowStatusLoaded && !workflowStatusError) void loadWorkflowStatus();
|
||||||
|
}, [active, currentReleaseId, sources, options, candidatesLoaded, workflowStatusLoaded, workflowStatusError, loadOptions, loadCandidates, loadWorkflowStatus]);
|
||||||
useEffect(() => { const candidate = new URLSearchParams(window.location.search).get('candidateReleaseId'); if (candidate) setResumeId(candidate); }, []);
|
useEffect(() => { const candidate = new URLSearchParams(window.location.search).get('candidateReleaseId'); if (candidate) setResumeId(candidate); }, []);
|
||||||
const opened = mode !== null || Boolean(resumeId);
|
const opened = mode !== null || Boolean(resumeId);
|
||||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); void loadOptions(); };
|
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); if (!options) { optionsAttempted.current = true; void loadOptions(); } };
|
||||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status"><div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span></div><Spin /></section>;
|
if (!workflowStatusLoaded) return <section className="panel nc-operation-status">{statusRead.busy ? <div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span><Spin /></div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void loadWorkflowStatus()}>重试</Button>} /> : null}</section>;
|
||||||
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={onBusyChange} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={onBusyChange} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
||||||
return <>
|
return <>
|
||||||
<section className="nc-intake-start panel">
|
<section className="nc-intake-start panel">
|
||||||
@@ -217,39 +238,54 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
|
|||||||
<div className="nc-primary-actions"><Button type="primary" size="large" icon={<UploadOutlined />} disabled={!canMaintain || !options} onClick={() => open('ADD')}>上传新数据</Button><Button size="large" icon={<SwapOutlined />} disabled={!canMaintain || !options || !options.targets.length} onClick={() => open('REPLACE')}>替换已有数据</Button></div>
|
<div className="nc-primary-actions"><Button type="primary" size="large" icon={<UploadOutlined />} disabled={!canMaintain || !options} onClick={() => open('ADD')}>上传新数据</Button><Button size="large" icon={<SwapOutlined />} disabled={!canMaintain || !options || !options.targets.length} onClick={() => open('REPLACE')}>替换已有数据</Button></div>
|
||||||
<div className="nc-intake-links"><Button type="link" disabled={!canMaintain || !options?.targets.length} onClick={() => open('REBUILD')}>按当前来源重新计算</Button><span>上传 → 选择年月 → 匹配列 → 校验 → 发布</span></div>
|
<div className="nc-intake-links"><Button type="link" disabled={!canMaintain || !options?.targets.length} onClick={() => open('REBUILD')}>按当前来源重新计算</Button><span>上传 → 选择年月 → 匹配列 → 校验 → 发布</span></div>
|
||||||
</section>
|
</section>
|
||||||
{optionError && <Alert type="error" showIcon message="数据操作信息读取失败" description={optionError} action={<Button size="small" onClick={() => { void loadOptions(); void loadCandidates(); }}>重试</Button>} />}
|
{optionError && <Alert type="error" message="上传选项读取失败" showIcon description={options ? `${optionError};已成功读取的选项仍保留。` : optionError} action={<Button size="small" onClick={() => { optionsAttempted.current = true; void loadOptions(); }}>重试</Button>} />}
|
||||||
|
{candidateError && <Alert type="error" message="候选数据读取失败" showIcon description={candidatesLoaded ? `${candidateError};上次成功读取的候选仍保留。` : candidateError} action={<Button size="small" onClick={() => { candidatesAttempted.current = true; void loadCandidates(); }}>重试</Button>} />}
|
||||||
|
{!options && optionsRead.busy && <div className="completion-loading"><Spin />读取上传选项…</div>}
|
||||||
|
{!candidatesLoaded && candidatesRead.busy && <div className="completion-loading"><Spin />读取候选数据…</div>}
|
||||||
{!canMaintain && <Alert showIcon type="info" message={canPublish ? '当前账号可以核对和发布已有候选数据' : '上传和替换需要数据维护权限'} description="已授权的操作会按账号权限显示。" />}
|
{!canMaintain && <Alert showIcon type="info" message={canPublish ? '当前账号可以核对和发布已有候选数据' : '上传和替换需要数据维护权限'} description="已授权的操作会按账号权限显示。" />}
|
||||||
{candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
{candidatesLoaded && candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||||||
{opened && options && <DataUploadWizard key={`${mode}:${resumeId}`} user={user} mode={mode || 'ADD'} options={options} sources={sources} resumeId={resumeId} onUnauthorized={onUnauthorized} onClose={() => { setMode(null); setResumeId(''); }} onComplete={() => { onRefresh(); void loadOptions(); void loadCandidates(); message.success('操作结果已刷新'); }} />}
|
{opened && options && <DataUploadWizard key={`${mode}:${resumeId}`} user={user} mode={mode || 'ADD'} options={options} sources={sources} resumeId={resumeId} onUnauthorized={onUnauthorized} onClose={() => { setMode(null); setResumeId(''); }} onComplete={() => { onRefresh(); void loadOptions(); void loadCandidates(); message.success('操作结果已刷新'); }} />}
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; 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 { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
|
const { active } = usePageCache();
|
||||||
const [showDeleted, setShowDeleted] = useState(false);
|
const [showDeleted, setShowDeleted] = useState(false);
|
||||||
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
||||||
|
const [deletedLoaded, setDeletedLoaded] = useState(false);
|
||||||
|
const deletedRead = useDelayedBusy();
|
||||||
|
const [metadataError, setMetadataError] = useState('');
|
||||||
|
const metadataAttempted = useRef(false);
|
||||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||||
const [currentSourceIds, setCurrentSourceIds] = useState<string[] | null>(null);
|
const [currentSourceIds, setCurrentSourceIds] = useState<string[] | null>(null);
|
||||||
const [deletedLoading, setDeletedLoading] = useState(false);
|
|
||||||
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_MAINTAINER', 'DATA_PUBLISHER']);
|
||||||
const loadDeleted = async () => {
|
const loadDeleted = useCallback(() => deletedRead.run(async () => {
|
||||||
setDeletedLoading(true);
|
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); }
|
||||||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedError(''); }
|
|
||||||
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
||||||
finally { setDeletedLoading(false); }
|
}), [deletedRead.run, onUnauthorized]);
|
||||||
};
|
|
||||||
const sourceOperation = useDataWorkflowOperation('source-maintenance', value => {
|
const sourceOperation = useDataWorkflowOperation('source-maintenance', value => {
|
||||||
onRefresh(); if (showDeleted) void loadDeleted();
|
onRefresh(); if (showDeleted) void loadDeleted();
|
||||||
message.success(String(value.operationType || '').toUpperCase().includes('RESTORE') ? '来源已恢复,报表已更新' : '来源已删除,报表已更新');
|
message.success(String(value.operationType || '').toUpperCase().includes('RESTORE') ? '来源已恢复,报表已更新' : '来源已删除,报表已更新');
|
||||||
});
|
});
|
||||||
|
const loadMetadata = useCallback(async () => {
|
||||||
|
const [status, options] = await Promise.allSettled([api.dataWorkflowStatus(), api.sourceUploadOptions()]);
|
||||||
|
const errors: string[] = [];
|
||||||
|
if (status.status === 'fulfilled') { setWorkflowStatus(status.value); setWorkflowStatusLoaded(true); }
|
||||||
|
else if (!onUnauthorized(status.reason)) errors.push(`维护状态:${failure(status.reason)}`);
|
||||||
|
if (options.status === 'fulfilled') setCurrentSourceIds(options.value.currentSourceIds || []);
|
||||||
|
else if (!onUnauthorized(options.reason)) errors.push(`来源范围:${failure(options.reason)}`);
|
||||||
|
setMetadataError(errors.join(';'));
|
||||||
|
}, [onUnauthorized]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void api.dataWorkflowStatus().then(setWorkflowStatus).catch(() => setWorkflowStatus(null)).finally(() => setWorkflowStatusLoaded(true));
|
if (!active || metadataAttempted.current) return;
|
||||||
void api.sourceUploadOptions().then(options => setCurrentSourceIds(options.currentSourceIds || [])).catch(() => setCurrentSourceIds(null));
|
metadataAttempted.current = true;
|
||||||
}, [sources]);
|
void loadMetadata();
|
||||||
useEffect(() => { if (showDeleted && canOperate) void loadDeleted(); }, [showDeleted, sources]);
|
}, [active, sources, loadMetadata]);
|
||||||
|
useEffect(() => { if (active && showDeleted && canOperate && !deletedLoaded) void loadDeleted(); }, [active, showDeleted, canOperate, deletedLoaded, loadDeleted, sources]);
|
||||||
const period = (source: DeletionSource) => source.year && source.month ? `${source.year}年${String(source.month).padStart(2, '0')}月` : '尚未确认';
|
const period = (source: DeletionSource) => source.year && source.month ? `${source.year}年${String(source.month).padStart(2, '0')}月` : '尚未确认';
|
||||||
const close = () => { setSelected(null); const url = new URL(window.location.href); if (url.searchParams.has('sourceDeleteId')) { url.searchParams.delete('sourceDeleteId'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } };
|
const close = () => { setSelected(null); const url = new URL(window.location.href); if (url.searchParams.has('sourceDeleteId')) { url.searchParams.delete('sourceDeleteId'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } };
|
||||||
const simplified = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
const simplified = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||||||
@@ -262,9 +298,10 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
|
|||||||
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件${pendingIds.length ? ` · ${pendingIds.length} 个待删除` : ''}` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件${pendingIds.length ? ` · ${pendingIds.length} 个待删除` : ''}` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
||||||
{simplified && <p className="nc-source-maintenance-note">删除先标记为待删除,可连续操作和撤销,点击上方“更新报表”后统一生效。原文件和处理记录保留。</p>}
|
{simplified && <p className="nc-source-maintenance-note">删除先标记为待删除,可连续操作和撤销,点击上方“更新报表”后统一生效。原文件和处理记录保留。</p>}
|
||||||
{simplified && pendingIds.length > 0 && <div className="nc-source-maintenance-note"><Button disabled={maintenanceBusy} onClick={onClearDeletes}>撤销全部待删除({pendingIds.length})</Button></div>}
|
{simplified && pendingIds.length > 0 && <div className="nc-source-maintenance-note"><Button disabled={maintenanceBusy} onClick={onClearDeletes}>撤销全部待删除({pendingIds.length})</Button></div>}
|
||||||
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedLoaded ? `${deletedError};上次成功读取的来源仍保留。` : deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||||
|
{metadataError && <Alert showIcon type="error" message="来源操作信息读取失败" description={workflowStatusLoaded || currentSourceIds !== null ? `${metadataError};已成功读取的状态仍保留。` : metadataError} action={<Button size="small" onClick={() => { metadataAttempted.current = true; setMetadataError(''); void loadMetadata(); }}>重试</Button>} />}
|
||||||
{sourceOperation.operation && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
|
{sourceOperation.operation && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
|
||||||
<Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedLoading : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
{(!showDeleted && sourcesLoaded) || (showDeleted && (deletedLoaded || deletedRead.busy)) ? <Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedRead.busy : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
|
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
|
||||||
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
|
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
|
||||||
{ title: '统计期间', key: 'period', align: 'center', width: 140, render: (_, row) => period(row) },
|
{ title: '统计期间', key: 'period', align: 'center', width: 140, render: (_, row) => period(row) },
|
||||||
@@ -276,22 +313,24 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
|
|||||||
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={() => simplified ? showDeleted ? void runSourceOperation(row.id, true) : onToggleDelete(row.id) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
|
||||||
} },
|
} },
|
||||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} />
|
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null}
|
||||||
</section>
|
</section>
|
||||||
{selected && !simplified && <SourceDeletionDialog key={`${selected.id}:${selected.restore}`} user={user} sourceId={selected.id} restoring={selected.restore} sources={sources} onUnauthorized={onUnauthorized} onClose={close} onRefresh={() => { onRefresh(); if (showDeleted) void loadDeleted(); }} />}
|
{selected && !simplified && <SourceDeletionDialog key={`${selected.id}:${selected.restore}`} user={user} sourceId={selected.id} restoring={selected.restore} sources={sources} onUnauthorized={onUnauthorized} onClose={close} onRefresh={() => { onRefresh(); if (showDeleted) void loadDeleted(); }} />}
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthorized, onClose, onRefresh }: { user: AuthUser; sourceId: string; restoring: boolean; sources: SourceItem[]; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onRefresh: () => void }) {
|
function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthorized, onClose, onRefresh }: { user: AuthUser; sourceId: string; restoring: boolean; sources: SourceItem[]; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onRefresh: () => void }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp(); const { active } = usePageCache();
|
||||||
const [preview, setPreview] = useState<SourceDeletionPreview | null>(null);
|
const [preview, setPreview] = useState<SourceDeletionPreview | null>(null);
|
||||||
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
||||||
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
||||||
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||||
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
||||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
const actionLock = useRef(false); const candidateLock = useRef(false);
|
||||||
const load = async () => { setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } };
|
const showBusy = useDelayedIndicator(busy, 150);
|
||||||
useEffect(() => { void load(); }, [sourceId]);
|
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||||
|
const load = useCallback(async () => { if (!active || actionLock.current) return; setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } }, [active, reportError, restoring, sourceId]);
|
||||||
|
useEffect(() => { if (active) void load(); }, [active, load]);
|
||||||
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;
|
||||||
@@ -303,7 +342,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
|||||||
const actualRestore = Boolean((restoring || preview?.hidden) && !finished);
|
const actualRestore = Boolean((restoring || preview?.hidden) && !finished);
|
||||||
const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由';
|
const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由';
|
||||||
const act = async (kind: 'delete' | 'restore' | 'approve' | 'reject' | 'build') => {
|
const act = async (kind: 'delete' | 'restore' | 'approve' | 'reject' | 'build') => {
|
||||||
if (!preview) return; setBusy(true); setError('');
|
if (!active || !preview || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
if (kind === 'delete') {
|
if (kind === 'delete') {
|
||||||
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
||||||
@@ -325,12 +364,12 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
|||||||
}
|
}
|
||||||
setReason(''); setConfirmed(false); onRefresh();
|
setReason(''); setConfirmed(false); onRefresh();
|
||||||
} catch (value) { reportError(value); }
|
} catch (value) { reportError(value); }
|
||||||
finally { setBusy(false); }
|
finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const openCandidate = async (releaseId: string) => {
|
const openCandidate = async (releaseId: string) => {
|
||||||
setBusy(true); setError('');
|
if (!active || candidateLock.current) return; candidateLock.current = true; setBusy(true); setError('');
|
||||||
try { const support = await api.sourceUploadOptions(); setOptions(support); setCandidateId(releaseId); }
|
try { const support = await api.sourceUploadOptions(); setOptions(support); setCandidateId(releaseId); }
|
||||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
catch (value) { reportError(value); } finally { candidateLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const handoff = async () => {
|
const handoff = async () => {
|
||||||
const url = new URL(window.location.href); url.searchParams.set('page', 'sources'); url.searchParams.set('sourceDeleteId', sourceId); url.searchParams.delete('candidateReleaseId');
|
const url = new URL(window.location.href); url.searchParams.set('page', 'sources'); url.searchParams.set('sourceDeleteId', sourceId); url.searchParams.delete('candidateReleaseId');
|
||||||
@@ -343,9 +382,9 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
|||||||
<Button icon={<ReloadOutlined />} disabled={busy} onClick={() => void load()}>刷新状态</Button>
|
<Button icon={<ReloadOutlined />} disabled={busy} onClick={() => void load()}>刷新状态</Button>
|
||||||
{actualRestore ? <Button type="primary" loading={busy} disabled={!canRestore || !confirmed || !reason.trim()} onClick={() => void act('restore')}>确认恢复来源</Button> : isRequested ? <>{canReview && <><Button danger disabled={busy || !reason.trim()} onClick={() => void act('reject')}>驳回申请</Button><Button type="primary" loading={busy} disabled={!confirmed || !reason.trim()} onClick={() => void act('approve')}>批准删除申请</Button></>}</> : isApproved ? <Button type="primary" loading={busy} disabled={!canBuild || !confirmed} onClick={() => void act('build')}>生成删除候选</Button> : isBuilt ? <Button type="primary" loading={busy} disabled={!request?.resultReleaseId} onClick={() => { if (request?.resultReleaseId) void openCandidate(request.resultReleaseId); }}>核对并发布删除候选</Button> : <Button type="primary" danger loading={busy} disabled={!canStart || !confirmed || !reason.trim()} onClick={() => void act('delete')}>{withdrawing ? '提交删除申请' : '确认删除来源'}</Button>}
|
{actualRestore ? <Button type="primary" loading={busy} disabled={!canRestore || !confirmed || !reason.trim()} onClick={() => void act('restore')}>确认恢复来源</Button> : isRequested ? <>{canReview && <><Button danger disabled={busy || !reason.trim()} onClick={() => void act('reject')}>驳回申请</Button><Button type="primary" loading={busy} disabled={!confirmed || !reason.trim()} onClick={() => void act('approve')}>批准删除申请</Button></>}</> : isApproved ? <Button type="primary" loading={busy} disabled={!canBuild || !confirmed} onClick={() => void act('build')}>生成删除候选</Button> : isBuilt ? <Button type="primary" loading={busy} disabled={!request?.resultReleaseId} onClick={() => { if (request?.resultReleaseId) void openCandidate(request.resultReleaseId); }}>核对并发布删除候选</Button> : <Button type="primary" danger loading={busy} disabled={!canStart || !confirmed || !reason.trim()} onClick={() => void act('delete')}>{withdrawing ? '提交删除申请' : '确认删除来源'}</Button>}
|
||||||
</>}</div></div>}>
|
</>}</div></div>}>
|
||||||
{error && <Alert type="error" showIcon message="操作未完成" description={error} />}
|
{error && <Alert type="error" showIcon message="操作未完成" description={preview ? `${error};已成功读取的来源信息仍保留。` : error} action={!preview ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||||
{notice && <Alert type={finished ? 'success' : 'info'} showIcon message={notice} />}
|
{notice && <Alert type={finished ? 'success' : 'info'} showIcon message={notice} />}
|
||||||
<Spin spinning={busy}>{preview ? <>
|
<Spin spinning={showBusy}>{preview ? <>
|
||||||
<div className="nc-file-summary"><FileExcelOutlined /><strong>{preview.source.sourceFile}</strong><span>{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}</span></div>
|
<div className="nc-file-summary"><FileExcelOutlined /><strong>{preview.source.sourceFile}</strong><span>{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}</span></div>
|
||||||
{withdrawing && !actualRestore && <Steps className="nc-delete-steps" current={deletionStep} size="small" items={[{ title: '确认影响' }, { title: '审批申请' }, { title: '生成候选' }, { title: '对账与发布' }, { title: '移入已删除' }]} />}
|
{withdrawing && !actualRestore && <Steps className="nc-delete-steps" current={deletionStep} size="small" items={[{ title: '确认影响' }, { title: '审批申请' }, { title: '生成候选' }, { title: '对账与发布' }, { title: '移入已删除' }]} />}
|
||||||
<div className="nc-review-facts nc-deletion-impact"><div><small>当前正式数据</small><strong>{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}</strong></div><div><small>归档来源记录</small><strong>{preview.history.revisionCount} 个</strong></div><div><small>正式处理记录</small><strong>{preview.history.publishedReleaseCount} 个</strong></div><div><small>候选处理记录</small><strong>{preview.history.candidateReleaseCount} 个</strong></div></div>
|
<div className="nc-review-facts nc-deletion-impact"><div><small>当前正式数据</small><strong>{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}</strong></div><div><small>归档来源记录</small><strong>{preview.history.revisionCount} 个</strong></div><div><small>正式处理记录</small><strong>{preview.history.publishedReleaseCount} 个</strong></div><div><small>候选处理记录</small><strong>{preview.history.candidateReleaseCount} 个</strong></div></div>
|
||||||
@@ -358,97 +397,145 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
|||||||
</>}
|
</>}
|
||||||
{waitingForColleague && !awaitingTask && <Alert type="info" showIcon message={isRequested ? '等待有审批权限的发布者继续' : isApproved ? '等待有权限的发布者生成候选' : actualRestore ? '此账号没有恢复权限' : '此账号没有本次删除操作权限'} description={<>{preview.blockedReason && <p>{preview.blockedReason}</p>}<span>可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。</span><Button type="link" onClick={() => void handoff()}>复制处理链接</Button></>} />}
|
{waitingForColleague && !awaitingTask && <Alert type="info" showIcon message={isRequested ? '等待有审批权限的发布者继续' : isApproved ? '等待有权限的发布者生成候选' : actualRestore ? '此账号没有恢复权限' : '此账号没有本次删除操作权限'} description={<>{preview.blockedReason && <p>{preview.blockedReason}</p>}<span>可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。</span><Button type="link" onClick={() => void handoff()}>复制处理链接</Button></>} />}
|
||||||
{!finished && isBuilt && <Alert type="info" showIcon message="删除候选已保存,等待核对与发布" description="点击“核对并发布删除候选”继续查看差异;没有发布权限的账号可在候选窗口复制交接链接。" />}
|
{!finished && isBuilt && <Alert type="info" showIcon message="删除候选已保存,等待核对与发布" description="点击“核对并发布删除候选”继续查看差异;没有发布权限的账号可在候选窗口复制交接链接。" />}
|
||||||
</> : !busy ? <Empty description="未读取到来源信息" /> : <div className="loading-panel">正在核对来源及影响…</div>}</Spin>
|
</> : showBusy ? <div className="loading-panel">正在核对来源及影响…</div> : null}</Spin>
|
||||||
</Modal>
|
</Modal>
|
||||||
{candidateId && options && <DataUploadWizard key={`deletion:${candidateId}`} user={user} mode="ADD" purpose="WITHDRAW" handoffSourceId={sourceId} initialReason={request?.reason} options={options} sources={sources} resumeId={candidateId} onUnauthorized={onUnauthorized} onClose={() => { setCandidateId(''); void load(); }} onComplete={() => { setFinished(true); setNotice('删除候选已发布,该来源已从当前结果移除;原件和处理记录保留。'); onRefresh(); void load(); }} />}
|
{candidateId && options && <DataUploadWizard key={`deletion:${candidateId}`} user={user} mode="ADD" purpose="WITHDRAW" handoffSourceId={sourceId} initialReason={request?.reason} options={options} sources={sources} resumeId={candidateId} onUnauthorized={onUnauthorized} onClose={() => { setCandidateId(''); void load(); }} onComplete={() => { setFinished(true); setNotice('删除候选已发布,该来源已从当前结果移除;原件和处理记录保留。'); onRefresh(); void load(); }} />}
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
||||||
const { message } = App.useApp(); const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||||
const [pollAttempt, setPollAttempt] = useState(0);
|
const runStorageKey = `quality-import-run:${user.id}`;
|
||||||
const [step, setStep] = useState(resumeId ? 4 : 0); const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
const [storedRunId] = useState(() => { try { return localStorage.getItem(runStorageKey) || ''; } catch { return ''; } });
|
||||||
|
const [step, setStep] = useState(resumeId ? 4 : storedRunId ? 3 : 0); const [busy, setBusy] = useState(Boolean(storedRunId)); const [error, setError] = useState('');
|
||||||
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null); const [stage, setStage] = useState<DataStage>('black');
|
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null); const [stage, setStage] = useState<DataStage>('black');
|
||||||
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
||||||
const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL'); const [targetId, setTargetId] = useState('');
|
const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL'); const [targetId, setTargetId] = useState('');
|
||||||
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
||||||
const [configuredSourceId, setConfiguredSourceId] = useState('');
|
const [configuredSourceId, setConfiguredSourceId] = useState('');
|
||||||
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(null); const [release, setRelease] = useState<Row | null>(null);
|
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(() => storedRunId ? { id: storedRunId, status: 'RUNNING' } : null); const [release, setRelease] = useState<Row | null>(null);
|
||||||
|
const [runTerminalId, setRunTerminalId] = useState('');
|
||||||
|
const completionNotified = useRef(new Set<string>());
|
||||||
|
const actionLock = useRef(false); const pollLock = useRef(false); const pollAgainAfterCurrent = useRef(false); const candidateReadLock = useRef(false);
|
||||||
|
const runIdRef = useRef('');
|
||||||
const [reconciliation, setReconciliation] = useState<Row | null>(null); const [issues, setIssues] = useState<Row[]>([]);
|
const [reconciliation, setReconciliation] = useState<Row | null>(null); const [issues, setIssues] = useState<Row[]>([]);
|
||||||
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_PUBLISHER']);
|
||||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||||
const loadCandidate = async (id: string) => {
|
const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => {
|
||||||
const inspected = await api.governanceReleaseInspect(id); setRelease(asRow(inspected.release));
|
if (!activeRef.current || !isCurrent()) return false;
|
||||||
const result = await api.governanceReleaseReconciliations(id); const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
const inspected = await api.governanceReleaseInspect(id);
|
||||||
setReconciliation(selected?.id ? await api.governanceReconciliation(String(selected.id)) : null);
|
if (!activeRef.current || !isCurrent()) return false;
|
||||||
|
setRelease(asRow(inspected.release));
|
||||||
|
const result = await api.governanceReleaseReconciliations(id);
|
||||||
|
if (!activeRef.current || !isCurrent()) return false;
|
||||||
|
const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||||||
|
const reconciliation = selected?.id ? await api.governanceReconciliation(String(selected.id)) : null;
|
||||||
|
if (!activeRef.current || !isCurrent()) return false;
|
||||||
|
setReconciliation(reconciliation);
|
||||||
|
return true;
|
||||||
};
|
};
|
||||||
useEffect(() => { if (resumeId) { setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => setBusy(false)); } return () => { generation.current++; }; }, []);
|
|
||||||
const runId = String(run?.id || '');
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!runId) return;
|
if (!active || !resumeId || candidateReadLock.current) return;
|
||||||
let alive = true; let timer: ReturnType<typeof setTimeout>;
|
candidateReadLock.current = true; setBusy(true);
|
||||||
const poll = async () => {
|
loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); });
|
||||||
try {
|
return () => { generation.current++; };
|
||||||
const result = await api.importRun(runId); if (!alive) return; setRun(result.run);
|
}, [active, reportError, resumeId]);
|
||||||
if (String(result.run.status) === 'COMPLETED') {
|
const runId = String(run?.id || '');
|
||||||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
runIdRef.current = runId;
|
||||||
await loadCandidate(id); if (!alive) return; setStep(4); setBusy(false); onComplete();
|
const pollRun = useCallback(async () => {
|
||||||
if (asRow(result.run.validation).complete === false) { const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList)); }
|
if (!activeRef.current || !runId) return;
|
||||||
} else if (['FAILED', 'CANCELLED'].includes(String(result.run.status))) {
|
if (pollLock.current) { pollAgainAfterCurrent.current = true; return; }
|
||||||
setBusy(false); const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList));
|
pollLock.current = true;
|
||||||
} else timer = setTimeout(poll, 1400);
|
try {
|
||||||
} catch (value) { if (alive) { reportError(value); setBusy(false); } }
|
const result = await api.importRun(runId);
|
||||||
};
|
const isCurrent = () => activeRef.current && runIdRef.current === runId;
|
||||||
timer = setTimeout(poll, 700); return () => { alive = false; clearTimeout(timer); };
|
if (!isCurrent()) return;
|
||||||
}, [runId, pollAttempt]);
|
setRun(result.run); setError('');
|
||||||
|
const status = String(result.run.status || '').toUpperCase();
|
||||||
|
if (status === 'COMPLETED') {
|
||||||
|
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||||||
|
const candidateRead = await runImportPollFollowup(runId, () => isCurrent(), () => loadCandidate(id, isCurrent));
|
||||||
|
if (!candidateRead.started || !candidateRead.current || !candidateRead.value || !isCurrent()) return;
|
||||||
|
setStep(4);
|
||||||
|
if (asRow(result.run.validation).complete === false) {
|
||||||
|
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||||||
|
if (!issueRead.started || !issueRead.current) return;
|
||||||
|
setIssues(collectionItems(issueRead.value));
|
||||||
|
}
|
||||||
|
if (!completionNotified.current.has(runId)) { completionNotified.current.add(runId); onComplete(); }
|
||||||
|
setRunTerminalId(runId); setBusy(false);
|
||||||
|
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||||||
|
} else if (['FAILED', 'CANCELLED'].includes(status)) {
|
||||||
|
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||||||
|
if (!issueRead.started || !issueRead.current) return;
|
||||||
|
setIssues(collectionItems(issueRead.value)); setRunTerminalId(runId); setBusy(false);
|
||||||
|
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||||||
|
}
|
||||||
|
} catch (value) { if (activeRef.current && runIdRef.current === runId) { reportError(value); setBusy(false); } }
|
||||||
|
finally {
|
||||||
|
pollLock.current = false;
|
||||||
|
if (pollAgainAfterCurrent.current && activeRef.current && runIdRef.current === runId) {
|
||||||
|
pollAgainAfterCurrent.current = false;
|
||||||
|
void pollRun();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [loadCandidate, onComplete, reportError, runId, runStorageKey]);
|
||||||
|
useVisiblePolling(pollRun, 2000, active && Boolean(runId) && runTerminalId !== runId, true);
|
||||||
const readFile = async (file?: File) => {
|
const readFile = async (file?: File) => {
|
||||||
if (!file) return; setBusy(true); setError(''); const ownGeneration = generation.current;
|
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); const ownGeneration = generation.current;
|
||||||
try { const result = await api.previewSourceWorkbook(file); if (ownGeneration !== generation.current) return; setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); setFieldMap(matchFields(options.fields[stage] || [], result.preview.headers)); setStep(1); }
|
try { const result = await api.previewSourceWorkbook(file); if (ownGeneration !== generation.current) return; setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); setFieldMap(matchFields(options.fields[stage] || [], result.preview.headers)); setStep(1); }
|
||||||
catch (value) { reportError(value); } finally { setBusy(false); if (input.current) input.current.value = ''; }
|
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); if (input.current) input.current.value = ''; }
|
||||||
};
|
};
|
||||||
const changePreview = async (nextSheet: string, nextHeader: number, nextStage = stage, preferredMap?: Record<string, string>) => {
|
const changePreview = async (nextSheet: string, nextHeader: number, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||||
if (!workbook) return; setBusy(true); setError('');
|
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try { const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage }); setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); const chosen = preferredMap || fieldMap; setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(chosen).filter(([, header]) => result.preview.headers.includes(header))) }); }
|
try { const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage }); setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); const chosen = preferredMap || fieldMap; setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(chosen).filter(([, header]) => result.preview.headers.includes(header))) }); }
|
||||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const chooseTarget = (id: string) => { const selected = options.targets.find(item => item.documentId === id); setTargetId(id); if (selected) { setStage(selected.stage); setYear(selected.year); setMonth(selected.month); setScopeCode(selected.scopeCode); setFieldMap(matchFields(options.fields[selected.stage] || [], headers)); } };
|
const chooseTarget = (id: string) => { const selected = options.targets.find(item => item.documentId === id); setTargetId(id); if (selected) { setStage(selected.stage); setYear(selected.year); setMonth(selected.month); setScopeCode(selected.scopeCode); setFieldMap(matchFields(options.fields[selected.stage] || [], headers)); } };
|
||||||
const beginImport = async () => {
|
const beginImport = async () => {
|
||||||
if (!workbook || missingFields.length || (mode === 'REPLACE' && !target)) return;
|
if (!active || !workbook || missingFields.length || (mode === 'REPLACE' && !target) || actionLock.current) return;
|
||||||
|
actionLock.current = true;
|
||||||
setBusy(true); setError('');
|
setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
const configured = configuredSourceId ? { source: { id: configuredSourceId } } : await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode: mode === 'REPLACE' ? 'REPLACE' : 'ADD', expectedCurrentReleaseId: options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: reason.trim() || `新增${year}年${month}月${stageName(stage)}数据`, scopeCode });
|
const configured = configuredSourceId ? { source: { id: configuredSourceId } } : await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode: mode === 'REPLACE' ? 'REPLACE' : 'ADD', expectedCurrentReleaseId: options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: reason.trim() || `新增${year}年${month}月${stageName(stage)}数据`, scopeCode });
|
||||||
setConfiguredSourceId(configured.source.id);
|
setConfiguredSourceId(configured.source.id);
|
||||||
const created = asRow(await api.startImport({ sourceIds: [configured.source.id], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); const nextRun = asRow(created.run || created); setRun(nextRun);
|
const created = asRow(await api.startImport({ sourceIds: [configured.source.id], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); const nextRun = asRow(created.run || created); setRun(nextRun);
|
||||||
if (!nextRun.id) throw new Error('服务端未返回计算任务,已接收的来源可稍后重新校验');
|
if (!nextRun.id) throw new Error('服务端未返回计算任务,已接收的来源可稍后重新校验');
|
||||||
|
try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||||||
} catch (value) { reportError(value); setBusy(false); }
|
} catch (value) { reportError(value); setBusy(false); }
|
||||||
|
finally { actionLock.current = false; }
|
||||||
};
|
};
|
||||||
const rebuild = async () => {
|
const rebuild = async () => {
|
||||||
|
if (!active || actionLock.current) return; actionLock.current = true;
|
||||||
setBusy(true); setError(''); setStep(3);
|
setBusy(true); setError(''); setStep(3);
|
||||||
try {
|
try {
|
||||||
if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源');
|
if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源');
|
||||||
const inspected = await api.governanceReleaseInspect(options.currentReleaseId); const members = asRows(inspected.members);
|
const inspected = await api.governanceReleaseInspect(options.currentReleaseId); const members = asRows(inspected.members);
|
||||||
const ids = options.currentSourcesComplete && options.currentSourceIds?.length ? options.currentSourceIds : members.map(member => sources.find(source => source.sha256 === member.sha256 && source.stage === member.stage && source.year === Number(member.sourceYear) && source.month === Number(member.sourceMonth))?.id);
|
const ids = options.currentSourcesComplete && options.currentSourceIds?.length ? options.currentSourceIds : members.map(member => sources.find(source => source.sha256 === member.sha256 && source.stage === member.stage && source.year === Number(member.sourceYear) && source.month === Number(member.sourceMonth))?.id);
|
||||||
if (!ids.length || ids.some(id => !id)) throw new Error('部分原始文件当前不可用于重算,请重新上传缺少的原始文件。');
|
if (!ids.length || ids.some(id => !id)) throw new Error('部分原始文件当前不可用于重算,请重新上传缺少的原始文件。');
|
||||||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); setRun(asRow(created.run || created));
|
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current }));
|
||||||
|
const nextRun = asRow(created.run || created); if (!nextRun.id) throw new Error('服务端未返回计算任务编号');
|
||||||
|
setRun(nextRun); try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||||||
} catch (value) { reportError(value); setBusy(false); }
|
} catch (value) { reportError(value); setBusy(false); }
|
||||||
|
finally { actionLock.current = false; }
|
||||||
};
|
};
|
||||||
const reconcile = async () => {
|
const reconcile = async () => {
|
||||||
if (!release?.id) return; setBusy(true); setError('');
|
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try { const created = await api.createGovernanceReconciliation(String(release.id), { ...(options.currentReleaseId ? { baselineReleaseId: options.currentReleaseId } : {}), dimensions: ['overall', 'department', 'group', 'product', 'projectGroup'] }); const detail = asRow(created.reconciliation || created); setReconciliation(detail.id ? await api.governanceReconciliation(String(detail.id)) : detail); setConfirmDifferences(false); }
|
try { const created = await api.createGovernanceReconciliation(String(release.id), { ...(options.currentReleaseId ? { baselineReleaseId: options.currentReleaseId } : {}), dimensions: ['overall', 'department', 'group', 'product', 'projectGroup'] }); const detail = asRow(created.reconciliation || created); setReconciliation(detail.id ? await api.governanceReconciliation(String(detail.id)) : detail); setConfirmDifferences(false); }
|
||||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const confirm = async () => {
|
const confirm = async () => {
|
||||||
if (!reconciliation?.id) return; setBusy(true); setError('');
|
if (!active || !reconciliation?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try { const evidence = asRow(reconciliation.result); const result = await api.confirmGovernanceReconciliation(String(reconciliation.id), { expectedRowVersion: Number(reconciliation.rowVersion || 0), expectedDifferenceHash: String(reconciliation.differenceHash), ...(evidence.transitionDifferenceHash ? { expectedTransitionDifferenceHash: String(evidence.transitionDifferenceHash) } : {}), reason: differenceReason.trim() }); setReconciliation(result); }
|
try { const evidence = asRow(reconciliation.result); const result = await api.confirmGovernanceReconciliation(String(reconciliation.id), { expectedRowVersion: Number(reconciliation.rowVersion || 0), expectedDifferenceHash: String(reconciliation.differenceHash), ...(evidence.transitionDifferenceHash ? { expectedTransitionDifferenceHash: String(evidence.transitionDifferenceHash) } : {}), reason: differenceReason.trim() }); setReconciliation(result); }
|
||||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const publish = async () => {
|
const publish = async () => {
|
||||||
if (!release?.id) return; setBusy(true); setError('');
|
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try { await api.publishRelease(String(release.id), { expectedCurrentReleaseId: release.expectedCurrentReleaseId === undefined ? options.currentReleaseId : release.expectedCurrentReleaseId as string | null, idempotencyKey: publishKey.current, reason: reason.trim() || differenceReason.trim() || '经来源校验与候选基线对账后发布' }); setPublished(true); onComplete(); }
|
try { await api.publishRelease(String(release.id), { expectedCurrentReleaseId: release.expectedCurrentReleaseId === undefined ? options.currentReleaseId : release.expectedCurrentReleaseId as string | null, idempotencyKey: publishKey.current, reason: reason.trim() || differenceReason.trim() || '经来源校验与候选基线对账后发布' }); setPublished(true); onComplete(); }
|
||||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const evidence = asRow(reconciliation?.result); const comparisons = asRows(evidence.periodComparisons); const reconciliationErrors = Array.isArray(evidence.errors) ? evidence.errors : [];
|
const evidence = asRow(reconciliation?.result); const comparisons = asRows(evidence.periodComparisons); const reconciliationErrors = Array.isArray(evidence.errors) ? evidence.errors : [];
|
||||||
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
|
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
|
||||||
@@ -456,13 +543,13 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
|
|||||||
const close = () => { generation.current++; onClose(); };
|
const close = () => { generation.current++; onClose(); };
|
||||||
return <Modal className="management-modal nc-workflow-modal" open width={1120} title={published ? purpose === 'WITHDRAW' ? '来源删除已发布' : '数据已发布' : purpose === 'WITHDRAW' ? '核对并发布删除候选' : resumeId ? '继续处理候选数据' : mode === 'REPLACE' ? '替换已有数据' : mode === 'REBUILD' ? '按当前来源重新计算' : '上传新数据'} onCancel={close} maskClosable={!busy} footer={<div className="nc-modal-footer"><span>{runId ? '关闭后任务继续,可在“数据接入”的“导入记录”查看;完成后从候选继续。' : '确认发布前,当前查询结果保持不变。'}</span><div>{step > 0 && step < 4 && !runId && !configuredSourceId && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={mode === 'REPLACE' && !target} loading={busy} onClick={() => { setStep(2); void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={Boolean(missingFields.length) || duplicateColumns || !sheetName} onClick={() => { if (workbook && (workbook.preview.headerRow !== headerRow || workbook.preview.sheetName !== sheetName)) { void changePreview(sheetName, headerRow); return; } setStep(3); }}>下一步:预览验证</Button>}{!published && step === 3 && !runId && mode !== 'REBUILD' && <Button type="primary" loading={busy} disabled={mode === 'REPLACE' && !reason.trim()} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
|
return <Modal className="management-modal nc-workflow-modal" open width={1120} title={published ? purpose === 'WITHDRAW' ? '来源删除已发布' : '数据已发布' : purpose === 'WITHDRAW' ? '核对并发布删除候选' : resumeId ? '继续处理候选数据' : mode === 'REPLACE' ? '替换已有数据' : mode === 'REBUILD' ? '按当前来源重新计算' : '上传新数据'} onCancel={close} maskClosable={!busy} footer={<div className="nc-modal-footer"><span>{runId ? '关闭后任务继续,可在“数据接入”的“导入记录”查看;完成后从候选继续。' : '确认发布前,当前查询结果保持不变。'}</span><div>{step > 0 && step < 4 && !runId && !configuredSourceId && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={mode === 'REPLACE' && !target} loading={busy} onClick={() => { setStep(2); void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={Boolean(missingFields.length) || duplicateColumns || !sheetName} onClick={() => { if (workbook && (workbook.preview.headerRow !== headerRow || workbook.preview.sheetName !== sheetName)) { void changePreview(sheetName, headerRow); return; } setStep(3); }}>下一步:预览验证</Button>}{!published && step === 3 && !runId && mode !== 'REBUILD' && <Button type="primary" loading={busy} disabled={mode === 'REPLACE' && !reason.trim()} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
|
||||||
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
|
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
|
||||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} />}
|
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} action={resumeId && step === 4 ? <Button size="small" disabled={!active || busy || candidateReadLock.current} onClick={() => { if (!activeRef.current || candidateReadLock.current) return; candidateReadLock.current = true; setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); }); }}>重试读取候选</Button> : runId ? <Button size="small" disabled={!active || busy || pollLock.current} onClick={() => { if (!activeRef.current || pollLock.current) return; setBusy(true); void pollRun(); }}>重新获取处理结果</Button> : undefined} />}
|
||||||
{published ? <div className="nc-success"><FileExcelOutlined /><h2>{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}</h2><p>来源原件和本次对账记录均已保留。</p></div> : <>
|
{published ? <div className="nc-success"><FileExcelOutlined /><h2>{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}</h2><p>来源原件和本次对账记录均已保留。</p></div> : <>
|
||||||
{step === 0 && (mode === 'REBUILD' ? <div className="nc-rebuild-confirm"><h3>使用当前数据所用的全部来源重新计算</h3><p>计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。</p><div className="nc-target-list">{options.targets.map(item => <div key={item.documentId}><Tag>{stageName(item.stage)}</Tag><strong>{item.year}年{item.month}月</strong><span>{item.sourceFile}</span></div>)}</div><Button type="primary" loading={busy} disabled={!options.targets.length} onClick={() => void rebuild()}>开始重新计算</Button></div> : <div className="nc-file-drop"><FileExcelOutlined /><h3>选择要{mode === 'REPLACE' ? '替换' : '上传'}的 Excel 文件</h3><p>支持 .xlsx;保留你的文件名,接下来选择数据期间和表头。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" /><Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button></div>)}
|
{step === 0 && (mode === 'REBUILD' ? <div className="nc-rebuild-confirm"><h3>使用当前数据所用的全部来源重新计算</h3><p>计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。</p><div className="nc-target-list">{options.targets.map(item => <div key={item.documentId}><Tag>{stageName(item.stage)}</Tag><strong>{item.year}年{item.month}月</strong><span>{item.sourceFile}</span></div>)}</div><Button type="primary" loading={busy} disabled={!options.targets.length} onClick={() => void rebuild()}>开始重新计算</Button></div> : <div className="nc-file-drop"><FileExcelOutlined /><h3>选择要{mode === 'REPLACE' ? '替换' : '上传'}的 Excel 文件</h3><p>支持 .xlsx;保留你的文件名,接下来选择数据期间和表头。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" /><Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button></div>)}
|
||||||
{workbook && step > 0 && step < 4 && <div className="nc-file-summary"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong><span>{stageName(stage)} · {year}年{month}月</span></div>}
|
{workbook && step > 0 && step < 4 && <div className="nc-file-summary"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong><span>{stageName(stage)} · {year}年{month}月</span></div>}
|
||||||
{step === 1 && <Form layout="vertical"><div className="nc-form-grid">{mode === 'REPLACE' ? <Form.Item className="nc-full-width" label="选择当前数据中的替换目标" required><Select {...readableSelectPopup} aria-label="选择当前数据中的替换目标" showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择年月、阶段和原文件" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.sourceFile}` }))} onChange={chooseTarget} /></Form.Item> : <><Form.Item label="数据阶段" required><Select aria-label="数据阶段" value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></Form.Item><Form.Item label="统计年份" required><InputNumber aria-label="统计年份" min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></Form.Item><Form.Item label="统计月份" required><Select aria-label="统计月份" value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={setMonth} /></Form.Item>{options.scopes.length > 1 && <Form.Item label="数据范围" required><Select aria-label="数据范围" value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} /></Form.Item>}</>}</div>{target && <div className="nc-replacement"><span>原文件</span><strong>{target.sourceFile}</strong><ArrowRightOutlined /><span>新文件</span><strong>{workbook?.sourceFile}</strong></div>}<Form.Item label={mode === 'REPLACE' ? '替换理由' : '本次说明'} required={mode === 'REPLACE'}><Input.TextArea aria-label={mode === 'REPLACE' ? '替换理由' : '本次说明'} value={reason} rows={2} maxLength={1000} placeholder={mode === 'REPLACE' ? '例如:补齐遗漏记录,使用更新后的完整月表' : '可填写本次数据说明'} onChange={event => setReason(event.target.value)} /></Form.Item></Form>}
|
{step === 1 && <Form layout="vertical"><div className="nc-form-grid">{mode === 'REPLACE' ? <Form.Item className="nc-full-width" label="选择当前数据中的替换目标" required><Select {...readableSelectPopup} aria-label="选择当前数据中的替换目标" showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择年月、阶段和原文件" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.sourceFile}` }))} onChange={chooseTarget} /></Form.Item> : <><Form.Item label="数据阶段" required><Select aria-label="数据阶段" value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></Form.Item><Form.Item label="统计年份" required><InputNumber aria-label="统计年份" min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></Form.Item><Form.Item label="统计月份" required><Select aria-label="统计月份" value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={setMonth} /></Form.Item>{options.scopes.length > 1 && <Form.Item label="数据范围" required><Select aria-label="数据范围" value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} /></Form.Item>}</>}</div>{target && <div className="nc-replacement"><span>原文件</span><strong>{target.sourceFile}</strong><ArrowRightOutlined /><span>新文件</span><strong>{workbook?.sourceFile}</strong></div>}<Form.Item label={mode === 'REPLACE' ? '替换理由' : '本次说明'} required={mode === 'REPLACE'}><Input.TextArea aria-label={mode === 'REPLACE' ? '替换理由' : '本次说明'} value={reason} rows={2} maxLength={1000} placeholder={mode === 'REPLACE' ? '例如:补齐遗漏记录,使用更新后的完整月表' : '可填写本次数据说明'} onChange={event => setReason(event.target.value)} /></Form.Item></Form>}
|
||||||
{step === 2 && workbook && <><div className="nc-form-grid"><Form.Item label="工作表" required><Select aria-label="数据工作表" value={sheetName} options={workbook.sheets.map(sheet => ({ value: sheet.sheetName, label: sheet.sheetName }))} onChange={value => void changePreview(value, headerRow)} /></Form.Item><Form.Item label="表头在第几行" required><InputNumber aria-label="表头所在行" min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); }} onBlur={() => { if (headerRow !== workbook.preview.headerRow) void changePreview(sheetName, headerRow); }} onPressEnter={() => void changePreview(sheetName, headerRow)} /></Form.Item></div><div className="nc-section-title"><h3>业务字段对应 Excel 中哪一列</h3><span>{duplicateColumns ? '同一 Excel 列不能对应多个业务字段' : missingFields.length ? `还需选择 ${missingFields.length} 个必填字段` : '必填字段已全部匹配'}</span></div><Spin spinning={busy}><ColumnMatching fields={fields} headers={headers} value={fieldMap} onChange={setFieldMap} /></Spin><h3>原表前几行</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} /></>}
|
{step === 2 && workbook && <><div className="nc-form-grid"><Form.Item label="工作表" required><Select aria-label="数据工作表" value={sheetName} options={workbook.sheets.map(sheet => ({ value: sheet.sheetName, label: sheet.sheetName }))} onChange={value => void changePreview(value, headerRow)} /></Form.Item><Form.Item label="表头在第几行" required><InputNumber aria-label="表头所在行" min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); }} onBlur={() => { if (headerRow !== workbook.preview.headerRow) void changePreview(sheetName, headerRow); }} onPressEnter={() => void changePreview(sheetName, headerRow)} /></Form.Item></div><div className="nc-section-title"><h3>业务字段对应 Excel 中哪一列</h3><span>{duplicateColumns ? '同一 Excel 列不能对应多个业务字段' : missingFields.length ? `还需选择 ${missingFields.length} 个必填字段` : '必填字段已全部匹配'}</span></div><Spin spinning={busy}><ColumnMatching fields={fields} headers={headers} value={fieldMap} onChange={setFieldMap} /></Spin><h3>原表前几行</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} /></>}
|
||||||
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button onClick={() => { setBusy(true); setPollAttempt(previous => previous + 1); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button disabled={!active || pollLock.current} onClick={() => { if (!activeRef.current || pollLock.current) return; setBusy(true); void pollRun(); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
||||||
{step === 4 && <Spin spinning={busy}><div className="nc-review-facts"><div><small>候选数据</small><strong>待核对</strong></div><div><small>来源校验</small><strong>{release?.complete === true ? '通过' : '尚未通过'}</strong></div><div><small>基线对账</small><strong>{statusLabel[String(reconciliation?.status)] || '待执行'}</strong></div></div><ValidationNotice value={release?.validation || run?.validation} />{reconciliationErrors.length > 0 && <Alert showIcon type="error" message="对账存在阻断事项" description={reconciliationErrors.map(txt).join(';')} />}<div className="nc-section-title"><h3>与当前数据的差异</h3><Button icon={<ReloadOutlined />} loading={busy} disabled={!release?.id} onClick={() => void reconcile()}>{reconciliation ? '重新对账' : '执行基线对账'}</Button></div>{comparisons.length > 0 ? <Table size="small" bordered dataSource={comparisons} rowKey={(row, index) => `${row.dimension}:${row.key}:${index}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 900 }} columns={[{ title: '期间', width: 130, render: (_, row) => { const period = asRow(row.period); return `${txt(period.year)}年${period.month ? `${txt(period.month)}月` : period.quarter ? `第${txt(period.quarter)}季度` : '全年'}`; } }, { title: '维度 / 对象', width: 200, render: (_, row) => `${({ overall: '总体', department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(row.dimension)] || txt(row.dimension)} / ${txt(row.key)}` }, { title: '原综合率', width: 120, render: (_, row) => ratio(asRow(row.before).compositeRate) }, { title: '新综合率', width: 120, render: (_, row) => ratio(asRow(row.after).compositeRate) }, { title: '差异', render: (_, row) => asRows(row.differences).map(item => `${metricLabel(item.path)}:${txt(item.before)} → ${txt(item.after)}`).join(';') || '一致' }]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={reconciliation ? '本次没有可展示的期间比较;以对账结论为准' : '执行对账后在这里查看期间和指标差异'} />}{reconciliation?.status === 'REVIEW_REQUIRED' && <div className="nc-difference-confirm"><Alert type="warning" showIcon message={`发现 ${txt(evidence.differenceCount)} 项差异,需要发布者确认`} />{canPublish ? <><Input.TextArea aria-label="业务差异确认理由" rows={2} value={differenceReason} maxLength={1000} placeholder="填写差异原因及确认依据" onChange={event => setDifferenceReason(event.target.value)} /><Checkbox checked={confirmDifferences} onChange={event => setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确</Checkbox><Button type="primary" disabled={!confirmDifferences || !differenceReason.trim() || busy} onClick={() => void confirm()}>确认差异并验收</Button></> : <p>候选已保存,请交由有数据发布权限的同事完成差异确认。</p>}</div>}{canPublish ? <div className="nc-publish-confirm"><Checkbox disabled={!publishReady} checked={publishConfirmed} onChange={event => setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}</Checkbox><Button size="large" type="primary" disabled={!publishReady || !publishConfirmed || busy} onClick={() => void publish()}>确认发布</Button>{!publishReady && <span>来源校验和基线对账通过后可发布。</span>}</div> : <Alert showIcon type="info" message="候选数据已保存,等待有权限的同事发布" description={<><span>当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。</span><Button type="link" onClick={() => { const link = new URL(window.location.href); link.searchParams.set('page', 'sources'); if (handoffSourceId) { link.searchParams.set('sourceDeleteId', handoffSourceId); link.searchParams.delete('candidateReleaseId'); } else { link.searchParams.set('candidateReleaseId', String(release?.id || '')); link.searchParams.delete('sourceDeleteId'); } void navigator.clipboard.writeText(link.toString()).then(() => message.success('处理链接已复制')).catch(reportError); }}>复制处理链接</Button></>} />}</Spin>}
|
{step === 4 && <Spin spinning={busy}><div className="nc-review-facts"><div><small>候选数据</small><strong>待核对</strong></div><div><small>来源校验</small><strong>{release?.complete === true ? '通过' : '尚未通过'}</strong></div><div><small>基线对账</small><strong>{statusLabel[String(reconciliation?.status)] || '待执行'}</strong></div></div><ValidationNotice value={release?.validation || run?.validation} />{reconciliationErrors.length > 0 && <Alert showIcon type="error" message="对账存在阻断事项" description={reconciliationErrors.map(txt).join(';')} />}<div className="nc-section-title"><h3>与当前数据的差异</h3><Button icon={<ReloadOutlined />} loading={busy} disabled={!release?.id} onClick={() => void reconcile()}>{reconciliation ? '重新对账' : '执行基线对账'}</Button></div>{comparisons.length > 0 ? <Table size="small" bordered dataSource={comparisons} rowKey={(row, index) => `${row.dimension}:${row.key}:${index}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 900 }} columns={[{ title: '期间', width: 130, render: (_, row) => { const period = asRow(row.period); return `${txt(period.year)}年${period.month ? `${txt(period.month)}月` : period.quarter ? `第${txt(period.quarter)}季度` : '全年'}`; } }, { title: '维度 / 对象', width: 200, render: (_, row) => `${({ overall: '总体', department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(row.dimension)] || txt(row.dimension)} / ${txt(row.key)}` }, { title: '原综合率', width: 120, render: (_, row) => ratio(asRow(row.before).compositeRate) }, { title: '新综合率', width: 120, render: (_, row) => ratio(asRow(row.after).compositeRate) }, { title: '差异', render: (_, row) => asRows(row.differences).map(item => `${metricLabel(item.path)}:${txt(item.before)} → ${txt(item.after)}`).join(';') || '一致' }]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={reconciliation ? '本次没有可展示的期间比较;以对账结论为准' : '执行对账后在这里查看期间和指标差异'} />}{reconciliation?.status === 'REVIEW_REQUIRED' && <div className="nc-difference-confirm"><Alert type="warning" showIcon message={`发现 ${txt(evidence.differenceCount)} 项差异,需要发布者确认`} />{canPublish ? <><Input.TextArea aria-label="业务差异确认理由" rows={2} value={differenceReason} maxLength={1000} placeholder="填写差异原因及确认依据" onChange={event => setDifferenceReason(event.target.value)} /><Checkbox checked={confirmDifferences} onChange={event => setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确</Checkbox><Button type="primary" disabled={!confirmDifferences || !differenceReason.trim() || busy} onClick={() => void confirm()}>确认差异并验收</Button></> : <p>候选已保存,请交由有数据发布权限的同事完成差异确认。</p>}</div>}{canPublish ? <div className="nc-publish-confirm"><Checkbox disabled={!publishReady} checked={publishConfirmed} onChange={event => setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}</Checkbox><Button size="large" type="primary" disabled={!publishReady || !publishConfirmed || busy} onClick={() => void publish()}>确认发布</Button>{!publishReady && <span>来源校验和基线对账通过后可发布。</span>}</div> : <Alert showIcon type="info" message="候选数据已保存,等待有权限的同事发布" description={<><span>当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。</span><Button type="link" onClick={() => { const link = new URL(window.location.href); link.searchParams.set('page', 'sources'); if (handoffSourceId) { link.searchParams.set('sourceDeleteId', handoffSourceId); link.searchParams.delete('candidateReleaseId'); } else { link.searchParams.set('candidateReleaseId', String(release?.id || '')); link.searchParams.delete('sourceDeleteId'); } void navigator.clipboard.writeText(link.toString()).then(() => message.success('处理链接已复制')).catch(reportError); }}>复制处理链接</Button></>} />}</Spin>}
|
||||||
{issues.length > 0 && <><h3>需要处理的来源行</h3><Table size="small" bordered dataSource={issues} rowKey={(row, index) => String(row.id || index)} pagination={{ pageSize: 15 }} columns={[{ title: '工作表', dataIndex: 'sheet', width: 120 }, { title: '行号', dataIndex: 'rowNumber', width: 80 }, { title: '字段', dataIndex: 'field', width: 130 }, { title: '问题说明', dataIndex: 'message' }]} /></>}
|
{issues.length > 0 && <><h3>需要处理的来源行</h3><Table size="small" bordered dataSource={issues} rowKey={(row, index) => String(row.id || index)} pagination={{ pageSize: 15 }} columns={[{ title: '工作表', dataIndex: 'sheet', width: 120 }, { title: '行号', dataIndex: 'rowNumber', width: 80 }, { title: '字段', dataIndex: 'field', width: 130 }, { title: '问题说明', dataIndex: 'message' }]} /></>}
|
||||||
</>}
|
</>}
|
||||||
@@ -487,6 +574,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
|||||||
const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState<Record<string, string>>({});
|
const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState<Record<string, string>>({});
|
||||||
const [name, setName] = useState(''); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false);
|
const [name, setName] = useState(''); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false);
|
||||||
const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState<Row | null>(null);
|
const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState<Row | null>(null);
|
||||||
|
const actionLock = useRef(false);
|
||||||
const [preparedDefinition, setPreparedDefinition] = useState<Row | null>(null);
|
const [preparedDefinition, setPreparedDefinition] = useState<Row | null>(null);
|
||||||
const [preparedReleaseId, setPreparedReleaseId] = useState<string | null>(null);
|
const [preparedReleaseId, setPreparedReleaseId] = useState<string | null>(null);
|
||||||
const workflowOperation = useDataWorkflowOperation('mapping-workbook-import', () => { onComplete(); message.success('基础数据已保存,报表已更新'); });
|
const workflowOperation = useDataWorkflowOperation('mapping-workbook-import', () => { onComplete(); message.success('基础数据已保存,报表已更新'); });
|
||||||
@@ -523,7 +611,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
|||||||
setColumns(autoMatch(nextSheet?.headers || [], nextKind, format, suggestedTables, nextSheet?.name || sheetName));
|
setColumns(autoMatch(nextSheet?.headers || [], nextKind, format, suggestedTables, nextSheet?.name || sheetName));
|
||||||
};
|
};
|
||||||
const readFile = async (file?: File) => {
|
const readFile = async (file?: File) => {
|
||||||
if (!file) return; setBusy(true); setError('');
|
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
const response = await api.previewMasterWorkbook(file); setPreview(response);
|
const response = await api.previewMasterWorkbook(file); setPreview(response);
|
||||||
const nextKind = response.standardBundleAvailable ? 'standardBundle' : (selectedKind === 'standardBundle' ? kind === 'masterData' ? 'departments' : 'categoryLookup' : selectedKind);
|
const nextKind = response.standardBundleAvailable ? 'standardBundle' : (selectedKind === 'standardBundle' ? kind === 'masterData' ? 'departments' : 'categoryLookup' : selectedKind);
|
||||||
@@ -535,10 +623,10 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
|||||||
setName(simplified ? configurationDateTime(new Date()) : `${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
setName(simplified ? configurationDateTime(new Date()) : `${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||||||
setResult(null); setConfirmed(false);
|
setResult(null); setConfirmed(false);
|
||||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||||
finally { setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
finally { actionLock.current = false; setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||||
};
|
};
|
||||||
const submit = async () => {
|
const submit = async () => {
|
||||||
if (!preview || !base || !sheet) return; setBusy(true); setError('');
|
if (!preview || !base || !sheet || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
if (simplified && preparedDefinition) {
|
if (simplified && preparedDefinition) {
|
||||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition: preparedDefinition, description: '测试阶段基础数据导入', expectedCurrentReleaseId: preparedReleaseId }));
|
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition: preparedDefinition, description: '测试阶段基础数据导入', expectedCurrentReleaseId: preparedReleaseId }));
|
||||||
@@ -563,7 +651,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
|||||||
}
|
}
|
||||||
setResult(response); onComplete();
|
setResult(response); onComplete();
|
||||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||||
finally { setBusy(false); }
|
finally { actionLock.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
const canSubmit = Boolean(base && name.trim() && (simplified || (reason.trim() && confirmed)) && (bundle ? preview?.standardBundleAvailable && suggestedTables.length : sheet && activeColumns.every(column => !column.required || columns[column.key])));
|
const canSubmit = Boolean(base && name.trim() && (simplified || (reason.trim() && confirmed)) && (bundle ? preview?.standardBundleAvailable && suggestedTables.length : sheet && activeColumns.every(column => !column.required || columns[column.key])));
|
||||||
return <>
|
return <>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState } from 'react';
|
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';
|
||||||
@@ -20,6 +20,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
|||||||
const [form] = Form.useForm<PasswordValues>();
|
const [form] = Form.useForm<PasswordValues>();
|
||||||
const [activeTab, setActiveTab] = useState<AccountTab>('profile');
|
const [activeTab, setActiveTab] = useState<AccountTab>('profile');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const savingRef = useRef(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const forced = user.forcePasswordChange === true;
|
const forced = user.forcePasswordChange === true;
|
||||||
const open = tab !== null || forced;
|
const open = tab !== null || forced;
|
||||||
@@ -29,6 +30,8 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
|||||||
}, [open, tab, forced, form]);
|
}, [open, tab, forced, form]);
|
||||||
|
|
||||||
const save = async (values: PasswordValues) => {
|
const save = async (values: PasswordValues) => {
|
||||||
|
if (savingRef.current) return;
|
||||||
|
savingRef.current = true;
|
||||||
setBusy(true); setError('');
|
setBusy(true); setError('');
|
||||||
try {
|
try {
|
||||||
await api.changePassword(values.currentPassword, values.newPassword);
|
await api.changePassword(values.currentPassword, values.newPassword);
|
||||||
@@ -38,7 +41,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
|||||||
message.success('密码已修改,下次登录请使用新密码');
|
message.success('密码已修改,下次登录请使用新密码');
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试');
|
if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试');
|
||||||
} finally { setBusy(false); }
|
} finally { savingRef.current = false; setBusy(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
return <Modal className="personal-account-modal" open={open} title="个人账户" width={520} footer={null}
|
return <Modal className="personal-account-modal" open={open} title="个人账户" width={520} footer={null}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ import { workspaceThemes, type WorkspaceThemeId } from './ui-themes';
|
|||||||
import { readableSelectPopup } from './readableSelectPopup';
|
import { readableSelectPopup } from './readableSelectPopup';
|
||||||
import PersonalAccount, { type AccountTab } from './PersonalAccount';
|
import PersonalAccount, { type AccountTab } from './PersonalAccount';
|
||||||
|
|
||||||
import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages';
|
import { CachedWorkspacePages, preloadWorkspacePage, type WorkspaceNavigation } from './CachedWorkspacePages';
|
||||||
|
|
||||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||||
|
|
||||||
@@ -138,6 +138,8 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
let alive = true;
|
||||||
|
// Fetch only the selected page's code while identity validation runs; data stays gated.
|
||||||
|
void preloadWorkspacePage(pageFromLocation()).catch(() => {});
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await api.refreshCsrf();
|
await api.refreshCsrf();
|
||||||
|
|||||||
+58
-56
@@ -1,9 +1,12 @@
|
|||||||
|
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';
|
||||||
import { getWorkspaceTheme } from './ui-themes';
|
import { getWorkspaceTheme } from './ui-themes';
|
||||||
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
|
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
|
||||||
import { BusinessValue } from './BusinessValue';
|
import { BusinessValue } from './BusinessValue';
|
||||||
import { usePageCache } from './pageCache';
|
import { usePageCache } from './pageCache';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
|
import { useResourceVisibility } from './useResourceVisibility';
|
||||||
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
import * as echarts from 'echarts/core';
|
import * as echarts from 'echarts/core';
|
||||||
import { BarChart, LineChart } from 'echarts/charts';
|
import { BarChart, LineChart } from 'echarts/charts';
|
||||||
@@ -153,6 +156,7 @@ function monthNumber(value: number | string): number | null {
|
|||||||
return result >= 1 && result <= 12 ? result : null;
|
return result >= 1 && result <= 12 ? result : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] {
|
function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] {
|
||||||
if (granularity === 'year') return rows;
|
if (granularity === 'year') return rows;
|
||||||
const byPeriod = new Map<string, TrendMetricRow>();
|
const byPeriod = new Map<string, TrendMetricRow>();
|
||||||
@@ -228,16 +232,7 @@ function escapeTooltipText(value: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
export function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
||||||
const context = new URLSearchParams(search).get('context');
|
return readQueryLocation(search);
|
||||||
if (!context) return {};
|
|
||||||
try {
|
|
||||||
const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4));
|
|
||||||
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, character => character.charCodeAt(0)))) as { query?: unknown };
|
|
||||||
if (!parsed.query || typeof parsed.query !== 'object') return {};
|
|
||||||
const query = { ...(parsed.query as Partial<QueryParams>) };
|
|
||||||
delete query.releaseId;
|
|
||||||
return query;
|
|
||||||
} catch { return {}; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function toApiParams(args: {
|
function toApiParams(args: {
|
||||||
@@ -291,7 +286,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
|
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
|
||||||
}) {
|
}) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
|
const { active, initialSearch, refreshKey, onLocationChange, currentReleaseId } = usePageCache();
|
||||||
const baseView = SCOPE[page] || 'overall';
|
const baseView = SCOPE[page] || 'overall';
|
||||||
const [initialQuery] = useState(() => queryFromLocation(initialSearch));
|
const [initialQuery] = useState(() => queryFromLocation(initialSearch));
|
||||||
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
|
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
|
||||||
@@ -340,6 +335,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [errorKey, setErrorKey] = useState('');
|
const [errorKey, setErrorKey] = useState('');
|
||||||
const [queryRevision, setQueryRevision] = useState(0);
|
const [queryRevision, setQueryRevision] = useState(0);
|
||||||
|
const [trendRevision, setTrendRevision] = useState(0);
|
||||||
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
|
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
|
||||||
const [recordsOpen, setRecordsOpen] = useState(false);
|
const [recordsOpen, setRecordsOpen] = useState(false);
|
||||||
const [recordStage, setRecordStage] = useState<Stage>('black');
|
const [recordStage, setRecordStage] = useState<Stage>('black');
|
||||||
@@ -361,8 +357,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!active) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
api.options().then(result => {
|
const controller = new AbortController();
|
||||||
|
api.options(controller.signal).then(result => {
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
setOptions(result);
|
setOptions(result);
|
||||||
if (automaticPeriod.current) {
|
if (automaticPeriod.current) {
|
||||||
@@ -375,8 +373,8 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
if (onUnauthorized(errorValue)) return;
|
if (onUnauthorized(errorValue)) return;
|
||||||
if (alive) setOptionsError(chooseError(errorValue));
|
if (alive) setOptionsError(chooseError(errorValue));
|
||||||
}).finally(() => { if (alive) setOptionsLoading(false); });
|
}).finally(() => { if (alive) setOptionsLoading(false); });
|
||||||
return () => { alive = false; };
|
return () => { alive = false; controller.abort(); };
|
||||||
}, [onUnauthorized, queryRevision]);
|
}, [active, onUnauthorized, queryRevision]);
|
||||||
|
|
||||||
const allowedGroups = useMemo(() => {
|
const allowedGroups = useMemo(() => {
|
||||||
const parents = new Set(department);
|
const parents = new Set(department);
|
||||||
@@ -406,7 +404,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
if (product.length && !product.includes(exactProductSearch)) return [EMPTY_PRODUCT_SEARCH];
|
if (product.length && !product.includes(exactProductSearch)) return [EMPTY_PRODUCT_SEARCH];
|
||||||
return [exactProductSearch];
|
return [exactProductSearch];
|
||||||
}, [exactProductSearch, product]);
|
}, [exactProductSearch, product]);
|
||||||
const queryParams = useMemo(() => toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity]);
|
const queryParams = useMemo(() => ({ ...toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), releaseId: initialQuery.releaseId || currentReleaseId || undefined }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity, initialQuery.releaseId, currentReleaseId]);
|
||||||
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
|
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
|
||||||
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
|
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -420,7 +418,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
const queryBusy = loading || queryPending;
|
const queryBusy = loading || queryPending;
|
||||||
const metricKeyRef = useRef(metricKey);
|
const metricKeyRef = useRef(metricKey);
|
||||||
metricKeyRef.current = metricKey;
|
metricKeyRef.current = metricKey;
|
||||||
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
|
|
||||||
const trendParams = useMemo<QueryParams>(() => {
|
const trendParams = useMemo<QueryParams>(() => {
|
||||||
const params = applyTrendObject(queryParams, trendObject, view);
|
const params = applyTrendObject(queryParams, trendObject, view);
|
||||||
delete params.month;
|
delete params.month;
|
||||||
@@ -438,7 +435,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
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') || '')) return;
|
||||||
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryParams }));
|
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);
|
||||||
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
@@ -448,7 +445,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
}, [queryKey, active]);
|
}, [queryKey, active]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (optionsLoading) return;
|
if (!active || optionsLoading || optionsError) return;
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
@@ -457,10 +454,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
if (controller.signal.aborted || metricKeyRef.current !== metricKey) return;
|
if (controller.signal.aborted || metricKeyRef.current !== metricKey) return;
|
||||||
setData(result);
|
setData(result);
|
||||||
setDataKey(metricKey);
|
setDataKey(metricKey);
|
||||||
if (useSummaryTrend && trendKeyRef.current === trendKey) {
|
|
||||||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
|
||||||
setTrendDataKey(trendKey);
|
|
||||||
}
|
|
||||||
setError('');
|
setError('');
|
||||||
setErrorKey('');
|
setErrorKey('');
|
||||||
}).catch(errorValue => {
|
}).catch(errorValue => {
|
||||||
@@ -470,9 +463,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
setErrorKey(metricKey);
|
setErrorKey(metricKey);
|
||||||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [metricKey, queryRevision, onUnauthorized, optionsLoading]);
|
}, [active, metricKey, queryRevision, onUnauthorized, optionsLoading, optionsError]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!active) return;
|
||||||
if (!trendObject || defectQueryKey === queryKey) {
|
if (!trendObject || defectQueryKey === queryKey) {
|
||||||
setTrendObjectMetrics(null);
|
setTrendObjectMetrics(null);
|
||||||
setTrendObjectMetricsLoading(false);
|
setTrendObjectMetricsLoading(false);
|
||||||
@@ -491,18 +485,14 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
})
|
})
|
||||||
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
|
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
}, [active, trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (optionsLoading) return;
|
if (!active || optionsLoading || optionsError) return;
|
||||||
setTrendFailure(null);
|
setTrendFailure(null);
|
||||||
if (useSummaryTrend) {
|
|
||||||
setTrendLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
setTrendLoading(true);
|
setTrendLoading(true);
|
||||||
api.metrics(trendParams, controller.signal).then(result => {
|
api.trend(trendParams, controller.signal).then(result => {
|
||||||
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
|
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
|
||||||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
||||||
setTrendDataKey(trendKey);
|
setTrendDataKey(trendKey);
|
||||||
@@ -511,9 +501,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
|
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
|
||||||
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, optionsLoading]);
|
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!active || optionsLoading || optionsError) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
setTrendTarget(null);
|
setTrendTarget(null);
|
||||||
setTrendTargetKey('');
|
setTrendTargetKey('');
|
||||||
@@ -532,14 +523,15 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
return () => { alive = false; };
|
return () => { alive = false; };
|
||||||
}, [trendKey, queryRevision, onUnauthorized]);
|
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
|
||||||
|
|
||||||
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
|
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
|
||||||
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
|
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
|
||||||
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
|
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
|
||||||
const trendRefreshing = trendLoading || (useSummaryTrend && queryBusy) || (trendDataKey !== trendKey && !(useSummaryTrend ? currentMetricsError : currentTrendError));
|
const trendRefreshing = !currentTrendError && (trendLoading || trendDataKey !== trendKey);
|
||||||
|
const showTrendLoading = useDelayedIndicator(trendRefreshing);
|
||||||
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
|
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
|
||||||
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget } : null);
|
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget, query: trendParams } : null);
|
||||||
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
|
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
|
||||||
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
|
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
|
||||||
const drilledTrendData = useMemo(
|
const drilledTrendData = useMemo(
|
||||||
@@ -585,7 +577,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
view: drilledProduct ? 'overall' as const : view,
|
view: drilledProduct ? 'overall' as const : view,
|
||||||
layoutView: drilledProduct ? 'product' as const : view,
|
layoutView: drilledProduct ? 'product' as const : view,
|
||||||
period: drilledProduct ? 'year' as const : period,
|
period: drilledProduct ? 'year' as const : period,
|
||||||
year, month, quarter, drilledProduct,
|
year, month, quarter, drilledProduct, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
|
||||||
} : null);
|
} : null);
|
||||||
const tableRows = retainedTable?.rows || [];
|
const tableRows = retainedTable?.rows || [];
|
||||||
const tablePeriod = retainedTable?.period || period;
|
const tablePeriod = retainedTable?.period || period;
|
||||||
@@ -755,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
</div>}
|
</div>}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" 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' : ''}`} 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>
|
||||||
@@ -776,12 +768,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject}
|
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject}
|
||||||
objects={trendOptions} scopeName={scopeName}
|
objects={trendOptions} scopeName={scopeName}
|
||||||
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
|
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
|
||||||
{currentTrendError && <Alert type="warning" showIcon message="趋势读取失败" description={currentTrendError} action={<Button onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
|
||||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
|
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
|
||||||
{trendMode === 'data'
|
{trendMode === 'data'
|
||||||
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||||||
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||||||
{trendRefreshing && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
|
||||||
</div>
|
</div>
|
||||||
</QueryTrendPanel>
|
</QueryTrendPanel>
|
||||||
|
|
||||||
@@ -792,7 +784,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||||||
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
|
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
|
||||||
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
|
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
|
||||||
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
||||||
onExport={async () => {
|
onExport={async () => {
|
||||||
setSummaryExporting(true);
|
setSummaryExporting(true);
|
||||||
try { await summaryExport.current?.exportExcel(); }
|
try { await summaryExport.current?.exportExcel(); }
|
||||||
@@ -802,6 +794,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
|||||||
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
|
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
|
||||||
<MetricTable
|
<MetricTable
|
||||||
ref={summaryExport}
|
ref={summaryExport}
|
||||||
|
paginationScope={retainedTable?.paginationScope}
|
||||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||||
rows={tableRows}
|
rows={tableRows}
|
||||||
view={tableView}
|
view={tableView}
|
||||||
@@ -929,8 +922,11 @@ 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 showLoading = useDelayedIndicator(loading);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!active || !visible) return;
|
||||||
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
|
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
|
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
|
||||||
@@ -947,7 +943,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
|||||||
})
|
})
|
||||||
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
|
}, [active, visible, releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const refresh = () => setThemeRevision(value => value + 1);
|
const refresh = () => setThemeRevision(value => value + 1);
|
||||||
@@ -1049,7 +1045,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
|||||||
}, [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" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
|
||||||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <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="当前没有已发布数据版本" />}
|
||||||
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
|
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
|
||||||
@@ -1078,10 +1074,10 @@ const totalWeightTitle = (label: string) => <span className="query-total-weight-
|
|||||||
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
|
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
|
||||||
|
|
||||||
export function MetricTable({
|
export function MetricTable({
|
||||||
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
|
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
|
||||||
}: {
|
}: {
|
||||||
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
|
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
|
||||||
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
|
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; paginationScope?: string; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
|
||||||
rateBasis: 'original' | 'withoutHeadquartersScrap';
|
rateBasis: 'original' | 'withoutHeadquartersScrap';
|
||||||
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
|
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
|
||||||
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
|
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
|
||||||
@@ -1149,9 +1145,9 @@ export function MetricTable({
|
|||||||
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
|
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||||||
const effectivePage = pageSizeOverride == null ? currentPage : 1;
|
const effectivePage = pageSizeOverride == null ? Math.min(currentPage, Math.max(1, Math.ceil(rows.length / pageSize))) : 1;
|
||||||
const effectivePageSize = pageSizeOverride ?? pageSize;
|
const effectivePageSize = pageSizeOverride ?? pageSize;
|
||||||
useEffect(() => setCurrentPage(1), [rows]);
|
useEffect(() => setCurrentPage(1), [paginationScope ?? rows]);
|
||||||
const columnWidth = (column: ColumnsType<MetricRow>[number]): number => {
|
const columnWidth = (column: ColumnsType<MetricRow>[number]): number => {
|
||||||
if ('children' in column && column.children?.length) {
|
if ('children' in column && column.children?.length) {
|
||||||
return column.children.reduce((total, child) => total + columnWidth(child), 0);
|
return column.children.reduce((total, child) => total + columnWidth(child), 0);
|
||||||
@@ -1163,7 +1159,7 @@ export function MetricTable({
|
|||||||
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
|
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
|
||||||
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
|
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
|
||||||
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
|
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
|
||||||
{pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
|
{pageSizeOverride == null && <MetricTablePagination current={effectivePage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1181,6 +1177,7 @@ 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 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);
|
||||||
@@ -1228,7 +1225,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!container.current || !hasRows || !active) return;
|
if (!container.current || !hasRows || !visible) return;
|
||||||
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
|
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
|
||||||
chart.current = instance;
|
chart.current = instance;
|
||||||
graphicIds.current.clear();
|
graphicIds.current.clear();
|
||||||
@@ -1260,7 +1257,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
|||||||
});
|
});
|
||||||
observer.observe(container.current);
|
observer.observe(container.current);
|
||||||
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
||||||
}, [hasRows, refreshBarMasks, active]);
|
}, [hasRows, refreshBarMasks, visible]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const instance = chart.current;
|
const instance = chart.current;
|
||||||
@@ -1350,7 +1347,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
|||||||
}
|
}
|
||||||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||||||
refreshBarMasks();
|
refreshBarMasks();
|
||||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active]);
|
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active, visible]);
|
||||||
|
|
||||||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||||||
|
|
||||||
@@ -1420,7 +1417,7 @@ export function RecordsDrawer({
|
|||||||
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
|
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const { refreshKey } = usePageCache();
|
const { active, refreshKey } = usePageCache();
|
||||||
const recordPages = useRef(new Map<string, RecordsResponse>());
|
const recordPages = useRef(new Map<string, RecordsResponse>());
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
|
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
|
||||||
@@ -1445,14 +1442,16 @@ export function RecordsDrawer({
|
|||||||
const result = response?.key === requestKey ? response.data : null;
|
const result = response?.key === requestKey ? response.data : null;
|
||||||
const error = failure?.key === requestKey ? failure.message : '';
|
const error = failure?.key === requestKey ? failure.message : '';
|
||||||
const fetching = loading || !result && !error;
|
const fetching = loading || !result && !error;
|
||||||
|
const retainedResult = useRetainedResult(result);
|
||||||
|
const showRecordLoading = useDelayedIndicator(fetching && open);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open || !active) return;
|
||||||
const cached = recordPages.current.get(requestKey);
|
const cached = recordPages.current.get(requestKey);
|
||||||
if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; }
|
if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; }
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setResponse(null); setFailure(null);
|
setFailure(null);
|
||||||
api.records(requestParams, controller.signal).then(value => {
|
api.records(requestParams, controller.signal).then(value => {
|
||||||
if (controller.signal.aborted) return;
|
if (controller.signal.aborted) return;
|
||||||
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
|
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
|
||||||
@@ -1468,7 +1467,7 @@ export function RecordsDrawer({
|
|||||||
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
|
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
|
||||||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [open, requestKey, revision, onUnauthorized]);
|
}, [open, active, requestKey, revision, onUnauthorized]);
|
||||||
|
|
||||||
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
|
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
|
||||||
const exportRecords = async () => {
|
const exportRecords = async () => {
|
||||||
@@ -1536,7 +1535,7 @@ 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} 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>
|
<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>
|
||||||
<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); }} />
|
||||||
@@ -1548,8 +1547,11 @@ export function RecordsDrawer({
|
|||||||
]} onChange={value => { setSort(value); setPage(1); }} /></label>
|
]} onChange={value => { setSort(value); setPage(1); }} /></label>
|
||||||
<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="来源明细加载失败" 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>} />}
|
||||||
{fetching ? <div className="loading-panel"><Spin />正在读取来源行…</div> : result?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={result.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
|
{showRecordLoading && <div role="status">{retainedResult ? '正在更新,当前显示上次来源结果' : <><Spin size="small" />正在读取来源行…</>}</div>}
|
||||||
|
<div aria-busy={fetching} inert={!result || !!error}>
|
||||||
|
{retainedResult?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={retainedResult.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : !fetching && !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有来源记录" />}
|
||||||
|
</div>
|
||||||
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
|
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
|
||||||
</Drawer>;
|
</Drawer>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,13 +55,13 @@ export function SmoothTableFrame({ children, busy, blocked }: { children: ReactN
|
|||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
const node = content.current;
|
const node = content.current;
|
||||||
if (!node) return;
|
if (!node) return;
|
||||||
const measure = () => setHeight(node.offsetHeight);
|
const measure = () => { if (node.offsetHeight > 0) setHeight(node.offsetHeight); };
|
||||||
measure();
|
measure();
|
||||||
const observer = new ResizeObserver(measure);
|
const observer = new ResizeObserver(measure);
|
||||||
observer.observe(node);
|
observer.observe(node);
|
||||||
return () => observer.disconnect();
|
return () => observer.disconnect();
|
||||||
}, []);
|
}, []);
|
||||||
useLayoutEffect(() => { if (content.current) setHeight(content.current.offsetHeight); }, [children]);
|
useLayoutEffect(() => { if (content.current && content.current.offsetHeight > 0) setHeight(content.current.offsetHeight); }, [children]);
|
||||||
return <div className="smooth-table-frame" style={{ height }}>
|
return <div className="smooth-table-frame" style={{ height }}>
|
||||||
<div ref={content} className="query-table-content" aria-busy={busy} inert={blocked}>{children}</div>
|
<div ref={content} className="query-table-content" aria-busy={busy} inert={blocked}>{children}</div>
|
||||||
</div>;
|
</div>;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { loadedQueryScope, queryForLocation } from './queryLoadingScope';
|
||||||
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
|
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
|
||||||
import { queryScrapWeight } from './queryMetricValues';
|
import { queryScrapWeight } from './queryMetricValues';
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
@@ -8,10 +9,11 @@ import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHea
|
|||||||
import { StageSourceFilters } from './StageSourceFilters';
|
import { StageSourceFilters } from './StageSourceFilters';
|
||||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||||
import { usePageCache } from './pageCache';
|
import { usePageCache } from './pageCache';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||||
import { readableSelectPopup } from './readableSelectPopup';
|
import { readableSelectPopup } from './readableSelectPopup';
|
||||||
import { readableMetricFormula } from './publicDataDisplay';
|
import { readableMetricFormula } from './publicDataDisplay';
|
||||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
import type { 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';
|
||||||
@@ -19,7 +21,7 @@ import './stage-product.css';
|
|||||||
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
||||||
const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—';
|
const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—';
|
||||||
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
|
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
|
||||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
|
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange,currentReleaseId}=usePageCache();
|
||||||
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
|
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
|
||||||
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
|
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
|
||||||
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
||||||
@@ -33,21 +35,23 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
|||||||
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
||||||
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
|
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
|
||||||
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
||||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
const [trendResponse,setTrendResponse]=useState<{key:string;value:TrendResponse;query:QueryParams}|null>(null);const [trendRevision,setTrendRevision]=useState(0);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||||
const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
||||||
const label=stage==='black'?'黑片':'亮片';
|
const label=stage==='black'?'黑片':'亮片';
|
||||||
|
const supportGeneration=useRef(0);const supportController=useRef<AbortController|null>(null);
|
||||||
const loadSupport=useCallback(async()=>{
|
const loadSupport=useCallback(async()=>{
|
||||||
|
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(),api.sourceColumnCatalog()]);if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);}
|
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);}
|
||||||
catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
catch(error){if(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||||
finally{setSupportLoading(false);}
|
finally{if(generation===supportGeneration.current)setSupportLoading(false);}
|
||||||
},[onUnauthorized]);
|
},[onUnauthorized,initial.releaseId,currentReleaseId]);
|
||||||
useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]);
|
useEffect(()=>{if(active)void loadSupport();return()=>{supportGeneration.current++;supportController.current?.abort();};},[active,refreshKey,loadSupport]);
|
||||||
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]);
|
||||||
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:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]);
|
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]);
|
||||||
// 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:'';
|
||||||
@@ -56,10 +60,10 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
|||||||
void api.metrics(applied,controller.signal).then(value=>{if(!controller.signal.aborted)setResponse({key:queryKey,value});}).catch(e=>{if(!controller.signal.aborted&&!onUnauthorized(e))setFailure({key:queryKey,message:e instanceof Error?e.message:'查询失败'});}).finally(()=>{if(!controller.signal.aborted)setLoading(false);});
|
void api.metrics(applied,controller.signal).then(value=>{if(!controller.signal.aborted)setResponse({key:queryKey,value});}).catch(e=>{if(!controller.signal.aborted&&!onUnauthorized(e))setFailure({key:queryKey,message:e instanceof Error?e.message:'查询失败'});}).finally(()=>{if(!controller.signal.aborted)setLoading(false);});
|
||||||
return()=>controller.abort();
|
return()=>controller.abort();
|
||||||
},[active,queryKey,onUnauthorized,supportError]);
|
},[active,queryKey,onUnauthorized,supportError]);
|
||||||
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:applied}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:queryForLocation(applied,initial.releaseId)}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
||||||
const trendQuery=useMemo(()=>applied?{...applied,month:undefined,quarter:undefined,...(trendGranularity==='year'?{year:undefined}:{}),trendGranularity}:null,[applied,trendGranularity]);
|
const trendQuery=useMemo(()=>applied?{...applied,month:undefined,quarter:undefined,...(trendGranularity==='year'?{year:undefined}:{}),trendGranularity}:null,[applied,trendGranularity]);
|
||||||
const trendKey=JSON.stringify({query:trendQuery,revision});
|
const trendKey=JSON.stringify({query:trendQuery,revision});
|
||||||
useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]);
|
useEffect(()=>{if(!active||!trendQuery||supportError)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.trend(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value,query:trendQuery});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,trendRevision,onUnauthorized,supportError]);
|
||||||
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
|
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
|
||||||
const displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend;
|
const displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend;
|
||||||
const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
|
const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
|
||||||
@@ -83,8 +87,9 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
|||||||
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 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 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=trendLoading||!current||trendResponse?.key!==trendKey;
|
const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey);
|
||||||
const tableReady=!!current&&(!drilledProduct||!trendRefreshing);
|
const showTrendLoading=useDelayedIndicator(trendRefreshing);
|
||||||
|
const tableReady=!!current&&(!drilledProduct||(trendResponse?.key===trendKey&&!trendLoading&&!trendError));
|
||||||
const table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
|
const table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
|
||||||
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||||
@@ -110,7 +115,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
|||||||
{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="查询失败" 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" 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)}/>
|
||||||
@@ -121,12 +126,12 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
|||||||
<div className="analysis-stack">
|
<div className="analysis-stack">
|
||||||
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
|
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
|
||||||
{trendError&&<Alert type="warning" showIcon message="趋势读取失败" description={trendError} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
{trendError&&<Alert type="warning" showIcon message={trendResponse?"趋势更新失败,当前显示上次结果":"趋势读取失败"} description={trendResponse?`${trendError};当前范围:${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:trendError} action={<Button onClick={()=>setTrendRevision(v=>v+1)}>重试</Button>}/>}
|
||||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
|
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
|
||||||
{trendMode==='data'
|
{trendMode==='data'
|
||||||
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onMonth={selectTrendPeriod}/>
|
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onMonth={selectTrendPeriod}/>
|
||||||
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
|
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
|
||||||
{trendRefreshing&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}
|
{showTrendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}</span>}
|
||||||
</div>
|
</div>
|
||||||
</QueryTrendPanel>
|
</QueryTrendPanel>
|
||||||
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
|
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
|
||||||
@@ -136,6 +141,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
|||||||
exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}>
|
exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}>
|
||||||
<SmoothTableFrame busy={queryBusy||!tableReady} blocked={queryBusy||!tableReady}>
|
<SmoothTableFrame busy={queryBusy||!tableReady} blocked={queryBusy||!tableReady}>
|
||||||
<MetricTable ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
|
<MetricTable ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
|
||||||
|
paginationScope={JSON.stringify({query:table?.query,drilledProduct:table?.drilledProduct})}
|
||||||
rows={table?.rows||[]} view={table?.drilledProduct?'overall':'product'} layoutView="product" pageSizeOverride={table?.drilledProduct?12:undefined}
|
rows={table?.rows||[]} view={table?.drilledProduct?'overall':'product'} layoutView="product" pageSizeOverride={table?.drilledProduct?12:undefined}
|
||||||
period={table?.period||period} month={table?.query.month||month} quarter={table?.query.quarter||quarter}
|
period={table?.period||period} month={table?.query.month||month} quarter={table?.query.quarter||quarter}
|
||||||
fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)}
|
fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { usePageCache } from './pageCache';
|
||||||
|
import { useDelayedIndicator } from './useDelayedBusy';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Alert, Button, Select, Spin } from 'antd';
|
import { Alert, Button, Select, Spin } from 'antd';
|
||||||
import { CloseOutlined } from '@ant-design/icons';
|
import { CloseOutlined } from '@ant-design/icons';
|
||||||
@@ -7,8 +9,11 @@ import { readableSelectPopup } from './readableSelectPopup';
|
|||||||
|
|
||||||
function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:SourceColumnField;stage:Stage;query:QueryParams;value:string[];onChange:(value:string[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:SourceColumnField;stage:Stage;query:QueryParams;value:string[];onChange:(value:string[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||||
const [search,setSearch]=useState('');const [choices,setChoices]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [more,setMore]=useState(false);const [revision,setRevision]=useState(0);
|
const [search,setSearch]=useState('');const [choices,setChoices]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [more,setMore]=useState(false);const [revision,setRevision]=useState(0);
|
||||||
|
const {active}=usePageCache();
|
||||||
|
const showBusy=useDelayedIndicator(busy);
|
||||||
const contextKey=JSON.stringify(query);const current=useRef(0);
|
const contextKey=JSON.stringify(query);const current=useRef(0);
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
|
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}=query;
|
||||||
@@ -18,8 +23,8 @@ function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:S
|
|||||||
.finally(()=>{if(current.current===generation)setBusy(false);});
|
.finally(()=>{if(current.current===generation)setBusy(false);});
|
||||||
},search?300:0);
|
},search?300:0);
|
||||||
return()=>{window.clearTimeout(timer);controller.abort();current.current++;};
|
return()=>{window.clearTimeout(timer);controller.abort();current.current++;};
|
||||||
},[field.key,stage,contextKey,search,revision,onUnauthorized]);
|
},[active,field.key,stage,contextKey,search,revision,onUnauthorized]);
|
||||||
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={busy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={busy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={showBusy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={showBusy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
||||||
}
|
}
|
||||||
export function StageSourceFilters({stage,fields,query,value,onChange,onUnauthorized,part='both'}:{part?:'both'|'picker'|'rows';stage:Stage;fields:SourceColumnField[];query:QueryParams;value:SourceColumnFilter[];onChange:(value:SourceColumnFilter[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
export function StageSourceFilters({stage,fields,query,value,onChange,onUnauthorized,part='both'}:{part?:'both'|'picker'|'rows';stage:Stage;fields:SourceColumnField[];query:QueryParams;value:SourceColumnFilter[];onChange:(value:SourceColumnFilter[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||||
const selected=value.map(rule=>rule.field);const patch=(key:string,change:Partial<SourceColumnFilter>)=>onChange(value.map(rule=>rule.field===key?{...rule,...change}:rule));
|
const selected=value.map(rule=>rule.field);const patch=(key:string,change:Partial<SourceColumnFilter>)=>onChange(value.map(rule=>rule.field===key?{...rule,...change}:rule));
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import type { AuthUser } from './types';
|
|||||||
import { BackupOperationsPanel, OperationsMonitorPanel } from './GovernanceCompletion';
|
import { BackupOperationsPanel, OperationsMonitorPanel } from './GovernanceCompletion';
|
||||||
import { configurationDateTime } from './configurationName';
|
import { configurationDateTime } from './configurationName';
|
||||||
import { backupSummary, isActive, isFailed, monitorLabel, orderedTasks, taskFailure, taskPercent, type MonitorRow } from './taskMonitorModel';
|
import { backupSummary, isActive, isFailed, monitorLabel, orderedTasks, taskFailure, taskPercent, type MonitorRow } from './taskMonitorModel';
|
||||||
|
import { useDelayedBusy } from './useDelayedBusy';
|
||||||
|
import { useVisiblePolling } from './useVisiblePolling';
|
||||||
|
|
||||||
export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthorized:(error:unknown)=>boolean}) {
|
export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthorized:(error:unknown)=>boolean}) {
|
||||||
const {message}=App.useApp();
|
const {message}=App.useApp();
|
||||||
@@ -18,29 +20,35 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
|||||||
const [items,setItems]=useState<MonitorRow[]>([]);
|
const [items,setItems]=useState<MonitorRow[]>([]);
|
||||||
const [backup,setBackup]=useState<MonitorRow>({});
|
const [backup,setBackup]=useState<MonitorRow>({});
|
||||||
const [taskError,setTaskError]=useState(''); const [backupError,setBackupError]=useState('');
|
const [taskError,setTaskError]=useState(''); const [backupError,setBackupError]=useState('');
|
||||||
const [loading,setLoading]=useState(true);
|
const [tasksLoaded,setTasksLoaded]=useState(false); const [backupLoaded,setBackupLoaded]=useState(false);
|
||||||
const loaded = useRef(false);
|
|
||||||
const [section,setSection] = useState('tasks');
|
const [section,setSection] = useState('tasks');
|
||||||
|
const taskBusy = useDelayedBusy(); const backupBusy = useDelayedBusy();
|
||||||
|
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 canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role));
|
const canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role));
|
||||||
const load=useCallback(async()=>{
|
function sectionLoading() { return section === 'tasks' ? taskBusy.busy : backupBusy.busy; }
|
||||||
setLoading(true);
|
const loadTasks=useCallback(()=>taskBusy.run(async()=>{
|
||||||
await Promise.all([
|
try { const value=await api.taskOverview();setItems(value.items);setTaskError('');setTasksLoaded(true); }
|
||||||
api.taskOverview().then(value=>{setItems(value.items);setTaskError('');}).catch(error=>{if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败');}),
|
catch(error){ if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败'); }
|
||||||
api.latestBackup().then(value=>{setBackup(value);setBackupError('');}).catch(error=>{if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败');}),
|
}),[onUnauthorized,taskBusy.run]);
|
||||||
]);setLoading(false);
|
const loadBackup=useCallback(()=>backupBusy.run(async()=>{
|
||||||
},[onUnauthorized]);
|
try { const value=await api.latestBackup();setBackup(value);setBackupError('');setBackupLoaded(true); }
|
||||||
useEffect(()=>{if(!loaded.current){loaded.current=true;void load();}},[load]);
|
catch(error){ if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败'); }
|
||||||
|
}),[onUnauthorized,backupBusy.run]);
|
||||||
|
const load=useCallback(()=>section==='tasks'?loadTasks():loadBackup(),[section,loadTasks,loadBackup]);
|
||||||
|
useEffect(()=>{if(!active)return;if(section==='tasks'&&!tasksLoaded)void loadTasks();if(section==='latestBackup'&&!backupLoaded)void loadBackup();},[active,section,tasksLoaded,backupLoaded,loadTasks,loadBackup]);
|
||||||
useMaintenanceRefresh(load);
|
useMaintenanceRefresh(load);
|
||||||
useEffect(()=>{if(!active || !['tasks','latestBackup'].includes(section))return;const timer=window.setInterval(()=>{if(document.visibilityState==='visible')void load();},15000);return()=>window.clearInterval(timer);},[load,active,section]);
|
useVisiblePolling(load,15000,active&&['tasks','latestBackup'].includes(section));
|
||||||
const runAction=async(row:MonitorRow,action:'retry'|'cancel')=>{
|
const runAction=async(row:MonitorRow,action:'retry'|'cancel')=>{
|
||||||
|
if(actionInFlight.current)return; actionInFlight.current=true;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:crypto.randomUUID(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:crypto.randomUUID(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
||||||
else await api.cancelTask(String(row.id),{expectedStatus:String(row.status)});
|
else await api.cancelTask(String(row.id),{expectedStatus:String(row.status)});
|
||||||
message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load();
|
message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load();
|
||||||
} catch(error){if(!onUnauthorized(error))message.error(error instanceof Error?error.message:'任务操作失败');}
|
} catch(error){if(!onUnauthorized(error))message.error(error instanceof Error?error.message:'任务操作失败');}
|
||||||
finally{setBusy(false);}
|
finally{actionInFlight.current=false;setBusy(false);}
|
||||||
};
|
};
|
||||||
const latest=(backup.latest || {}) as MonitorRow;
|
const latest=(backup.latest || {}) as MonitorRow;
|
||||||
const columns:ColumnsType<MonitorRow>=[
|
const columns:ColumnsType<MonitorRow>=[
|
||||||
@@ -54,13 +62,14 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
|||||||
<ManagementSections onSelect={setSection} items={[
|
<ManagementSections onSelect={setSection} items={[
|
||||||
{ key:'tasks', label:'任务进度', children: <> <section className="panel section-panel">
|
{ key:'tasks', label:'任务进度', children: <> <section className="panel section-panel">
|
||||||
<div className="completion-panel-heading"><strong>任务进度</strong><div className="completion-actions"><Select aria-label="筛选任务" value={filter} onChange={setFilter} options={[{value:'all',label:'全部任务'},{value:'active',label:'进行中'},{value:'failed',label:'失败 / 未完成'},{value:'completed',label:'已完成'}]}/><Button icon={<ReloadOutlined/>} loading={loading} onClick={()=>void load()}>刷新</Button></div></div>
|
<div className="completion-panel-heading"><strong>任务进度</strong><div className="completion-actions"><Select aria-label="筛选任务" value={filter} onChange={setFilter} options={[{value:'all',label:'全部任务'},{value:'active',label:'进行中'},{value:'failed',label:'失败 / 未完成'},{value:'completed',label:'已完成'}]}/><Button icon={<ReloadOutlined/>} loading={loading} onClick={()=>void load()}>刷新</Button></div></div>
|
||||||
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={taskError}/>}
|
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={tasksLoaded?`${taskError};以下为上次成功读取的结果。`:taskError} action={!tasksLoaded?<Button size="small" onClick={()=>void loadTasks()}>重试</Button>:undefined}/>}
|
||||||
{loading&&!items.length?<Spin/>:!taskError&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
{loading&&!tasksLoaded?<Spin/>:tasksLoaded&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
||||||
<p className="completion-note">每类最多显示 50 条记录,进行中及失败任务优先。智能分析仅显示本人任务。</p>
|
<p className="completion-note">每类最多显示 50 条记录,进行中及失败任务优先。智能分析仅显示本人任务。</p>
|
||||||
</section>
|
</section>
|
||||||
</> },
|
</> },
|
||||||
{ key:'latestBackup', label:'最近备份', children: <> <section className="panel section-panel"><div className="completion-panel-heading"><strong>最近备份状态</strong></div>
|
{ key:'latestBackup', label:'最近备份', children: <> <section className="panel section-panel"><div className="completion-panel-heading"><strong>最近备份状态</strong></div>
|
||||||
{backupError?<Alert showIcon type="error" message="备份状态暂不可用" description={backupError}/>:loading&&!latest.createdAt?<Spin/>:<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
{backupError&&<Alert showIcon type="error" message="备份状态暂不可用" description={backupLoaded?`${backupError};以下为上次成功读取的结果。`:backupError} action={!backupLoaded?<Button size="small" onClick={()=>void loadBackup()}>重试</Button>:undefined}/>}
|
||||||
|
{loading&&!backupLoaded?<Spin/>:backupLoaded&&<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
||||||
</section>
|
</section>
|
||||||
</> },
|
</> },
|
||||||
...(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}/> }] : []),
|
||||||
|
|||||||
+218
-48
@@ -1,7 +1,15 @@
|
|||||||
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 { RequestTimeoutError, withRequestDeadline } from './requestDeadline';
|
import {
|
||||||
|
clearReadCache,
|
||||||
|
configureRequestScope,
|
||||||
|
coordinateRequest,
|
||||||
|
getRequestDiagnostics,
|
||||||
|
invalidateReadResources,
|
||||||
|
resetRequestScope,
|
||||||
|
type CoordinatedResult,
|
||||||
|
} from './requestCoordinator';
|
||||||
import type {
|
import type {
|
||||||
AuthUser,
|
AuthUser,
|
||||||
FilterField,
|
FilterField,
|
||||||
@@ -9,6 +17,7 @@ import type {
|
|||||||
Collection,
|
Collection,
|
||||||
FineDefectTopResponse,
|
FineDefectTopResponse,
|
||||||
MetricsResponse,
|
MetricsResponse,
|
||||||
|
TrendResponse,
|
||||||
OptionsResponse,
|
OptionsResponse,
|
||||||
QueryParams,
|
QueryParams,
|
||||||
RecordExportParams,
|
RecordExportParams,
|
||||||
@@ -17,6 +26,8 @@ import type {
|
|||||||
} from './types';
|
} from './types';
|
||||||
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||||
|
|
||||||
|
export { configureRequestScope, getRequestDiagnostics, invalidateReadResources, resetRequestScope };
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
status: number;
|
status: number;
|
||||||
details: unknown;
|
details: unknown;
|
||||||
@@ -39,8 +50,9 @@ async function fetchApi(path: string, init: RequestInit): Promise<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readResponse<T>(response: Response): Promise<T> {
|
async function readResponse<T>(response: Response): Promise<CoordinatedResult<T>> {
|
||||||
const raw = await response.text();
|
const raw = await response.text();
|
||||||
|
const responseBytes = new TextEncoder().encode(raw).byteLength;
|
||||||
let payload: unknown;
|
let payload: unknown;
|
||||||
if (raw) {
|
if (raw) {
|
||||||
try {
|
try {
|
||||||
@@ -61,43 +73,83 @@ async function readResponse<T>(response: Response): Promise<T> {
|
|||||||
: typeof payload === 'string' && payload.trim()
|
: typeof payload === 'string' && payload.trim()
|
||||||
? payload
|
? payload
|
||||||
: `请求失败(${response.status})`;
|
: `请求失败(${response.status})`;
|
||||||
throw new ApiError(response.status, message, payload);
|
const error = new ApiError(response.status, message, payload);
|
||||||
|
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
if (typeof payload === 'string') throw new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
if (typeof payload === 'string') {
|
||||||
return payload as T;
|
const error = new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||||||
|
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return { data: payload as T, status: response.status, bytes: responseBytes };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
export async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||||||
const headers = new Headers(init.headers);
|
const headers = new Headers(init.headers);
|
||||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
||||||
const send = async (signal = init.signal) => {
|
const method = (init.method ?? 'GET').toUpperCase();
|
||||||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
try {
|
||||||
return readResponse<T>(response);
|
return await coordinateRequest({
|
||||||
};
|
url: path,
|
||||||
if (!timeoutMs) return send();
|
method,
|
||||||
try { return await withRequestDeadline(signal => send(signal), timeoutMs); }
|
signal: init.signal ?? undefined,
|
||||||
|
timeoutMs: timeoutMs ?? requestTimeoutFor(path),
|
||||||
|
cache: method === 'GET' && isImmutableRead(path),
|
||||||
|
tags: requestResourceTags(path),
|
||||||
|
category: requestCategory(path),
|
||||||
|
priority: requestPriority(path),
|
||||||
|
execute: async signal => {
|
||||||
|
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||||||
|
return readResponse<T>(response);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
if (error instanceof RequestTimeoutError) throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
handleAccessFailure(error);
|
||||||
|
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||||||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal });
|
try {
|
||||||
if (!response.ok) {
|
return await coordinateRequest({
|
||||||
const raw = await response.text();
|
url: path,
|
||||||
let payload: unknown = raw;
|
method: 'GET',
|
||||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
signal,
|
||||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
timeoutMs: 900_000,
|
||||||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
queue: false,
|
||||||
throw new ApiError(response.status, message, payload);
|
retry: false,
|
||||||
|
tags: requestResourceTags(path),
|
||||||
|
category: 'export',
|
||||||
|
priority: 'active',
|
||||||
|
execute: async requestSignal => {
|
||||||
|
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal: requestSignal });
|
||||||
|
if (!response.ok) {
|
||||||
|
const raw = await response.text();
|
||||||
|
let payload: unknown = raw;
|
||||||
|
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||||
|
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||||
|
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||||||
|
const error = new ApiError(response.status, message, payload);
|
||||||
|
Object.defineProperty(error, 'responseBytes', { value: new TextEncoder().encode(raw).byteLength });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const disposition = response.headers.get('Content-Disposition') || '';
|
||||||
|
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||||
|
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||||
|
let filename = 'source-evidence.xlsx';
|
||||||
|
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||||||
|
const blob = await response.blob();
|
||||||
|
return { data: { blob, filename }, status: response.status, bytes: blob.size };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
handleAccessFailure(error);
|
||||||
|
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '文件导出超时,请稍后重试。');
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
const disposition = response.headers.get('Content-Disposition') || '';
|
|
||||||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
|
||||||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
|
||||||
let filename = 'source-evidence.xlsx';
|
|
||||||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
|
||||||
return { blob: await response.blob(), filename };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type { StreamEvent } from './eventStream';
|
export type { StreamEvent } from './eventStream';
|
||||||
@@ -105,16 +157,21 @@ export type { StreamEvent } from './eventStream';
|
|||||||
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
|
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
|
||||||
const headers = new Headers({ Accept: 'text/event-stream' });
|
const headers = new Headers({ Accept: 'text/event-stream' });
|
||||||
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
|
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
|
||||||
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
try {
|
||||||
if (!response.ok) {
|
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||||||
const raw = await response.text();
|
if (!response.ok) {
|
||||||
let payload: unknown = raw;
|
const raw = await response.text();
|
||||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
let payload: unknown = raw;
|
||||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||||
|
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||||||
|
}
|
||||||
|
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||||||
|
await consumeEventStream(response.body, options.onEvent);
|
||||||
|
} catch (error) {
|
||||||
|
handleAccessFailure(error);
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
|
||||||
await consumeEventStream(response.body, options.onEvent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function refreshCsrf(): Promise<string> {
|
export async function refreshCsrf(): Promise<string> {
|
||||||
@@ -131,7 +188,7 @@ async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutM
|
|||||||
headers,
|
headers,
|
||||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) invalidateAfterMutation(path);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,17 +199,17 @@ async function queryPost<T>(path: string, body: unknown, signal?: AbortSignal):
|
|||||||
|
|
||||||
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||||
const token = csrfToken ?? await refreshCsrf();
|
const token = csrfToken ?? await refreshCsrf();
|
||||||
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body });
|
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }, 900_000);
|
||||||
window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
invalidateAfterMutation(path);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
sourceColumnCatalog(releaseId?: string) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`); },
|
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 }>('/api/workspace/state', {}, 8000); },
|
workspaceState() { return request<{ authRevision: string; dataRevision: string; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); },
|
||||||
filterFields(manage = false) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`); },
|
filterFields(manage = false, signal?: AbortSignal) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`, { signal }); },
|
||||||
filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); },
|
filterFieldOptions(key: string, search = '', signal?: AbortSignal) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`, { 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,
|
||||||
@@ -160,17 +217,20 @@ export const api = {
|
|||||||
const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000);
|
const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000);
|
||||||
return result.user;
|
return result.user;
|
||||||
},
|
},
|
||||||
login(username: string, password: string) {
|
async login(username: string, password: string) {
|
||||||
|
csrfToken = undefined;
|
||||||
|
resetRequestScope();
|
||||||
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
||||||
},
|
},
|
||||||
logout() {
|
async logout() {
|
||||||
return mutate<void>('/api/auth/logout');
|
try { return await mutate<void>('/api/auth/logout'); }
|
||||||
|
finally { csrfToken = undefined; resetRequestScope(); }
|
||||||
},
|
},
|
||||||
changePassword(currentPassword: string, newPassword: string) {
|
changePassword(currentPassword: string, newPassword: string) {
|
||||||
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
|
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
|
||||||
},
|
},
|
||||||
options() {
|
options(signal?: AbortSignal) {
|
||||||
return request<OptionsResponse>('/api/options');
|
return request<OptionsResponse>('/api/options', { signal });
|
||||||
},
|
},
|
||||||
referenceNames() {
|
referenceNames() {
|
||||||
return request<Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups' | 'groupDepartments'>>('/api/options/reference-names');
|
return request<Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups' | 'groupDepartments'>>('/api/options/reference-names');
|
||||||
@@ -178,6 +238,9 @@ export const api = {
|
|||||||
metrics(params: QueryParams, signal?: AbortSignal) {
|
metrics(params: QueryParams, signal?: AbortSignal) {
|
||||||
return request<MetricsResponse>(`/api/metrics?${toQuery(params)}`, { signal });
|
return request<MetricsResponse>(`/api/metrics?${toQuery(params)}`, { signal });
|
||||||
},
|
},
|
||||||
|
trend(params: QueryParams, signal?: AbortSignal) {
|
||||||
|
return request<TrendResponse>(`/api/metrics/trend?${toQuery(params)}`, { signal });
|
||||||
|
},
|
||||||
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
|
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
|
||||||
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
|
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
|
||||||
},
|
},
|
||||||
@@ -690,6 +753,113 @@ function toQuery(values: object): string {
|
|||||||
return query.toString();
|
return query.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function requestPath(path: string): string {
|
||||||
|
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||||||
|
return new URL(path, base).pathname;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestTimeoutFor(path: string): number | undefined {
|
||||||
|
const pathname = requestPath(path);
|
||||||
|
return pathname === '/api/workspace/state' || pathname === '/api/auth/me' || pathname === '/api/auth/csrf' ? 8_000 : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isImmutableRead(path: string): boolean {
|
||||||
|
const pathname = requestPath(path);
|
||||||
|
if (pathname === '/api/metrics' || pathname === '/api/metrics/trend') return true;
|
||||||
|
if (pathname === '/api/options' || pathname === '/api/options/reference-names') return true;
|
||||||
|
if (pathname === '/api/analysis/source/catalog' || pathname === '/api/rules/schema') return true;
|
||||||
|
if (/^\/api\/governance\/releases\/[^/]+\/(?:inspect|diff)$/.test(pathname)) return true;
|
||||||
|
if (pathname === '/api/governance/coverage') {
|
||||||
|
const url = new URL(path, typeof location === 'undefined' ? 'http://localhost' : location.origin);
|
||||||
|
return Boolean(url.searchParams.get('releaseId'));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestResourceTags(path: string): string[] {
|
||||||
|
const pathname = requestPath(path);
|
||||||
|
if (pathname.startsWith('/api/metrics')) return ['metrics', 'trend', '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/records')) return ['records', 'query'];
|
||||||
|
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'query'];
|
||||||
|
if (pathname.startsWith('/api/sources')) return ['sources', 'workflow', 'catalog'];
|
||||||
|
if (pathname.startsWith('/api/data-workflow')) return ['workflow', 'sources', 'tasks', 'releases'];
|
||||||
|
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return ['tasks', 'workflow'];
|
||||||
|
if (pathname.startsWith('/api/analysis/')) return ['analysis', 'reports', 'options', 'catalog'];
|
||||||
|
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues')) return ['configuration', 'metrics', 'trend', 'records', 'options', 'catalog'];
|
||||||
|
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow'];
|
||||||
|
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow'];
|
||||||
|
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||||||
|
if (pathname.startsWith('/api/analytics/')) return ['configuration', 'targets'];
|
||||||
|
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['access', 'users', 'audit', 'policy'];
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestCategory(path: string): string {
|
||||||
|
const pathname = requestPath(path);
|
||||||
|
if (pathname === '/api/workspace/state') return 'workspace';
|
||||||
|
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||||||
|
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||||||
|
if (pathname.includes('/export') || pathname.endsWith('/download')) return 'export';
|
||||||
|
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||||||
|
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||||||
|
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return 'tasks';
|
||||||
|
if (pathname.startsWith('/api/sources')) return 'sources';
|
||||||
|
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||||||
|
return 'other';
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestPriority(path: string): 'active' | 'background' {
|
||||||
|
const pathname = requestPath(path);
|
||||||
|
return pathname.startsWith('/api/data-workflow/operations/') || pathname.startsWith('/api/import-runs/') || pathname.startsWith('/api/tasks/')
|
||||||
|
? 'background'
|
||||||
|
: 'active';
|
||||||
|
}
|
||||||
|
|
||||||
|
function mutationResources(path: string): string[] | null {
|
||||||
|
const pathname = requestPath(path);
|
||||||
|
if (pathname.startsWith('/api/auth/') || pathname.startsWith('/api/analysis/')) return [];
|
||||||
|
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['*'];
|
||||||
|
if (pathname.startsWith('/api/sources') || pathname.startsWith('/api/releases') || pathname.startsWith('/api/data-workflow') || pathname.startsWith('/api/import-runs')) {
|
||||||
|
return ['metrics', 'trend', 'records', 'options', 'catalog', 'sources', 'workflow', 'tasks', 'releases', 'configuration'];
|
||||||
|
}
|
||||||
|
if (pathname.startsWith('/api/filter-fields')) return ['options', 'catalog', 'query', 'configuration'];
|
||||||
|
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues') || pathname.startsWith('/api/metric-dictionary')) {
|
||||||
|
return ['metrics', 'trend', 'records', 'options', 'catalog', 'configuration'];
|
||||||
|
}
|
||||||
|
if (pathname.startsWith('/api/tasks')) return ['tasks', 'workflow'];
|
||||||
|
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow', 'configuration'];
|
||||||
|
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow', 'configuration'];
|
||||||
|
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'configuration'];
|
||||||
|
if (pathname.startsWith('/api/analytics/')) return ['configuration'];
|
||||||
|
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||||||
|
if (pathname.startsWith('/api/')) return null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidateAfterMutation(path: string): void {
|
||||||
|
const resources = mutationResources(path);
|
||||||
|
if (resources?.length === 0) return;
|
||||||
|
const invalidated = resources ?? ['*'];
|
||||||
|
invalidateReadResources(resources?.includes('*') ? undefined : resources ?? undefined);
|
||||||
|
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: invalidated } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasStatus(error: unknown, status: number): boolean {
|
||||||
|
return !!error && typeof error === 'object' && (error as { status?: unknown }).status === status;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleAccessFailure(error: unknown): void {
|
||||||
|
if (hasStatus(error, 401)) {
|
||||||
|
csrfToken = undefined;
|
||||||
|
resetRequestScope();
|
||||||
|
} else if (hasStatus(error, 403)) {
|
||||||
|
clearReadCache();
|
||||||
|
window.dispatchEvent(new Event('quality-permission-recheck'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const MULTI_VALUE_MARKER = '~qv1~';
|
const MULTI_VALUE_MARKER = '~qv1~';
|
||||||
|
|
||||||
/** Encodes multiple selected values into the scalar query wire format understood by the API. */
|
/** Encodes multiple selected values into the scalar query wire format understood by the API. */
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export type GovernanceResource = 'coverage' | 'protocols' | 'changes' | 'candidates' | 'documents';
|
||||||
|
export type GovernanceFreshness = Partial<Record<GovernanceResource, boolean>>;
|
||||||
|
|
||||||
|
export const GOVERNANCE_RESOURCES: GovernanceResource[] = ['coverage', 'protocols', 'changes', 'candidates', 'documents'];
|
||||||
|
|
||||||
|
const TAB_RESOURCES: Record<string, GovernanceResource[]> = {
|
||||||
|
coverage: ['coverage'],
|
||||||
|
protocols: ['protocols'],
|
||||||
|
changes: ['changes', 'candidates'],
|
||||||
|
revisions: ['documents'],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function governanceResourcesForTab(tab: string): GovernanceResource[] {
|
||||||
|
return TAB_RESOURCES[tab] || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function markGovernanceResourcesStale(
|
||||||
|
current: GovernanceFreshness,
|
||||||
|
resources: GovernanceResource[] = GOVERNANCE_RESOURCES,
|
||||||
|
): GovernanceFreshness {
|
||||||
|
return resources.reduce((next, resource) => ({ ...next, [resource]: true }), { ...current });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function markGovernanceResourcesFresh(current: GovernanceFreshness, resources: GovernanceResource[]): GovernanceFreshness {
|
||||||
|
return resources.reduce((next, resource) => ({ ...next, [resource]: false }), { ...current });
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export function importIssuePageKey(runId: string, page: number): string {
|
||||||
|
return `${runId}:${page}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchesImportIssuePage(loadedRunId: string, loadedPage: number, runId: string, page: number): boolean {
|
||||||
|
return loadedRunId === runId && loadedPage === page;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runImportPollFollowup<T>(
|
||||||
|
runId: string,
|
||||||
|
isCurrent: (runId: string) => boolean,
|
||||||
|
followup: () => Promise<T>,
|
||||||
|
): Promise<{ started: false; current: false } | { started: true; current: boolean; value: T }> {
|
||||||
|
if (!isCurrent(runId)) return { started: false, current: false };
|
||||||
|
const value = await followup();
|
||||||
|
return { started: true, current: isCurrent(runId), value };
|
||||||
|
}
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { createContext, useContext, useEffect, useRef } from 'react';
|
import { createContext, useContext, useEffect, useRef } from 'react';
|
||||||
|
|
||||||
export const WORKSPACE_INVALIDATED = 'quality-workspace-invalidated';
|
export const WORKSPACE_INVALIDATED = 'quality-workspace-invalidated';
|
||||||
export const PageCacheContext = createContext({ active: true, initialSearch: undefined as string | undefined, refreshKey: 0, onLocationChange: (_search: string) => {} });
|
export type PageCacheState = {
|
||||||
|
active: boolean; initialSearch?: string; refreshKey: number;
|
||||||
|
currentReleaseId?: string | null; authRevision?: string; dataRevision?: string;
|
||||||
|
onLocationChange: (search: string) => void;
|
||||||
|
};
|
||||||
|
export const PageCacheContext = createContext<PageCacheState>({ active: true, refreshKey: 0, onLocationChange: () => {} });
|
||||||
export const usePageCache = () => useContext(PageCacheContext);
|
export const usePageCache = () => useContext(PageCacheContext);
|
||||||
|
|
||||||
/** Revalidate retained maintenance data on a real revision change, not on every visit. */
|
/** Revalidate retained maintenance data on a real revision change, not on every visit. */
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { QueryParams } from './types';
|
||||||
|
|
||||||
|
export function loadedQueryPeriod(query: Pick<QueryParams, 'year' | 'month' | 'quarter'>): string {
|
||||||
|
if (query.year == null) return '全部年份';
|
||||||
|
return query.month ? `${query.year}年${String(query.month).padStart(2, '0')}月`
|
||||||
|
: query.quarter ? `${query.year}年第${query.quarter}季度` : `${query.year}年全年`;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Request snapshots follow the workspace unless the incoming link explicitly pins a release. */
|
||||||
|
export function queryForLocation(query: QueryParams, explicitReleaseId?: string): QueryParams {
|
||||||
|
const { releaseId: _boundRelease, ...filters } = query;
|
||||||
|
return explicitReleaseId ? { ...filters, releaseId: explicitReleaseId } : filters;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readQueryLocation(search = window.location.search): Partial<QueryParams> {
|
||||||
|
const context = new URLSearchParams(search).get('context');
|
||||||
|
if (!context) return {};
|
||||||
|
try {
|
||||||
|
const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4));
|
||||||
|
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, character => character.charCodeAt(0)))) as { query?: unknown };
|
||||||
|
if (!parsed.query || typeof parsed.query !== 'object') return {};
|
||||||
|
const query = { ...(parsed.query as Partial<QueryParams>) };
|
||||||
|
return query;
|
||||||
|
} catch { return {}; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Keep the applied scope readable while the controls already show a newer draft. */
|
||||||
|
export function loadedQueryScope(query: QueryParams, decode: (value: string | undefined) => string[]): string {
|
||||||
|
const selections = [query.department, query.group, query.product, query.projectGroup]
|
||||||
|
.flatMap(value => decode(value)).map(value => value === '__UNASSIGNED__' ? '未分类' : value);
|
||||||
|
const sourceCount = (query.columnFilters?.length || 0) + Object.keys(query.extraFilters || {}).length;
|
||||||
|
return [loadedQueryPeriod(query), ...selections, query.productSearch ? `搜索:${query.productSearch}` : '', sourceCount ? `来源条件 ${sourceCount} 项` : ''].filter(Boolean).join(' · ');
|
||||||
|
}
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
export interface RequestScope {
|
||||||
|
userId: string | null;
|
||||||
|
authRevision: string | null;
|
||||||
|
dataRevision: string | null;
|
||||||
|
currentReleaseId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CoordinatedResult<T> {
|
||||||
|
data: T;
|
||||||
|
status?: number;
|
||||||
|
bytes?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CoordinatedRequest<T> {
|
||||||
|
url: string;
|
||||||
|
method?: string;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
timeoutMs?: number;
|
||||||
|
cache?: boolean;
|
||||||
|
queue?: boolean;
|
||||||
|
retry?: boolean;
|
||||||
|
tags?: readonly string[];
|
||||||
|
category?: string;
|
||||||
|
priority?: 'active' | 'background';
|
||||||
|
execute: (signal: AbortSignal) => Promise<CoordinatedResult<T>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RequestDiagnostic {
|
||||||
|
category: string;
|
||||||
|
elapsedMs: number;
|
||||||
|
bytes: number;
|
||||||
|
status: number | null;
|
||||||
|
retries: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const REQUEST_CACHE_LIMIT_BYTES = 32 * 1024 * 1024;
|
||||||
|
export const REQUEST_MAX_GET_CONCURRENCY = 4;
|
||||||
|
const DEFAULT_GET_TIMEOUT_MS = 30_000;
|
||||||
|
const RETRY_DELAY_MS = 1_000;
|
||||||
|
const MAX_DIAGNOSTICS = 120;
|
||||||
|
|
||||||
|
export class RequestTimeoutError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('请求超时');
|
||||||
|
this.name = 'RequestTimeoutError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CacheEntry {
|
||||||
|
data: unknown;
|
||||||
|
bytes: number;
|
||||||
|
tags: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Subscriber<T = unknown> {
|
||||||
|
resolve: (value: T) => void;
|
||||||
|
reject: (error: unknown) => void;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
abortListener?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Flight<T = unknown> {
|
||||||
|
key: string;
|
||||||
|
url: string;
|
||||||
|
scopeKey: string;
|
||||||
|
scopeEpoch: number;
|
||||||
|
cacheEpoch: number;
|
||||||
|
controller: AbortController;
|
||||||
|
subscribers: Set<Subscriber<T>>;
|
||||||
|
request: CoordinatedRequest<T>;
|
||||||
|
startedAt: number;
|
||||||
|
deadlineAt: number;
|
||||||
|
timer?: ReturnType<typeof setTimeout>;
|
||||||
|
retries: number;
|
||||||
|
queued: boolean;
|
||||||
|
slotHeld: boolean;
|
||||||
|
settled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
let scope: RequestScope = { userId: null, authRevision: null, dataRevision: null, currentReleaseId: null };
|
||||||
|
let scopeKey = serializeScope(scope);
|
||||||
|
let scopeEpoch = 0;
|
||||||
|
let cacheEpoch = 0;
|
||||||
|
let activeGets = 0;
|
||||||
|
let cacheBytes = 0;
|
||||||
|
const flights = new Map<string, Flight<any>>();
|
||||||
|
const queue: Flight<any>[] = [];
|
||||||
|
const cache = new Map<string, CacheEntry>();
|
||||||
|
const diagnostics: RequestDiagnostic[] = [];
|
||||||
|
const directControllers = new Set<AbortController>();
|
||||||
|
|
||||||
|
export function configureRequestScope(next: RequestScope): void {
|
||||||
|
const normalized: RequestScope = {
|
||||||
|
userId: next.userId ?? null,
|
||||||
|
authRevision: next.authRevision ?? null,
|
||||||
|
dataRevision: next.dataRevision ?? null,
|
||||||
|
currentReleaseId: next.currentReleaseId ?? null,
|
||||||
|
};
|
||||||
|
const nextKey = serializeScope(normalized);
|
||||||
|
if (nextKey === scopeKey) return;
|
||||||
|
scope = normalized;
|
||||||
|
scopeKey = nextKey;
|
||||||
|
scopeEpoch += 1;
|
||||||
|
clearCache();
|
||||||
|
for (const flight of [...flights.values()]) abortFlight(flight, createAbortError());
|
||||||
|
for (const controller of directControllers) controller.abort();
|
||||||
|
drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateReadResources(tags?: readonly string[]): void {
|
||||||
|
const selected = tags ? new Set(tags) : null;
|
||||||
|
for (const [key, entry] of cache) {
|
||||||
|
if (!selected || entry.tags.some(tag => selected.has(tag))) {
|
||||||
|
cacheBytes -= entry.bytes;
|
||||||
|
cache.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const flight of [...flights.values()]) {
|
||||||
|
if (!selected || flight.request.tags?.some(tag => selected.has(tag))) abortFlight(flight, createAbortError());
|
||||||
|
}
|
||||||
|
drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clears private response data without interrupting unrelated active reads. */
|
||||||
|
export function clearReadCache(): void {
|
||||||
|
clearCache();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resetRequestScope(): void {
|
||||||
|
scope = { userId: null, authRevision: null, dataRevision: null, currentReleaseId: null };
|
||||||
|
scopeKey = serializeScope(scope);
|
||||||
|
scopeEpoch += 1;
|
||||||
|
clearCache();
|
||||||
|
for (const flight of [...flights.values()]) abortFlight(flight, createAbortError());
|
||||||
|
for (const controller of directControllers) controller.abort();
|
||||||
|
drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function coordinateRequest<T>(request: CoordinatedRequest<T>): Promise<T> {
|
||||||
|
const method = (request.method ?? 'GET').toUpperCase();
|
||||||
|
if (request.signal?.aborted) return Promise.reject(createAbortError());
|
||||||
|
if (method !== 'GET' || request.queue === false) return runDirect(request);
|
||||||
|
|
||||||
|
const normalizedUrl = normalizeUrl(request.url);
|
||||||
|
const flightKey = `${scopeEpoch}\u0000${scopeKey}\u0000${normalizedUrl}`;
|
||||||
|
if (request.cache) {
|
||||||
|
const cached = cache.get(flightKey);
|
||||||
|
if (cached) {
|
||||||
|
cache.delete(flightKey);
|
||||||
|
cache.set(flightKey, cached);
|
||||||
|
recordDiagnostic(request.category ?? categoryFromUrl(normalizedUrl), 0, cached.bytes, 200, 0);
|
||||||
|
return Promise.resolve(cloneValue(cached.data) as T);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = flights.get(flightKey) as Flight<T> | undefined;
|
||||||
|
if (existing && !existing.settled) return subscribe(existing, request.signal);
|
||||||
|
|
||||||
|
const timeoutMs = request.timeoutMs ?? DEFAULT_GET_TIMEOUT_MS;
|
||||||
|
const flight: Flight<T> = {
|
||||||
|
key: flightKey,
|
||||||
|
url: normalizedUrl,
|
||||||
|
scopeKey,
|
||||||
|
scopeEpoch,
|
||||||
|
cacheEpoch,
|
||||||
|
controller: new AbortController(),
|
||||||
|
subscribers: new Set(),
|
||||||
|
request: { ...request, method },
|
||||||
|
startedAt: Date.now(),
|
||||||
|
deadlineAt: Date.now() + timeoutMs,
|
||||||
|
retries: 0,
|
||||||
|
queued: true,
|
||||||
|
slotHeld: false,
|
||||||
|
settled: false,
|
||||||
|
};
|
||||||
|
flights.set(flightKey, flight);
|
||||||
|
const subscriber = subscribe(flight, request.signal);
|
||||||
|
flight.timer = setTimeout(() => {
|
||||||
|
abortFlight(flight, new RequestTimeoutError());
|
||||||
|
}, timeoutMs);
|
||||||
|
queue.push(flight);
|
||||||
|
drainQueue();
|
||||||
|
return subscriber;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRequestDiagnostics(): readonly RequestDiagnostic[] {
|
||||||
|
return diagnostics.map(item => ({ ...item }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearRequestDiagnostics(): void {
|
||||||
|
diagnostics.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function subscribe<T>(flight: Flight<T>, signal?: AbortSignal): Promise<T> {
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
const subscriber: Subscriber<T> = { resolve, reject, signal };
|
||||||
|
if (signal?.aborted) {
|
||||||
|
reject(createAbortError());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
subscriber.abortListener = () => {
|
||||||
|
removeSubscriber(flight, subscriber);
|
||||||
|
reject(createAbortError());
|
||||||
|
if (flight.subscribers.size === 0) abortFlight(flight, createAbortError());
|
||||||
|
};
|
||||||
|
signal?.addEventListener('abort', subscriber.abortListener, { once: true });
|
||||||
|
flight.subscribers.add(subscriber);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeSubscriber<T>(flight: Flight<T>, subscriber: Subscriber<T>): void {
|
||||||
|
flight.subscribers.delete(subscriber);
|
||||||
|
if (subscriber.signal && subscriber.abortListener) subscriber.signal.removeEventListener('abort', subscriber.abortListener);
|
||||||
|
}
|
||||||
|
|
||||||
|
function drainQueue(): void {
|
||||||
|
if (activeGets >= REQUEST_MAX_GET_CONCURRENCY || queue.length === 0) return;
|
||||||
|
queue.sort((left, right) => {
|
||||||
|
const priority = Number(right.request.priority !== 'background') - Number(left.request.priority !== 'background');
|
||||||
|
return priority || left.startedAt - right.startedAt;
|
||||||
|
});
|
||||||
|
while (activeGets < REQUEST_MAX_GET_CONCURRENCY && queue.length > 0) {
|
||||||
|
const flight = queue.shift()!;
|
||||||
|
if (flight.settled || flight.subscribers.size === 0) continue;
|
||||||
|
flight.queued = false;
|
||||||
|
flight.slotHeld = true;
|
||||||
|
activeGets += 1;
|
||||||
|
void executeFlight(flight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeFlight(flight: Flight<any>): Promise<void> {
|
||||||
|
const request = flight.request;
|
||||||
|
let status: number | null = null;
|
||||||
|
let bytes = 0;
|
||||||
|
try {
|
||||||
|
const result = await executeWithRetry(flight);
|
||||||
|
status = result.status ?? 200;
|
||||||
|
bytes = result.bytes ?? estimateBytes(result.data);
|
||||||
|
if (flight.settled) return;
|
||||||
|
if (!isCurrentScope(flight)) throw createAbortError();
|
||||||
|
if (request.cache && flight.cacheEpoch === cacheEpoch) putCache(flight.key, { data: cloneValue(result.data), bytes, tags: request.tags ?? [] });
|
||||||
|
settleFlight(flight, undefined, result.data);
|
||||||
|
} catch (error) {
|
||||||
|
status = readStatus(error);
|
||||||
|
bytes = readBytes(error);
|
||||||
|
if (!flight.settled) settleFlight(flight, error);
|
||||||
|
} finally {
|
||||||
|
if (flight.timer) clearTimeout(flight.timer);
|
||||||
|
flight.timer = undefined;
|
||||||
|
releaseSlot(flight);
|
||||||
|
recordDiagnostic(request.category ?? categoryFromUrl(flight.url), Date.now() - flight.startedAt, bytes, status, flight.retries);
|
||||||
|
drainQueue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeWithRetry(flight: Flight<any>): Promise<CoordinatedResult<any>> {
|
||||||
|
for (;;) {
|
||||||
|
if (flight.controller.signal.aborted) throw createAbortError();
|
||||||
|
try {
|
||||||
|
const result = await flight.request.execute(flight.controller.signal);
|
||||||
|
if (flight.controller.signal.aborted) throw createAbortError();
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
if (flight.controller.signal.aborted || flight.request.retry === false || flight.retries >= 1 || !isRetryable(error)) throw error;
|
||||||
|
flight.retries += 1;
|
||||||
|
await delay(RETRY_DELAY_MS, flight.controller.signal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runDirect<T>(request: CoordinatedRequest<T>): Promise<T> {
|
||||||
|
const startedAt = Date.now(), ownerEpoch = scopeEpoch;
|
||||||
|
const controller = new AbortController();
|
||||||
|
directControllers.add(controller);
|
||||||
|
let timedOut = false;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let status: number | null = null;
|
||||||
|
let bytes = 0;
|
||||||
|
let rejectCancellation: (error: Error) => void = () => {};
|
||||||
|
const cancelled = new Promise<never>((_, reject) => { rejectCancellation = reject; });
|
||||||
|
const onCancelled = () => rejectCancellation(createAbortError());
|
||||||
|
controller.signal.addEventListener('abort', onCancelled, { once: true });
|
||||||
|
const abortListener = () => controller.abort();
|
||||||
|
request.signal?.addEventListener('abort', abortListener, { once: true });
|
||||||
|
if (request.signal?.aborted) controller.abort();
|
||||||
|
try {
|
||||||
|
if (controller.signal.aborted) throw createAbortError();
|
||||||
|
if (request.timeoutMs && request.timeoutMs > 0) {
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
timedOut = true;
|
||||||
|
controller.abort();
|
||||||
|
}, request.timeoutMs);
|
||||||
|
}
|
||||||
|
const result = await Promise.race([request.execute(controller.signal), cancelled]);
|
||||||
|
if (controller.signal.aborted || ownerEpoch !== scopeEpoch) throw createAbortError();
|
||||||
|
status = result.status ?? 200;
|
||||||
|
bytes = result.bytes ?? estimateBytes(result.data);
|
||||||
|
return result.data;
|
||||||
|
} catch (error) {
|
||||||
|
status = readStatus(error);
|
||||||
|
bytes = readBytes(error);
|
||||||
|
if (timedOut) throw new RequestTimeoutError();
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
directControllers.delete(controller);
|
||||||
|
controller.signal.removeEventListener('abort', onCancelled);
|
||||||
|
request.signal?.removeEventListener('abort', abortListener);
|
||||||
|
recordDiagnostic(request.category ?? categoryFromUrl(request.url), Date.now() - startedAt, bytes, status, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function settleFlight(flight: Flight<any>, error?: unknown, value?: unknown): void {
|
||||||
|
if (flight.settled) return;
|
||||||
|
flight.settled = true;
|
||||||
|
if (flight.timer) clearTimeout(flight.timer);
|
||||||
|
flight.timer = undefined;
|
||||||
|
flights.delete(flight.key);
|
||||||
|
if (flight.queued) {
|
||||||
|
const index = queue.indexOf(flight);
|
||||||
|
if (index >= 0) queue.splice(index, 1);
|
||||||
|
flight.queued = false;
|
||||||
|
}
|
||||||
|
const subscribers = [...flight.subscribers];
|
||||||
|
flight.subscribers.clear();
|
||||||
|
for (const subscriber of subscribers) {
|
||||||
|
if (subscriber.signal && subscriber.abortListener) subscriber.signal.removeEventListener('abort', subscriber.abortListener);
|
||||||
|
if (error !== undefined) subscriber.reject(error);
|
||||||
|
else subscriber.resolve(value as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function abortFlight(flight: Flight<any>, error: unknown): void {
|
||||||
|
if (flight.settled) return;
|
||||||
|
flight.controller.abort();
|
||||||
|
settleFlight(flight, error);
|
||||||
|
releaseSlot(flight);
|
||||||
|
}
|
||||||
|
|
||||||
|
function releaseSlot(flight: Flight<any>): void {
|
||||||
|
if (!flight.slotHeld) return;
|
||||||
|
flight.slotHeld = false;
|
||||||
|
activeGets = Math.max(0, activeGets - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCurrentScope(flight: Flight<any>): boolean {
|
||||||
|
return flight.scopeEpoch === scopeEpoch && flight.scopeKey === scopeKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
function putCache(key: string, entry: CacheEntry): void {
|
||||||
|
const safeBytes = Math.max(0, Number.isFinite(entry.bytes) ? entry.bytes : estimateBytes(entry.data));
|
||||||
|
if (safeBytes > REQUEST_CACHE_LIMIT_BYTES) return;
|
||||||
|
const previous = cache.get(key);
|
||||||
|
if (previous) cacheBytes -= previous.bytes;
|
||||||
|
cache.delete(key);
|
||||||
|
cache.set(key, { ...entry, bytes: safeBytes });
|
||||||
|
cacheBytes += safeBytes;
|
||||||
|
while (cacheBytes > REQUEST_CACHE_LIMIT_BYTES && cache.size > 0) {
|
||||||
|
const oldestKey = cache.keys().next().value as string | undefined;
|
||||||
|
if (oldestKey === undefined) break;
|
||||||
|
const oldest = cache.get(oldestKey)!;
|
||||||
|
cache.delete(oldestKey);
|
||||||
|
cacheBytes -= oldest.bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearCache(): void {
|
||||||
|
cache.clear();
|
||||||
|
cacheBytes = 0;
|
||||||
|
cacheEpoch += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimateBytes(value: unknown): number {
|
||||||
|
try { return new TextEncoder().encode(JSON.stringify(value) ?? '').byteLength; }
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function cloneValue(value: unknown): unknown {
|
||||||
|
if (typeof structuredClone === 'function') return structuredClone(value);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function recordDiagnostic(category: string, elapsedMs: number, bytes: number, status: number | null, retries: number): void {
|
||||||
|
diagnostics.push({ category, elapsedMs: Math.max(0, elapsedMs), bytes: Math.max(0, bytes), status, retries });
|
||||||
|
if (diagnostics.length > MAX_DIAGNOSTICS) diagnostics.splice(0, diagnostics.length - MAX_DIAGNOSTICS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRetryable(error: unknown): boolean {
|
||||||
|
if (!error || typeof error !== 'object') return false;
|
||||||
|
if ((error as { name?: unknown }).name === 'AbortError' || (error as { name?: unknown }).name === 'RequestTimeoutError') return false;
|
||||||
|
const status = readStatus(error);
|
||||||
|
return error instanceof TypeError || status === 0 || status === 502 || status === 503 || status === 504;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readStatus(error: unknown): number | null {
|
||||||
|
if (!error || typeof error !== 'object') return null;
|
||||||
|
const status = (error as { status?: unknown }).status;
|
||||||
|
return typeof status === 'number' && Number.isFinite(status) ? status : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBytes(error: unknown): number {
|
||||||
|
if (!error || typeof error !== 'object') return 0;
|
||||||
|
const bytes = (error as { responseBytes?: unknown }).responseBytes;
|
||||||
|
return typeof bytes === 'number' && Number.isFinite(bytes) ? bytes : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (signal.aborted) { reject(createAbortError()); return; }
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
signal.removeEventListener('abort', onAbort);
|
||||||
|
resolve();
|
||||||
|
}, ms);
|
||||||
|
const onAbort = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
signal.removeEventListener('abort', onAbort);
|
||||||
|
reject(createAbortError());
|
||||||
|
};
|
||||||
|
signal.addEventListener('abort', onAbort, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUrl(value: string): string {
|
||||||
|
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||||||
|
const url = new URL(value, base);
|
||||||
|
const params = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) =>
|
||||||
|
leftKey.localeCompare(rightKey) || leftValue.localeCompare(rightValue));
|
||||||
|
const normalized = new URLSearchParams();
|
||||||
|
for (const [key, item] of params) normalized.append(key, item);
|
||||||
|
return `${url.pathname}${normalized.size ? `?${normalized.toString()}` : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeScope(value: RequestScope): string {
|
||||||
|
return JSON.stringify([value.userId, value.authRevision, value.dataRevision, value.currentReleaseId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function categoryFromUrl(value: string): string {
|
||||||
|
const pathname = new URL(value, 'http://localhost').pathname;
|
||||||
|
if (pathname === '/api/workspace/state') return 'workspace';
|
||||||
|
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||||||
|
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||||||
|
if (pathname.includes('/export')) return 'export';
|
||||||
|
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||||||
|
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||||||
|
if (pathname.startsWith('/api/tasks')) return 'tasks';
|
||||||
|
if (pathname.startsWith('/api/sources')) return 'sources';
|
||||||
|
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||||||
|
return 'other';
|
||||||
|
}
|
||||||
|
|
||||||
|
function createAbortError(): Error {
|
||||||
|
if (typeof DOMException !== 'undefined') return new DOMException('请求已取消', 'AbortError');
|
||||||
|
const error = new Error('请求已取消');
|
||||||
|
error.name = 'AbortError';
|
||||||
|
return error;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
/** 仅唤醒依赖这些资源的页面;未知写操作按全局失效处理。 */
|
||||||
|
export function pageUsesResources(page: string, resources?: string[]): boolean {
|
||||||
|
if (!resources?.length || resources.includes('*')) return true;
|
||||||
|
const query = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'].includes(page);
|
||||||
|
const dependencies = query ? ['metrics', 'trend', 'records', 'options', 'catalog', 'targets', 'query']
|
||||||
|
: page === 'analysis' ? ['analysis', 'options', 'reports', 'catalog']
|
||||||
|
: page === 'sources' || page === 'imports' ? ['sources', 'workflow', 'tasks', 'releases']
|
||||||
|
: page === 'tasks' ? ['tasks', 'workflow', 'backups', 'monitor']
|
||||||
|
: page === 'access' ? ['access', 'users', 'audit', 'policy']
|
||||||
|
: [page, 'configuration', 'workflow'];
|
||||||
|
return resources.some(resource => dependencies.includes(resource));
|
||||||
|
}
|
||||||
@@ -107,6 +107,14 @@ export interface MetricsResponse {
|
|||||||
coverage: CoverageSummary;
|
coverage: CoverageSummary;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 趋势专用响应,不包含汇总表的产品行。 */
|
||||||
|
export interface TrendResponse {
|
||||||
|
release: MetricsResponse['release'];
|
||||||
|
context: Record<string, unknown>;
|
||||||
|
trend: TrendMetricRow[];
|
||||||
|
coverage: CoverageSummary;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CoverageSummary {
|
export interface CoverageSummary {
|
||||||
rawRows: number;
|
rawRows: number;
|
||||||
includedRows: number;
|
includedRows: number;
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { api } from './api';
|
import { api } from './api';
|
||||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
import { WORKSPACE_INVALIDATED, usePageCache } from './pageCache';
|
||||||
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
||||||
|
import { useVisiblePolling } from './useVisiblePolling';
|
||||||
|
|
||||||
type StoredOperation = { operationId: string; startedAt: string };
|
type StoredOperation = { operationId: string; startedAt: string };
|
||||||
const storageKey = (slot: string) => `quality-data-workflow:${slot}`;
|
const storageKey = (slot: string) => `quality-data-workflow:${slot}`;
|
||||||
const isPending = (value: DataWorkflowOperation | null) => value && ['QUEUED', 'RUNNING'].includes(String(value.status).toUpperCase());
|
const isPending = (value: DataWorkflowOperation | null) => value && ['QUEUED', 'RUNNING'].includes(String(value.status).toUpperCase());
|
||||||
const delay = (ms: number) => new Promise(resolve => window.setTimeout(resolve, ms));
|
|
||||||
|
|
||||||
export function operationError(value: DataWorkflowOperation | null): string {
|
export function operationError(value: DataWorkflowOperation | null): string {
|
||||||
const errors = Array.isArray(value?.errors) ? value.errors : [];
|
const errors = Array.isArray(value?.errors) ? value.errors : [];
|
||||||
@@ -14,14 +14,25 @@ export function operationError(value: DataWorkflowOperation | null): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
|
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
|
||||||
|
const { active } = usePageCache();
|
||||||
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
|
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
|
||||||
|
const [operationId, setOperationId] = useState('');
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [pollRevision, setPollRevision] = useState(0);
|
|
||||||
const [starting, setStarting] = useState(false);
|
const [starting, setStarting] = useState(false);
|
||||||
const callbackRef = useRef(onComplete);
|
const callbackRef = useRef(onComplete);
|
||||||
const activeRef = useRef(0);
|
|
||||||
const startPromiseRef = useRef<Promise<DataWorkflowOperation> | null>(null);
|
const startPromiseRef = useRef<Promise<DataWorkflowOperation> | null>(null);
|
||||||
|
const pollRequestRef = useRef<Promise<void> | null>(null);
|
||||||
|
const terminalHandledRef = useRef(new Set<string>());
|
||||||
|
const generationRef = useRef(0);
|
||||||
|
const mountedRef = useRef(false);
|
||||||
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
|
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
let pending: StoredOperation | null = null;
|
||||||
|
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||||
|
if (pending?.operationId) setOperationId(pending.operationId);
|
||||||
|
return () => { mountedRef.current = false; generationRef.current++; };
|
||||||
|
}, [slot]);
|
||||||
|
|
||||||
const savePendingId = useCallback((value: StoredOperation | null) => {
|
const savePendingId = useCallback((value: StoredOperation | null) => {
|
||||||
try {
|
try {
|
||||||
@@ -30,35 +41,36 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
|||||||
} catch { /* storage may be unavailable in a restricted browser context */ }
|
} catch { /* storage may be unavailable in a restricted browser context */ }
|
||||||
}, [slot]);
|
}, [slot]);
|
||||||
|
|
||||||
const poll = useCallback(async (operationId: string) => {
|
const poll = useCallback((id: string) => {
|
||||||
const runId = ++activeRef.current;
|
if (!id || terminalHandledRef.current.has(id) || pollRequestRef.current) return pollRequestRef.current || Promise.resolve();
|
||||||
setError('');
|
const generation = generationRef.current;
|
||||||
while (activeRef.current === runId) {
|
const attempt = (async () => {
|
||||||
try {
|
try {
|
||||||
const current = await api.dataWorkflowOperation(operationId);
|
const current = await api.dataWorkflowOperation(id);
|
||||||
if (activeRef.current !== runId) return;
|
if (!mountedRef.current || generation !== generationRef.current) return;
|
||||||
setOperation(current);
|
setOperation(current);
|
||||||
|
setError('');
|
||||||
const status = String(current.status || '').toUpperCase();
|
const status = String(current.status || '').toUpperCase();
|
||||||
if (status === 'COMPLETED' || status === 'FAILED') {
|
if (status === 'COMPLETED' || status === 'FAILED') {
|
||||||
if (status === 'COMPLETED') { savePendingId(null); window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); callbackRef.current?.(current); }
|
terminalHandledRef.current.add(id);
|
||||||
else setError(operationError(current));
|
generationRef.current++;
|
||||||
return;
|
setOperationId('');
|
||||||
|
if (status === 'COMPLETED') {
|
||||||
|
savePendingId(null);
|
||||||
|
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration'] } }));
|
||||||
|
callbackRef.current?.(current);
|
||||||
|
} else setError(operationError(current));
|
||||||
}
|
}
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
if (activeRef.current !== runId) return;
|
if (!mountedRef.current || generation !== generationRef.current) return;
|
||||||
setError(value instanceof Error ? value.message : '处理进度读取失败');
|
setError(value instanceof Error ? value.message : '处理进度读取失败');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
await delay(900);
|
})().finally(() => { if (pollRequestRef.current === attempt) pollRequestRef.current = null; });
|
||||||
}
|
pollRequestRef.current = attempt;
|
||||||
|
return attempt;
|
||||||
}, [savePendingId]);
|
}, [savePendingId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useVisiblePolling(() => poll(operationId), 2000, active && Boolean(operationId), true);
|
||||||
let pending: StoredOperation | null = null;
|
|
||||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
|
||||||
if (pending?.operationId) void poll(pending.operationId);
|
|
||||||
return () => { activeRef.current++; };
|
|
||||||
}, [poll, slot, pollRevision]);
|
|
||||||
|
|
||||||
const start = useCallback(async (create: () => Promise<DataWorkflowOperation>) => {
|
const start = useCallback(async (create: () => Promise<DataWorkflowOperation>) => {
|
||||||
if (startPromiseRef.current) return startPromiseRef.current;
|
if (startPromiseRef.current) return startPromiseRef.current;
|
||||||
@@ -69,9 +81,11 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
|||||||
try {
|
try {
|
||||||
const started = await create();
|
const started = await create();
|
||||||
if (!started?.operationId) throw new Error('服务端未返回操作编号');
|
if (!started?.operationId) throw new Error('服务端未返回操作编号');
|
||||||
|
generationRef.current++;
|
||||||
setOperation(started);
|
setOperation(started);
|
||||||
|
terminalHandledRef.current.delete(started.operationId);
|
||||||
|
setOperationId(started.operationId);
|
||||||
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
|
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
|
||||||
void poll(started.operationId);
|
|
||||||
return started;
|
return started;
|
||||||
} catch (value) {
|
} catch (value) {
|
||||||
setError(value instanceof Error ? value.message : '操作未能开始');
|
setError(value instanceof Error ? value.message : '操作未能开始');
|
||||||
@@ -83,18 +97,19 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
|||||||
})();
|
})();
|
||||||
startPromiseRef.current = attempt;
|
startPromiseRef.current = attempt;
|
||||||
return attempt;
|
return attempt;
|
||||||
}, [operation, poll, savePendingId]);
|
}, [operation, savePendingId]);
|
||||||
|
|
||||||
const resume = useCallback(() => {
|
const resume = useCallback(() => {
|
||||||
if (operation?.operationId) void poll(operation.operationId);
|
const id = operation?.operationId || (() => {
|
||||||
else {
|
try { return (JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null)?.operationId || ''; }
|
||||||
let pending: StoredOperation | null = null;
|
catch { return ''; }
|
||||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
})();
|
||||||
if (pending?.operationId) void poll(pending.operationId);
|
if (id) { setError(''); setOperationId(id); void poll(id); }
|
||||||
else setPollRevision(value => value + 1);
|
|
||||||
}
|
|
||||||
}, [operation?.operationId, poll, slot]);
|
}, [operation?.operationId, poll, slot]);
|
||||||
|
|
||||||
const clear = useCallback(() => { activeRef.current++; setOperation(null); setError(''); savePendingId(null); }, [savePendingId]);
|
const clear = useCallback(() => {
|
||||||
|
generationRef.current++;
|
||||||
|
setOperation(null); setOperationId(''); setError(''); savePendingId(null);
|
||||||
|
}, [savePendingId]);
|
||||||
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
|
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
/** Shows a loading indicator only when the request has lasted beyond the delay. */
|
||||||
|
export function useDelayedIndicator(active: boolean, delayMs = 150): boolean {
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) { setVisible(false); return; }
|
||||||
|
setVisible(false);
|
||||||
|
const timer = window.setTimeout(() => setVisible(true), delayMs);
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
}, [active, delayMs]);
|
||||||
|
return active && visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wraps reads with a delayed, concurrency-safe busy indicator. */
|
||||||
|
export function useDelayedBusy(delayMs = 150) {
|
||||||
|
const [pendingCount, setPendingCount] = useState(0);
|
||||||
|
const busy = useDelayedIndicator(pendingCount > 0, delayMs);
|
||||||
|
const mounted = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
mounted.current = true;
|
||||||
|
return () => { mounted.current = false; };
|
||||||
|
}, []);
|
||||||
|
const run = useCallback(async <T,>(work: () => Promise<T>): Promise<T> => {
|
||||||
|
setPendingCount(count => count + 1);
|
||||||
|
try { return await work(); }
|
||||||
|
finally { if (mounted.current) setPendingCount(count => Math.max(0, count - 1)); }
|
||||||
|
}, []);
|
||||||
|
return { busy, run };
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { useEffect, useState, type RefObject } from 'react';
|
||||||
|
|
||||||
|
/** 低频图表接近视口后才读取,页面隐藏时不发起请求。 */
|
||||||
|
export function useResourceVisibility(ref: RefObject<HTMLElement | null>, active: boolean): boolean {
|
||||||
|
const [seen, setSeen] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active || seen) return;
|
||||||
|
const node = ref.current;
|
||||||
|
if (!node) return;
|
||||||
|
if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
|
||||||
|
const observer = new IntersectionObserver(entries => {
|
||||||
|
if (entries.some(entry => entry.isIntersecting)) { setSeen(true); observer.disconnect(); }
|
||||||
|
}, { rootMargin: '240px' });
|
||||||
|
observer.observe(node);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [ref, active, seen]);
|
||||||
|
return active && seen;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import { createVisiblePollingController } from './visiblePollingController';
|
||||||
|
|
||||||
|
/** Polls serially while the owning page is active and the browser tab is visible. */
|
||||||
|
export function useVisiblePolling(callback: () => void | Promise<void>, intervalMs: number, enabled: boolean, immediateOnEnable = false) {
|
||||||
|
const callbackRef = useRef(callback);
|
||||||
|
callbackRef.current = callback;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) return;
|
||||||
|
const controller = createVisiblePollingController(() => callbackRef.current(), intervalMs);
|
||||||
|
const syncVisibility = () => controller.setVisible(document.visibilityState === 'visible');
|
||||||
|
controller.start(document.visibilityState === 'visible', immediateOnEnable);
|
||||||
|
document.addEventListener('visibilitychange', syncVisibility);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('visibilitychange', syncVisibility);
|
||||||
|
controller.stop();
|
||||||
|
};
|
||||||
|
}, [enabled, intervalMs, immediateOnEnable]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
export type PollScheduler = {
|
||||||
|
setTimeout: (callback: () => void, delayMs: number) => unknown;
|
||||||
|
clearTimeout: (handle: unknown) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type VisiblePollingController = {
|
||||||
|
start: (visible: boolean, runImmediately?: boolean) => void;
|
||||||
|
setVisible: (visible: boolean) => void;
|
||||||
|
stop: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Runs one request at a time and starts the next delay only after it settles. */
|
||||||
|
export function createVisiblePollingController(
|
||||||
|
callback: () => void | Promise<void>,
|
||||||
|
intervalMs: number,
|
||||||
|
scheduler: PollScheduler = {
|
||||||
|
setTimeout: (run, delay) => window.setTimeout(run, delay),
|
||||||
|
clearTimeout: handle => window.clearTimeout(handle as number),
|
||||||
|
},
|
||||||
|
): VisiblePollingController {
|
||||||
|
let enabled = false;
|
||||||
|
let visible = false;
|
||||||
|
let inFlight = false;
|
||||||
|
let runImmediatelyAfterFlight = false;
|
||||||
|
let timer: unknown = null;
|
||||||
|
|
||||||
|
const clear = () => {
|
||||||
|
if (timer !== null) scheduler.clearTimeout(timer);
|
||||||
|
timer = null;
|
||||||
|
};
|
||||||
|
const schedule = () => {
|
||||||
|
if (!enabled || !visible || inFlight || timer !== null) return;
|
||||||
|
timer = scheduler.setTimeout(() => {
|
||||||
|
timer = null;
|
||||||
|
void run();
|
||||||
|
}, intervalMs);
|
||||||
|
};
|
||||||
|
const run = async () => {
|
||||||
|
if (!enabled || !visible) return;
|
||||||
|
if (inFlight) {
|
||||||
|
runImmediatelyAfterFlight = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clear();
|
||||||
|
inFlight = true;
|
||||||
|
try { await callback(); } catch { /* Polling errors are rendered by the caller. */ }
|
||||||
|
finally {
|
||||||
|
inFlight = false;
|
||||||
|
if (!enabled || !visible) return;
|
||||||
|
if (runImmediatelyAfterFlight) {
|
||||||
|
runImmediatelyAfterFlight = false;
|
||||||
|
void run();
|
||||||
|
} else schedule();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
start(nextVisible, runImmediately = false) {
|
||||||
|
enabled = true;
|
||||||
|
visible = nextVisible;
|
||||||
|
if (visible) runImmediately ? void run() : schedule();
|
||||||
|
},
|
||||||
|
setVisible(nextVisible) {
|
||||||
|
if (visible === nextVisible) return;
|
||||||
|
visible = nextVisible;
|
||||||
|
if (!enabled) return;
|
||||||
|
if (!visible) clear();
|
||||||
|
else void run();
|
||||||
|
},
|
||||||
|
stop() {
|
||||||
|
enabled = false;
|
||||||
|
runImmediatelyAfterFlight = false;
|
||||||
|
clear();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -28,11 +28,19 @@ function fixture({ authorize=async()=>{}, load }={}) {
|
|||||||
useCallback(fn){cursor++;return fn;},
|
useCallback(fn){cursor++;return fn;},
|
||||||
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});},
|
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});},
|
||||||
};
|
};
|
||||||
|
hooks.useDelayedIndicator=(active,delayMs=150)=>{
|
||||||
|
const [visible,setVisible]=hooks.useState(false);
|
||||||
|
hooks.useEffect(()=>{
|
||||||
|
if(!active){setVisible(false);return;}
|
||||||
|
setVisible(false);const timer=setTimeout(()=>setVisible(true),delayMs);return()=>clearTimeout(timer);
|
||||||
|
},[active,delayMs]);
|
||||||
|
return active&&visible;
|
||||||
|
};
|
||||||
const source=fs.readFileSync(new URL('../src/AnalysisVisuals.tsx',import.meta.url),'utf8');
|
const source=fs.readFileSync(new URL('../src/AnalysisVisuals.tsx',import.meta.url),'utf8');
|
||||||
const componentSource=source.slice(source.indexOf('export function AnalysisVisualCard('),source.indexOf('export function AnalysisVisuals(')).replace('export function','function');
|
const componentSource=source.slice(source.indexOf('export function AnalysisVisualCard('),source.indexOf('export function AnalysisVisuals(')).replace('export function','function');
|
||||||
const body=ts.transpileModule(componentSource,{fileName:'component.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
const body=ts.transpileModule(componentSource,{fileName:'component.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||||
const Component=new Function('React','hooks','runtime',`
|
const Component=new Function('React','hooks','runtime',`
|
||||||
const {useState,useRef,useEffect,useCallback}=hooks;
|
const {useState,useRef,useEffect,useCallback,useDelayedIndicator}=hooks;
|
||||||
const Button='Button',Dropdown='Dropdown',Tag='Tag',Modal='Modal',TableOutlined='TableOutlined',DownloadOutlined='DownloadOutlined',MoreOutlined='MoreOutlined',ChartDataTable='ChartDataTable';
|
const Button='Button',Dropdown='Dropdown',Tag='Tag',Modal='Modal',TableOutlined='TableOutlined',DownloadOutlined='DownloadOutlined',MoreOutlined='MoreOutlined',ChartDataTable='ChartDataTable';
|
||||||
const document={visibilityState:'visible',documentElement:{},addEventListener(){},removeEventListener(){}};
|
const document={visibilityState:'visible',documentElement:{},addEventListener(){},removeEventListener(){}};
|
||||||
const documentIsHidden=()=>false,visualTheme=()=>({}),visualPeriodSummary=()=>'',visualScopeSummary=()=>'',chartSummary=v=>v.title,analysisVisualTypeLabel=()=>'',visualUnitLabel=()=>'';
|
const documentIsHidden=()=>false,visualTheme=()=>({}),visualPeriodSummary=()=>'',visualScopeSummary=()=>'',chartSummary=v=>v.title,analysisVisualTypeLabel=()=>'',visualUnitLabel=()=>'';
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ const json = (value: unknown) => new Response(JSON.stringify(value), {headers:{'
|
|||||||
window.fetch = async (target) => {
|
window.fetch = async (target) => {
|
||||||
const url = new URL(String(target), location.origin);
|
const url = new URL(String(target), location.origin);
|
||||||
if(url.pathname==='/api/auth/me')return json({user:{id:'local-fixture',username:'admin',displayName:'admin',roles:['SYSTEM_ADMIN'],departments:[],groups:[]}});
|
if(url.pathname==='/api/auth/me')return json({user:{id:'local-fixture',username:'admin',displayName:'admin',roles:['SYSTEM_ADMIN'],departments:[],groups:[]}});
|
||||||
if(url.pathname==='/api/workspace/state')return json({authRevision:'fixture',dataRevision:'fixture'});
|
if(url.pathname==='/api/workspace/state')return json({authRevision:'fixture',dataRevision:'fixture',currentReleaseId:'fixture-release'});
|
||||||
if(url.pathname==='/api/options')return json({years:[2026],departments:['工业电机产业部'],groups:['工业电机-VCM'],groupDepartments:{'工业电机-VCM':'工业电机产业部'},products,projectGroupStatus:'READY',projectGroups:[],releases:[{id:'fixture-release',name:'本地验收',status:'PUBLISHED'}]});
|
if(url.pathname==='/api/options')return json({years:[2026],departments:['工业电机产业部'],groups:['工业电机-VCM'],groupDepartments:{'工业电机-VCM':'工业电机产业部'},products,projectGroupStatus:'READY',projectGroups:[],releases:[{id:'fixture-release',name:'本地验收',status:'PUBLISHED'}]});
|
||||||
if(url.pathname==='/api/filter-fields')return json([]);
|
if(url.pathname==='/api/filter-fields')return json([]);
|
||||||
if(url.pathname==='/api/metrics') {
|
if(url.pathname==='/api/metrics'||url.pathname==='/api/metrics/trend') {
|
||||||
const view=url.searchParams.get('view');
|
const view=url.searchParams.get('view');
|
||||||
const product=url.searchParams.get('product');
|
const product=url.searchParams.get('product');
|
||||||
let visible=product?rows.filter(r=>r.product===product):rows;
|
let visible=product?rows.filter(r=>r.product===product):rows;
|
||||||
|
|||||||
@@ -7,13 +7,13 @@ function fixture() {
|
|||||||
const source=fs.readFileSync(process.env.QUERY_CHART_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
|
const source=fs.readFileSync(process.env.QUERY_CHART_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
|
||||||
const end=source.includes('export function TrendTable(')?source.indexOf('export function TrendTable('):source.indexOf('function TrendTable(');
|
const end=source.includes('export function TrendTable(')?source.indexOf('export function TrendTable('):source.indexOf('function TrendTable(');
|
||||||
const code=source.slice(source.indexOf('export function TrendChart('),end).replace('export function','function');
|
const code=source.slice(source.indexOf('export function TrendChart('),end).replace('export function','function');
|
||||||
const slots=new Map(),effects=new Map(),observers=[],charts=[];let cursor=0,dirty=false,queued=[],active=true;
|
const slots=new Map(),effects=new Map(),observers=[],charts=[];let cursor=0,dirty=false,queued=[],active=true,visible=true;
|
||||||
const node={clientWidth:900,clientHeight:380};
|
const node={clientWidth:900,clientHeight:380};
|
||||||
const hooks={useRef(initial){const i=cursor++;if(!slots.has(i))slots.set(i,{current:initial});return slots.get(i);},useState(initial){const i=cursor++;if(!slots.has(i))slots.set(i,initial);return [slots.get(i),v=>{const next=typeof v==='function'?v(slots.get(i)):v;if(!Object.is(next,slots.get(i))){slots.set(i,next);dirty=true;}}];},useCallback(fn,deps){const i=cursor++;const old=slots.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))slots.set(i,{fn,deps});return slots.get(i).fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
|
const hooks={useRef(initial){const i=cursor++;if(!slots.has(i))slots.set(i,{current:initial});return slots.get(i);},useState(initial){const i=cursor++;if(!slots.has(i))slots.set(i,initial);return [slots.get(i),v=>{const next=typeof v==='function'?v(slots.get(i)):v;if(!Object.is(next,slots.get(i))){slots.set(i,next);dirty=true;}}];},useCallback(fn,deps){const i=cursor++;const old=slots.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))slots.set(i,{fn,deps});return slots.get(i).fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
|
||||||
hooks.useLayoutEffect=hooks.useEffect;
|
hooks.useLayoutEffect=hooks.useEffect;
|
||||||
const ec={init(_node,_theme,opts){const c={opts,options:[],resizes:[],disposed:false,getWidth:()=>c.opts.width??100,getHeight:()=>c.opts.height??380,on(){},resize(o){c.resizes.push(o);},setOption(o){c.options.push(o);},convertToPixel:()=>0,dispose(){c.disposed=true;}};charts.push(c);return c;}};
|
const ec={init(_node,_theme,opts){const c={opts,options:[],resizes:[],disposed:false,getWidth:()=>c.opts.width??100,getHeight:()=>c.opts.height??380,on(){},resize(o){c.resizes.push(o);},setOption(o){c.options.push(o);},convertToPixel:()=>0,dispose(){c.disposed=true;}};charts.push(c);return c;}};
|
||||||
const prelude=`const {useRef,useState,useEffect,useLayoutEffect,useCallback}=hooks;
|
const prelude=`const {useRef,useState,useEffect,useLayoutEffect,useCallback}=hooks;
|
||||||
const usePageCache=()=>({active:getActive()});
|
const usePageCache=()=>({active:getActive()}),useResourceVisibility=()=>getActive()&&getVisible();
|
||||||
const Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'});
|
const Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'});
|
||||||
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{constructor(fn){this.fn=fn;observers.push(this)}observe(){}disconnect(){this.disconnected=true}};
|
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{constructor(fn){this.fn=fn;observers.push(this)}observe(){}disconnect(){this.disconnected=true}};
|
||||||
const document={documentElement:{dataset:{}}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
|
const document={documentElement:{dataset:{}}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
|
||||||
@@ -22,11 +22,11 @@ function fixture() {
|
|||||||
const trendBarWidth=()=>32,hasStageRows=()=>true,stageValue=(r,s,f)=>r[s][f],visibleCompositeRate=()=>.95,visibleStageRate=()=>.97,rateNumber=v=>v*100,numberText=String,escapeTooltipText=String,defectWeightRate=()=>0;
|
const trendBarWidth=()=>32,hasStageRows=()=>true,stageValue=(r,s,f)=>r[s][f],visibleCompositeRate=()=>.95,visibleStageRate=()=>.97,rateNumber=v=>v*100,numberText=String,escapeTooltipText=String,defectWeightRate=()=>0;
|
||||||
`;
|
`;
|
||||||
const compiled=ts.transpileModule(prelude+code+'\nreturn TrendChart;',{fileName:'motion.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
const compiled=ts.transpileModule(prelude+code+'\nreturn TrendChart;',{fileName:'motion.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||||
const Component=new Function('React','hooks','echarts','getActive','observers',compiled)(React,hooks,ec,()=>active,observers);
|
const Component=new Function('React','hooks','echarts','getActive','getVisible','observers',compiled)(React,hooks,ec,()=>active,()=>visible,observers);
|
||||||
const stage={qualifiedWeight:90,scrapWeight:10,totalWeight:100,defects:[]};const props={rows:[{month:1,black:stage,bright:stage}],mode:'production',stage:'bright',rateBasis:'original',targetRate:null,onMonth(){}};
|
const stage={qualifiedWeight:90,scrapWeight:10,totalWeight:100,defects:[]};const props={rows:[{month:1,black:stage,bright:stage}],mode:'production',stage:'bright',rateBasis:'original',targetRate:null,onMonth(){}};
|
||||||
function attach(t){if(!t||typeof t!=='object')return;if(t.props?.ref)t.props.ref.current=node;React.Children.forEach(t.props?.children,attach);}
|
function attach(t){if(!t||typeof t!=='object')return;if(t.props?.ref)t.props.ref.current=node;React.Children.forEach(t.props?.children,attach);}
|
||||||
function render(){let n=0;do{cursor=0;dirty=false;queued=[];attach(Component(props));queued.forEach(f=>f());assert.ok(++n<10);}while(dirty);}
|
function render(){let n=0;do{cursor=0;dirty=false;queued=[];attach(Component(props));queued.forEach(f=>f());assert.ok(++n<10);}while(dirty);}
|
||||||
return {charts,node,render,setActive(v){active=v;render();},resize(){for(const o of observers)if(!o.disconnected)o.fn();},unmount(){effects.forEach(e=>e.cleanup?.());}};
|
return {charts,node,render,setVisible(v){visible=v;render();},setActive(v){active=v;render();},resize(){for(const o of observers)if(!o.disconnected)o.fn();},unmount(){effects.forEach(e=>e.cleanup?.());}};
|
||||||
}
|
}
|
||||||
test('visible entry uses the actual chart size and enables native vertical bar growth',()=>{
|
test('visible entry uses the actual chart size and enables native vertical bar growth',()=>{
|
||||||
const f=fixture();f.render();const c=f.charts[0];assert.equal(c.opts.width,900);assert.equal(c.opts.height,380);
|
const f=fixture();f.render();const c=f.charts[0];assert.equal(c.opts.width,900);assert.equal(c.opts.height,380);
|
||||||
@@ -37,3 +37,7 @@ test('cached page reentry creates a fresh vertical reveal and never resizes a hi
|
|||||||
f.setActive(false);assert.equal(f.charts[0].disposed,true);assert.equal(f.charts.length,1);
|
f.setActive(false);assert.equal(f.charts[0].disposed,true);assert.equal(f.charts.length,1);
|
||||||
f.node.clientWidth=900;f.setActive(true);assert.equal(f.charts.length,2);assert.equal(f.charts[1].opts.width,900);assert.ok(f.charts[1].options.find(o=>o.series).animationDuration>0);f.unmount();
|
f.node.clientWidth=900;f.setActive(true);assert.equal(f.charts.length,2);assert.equal(f.charts[1].opts.width,900);assert.ok(f.charts[1].options.find(o=>o.series).animationDuration>0);f.unmount();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('offscreen chart defers initialization until its region becomes visible',()=>{
|
||||||
|
const f=fixture();f.setVisible(false);assert.equal(f.charts.length,0);f.setVisible(true);assert.equal(f.charts.length,1);f.unmount();
|
||||||
|
});
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ function fixture(){
|
|||||||
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{observe(){}disconnect(){}};
|
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{observe(){}disconnect(){}};
|
||||||
const document={documentElement:{}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
|
const document={documentElement:{}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
|
||||||
const usePageCache=()=>({active:true});
|
const usePageCache=()=>({active:true});
|
||||||
|
const useResourceVisibility=()=>true,useDelayedIndicator=value=>value;
|
||||||
const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12});
|
const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12});
|
||||||
const getComputedStyle=()=>({getPropertyValue:()=>''}),escapeTooltipText=v=>v,numberText=v=>String(v),chooseError=e=>e.message;
|
const getComputedStyle=()=>({getPropertyValue:()=>''}),escapeTooltipText=v=>v,numberText=v=>String(v),chooseError=e=>e.message;
|
||||||
class ApiError extends Error{};
|
class ApiError extends Error{};
|
||||||
|
|||||||
@@ -17,10 +17,11 @@ function policyFixture(api, validate) {
|
|||||||
const actions=panel.slice(panel.indexOf(' const save ='),panel.indexOf(' const scopeCounts'));
|
const actions=panel.slice(panel.indexOf(' const save ='),panel.indexOf(' const scopeCounts'));
|
||||||
return new Function('api','validate',transpile(`
|
return new Function('api','validate',transpile(`
|
||||||
let userId,policy=null,effective=null,scopePreview=null,previewBusy=false,loading=false,saving=false,error='',fields={};
|
let userId,policy=null,effective=null,scopePreview=null,previewBusy=false,loading=false,saving=false,error='',fields={};
|
||||||
|
const active=true,policyRequest={current:null},policyRead={run:async work=>{loading=true;try{return await work();}finally{loading=false;}}};
|
||||||
const selectedUser={current:undefined},policyGeneration={current:0},savingRef={current:false},mounted={current:true};
|
const selectedUser={current:undefined},policyGeneration={current:0},savingRef={current:false},mounted={current:true};
|
||||||
const obj=v=>v,text=(v,f)=>v??f,onUnauthorized=()=>false,message={success(){},error(){}};
|
const useCallback=fn=>fn,obj=v=>v,text=(v,f)=>v??f,onUnauthorized=()=>false,message={success(){},error(){}};
|
||||||
class ApiError extends Error{}
|
class ApiError extends Error{}
|
||||||
const form={resetFields(){fields={};},setFieldsValue(v){fields={...fields,...v};},async validateFields(){return validate?validate():{...fields,reason:'fixture reason'};}};
|
const form={isFieldsTouched:()=>false,resetFields(){fields={};},setFieldsValue(v){fields={...fields,...v};},async validateFields(){return validate?validate():{...fields,reason:'fixture reason'};}};
|
||||||
const setUserId=v=>userId=v,setPolicy=v=>policy=v,setEffective=v=>effective=v,setScopePreview=v=>scopePreview=v,
|
const setUserId=v=>userId=v,setPolicy=v=>policy=v,setEffective=v=>effective=v,setScopePreview=v=>scopePreview=v,
|
||||||
setPreviewBusy=v=>previewBusy=v,setLoading=v=>loading=v,setSaving=v=>saving=v,setError=v=>error=v;
|
setPreviewBusy=v=>previewBusy=v,setLoading=v=>loading=v,setSaving=v=>saving=v,setError=v=>error=v;
|
||||||
${selection}${load}${actions}
|
${selection}${load}${actions}
|
||||||
@@ -104,7 +105,9 @@ function drawerFixture() {
|
|||||||
const requests=[],exports=[];let downloaded=0,refreshKey=0;
|
const requests=[],exports=[];let downloaded=0,refreshKey=0;
|
||||||
const props={open:true,row:null,stage:'black',onStage(){},onClose(){},query:freezeSourceRecordsQuery(baseQuery,'release-A','overall',null),onUnauthorized:()=>false};
|
const props={open:true,row:null,stage:'black',onStage(){},onClose(){},query:freezeSourceRecordsQuery(baseQuery,'release-A','overall',null),onUnauthorized:()=>false};
|
||||||
const renderer=hookRenderer(hooks=>new Function('React','hooks','api',transpile(`
|
const renderer=hookRenderer(hooks=>new Function('React','hooks','api',transpile(`
|
||||||
const {useState,useRef,useMemo,useEffect}=hooks;const usePageCache=()=>({refreshKey:api.refreshKey()});const TABLE_PAGE_SIZE=20,MONTHS=Array.from({length:12},(_,i)=>i+1+'月');
|
const {useState,useRef,useMemo,useEffect}=hooks;const useLayoutEffect=useEffect;const usePageCache=()=>({active:true,refreshKey:api.refreshKey()});
|
||||||
|
const useDelayedIndicator=value=>value;
|
||||||
|
${read('QueryResultMotion.tsx').slice(read('QueryResultMotion.tsx').indexOf('export function useRetainedResult'),read('QueryResultMotion.tsx').indexOf('function numericText')).replace('export function','function')}const TABLE_PAGE_SIZE=20,MONTHS=Array.from({length:12},(_,i)=>i+1+'月');
|
||||||
const Drawer='Drawer',Segmented='Segmented',Select='Select',Button='Button',Alert='Alert',Spin='Spin',Table='Table',Pagination='Pagination',SearchOutlined='SearchOutlined',DownloadOutlined='DownloadOutlined';
|
const Drawer='Drawer',Segmented='Segmented',Select='Select',Button='Button',Alert='Alert',Spin='Spin',Table='Table',Pagination='Pagination',SearchOutlined='SearchOutlined',DownloadOutlined='DownloadOutlined';
|
||||||
const Input='Input',readableSelectPopup={},Empty=Object.assign(()=>null,{PRESENTED_IMAGE_SIMPLE:'empty'}),App={useApp:()=>({message:{success(){},error(){}}})};
|
const Input='Input',readableSelectPopup={},Empty=Object.assign(()=>null,{PRESENTED_IMAGE_SIMPLE:'empty'}),App={useApp:()=>({message:{success(){},error(){}}})};
|
||||||
const isSystemVersionField=()=>false,chooseError=e=>e.message,withoutSystemVersionFields=v=>v;
|
const isSystemVersionField=()=>false,chooseError=e=>e.message,withoutSystemVersionFields=v=>v;
|
||||||
@@ -115,11 +118,11 @@ function drawerFixture() {
|
|||||||
return {requests,exports,props,render:()=>renderer.render(props),unmount:()=>renderer.unmount(),invalidate(){refreshKey++;},get downloaded(){return downloaded;}};
|
return {requests,exports,props,render:()=>renderer.render(props),unmount:()=>renderer.unmount(),invalidate(){refreshKey++;},get downloaded(){return downloaded;}};
|
||||||
}
|
}
|
||||||
|
|
||||||
test('actual drawer clears prior rows during page load/failure and offers retry on the same frozen release',async()=>{
|
test('actual drawer retains prior rows without enabling stale actions and retries the same frozen release',async()=>{
|
||||||
const ui=drawerFixture();ui.render();assert.equal(ui.requests[0].params.page,1);assert.equal(ui.requests[0].params.releaseId,'release-A');
|
const ui=drawerFixture();ui.render();assert.equal(ui.requests[0].params.page,1);assert.equal(ui.requests[0].params.releaseId,'release-A');
|
||||||
ui.requests[0].resolve({rows:[{id:'A-1',raw:{field:'value'}}],total:45,pageSize:20,page:1});await tick();let tree=ui.render();
|
ui.requests[0].resolve({rows:[{id:'A-1',raw:{field:'value'}}],total:45,pageSize:20,page:1});await tick();let tree=ui.render();
|
||||||
assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'A-1');find(tree,n=>n.type==='Pagination').props.onChange(2);tree=ui.render();
|
assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'A-1');find(tree,n=>n.type==='Pagination').props.onChange(2);tree=ui.render();
|
||||||
assert.equal(find(tree,n=>n.type==='Table'),undefined);ui.requests[1].reject(Error('page failed'));await tick();tree=ui.render();assert.equal(find(tree,n=>n.type==='Table'),undefined);
|
assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'A-1');assert.equal(find(tree,n=>n.props?.['aria-busy']===true).props.inert,true);ui.requests[1].reject(Error('page failed'));await tick();tree=ui.render();assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'A-1');assert.equal(find(tree,n=>n.type==='Button'&&textOf(n)==='导出明细 Excel').props.disabled,true);
|
||||||
const alert=find(tree,n=>n.type==='Alert');assert.equal(alert.props.description,'page failed');alert.props.action.props.onClick();ui.render();
|
const alert=find(tree,n=>n.type==='Alert');assert.equal(alert.props.description,'page failed');alert.props.action.props.onClick();ui.render();
|
||||||
assert.equal(ui.requests[2].params.page,2);assert.equal(ui.requests[2].params.releaseId,'release-A');ui.unmount();assert.equal(ui.requests[2].signal.aborted,true);
|
assert.equal(ui.requests[2].params.page,2);assert.equal(ui.requests[2].params.releaseId,'release-A');ui.unmount();assert.equal(ui.requests[2].signal.aborted,true);
|
||||||
});
|
});
|
||||||
@@ -143,11 +146,12 @@ test('closing and reopening a different month remounts page/search state and ign
|
|||||||
test('reopening the same frozen drawer reuses its page until the workspace revision changes',async()=>{
|
test('reopening the same frozen drawer reuses its page until the workspace revision changes',async()=>{
|
||||||
const ui=drawerFixture();ui.render();ui.requests[0].resolve({rows:[{id:'cached'}],total:1,pageSize:20,page:1});await tick();ui.render();
|
const ui=drawerFixture();ui.render();ui.requests[0].resolve({rows:[{id:'cached'}],total:1,pageSize:20,page:1});await tick();ui.render();
|
||||||
ui.props.open=false;ui.render();ui.props.open=true;let tree=ui.render();assert.equal(ui.requests.length,1);assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'cached');
|
ui.props.open=false;ui.render();ui.props.open=true;let tree=ui.render();assert.equal(ui.requests.length,1);assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'cached');
|
||||||
ui.invalidate();tree=ui.render();assert.equal(ui.requests.length,2);assert.equal(find(tree,n=>n.type==='Table'),undefined);ui.unmount();
|
ui.invalidate();tree=ui.render();assert.equal(ui.requests.length,2);assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'cached');assert.equal(find(tree,n=>n.props?.['aria-busy']===true).props.inert,true);ui.unmount();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('export from the actual drawer keeps the clicked release even after current publication changes',async()=>{
|
test('export from the actual drawer keeps the clicked release even after current publication changes',async()=>{
|
||||||
const ui=drawerFixture();ui.render();const tree=ui.render();
|
const ui=drawerFixture();ui.render();ui.requests[0].resolve({rows:[{id:'export-ready'}],total:1,pageSize:20,page:1});await tick();const tree=ui.render();
|
||||||
|
assert.equal(find(tree,n=>n.type==='Button'&&textOf(n)==='导出明细 Excel').props.disabled,false);
|
||||||
await find(tree,n=>n.type==='Button'&&textOf(n)==='导出明细 Excel').props.onClick();
|
await find(tree,n=>n.type==='Button'&&textOf(n)==='导出明细 Excel').props.onClick();
|
||||||
assert.equal(ui.exports[0].params.releaseId,'release-A');assert.equal(ui.exports[0].params.month,1);assert.equal(ui.downloaded,1);ui.unmount();
|
assert.equal(ui.exports[0].params.releaseId,'release-A');assert.equal(ui.exports[0].params.month,1);assert.equal(ui.downloaded,1);ui.unmount();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import ts from 'typescript';
|
||||||
|
|
||||||
|
const source = ts.transpileModule(readFileSync(new URL('../src/governanceTabResources.ts', import.meta.url), 'utf8'), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
|
||||||
|
}).outputText.replace(/export /g, '');
|
||||||
|
const { governanceResourcesForTab, markGovernanceResourcesStale, markGovernanceResourcesFresh } = new Function(`${source};return { governanceResourcesForTab, markGovernanceResourcesStale, markGovernanceResourcesFresh };`)();
|
||||||
|
|
||||||
|
test('governance tabs read only their visible resources, with candidates scoped to changes', () => {
|
||||||
|
assert.deepEqual(governanceResourcesForTab('coverage'), ['coverage']);
|
||||||
|
assert.deepEqual(governanceResourcesForTab('protocols'), ['protocols']);
|
||||||
|
assert.deepEqual(governanceResourcesForTab('changes'), ['changes', 'candidates']);
|
||||||
|
assert.deepEqual(governanceResourcesForTab('revisions'), ['documents']);
|
||||||
|
assert.deepEqual(governanceResourcesForTab('unknown'), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('maintenance refresh dirties every visited governance resource but only clears the active tab', () => {
|
||||||
|
let stale = markGovernanceResourcesFresh(markGovernanceResourcesStale({}), ['documents']);
|
||||||
|
assert.equal(stale.documents, false, 'the revisions tab was already read successfully');
|
||||||
|
|
||||||
|
stale = markGovernanceResourcesStale(stale);
|
||||||
|
stale = markGovernanceResourcesFresh(stale, governanceResourcesForTab('coverage'));
|
||||||
|
|
||||||
|
assert.equal(stale.coverage, false, 'the active coverage tab was refreshed');
|
||||||
|
assert.equal(stale.documents, true, 'the previously visited revisions tab stays dirty until selected');
|
||||||
|
assert.equal(governanceResourcesForTab('revisions').some(resource => stale[resource]), true);
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import ts from 'typescript';
|
||||||
|
|
||||||
|
const source = ts.transpileModule(readFileSync(new URL('../src/importLifecycleGuards.ts', import.meta.url), 'utf8'), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
|
||||||
|
}).outputText.replace(/export /g, '');
|
||||||
|
const guards = new Function(`${source};return { importIssuePageKey, matchesImportIssuePage, runImportPollFollowup };`)();
|
||||||
|
|
||||||
|
test('import issue page identity includes both run and page', () => {
|
||||||
|
assert.equal(guards.importIssuePageKey('run-a', 2), 'run-a:2');
|
||||||
|
assert.notEqual(guards.importIssuePageKey('run-a', 2), guards.importIssuePageKey('run-a', 3));
|
||||||
|
assert.notEqual(guards.importIssuePageKey('run-a', 2), guards.importIssuePageKey('run-b', 2));
|
||||||
|
assert.equal(guards.matchesImportIssuePage('run-a', 2, 'run-a', 2), true);
|
||||||
|
assert.equal(guards.matchesImportIssuePage('run-a', 2, 'run-a', 3), false);
|
||||||
|
assert.equal(guards.matchesImportIssuePage('run-a', 2, 'run-b', 2), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an import poll does not start candidate or issue follow-up reads after the view becomes inactive', async () => {
|
||||||
|
let active = false;
|
||||||
|
let followupCalls = 0;
|
||||||
|
const skipped = await guards.runImportPollFollowup('run-a', () => active, async () => { followupCalls++; });
|
||||||
|
assert.deepEqual(skipped, { started: false, current: false });
|
||||||
|
assert.equal(followupCalls, 0);
|
||||||
|
|
||||||
|
active = true;
|
||||||
|
let resolveRead;
|
||||||
|
const pending = guards.runImportPollFollowup('run-a', () => active, () => {
|
||||||
|
followupCalls++;
|
||||||
|
return new Promise(resolve => { resolveRead = resolve; });
|
||||||
|
});
|
||||||
|
active = false;
|
||||||
|
resolveRead({ items: [] });
|
||||||
|
const stale = await pending;
|
||||||
|
assert.deepEqual(stale, { started: true, current: false, value: { items: [] } });
|
||||||
|
assert.equal(followupCalls, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { queryForLocation, loadedQueryPeriod } from '../src/queryLoadingScope.ts';
|
||||||
|
|
||||||
|
test('automatic current snapshots follow the next workspace release after a reload', () => {
|
||||||
|
const urlQuery=queryForLocation({year:2026,view:'product',releaseId:'r1'});
|
||||||
|
const restored=JSON.parse(JSON.stringify(urlQuery));
|
||||||
|
assert.equal(restored.releaseId,undefined);
|
||||||
|
assert.equal(restored.releaseId || 'r2','r2');
|
||||||
|
});
|
||||||
|
test('explicit historical links stay pinned across reloads and current-release changes', () => {
|
||||||
|
const restored=JSON.parse(JSON.stringify(queryForLocation({year:2026,view:'product',releaseId:'r2'},'r1')));
|
||||||
|
assert.equal(restored.releaseId || 'r2','r1');
|
||||||
|
});
|
||||||
|
test('failed drilled trends cannot ready a replacement table or enable stale exports', () => {
|
||||||
|
const stage=fs.readFileSync(new URL('../src/StageProductPage.tsx',import.meta.url),'utf8');
|
||||||
|
const query=fs.readFileSync(new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
|
||||||
|
const readyExpression=stage.match(/const tableReady=([^;]+);/)[1];
|
||||||
|
const stageReady=new Function('current','drilledProduct','trendResponse','trendKey','trendLoading','trendError',`return ${readyExpression}`);
|
||||||
|
assert.equal(stageReady({},'B',{key:'A'},'B',false,'offline'),false);
|
||||||
|
assert.equal(stageReady({},'B',{key:'B'},'B',false,''),true);
|
||||||
|
assert.equal(stageReady({},'',null,'B',false,'offline'),true);
|
||||||
|
const exportExpression=query.match(/exporting=\{summaryExporting\} exportDisabled=\{([^\n]+)\}/)[1];
|
||||||
|
const disabled=new Function('queryBusy','summaryBusy','tableReady','summaryMetricsData','drilledProduct','trendLoading','currentTrendError','drilledTrendData','visibleRows',`return ${exportExpression}`);
|
||||||
|
assert.equal(disabled(false,false,false,{},'B',false,'offline',Array(12).fill({}),[]),true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cross-year retained scope has a readable label when year is omitted',()=>{assert.equal(loadedQueryPeriod({}), '全部年份');});
|
||||||
@@ -5,11 +5,11 @@ const fields=[{key:'customer',label:'客户代码',type:'source_value',stages:['
|
|||||||
const metric=(qualified:number,scrap:number)=>({qualifiedWeight:qualified,scrapWeight:scrap,totalWeight:qualified+scrap,rate:qualified/(qualified+scrap),headquartersScrapWeight:0,rateWithoutHeadquartersScrap:qualified/(qualified+scrap),defects:[{name:'材料废',weight:scrap*.5,rate:.5},{name:'加工废',weight:scrap*.3,rate:.3},{name:'镀废',weight:scrap*.2,rate:.2}]});
|
const metric=(qualified:number,scrap:number)=>({qualifiedWeight:qualified,scrapWeight:scrap,totalWeight:qualified+scrap,rate:qualified/(qualified+scrap),headquartersScrapWeight:0,rateWithoutHeadquartersScrap:qualified/(qualified+scrap),defects:[{name:'材料废',weight:scrap*.5,rate:.5},{name:'加工废',weight:scrap*.3,rate:.3},{name:'镀废',weight:scrap*.2,rate:.2}]});
|
||||||
window.fetch=async(target,init)=>{
|
window.fetch=async(target,init)=>{
|
||||||
const url=new URL(String(target),location.origin),path=url.pathname;
|
const url=new URL(String(target),location.origin),path=url.pathname;
|
||||||
if(path==='/api/auth/me')return json({user});if(path==='/api/auth/csrf')return json({token:'local-preview'});if(path==='/api/workspace/state')return json({authRevision:'preview',dataRevision:'preview'});
|
if(path==='/api/auth/me')return json({user});if(path==='/api/auth/csrf')return json({token:'local-preview'});if(path==='/api/workspace/state')return json({authRevision:'preview',dataRevision:'preview',currentReleaseId:'preview-published'});
|
||||||
if(path==='/api/options')return json({years:[2026],departments:['汽车交通产业部','工业电机产业部'],groups:['汽车交通-国内','汽车交通-海外','工业电机-中国区'],products:['P001 磁钢','P002 磁环'],projectGroupStatus:'READY',projectGroups:['新能源汽车'],groupDepartments:{'汽车交通-国内':'汽车交通产业部','汽车交通-海外':'汽车交通产业部','工业电机-中国区':'工业电机产业部'},organizationPaths:[{department:'汽车交通产业部',group:'汽车交通-国内',product:'P001 磁钢'},{department:'工业电机产业部',group:'工业电机-中国区',product:'P002 磁环'}]});
|
if(path==='/api/options')return json({years:[2026],departments:['汽车交通产业部','工业电机产业部'],groups:['汽车交通-国内','汽车交通-海外','工业电机-中国区'],products:['P001 磁钢','P002 磁环'],projectGroupStatus:'READY',projectGroups:['新能源汽车'],groupDepartments:{'汽车交通-国内':'汽车交通产业部','汽车交通-海外':'汽车交通产业部','工业电机-中国区':'工业电机产业部'},organizationPaths:[{department:'汽车交通产业部',group:'汽车交通-国内',product:'P001 磁钢'},{department:'工业电机产业部',group:'工业电机-中国区',product:'P002 磁环'}]});
|
||||||
if(path==='/api/analysis/source/catalog')return json({releaseId:'preview-published',sourceFields:fields});
|
if(path==='/api/analysis/source/catalog')return json({releaseId:'preview-published',sourceFields:fields});
|
||||||
if(path==='/api/analysis/source/values')return json({values:['0007','0012','0090'],hasMore:false,totalCount:3});
|
if(path==='/api/analysis/source/values')return json({values:['0007','0012','0090'],hasMore:false,totalCount:3});
|
||||||
if(path==='/api/metrics'){
|
if(path==='/api/metrics'||path==='/api/metrics/trend'){
|
||||||
const stage=url.searchParams.get('stage')==='black'?'black':'bright',filters=JSON.parse(url.searchParams.get('columnFilters')||'[]');requests.push({stage,filters,trendGranularity:url.searchParams.get('trendGranularity'),group:url.searchParams.get('group'),department:url.searchParams.get('department')});document.getElementById('request-log')!.textContent=JSON.stringify(requests);
|
const stage=url.searchParams.get('stage')==='black'?'black':'bright',filters=JSON.parse(url.searchParams.get('columnFilters')||'[]');requests.push({stage,filters,trendGranularity:url.searchParams.get('trendGranularity'),group:url.searchParams.get('group'),department:url.searchParams.get('department')});document.getElementById('request-log')!.textContent=JSON.stringify(requests);
|
||||||
const selected=stage==='black'?metric(900,100):metric(920,80),empty={qualifiedWeight:0,scrapWeight:0,totalWeight:0,rate:null,defects:[]};
|
const selected=stage==='black'?metric(900,100):metric(920,80),empty={qualifiedWeight:0,scrapWeight:0,totalWeight:0,rate:null,defects:[]};
|
||||||
const row={key:'P001',label:'P001 磁钢',department:'汽车交通产业部',group:'汽车交通-国内',product:'P001 磁钢',projectGroup:'新能源汽车',black:stage==='black'?selected:empty,bright:stage==='bright'?selected:empty,compositeRate:selected.rate,coverage:{blackRows:stage==='black'?20:0,brightRows:stage==='bright'?20:0}};
|
const row={key:'P001',label:'P001 磁钢',department:'汽车交通产业部',group:'汽车交通-国内',product:'P001 磁钢',projectGroup:'新能源汽车',black:stage==='black'?selected:empty,bright:stage==='bright'?selected:empty,compositeRate:selected.rate,coverage:{blackRows:stage==='black'?20:0,brightRows:stage==='bright'?20:0}};
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createVisiblePollingController } from '../src/visiblePollingController.ts';
|
||||||
|
|
||||||
|
function fakeClock() {
|
||||||
|
let nextId = 0;
|
||||||
|
let now = 0;
|
||||||
|
const timers = new Map();
|
||||||
|
return {
|
||||||
|
timers,
|
||||||
|
now: () => now,
|
||||||
|
setTimeout(callback, delay) { const id = ++nextId; timers.set(id, { at: now + delay, callback }); return id; },
|
||||||
|
clearTimeout(id) { timers.delete(id); },
|
||||||
|
advance(ms) {
|
||||||
|
now += ms;
|
||||||
|
const due = [...timers.entries()].filter(([, timer]) => timer.at <= now).sort((a, b) => a[1].at - b[1].at);
|
||||||
|
for (const [id, timer] of due) { timers.delete(id); timer.callback(); }
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const flush = async () => { await Promise.resolve(); await Promise.resolve(); };
|
||||||
|
|
||||||
|
test('polls serially and waits the full interval after each request settles', async () => {
|
||||||
|
const clock = fakeClock(); let completeFirst; let calls = 0;
|
||||||
|
const controller = createVisiblePollingController(() => {
|
||||||
|
calls++;
|
||||||
|
if (calls === 1) return new Promise(resolve => { completeFirst = resolve; });
|
||||||
|
}, 15000, clock);
|
||||||
|
controller.start(true);
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
clock.advance(15000);
|
||||||
|
await flush();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
clock.advance(60000);
|
||||||
|
assert.equal(calls, 1, 'an unresolved request prevents overlap');
|
||||||
|
completeFirst();
|
||||||
|
await flush();
|
||||||
|
clock.advance(14999);
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
clock.advance(1);
|
||||||
|
await flush();
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
controller.stop();
|
||||||
|
assert.equal(clock.timers.size, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pauses while hidden and immediately checks on resume without overlapping an in-flight read', async () => {
|
||||||
|
const clock = fakeClock(); let release; let calls = 0; let concurrent = 0; let maxConcurrent = 0;
|
||||||
|
const controller = createVisiblePollingController(async () => {
|
||||||
|
calls++; concurrent++; maxConcurrent = Math.max(maxConcurrent, concurrent);
|
||||||
|
if (calls === 1) await new Promise(resolve => { release = resolve; });
|
||||||
|
concurrent--;
|
||||||
|
}, 2000, clock);
|
||||||
|
controller.start(false, true);
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
controller.setVisible(true);
|
||||||
|
await flush();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
controller.setVisible(false);
|
||||||
|
controller.setVisible(true);
|
||||||
|
await flush();
|
||||||
|
assert.equal(calls, 1, 'visibility return queues an immediate read behind the active request');
|
||||||
|
release();
|
||||||
|
await flush();
|
||||||
|
await flush();
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.equal(maxConcurrent, 1);
|
||||||
|
controller.stop();
|
||||||
|
assert.equal(clock.timers.size, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stopping polling leaves the current request alone and prevents future scheduling', async () => {
|
||||||
|
const clock = fakeClock(); let release; let calls = 0;
|
||||||
|
const controller = createVisiblePollingController(() => { calls++; return new Promise(resolve => { release = resolve; }); }, 5000, clock);
|
||||||
|
controller.start(true);
|
||||||
|
clock.advance(5000);
|
||||||
|
await flush();
|
||||||
|
controller.stop();
|
||||||
|
release();
|
||||||
|
await flush();
|
||||||
|
assert.equal(clock.timers.size, 0);
|
||||||
|
clock.advance(50000);
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const ts = require('typescript');
|
||||||
|
const sourcePath = new URL('../src/requestCoordinator.ts', import.meta.url);
|
||||||
|
|
||||||
|
async function loadCoordinator() {
|
||||||
|
const source = await readFile(sourcePath, 'utf8');
|
||||||
|
const compiled = ts.transpileModule(source, {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
|
||||||
|
}).outputText;
|
||||||
|
return import(`data:text/javascript;base64,${Buffer.from(compiled).toString('base64')}#${Date.now()}-${Math.random()}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||||
|
const result = data => ({ data, status: 200, bytes: Buffer.byteLength(JSON.stringify(data)) });
|
||||||
|
|
||||||
|
test('same scoped GET and normalized query share one execution', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
let runs = 0;
|
||||||
|
let finish;
|
||||||
|
const execute = () => {
|
||||||
|
runs += 1;
|
||||||
|
return new Promise(resolve => { finish = () => resolve(result({ value: 7 })); });
|
||||||
|
};
|
||||||
|
const first = coordinator.coordinateRequest({ url: '/api/metrics?b=2&a=1', execute });
|
||||||
|
const second = coordinator.coordinateRequest({ url: '/api/metrics?a=1&b=2', execute });
|
||||||
|
await tick();
|
||||||
|
assert.equal(runs, 1);
|
||||||
|
finish();
|
||||||
|
assert.deepEqual(await Promise.all([first, second]), [{ value: 7 }, { value: 7 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('one subscriber can cancel without aborting the shared GET for another', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
const left = new AbortController();
|
||||||
|
const right = new AbortController();
|
||||||
|
let networkSignal;
|
||||||
|
let finish;
|
||||||
|
const execute = signal => {
|
||||||
|
networkSignal = signal;
|
||||||
|
return new Promise(resolve => { finish = () => resolve(result('ok')); });
|
||||||
|
};
|
||||||
|
const first = coordinator.coordinateRequest({ url: '/api/metrics?x=1', signal: left.signal, execute });
|
||||||
|
const second = coordinator.coordinateRequest({ url: '/api/metrics?x=1', signal: right.signal, execute });
|
||||||
|
await tick();
|
||||||
|
left.abort();
|
||||||
|
await assert.rejects(first, error => error.name === 'AbortError');
|
||||||
|
assert.equal(networkSignal.aborted, false);
|
||||||
|
finish();
|
||||||
|
assert.equal(await second, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a cancelled queued GET never starts and an active read starts before background work', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
const started = [];
|
||||||
|
const releases = new Map();
|
||||||
|
const execute = label => signal => {
|
||||||
|
started.push(label);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
releases.set(label, () => resolve(result(label)));
|
||||||
|
signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const active = Array.from({ length: 4 }, (_, index) => coordinator.coordinateRequest({ url: `/hold/${index}`, execute: execute(`hold-${index}`) }));
|
||||||
|
await tick();
|
||||||
|
assert.equal(started.length, 4);
|
||||||
|
const queued = new AbortController();
|
||||||
|
const cancelled = coordinator.coordinateRequest({ url: '/queued/cancel', signal: queued.signal, execute: execute('cancelled') });
|
||||||
|
const background = coordinator.coordinateRequest({ url: '/queued/background', priority: 'background', execute: execute('background') });
|
||||||
|
const foreground = coordinator.coordinateRequest({ url: '/queued/foreground', priority: 'active', execute: execute('foreground') });
|
||||||
|
queued.abort();
|
||||||
|
await assert.rejects(cancelled, error => error.name === 'AbortError');
|
||||||
|
releases.get('hold-0')();
|
||||||
|
const waitForStart = async label => {
|
||||||
|
const expires = Date.now() + 1_000;
|
||||||
|
while (!started.includes(label) && Date.now() < expires) await tick();
|
||||||
|
assert.ok(started.includes(label), `${label} did not start`);
|
||||||
|
};
|
||||||
|
await waitForStart('foreground');
|
||||||
|
assert.equal(started[4], 'foreground');
|
||||||
|
releases.get('foreground')();
|
||||||
|
await waitForStart('background');
|
||||||
|
releases.get('background')();
|
||||||
|
for (const label of ['hold-1', 'hold-2', 'hold-3']) releases.get(label)();
|
||||||
|
await Promise.all([...active, background, foreground]);
|
||||||
|
assert.equal(started.includes('cancelled'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('retry is limited to one and the one second backoff counts against the request budget', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
let runs = 0;
|
||||||
|
const started = Date.now();
|
||||||
|
await assert.rejects(coordinator.coordinateRequest({
|
||||||
|
url: '/api/metrics', timeoutMs: 35,
|
||||||
|
execute: async () => { runs += 1; throw Object.assign(new Error('unavailable'), { status: 503 }); },
|
||||||
|
}), error => error.name === 'RequestTimeoutError');
|
||||||
|
assert.equal(runs, 1);
|
||||||
|
assert.ok(Date.now() - started < 500);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a successful read retries a transient gateway failure exactly once after one second', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
let runs = 0;
|
||||||
|
const started = Date.now();
|
||||||
|
const value = await coordinator.coordinateRequest({
|
||||||
|
url: '/api/metrics', timeoutMs: 2500,
|
||||||
|
execute: async () => {
|
||||||
|
runs += 1;
|
||||||
|
if (runs === 1) throw Object.assign(new Error('gateway'), { status: 502 });
|
||||||
|
return result('recovered');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(value, 'recovered');
|
||||||
|
assert.equal(runs, 2);
|
||||||
|
assert.ok(Date.now() - started >= 950);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('response body work is covered by the deadline and authorization failures are not retried', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
let bodyRuns = 0;
|
||||||
|
await assert.rejects(coordinator.coordinateRequest({
|
||||||
|
url: '/api/metrics/body', timeoutMs: 20,
|
||||||
|
execute: signal => {
|
||||||
|
bodyRuns += 1;
|
||||||
|
return new Promise((_, reject) => signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true }));
|
||||||
|
},
|
||||||
|
}), error => error.name === 'RequestTimeoutError');
|
||||||
|
assert.equal(bodyRuns, 1);
|
||||||
|
|
||||||
|
let deniedRuns = 0;
|
||||||
|
await assert.rejects(coordinator.coordinateRequest({
|
||||||
|
url: '/api/private', execute: async () => { deniedRuns += 1; throw Object.assign(new Error('denied'), { status: 401 }); },
|
||||||
|
}), error => error.status === 401);
|
||||||
|
assert.equal(deniedRuns, 1);
|
||||||
|
|
||||||
|
let writeRuns = 0;
|
||||||
|
await assert.rejects(coordinator.coordinateRequest({
|
||||||
|
url: '/api/sources', method: 'POST', execute: async () => { writeRuns += 1; throw Object.assign(new Error('gateway'), { status: 503 }); },
|
||||||
|
}), error => error.status === 503);
|
||||||
|
assert.equal(writeRuns, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cache is LRU bounded, scoped to the tenant, and invalidated by tags', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
coordinator.configureRequestScope({ userId: 'u1', authRevision: 'a1', dataRevision: 'd1', currentReleaseId: 'r1' });
|
||||||
|
let runs = 0;
|
||||||
|
const fetchValue = url => coordinator.coordinateRequest({ url, cache: true, tags: ['metrics'], execute: async () => {
|
||||||
|
runs += 1;
|
||||||
|
return result({ payload: 'x'.repeat(11 * 1024 * 1024), version: runs });
|
||||||
|
} });
|
||||||
|
await fetchValue('/api/metrics?a=1');
|
||||||
|
await fetchValue('/api/metrics?a=2');
|
||||||
|
await fetchValue('/api/metrics?a=3');
|
||||||
|
await fetchValue('/api/metrics?a=2');
|
||||||
|
assert.equal(runs, 3);
|
||||||
|
await fetchValue('/api/metrics?a=1');
|
||||||
|
assert.equal(runs, 4);
|
||||||
|
|
||||||
|
coordinator.configureRequestScope({ userId: 'u2', authRevision: 'a1', dataRevision: 'd1', currentReleaseId: 'r1' });
|
||||||
|
await fetchValue('/api/metrics?a=2');
|
||||||
|
assert.equal(runs, 5);
|
||||||
|
coordinator.invalidateReadResources(['metrics']);
|
||||||
|
await fetchValue('/api/metrics?a=2');
|
||||||
|
assert.equal(runs, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('scope changes prevent an old response from resolving or entering the new scope cache', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
coordinator.configureRequestScope({ userId: 'old', authRevision: '1', dataRevision: '1', currentReleaseId: null });
|
||||||
|
let finishOld;
|
||||||
|
const stale = coordinator.coordinateRequest({ url: '/api/metrics', cache: true, tags: ['metrics'], execute: () => new Promise(resolve => { finishOld = () => resolve(result('old')); }) });
|
||||||
|
await tick();
|
||||||
|
coordinator.configureRequestScope({ userId: 'new', authRevision: '1', dataRevision: '1', currentReleaseId: null });
|
||||||
|
await assert.rejects(stale, error => error.name === 'AbortError');
|
||||||
|
finishOld();
|
||||||
|
let newRuns = 0;
|
||||||
|
const readNew = () => coordinator.coordinateRequest({ url: '/api/metrics', cache: true, tags: ['metrics'], execute: async () => { newRuns += 1; return result('new'); } });
|
||||||
|
assert.equal(await readNew(), 'new');
|
||||||
|
assert.equal(await readNew(), 'new');
|
||||||
|
assert.equal(newRuns, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('security cache clearing keeps unrelated in-flight reads alive and blocks their stale cache write', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
let finish;
|
||||||
|
let runs = 0;
|
||||||
|
const read = () => coordinator.coordinateRequest({
|
||||||
|
url: '/api/options', cache: true, tags: ['options'],
|
||||||
|
execute: async () => {
|
||||||
|
runs += 1;
|
||||||
|
if (runs === 1) return new Promise(resolve => { finish = () => resolve(result('already-authorized')); });
|
||||||
|
return result('fresh');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const active = read();
|
||||||
|
await tick();
|
||||||
|
coordinator.clearReadCache();
|
||||||
|
finish();
|
||||||
|
assert.equal(await active, 'already-authorized');
|
||||||
|
assert.equal(await read(), 'fresh');
|
||||||
|
assert.equal(runs, 2);
|
||||||
|
const diagnostic = coordinator.getRequestDiagnostics().at(-1);
|
||||||
|
assert.deepEqual(Object.keys(diagnostic).sort(), ['bytes', 'category', 'elapsedMs', 'retries', 'status']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a file read outside the data queue is cancelled when its owning account changes', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
coordinator.configureRequestScope({ userId: 'old', authRevision: '1', dataRevision: '1', currentReleaseId: 'r' });
|
||||||
|
let finish, signal;
|
||||||
|
const file = coordinator.coordinateRequest({
|
||||||
|
url: '/api/records/export', queue: false, retry: false, timeoutMs: 1000,
|
||||||
|
execute: current => { signal = current; return new Promise(resolve => { finish = () => resolve(result('old-user-file')); }); },
|
||||||
|
});
|
||||||
|
const outcome = file.then(value => ({ value }), error => ({ error }));
|
||||||
|
coordinator.configureRequestScope({ userId: 'new', authRevision: '1', dataRevision: '1', currentReleaseId: 'r' });
|
||||||
|
finish();
|
||||||
|
const settled = await outcome;
|
||||||
|
assert.equal(signal.aborted, true);
|
||||||
|
assert.equal(settled.error?.name, 'AbortError');
|
||||||
|
assert.equal(settled.value, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a dropped response body is retried once as a network read failure', async () => {
|
||||||
|
const coordinator = await loadCoordinator();
|
||||||
|
let runs = 0;
|
||||||
|
const value = await coordinator.coordinateRequest({
|
||||||
|
url: '/api/metrics/trend', timeoutMs: 2500,
|
||||||
|
execute: async () => {
|
||||||
|
runs++;
|
||||||
|
// 浏览器在 headers 已到、正文读取期间断网时抛出 TypeError。
|
||||||
|
await new Response(new ReadableStream({ start(controller) {
|
||||||
|
if (runs === 1) controller.error(new TypeError('terminated'));
|
||||||
|
else { controller.enqueue(new TextEncoder().encode('ok')); controller.close(); }
|
||||||
|
} })).text();
|
||||||
|
return result('recovered');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(runs, 2);
|
||||||
|
assert.equal(value, 'recovered');
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { pageUsesResources } from '../src/resourceInvalidation.ts';
|
||||||
|
|
||||||
|
test('analysis and task changes do not invalidate retained query tables', () => {
|
||||||
|
for (const page of ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct']) {
|
||||||
|
assert.equal(pageUsesResources(page, ['analysis', 'tasks']), false);
|
||||||
|
assert.equal(pageUsesResources(page, ['metrics', 'releases']), true);
|
||||||
|
assert.equal(pageUsesResources(page, ['options']), true);
|
||||||
|
}
|
||||||
|
assert.equal(pageUsesResources('tasks', ['tasks']), true);
|
||||||
|
assert.equal(pageUsesResources('analysis', ['analysis']), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('configuration resources wake only dependent editors and unknown writes safely invalidate all', () => {
|
||||||
|
assert.equal(pageUsesResources('rules', ['configuration']), true);
|
||||||
|
assert.equal(pageUsesResources('masterData', ['configuration']), true);
|
||||||
|
assert.equal(pageUsesResources('access', ['policy']), true);
|
||||||
|
assert.equal(pageUsesResources('sources', ['workflow']), true);
|
||||||
|
for (const page of ['overall', 'analysis', 'rules', 'access']) {
|
||||||
|
assert.equal(pageUsesResources(page), true);
|
||||||
|
assert.equal(pageUsesResources(page, ['*']), true);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import ts from 'typescript';
|
||||||
|
import React from 'react';
|
||||||
|
import { readQueryLocation } from '../src/queryLoadingScope.ts';
|
||||||
|
import { pageUsesResources } from '../src/resourceInvalidation.ts';
|
||||||
|
|
||||||
|
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||||
|
const deferred = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); return { promise, resolve, reject }; };
|
||||||
|
|
||||||
|
function fixture() {
|
||||||
|
const source = fs.readFileSync(new URL('../src/CachedWorkspacePages.tsx', import.meta.url), 'utf8')
|
||||||
|
.replace(/^import[\s\S]*?;\n/gm, '').replace(/export /g, '');
|
||||||
|
const values = new Map(), refs = new Map(), effects = new Map(), events = new Map(), navigations = [], scopes = [];
|
||||||
|
let cursor = 0, dirty = false, queued = [], tree;
|
||||||
|
let state = { authRevision: 'a1', dataRevision: 'd1', currentReleaseId: 'r1' }, failState = false, failStatus, me, optionReads=0, optionDenied=false;
|
||||||
|
const props = { page: 'overall', user: { id: 'A' }, onUnauthorized: () => false,
|
||||||
|
onPageChange(page) { props.page = page; dirty = true; }, onUserChange(user) { props.user = user; dirty = true; } };
|
||||||
|
const ref = { current: null };
|
||||||
|
const hooks = {
|
||||||
|
useState(initial) { const i = cursor++; if (!values.has(i)) values.set(i, typeof initial === 'function' ? initial() : initial); return [values.get(i), next => { values.set(i, typeof next === 'function' ? next(values.get(i)) : next); dirty = true; }]; },
|
||||||
|
useRef(initial) { const i = cursor++; if (!refs.has(i)) refs.set(i, { current: initial }); return refs.get(i); },
|
||||||
|
useEffect(fn, deps) { const i = cursor++, old = effects.get(i); if (!old || deps.some((value, j) => !Object.is(value, old.deps[j]))) queued.push(() => { old?.cleanup?.(); effects.set(i, { deps, fn, cleanup: fn() }); }); },
|
||||||
|
useImperativeHandle(target, factory) { cursor++; target.current = factory(); },
|
||||||
|
};
|
||||||
|
const api = { async options() { optionReads++; if(optionDenied) { events.get('quality-permission-recheck')?.(); throw Object.assign(Error('denied'),{status:403}); } return {}; }, async sourceColumnCatalog() { return {}; }, async workspaceState() { if (failState) { failState = false; throw Object.assign(Error('temporary-offline'), { status: failStatus }); } return { ...state }; }, async me() { return me ? me.promise : props.user; } };
|
||||||
|
const env = {
|
||||||
|
location: { search: '?page=overall', pathname: '/' },
|
||||||
|
window: { scrollY: 0, scrollTo() {}, matchMedia: () => ({ matches: false }), addEventListener: (name, fn) => events.set(name, fn), removeEventListener: name => events.delete(name) },
|
||||||
|
document: { visibilityState: 'visible', addEventListener: (name, fn) => events.set(name, fn), removeEventListener: name => events.delete(name), querySelector() {} },
|
||||||
|
history: { pushState(_state, _title, url) { env.location.search = url.slice(url.indexOf('?')); } },
|
||||||
|
requestAnimationFrame(fn) { fn(); return 1; }, cancelAnimationFrame() {},
|
||||||
|
forwardRef: component => component, lazy: () => 'Page', Suspense: 'Suspense', Alert: 'Alert', Button: 'Button', Spin: 'Spin',
|
||||||
|
PageCacheContext: { Provider: 'Provider' }, WORKSPACE_INVALIDATED: 'invalidate',
|
||||||
|
configureRequestScope: scope => scopes.push({ ...scope }), resetRequestScope: () => {},
|
||||||
|
createWorkspaceTransition: () => ({ run(callback) { const promise = callback(new AbortController().signal); navigations.push(promise); }, cancel() {} }),
|
||||||
|
waitForWorkspaceContent: async () => {}, flushSync: fn => fn(),
|
||||||
|
};
|
||||||
|
const prelude = 'const {useState,useRef,useEffect,useImperativeHandle}=hooks;const useLayoutEffect=useEffect;';
|
||||||
|
const compiled = ts.transpileModule(prelude + source + '\nreturn CachedWorkspacePages;', { fileName: 'fixture.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText;
|
||||||
|
const component = new Function('React', 'hooks', 'api', 'pageUsesResources','readQueryLocation', ...Object.keys(env), compiled)(React, hooks, api, pageUsesResources,readQueryLocation, ...Object.values(env));
|
||||||
|
const render = () => { let attempts = 0; do { cursor = 0; dirty = false; queued = []; tree = component(props, ref); queued.forEach(fn => fn()); assert.ok(++attempts < 15); } while (dirty); return tree; };
|
||||||
|
const pages = () => { const result = []; function walk(node) { if (!node || typeof node !== 'object') return; if (node.props?.['data-page']) result.push(node.props['data-page']); React.Children.forEach(node.props?.children, walk); } walk(tree); return result; };
|
||||||
|
return { render, pages, props, scopes, ref, async start() { render(); await tick(); render(); }, async settle() { await Promise.all(navigations); await tick(); render(); },
|
||||||
|
getOptionReads:()=>optionReads,denyOptions(){optionDenied=true;},failNextState(status) { failState = true; failStatus = status; }, changeIdentity() { state = { ...state, authRevision: 'b2' }; me = deferred(); return me; },
|
||||||
|
async focus() { events.get('focus')?.(); await tick(); render(); }, cleanup() { effects.forEach(effect => effect.cleanup?.()); } };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a navigation rejected by workspace validation can be retried to the same destination', async () => {
|
||||||
|
const ui = fixture(); await ui.start();
|
||||||
|
ui.failNextState(); ui.ref.current.navigate('department'); await ui.settle();
|
||||||
|
assert.equal(ui.props.page, 'overall');
|
||||||
|
ui.ref.current.navigate('department'); await ui.settle();
|
||||||
|
assert.equal(ui.props.page, 'department'); ui.cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('revoked authorization immediately hides retained pages while the latest identity is pending or failed', async () => {
|
||||||
|
const ui = fixture(); await ui.start(); assert.deepEqual(ui.pages(), ['overall']);
|
||||||
|
const me = ui.changeIdentity(); await ui.focus();
|
||||||
|
assert.deepEqual(ui.pages(), []);
|
||||||
|
me.reject(Error('identity-unavailable')); await tick(); ui.render();
|
||||||
|
assert.deepEqual(ui.pages(), []); ui.cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('foreground validation uses the refreshed identity instead of the first mounted user', async () => {
|
||||||
|
const ui = fixture(); await ui.start(); const me = ui.changeIdentity(); await ui.focus();
|
||||||
|
me.resolve({ id: 'B' }); await tick(); ui.render();
|
||||||
|
assert.equal(ui.props.user.id, 'B');
|
||||||
|
await ui.focus(); assert.equal(ui.scopes.at(-1).userId, 'B'); ui.cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test('workspace 403 hides private retained results and rebuilds after authorization recovery', async () => {
|
||||||
|
const ui = fixture(); await ui.start(); assert.deepEqual(ui.pages(), ['overall']);
|
||||||
|
ui.failNextState(403); await ui.focus(); assert.deepEqual(ui.pages(), []);
|
||||||
|
await ui.focus(); await tick(); ui.render(); assert.deepEqual(ui.pages(), ['overall']); ui.cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a first-load workspace 403 can recover into a populated workspace', async () => {
|
||||||
|
const ui = fixture(); ui.failNextState(403); await ui.start(); assert.deepEqual(ui.pages(), []);
|
||||||
|
await ui.focus(); await tick(); ui.render(); assert.deepEqual(ui.pages(), ['overall']); ui.cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a forbidden options resource does not trigger repeated warm reads during permission rechecks', async () => {
|
||||||
|
const ui=fixture();ui.denyOptions();await ui.start();await tick();ui.render();const count=ui.getOptionReads();
|
||||||
|
await ui.focus();await tick();ui.render();assert.equal(ui.getOptionReads(),count);assert.ok(count<=1);ui.cleanup();
|
||||||
|
});
|
||||||
@@ -1,32 +1,53 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import {readFileSync} from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
import ts from 'typescript';
|
import ts from 'typescript';
|
||||||
|
|
||||||
const source=ts.transpileModule(readFileSync(new URL('../src/useDataWorkflowOperation.ts',import.meta.url),'utf8'),{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext}}).outputText.replace(/^import .*;\n/gm,'').replace(/export /g,'');
|
const source = ts.transpileModule(readFileSync(new URL('../src/useDataWorkflowOperation.ts', import.meta.url), 'utf8'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText.replace(/^import .*;\n/gm, '').replace(/export /g, '');
|
||||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||||
const deferred=()=>{let resolve;const promise=new Promise(done=>{resolve=done;});return{promise,resolve};};
|
const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };
|
||||||
|
|
||||||
test('the actual workflow hook refreshes retained data after completion, rather than while work is pending',async()=>{
|
function operationHook(api) {
|
||||||
const final=deferred(),events=[],callbacks=[],storage=new Map();let calls=0;
|
const events = [], callbacks = [], storage = new Map();
|
||||||
const window={localStorage:storage,setTimeout:fn=>setImmediate(fn),dispatchEvent:event=>events.push(event.type)};
|
const window = { localStorage: storage, dispatchEvent: event => events.push(event) };
|
||||||
const localStorage={getItem:key=>storage.get(key)??null,setItem:(key,value)=>storage.set(key,value),removeItem:key=>storage.delete(key)};
|
const localStorage = { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) };
|
||||||
const api={dataWorkflowOperation:async()=>++calls===1?{operationId:'job',status:'RUNNING'}:final.promise};
|
const hooks = { useState: value => [value, () => {}], useRef: current => ({ current }), useCallback: fn => fn, useEffect: fn => { fn(); } };
|
||||||
const hooks={useState:value=>[value,()=>{}],useRef:current=>({current}),useCallback:fn=>fn,useEffect:fn=>{fn();}};
|
const load = new Function('api', 'window', 'localStorage', 'WORKSPACE_INVALIDATED', 'usePageCache', 'useVisiblePolling', 'hooks', `const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`);
|
||||||
const load=new Function('api','window','localStorage','WORKSPACE_INVALIDATED','hooks',`const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`);
|
const useDataWorkflowOperation = load(api, window, localStorage, 'quality-workspace-invalidated', () => ({ active: true }), () => {}, hooks);
|
||||||
const hook=load(api,window,localStorage,'quality-workspace-invalidated',hooks)('project',value=>callbacks.push(value));
|
const hook = useDataWorkflowOperation('project', value => callbacks.push(value));
|
||||||
await hook.start(async()=>({operationId:'job',status:'QUEUED'}));await tick();await tick();
|
return { hook, events, callbacks, storage };
|
||||||
assert.equal(calls,2);assert.deepEqual(events,[]);assert.equal(storage.size,1);
|
}
|
||||||
final.resolve({operationId:'job',status:'COMPLETED',currentReleaseId:'new-release'});await tick();
|
|
||||||
assert.deepEqual(events,['quality-workspace-invalidated']);assert.equal(callbacks[0].currentReleaseId,'new-release');assert.equal(storage.size,0);
|
test('a completed workflow invalidates retained data exactly once after the server marks it complete', async () => {
|
||||||
|
const final = deferred(); let calls = 0;
|
||||||
|
const { hook, events, callbacks, storage } = operationHook({ dataWorkflowOperation: async () => { calls++; return final.promise; } });
|
||||||
|
await hook.start(async () => ({ operationId: 'job', status: 'QUEUED' }));
|
||||||
|
assert.equal(storage.size, 1, 'the operation id is retained for refresh recovery');
|
||||||
|
hook.resume(); hook.resume();
|
||||||
|
await tick();
|
||||||
|
assert.equal(calls, 1, 'overlapping progress checks are coalesced');
|
||||||
|
assert.deepEqual(events, []);
|
||||||
|
final.resolve({ operationId: 'job', status: 'COMPLETED', currentReleaseId: 'new-release' });
|
||||||
|
await tick(); await tick();
|
||||||
|
assert.equal(events.length, 1);
|
||||||
|
assert.equal(events[0].type, 'quality-workspace-invalidated');
|
||||||
|
assert.deepEqual(events[0].detail.resources, ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration']);
|
||||||
|
assert.equal(callbacks.length, 1);
|
||||||
|
assert.equal(callbacks[0].currentReleaseId, 'new-release');
|
||||||
|
assert.equal(storage.size, 0);
|
||||||
|
hook.resume(); await tick();
|
||||||
|
assert.equal(events.length, 1, 'a terminal result cannot invalidate a second time');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('failed work never refreshes retained data as though a new version had been published',async()=>{
|
test('failed workflows never invalidate published data and keep the operation id available for recovery', async () => {
|
||||||
const events=[],callbacks=[];const api={dataWorkflowOperation:async()=>({operationId:'job',status:'FAILED',errors:[{message:'rejected'}]})};
|
let calls = 0;
|
||||||
const hooks={useState:value=>[value,()=>{}],useRef:current=>({current}),useCallback:fn=>fn,useEffect:fn=>{fn();}};
|
const { hook, events, callbacks, storage } = operationHook({ dataWorkflowOperation: async () => { calls++; return { operationId: 'job', status: 'FAILED', errors: [{ message: 'rejected' }] }; } });
|
||||||
const localStorage={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};
|
await hook.start(async () => ({ operationId: 'job', status: 'QUEUED' }));
|
||||||
const window={setTimeout:fn=>setImmediate(fn),dispatchEvent:event=>events.push(event.type)};
|
hook.resume(); await tick(); await tick();
|
||||||
const load=new Function('api','window','localStorage','WORKSPACE_INVALIDATED','hooks',`const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`);
|
assert.deepEqual(events, []);
|
||||||
const hook=load(api,window,localStorage,'quality-workspace-invalidated',hooks)('project',value=>callbacks.push(value));
|
assert.deepEqual(callbacks, []);
|
||||||
await hook.start(async()=>({operationId:'job',status:'QUEUED'}));await tick();assert.deepEqual(events,[]);assert.deepEqual(callbacks,[]);
|
assert.equal(storage.size, 1);
|
||||||
|
hook.resume(); await tick();
|
||||||
|
assert.equal(calls, 1, 'a terminal failure is not polled repeatedly');
|
||||||
|
assert.deepEqual(events, []);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user