report-statistics.mjs 2.2 KB

1234567891011121314151617181920212223242526272829303132
  1. /** A semantic table within the existing report schema; no new section.kind or API fields. */
  2. export const STATISTICS_SECTION_ID = 'statistics-summary';
  3. export const STATISTICS_COLUMNS = Object.freeze(['维度/主题', '提及数 n', '有效样本 N', '统计口径与范围', '数据解释与限制', '产品含义', '证据']);
  4. const invalid = () => { throw Object.assign(new Error('REPORT_STATISTICS_INVALID'), { code: 'REPORT_STATISTICS_INVALID' }); };
  5. const hasText = value => typeof value === 'string' && Boolean(value.trim());
  6. const count = value => value === null || Number.isSafeInteger(value) && value >= 0;
  7. // The board's CJK typography pass may replace ASCII spaces with thin spaces.
  8. const columnKey = value => typeof value === 'string' ? value.replace(/\s/gu, '') : null;
  9. export function statisticsRows(section) {
  10. if (section?.id !== STATISTICS_SECTION_ID) return null;
  11. if (section.kind !== 'table' || !Array.isArray(section.data?.cols) || section.data.cols.length !== STATISTICS_COLUMNS.length
  12. || section.data.cols.some((column, index) => columnKey(column) !== columnKey(STATISTICS_COLUMNS[index]))
  13. || !Array.isArray(section.data?.rows) || !section.data.rows.length) invalid();
  14. return section.data.rows.map(row => {
  15. if (!Array.isArray(row) || row.length !== 7) invalid();
  16. const [label, numerator, denominator, scope, interpretation, implication, evidenceId] = row;
  17. if (![label, scope, interpretation, implication].every(hasText) || typeof evidenceId !== 'string'
  18. || !count(numerator) || !count(denominator)
  19. || numerator !== null && denominator !== null && numerator > denominator) invalid();
  20. const ratio = numerator !== null && denominator !== null && denominator > 0 ? numerator / denominator : null;
  21. return { label, numerator, denominator, scope, interpretation, implication, evidenceId,
  22. ratio, percent: ratio === null ? null : (ratio * 100).toFixed(1) + '%' };
  23. });
  24. }
  25. export function validateReportStatistics(report) {
  26. for (const chapter of report?.chapters || []) for (const section of chapter.sections || []) {
  27. const rows = statisticsRows(section);
  28. if (rows?.some(row => row.evidenceId && !Object.hasOwn(report.evidence || {}, row.evidenceId))) invalid();
  29. }
  30. }