diff --git a/DESIGN.md b/DESIGN.md index 3a2eafc..bf3049e 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -115,3 +115,10 @@ - 各级返回按钮统一为带左箭头的“返回上一级”,沿用原有父级路径,使用主题色描边与浅底;Excel 导出使用实色主按钮,两者统一加粗。 - 趋势数据表取消底部分页统计与月份汇总链接,直接展示已返回的期间;保留月份行的筛选操作。各查询页删除“点击期间筛选”类提示。 - 本地实测三级返回、月份行筛选及六主题按钮效果;主汇总表分页和 Excel 导出行为保持原有方式。 + +## 2026-11-02:全系统统一加载(用户批准方案) + +- 维持现有布局、主题及 280/520 毫秒过渡;150 毫秒后显示区域加载提示。首次失败、更新失败、成功空结果分别呈现,更新时保留已生效范围的结果。 +- 更新中的旧范围结果不能钻取、查看明细或导出;区域独立重试。任务使用真实阶段,写入即时忙碌并防重复,不显示虚构百分比或新增常驻说明。 +- 返回页面保留筛选、页码、滚动位置及表格高度;隐藏页面和未选管理页签不主动刷新。业务分页、全范围搜索排序和导出不变。 +- 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。 diff --git a/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java b/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java index f386fc6..b914a4b 100644 --- a/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java +++ b/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java @@ -5,6 +5,7 @@ import cn.yunsheng.quality.identity.AppUserPrincipal; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; 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()); String auth = digest(List.of(actor.getId(), actor.getRoleCodes().stream().sorted().toList(), 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( - jdbc.queryForList("SELECT * FROM current_release ORDER BY dataset_id"), + currentRelease, 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 * FROM query_filter_field ORDER BY field_key"), jdbc.queryForList("SELECT id,row_version FROM service_identity ORDER BY id"), jdbc.queryForList("SELECT * FROM service_binding ORDER BY service_type"))); - return Map.of("authRevision", auth, "dataRevision", data); + Map result = new LinkedHashMap<>(); + result.put("authRevision", auth); + result.put("dataRevision", data); + result.put("currentReleaseId", currentReleaseId); + return result; } private static String digest(Object value) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.toString().getBytes(StandardCharsets.UTF_8))); } diff --git a/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsController.java b/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsController.java index f923410..89b795e 100644 --- a/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsController.java +++ b/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsController.java @@ -76,6 +76,37 @@ public class MetricsController { 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. */ public MetricsService.MetricSnapshot calculate(Integer year, Integer month, String quarter, String department, String group, String product, String productSearch, diff --git a/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsResponseAccess.java b/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsResponseAccess.java index 1ab1cd0..754ad7f 100644 --- a/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsResponseAccess.java +++ b/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsResponseAccess.java @@ -5,6 +5,7 @@ import cn.yunsheng.quality.identity.AppUserPrincipal; import cn.yunsheng.quality.metrics.MetricsService.DefectRow; import cn.yunsheng.quality.metrics.MetricsService.MetricRow; 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.TrendMetricRow; 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()); } + /** 趋势查询沿用明细授权和指标字段可见性边界。 */ + 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 allowed = governance.allowedFields(actor); + List 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 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) { 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()); diff --git a/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsService.java b/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsService.java index 9b18c4f..afc483f 100644 --- a/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsService.java +++ b/backend/src/main/java/cn/yunsheng/quality/metrics/MetricsService.java @@ -71,6 +71,113 @@ public class MetricsService { 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 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 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 coverage = queryCoverage(release.id(), query, actor, hasUnrolledBuilds); + Map 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 queryTrendAggregates(String releaseId, MetricsQuery query, + AppUserPrincipal actor, boolean hasUnrolledBuilds) { + Map 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 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 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. */ public MetricSnapshot calculateCandidateForGovernance(MetricsQuery query, AppUserPrincipal actor) { return withGovernanceSnapshot(() -> calculateForGovernance(query, actor, true)); @@ -393,8 +500,12 @@ public class MetricsService { } private List trendRows(AggregateSet aggregates, String granularity) { + return trendRows(aggregates.periods(), granularity); + } + + private List trendRows(Map periods, String granularity) { List trend = new ArrayList<>(); - aggregates.periods().forEach((period, stats) -> { + periods.forEach((period, stats) -> { String label = switch (granularity) { case "quarter" -> period.replace("-Q", "年第") + "季度"; case "year" -> period + "年"; @@ -688,6 +799,12 @@ public class MetricsService { Map.of("black", empty.black().defects(), "bright", empty.bright().defects()), coverage); } + private MetricTrendSnapshot emptyTrendSnapshot(MetricsQuery query) { + Map 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) { 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, "月份无效"); @@ -831,6 +948,8 @@ public class MetricsService { public record MetricSnapshot(Map release, Map context, MetricRow summary, List rows, List trend, Map defects, Map coverage) {} + public record MetricTrendSnapshot(Map release, Map context, + List trend, Map coverage) {} public record ComparisonSnapshots(MetricSnapshot current, MetricSnapshot comparison) {} private record Fact(String stage, String month, String department, String group, String projectGroup, String product, diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index a6b6207..b1a578d 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -2,6 +2,13 @@ server: address: 127.0.0.1 port: ${PORT:5281} shutdown: graceful + # 只压缩较大的 JSON 响应;SSE、表格和压缩包不在类型白名单中。 + compression: + enabled: true + min-response-size: 1KB + mime-types: + - application/json + - application/problem+json servlet: session: cookie: diff --git a/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java b/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java index 54f4908..ad4e53c 100644 --- a/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java +++ b/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java @@ -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"))); var first = controller.state(actor(List.of("A","B"))); 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")); verify(access,times(2)).requireUserActivePolicy(any()); } @@ -41,4 +43,17 @@ class WorkspaceStateControllerTest { assertThrows(IllegalStateException.class,()->controller.state(actor)); 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()); + } } diff --git a/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsResponseAccessTest.java b/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsResponseAccessTest.java index 2412aae..4951fa7 100644 --- a/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsResponseAccessTest.java +++ b/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsResponseAccessTest.java @@ -66,4 +66,22 @@ class MetricsResponseAccessTest { when(governance.allowedFields(actor)).thenReturn(Set.of("*")); 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"); + } } diff --git a/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsTrendControllerTest.java b/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsTrendControllerTest.java new file mode 100644 index 0000000..4ff9b06 --- /dev/null +++ b/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsTrendControllerTest.java @@ -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 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")); + } +} diff --git a/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsTrendServiceTest.java b/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsTrendServiceTest.java new file mode 100644 index 0000000..a47e813 --- /dev/null +++ b/backend/src/test/java/cn/yunsheng/quality/metrics/MetricsTrendServiceTest.java @@ -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 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 sql = capturedSql(jdbc); + List 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 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 capturedSql(JdbcTemplate jdbc) { + var details = mockingDetails(jdbc).getInvocations(); + List 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); } + } +} diff --git a/deploy/aliyun/quality-center.conf b/deploy/aliyun/quality-center.conf index a43bbac..275447c 100644 --- a/deploy/aliyun/quality-center.conf +++ b/deploy/aliyun/quality-center.conf @@ -61,7 +61,12 @@ server { proxy_cookie_flags XSRF-TOKEN secure samesite=strict; } + # 静态文本压缩只在站点根目录启用;API 的 SSE 代理缓冲仍保持关闭。 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; } } diff --git a/docs/全系统统一加载实现与验收_20261102.md b/docs/全系统统一加载实现与验收_20261102.md new file mode 100644 index 0000000..10cc639 --- /dev/null +++ b/docs/全系统统一加载实现与验收_20261102.md @@ -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 推断后端。保留旧哈希资源供已打开浏览器继续加载。无需数据库结构迁移,不恢复或重写业务数据。 diff --git a/web/src/AnalysisApiSettings.tsx b/web/src/AnalysisApiSettings.tsx index 1cc9fd3..5a50530 100644 --- a/web/src/AnalysisApiSettings.tsx +++ b/web/src/AnalysisApiSettings.tsx @@ -4,6 +4,7 @@ import { Alert, App, Button, Form, Input, Modal, Select, Spin, Switch, Tag } fro import { SettingOutlined } from '@ant-design/icons'; import { api } from './api'; 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 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]); const [open, setOpen] = useState(false); const [loading, setLoading] = useState(false); + const showLoading = useDelayedIndicator(loading, 150); const [saving, setSaving] = useState(false); const [testing, setTesting] = useState(false); const [settings, setSettings] = useState(); @@ -26,10 +28,11 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error const selectedProfile = settings?.profiles.find(profile => profile.id === profileId); const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>(); 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 load = async () => { const current = ++sequence.current; - setOpen(true); setLoading(true); setSettings(undefined); setProfileId(undefined); setNotice(undefined); form.resetFields(); + setOpen(true); setLoading(true); setNotice(undefined); try { const value = await api.analysisSettings(); if (sequence.current !== current) return; @@ -39,9 +42,10 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error } finally { if (sequence.current === current) setLoading(false); } }; const submit = async (test: boolean) => { - if (!settings) return; + if (!settings || submitLock.current) return; let values: AnalysisModelSettingsInput; try { values = await form.validateFields(); } catch { return; } + submitLock.current = true; const current = sequence.current; setNotice(undefined); test ? setTesting(true) : setSaving(true); try { @@ -57,7 +61,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error } } catch (error) { 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 <> @@ -66,7 +70,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error }> - {loading ?
: <> + {showLoading && !settings ?
: <> {settings &&
选择配置 当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}
diff --git a/web/src/AnalysisReportExport.tsx b/web/src/AnalysisReportExport.tsx index 2fd3bc0..91f8f60 100644 --- a/web/src/AnalysisReportExport.tsx +++ b/web/src/AnalysisReportExport.tsx @@ -18,6 +18,7 @@ import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './ana import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals'; import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel'; import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList'; +import { useDelayedIndicator } from './useDelayedBusy'; type Row = Record; 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 [exporting, setExporting] = useState(false); + const showExporting = useDelayedIndicator(exporting, 150); const [progress, setProgress] = useState(''); const [error, setError] = useState(''); const [stamp, setStamp] = useState(''); @@ -239,6 +241,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false } const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown }); currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown }; const visualReport = useReportVisualImages(turn, open); + const showVisualLoading = useDelayedIndicator(visualReport.loading, 150); const safeHtml = useMemo(() => { if (parseServerReadingSummary(reportTurn)) return ''; if (!reportHtml?.trim()) return ''; @@ -358,10 +361,10 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false } : } {prepared ? - : } + : } }> - {visualReport.loading &&

{visualReport.progress || '正在准备报告图表…'}

} - {progress &&

{progress}

} + {showVisualLoading &&

{visualReport.progress || '正在准备报告图表…'}

} + {progress && (!exporting || showExporting) &&

{progress}

} {error && setError('')} />} {visualReport.failed && } {visualReport.authorizationError && visualReport.authorizationError !== error && } diff --git a/web/src/AnalysisReportsPanel.tsx b/web/src/AnalysisReportsPanel.tsx index afbe209..6ccf4a7 100644 --- a/web/src/AnalysisReportsPanel.tsx +++ b/web/src/AnalysisReportsPanel.tsx @@ -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 { api } from './api'; +import { usePageCache, useMaintenanceRefresh } from './pageCache'; +import { useDelayedBusy } from './useDelayedBusy'; const labels: Record = { MONTH: '月报', QUARTER: '季报', YEAR: '年报' }; export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }: { @@ -10,15 +12,26 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen } const [plans, setPlans] = useState[]>([]); const [error, setError] = useState(''); 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 load = async () => { - try { - const [history, savedPlans] = await Promise.all([api.analysisReports(), api.analysisReportPlans()]); - setReports(history.items || []); setPlans(savedPlans.items || []); - } catch (value) { setError(value instanceof Error ? value.message : '报告读取失败'); } - }; - useEffect(() => { void load(); }, []); + const load = useCallback(() => read.run(async () => { + const [history, savedPlans] = await Promise.allSettled([api.analysisReports(), api.analysisReportPlans()]); + const errors: string[] = []; + if (history.status === 'fulfilled') { setReports(history.value.items || []); setReportsLoaded(true); } + else errors.push(`报告列表:${history.reason instanceof Error ? history.reason.message : '读取失败'}`); + if (savedPlans.status === 'fulfilled') { setPlans(savedPlans.value.items || []); setPlansLoaded(true); } + 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 () => { + if (actionInFlight.current) return; actionInFlight.current = true; setBusy(true); setError(''); try { 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); else setError('报告已登记,正在准备分析任务,请稍后刷新列表。'); } catch (value) { setError(value instanceof Error ? value.message : '报告生成失败'); } - finally { setBusy(false); } + finally { actionInFlight.current = false; setBusy(false); } }; const toggle = async (type: string, enabled: boolean) => { + if (actionInFlight.current) return; actionInFlight.current = true; setBusy(true); setError(''); try { 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); await load(); } catch (value) { setError(value instanceof Error ? value.message : '报告计划保存失败'); } - finally { setBusy(false); } + finally { actionInFlight.current = false; setBusy(false); } }; const saveDay = async () => { + if (actionInFlight.current) return; actionInFlight.current = true; setBusy(true); setError(''); try { await Promise.all(plans.map(plan => api.updateAnalysisReportPlan(String(plan.id), { runDay, runHour: 9 }))); await load(); } catch (value) { setError(value instanceof Error ? value.message : '执行日期保存失败'); } - finally { setBusy(false); } + finally { actionInFlight.current = false; setBusy(false); } }; - return
月报、季报与年报 + return
setExpanded(event.currentTarget.open)}>月报、季报与年报

报告使用统一指标与同一分析任务,包含期间比较、趋势和异常追查。自动计划在本机服务运行时执行。

- {error && } + {error && void load()}>重试 : undefined} />} + {read.busy && !reportsLoaded && !plansLoaded &&
正在读取报告与自动计划…
}
{periodKey} · {labels[periodType]} · 总体范围
-
自动生成上一完整周期:每个适用周期首月 ({ 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 ; })} -
- {reports.length > 0 &&
    {reports.slice(0, 8).map(report =>
  • {String(report.periodKey)} {labels[String(report.periodType)] || ''} {String(report.status)}
  • )}
} +
} + {reportsLoaded && reports.length > 0 &&
    {reports.slice(0, 8).map(report =>
  • {String(report.periodKey)} {labels[String(report.periodType)] || ''} {String(report.status)}
  • )}
} + {reportsLoaded && !reports.length &&

当前没有已生成的报告。

} ; } diff --git a/web/src/AnalysisVisuals.tsx b/web/src/AnalysisVisuals.tsx index 3e54138..aabbdef 100644 --- a/web/src/AnalysisVisuals.tsx +++ b/web/src/AnalysisVisuals.tsx @@ -16,6 +16,7 @@ import { visualUnitLabel, } from './analysisVisualsModel'; import type { AnalysisVisual } from './analysisVisualsModel'; +import { useDelayedIndicator } from './useDelayedBusy'; import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation'; import './analysis-visuals.css'; @@ -126,9 +127,11 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna const [nearViewport, setNearViewport] = useState(false); const [chartReady, setChartReady] = useState(false); const [chartLoading, setChartLoading] = useState(false); + const showChartLoading = useDelayedIndicator(chartLoading, 150); const [chartError, setChartError] = useState(''); const [dataOpen, setDataOpen] = useState(false); const [exporting, setExporting] = useState(false); + const showExporting = useDelayedIndicator(exporting, 150); const [exportError, setExportError] = useState(''); const [themeRevision, setThemeRevision] = useState(0); const [renderAttempt, setRenderAttempt] = useState(0); @@ -312,9 +315,9 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna , label: exporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }} + menu={{ items: [{ key: 'png', icon: , label: showExporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }} > -
@@ -337,7 +340,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna 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} /> {!nearViewport &&
图表将在进入视口时加载
} - {nearViewport && chartLoading &&
正在加载图表…
} + {nearViewport && showChartLoading &&
正在加载图表…
} {chartError &&
{chartError} diff --git a/web/src/CachedWorkspacePages.tsx b/web/src/CachedWorkspacePages.tsx index dfce0d4..96712e8 100644 --- a/web/src/CachedWorkspacePages.tsx +++ b/web/src/CachedWorkspacePages.tsx @@ -1,19 +1,29 @@ +import { readQueryLocation } from './queryLoadingScope'; import { flushSync } from 'react-dom'; import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition'; import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react'; 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 { PageKey } from './QualityWorkspace'; import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache'; -const QueryPage = lazy(() => import('./QueryPage')); -const StageProductPage = lazy(() => import('./StageProductPage')); -const ManagementPages = lazy(() => import('./ManagementPages')); +const loadQueryPage = () => import('./QueryPage'); +const loadStageProductPage = () => import('./StageProductPage'); +const loadManagementPages = () => import('./ManagementPages'); +const QueryPage = lazy(loadQueryPage); +const StageProductPage = lazy(loadStageProductPage); +const ManagementPages = lazy(loadManagementPages); + +export function preloadWorkspacePage(page: PageKey): Promise { + return page === 'blackProduct' || page === 'brightProduct' ? loadStageProductPage() + : QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages(); +} const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct']; const retained = (_page: PageKey) => true; 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 }; function encode(value: unknown) { const bytes = new TextEncoder().encode(JSON.stringify(value)); @@ -23,10 +33,12 @@ function encode(value: unknown) { export const CachedWorkspacePages = forwardRef void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean; }>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) { + const userRef = useRef(user); + userRef.current = user; const entries = useRef(new Map([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]])); const requested = useRef(page); 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 | null>(null); const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0); const [ready, setReady] = useState(false), [error, setError] = useState(''); @@ -38,28 +50,47 @@ export const CachedWorkspacePages = forwardRef window.matchMedia('(prefers-reduced-motion: reduce)').matches, busy => { if (alive.current) setNavigationBusy(busy); }, ); - const validate = () => { + const validate = (warmVisibleOptions = false) => { if (validation.current) return validation.current; const epoch = generation.current; const request = (async () => { try { const state = await api.workspaceState(); 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(); if (!alive.current || generation.current !== epoch) return false; // 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。 transitions.current?.cancel(); requested.current = current.current; + userRef.current = latest; + configureRequestScope({ userId: latest.id, ...state }); onUserChange(latest); entries.current.clear(); entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 }); render(value => value + 1); } if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1); revisions.current = state; + render(value => value + 1); 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); return true; } 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 : '页面状态校验失败,请重试'); return false; } @@ -79,6 +110,11 @@ export const CachedWorkspacePages = forwardRef { + // 先核实权限与版本,再让已保留页面重新订阅,避免旧版本内容先闪出。 + 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; // 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。 flushSync(() => { @@ -86,8 +122,8 @@ export const CachedWorkspacePages = forwardRef value + 1); }); window.scrollTo(0, entry.scroll); - void validate(); 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) => { @@ -105,10 +141,22 @@ export const CachedWorkspacePages = forwardRef { alive.current = true; - void validate(); - const invalidate = () => setRefreshKey(value => value + 1); + configureRequestScope({ userId: userRef.current.id, authRevision: null, dataRevision: null, currentReleaseId: null }); + 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); - 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; useLayoutEffect(() => { @@ -121,7 +169,7 @@ export const CachedWorkspacePages = forwardRef{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => { const active = name === page; return }> {name === 'blackProduct' || name === 'brightProduct' ? : QUERY_PAGES.includes(name) ? : } diff --git a/web/src/ExtraQueryFilters.tsx b/web/src/ExtraQueryFilters.tsx index 1854a75..2da3525 100644 --- a/web/src/ExtraQueryFilters.tsx +++ b/web/src/ExtraQueryFilters.tsx @@ -1,3 +1,5 @@ +import { usePageCache } from './pageCache'; +import { useDelayedIndicator } from './useDelayedBusy'; import { useEffect, useRef, useState } from 'react'; import { Alert, Button, Select, Spin } from 'antd'; import { DownOutlined, UpOutlined } from '@ant-design/icons'; @@ -6,6 +8,7 @@ import type { FilterField } from './types'; import { readableSelectPopup } from './readableSelectPopup'; 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 [choices, setChoices] = useState([]); const [loading, setLoading] = useState(true); @@ -13,23 +16,25 @@ function FieldSelect({ field, value, onChange, onUnauthorized }: { field: Filter const [error, setError] = useState(''); const [revision, setRevision] = useState(0); const generation = useRef(0); + const showLoading = useDelayedIndicator(loading); useEffect(() => { - const current = ++generation.current; + if (!active) return; + const current = ++generation.current, controller = new AbortController(); setLoading(true); setChoices([]); setError(''); 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; setChoices(result.values); setHasMore(result.hasMore); }).catch(e => { if (generation.current === current && !onUnauthorized(e)) setError(e.message || '选项加载失败'); }) .finally(() => { if (generation.current === current) setLoading(false); }); }, search ? 250 : 0); - return () => { window.clearTimeout(timer); generation.current++; }; - }, [field.key, search, revision, onUnauthorized]); + return () => { window.clearTimeout(timer); controller.abort(); generation.current++; }; + }, [active, field.key, search, revision, onUnauthorized]); return } {fields.map(field => { const next = { ...value }; if (values.length) next[field.key] = values; else delete next[field.key]; onChange(next); }} />)} diff --git a/web/src/GovernanceCompletion.tsx b/web/src/GovernanceCompletion.tsx index c7309d9..5bf0328 100644 --- a/web/src/GovernanceCompletion.tsx +++ b/web/src/GovernanceCompletion.tsx @@ -1,7 +1,7 @@ import { ManagementSections } from './ManagementSections'; import { configurationDateTime } from './configurationName'; import { alertObject, alertsForStatus, monitorLabel } from './taskMonitorModel'; -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { Alert, App, Button, Checkbox, Drawer, Empty, Form, Input, InputNumber, Modal, Select, Spin, Switch, Tabs, Tag } from 'antd'; import type { ColumnsType } from 'antd/es/table'; import { QualityTable as Table } from './QualityTable'; @@ -11,6 +11,10 @@ import type { AuthUser, SourceItem } from './types'; import { readableSelectPopup } from './readableSelectPopup'; import { isInternalDataField } from './publicDataDisplay'; import './completion.css'; +import { usePageCache, useMaintenanceRefresh } from './pageCache'; +import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy'; +import { useVisiblePolling } from './useVisiblePolling'; +import { governanceResourcesForTab, markGovernanceResourcesFresh, markGovernanceResourcesStale, type GovernanceResource } from './governanceTabResources'; type Row = Record; const TABLE_PAGE_SIZE = 15; @@ -66,47 +70,45 @@ function analysisDeepLink(sessionId: string, turnId: string): string { function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const canRun = user.roles.some(role => ['QUALITY_VIEWER', 'BUSINESS_ANALYST'].includes(role)); const [strategies, setStrategies] = useState([]); const [releaseId, setReleaseId] = useState(''); const [runs, setRuns] = useState([]); - const [loading, setLoading] = useState(false); + const [strategiesLoaded, setStrategiesLoaded] = useState(false); + const [runsLoaded, setRunsLoaded] = useState(false); + const strategyRead = useDelayedBusy(); const runRead = useDelayedBusy(); + const loading = strategyRead.busy || runRead.busy; const [running, setRunning] = useState(false); const [saving, setSaving] = useState(false); + const actionLock = useRef(false); const [error, setError] = useState(''); const [selectedRun, setSelectedRun] = useState(null); const [editing, setEditing] = useState(null); const [form] = Form.useForm(); - const load = async () => { - setLoading(true); setError(''); - const results = await Promise.allSettled([ - canManage ? api.inspectionStrategies() : Promise.resolve({ items: [] }), - api.releases(), - ]); - if (results[0].status === 'fulfilled') setStrategies(collectionItems(results[0].value)); - else if (!onUnauthorized(results[0].reason)) setError(results[0].reason instanceof Error ? results[0].reason.message : '巡检策略读取失败'); - if (results[1].status === 'fulfilled') { - const current = String(results[1].value.currentReleaseId || ''); - setReleaseId(current); - } else if (!onUnauthorized(results[1].reason)) { - const failure = results[1].reason; - setError(value => [value, failure instanceof Error ? failure.message : '当前数据读取失败'].filter(Boolean).join(';')); - } - setLoading(false); - }; - const loadRuns = async (selectedRelease = releaseId) => { + const load = useCallback(() => strategyRead.run(async () => { + const results = await Promise.allSettled([canManage ? api.inspectionStrategies() : Promise.resolve({ items: [] }), api.releases()]); + const failures: string[] = []; + if (results[0].status === 'fulfilled') { setStrategies(collectionItems(results[0].value)); setStrategiesLoaded(true); } + else if (!onUnauthorized(results[0].reason)) failures.push(results[0].reason instanceof Error ? results[0].reason.message : '巡检策略读取失败'); + if (results[1].status === 'fulfilled') setReleaseId(String(results[1].value.currentReleaseId || '')); + else if (!onUnauthorized(results[1].reason)) failures.push(results[1].reason instanceof Error ? results[1].reason.message : '当前数据读取失败'); + setError(failures.join(';')); + }), [canManage, onUnauthorized, strategyRead.run]); + const loadRuns = useCallback(async (selectedRelease = releaseId) => { if (!canRun || !selectedRelease) { setRuns([]); return; } - setRuns([]); - try { const result = await api.inspectionRuns(selectedRelease); setRuns(collectionItems(result)); } + await runRead.run(async () => { try { const result = await api.inspectionRuns(selectedRelease); setRuns(collectionItems(result)); setRunsLoaded(true); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检运行记录读取失败'); } - }; - useEffect(() => { void load(); }, []); - useEffect(() => { if (releaseId) void loadRuns(releaseId); }, [releaseId]); + }); + }, [canRun, onUnauthorized, releaseId, runRead.run]); + useEffect(() => { if (active && !strategiesLoaded) void load(); }, [active, strategiesLoaded, load]); + useEffect(() => { if (active && releaseId && !runsLoaded) void loadRuns(releaseId); }, [active, releaseId, runsLoaded, loadRuns]); + useMaintenanceRefresh(() => { void load(); if (releaseId) void loadRuns(releaseId); }); const openEditor = async (row?: Row) => { - if (!canManage) return; + if (!canManage || actionLock.current) return; actionLock.current = true; setSaving(true); try { const source = row?.id ? await api.inspectionStrategy(String(row.id)) : {}; @@ -115,9 +117,10 @@ function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onU const config = { ...INSPECTION_DEFAULTS, ...obj(strategy.config || row?.config) }; form.setFieldsValue({ name: String(strategy.name || row?.name || ''), active: strategy.active === true || row?.active === true, ...config }); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '巡检策略详情读取失败'); } - finally { setSaving(false); } + finally { actionLock.current = false; setSaving(false); } }; const save = async () => { + if (actionLock.current) return; actionLock.current = true; try { const value = await form.validateFields(); const config = Object.fromEntries(Object.keys(INSPECTION_DEFAULTS).map(key => [key, value[key]])); @@ -128,10 +131,10 @@ function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onU } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '巡检策略已被更新,请重新读取。' : value instanceof Error ? value.message : '巡检策略保存失败'); - } finally { setSaving(false); } + } finally { actionLock.current = false; setSaving(false); } }; const run = async () => { - if (!canRun || !releaseId) return; + if (!canRun || !releaseId || actionLock.current) return; actionLock.current = true; setRunning(true); setError(''); try { const result = await api.runInspection(releaseId); @@ -139,7 +142,7 @@ function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onU if (result.resultAvailable === false) message.warning('巡检已执行;当前授权不包含完整结果字段。'); else message.success('巡检已执行,运行记录已刷新。'); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检执行失败'); } - finally { setRunning(false); } + finally { actionLock.current = false; setRunning(false); } }; const strategyColumns: ColumnsType = [ { title: '策略名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 220 }, @@ -209,11 +212,11 @@ function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onU return
质量巡检策略与运行记录策略阈值由服务端执行;运行结果受当前用户数据权限约束
{canManage && }
{!canManage && } - {error && { void load(); void loadRuns(); }} />} - {loading ?
读取巡检策略…
: canManage ? strategies.length ? String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : : null} + {error && { void load(); if (releaseId) void loadRuns(releaseId); }} />} + {loading && !strategiesLoaded ?
读取巡检策略…
: strategiesLoaded && canManage ? strategies.length ?
String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : : null}
{canRun && }
{!canRun && } - {canRun && (runs.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1120 }} /> : )} + {canRun && (runsLoaded ? runs.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1120 }} /> : : runRead.busy ?
读取巡检运行记录…
: null)} { setEditing(null); form.resetFields(); }} onOk={() => void save()} width={Math.min(820, window.innerWidth - 24)}>

巡检规则

{booleanFields.map(([key, label]) => )}{metricFields.map(field => )}

阈值范围由服务端校验;保存后对后续巡检生效。

@@ -237,14 +240,28 @@ function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onU export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [protocols, setProtocols] = useState([]); const [coverage, setCoverage] = useState(null); const [sourceChanges, setSourceChanges] = useState([]); const [sourceItems, setSourceItems] = useState([]); const [documents, setDocuments] = useState([]); const [revisions, setRevisions] = useState([]); - const [loading, setLoading] = useState(false); + const read = useDelayedBusy(); + const loading = read.busy; + const [loaded, setLoaded] = useState>({}); + const loadedRef = useRef(loaded); loadedRef.current = loaded; + const [needsRefresh, setNeedsRefresh] = useState>({}); + const needsRefreshRef = useRef(needsRefresh); needsRefreshRef.current = needsRefresh; const [errors, setErrors] = useState>({}); + const [pending, setPending] = useState>({}); + const activeRef = useRef(active); activeRef.current = active; + const releaseRef = useRef(currentReleaseId); releaseRef.current = currentReleaseId; + const unauthorizedRef = useRef(onUnauthorized); unauthorizedRef.current = onUnauthorized; + const coverageLoadedRelease = useRef(undefined); + const requests = useRef(new Map>()); + const queuedRefreshes = useRef(new Map>()); + const pendingRequestKeys = useRef(new Set()); const [protocolOpen, setProtocolOpen] = useState(false); const [changeOpen, setChangeOpen] = useState(false); const [reviewItem, setReviewItem] = useState(null); @@ -252,11 +269,13 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized } const [evidenceRevision, setEvidenceRevision] = useState(''); const [evidence, setEvidence] = useState(null); const [actionBusy, setActionBusy] = useState(''); + const actionLock = useRef(false); const [protocolForm] = Form.useForm(); const [changeForm] = Form.useForm(); const [reviewForm] = Form.useForm<{ reason: string }>(); const [resolveForm] = Form.useForm(); const [tab, setTab] = useState('coverage'); + const tabRef = useRef(tab); tabRef.current = tab; const canMaintain = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role)); const canReview = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_PUBLISHER'].includes(role)); const canDownload = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER', 'BUSINESS_ANALYST', 'QUALITY_VIEWER', 'AUDIT_VIEWER'].includes(role)); @@ -264,22 +283,94 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized } const changeType = Form.useWatch('type', changeForm); const resolveDecision = Form.useWatch('decision', resolveForm); - const load = async () => { - setLoading(true); - const failures: Record = {}; - const results = await Promise.allSettled([ - api.governanceProtocols(), api.governanceCoverage(currentReleaseId || undefined), api.sourceChanges(), api.sources(), api.governanceSourceDocuments(), - ]); - if (results[0].status === 'fulfilled') setProtocols(collectionItems(results[0].value)); else { if (!onUnauthorized(results[0].reason)) failures.protocols = results[0].reason instanceof Error ? results[0].reason.message : '协议读取失败'; } - if (results[1].status === 'fulfilled') setCoverage(results[1].value); else { if (!onUnauthorized(results[1].reason)) failures.coverage = results[1].reason instanceof Error ? results[1].reason.message : '到齐矩阵读取失败'; } - if (results[2].status === 'fulfilled') setSourceChanges(collectionItems(results[2].value)); else { if (!onUnauthorized(results[2].reason)) failures.changes = results[2].reason instanceof Error ? results[2].reason.message : '来源变更清单读取失败'; } - if (results[3].status === 'fulfilled') setSourceItems(collectionItems(results[3].value)); else { if (!onUnauthorized(results[3].reason)) failures.candidates = results[3].reason instanceof Error ? results[3].reason.message : '候选文件读取失败'; } - if (results[4].status === 'fulfilled') { setDocuments(collectionItems(results[4].value)); setRevisions(rows(results[4].value.revisions)); } else { if (!onUnauthorized(results[4].reason)) failures.documents = results[4].reason instanceof Error ? results[4].reason.message : '来源记录读取失败'; } - setErrors(failures); setLoading(false); - }; - useEffect(() => { void load(); }, [currentReleaseId]); + const loadResource = useCallback((resource: GovernanceResource, force = false): Promise => { + if (!activeRef.current) return Promise.resolve(); + if (!force && loadedRef.current[resource]) return Promise.resolve(); + const releaseId = resource === 'coverage' ? releaseRef.current : null; + const requestKey = `${resource}:${releaseId || ''}`; + const existing = requests.current.get(requestKey); + if (existing) { + if (!force) return existing; + const queued = queuedRefreshes.current.get(requestKey); + if (queued) return queued; + const refresh = existing.then(() => { + queuedRefreshes.current.delete(requestKey); + return loadResource(resource, true); + }); + queuedRefreshes.current.set(requestKey, refresh); + return refresh; + } + pendingRequestKeys.current.add(requestKey); + setPending(value => ({ ...value, [resource]: true })); + const work = read.run(async () => { + try { + if (resource === 'protocols') { + const result = await api.governanceProtocols(); + setProtocols(collectionItems(result)); + } else if (resource === 'coverage') { + const result = await api.governanceCoverage(releaseId || undefined); + if (releaseRef.current !== releaseId) return; + setCoverage(result); + coverageLoadedRelease.current = releaseId; + } else if (resource === 'changes') { + const result = await api.sourceChanges(); + setSourceChanges(collectionItems(result)); + } else if (resource === 'candidates') { + const result = await api.sources(); + setSourceItems(collectionItems(result)); + } else { + const result = await api.governanceSourceDocuments(); + setDocuments(collectionItems(result)); setRevisions(rows(result.revisions)); + } + setLoaded(value => ({ ...value, [resource]: true })); + setNeedsRefresh(value => markGovernanceResourcesFresh(value, [resource])); + setErrors(value => { const next = { ...value }; delete next[resource]; return next; }); + } catch (error) { + if (resource === 'coverage' && releaseRef.current !== releaseId) return; + if (unauthorizedRef.current(error)) return; + const fallback: Record = { protocols: '协议读取失败', coverage: '到齐矩阵读取失败', changes: '来源变更清单读取失败', candidates: '候选文件读取失败', documents: '来源记录读取失败' }; + setErrors(value => ({ ...value, [resource]: error instanceof Error ? error.message : fallback[resource] })); + } finally { + pendingRequestKeys.current.delete(requestKey); + const remains = [...pendingRequestKeys.current].some(key => key.startsWith(`${resource}:`)); + setPending(value => ({ ...value, [resource]: remains })); + } + }); + let promise: Promise; + promise = work.finally(() => { if (requests.current.get(requestKey) === promise) requests.current.delete(requestKey); }); + requests.current.set(requestKey, promise); + return promise; + }, [read.run]); + const loadCurrentTab = useCallback((force = false) => { + return Promise.all(governanceResourcesForTab(tab).map(resource => loadResource(resource, force || needsRefreshRef.current[resource]))).then(() => undefined); + }, [loadResource, tab]); + const refreshAffectedCurrent = useCallback((resources: GovernanceResource[]) => { + const visible = new Set(governanceResourcesForTab(tabRef.current)); + setNeedsRefresh(value => markGovernanceResourcesStale(value, resources)); + return Promise.all(resources.filter(resource => visible.has(resource)).map(resource => loadResource(resource, true))).then(() => undefined); + }, [loadResource]); + const markAffectedResources = useCallback((resources: GovernanceResource[]) => { + setNeedsRefresh(value => markGovernanceResourcesStale(value, resources)); + }, []); + useEffect(() => { + if (!active) return; + if (tab === 'coverage') void loadResource('coverage', needsRefreshRef.current.coverage || loadedRef.current.coverage && coverageLoadedRelease.current !== currentReleaseId); + else void loadCurrentTab(); + }, [active, currentReleaseId, loadCurrentTab, loadResource, tab]); + useEffect(() => { if (active && changeOpen) { void loadResource('documents', true); if (changeType === 'REVISION') void loadResource('candidates', true); } }, [active, changeOpen, changeType, loadResource]); + useEffect(() => { if (active && resolveItem) void loadResource('protocols', true); }, [active, loadResource, resolveItem]); + useMaintenanceRefresh(() => { + setNeedsRefresh(value => markGovernanceResourcesStale(value)); + void loadCurrentTab(true); + }); + const tabLoading = useDelayedIndicator(active && governanceResourcesForTab(tab).some(resource => pending[resource])); + const changeFormLoading = useDelayedIndicator(active && changeOpen && (pending.documents || changeType === 'REVISION' && pending.candidates)); + const resolveFormLoading = useDelayedIndicator(active && Boolean(resolveItem) && pending.protocols); + const errorFor = (resource: GovernanceResource, title: string) => errors[resource] ? void loadResource(resource, true)} /> : null; + const loadingFor = (resource: GovernanceResource) => tabLoading && pending[resource] ?
正在读取或刷新{resource === 'coverage' ? '到齐矩阵' : resource === 'protocols' ? '来源协议' : resource === 'changes' ? '来源变更清单' : resource === 'candidates' ? '候选文件' : '原文件记录'};已有结果会暂时保留。
: null; const submitProtocol = async () => { + if (actionLock.current) return; actionLock.current = true; try { const value = await protocolForm.validateFields(); setActionBusy('protocol'); const body: Row = { @@ -294,45 +385,46 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized } shardCode: String(value.shardCode || '').trim() || 'MAIN', reason: String(value.reason || '').trim(), }; - await api.createGovernanceProtocol(body); message.success('来源协议已保存'); setProtocolOpen(false); protocolForm.resetFields(); await load(); + await api.createGovernanceProtocol(body); message.success('来源协议已保存'); setProtocolOpen(false); protocolForm.resetFields(); markAffectedResources(['protocols', 'coverage']); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '协议保存失败'); } - finally { setActionBusy(''); } + finally { actionLock.current = false; setActionBusy(''); } }; const submitChange = async () => { + if (actionLock.current) return; actionLock.current = true; try { const value = await changeForm.validateFields(); setActionBusy('change'); await api.createSourceChange({ ...value, reason: String(value.reason || '').trim(), idempotencyKey: crypto.randomUUID() }); - message.success('来源变更申请已提交,当前数据保持不变'); setChangeOpen(false); changeForm.resetFields(); await load(); + message.success('来源变更申请已提交,当前数据保持不变'); setChangeOpen(false); changeForm.resetFields(); markAffectedResources(['changes', 'candidates']); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源变更申请失败'); } - finally { setActionBusy(''); } + finally { actionLock.current = false; setActionBusy(''); } }; const submitReview = async (approve: boolean) => { - if (!reviewItem) return; + if (!reviewItem || actionLock.current) return; actionLock.current = true; try { const values = await reviewForm.validateFields(); setActionBusy(String(reviewItem.id)); await api.reviewSourceChange(String(reviewItem.id), { approve, reason: values.reason.trim(), expectedRowVersion: Number(reviewItem.rowVersion || 0) }); - message.success(approve ? '变更申请已通过' : '变更申请已驳回'); setReviewItem(null); reviewForm.resetFields(); await load(); - } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '申请已被其他操作更新,请刷新后复核。' : value instanceof Error ? value.message : '审核失败'); if (value instanceof ApiError && value.status === 409) await load(); } - finally { setActionBusy(''); } + message.success(approve ? '变更申请已通过' : '变更申请已驳回'); setReviewItem(null); reviewForm.resetFields(); markAffectedResources(['changes', 'candidates']); + } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '申请已被其他操作更新,请刷新后复核。' : value instanceof Error ? value.message : '审核失败'); if (value instanceof ApiError && value.status === 409) await refreshAffectedCurrent(['changes', 'candidates']); } + finally { actionLock.current = false; setActionBusy(''); } }; const buildChange = async (item: Row) => { - const id = String(item.id || ''); if (!id) return; + const id = String(item.id || ''); if (!id || actionLock.current) return; actionLock.current = true; setActionBusy(id); try { const result = await api.releases(); await api.buildSourceChange(id, { expectedCurrentReleaseId: result.currentReleaseId ?? null, idempotencyKey: crypto.randomUUID() }); - message.success('来源变更处理已完成;请检查候选数据与校验状态。'); await load(); - } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '当前数据或申请状态已变化,请刷新核对。' : value instanceof Error ? value.message : '变更处理失败'); if (value instanceof ApiError && value.status === 409) await load(); } - finally { setActionBusy(''); } + message.success('来源变更处理已完成;请检查候选数据与校验状态。'); markAffectedResources(['changes', 'candidates', 'coverage']); + } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '当前数据或申请状态已变化,请刷新核对。' : value instanceof Error ? value.message : '变更处理失败'); if (value instanceof ApiError && value.status === 409) await refreshAffectedCurrent(['changes', 'candidates', 'coverage']); } + finally { actionLock.current = false; setActionBusy(''); } }; const resolveCandidate = async () => { - if (!resolveItem) return; + if (!resolveItem || actionLock.current) return; actionLock.current = true; try { const value = await resolveForm.validateFields(); setActionBusy(resolveItem.id); await api.resolveSourceCandidate(resolveItem.id, { ...value, reason: String(value.reason || '').trim() }); - message.success('候选来源身份已裁决'); setResolveItem(null); resolveForm.resetFields(); await load(); + message.success('候选来源身份已裁决'); setResolveItem(null); resolveForm.resetFields(); markAffectedResources(['changes', 'candidates']); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源裁决失败'); } - finally { setActionBusy(''); } + finally { actionLock.current = false; setActionBusy(''); } }; const showEvidence = async (id: string) => { setEvidenceRevision(id); setEvidence(null); @@ -340,10 +432,11 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '证据读取失败'); } }; const download = async (id: string) => { + if (actionLock.current) return; actionLock.current = true; setActionBusy(id); try { showDownload(await api.downloadSourceRevision(id)); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 403 ? '当前账号无权下载此原始文件或文件超出组织范围。' : value instanceof Error ? value.message : '原文件下载失败'); } - finally { setActionBusy(''); } + finally { actionLock.current = false; setActionBusy(''); } }; const coverageItems = rows(coverage?.items); @@ -392,26 +485,27 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized } const candidateChoices = sourceItems.map(item => ({ label: `${item.sourceFile} · ${item.year}-${String(item.month).padStart(2, '0')} · ${item.status}`, value: item.id })); return
-
来源协议、覆盖与变更当前数据的来源覆盖、到齐状态和原文件下载权限由服务端控制
{canMaintain && <>}
- void load()} /> void load()} /> void load()} /> +
来源协议、覆盖与变更当前数据的来源覆盖、到齐状态和原文件下载权限由服务端控制
{canMaintain && <>}
适用数据 当前数据{coverage?.complete === true ? '覆盖完整' : coverage?.complete === false ? '覆盖未齐' : '未返回'}
{coverageItems.length ?
String(row.protocolId || row.sourceSlot)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 980 }} /> : } }, - { key: 'protocols', label: `来源协议(${protocols.length})`, children:
{protocols.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1120 }} /> : } }, - { key: 'changes', label: `来源变更与撤销(${sourceChanges.length})`, children:
{conflictCandidates.length > 0 && {conflictCandidates.map(item => )}} />}{errors.changes ? : sourceChanges.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1080 }} /> : } }, - { key: 'revisions', label: `原文件记录与证据(${revisions.length})`, children:
{revisions.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1280 }} /> : } }, + { key: 'coverage', label: '到齐与告警', children:
{errorFor('coverage', '到齐矩阵读取失败')}{loadingFor('coverage')}{loaded.coverage && coverageLoadedRelease.current !== currentReleaseId && }{loaded.coverage && <>
适用数据 {coverageLoadedRelease.current === currentReleaseId ? '当前数据' : '上次成功数据'}{coverage?.complete === true ? '覆盖完整' : coverage?.complete === false ? '覆盖未齐' : '未返回'}
{coverageItems.length ?
String(row.protocolId || row.sourceSlot)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 980 }} /> : }} }, + { key: 'protocols', label: `来源协议(${protocols.length})`, children:
{errorFor('protocols', '协议读取失败')}{loadingFor('protocols')}{loaded.protocols ? protocols.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1120 }} /> : : null} }, + { key: 'changes', label: `来源变更与撤销(${sourceChanges.length})`, children:
{errorFor('changes', '来源变更清单读取失败')}{errorFor('candidates', '候选文件读取失败')}{loadingFor('changes')}{pending.candidates && tabLoading &&
正在读取或刷新候选文件;已有结果会暂时保留。
}{loaded.candidates && conflictCandidates.length > 0 && {conflictCandidates.map(item => )}} />}{loaded.changes ? sourceChanges.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1080 }} /> : : null} }, + { key: 'revisions', label: `原文件记录与证据(${revisions.length})`, children:
{errorFor('documents', '来源记录读取失败')}{loadingFor('documents')}{loaded.documents ? revisions.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1280 }} /> : : null} }, ]} /> setProtocolOpen(false)} onOk={() => void submitProtocol()}>
该阶段适用列为预期到齐来源解析工作表将使用已验证名称:{stage === 'black' ? '报废明细' : '明细'}。
setChangeOpen(false)} onOk={() => void submitChange()}> + {errorFor('documents', '当前来源文档读取失败')}{errorFor('candidates', '待替换候选文件读取失败')} + {changeFormLoading &&
正在读取申请所需来源信息…
}
{changeType === 'REVISION' && {resolveDecision !== 'RETURN' && {resolveDecision !== 'RETURN' &&
String(row.id)} pagination={false} columns={[{ title: '处理状态', dataIndex: 'status', key: 'status', width: 120 }, { title: '行数 / 拒绝', key: 'counts', align: 'right', render: (_, row) => `${text(row.rowCount)} / ${text(row.rejectedCount)}` }, { title: '分量摘要', dataIndex: 'componentSummary', key: 'componentSummary', render: value => text(value) }]} scroll={{ x: 520 }} /> : }{canDownload && } :
读取来源记录…
} @@ -421,25 +515,31 @@ export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized } export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [data, setData] = useState(null); - const [loading, setLoading] = useState(true); + const [loaded, setLoaded] = useState(false); + const read = useDelayedBusy(); const loading = read.busy; const [busy, setBusy] = useState(false); + const actionLock = useRef(false); const [error, setError] = useState(''); const [planOpen, setPlanOpen] = useState(false); const [form] = Form.useForm(); const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); - const load = async () => { setLoading(true); try { setData(await api.governanceBackups()); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '备份状态读取失败'); } finally { setLoading(false); } }; - useEffect(() => { void load(); }, []); + const load = useCallback(() => read.run(async () => { try { setData(await api.governanceBackups()); setLoaded(true); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '备份状态读取失败'); } }), [onUnauthorized, read.run]); + useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]); + useMaintenanceRefresh(load); const runJob = async (type: string, backupId?: string) => { + if (actionLock.current) return; actionLock.current = true; setBusy(true); try { await api.createBackupJob({ type, ...(backupId ? { backupId } : {}), idempotencyKey: crypto.randomUUID() }); message.success('备份任务已登记'); await load(); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '备份任务提交失败'); } - finally { setBusy(false); } + finally { actionLock.current = false; setBusy(false); } }; const savePlan = async () => { + if (actionLock.current) return; actionLock.current = true; try { const value = await form.validateFields(); setBusy(true); await api.updateBackupPlan({ ...value, reason: String(value.reason || '').trim(), expectedRowVersion: Number(obj(data?.plan).rowVersion || 0) }); message.success('备份计划已保存'); setPlanOpen(false); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '备份计划已被更新,请刷新后重试。' : value instanceof Error ? value.message : '保存备份计划失败'); } - finally { setBusy(false); } + finally { actionLock.current = false; setBusy(false); } }; const plan = obj(data?.plan); const backups = rows(data?.items); const columns: ColumnsType = [ @@ -459,8 +559,8 @@ export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { us ]; return
备份、恢复验证与计划恢复验证仅在隔离目录执行;当前不开放在线业务库覆盖恢复
{canManage && <>}
- {error && } - {loading ?
读取备份与恢复状态…
: <>
计划{plan.active === true ? '已启用' : plan.active === false ? '已停用' : '未配置'}
周期 / RPO{text(plan.intervalHours)} 小时 / {text(plan.rpoHours)} 小时
RTO{text(plan.rtoHours)} 小时
在线恢复{obj(data).liveRestoreEnabled === true ? '开放' : '关闭'}
{backups.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 920 }} /> : }} + {error && void load()}>重试 : undefined} />} + {loading && !loaded ?
读取备份与恢复状态…
: loaded && <>
计划{plan.active === true ? '已启用' : plan.active === false ? '已停用' : '未配置'}
周期 / RPO{text(plan.intervalHours)} 小时 / {text(plan.rpoHours)} 小时
RTO{text(plan.rtoHours)} 小时
在线恢复{obj(data).liveRestoreEnabled === true ? '开放' : '关闭'}
{backups.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 920 }} /> : }} {onNavigate && } setPlanOpen(false)} onOk={() => void savePlan()}>
; @@ -468,8 +568,11 @@ export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { us export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [data, setData] = useState(null); - const [loading, setLoading] = useState(true); + const [loaded, setLoaded] = useState(false); + const read = useDelayedBusy(); const loading = read.busy; + const [section, setSection] = useState('health'); const [refreshing, setRefreshing] = useState(false); const [error, setError] = useState(''); const [alertPolicy, setAlertPolicy] = useState(null); @@ -478,24 +581,27 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse const [policyBusy, setPolicyBusy] = useState(false); const [policyError, setPolicyError] = useState(''); const [policyForm] = Form.useForm(); + const actionLock = useRef(false); const canRefresh = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); - const load = async () => { - setLoading(true); - try { setData(await api.governanceMonitor()); setError(''); } + const load = useCallback(() => read.run(async () => { + try { setData(await api.governanceMonitor()); setLoaded(true); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '运行监控读取失败'); } - finally { setLoading(false); } - }; - useEffect(() => { void load(); }, []); - const loadPolicy = async () => { + }), [onUnauthorized, read.run]); + useEffect(() => { if (active && ['health', 'requests'].includes(section) && !loaded) void load(); }, [active, section, loaded, load]); + useVisiblePolling(load, 15000, active && loaded && ['health', 'requests'].includes(section)); + useMaintenanceRefresh(() => { if (['health', 'requests'].includes(section)) void load(); }); + const loadPolicy = useCallback(async () => { try { const response = await api.governanceAlertPolicy(); const policy = obj(response.policy); setAlertPolicy(policy); setPolicyError(''); } catch (value) { if (!onUnauthorized(value)) setPolicyError(value instanceof Error ? value.message : '告警策略读取失败'); } - }; - useEffect(() => { if (canRefresh) void loadPolicy(); }, [canRefresh]); + }, [onUnauthorized]); + useEffect(() => { if (active && section === 'health' && canRefresh && !alertPolicy && !policyError) void loadPolicy(); }, [active, section, canRefresh, alertPolicy, policyError, loadPolicy]); const editPolicy = () => { if (!alertPolicy) return; policyForm.setFieldsValue({ ...alertPolicy, severityOverrides: JSON.stringify(alertPolicy.severityOverrides || {}, null, 2), silenceUntil: text(alertPolicy.silenceUntil, ''), reason: '' }); setPolicyOpen(true); }; const savePolicy = async () => { + if (actionLock.current) return; + actionLock.current = true; try { const values = await policyForm.validateFields(); let severityOverrides: unknown; try { severityOverrides = JSON.parse(String(values.severityOverrides || '{}')); } catch { message.error('严重度配置不是有效 JSON'); return; } @@ -503,13 +609,15 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse await api.updateGovernanceAlertPolicy({ queueAgeMinutes: Number(values.queueAgeMinutes), diskFreeBytes: Number(values.diskFreeBytes), backupAgeHours: Number(values.backupAgeHours), quietPeriodMinutes: Number(values.quietPeriodMinutes), slowRequestMillis: Number(values.slowRequestMillis), severityOverrides, silenceUntil: String(values.silenceUntil || '').trim() || null, expectedRowVersion: Number(alertPolicy?.rowVersion || 0), reason: String(values.reason || '').trim() }); message.success('告警策略已保存'); setPolicyOpen(false); await loadPolicy(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) setPolicyError(value instanceof ApiError && value.status === 409 ? '告警策略已发生并发修改,请重新读取。' : value instanceof Error ? value.message : '告警策略保存失败'); } - finally { setPolicyBusy(false); } + finally { actionLock.current = false; setPolicyBusy(false); } }; const refresh = async () => { + if (actionLock.current) return; + actionLock.current = true; setRefreshing(true); try { const result = await api.refreshGovernanceMonitor(); setData(result); message.success('系统健康检查已完成'); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检失败'); } - finally { setRefreshing(false); } + finally { actionLock.current = false; setRefreshing(false); } }; const summary = obj(data?.summary); const summaryEntries = Object.entries(summary).filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value)); @@ -536,14 +644,15 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse { title: '最近请求', dataIndex: 'lastSeen', key: 'lastSeen', width: 190, render: value => configurationDateTime(value) || '—' }, ]; return <> -
运行监控与告警只读取并更新服务端运行状态;不发送外部通知
{canRefresh && <>}
- {error && } - {policyError && } - {loading ?
读取平台状态…
: <>
{summaryEntries.length ? summaryEntries.map(([key, value]) =>
{summaryLabels[key] || '其他指标'}{text(value)}
) :
服务端没有返回运行指标
}
{alertRows.length ?
String(row.id || row.code)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1260 }} /> : }} }, - { key: 'requests', label: '接口请求指标', children:

接口请求指标

累计请求数、失败数与耗时;最近请求时间不代表统计起点。

- {loading ?
读取接口指标…
: requestMetricRows.length ?
`${text(row.routePattern)}-${text(row.method)}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1200 }} /> : } + {error && void load()}>重试 : undefined} />} + {policyError && void loadPolicy()}>重试 : undefined} />} + {loading && !loaded ?
读取平台状态…
: loaded && <>
{summaryEntries.length ? summaryEntries.map(([key, value]) =>
{summaryLabels[key] || '其他指标'}{text(value)}
) :
服务端没有返回运行指标
}
{alertRows.length ?
String(row.id || row.code)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1260 }} /> : }} }, + { key: 'requests', label: '接口请求指标', children:

接口请求指标

累计请求数、失败数与耗时;最近请求时间不代表统计起点。

+ {error && void load()}>重试 : undefined} />} + {loading && !loaded ?
读取接口指标…
: loaded && (requestMetricRows.length ?
`${text(row.routePattern)}-${text(row.method)}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1200 }} /> : )} }, { key: 'inspection', label: '巡检策略', children: }, ]} /> @@ -558,62 +667,81 @@ const ACTIONS_BY_TYPE: Record = { export function ServiceIdentityPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [items, setItems] = useState([]); const [allowedActions, setAllowedActions] = useState([]); const [serviceTypes, setServiceTypes] = useState([]); const [bindings, setBindings] = useState([]); - const [loading, setLoading] = useState(true); + const [identityLoaded, setIdentityLoaded] = useState(false); + const [bindingLoaded, setBindingLoaded] = useState(false); + const identityRead = useDelayedBusy(); const bindingRead = useDelayedBusy(); + const [section, setSection] = useState('identities'); const [error, setError] = useState(''); + const [bindingError, setBindingError] = useState(''); const [editing, setEditing] = useState(null); const [rotating, setRotating] = useState(null); const [rotations, setRotations] = useState([]); + const [historyLoading, setHistoryLoading] = useState(false); const [bindingEdit, setBindingEdit] = useState<{ type: string; identityId: string } | null>(null); const [busy, setBusy] = useState(false); + const actionLock = useRef(false); const [form] = Form.useForm(); const [rotateForm] = Form.useForm(); const [bindingForm] = Form.useForm<{ reason: string }>(); const canManage = user.roles.includes('SYSTEM_ADMIN'); + const historyReadLock = useRef(false); const serviceType = Form.useWatch('serviceType', form); - const load = async () => { - setLoading(true); + const loadIdentities = useCallback(() => identityRead.run(async () => { + try { const result = await api.serviceIdentities(); setItems(collectionItems(result)); setAllowedActions(Array.isArray(result.allowedActions) ? result.allowedActions.map(String) : []); setServiceTypes(Array.isArray(result.serviceTypes) ? result.serviceTypes.map(String) : []); setIdentityLoaded(true); setError(''); } + catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '服务身份读取失败'); } + }), [identityRead.run, onUnauthorized]); + const loadBindings = useCallback(() => bindingRead.run(async () => { const canReadBindings = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); - const [identityResult, bindingResult] = await Promise.allSettled([api.serviceIdentities(), canReadBindings ? api.serviceBindings() : Promise.resolve({ items: [] as Row[] })]); - if (identityResult.status === 'fulfilled') { setItems(collectionItems(identityResult.value)); setAllowedActions(Array.isArray(identityResult.value.allowedActions) ? identityResult.value.allowedActions.map(String) : []); setServiceTypes(Array.isArray(identityResult.value.serviceTypes) ? identityResult.value.serviceTypes.map(String) : []); } - else if (!onUnauthorized(identityResult.reason)) setError(identityResult.reason instanceof Error ? identityResult.reason.message : '服务身份读取失败'); - if (bindingResult.status === 'fulfilled') setBindings(collectionItems(bindingResult.value)); else if (!onUnauthorized(bindingResult.reason)) setError(bindingResult.reason instanceof Error ? bindingResult.reason.message : '服务绑定读取失败'); - setLoading(false); - }; - useEffect(() => { void load(); }, []); + if (!canReadBindings) { setBindings([]); setBindingLoaded(true); return; } + try { setBindings(collectionItems(await api.serviceBindings())); setBindingLoaded(true); setBindingError(''); } + catch (value) { if (!onUnauthorized(value)) setBindingError(value instanceof Error ? value.message : '服务绑定读取失败'); } + }), [bindingRead.run, onUnauthorized, user.roles]); + const loadCurrent = useCallback(() => { if (!active) return; if (section === 'bindings') { void loadIdentities(); void loadBindings(); } else void loadIdentities(); }, [active, loadBindings, loadIdentities, section]); + const loading = section === 'bindings' ? identityRead.busy || bindingRead.busy : identityRead.busy; + useEffect(() => { + if (!active) return; + if (!identityLoaded) void loadIdentities(); + if (section === 'bindings' && !bindingLoaded) void loadBindings(); + }, [active, section, identityLoaded, bindingLoaded, loadIdentities, loadBindings]); + useMaintenanceRefresh(loadCurrent); const open = (item?: Row) => { const next = item || {}; setEditing(next); form.setFieldsValue({ name: text(next.name, ''), serviceType: text(next.serviceType, serviceTypes[0] || ''), allowedActions: Array.isArray(next.allowedActions) ? next.allowedActions.map(String) : [], credentialReference: text(next.credentialReference, ''), credentialStatus: text(next.credentialStatus, 'UNCONFIGURED'), active: next.active === true, reason: '' }); }; const save = async () => { + if (actionLock.current) return; actionLock.current = true; try { const values = await form.validateFields(); setBusy(true); const id = String(editing?.id || ''); const body = { name: String(values.name || '').trim(), serviceType: values.serviceType, allowedActions: values.allowedActions || [], credentialReference: values.credentialReference || null, credentialStatus: values.credentialStatus, active: id ? values.active === true : false, ...(id ? { expectedRowVersion: Number(editing?.rowVersion || 0) } : {}), reason: String(values.reason || '').trim() }; if (id) await api.updateServiceIdentity(id, body); else await api.createServiceIdentity(body); - message.success(id ? '服务身份已更新' : '服务身份已创建并保持停用'); setEditing(null); await load(); + message.success(id ? '服务身份已更新' : '服务身份已创建并保持停用'); setEditing(null); await loadCurrent(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '服务身份已被其他操作更新,请刷新后重试。' : value instanceof Error ? value.message : '服务身份保存失败'); } - finally { setBusy(false); } + finally { actionLock.current = false; setBusy(false); } }; const rotate = async () => { if (!rotating?.id) return; - try { const values = await rotateForm.validateFields(); setBusy(true); await api.rotateServiceIdentity(String(rotating.id), { credentialReference: values.credentialReference, credentialStatus: values.credentialStatus, reason: String(values.reason || '').trim(), expectedRowVersion: Number(rotating.rowVersion || 0) }); message.success('凭据引用状态已轮换,服务端未接收密钥内容'); setRotating(null); await load(); } + if (actionLock.current) return; actionLock.current = true; + try { const values = await rotateForm.validateFields(); setBusy(true); await api.rotateServiceIdentity(String(rotating.id), { credentialReference: values.credentialReference, credentialStatus: values.credentialStatus, reason: String(values.reason || '').trim(), expectedRowVersion: Number(rotating.rowVersion || 0) }); message.success('凭据引用状态已轮换,服务端未接收密钥内容'); setRotating(null); await loadCurrent(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '服务身份已被其他操作更新。' : value instanceof Error ? value.message : '凭据轮换失败'); } - finally { setBusy(false); } + finally { actionLock.current = false; setBusy(false); } }; const bind = async (type: string, identityId: string) => { bindingForm.resetFields(); setBindingEdit({ type, identityId }); }; const submitBinding = async () => { - if (!bindingEdit) return; + if (!bindingEdit || actionLock.current) return; let values: { reason: string }; try { values = await bindingForm.validateFields(); } catch { return; } + if (actionLock.current) return; actionLock.current = true; setBusy(true); - try { await api.updateServiceBinding(bindingEdit.type, { identityId: bindingEdit.identityId, reason: values.reason.trim() }); message.success(`${bindingEdit.type} 服务绑定已更新`); setBindingEdit(null); await load(); } + try { await api.updateServiceBinding(bindingEdit.type, { identityId: bindingEdit.identityId, reason: values.reason.trim() }); message.success(`${bindingEdit.type} 服务绑定已更新`); setBindingEdit(null); await loadBindings(); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '服务身份绑定失败'); } - finally { setBusy(false); } + finally { actionLock.current = false; setBusy(false); } }; const columns: ColumnsType = [ { title: '服务身份', dataIndex: 'name', key: 'name', fixed: 'left', width: 190 }, @@ -621,17 +749,17 @@ export function ServiceIdentityPanel({ user, onUnauthorized }: { user: AuthUser; { title: '授权动作', dataIndex: 'allowedActions', key: 'allowedActions', width: 280, render: value => Array.isArray(value) ? value.join('、') : '—' }, { title: '凭据引用 / 状态', key: 'credential', width: 260, render: (_, row) => {text(row.credentialStatus)}{text(row.credentialReference, '未配置引用')} }, { title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => {value === true ? '启用' : '停用'} }, - { title: '操作', key: 'action', fixed: 'right', width: 230, render: (_, row) => {canManage && <>} }, + { title: '操作', key: 'action', fixed: 'right', width: 230, render: (_, row) => {canManage && <>} }, ]; return
-
-
服务身份与最小动作授权仅保存 env: 或 file: 凭据引用,不在浏览器或服务端表单中接收密钥文本
{canManage && }
- {error && } - {loading ?
读取服务身份…
: items.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1200 }} /> : } +
服务身份与最小动作授权仅保存 env: 或 file: 凭据引用,不在浏览器或服务端表单中接收密钥文本
{canManage && }
+ {error && void loadIdentities()}>重试 : undefined} />} + {loading && !identityLoaded ?
读取服务身份…
: identityLoaded && (items.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1200 }} /> : )} }, - { key: 'bindings', label: '接入绑定', children: <>
服务接入绑定只允许类型匹配且授权状态可用的身份
{serviceTypes.length ?
{serviceTypes.map(type =>
{type}{text(bindings.find(item => item.serviceType === type)?.serviceIdentityId, '未绑定')}{canManage && item.serviceType === type)?.serviceIdentityId || '') || undefined} loading={busy} options={items.filter(item => item.serviceType === type).map(item => ({ label: `${text(item.name)} · ${text(item.credentialStatus)}`, value: String(item.id) }))} onChange={value => void bind(type, value)} />}
)}
: )}
}, ]} /> setEditing(null)} onOk={() => void save()}> @@ -640,19 +768,24 @@ export function ServiceIdentityPanel({ user, onUnauthorized }: { user: AuthUser; setRotating(null)} onOk={() => void rotate()}>
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} columns={[{ title: '引用', dataIndex: 'credentialReference', key: 'credentialReference' }, { title: '状态', dataIndex: 'credentialStatus', key: 'credentialStatus' }, { title: '原因', dataIndex: 'reason', key: 'reason' }, { title: '时间', dataIndex: 'createdAt', key: 'createdAt' }]} /> : } + setRotating(null)}>{historyLoading ?
读取轮换历史…
: rotations.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} columns={[{ title: '引用', dataIndex: 'credentialReference', key: 'credentialReference' }, { title: '状态', dataIndex: 'credentialStatus', key: 'credentialStatus' }, { title: '原因', dataIndex: 'reason', key: 'reason' }, { title: '时间', dataIndex: 'createdAt', key: 'createdAt' }]} /> : } ; } export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [userId, setUserId] = useState(); const [policy, setPolicy] = useState(null); const [users, setUsers] = useState([]); + const [usersLoaded, setUsersLoaded] = useState(false); + const [usersError, setUsersError] = useState(''); const [effective, setEffective] = useState(null); const [scopePreview, setScopePreview] = useState(null); const [previewBusy, setPreviewBusy] = useState(false); - const [loading, setLoading] = useState(false); + const usersRead = useDelayedBusy(); + const policyRead = useDelayedBusy(); + const loading = policyRead.busy; const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [form] = Form.useForm(); @@ -660,35 +793,52 @@ export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (err const policyGeneration = useRef(0); const savingRef = useRef(false); const mounted = useRef(true); + const usersRequest = useRef | null>(null); + const policyRequest = useRef<{ id: string; promise: Promise } | null>(null); + const loadUsers = useCallback(() => { + if (usersRequest.current) return usersRequest.current; + const request = usersRead.run(async () => { + try { setUsers(collectionItems(await api.users())); setUsersLoaded(true); setUsersError(''); } + catch (value) { if (!onUnauthorized(value) && mounted.current) setUsersError(value instanceof Error ? value.message : '用户列表读取失败'); } + }).finally(() => { if (usersRequest.current === request) usersRequest.current = null; }); + usersRequest.current = request; + return request; + }, [onUnauthorized, usersRead.run]); const selectUser = (id: string) => { if (savingRef.current) return; selectedUser.current = id; policyGeneration.current++; setUserId(id); setPolicy(null); form.resetFields(); setEffective(null); setScopePreview(null); setPreviewBusy(false); setError(''); - setLoading(true); + policyRequest.current = null; }; const userOptions = users.map(item => ({ label: `${text(item.displayName || item.username)} · ${text(item.username)}`, value: String(item.id) })).filter(item => item.value); - const load = async (id: string) => { + const load = useCallback((id: string) => { + if (!active || !id) return Promise.resolve(); + if (policyRequest.current?.id === id) return policyRequest.current.promise; const generation = ++policyGeneration.current; const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation; - if (selectedUser.current !== id) return; - setLoading(true); - setPolicy(null); form.resetFields(); - try { - const result = await api.userAccessPolicy(id); - if (!current()) return; - const value = obj(result.policy || result); - if (value.userId !== id) throw new Error('访问策略与当前用户不匹配,请重新选择用户。'); - setPolicy(value); form.setFieldsValue({ detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields: Array.isArray(value.allowedFields) ? value.allowedFields.join('\n') : '*', validUntil: text(value.validUntil, ''), reason: '' }); setError(''); - } catch (value) { if (!onUnauthorized(value) && current()) setError(value instanceof Error ? value.message : '访问策略读取失败'); } - finally { if (current()) setLoading(false); } - }; + if (selectedUser.current !== id) return Promise.resolve(); + const request = policyRead.run(async () => { + try { + const result = await api.userAccessPolicy(id); + if (!current()) return; + const value = obj(result.policy || result); + if (value.userId !== id) throw new Error('访问策略与当前用户不匹配,请重新选择用户。'); + const preserveDraft = policy?.userId === id && form.isFieldsTouched(); + setPolicy(value); + if (!preserveDraft) form.setFieldsValue({ detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields: Array.isArray(value.allowedFields) ? value.allowedFields.join('\n') : '*', validUntil: text(value.validUntil, ''), reason: '' }); + setError(''); + } catch (value) { if (!onUnauthorized(value) && current()) setError(value instanceof Error ? value.message : '访问策略读取失败'); } + }).finally(() => { if (policyRequest.current?.promise === request) policyRequest.current = null; }); + policyRequest.current = { id, promise: request }; + return request; + }, [active, form, onUnauthorized, policy, policyRead.run]); useEffect(() => { mounted.current = true; - api.users().then(value => { if (mounted.current) setUsers(collectionItems(value)); }).catch(errorValue => { if (!onUnauthorized(errorValue) && mounted.current) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); }); return () => { mounted.current = false; policyGeneration.current++; }; }, []); - useEffect(() => { if (userId) void load(userId); else setPolicy(null); }, [userId]); + useEffect(() => { if (active && !usersLoaded && !usersError) void loadUsers(); }, [active, loadUsers, usersError, usersLoaded]); + useEffect(() => { if (active && userId && policy?.userId !== userId) void load(userId); }, [active, userId, policy?.userId, load]); const save = async () => { const id = selectedUser.current; if (!id || !policy || policy.userId !== id || loading || savingRef.current) return; @@ -719,5 +869,5 @@ export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (err const effectiveDepartments = Array.isArray(effective?.departments) ? effective.departments.map(String).join('、') : '—'; const grantedDepartments = Array.isArray(effective?.grantedDepartments) ? effective.grantedDepartments.map(String).join('、') : '—'; const hierarchyRows = rows(effective?.hierarchySource); - return
用户明细与证据访问策略明细、原文件下载与字段授权由服务端二次校验

空字段集合将由服务端按其默认策略处理。

}{effective &&
服务端有效授权{effective.authorizationEffective === true ? '有效' : '未生效'}

用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验

角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}

原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}

业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}

动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}

字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}

{hierarchyRows.length > 0 &&

层级展开依据:当前映射配置

}
}{scopePreview &&
授权范围行数{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}

原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}

{rows(scopePreview.hierarchySource).length > 0 &&

层级依据:当前映射配置

}{scopeCounts.length ?
String(row.stage)} pagination={false} columns={[{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 100, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '总行数', dataIndex: 'totalRows', key: 'totalRows', align: 'right' }, { title: '授权行数', dataIndex: 'authorizedRows', key: 'authorizedRows', align: 'right' }]} /> : }}{!userId && }; + return
用户明细与证据访问策略明细、原文件下载与字段授权由服务端二次校验

空字段集合将由服务端按其默认策略处理。

}{effective &&
服务端有效授权{effective.authorizationEffective === true ? '有效' : '未生效'}

用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验

角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}

原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}

业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}

动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}

字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}

{hierarchyRows.length > 0 &&

层级展开依据:当前映射配置

}
}{scopePreview &&
授权范围行数{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}

原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}

{rows(scopePreview.hierarchySource).length > 0 &&

层级依据:当前映射配置

}{scopeCounts.length ?
String(row.stage)} pagination={false} columns={[{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 100, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '总行数', dataIndex: 'totalRows', key: 'totalRows', align: 'right' }, { title: '授权行数', dataIndex: 'authorizedRows', key: 'authorizedRows', align: 'right' }]} /> : }}{!userId && usersLoaded && users.length > 0 && }; } diff --git a/web/src/ManagementPages.tsx b/web/src/ManagementPages.tsx index a089f9b..e913003 100644 --- a/web/src/ManagementPages.tsx +++ b/web/src/ManagementPages.tsx @@ -65,6 +65,9 @@ import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, Source import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors'; import { useDataWorkflowOperation } from './useDataWorkflowOperation'; 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 { 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 }) { + const { active } = usePageCache(); const [sources, setSources] = useState([]); const [currentReleaseId, setCurrentReleaseId] = useState(null); - const [loading, setLoading] = useState(true); + const [sourcesLoaded, setSourcesLoaded] = useState(false); + const [releaseLoaded, setReleaseLoaded] = useState(false); + const sourceRead = useDelayedBusy(); const [error, setError] = useState(''); const [maintenanceBusy, setMaintenanceBusy] = useState(false); 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.length >= 50 ? previous : { ids: [...previous.ids, id], releaseId: previous.ids.length ? previous.releaseId : currentReleaseId }); - const load = async () => { - setLoading(true); - try { - const [sourceResult, releaseResult] = await Promise.all([api.sources(), api.releases()]); - setSources(collectionItems(sourceResult)); setCurrentReleaseId(releaseResult.currentReleaseId ?? null); setError(''); - } catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); } - finally { setLoading(false); } - }; - useEffect(() => { void load(); }, []); + const load = useCallback(() => sourceRead.run(async () => { + const failures: string[] = []; + const [sourceResult, releaseResult] = await Promise.allSettled([api.sources(), api.releases()]); + if (sourceResult.status === 'fulfilled') { setSources(collectionItems(sourceResult.value)); setSourcesLoaded(true); } + else if (!onUnauthorized(sourceResult.reason)) failures.push(`来源清单:${apiMessage(sourceResult.reason)}`); + if (releaseResult.status === 'fulfilled') { setCurrentReleaseId(releaseResult.value.currentReleaseId ?? null); setReleaseLoaded(true); } + else if (!onUnauthorized(releaseResult.reason)) failures.push(`当前发布版本:${apiMessage(releaseResult.reason)}`); + setError(failures.join(';')); + }), [onUnauthorized, sourceRead.run]); + useEffect(() => { if (active && (!sourcesLoaded || !releaseLoaded)) void load(); }, [active, sourcesLoaded, releaseLoaded, load]); useMaintenanceRefresh(load); return
- {error && void load()}>重试} />} + {error && void load()}>重试} />} void load()} /> }, - { key: 'files', label: '来源文件', children: setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> }, - { key: 'history', label: '导入记录', children: }, + { key: 'files', label: '来源文件', children: setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> }, + { key: 'history', label: '导入记录', children: }, { key: 'audit', label: '来源审计', children: }, ]} />
; } -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 [items, setItems] = useState[]>([]); - const [loading, setLoading] = useState(true); + const [loaded, setLoaded] = useState(false); + const read = useDelayedBusy(); + const loading = read.busy; const [error, setError] = useState(''); - const load = useCallback(async () => { - try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setError(''); } + const load = useCallback(() => read.run(async () => { + 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)); } - finally { setLoading(false); } - }, [onUnauthorized]); - useEffect(() => { void load(); }, [load, currentReleaseId]); - 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]); - return
导入记录{items.length} 条 · 可查看处理结果和逐行校验问题
- {error && void load()}>重试} />} - {loading ? : void load()} />} + }), [onUnauthorized, read.run]); + useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]); + useVisiblePolling(load, 2000, active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))); + useMaintenanceRefresh(load); + return
导入记录{items.length} 条 · 可查看处理结果和逐行校验问题
+ {error && void load()}>重试} />} + {loading && !loaded ? : loaded && void load()} />}
; } function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) { + const { active } = usePageCache(); const [result, setResult] = useState(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 [page, setPage] = useState(1); + const activeRef = useRef(active); activeRef.current = active; + const requestGeneration = useRef(0); + const requestRef = useRef<{ key: string; promise: Promise } | 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(() => { - if (!runId) return; - let alive = true; - setLoading(true); - api.importIssues(runId, page, TABLE_PAGE_SIZE).then(value => { if (alive) { setResult(value); setError(''); } }) - .catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); }) - .finally(() => { if (alive) setLoading(false); }); - return () => { alive = false; }; - }, [runId, page, onUnauthorized]); - const items = unwrapItems(result).items; + if (active && runId && (loadedRunId !== runId || loadedPage !== page)) void load(); + }, [active, loadedPage, loadedRunId, load, page, runId]); + const items = loadedRunId === runId ? unwrapItems(result).items : []; + const hasSameRunResult = loadedRunId === runId && loadedPage > 0; + const pageMatches = hasSameRunResult && matchesImportIssuePage(loadedRunId, loadedPage, runId, page); return - {error && } - {loading ?
正在读取问题行…
: } - {result?.total && result.total > TABLE_PAGE_SIZE && `共 ${count} 条问题`} onChange={setPage} />} + {error && void load()}>重试} />} + {loading && !hasSameRunResult ?
正在读取问题行…
: hasSameRunResult ? <>{!pageMatches && loading &&
正在读取第 {page} 页,暂时保留第 {loadedPage} 页结果。
} : null} + {hasSameRunResult && result?.total && result.total > TABLE_PAGE_SIZE && `共 ${count} 条问题`} onChange={setPage} />}
; } @@ -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; }) { const [items, setItems] = useState[]>([]); - 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 [metadata, setMetadata] = useState<{ total?: number; page?: number; pageSize?: number }>({}); - const load = async () => { - setLoading(true); + const load = useCallback(() => read.run(async () => { try { const result = await api.tasks(); const normalized = unwrapItems(result); setItems(endpoint === 'imports' ? normalized.items.filter(item => String(item.type).toUpperCase() === 'IMPORT') : normalized.items); setMetadata({ total: normalized.total, page: normalized.page, pageSize: normalized.pageSize }); - setError(''); + setError(''); setLoaded(true); } catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); - } finally { setLoading(false); } - }; - useEffect(() => { void load(); }, [endpoint]); + } + }), [endpoint, onUnauthorized, read.run]); + 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
- } onClick={() => void load()}>刷新} /> - {error && } + } loading={loading} onClick={() => void load()}>刷新} /> + {error && void load()}>重试 : undefined} />}
{title}{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}
- {loading ?
正在读取…
: void load()} />} + {loading && !loaded ?
正在读取…
: loaded && void load()} />}
; } @@ -373,10 +403,14 @@ type PublishedConfigNames = Pick boolean; onNavigate: (page: PageKey) => void }) { const { message } = App.useApp(); + const { active: pageActive } = usePageCache(); const [items, setItems] = useState[]>([]); - const [loading, setLoading] = useState(true); + const [itemsLoaded, setItemsLoaded] = useState(false); + const itemRead = useDelayedBusy(); + const loading = itemRead.busy; const [error, setError] = useState(''); const [busyId, setBusyId] = useState(''); + const actionLock = useRef(false); const [drafting, setDrafting] = useState | null>(null); const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null); const [impactOpen, setImpactOpen] = useState(false); @@ -399,6 +433,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec const [differenceConfirmed, setDifferenceConfirmed] = useState(false); const [workflowStatus, setWorkflowStatus] = useState(null); const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false); + const [workflowStatusError, setWorkflowStatusError] = useState(''); + const statusRead = useDelayedBusy(); + const supportRequested = useRef(false); const isRules = kind === 'rules'; const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系'; 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.status).toUpperCase() === 'ACTIVE'); - const load = async (silent = false) => { - if(!silent)setLoading(true); - try { - const result = isRules ? await api.rules() : await api.mappings(); - setItems(collectionItems(result)); setError(''); - } catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); } - finally { setLoading(false); } - }; - const loadEditorSupport = async () => { + const load = useCallback((silent = false) => { + const read = async () => { + try { + const result = isRules ? await api.rules() : await api.mappings(); + setItems(collectionItems(result)); setItemsLoaded(true); setError(''); + } catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); } + }; + return silent ? read() : itemRead.run(read); + }, [isRules, itemRead.run, onUnauthorized]); + const loadEditorSupport = useCallback(async () => { try { 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)}`); } } - }; - const refreshWorkflowStatus = async () => { - try { setWorkflowStatus(await api.dataWorkflowStatus()); } - catch { setWorkflowStatus(null); } - finally { setWorkflowStatusLoaded(true); } - }; + }, [isRules, onUnauthorized]); + const refreshWorkflowStatus = useCallback(() => statusRead.run(async () => { + try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); } + catch (value) { if (!onUnauthorized(value)) setWorkflowStatusError(apiMessage(value)); } + }), [onUnauthorized, statusRead.run]); const workflowOperation = useDataWorkflowOperation(isRules ? 'apply-rule' : 'apply-mapping', () => { void load(); void refreshWorkflowStatus(); }); - useEffect(() => { void load(); }, [kind]); - useEffect(() => { void loadEditorSupport(); }, [isRules]); - useEffect(() => { void refreshWorkflowStatus(); }, [kind]); + useEffect(() => { if (pageActive && !itemsLoaded) void load(); }, [pageActive, itemsLoaded, load]); + useEffect(() => { if (pageActive && !supportRequested.current) { supportRequested.current = true; void loadEditorSupport(); } }, [pageActive, loadEditorSupport]); + useEffect(() => { if (pageActive && !workflowStatusLoaded && !workflowStatusError) void refreshWorkflowStatus(); }, [pageActive, workflowStatusLoaded, workflowStatusError, refreshWorkflowStatus]); useEffect(() => { if (!workflowStatus) return; const active = (isRules ? workflowStatus.activeRule : workflowStatus.activeMapping) as { id?: string; name?: string; description?: string; definition?: Record } | null | undefined; @@ -445,8 +488,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec 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;} 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 || '') }); - }, [workflowStatus, items, kind, isRules, testMode, ruleSchema]); + 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, drafting, form]); const openRegression = async (item: Record, preferredRunId?: string) => { if (!isRules) return; @@ -486,6 +529,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec }; const saveDraft = async () => { + if (actionLock.current) return; actionLock.current = true; try { const values = await form.validateFields(); const body: Record = { 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 (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); - } finally { setBusyId(''); } + } finally { actionLock.current = false; setBusyId(''); } }; const runAction = async (item: Record, 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); try { const result = isRules @@ -522,7 +566,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec if (action === 'activate') setDifferenceItem(null); 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) => { @@ -566,6 +610,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec }; const classificationBusy=classificationUpdates.jobs.some(job=>!['failed','completed'].includes(job.status)); const applyCurrent = async () => { + if (actionLock.current) return; actionLock.current = true; try { await form.validateFields(); 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 (!onUnauthorized(value)) message.error(apiMessage(value)); } + finally { actionLock.current = false; } }; useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); }); - if (!workflowStatusLoaded) return
正在读取当前维护模式…
; + if (!workflowStatusLoaded) return
{statusRead.busy ?
正在读取当前维护模式…
: workflowStatusError ? void refreshWorkflowStatus()}>重试} /> : null}
; if (testMode) { const notices = <> {kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&
{classificationBusy&& 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条} {classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=>{job.status==='failed'&&}}/>)}
} - {error && } + {error && void load()}>重试 : undefined} />} {isRules && ruleSchemaError && } {!canApplyWorkflow && } {workflowOperation.error && 重试读取进度 : undefined} />} @@ -621,10 +667,10 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec {canManage && } } /> - {error && } + {error && void load()}>重试 : undefined} />} {isRules && ruleSchemaError && }
{title}记录{items.length} 个服务端记录
- {loading ?
正在读取…
: items.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /> : } + {loading && !itemsLoaded ?
正在读取…
: itemsLoaded ? items.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /> : : null} onNavigate('sources')}>前往重新计算 : undefined} /> setDrafting(null)} onOk={() => void saveDraft()}> @@ -691,7 +737,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
影响预览技术字段
{publicJson(impact)}
:
由服务端重新核对配置依赖…
} ; - return extraSections ? {void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));});}}}> : standardContent; + return extraSections ? {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;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('');});}}}> : standardContent; } function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit) { @@ -767,24 +813,23 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [items, setItems] = useState[]>([]); - const [loading, setLoading] = useState(true); + const [loaded, setLoaded] = useState(false); + const read = useDelayedBusy(); const loading = read.busy; const [dictionaryError, setDictionaryError] = useState(''); const [saving, setSaving] = useState(false); + const savingRef = useRef(false); const [editing, setEditing] = useState | null>(null); const [inspecting, setInspecting] = useState | null>(null); 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 load = async () => { - setLoading(true); - try { - const result = await api.metricDictionary(); - setItems(collectionItems(result)); setDictionaryError(''); - } catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); } - setLoading(false); - }; - useEffect(() => { void load(); }, []); + const load = useCallback(() => read.run(async () => { + try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); } + catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); } + }), [onUnauthorized, read.run]); + useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]); const openEditor = (item: Record) => { setEditing(item); @@ -795,7 +840,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna }); }; const save = async () => { - if (!editing) return; + if (!editing || savingRef.current) return; savingRef.current = true; try { const values = await form.validateFields(); 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 (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); - } finally { setSaving(false); } + } finally { savingRef.current = false; setSaving(false); } }; const columns: ColumnsType> = [ @@ -828,8 +873,8 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna useMaintenanceRefresh(load); return
指标术语字典维护展示名称与别名;计算公式在上方计算规则中维护
- {dictionaryError && } - {loading ?
读取术语定义…
: items.length ?
String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /> : !dictionaryError && } + {dictionaryError && void load()}>重试 : undefined} />} + {loading && !loaded ?
读取术语定义…
: loaded ? items.length ?
String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /> : : null} { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
@@ -851,6 +896,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite const [selected, setSelected] = useState | null>(null); const [issuesRunId, setIssuesRunId] = useState(''); const [busyId, setBusyId] = useState(''); + const actionLock = useRef(false); 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 runIdOf = (row: Record) => { @@ -859,6 +905,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite }; const retry = async (row: Record) => { const id = String(row.id || ''); if (!id) return; + if (actionLock.current) return; actionLock.current = true; setBusyId(id); try { const releases = await api.releases(); @@ -869,16 +916,17 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite else message.success(`任务重试完成:${toText(run.status || '已更新')}`); 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) => { const id = String(row.id || ''); if (!id) return; + if (actionLock.current) return; actionLock.current = true; setBusyId(id); try { await api.cancelTask(id, { expectedStatus: String(row.status || '') }); message.success('已取消排队任务'); 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 columns: ColumnsType> = [ @@ -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) => {importOnly && runIdOf(row) && } - {canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && } - {canCancel && String(row.status).toUpperCase() === 'QUEUED' && } + {canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && } + {canCancel && String(row.status).toUpperCase() === 'QUEUED' && } }, ]; return <> @@ -913,6 +961,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow const [renameTarget, setRenameTarget] = useState | null>(null); const [renameTitle, setRenameTitle] = useState(''); const [renaming, setRenaming] = useState(false); + const sessionMutationLock = useRef(false); const { active, initialSearch, refreshKey, onLocationChange } = usePageCache(); const activePage = useRef(active); activePage.current = active; 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 [sessionContext, setSessionContext] = useState | null>(null); const [sessions, setSessions] = useState[]>([]); + const [sessionsLoaded, setSessionsLoaded] = useState(false); + const sessionReadRequest = useRef | null>(null); const [turns, setTurns] = useState[]>([]); const [options, setOptions] = useState(null); 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 [queuedFollowup, setQueuedFollowup] = useState(''); const [stopping, setStopping] = useState(false); @@ -1052,22 +1108,33 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow }, [lastTurn, busy, turns, sessionId, active]); const loadSessions = async () => { - try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); } - catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); } + if (!mounted.current || !active || document.visibilityState !== 'visible') return; + 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(() => { - let alive = true; - api.options().then(value => { if (alive) setOptions(value); }) - .catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); }); - return () => { alive = false; }; - }, []); + if (!active || optionsRequestStarted.current) return; + optionsRequestStarted.current = true; + void optionsRead.run(async () => { + 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)); + useVisiblePolling(loadSessions, 5000, active && hasBackgroundTurns); + const wasActive = useRef(active); useEffect(() => { - if (!hasBackgroundTurns) return; - const timer = window.setInterval(() => void loadSessions(), 5000); - return () => window.clearInterval(timer); - }, [hasBackgroundTurns]); + if (active && !wasActive.current && hasBackgroundTurns) void loadSessions(); + wasActive.current = active; + }, [active, hasBackgroundTurns]); useEffect(() => { 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) => { + if (sessionMutationLock.current) return; sessionMutationLock.current = true; const generation = navigationGeneration.current; try { await api.deleteAnalysisSession(id); @@ -1237,17 +1305,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow message.success('会话已删除'); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除会话失败'); - } + } finally { sessionMutationLock.current = false; } }; const renameSession = async () => { - if (!renameTarget || !renameTitle.trim() || renaming) return; + if (!renameTarget || !renameTitle.trim() || sessionMutationLock.current) return; sessionMutationLock.current = true; setRenaming(true); try { await api.renameAnalysisSession(String(renameTarget.id), renameTitle.trim()); setRenameTarget(null); await loadSessions(); message.success('会话已重命名'); } 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) => { @@ -1367,31 +1435,36 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow }; useEffect(() => { + if (!active || restoreStarted.current) return; + restoreStarted.current = true; mounted.current = true; - let cancelled = false; const restore = async () => { const requestedAt = navigationGeneration.current; setHistoryLoading(true); try { const items = collectionItems(await api.analysisSessions()); - if (cancelled || requestedAt !== navigationGeneration.current) return; + if (!mounted.current || requestedAt !== navigationGeneration.current) return; setSessions(items); + setSessionsLoaded(true); let linkedSession = initialSessionId; if (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 || ''); if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配'); linkedSession ||= turnSession; } if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items); - if (!cancelled && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined); - } catch (value) { if (!cancelled && !onUnauthorized(value)) setError(apiMessage(value)); } - finally { if (!cancelled && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); } + if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined); + } catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); } + finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); } }; void restore(); + }, [active]); + useEffect(() => { + mounted.current = true; return () => { - cancelled = true; mounted.current = false; + mounted.current = false; navigationGeneration.current += 1; subscriptionGeneration.current += 1; // Unsubscribe from updates only. The accepted server task continues independently. streamController.current?.abort(); streamController.current = null; @@ -1589,17 +1662,19 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow return
- {error && void submit(retryQuestion)}>重试上一问} />} + {error && {retryQuestion && }} />} + {optionsError && { 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)); } }); }}>重试} />} + {!options && optionsRead.busy &&
读取分析选项…
}
: : null}
{ @@ -1758,23 +1833,24 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: } function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { + const { active } = usePageCache(); const [result, setResult] = useState(null); 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 load = async (nextPage = page) => { - setLoading(true); - try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setError(''); } + const load = useCallback((nextPage = page) => read.run(async () => { + try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setLoadedPage(nextPage); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); } - finally { setLoading(false); } - }; - useEffect(() => { void load(page); }, [page]); + }), [onUnauthorized, page, read.run]); + useEffect(() => { if (active && loadedPage !== page) void load(page); }, [active, loadedPage, page, load]); + useMaintenanceRefresh(() => { void load(page); }); const items = unwrapItems(result).items; const total = result?.total ?? items.length; return
- {error && } -
审计事件{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}
- {loading ?
正在读取…
: } + {error && void load(page)}>重试 : undefined} />} +
审计事件{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}
+ {loading && loadedPage !== page ?
正在读取…
: result && } {total > TABLE_PAGE_SIZE && `共 ${count} 条`} onChange={setPage} />}
; } @@ -1783,29 +1859,35 @@ const ROLE_OPTIONS = ['SYSTEM_ADMIN', 'QUALITY_VIEWER', 'BUSINESS_ANALYST', 'DAT function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [users, setUsers] = useState[]>([]); const [departments, setDepartments] = useState([]); const [groups, setGroups] = useState([]); - 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 [error, setError] = useState(''); + const saveLock = useRef(false); const [editing, setEditing] = useState | null>(null); 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 load = async () => { - setLoading(true); - try { - const [userResult, optionsResult] = await Promise.all([api.users(), api.options()]); - const rows = collectionItems(userResult); - setUsers(rows); - setDepartments(Array.from(new Set([...(optionsResult.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])]))); - setGroups(Array.from(new Set([...(optionsResult.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])]))); - setError(''); - } catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); } - finally { setLoading(false); } - }; - useEffect(() => { void load(); }, []); + const load = useCallback(() => read.run(async () => { + const [userResult, optionsResult] = await Promise.allSettled([api.users(), api.options()]); + const failures: string[] = []; + let rows = users; + if (userResult.status === 'fulfilled') { rows = collectionItems(userResult.value); setUsers(rows); setUsersLoaded(true); } + else if (!onUnauthorized(userResult.reason)) failures.push(`用户清单:${apiMessage(userResult.reason)}`); + if (optionsResult.status === 'fulfilled') { + setDepartments(Array.from(new Set([...(optionsResult.value.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])]))); + setGroups(Array.from(new Set([...(optionsResult.value.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])]))); + setOptionsLoaded(true); + } else if (!onUnauthorized(optionsResult.reason)) failures.push(`授权选项:${apiMessage(optionsResult.reason)}`); + setError(failures.join(';')); + }), [onUnauthorized, read.run, users]); + useEffect(() => { if (active && !usersLoaded) void load(); }, [active, usersLoaded, load]); + useMaintenanceRefresh(load); const openEditor = (record?: Record) => { setEditing(record || {}); @@ -1819,6 +1901,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor }; const save = async () => { + if (saveLock.current) return; saveLock.current = true; try { const values = await form.validateFields(); setBusy(true); @@ -1834,7 +1917,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); - } finally { setBusy(false); } + } finally { saveLock.current = false; setBusy(false); } }; const columns: ColumnsType> = [ @@ -1847,9 +1930,9 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor { title: '操作', key: 'actions', fixed: 'right', width: 110, align: 'center', render: (_, row) => canManage ? : 权限不足 }, ]; return
- {error && } + {error && void load()}>重试} />}
用户清单{users.length} 个账号{canManage && }
- {loading ?
正在读取用户与授权范围…
: users.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /> : } + {loading && !usersLoaded ?
正在读取用户与授权范围…
: usersLoaded ? users.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /> : : null} setEditing(null)} onOk={() => void save()}> @@ -1865,21 +1948,22 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor } function BasisPage({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { + const { active } = usePageCache(); const [rules, setRules] = useState[]>([]); const [ruleError, setRuleError] = useState(''); - const [loading, setLoading] = useState(true); - const load = async () => { - setLoading(true); - try { setRules(unwrapItems(await api.rules()).items); setRuleError(''); } + const [loaded, setLoaded] = useState(false); + const read = useDelayedBusy(); const loading = read.busy; + const load = useCallback(() => read.run(async () => { + try { setRules(unwrapItems(await api.rules()).items); setLoaded(true); setRuleError(''); } catch (value) { if (!onUnauthorized(value)) setRuleError(apiMessage(value)); } - finally { setLoading(false); } - }; - useEffect(() => { void load(); }, []); + }), [onUnauthorized, read.run]); + useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]); + useMaintenanceRefresh(load); return
} onClick={() => void load()}>刷新} />
-
指标规则{rules.length} 条
{ruleError && }{loading ?
: }
+
指标规则{rules.length} 条
{ruleError && void load()}>重试 : undefined} />}{loading && !loaded ?
: loaded && }
; } diff --git a/web/src/ManagementSections.tsx b/web/src/ManagementSections.tsx index ea14cdf..84d1e84 100644 --- a/web/src/ManagementSections.tsx +++ b/web/src/ManagementSections.tsx @@ -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 }) { 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; - return { setSelected(key); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: {item.children} }))} />; + const [visited, setVisited] = useState(() => new Set(activeKey ? [activeKey] : [])); + return { setSelected(key); setVisited(previous => new Set(previous).add(key)); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: {visited.has(item.key) ? item.children : null} }))} />; } diff --git a/web/src/NoCodeDataWorkflow.tsx b/web/src/NoCodeDataWorkflow.tsx index b5cca15..a973966 100644 --- a/web/src/NoCodeDataWorkflow.tsx +++ b/web/src/NoCodeDataWorkflow.tsx @@ -1,5 +1,5 @@ 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 { QualityTable as Table } from './QualityTable'; import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons'; @@ -7,7 +7,12 @@ import { api, collectionItems } from './api'; import type { AuthUser, SourceItem } from './types'; import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes'; import { useDataWorkflowOperation } from './useDataWorkflowOperation'; +import { detectSourceWorkbook } from './sourceWorkbookDetection'; 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'; type Row = Record; @@ -55,6 +60,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe const [activeId, setActiveId] = useState(''); const [reading, setReading] = useState<{ done: number; total: number } | null>(null); 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 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]; @@ -80,8 +86,9 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe 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 readFiles = async (files: File[]) => { - if (!files.length || importBusy) return; - if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); if (input.current) input.current.value = ''; return; } + if (!files.length || importBusy || actionLock.current) 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[] = []; 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; }); @@ -89,9 +96,8 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe for (let index = 0; index < selected.length; index += 2) { const results = await Promise.all(selected.slice(index, index + 2).map(async file => { try { - const result = await api.previewSourceWorkbook(file); - const scores = (['black', 'bright'] as DataStage[]).map(value => { const required = (options.fields[value] || []).filter(field => field.required); const matched = matchFields(options.fields[value] || [], result.preview.headers); return { stage: value, score: required.length ? required.filter(field => matched[field.name]).length / required.length : 0 }; }); - const detected = scores.sort((a, b) => b.score - a.score)[0].stage; + const uploaded = await api.previewSourceWorkbook(file); + const { workbook: result, stage: detected } = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview); const nextMonth = Number(file.name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/)?.[1] || new Date().getMonth() + 1); const nextYear = Number(file.name.match(/(20\d{2})年/)?.[1] || new Date().getFullYear()); return { id: crypto.randomUUID(), file, workbook: result, stage: detected, year: nextYear, month: nextMonth, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: matchFields(options.fields[detected] || [], result.preview.headers), mode: 'ADD' as const, targetId: '', scopeCode: options.scopes[0] || 'ALL' }; @@ -102,19 +108,19 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe setReading({ done: Math.min(index + 2, selected.length), total: selected.length }); } 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) => { - 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 previous = preferredMap || fieldMap; 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 () => { - if (!canImport || importBusy) return; setBusy(true); setError(''); + if (!canImport || importBusy || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); try { const sourceIds: string[] = []; 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); } 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 () => { + if (actionLock.current) return; actionLock.current = true; setError(''); try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); } catch (value) { reportError(value); } + finally { actionLock.current = false; } }; return
@@ -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 }) { const { message } = App.useApp(); + const { active } = usePageCache(); const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null); const [options, setOptions] = useState(null); const [workflowStatus, setWorkflowStatus] = useState(null); const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false); + const [workflowStatusError, setWorkflowStatusError] = useState(''); + const statusRead = useDelayedBusy(); + const optionsRead = useDelayedBusy(); + const candidatesRead = useDelayedBusy(); const [optionError, setOptionError] = useState(''); + const [candidateError, setCandidateError] = useState(''); const [candidates, setCandidates] = useState([]); + const [candidatesLoaded, setCandidatesLoaded] = useState(false); + const optionsAttempted = useRef(false); + const candidatesAttempted = useRef(false); const [resumeId, setResumeId] = useState(''); const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER']); const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']); - const loadOptions = async () => { + const loadOptions = useCallback(() => optionsRead.run(async () => { try { setOptions(await api.sourceUploadOptions()); setOptionError(''); } catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); } - }; - const loadWorkflowStatus = async () => { - try { setWorkflowStatus(await api.dataWorkflowStatus()); } - catch (error) { if (!onUnauthorized(error)) setWorkflowStatus(null); } - finally { setWorkflowStatusLoaded(true); } - }; - const loadCandidates = async () => { - try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); } - catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); } - }; - useEffect(() => { void loadOptions(); void loadCandidates(); void loadWorkflowStatus(); }, [currentReleaseId, sources]); + }), [onUnauthorized, optionsRead.run]); + const loadWorkflowStatus = useCallback(() => statusRead.run(async () => { + try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); } + catch (error) { if (!onUnauthorized(error)) setWorkflowStatusError(failure(error)); } + }), [onUnauthorized, statusRead.run]); + const loadCandidates = useCallback(() => candidatesRead.run(async () => { + try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); setCandidatesLoaded(true); setCandidateError(''); } + catch (error) { if (!onUnauthorized(error)) setCandidateError(failure(error)); } + }), [candidatesRead.run, onUnauthorized]); + useEffect(() => { + 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); }, []); const opened = mode !== null || Boolean(resumeId); - const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); void loadOptions(); }; - if (!workflowStatusLoaded) return
读取当前维护模式正在加载可执行操作
; + const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); if (!options) { optionsAttempted.current = true; void loadOptions(); } }; + if (!workflowStatusLoaded) return
{statusRead.busy ?
读取当前维护模式正在加载可执行操作
: workflowStatusError ? void loadWorkflowStatus()}>重试} /> : null}
; if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return ; return <>
@@ -217,39 +238,54 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
上传 → 选择年月 → 匹配列 → 校验 → 发布
- {optionError && { void loadOptions(); void loadCandidates(); }}>重试} />} + {optionError && { optionsAttempted.current = true; void loadOptions(); }}>重试} />} + {candidateError && { candidatesAttempted.current = true; void loadCandidates(); }}>重试} />} + {!options && optionsRead.busy &&
读取上传选项…
} + {!candidatesLoaded && candidatesRead.busy &&
读取候选数据…
} {!canMaintain && } - {candidates.length > 0 &&
待完成的数据已保存的候选可继续校验、对账和发布。
({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} />
} {opened && options && { 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 { active } = usePageCache(); const [showDeleted, setShowDeleted] = useState(false); const [deleted, setDeleted] = useState([]); + const [deletedLoaded, setDeletedLoaded] = useState(false); + const deletedRead = useDelayedBusy(); + const [metadataError, setMetadataError] = useState(''); + const metadataAttempted = useRef(false); const [workflowStatus, setWorkflowStatus] = useState(null); const [currentSourceIds, setCurrentSourceIds] = useState(null); - const [deletedLoading, setDeletedLoading] = useState(false); const [deletedError, setDeletedError] = useState(''); 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 canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER']); - const loadDeleted = async () => { - setDeletedLoading(true); - try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedError(''); } + const loadDeleted = useCallback(() => deletedRead.run(async () => { + try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); } catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); } - finally { setDeletedLoading(false); } - }; + }), [deletedRead.run, onUnauthorized]); const sourceOperation = useDataWorkflowOperation('source-maintenance', value => { onRefresh(); if (showDeleted) void loadDeleted(); 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(() => { - void api.dataWorkflowStatus().then(setWorkflowStatus).catch(() => setWorkflowStatus(null)).finally(() => setWorkflowStatusLoaded(true)); - void api.sourceUploadOptions().then(options => setCurrentSourceIds(options.currentSourceIds || [])).catch(() => setCurrentSourceIds(null)); - }, [sources]); - useEffect(() => { if (showDeleted && canOperate) void loadDeleted(); }, [showDeleted, sources]); + if (!active || metadataAttempted.current) return; + metadataAttempted.current = true; + void loadMetadata(); + }, [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 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'; @@ -262,9 +298,10 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件${pendingIds.length ? ` · ${pendingIds.length} 个待删除` : ''}` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}{canOperate && setShowDeleted(event.target.checked)}>查看已删除来源}
{simplified &&

删除先标记为待删除,可连续操作和撤销,点击上方“更新报表”后统一生效。原文件和处理记录保留。

} {simplified && pendingIds.length > 0 &&
} - {deletedError && void loadDeleted()}>重试} />} + {deletedError && void loadDeleted()}>重试} />} + {metadataError && { metadataAttempted.current = true; setMetadataError(''); void loadMetadata(); }}>重试} />} {sourceOperation.operation && } - 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)) ? 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: 'stage', key: 'stage', align: 'center', width: 90, render: value => {stageName(value)} }, { 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; return ; } }, - ]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> + ]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null}
{selected && !simplified && { 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 }) { - const { message } = App.useApp(); + const { message } = App.useApp(); const { active } = usePageCache(); const [preview, setPreview] = useState(null); 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 [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState(null); const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID()); - const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }; - 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); } }; - useEffect(() => { void load(); }, [sourceId]); + const actionLock = useRef(false); const candidateLock = useRef(false); + const showBusy = useDelayedIndicator(busy, 150); + 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 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; @@ -303,7 +342,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz const actualRestore = Boolean((restoring || preview?.hidden) && !finished); const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由'; 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 { 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 }); @@ -325,12 +364,12 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz } setReason(''); setConfirmed(false); onRefresh(); } catch (value) { reportError(value); } - finally { setBusy(false); } + finally { actionLock.current = false; setBusy(false); } }; 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); } - catch (value) { reportError(value); } finally { setBusy(false); } + catch (value) { reportError(value); } finally { candidateLock.current = false; setBusy(false); } }; const handoff = async () => { 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 {actualRestore ? : isRequested ? <>{canReview && <>} : isApproved ? : isBuilt ? : } }
}> - {error && } + {error && void load()}>重试 : undefined} />} {notice && } - {preview ? <> + {preview ? <>
{preview.source.sourceFile}{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}
{withdrawing && !actualRestore && }
当前正式数据{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}
归档来源记录{preview.history.revisionCount} 个
正式处理记录{preview.history.publishedReleaseCount} 个
候选处理记录{preview.history.candidateReleaseCount} 个
@@ -358,97 +397,145 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz } {waitingForColleague && !awaitingTask && {preview.blockedReason &&

{preview.blockedReason}

}可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。} />} {!finished && isBuilt && } - : !busy ? :
正在核对来源及影响…
}
+ : showBusy ?
正在核对来源及影响…
: null}
{candidateId && options && { 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 }) { - const { message } = App.useApp(); const input = useRef(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID()); - const [pollAttempt, setPollAttempt] = useState(0); - const [step, setStep] = useState(resumeId ? 4 : 0); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); + const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID()); + const runStorageKey = `quality-import-run:${user.id}`; + 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(null); const [stage, setStage] = useState('black'); 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 [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState>({}); const [configuredSourceId, setConfiguredSourceId] = useState(''); - const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState(null); const [release, setRelease] = useState(null); + const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState(() => storedRunId ? { id: storedRunId, status: 'RUNNING' } : null); const [release, setRelease] = useState(null); + const [runTerminalId, setRunTerminalId] = useState(''); + const completionNotified = useRef(new Set()); + const actionLock = useRef(false); const pollLock = useRef(false); const pollAgainAfterCurrent = useRef(false); const candidateReadLock = useRef(false); + const runIdRef = useRef(''); const [reconciliation, setReconciliation] = useState(null); const [issues, setIssues] = useState([]); 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 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 reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }; - const loadCandidate = async (id: string) => { - const inspected = await api.governanceReleaseInspect(id); setRelease(asRow(inspected.release)); - const result = await api.governanceReleaseReconciliations(id); const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0]; - setReconciliation(selected?.id ? await api.governanceReconciliation(String(selected.id)) : null); + const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]); + const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => { + if (!activeRef.current || !isCurrent()) return false; + const inspected = await api.governanceReleaseInspect(id); + 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(() => { - if (!runId) return; - let alive = true; let timer: ReturnType; - const poll = async () => { - try { - const result = await api.importRun(runId); if (!alive) return; setRun(result.run); - if (String(result.run.status) === 'COMPLETED') { - const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据'); - await loadCandidate(id); if (!alive) return; setStep(4); setBusy(false); onComplete(); - if (asRow(result.run.validation).complete === false) { const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList)); } - } else if (['FAILED', 'CANCELLED'].includes(String(result.run.status))) { - setBusy(false); const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList)); - } else timer = setTimeout(poll, 1400); - } catch (value) { if (alive) { reportError(value); setBusy(false); } } - }; - timer = setTimeout(poll, 700); return () => { alive = false; clearTimeout(timer); }; - }, [runId, pollAttempt]); + if (!active || !resumeId || candidateReadLock.current) return; + candidateReadLock.current = true; setBusy(true); + loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); }); + return () => { generation.current++; }; + }, [active, reportError, resumeId]); + const runId = String(run?.id || ''); + runIdRef.current = runId; + const pollRun = useCallback(async () => { + if (!activeRef.current || !runId) return; + if (pollLock.current) { pollAgainAfterCurrent.current = true; return; } + pollLock.current = true; + try { + const result = await api.importRun(runId); + const isCurrent = () => activeRef.current && runIdRef.current === runId; + if (!isCurrent()) return; + 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) => { - 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); } - 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) => { - 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))) }); } - 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 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(''); 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 }); 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); 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); } + finally { actionLock.current = false; } }; const rebuild = async () => { + if (!active || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); setStep(3); try { if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源'); 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); 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); } + finally { actionLock.current = false; } }; 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); } - catch (value) { reportError(value); } finally { setBusy(false); } + catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); } }; 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); } - catch (value) { reportError(value); } finally { setBusy(false); } + catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); } }; 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(); } - 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 publishReady = release?.complete === true && reconciliation?.publishReady === true; @@ -456,13 +543,13 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, const close = () => { generation.current++; onClose(); }; return {runId ? '关闭后任务继续,可在“数据接入”的“导入记录”查看;完成后从候选继续。' : '确认发布前,当前查询结果保持不变。'}
{step > 0 && step < 4 && !runId && !configuredSourceId && !busy && }{!published && step === 1 && }{!published && step === 2 && }{!published && step === 3 && !runId && mode !== 'REBUILD' && }
}> ({ title }))} /> - {error && } + {error && { if (!activeRef.current || candidateReadLock.current) return; candidateReadLock.current = true; setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); }); }}>重试读取候选 : runId ? : undefined} />} {published ?

{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}

来源原件和本次对账记录均已保留。

: <> {step === 0 && (mode === 'REBUILD' ?

使用当前数据所用的全部来源重新计算

计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。

{options.targets.map(item =>
{stageName(item.stage)}{item.year}年{item.month}月{item.sourceFile}
)}
:

选择要{mode === 'REPLACE' ? '替换' : '上传'}的 Excel 文件

支持 .xlsx;保留你的文件名,接下来选择数据期间和表头。

void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" />
)} {workbook && step > 0 && step < 4 &&
{workbook.sourceFile}{stageName(stage)} · {year}年{month}月
} {step === 1 &&
{mode === 'REPLACE' ? { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /> { if (value) setYear(value); }} /> ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} />}}
{target &&
原文件{target.sourceFile}新文件{workbook?.sourceFile}
} setReason(event.target.value)} />} {step === 2 && workbook && <>
`${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(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(';') || '一致' }]} /> : }{reconciliation?.status === 'REVIEW_REQUIRED' &&
{canPublish ? <> setDifferenceReason(event.target.value)} /> setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确 :

候选已保存,请交由有数据发布权限的同事完成差异确认。

}
}{canPublish ?
setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}{!publishReady && 来源校验和基线对账通过后可发布。}
: 当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。} />}} {issues.length > 0 && <>

需要处理的来源行

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>({}); 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(null); + const actionLock = useRef(false); const [preparedDefinition, setPreparedDefinition] = useState(null); const [preparedReleaseId, setPreparedReleaseId] = useState(null); 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)); }; const readFile = async (file?: File) => { - if (!file) return; setBusy(true); setError(''); + if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); try { const response = await api.previewMasterWorkbook(file); setPreview(response); 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)); setResult(null); setConfirmed(false); } 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 () => { - if (!preview || !base || !sheet) return; setBusy(true); setError(''); + if (!preview || !base || !sheet || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); try { if (simplified && preparedDefinition) { 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(); } 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]))); return <> diff --git a/web/src/PersonalAccount.tsx b/web/src/PersonalAccount.tsx index 1d5b789..806b9d0 100644 --- a/web/src/PersonalAccount.tsx +++ b/web/src/PersonalAccount.tsx @@ -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 { api } from './api'; import type { AuthUser } from './types'; @@ -20,6 +20,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn const [form] = Form.useForm(); const [activeTab, setActiveTab] = useState('profile'); const [busy, setBusy] = useState(false); + const savingRef = useRef(false); const [error, setError] = useState(''); const forced = user.forcePasswordChange === true; const open = tab !== null || forced; @@ -29,6 +30,8 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn }, [open, tab, forced, form]); const save = async (values: PasswordValues) => { + if (savingRef.current) return; + savingRef.current = true; setBusy(true); setError(''); try { await api.changePassword(values.currentPassword, values.newPassword); @@ -38,7 +41,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn message.success('密码已修改,下次登录请使用新密码'); } catch (failure) { if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试'); - } finally { setBusy(false); } + } finally { savingRef.current = false; setBusy(false); } }; return { let alive = true; + // Fetch only the selected page's code while identity validation runs; data stays gated. + void preloadWorkspacePage(pageFromLocation()).catch(() => {}); (async () => { try { await api.refreshCsrf(); diff --git a/web/src/QueryPage.tsx b/web/src/QueryPage.tsx index 14756ec..dcf34d0 100644 --- a/web/src/QueryPage.tsx +++ b/web/src/QueryPage.tsx @@ -1,9 +1,12 @@ +import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope'; import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion'; import { trendBarPalette } from './trendBarPalette'; import { getWorkspaceTheme } from './ui-themes'; import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues'; import { BusinessValue } from './BusinessValue'; import { usePageCache } from './pageCache'; +import { useDelayedIndicator } from './useDelayedBusy'; +import { useResourceVisibility } from './useResourceVisibility'; import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react'; import * as echarts from 'echarts/core'; import { BarChart, LineChart } from 'echarts/charts'; @@ -153,6 +156,7 @@ function monthNumber(value: number | string): number | null { return result >= 1 && result <= 12 ? result : null; } + function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] { if (granularity === 'year') return rows; const byPeriod = new Map(); @@ -228,16 +232,7 @@ function escapeTooltipText(value: string): string { } export function queryFromLocation(search = window.location.search): Partial { - 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) }; - delete query.releaseId; - return query; - } catch { return {}; } + return readQueryLocation(search); } function toApiParams(args: { @@ -291,7 +286,7 @@ export default function QueryPage({ page, onUnauthorized }: { onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void; }) { const { message } = App.useApp(); - const { active, initialSearch, refreshKey, onLocationChange } = usePageCache(); + const { active, initialSearch, refreshKey, onLocationChange, currentReleaseId } = usePageCache(); const baseView = SCOPE[page] || 'overall'; const [initialQuery] = useState(() => queryFromLocation(initialSearch)); 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 [errorKey, setErrorKey] = useState(''); const [queryRevision, setQueryRevision] = useState(0); + const [trendRevision, setTrendRevision] = useState(0); const [selectedRecord, setSelectedRecord] = useState(null); const [recordsOpen, setRecordsOpen] = useState(false); const [recordStage, setRecordStage] = useState('black'); @@ -361,8 +357,10 @@ export default function QueryPage({ page, onUnauthorized }: { useEffect(() => { + if (!active) return; let alive = true; - api.options().then(result => { + const controller = new AbortController(); + api.options(controller.signal).then(result => { if (!alive) return; setOptions(result); if (automaticPeriod.current) { @@ -375,8 +373,8 @@ export default function QueryPage({ page, onUnauthorized }: { if (onUnauthorized(errorValue)) return; if (alive) setOptionsError(chooseError(errorValue)); }).finally(() => { if (alive) setOptionsLoading(false); }); - return () => { alive = false; }; - }, [onUnauthorized, queryRevision]); + return () => { alive = false; controller.abort(); }; + }, [active, onUnauthorized, queryRevision]); const allowedGroups = useMemo(() => { 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]; return [exactProductSearch]; }, [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 drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned }); useEffect(() => { @@ -420,7 +418,6 @@ export default function QueryPage({ page, onUnauthorized }: { const queryBusy = loading || queryPending; const metricKeyRef = useRef(metricKey); metricKeyRef.current = metricKey; - const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month'; const trendParams = useMemo(() => { const params = applyTrendObject(queryParams, trendObject, view); delete params.month; @@ -438,7 +435,7 @@ export default function QueryPage({ page, onUnauthorized }: { if (!active) return; const url = new URL(window.location.href); 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 = ''; for (const byte of bytes) binary += String.fromCharCode(byte); const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); @@ -448,7 +445,7 @@ export default function QueryPage({ page, onUnauthorized }: { }, [queryKey, active]); useEffect(() => { - if (optionsLoading) return; + if (!active || optionsLoading || optionsError) return; const controller = new AbortController(); setLoading(true); setError(''); @@ -457,10 +454,6 @@ export default function QueryPage({ page, onUnauthorized }: { if (controller.signal.aborted || metricKeyRef.current !== metricKey) return; setData(result); setDataKey(metricKey); - if (useSummaryTrend && trendKeyRef.current === trendKey) { - setTrendData(Array.isArray(result.trend) ? result.trend : []); - setTrendDataKey(trendKey); - } setError(''); setErrorKey(''); }).catch(errorValue => { @@ -470,9 +463,10 @@ export default function QueryPage({ page, onUnauthorized }: { setErrorKey(metricKey); }).finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); - }, [metricKey, queryRevision, onUnauthorized, optionsLoading]); + }, [active, metricKey, queryRevision, onUnauthorized, optionsLoading, optionsError]); useEffect(() => { + if (!active) return; if (!trendObject || defectQueryKey === queryKey) { setTrendObjectMetrics(null); setTrendObjectMetricsLoading(false); @@ -491,18 +485,14 @@ export default function QueryPage({ page, onUnauthorized }: { }) .finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); }); return () => controller.abort(); - }, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]); + }, [active, trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]); useEffect(() => { - if (optionsLoading) return; + if (!active || optionsLoading || optionsError) return; setTrendFailure(null); - if (useSummaryTrend) { - setTrendLoading(false); - return; - } const controller = new AbortController(); setTrendLoading(true); - api.metrics(trendParams, controller.signal).then(result => { + api.trend(trendParams, controller.signal).then(result => { if (controller.signal.aborted || trendKeyRef.current !== trendKey) return; setTrendData(Array.isArray(result.trend) ? result.trend : []); setTrendDataKey(trendKey); @@ -511,9 +501,10 @@ export default function QueryPage({ page, onUnauthorized }: { if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) }); }).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); }); return () => controller.abort(); - }, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, optionsLoading]); + }, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]); useEffect(() => { + if (!active || optionsLoading || optionsError) return; let alive = true; setTrendTarget(null); setTrendTargetKey(''); @@ -532,14 +523,15 @@ export default function QueryPage({ page, onUnauthorized }: { } }); return () => { alive = false; }; - }, [trendKey, queryRevision, onUnauthorized]); + }, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]); const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null; const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]); 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 renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget; const drilledTrendData = useMemo( @@ -585,7 +577,7 @@ export default function QueryPage({ page, onUnauthorized }: { view: drilledProduct ? 'overall' as const : view, layoutView: drilledProduct ? 'product' as const : view, period: drilledProduct ? 'year' as const : period, - year, month, quarter, drilledProduct, + year, month, quarter, drilledProduct, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}), } : null); const tableRows = retainedTable?.rows || []; const tablePeriod = retainedTable?.period || period; @@ -755,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: { } - {currentMetricsError && } onClick={() => setQueryRevision(value => value + 1)}>重试} />} + {currentMetricsError && } onClick={() => setQueryRevision(value => value + 1)}>重试} />} {drilledProduct && summaryMetricsError && setQueryRevision(value => value + 1)}>重试} />}
setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" />
@@ -776,12 +768,12 @@ export default function QueryPage({ page, onUnauthorized }: { defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject} objects={trendOptions} scopeName={scopeName} stageSwitch={ setTrendStage(value as Stage)} aria-label="趋势阶段" />}> - {currentTrendError && setQueryRevision(value => value + 1)}>重试} />} + {currentTrendError && setTrendRevision(value => value + 1)}>重试} />}
{trendMode === 'data' ? : } - {trendRefreshing && 正在更新趋势} + {showTrendLoading && {retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}}
@@ -792,7 +784,7 @@ export default function QueryPage({ page, onUnauthorized }: { fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && } {drilledProduct && }} - 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 () => { setSummaryExporting(true); try { await summaryExport.current?.exportExcel(); } @@ -802,6 +794,7 @@ export default function QueryPage({ page, onUnauthorized }: { { + if (!active || !visible) return; if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; } const controller = new AbortController(); 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); }); return () => controller.abort(); - }, [releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]); + }, [active, visible, releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]); useEffect(() => { const refresh = () => setThemeRevision(value => value + 1); @@ -1049,7 +1045,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna }, [items, totalWeight, themeRevision, active]); return
-
{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}{loading && 正在更新}
+
{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}{showLoading && 正在更新}
{error && } {!loading && !releaseId && } {!loading && !error && responses && !items.length && } @@ -1078,10 +1074,10 @@ const totalWeightTitle = (label: string) => {onBasis ? : label}{basis !== 'original' && (去本部报废)}{basis !== 'original' && {kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。
}原口径:亮片合格重量÷亮片总重量。
去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。
当前:去本部报废。计算结果以已发布数据版本及生效规则为准。}>
}
; 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 }>; 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'; onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void; 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 [currentPage, setCurrentPage] = useState(1); 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; - useEffect(() => setCurrentPage(1), [rows]); + useEffect(() => setCurrentPage(1), [paginationScope ?? rows]); const columnWidth = (column: ColumnsType[number]): number => { if ('children' in column && column.children?.length) { 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 pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize); return
size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} /> - {pageSizeOverride == null && { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />} + {pageSizeOverride == null && { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
; } @@ -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 }) { const { active } = usePageCache(); const container = useRef(null); + const visible = useResourceVisibility(container, active); const chart = useRef | null>(null); const onMonthRef = useRef(onMonth); const rowsRef = useRef(rows); @@ -1228,7 +1225,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP }, []); 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 }); chart.current = instance; graphicIds.current.clear(); @@ -1260,7 +1257,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP }); observer.observe(container.current); return () => { observer.disconnect(); instance.dispose(); chart.current = null; }; - }, [hasRows, refreshBarMasks, active]); + }, [hasRows, refreshBarMasks, visible]); useEffect(() => { 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 }); 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; @@ -1420,7 +1417,7 @@ export function RecordsDrawer({ query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean; }) { const { message } = App.useApp(); - const { refreshKey } = usePageCache(); + const { active, refreshKey } = usePageCache(); const recordPages = useRef(new Map()); const [page, setPage] = useState(1); 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 error = failure?.key === requestKey ? failure.message : ''; const fetching = loading || !result && !error; + const retainedResult = useRetainedResult(result); + const showRecordLoading = useDelayedIndicator(fetching && open); useEffect(() => { - if (!open) return; + if (!open || !active) return; const cached = recordPages.current.get(requestKey); if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; } const controller = new AbortController(); setLoading(true); - setResponse(null); setFailure(null); + setFailure(null); api.records(requestParams, controller.signal).then(value => { if (controller.signal.aborted) return; 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) }); }).finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); - }, [open, requestKey, revision, onUnauthorized]); + }, [open, active, requestKey, revision, onUnauthorized]); const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8); const exportRecords = async () => { @@ -1536,7 +1535,7 @@ export function RecordsDrawer({ ]; return 来源明细 {row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}} destroyOnClose> -
{ onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" />{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}
+
{ onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" />{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}
{ setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
- {error && setRevision(value => value + 1)}>重试} />} - {fetching ?
正在读取来源行…
: result?.rows.length ?
: } + {error && setRevision(value => value + 1)}>重试} />} + {showRecordLoading &&
{retainedResult ? '正在更新,当前显示上次来源结果' : <>正在读取来源行…}
} +
+ {retainedResult?.rows.length ?
: !fetching && !error && } + {result && result.total > result.pageSize && `共 ${total} 条`} onChange={next => setPage(next)} />} ; } diff --git a/web/src/QueryResultMotion.tsx b/web/src/QueryResultMotion.tsx index 25f6d10..a6aedd4 100644 --- a/web/src/QueryResultMotion.tsx +++ b/web/src/QueryResultMotion.tsx @@ -55,13 +55,13 @@ export function SmoothTableFrame({ children, busy, blocked }: { children: ReactN useLayoutEffect(() => { const node = content.current; if (!node) return; - const measure = () => setHeight(node.offsetHeight); + const measure = () => { if (node.offsetHeight > 0) setHeight(node.offsetHeight); }; measure(); const observer = new ResizeObserver(measure); observer.observe(node); 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
{children}
; diff --git a/web/src/StageProductPage.tsx b/web/src/StageProductPage.tsx index aaa71f4..bace554 100644 --- a/web/src/StageProductPage.tsx +++ b/web/src/StageProductPage.tsx @@ -1,3 +1,4 @@ +import { loadedQueryScope, queryForLocation } from './queryLoadingScope'; import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion'; import { queryScrapWeight } from './queryMetricValues'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -8,10 +9,11 @@ import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHea import { StageSourceFilters } from './StageSourceFilters'; import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery'; import { usePageCache } from './pageCache'; +import { useDelayedIndicator } from './useDelayedBusy'; import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults'; import { readableSelectPopup } from './readableSelectPopup'; 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 { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection'; 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 rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—'; 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 automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter); const [period,setPeriod]=useState(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 [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef(''); 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}>(null);const [exporting,setExporting]=useState(false); const label=stage==='black'?'黑片':'亮片'; + const supportGeneration=useRef(0);const supportController=useRef(null); const loadSupport=useCallback(async()=>{ + const generation=++supportGeneration.current;supportController.current?.abort();const controller=new AbortController();supportController.current=controller; 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);} - catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');} - finally{setSupportLoading(false);} - },[onUnauthorized]); - useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]); + 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(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');} + finally{if(generation===supportGeneration.current)setSupportLoading(false);} + },[onUnauthorized,initial.releaseId,currentReleaseId]); + 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 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]); 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. 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:''; @@ -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);}); return()=>controller.abort(); },[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 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 displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend; 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 displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null); const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]); - const trendRefreshing=trendLoading||!current||trendResponse?.key!==trendKey; - const tableReady=!!current&&(!drilledProduct||!trendRefreshing); + const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey); + 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 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}: {})}});}; @@ -110,7 +115,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU {catalog&&} } - {error&&setRevision(v=>v+1)}>重试}/>} + {error&&setRevision(v=>v+1)}>重试}/>}
{stage==='bright'&&
setRateBasis(v as typeof rateBasis)}/>
} setBasisOpen(true)}/> @@ -121,12 +126,12 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
- {trendError&&setRevision(v=>v+1)}>重试}/>} + {trendError&&setTrendRevision(v=>v+1)}>重试}/>}
{trendMode==='data' ? : } - {trendRefreshing&&正在更新趋势} + {showTrendLoading&&{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}}
} @@ -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()}> setBasisOpen(true)} diff --git a/web/src/StageSourceFilters.tsx b/web/src/StageSourceFilters.tsx index aff60cc..a5a2f03 100644 --- a/web/src/StageSourceFilters.tsx +++ b/web/src/StageSourceFilters.tsx @@ -1,3 +1,5 @@ +import { usePageCache } from './pageCache'; +import { useDelayedIndicator } from './useDelayedBusy'; import { useEffect, useRef, useState } from 'react'; import { Alert, Button, Select, Spin } from 'antd'; 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}) { const [search,setSearch]=useState('');const [choices,setChoices]=useState([]);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); useEffect(()=>{ + if(!active)return; const generation=++current.current,controller=new AbortController();setBusy(true);setError('');setChoices([]); const timer=window.setTimeout(()=>{ 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);}); },search?300:0); return()=>{window.clearTimeout(timer);controller.abort();current.current++;}; - },[field.key,stage,contextKey,search,revision,onUnauthorized]); - return {onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={showBusy?:error?:'暂无匹配值'} popupRender={menu=><>{menu}{more&&
输入关键词搜索更多值
}{error&&
{error}
}}/>; } 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)=>onChange(value.map(rule=>rule.field===key?{...rule,...change}:rule)); diff --git a/web/src/TasksMonitorPage.tsx b/web/src/TasksMonitorPage.tsx index 53531b6..f615992 100644 --- a/web/src/TasksMonitorPage.tsx +++ b/web/src/TasksMonitorPage.tsx @@ -10,6 +10,8 @@ import type { AuthUser } from './types'; import { BackupOperationsPanel, OperationsMonitorPanel } from './GovernanceCompletion'; import { configurationDateTime } from './configurationName'; 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}) { const {message}=App.useApp(); @@ -18,29 +20,35 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor const [items,setItems]=useState([]); const [backup,setBackup]=useState({}); const [taskError,setTaskError]=useState(''); const [backupError,setBackupError]=useState(''); - const [loading,setLoading]=useState(true); - const loaded = useRef(false); + const [tasksLoaded,setTasksLoaded]=useState(false); const [backupLoaded,setBackupLoaded]=useState(false); const [section,setSection] = useState('tasks'); + const taskBusy = useDelayedBusy(); const backupBusy = useDelayedBusy(); + const loading = sectionLoading(); const [filter,setFilter]=useState('all'); const [selected,setSelected]=useState(null); + const actionInFlight = useRef(false); const canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role)); - const load=useCallback(async()=>{ - setLoading(true); - await Promise.all([ - api.taskOverview().then(value=>{setItems(value.items);setTaskError('');}).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:'备份状态读取失败');}), - ]);setLoading(false); - },[onUnauthorized]); - useEffect(()=>{if(!loaded.current){loaded.current=true;void load();}},[load]); + function sectionLoading() { return section === 'tasks' ? taskBusy.busy : backupBusy.busy; } + const loadTasks=useCallback(()=>taskBusy.run(async()=>{ + try { const value=await api.taskOverview();setItems(value.items);setTaskError('');setTasksLoaded(true); } + catch(error){ if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败'); } + }),[onUnauthorized,taskBusy.run]); + const loadBackup=useCallback(()=>backupBusy.run(async()=>{ + try { const value=await api.latestBackup();setBackup(value);setBackupError('');setBackupLoaded(true); } + 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); - 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')=>{ + if(actionInFlight.current)return; actionInFlight.current=true; setBusy(true); try { 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)}); message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load(); } 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 columns:ColumnsType=[ @@ -54,13 +62,14 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
任务进度
`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:}}/>} + {taskError&&void loadTasks()}>重试:undefined}/>} + {loading&&!tasksLoaded?:tasksLoaded&&
`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:}}/>}

每类最多显示 50 条记录,进行中及失败任务优先。智能分析仅显示本人任务。

}, { key:'latestBackup', label:'最近备份', children: <>
最近备份状态
- {backupError?:loading&&!latest.createdAt?:
最近备份{backupSummary(latest)}
备份时间{configurationDateTime(latest.createdAt)||'—'}
恢复验证时间{configurationDateTime(latest.restoreVerifiedAt)||'—'}
自动备份{backup.planActive===true?'已启用':'未启用'}
} + {backupError&&void loadBackup()}>重试:undefined}/>} + {loading&&!backupLoaded?:backupLoaded&&
最近备份{backupSummary(latest)}
备份时间{configurationDateTime(latest.createdAt)||'—'}
恢复验证时间{configurationDateTime(latest.restoreVerifiedAt)||'—'}
自动备份{backup.planActive===true?'已启用':'未启用'}
}
}, ...(canManage ? [{ key:'monitor', label:'运行监控与告警', children: },{ key:'backups', label:'备份管理', children: }] : []), diff --git a/web/src/api.ts b/web/src/api.ts index 8640229..698892c 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1,7 +1,15 @@ import { WORKSPACE_INVALIDATED } from './pageCache'; import { consumeEventStream, type StreamEvent } from './eventStream'; import { publicErrorMessage } from './publicDataDisplay'; -import { RequestTimeoutError, withRequestDeadline } from './requestDeadline'; +import { + clearReadCache, + configureRequestScope, + coordinateRequest, + getRequestDiagnostics, + invalidateReadResources, + resetRequestScope, + type CoordinatedResult, +} from './requestCoordinator'; import type { AuthUser, FilterField, @@ -9,6 +17,7 @@ import type { Collection, FineDefectTopResponse, MetricsResponse, + TrendResponse, OptionsResponse, QueryParams, RecordExportParams, @@ -17,6 +26,8 @@ import type { } from './types'; import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes'; +export { configureRequestScope, getRequestDiagnostics, invalidateReadResources, resetRequestScope }; + export class ApiError extends Error { status: number; details: unknown; @@ -39,8 +50,9 @@ async function fetchApi(path: string, init: RequestInit): Promise { } } -async function readResponse(response: Response): Promise { +async function readResponse(response: Response): Promise> { const raw = await response.text(); + const responseBytes = new TextEncoder().encode(raw).byteLength; let payload: unknown; if (raw) { try { @@ -61,43 +73,83 @@ async function readResponse(response: Response): Promise { : typeof payload === 'string' && payload.trim() ? payload : `请求失败(${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, '服务返回格式异常,请稍后重试。'); - return payload as T; + if (typeof payload === 'string') { + 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(path: string, init: RequestInit = {}, timeoutMs?: number): Promise { +export async function request(path: string, init: RequestInit = {}, timeoutMs?: number): Promise { const headers = new Headers(init.headers); if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json'); - const send = async (signal = init.signal) => { - const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' }); - return readResponse(response); - }; - if (!timeoutMs) return send(); - try { return await withRequestDeadline(signal => send(signal), timeoutMs); } + const method = (init.method ?? 'GET').toUpperCase(); + try { + return await coordinateRequest({ + url: path, + method, + 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(response); + }, + }); + } 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; } } async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> { - const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal }); - 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 : undefined; - const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`; - throw new ApiError(response.status, message, payload); + try { + return await coordinateRequest({ + url: path, + method: 'GET', + signal, + timeoutMs: 900_000, + queue: false, + 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 : 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'; @@ -105,16 +157,21 @@ export type { StreamEvent } from './eventStream'; async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise { const headers = new Headers({ Accept: 'text/event-stream' }); 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 }); - 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 : undefined; - throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload); + try { + const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal }); + 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 : 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 { @@ -131,7 +188,7 @@ async function mutate(path: string, body?: unknown, method = 'POST', timeoutM headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }, 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; } @@ -142,17 +199,17 @@ async function queryPost(path: string, body: unknown, signal?: AbortSignal): async function mutateForm(path: string, body: FormData): Promise { const token = csrfToken ?? await refreshCsrf(); - const result = await request(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }); - window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); + const result = await request(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }, 900_000); + invalidateAfterMutation(path); return result; } 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, signal?: AbortSignal) { return queryPost<{values:Array;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); }, - workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state', {}, 8000); }, - filterFields(manage = false) { return request(`/api/filter-fields?manage=${manage}`); }, - filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); }, + workspaceState() { return request<{ authRevision: string; dataRevision: string; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); }, + filterFields(manage = false, signal?: AbortSignal) { return request(`/api/filter-fields?manage=${manage}`, { signal }); }, + filterFieldOptions(key: string, search = '', signal?: AbortSignal) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`, { signal }); }, filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); }, saveFilterFields(fields: FilterField[]) { return mutate('/api/filter-fields', fields, 'PUT'); }, refreshCsrf, @@ -160,17 +217,20 @@ export const api = { const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000); 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 }); }, - logout() { - return mutate('/api/auth/logout'); + async logout() { + try { return await mutate('/api/auth/logout'); } + finally { csrfToken = undefined; resetRequestScope(); } }, changePassword(currentPassword: string, newPassword: string) { return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword }); }, - options() { - return request('/api/options'); + options(signal?: AbortSignal) { + return request('/api/options', { signal }); }, referenceNames() { return request>('/api/options/reference-names'); @@ -178,6 +238,9 @@ export const api = { metrics(params: QueryParams, signal?: AbortSignal) { return request(`/api/metrics?${toQuery(params)}`, { signal }); }, + trend(params: QueryParams, signal?: AbortSignal) { + return request(`/api/metrics/trend?${toQuery(params)}`, { signal }); + }, fineDefectTop(params: Record, signal?: AbortSignal) { return queryPost('/api/analysis/defects', params, signal); }, @@ -690,6 +753,113 @@ function toQuery(values: object): string { 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~'; /** Encodes multiple selected values into the scalar query wire format understood by the API. */ diff --git a/web/src/governanceTabResources.ts b/web/src/governanceTabResources.ts new file mode 100644 index 0000000..0f20f2d --- /dev/null +++ b/web/src/governanceTabResources.ts @@ -0,0 +1,26 @@ +export type GovernanceResource = 'coverage' | 'protocols' | 'changes' | 'candidates' | 'documents'; +export type GovernanceFreshness = Partial>; + +export const GOVERNANCE_RESOURCES: GovernanceResource[] = ['coverage', 'protocols', 'changes', 'candidates', 'documents']; + +const TAB_RESOURCES: Record = { + 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 }); +} diff --git a/web/src/importLifecycleGuards.ts b/web/src/importLifecycleGuards.ts new file mode 100644 index 0000000..2575cc2 --- /dev/null +++ b/web/src/importLifecycleGuards.ts @@ -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( + runId: string, + isCurrent: (runId: string) => boolean, + followup: () => Promise, +): 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 }; +} diff --git a/web/src/pageCache.tsx b/web/src/pageCache.tsx index a3ec82a..f09743a 100644 --- a/web/src/pageCache.tsx +++ b/web/src/pageCache.tsx @@ -1,7 +1,12 @@ import { createContext, useContext, useEffect, useRef } from 'react'; 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({ active: true, refreshKey: 0, onLocationChange: () => {} }); export const usePageCache = () => useContext(PageCacheContext); /** Revalidate retained maintenance data on a real revision change, not on every visit. */ diff --git a/web/src/queryLoadingScope.ts b/web/src/queryLoadingScope.ts new file mode 100644 index 0000000..f3b2653 --- /dev/null +++ b/web/src/queryLoadingScope.ts @@ -0,0 +1,35 @@ +import type { QueryParams } from './types'; + +export function loadedQueryPeriod(query: Pick): 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 { + 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) }; + 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(' · '); +} diff --git a/web/src/requestCoordinator.ts b/web/src/requestCoordinator.ts new file mode 100644 index 0000000..d1dbec5 --- /dev/null +++ b/web/src/requestCoordinator.ts @@ -0,0 +1,457 @@ +export interface RequestScope { + userId: string | null; + authRevision: string | null; + dataRevision: string | null; + currentReleaseId: string | null; +} + +export interface CoordinatedResult { + data: T; + status?: number; + bytes?: number; +} + +export interface CoordinatedRequest { + 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>; +} + +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 { + resolve: (value: T) => void; + reject: (error: unknown) => void; + signal?: AbortSignal; + abortListener?: () => void; +} + +interface Flight { + key: string; + url: string; + scopeKey: string; + scopeEpoch: number; + cacheEpoch: number; + controller: AbortController; + subscribers: Set>; + request: CoordinatedRequest; + startedAt: number; + deadlineAt: number; + timer?: ReturnType; + 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>(); +const queue: Flight[] = []; +const cache = new Map(); +const diagnostics: RequestDiagnostic[] = []; +const directControllers = new Set(); + +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(request: CoordinatedRequest): Promise { + 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 | undefined; + if (existing && !existing.settled) return subscribe(existing, request.signal); + + const timeoutMs = request.timeoutMs ?? DEFAULT_GET_TIMEOUT_MS; + const flight: Flight = { + 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(flight: Flight, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const subscriber: Subscriber = { 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(flight: Flight, subscriber: Subscriber): 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): Promise { + 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): Promise> { + 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(request: CoordinatedRequest): Promise { + const startedAt = Date.now(), ownerEpoch = scopeEpoch; + const controller = new AbortController(); + directControllers.add(controller); + let timedOut = false; + let timer: ReturnType | undefined; + let status: number | null = null; + let bytes = 0; + let rejectCancellation: (error: Error) => void = () => {}; + const cancelled = new Promise((_, 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, 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, error: unknown): void { + if (flight.settled) return; + flight.controller.abort(); + settleFlight(flight, error); + releaseSlot(flight); +} + +function releaseSlot(flight: Flight): void { + if (!flight.slotHeld) return; + flight.slotHeld = false; + activeGets = Math.max(0, activeGets - 1); +} + +function isCurrentScope(flight: Flight): 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 { + 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; +} diff --git a/web/src/resourceInvalidation.ts b/web/src/resourceInvalidation.ts new file mode 100644 index 0000000..d43b38e --- /dev/null +++ b/web/src/resourceInvalidation.ts @@ -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)); +} diff --git a/web/src/sourceWorkbookDetection.ts b/web/src/sourceWorkbookDetection.ts new file mode 100644 index 0000000..a5876d7 --- /dev/null +++ b/web/src/sourceWorkbookDetection.ts @@ -0,0 +1,29 @@ +import type { DataField, DataStage, WorkbookPreview } from './NoCodeDataTypes'; + +type Candidate = { workbook: WorkbookPreview; stage: DataStage; score: number; matched: number }; + +function identify(workbook: WorkbookPreview, fields: Record): Candidate { + return (['black', 'bright'] as DataStage[]).map(stage => { + const required = fields[stage].filter(field => field.required); + const matched = required.filter(field => workbook.preview.headers.includes(field.name)).length; + return { workbook, stage, matched, score: required.length ? matched / required.length : 0 }; + }).sort((a, b) => b.score - a.score || b.matched - a.matched)[0]; +} + +/** 按业务字段比较各工作表,避免把排在明细前面的汇总页当作导入来源。 */ +export async function detectSourceWorkbook( + initial: WorkbookPreview, + fields: Record, + preview: (uploadId: string, params: { sheetName: string; headerRow: number; stage: DataStage }) => Promise, +): Promise<{ workbook: WorkbookPreview; stage: DataStage }> { + let best = identify(initial, fields); + const sheets = initial.sheets.filter(sheet => sheet.sheetName !== initial.preview.sheetName) + .sort((a, b) => Number(b.sheetName.includes('明细')) - Number(a.sheetName.includes('明细'))); + for (const sheet of sheets) { + if (best.score === 1) break; + const workbook = await preview(initial.uploadId, { sheetName: sheet.sheetName, headerRow: 1, stage: best.stage }); + const candidate = identify(workbook, fields); + if (candidate.score > best.score || candidate.score === best.score && candidate.matched > best.matched) best = candidate; + } + return { workbook: best.workbook, stage: best.stage }; +} diff --git a/web/src/types.ts b/web/src/types.ts index e76bd9a..1a566b9 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -107,6 +107,14 @@ export interface MetricsResponse { coverage: CoverageSummary; } +/** 趋势专用响应,不包含汇总表的产品行。 */ +export interface TrendResponse { + release: MetricsResponse['release']; + context: Record; + trend: TrendMetricRow[]; + coverage: CoverageSummary; +} + export interface CoverageSummary { rawRows: number; includedRows: number; diff --git a/web/src/useDataWorkflowOperation.ts b/web/src/useDataWorkflowOperation.ts index 3e28626..9cba55d 100644 --- a/web/src/useDataWorkflowOperation.ts +++ b/web/src/useDataWorkflowOperation.ts @@ -1,12 +1,12 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { api } from './api'; -import { WORKSPACE_INVALIDATED } from './pageCache'; +import { WORKSPACE_INVALIDATED, usePageCache } from './pageCache'; import type { DataWorkflowOperation } from './NoCodeDataTypes'; +import { useVisiblePolling } from './useVisiblePolling'; type StoredOperation = { operationId: string; startedAt: string }; const storageKey = (slot: string) => `quality-data-workflow:${slot}`; 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 { 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) { + const { active } = usePageCache(); const [operation, setOperation] = useState(null); + const [operationId, setOperationId] = useState(''); const [error, setError] = useState(''); - const [pollRevision, setPollRevision] = useState(0); const [starting, setStarting] = useState(false); const callbackRef = useRef(onComplete); - const activeRef = useRef(0); const startPromiseRef = useRef | null>(null); + const pollRequestRef = useRef | null>(null); + const terminalHandledRef = useRef(new Set()); + const generationRef = useRef(0); + const mountedRef = useRef(false); 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) => { try { @@ -30,35 +41,36 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data } catch { /* storage may be unavailable in a restricted browser context */ } }, [slot]); - const poll = useCallback(async (operationId: string) => { - const runId = ++activeRef.current; - setError(''); - while (activeRef.current === runId) { + const poll = useCallback((id: string) => { + if (!id || terminalHandledRef.current.has(id) || pollRequestRef.current) return pollRequestRef.current || Promise.resolve(); + const generation = generationRef.current; + const attempt = (async () => { try { - const current = await api.dataWorkflowOperation(operationId); - if (activeRef.current !== runId) return; + const current = await api.dataWorkflowOperation(id); + if (!mountedRef.current || generation !== generationRef.current) return; setOperation(current); + setError(''); const status = String(current.status || '').toUpperCase(); if (status === 'COMPLETED' || status === 'FAILED') { - if (status === 'COMPLETED') { savePendingId(null); window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); callbackRef.current?.(current); } - else setError(operationError(current)); - return; + terminalHandledRef.current.add(id); + generationRef.current++; + 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) { - if (activeRef.current !== runId) return; + if (!mountedRef.current || generation !== generationRef.current) return; setError(value instanceof Error ? value.message : '处理进度读取失败'); - return; } - await delay(900); - } + })().finally(() => { if (pollRequestRef.current === attempt) pollRequestRef.current = null; }); + pollRequestRef.current = attempt; + return attempt; }, [savePendingId]); - useEffect(() => { - 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]); + useVisiblePolling(() => poll(operationId), 2000, active && Boolean(operationId), true); const start = useCallback(async (create: () => Promise) => { if (startPromiseRef.current) return startPromiseRef.current; @@ -69,9 +81,11 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data try { const started = await create(); if (!started?.operationId) throw new Error('服务端未返回操作编号'); + generationRef.current++; setOperation(started); + terminalHandledRef.current.delete(started.operationId); + setOperationId(started.operationId); savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() }); - void poll(started.operationId); return started; } catch (value) { setError(value instanceof Error ? value.message : '操作未能开始'); @@ -83,18 +97,19 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data })(); startPromiseRef.current = attempt; return attempt; - }, [operation, poll, savePendingId]); + }, [operation, savePendingId]); const resume = useCallback(() => { - if (operation?.operationId) void poll(operation.operationId); - else { - 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); - else setPollRevision(value => value + 1); - } + const id = operation?.operationId || (() => { + try { return (JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null)?.operationId || ''; } + catch { return ''; } + })(); + if (id) { setError(''); setOperationId(id); void poll(id); } }, [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 }; } diff --git a/web/src/useDelayedBusy.ts b/web/src/useDelayedBusy.ts new file mode 100644 index 0000000..12e2e40 --- /dev/null +++ b/web/src/useDelayedBusy.ts @@ -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 (work: () => Promise): Promise => { + setPendingCount(count => count + 1); + try { return await work(); } + finally { if (mounted.current) setPendingCount(count => Math.max(0, count - 1)); } + }, []); + return { busy, run }; +} diff --git a/web/src/useResourceVisibility.ts b/web/src/useResourceVisibility.ts new file mode 100644 index 0000000..46e1101 --- /dev/null +++ b/web/src/useResourceVisibility.ts @@ -0,0 +1,18 @@ +import { useEffect, useState, type RefObject } from 'react'; + +/** 低频图表接近视口后才读取,页面隐藏时不发起请求。 */ +export function useResourceVisibility(ref: RefObject, 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; +} diff --git a/web/src/useVisiblePolling.ts b/web/src/useVisiblePolling.ts new file mode 100644 index 0000000..d883b8e --- /dev/null +++ b/web/src/useVisiblePolling.ts @@ -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, 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]); +} diff --git a/web/src/visiblePollingController.ts b/web/src/visiblePollingController.ts new file mode 100644 index 0000000..077bbfc --- /dev/null +++ b/web/src/visiblePollingController.ts @@ -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, + 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(); + }, + }; +} diff --git a/web/verification/analysis_visual_retry.test.mjs b/web/verification/analysis_visual_retry.test.mjs index 156e112..19aff6a 100644 --- a/web/verification/analysis_visual_retry.test.mjs +++ b/web/verification/analysis_visual_retry.test.mjs @@ -28,11 +28,19 @@ function fixture({ authorize=async()=>{}, load }={}) { 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()});});}, }; + 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 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 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 document={visibilityState:'visible',documentElement:{},addEventListener(){},removeEventListener(){}}; const documentIsHidden=()=>false,visualTheme=()=>({}),visualPeriodSummary=()=>'',visualScopeSummary=()=>'',chartSummary=v=>v.title,analysisVisualTypeLabel=()=>'',visualUnitLabel=()=>''; diff --git a/web/verification/business-query.tsx b/web/verification/business-query.tsx index 31fb7f1..ca92a12 100644 --- a/web/verification/business-query.tsx +++ b/web/verification/business-query.tsx @@ -6,10 +6,10 @@ const json = (value: unknown) => new Response(JSON.stringify(value), {headers:{' window.fetch = async (target) => { 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/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/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 product=url.searchParams.get('product'); let visible=product?rows.filter(r=>r.product===product):rows; diff --git a/web/verification/chart_entry_motion.test.mjs b/web/verification/chart_entry_motion.test.mjs index bf2eed8..76a7207 100644 --- a/web/verification/chart_entry_motion.test.mjs +++ b/web/verification/chart_entry_motion.test.mjs @@ -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 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 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 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; 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 usePageCache=()=>({active:getActive()}); + const usePageCache=()=>({active:getActive()}),useResourceVisibility=()=>getActive()&&getVisible(); 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 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 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(){}}; 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);} - 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',()=>{ 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.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(); +}); diff --git a/web/verification/defect_smooth_refresh.test.mjs b/web/verification/defect_smooth_refresh.test.mjs index 237c7c2..66b202c 100644 --- a/web/verification/defect_smooth_refresh.test.mjs +++ b/web/verification/defect_smooth_refresh.test.mjs @@ -20,6 +20,7 @@ function fixture(){ const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{observe(){}disconnect(){}}; const document={documentElement:{}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})}; const usePageCache=()=>({active:true}); + const useResourceVisibility=()=>true,useDelayedIndicator=value=>value; const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12}); const getComputedStyle=()=>({getPropertyValue:()=>''}),escapeTooltipText=v=>v,numberText=v=>String(v),chooseError=e=>e.message; class ApiError extends Error{}; diff --git a/web/verification/frontend_remediation.test.mjs b/web/verification/frontend_remediation.test.mjs index 494ce52..c63a753 100644 --- a/web/verification/frontend_remediation.test.mjs +++ b/web/verification/frontend_remediation.test.mjs @@ -17,10 +17,11 @@ function policyFixture(api, validate) { const actions=panel.slice(panel.indexOf(' const save ='),panel.indexOf(' const scopeCounts')); return new Function('api','validate',transpile(` 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 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{} - 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, setPreviewBusy=v=>previewBusy=v,setLoading=v=>loading=v,setSaving=v=>saving=v,setError=v=>error=v; ${selection}${load}${actions} @@ -104,7 +105,9 @@ function drawerFixture() { 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 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 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; @@ -115,11 +118,11 @@ function drawerFixture() { 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'); 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'),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(); 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()=>{ 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.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()=>{ - 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(); assert.equal(ui.exports[0].params.releaseId,'release-A');assert.equal(ui.exports[0].params.month,1);assert.equal(ui.downloaded,1);ui.unmount(); }); diff --git a/web/verification/governance_tab_loading.test.mjs b/web/verification/governance_tab_loading.test.mjs new file mode 100644 index 0000000..88a1f8a --- /dev/null +++ b/web/verification/governance_tab_loading.test.mjs @@ -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); +}); diff --git a/web/verification/import_lifecycle_guards.test.mjs b/web/verification/import_lifecycle_guards.test.mjs new file mode 100644 index 0000000..e3cbe43 --- /dev/null +++ b/web/verification/import_lifecycle_guards.test.mjs @@ -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); +}); diff --git a/web/verification/query_loading_scope.test.mjs b/web/verification/query_loading_scope.test.mjs new file mode 100644 index 0000000..95276c9 --- /dev/null +++ b/web/verification/query_loading_scope.test.mjs @@ -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({}), '全部年份');}); diff --git a/web/verification/source_workbook_detection.test.mjs b/web/verification/source_workbook_detection.test.mjs new file mode 100644 index 0000000..0c97e5a --- /dev/null +++ b/web/verification/source_workbook_detection.test.mjs @@ -0,0 +1,43 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import ts from 'typescript'; + +const compiled = ts.transpileModule(readFileSync(new URL('../src/sourceWorkbookDetection.ts', import.meta.url), 'utf8'), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, +}).outputText; +const module = { exports: {} }; +new Function('exports', compiled)(module.exports); +const { detectSourceWorkbook } = module.exports; +const fields = Object.fromEntries(Object.entries({ black: ['序号', '成品规格', '送电镀重量', '责废总重量'], bright: ['序号', '成品规格', '合格重量', '是否电镀来料/二等品库来料'] }) + .map(([stage, names]) => [stage, names.map(name => ({ name, required: true }))])); +const workbook = (sheetName, headers, sheets) => ({ uploadId: 'upload', sourceFile: '10月.xlsx', sheets: sheets.map(sheetName => ({ sheetName })), fields, + preview: { sheetName, headerRow: 1, headers, sampleRows: [] } }); + +test('bright detail following a summary is selected from its business columns', async () => { + const sheets = ['合格率报表', '明细', '成品报废']; + const calls = []; + const detail = workbook('明细', fields.bright.map(x => x.name), sheets); + const result = await detectSourceWorkbook(workbook(sheets[0], ['成品质量统计表(汇总)'], sheets), fields, async (_, params) => { calls.push(params); return detail; }); + assert.equal(result.stage, 'bright'); assert.equal(result.workbook, detail); assert.equal(calls.length, 1); + assert.equal(calls[0].sheetName, '明细'); +}); + +test('black specification summary is rejected in favor of the complete detail', async () => { + const sheets = ['黑片报废(按规格)', '报废明细']; + const result = await detectSourceWorkbook(workbook(sheets[0], ['成品规格', '合格重量'], sheets), fields, + async () => workbook(sheets[1], fields.black.map(x => x.name), sheets)); + assert.equal(result.stage, 'black'); assert.equal(result.workbook.preview.sheetName, '报废明细'); +}); + +test('a complete first sheet needs no further reads; incomplete sheets remain incomplete', async () => { + const complete = workbook('明细', fields.bright.map(x => x.name), ['明细', '汇总']); + assert.equal((await detectSourceWorkbook(complete, fields, async () => { throw Error('unexpected request'); })).workbook, complete); + const partial = workbook('汇总', ['成品规格'], ['汇总', '其他']); + const result = await detectSourceWorkbook(partial, fields, async () => workbook('其他', [], ['汇总', '其他'])); + assert.equal(result.workbook, partial); assert.equal(result.workbook.preview.headers.length, 1); +}); + +test('preview errors propagate instead of silently offering the wrong worksheet', async () => { + await assert.rejects(detectSourceWorkbook(workbook('汇总', [], ['汇总', '明细']), fields, async () => { throw Error('读取失败'); }), /读取失败/); +}); diff --git a/web/verification/stage-products.tsx b/web/verification/stage-products.tsx index 303ced1..70527ef 100644 --- a/web/verification/stage-products.tsx +++ b/web/verification/stage-products.tsx @@ -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}]}); window.fetch=async(target,init)=>{ 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/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/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 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}}; diff --git a/web/verification/unified_loading.test.mjs b/web/verification/unified_loading.test.mjs new file mode 100644 index 0000000..c036835 --- /dev/null +++ b/web/verification/unified_loading.test.mjs @@ -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); +}); diff --git a/web/verification/unified_request_coordinator.test.mjs b/web/verification/unified_request_coordinator.test.mjs new file mode 100644 index 0000000..c6d5ab4 --- /dev/null +++ b/web/verification/unified_request_coordinator.test.mjs @@ -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'); +}); diff --git a/web/verification/unified_resource_invalidation.test.mjs b/web/verification/unified_resource_invalidation.test.mjs new file mode 100644 index 0000000..1b9c35d --- /dev/null +++ b/web/verification/unified_resource_invalidation.test.mjs @@ -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); + } +}); diff --git a/web/verification/unified_workspace_loading.test.mjs b/web/verification/unified_workspace_loading.test.mjs new file mode 100644 index 0000000..4b06986 --- /dev/null +++ b/web/verification/unified_workspace_loading.test.mjs @@ -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(); +}); diff --git a/web/verification/workflow_completion_refresh.test.mjs b/web/verification/workflow_completion_refresh.test.mjs index c8d30aa..8ac8b39 100644 --- a/web/verification/workflow_completion_refresh.test.mjs +++ b/web/verification/workflow_completion_refresh.test.mjs @@ -1,32 +1,53 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {readFileSync} from 'node:fs'; +import { readFileSync } from 'node:fs'; 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 tick=()=>new Promise(resolve=>setImmediate(resolve)); -const deferred=()=>{let resolve;const promise=new Promise(done=>{resolve=done;});return{promise,resolve};}; +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 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()=>{ - const final=deferred(),events=[],callbacks=[],storage=new Map();let calls=0; - const window={localStorage:storage,setTimeout:fn=>setImmediate(fn),dispatchEvent:event=>events.push(event.type)}; - 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 load=new Function('api','window','localStorage','WORKSPACE_INVALIDATED','hooks',`const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`); - const hook=load(api,window,localStorage,'quality-workspace-invalidated',hooks)('project',value=>callbacks.push(value)); - await hook.start(async()=>({operationId:'job',status:'QUEUED'}));await tick();await tick(); - 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); +function operationHook(api) { + const events = [], callbacks = [], storage = new Map(); + 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 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 useDataWorkflowOperation = load(api, window, localStorage, 'quality-workspace-invalidated', () => ({ active: true }), () => {}, hooks); + const hook = useDataWorkflowOperation('project', value => callbacks.push(value)); + return { hook, events, callbacks, storage }; +} + +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()=>{ - const events=[],callbacks=[];const api={dataWorkflowOperation:async()=>({operationId:'job',status:'FAILED',errors:[{message:'rejected'}]})}; - const hooks={useState:value=>[value,()=>{}],useRef:current=>({current}),useCallback:fn=>fn,useEffect:fn=>{fn();}}; - const localStorage={getItem:()=>null,setItem:()=>{},removeItem:()=>{}}; - const window={setTimeout:fn=>setImmediate(fn),dispatchEvent:event=>events.push(event.type)}; - const load=new Function('api','window','localStorage','WORKSPACE_INVALIDATED','hooks',`const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`); - const hook=load(api,window,localStorage,'quality-workspace-invalidated',hooks)('project',value=>callbacks.push(value)); - await hook.start(async()=>({operationId:'job',status:'QUEUED'}));await tick();assert.deepEqual(events,[]);assert.deepEqual(callbacks,[]); +test('failed workflows never invalidate published data and keep the operation id available for recovery', async () => { + let calls = 0; + const { hook, events, callbacks, storage } = operationHook({ dataWorkflowOperation: async () => { calls++; return { operationId: 'job', status: 'FAILED', errors: [{ message: 'rejected' }] }; } }); + await hook.start(async () => ({ operationId: 'job', status: 'QUEUED' })); + hook.resume(); await tick(); 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, []); });