excel.test.ts 14.2 KB
/** Excel 输入、保真回写与排序的离线测试。运行:npm test */
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import XLSX from 'xlsx';
import type { CellObject, WorkSheet } from 'xlsx';
import { describe, test } from 'node:test';
import { atomicCsv, readCsv } from '../src/csv-store.ts';
import { readExcel } from '../src/excel-store.ts';
import { runJob } from '../src/fill.ts';
import { DEFAULTS, main } from '../src/run-tool.ts';
import { FIRST, FakeClient, HEADER, tempRoot } from './helpers.ts';

const TABLE_HEADER = ['案件号', '出险地点', '报案时间', '经度', '纬度', '行政区', '街道', '道路'];
const DATE_FORMAT = 'yyyy-mm-dd hh:mm:ss';

type Spec = Partial<CellObject>;
type Grid = (Spec | null)[][];

const text = (value: string): Spec => ({ t: 's', v: value });
const number = (value: number, z?: string): Spec => (z === undefined ? { t: 'n', v: value } : { t: 'n', v: value, z });

function makeSheet(rows: Grid, extraTrailingRows = 0): WorkSheet {
  const sheet: WorkSheet = {};
  const width = Math.max(...rows.map((row) => row.length));
  rows.forEach((row, r) => {
    row.forEach((spec, c) => {
      if (spec !== null) sheet[XLSX.utils.encode_cell({ r, c })] = spec as CellObject;
    });
  });
  if (extraTrailingRows > 0) {
    // 表格软件常留下的表尾空行:只有样式没有内容。
    sheet[XLSX.utils.encode_cell({ r: rows.length, c: 0 })] = { t: 'z' };
  }
  sheet['!ref'] = XLSX.utils.encode_range({
    s: { r: 0, c: 0 }, e: { r: rows.length - 1 + extraTrailingRows, c: width - 1 },
  });
  sheet['!cols'] = rows[0].filter((spec) => spec !== null).map(() => ({ wch: 18 }));
  return sheet;
}

function saveWorkbook(file: string, sheets: Record<string, WorkSheet>): void {
  const workbook = XLSX.utils.book_new();
  for (const [name, sheet] of Object.entries(sheets)) XLSX.utils.book_append_sheet(workbook, sheet, name);
  fs.writeFileSync(file, XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer', cellStyles: true }));
}

function readSheet(file: string, index = 0): WorkSheet {
  const workbook = XLSX.readFile(file, { cellNF: true, cellStyles: true });
  return workbook.Sheets[workbook.SheetNames[index]];
}

const cellAt = (sheet: WorkSheet, ref: string): Spec => (sheet[ref] ?? {}) as Spec;

function sourceRows(): Grid {
  return [
    TABLE_HEADER.map((value) => text(value)) as Grid[number],
    [text('00000000000000000001'), text('虚构地址甲'), number(46023.4, DATE_FORMAT),
      text('113.936672'), text('22.740500'), null, null, null],
    [text('00000000000000000002'), text('虚构地址乙'), number(46024.5, DATE_FORMAT),
      number(114.123456, '0.000000'), text('22.500000'), text('原区'), null, text('原路')],
  ];
}

describe('Excel 读写', () => {
  test('只补目标列空白并保持其余单元格类型与显示格式', async () => {
    const root = tempRoot('amap xlsx ');
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, { 出险记录: makeSheet(sourceRows()) });
    const original = fs.readFileSync(source);
    const output = path.join(root, '结果.xlsx');
    const client = new FakeClient();
    const report = await runJob(source, output, path.join(root, 'cache/x.sqlite3'), { client, workers: 2 });
    assert.equal(report.exit_code, 0);
    assert.deepEqual(client.calls, [['113.936672', '22.740500'], ['114.123456', '22.500000']]);
    assert.equal(fs.readFileSync(source).equals(original), true, '源文件不应被改写');

    const sheet = readSheet(output);
    assert.deepEqual([cellAt(sheet, 'A2').t, cellAt(sheet, 'A2').v], ['s', '00000000000000000001']);
    assert.deepEqual([cellAt(sheet, 'C2').t, cellAt(sheet, 'C2').v, cellAt(sheet, 'C2').z],
      ['n', 46023.4, DATE_FORMAT]);
    assert.deepEqual([cellAt(sheet, 'D3').t, cellAt(sheet, 'D3').v, cellAt(sheet, 'D3').z],
      ['n', 114.123456, '0.000000']);
    assert.deepEqual([cellAt(sheet, 'E3').t, cellAt(sheet, 'E3').v], ['s', '22.500000']);
    assert.deepEqual([cellAt(sheet, 'F2').t, cellAt(sheet, 'H2').t], ['s', 's']);
    assert.equal(cellAt(sheet, 'F2').v, '光明区');
    assert.equal(cellAt(sheet, 'G2').v, '凤凰街道');
    assert.equal(cellAt(sheet, 'H2').v, '光源四路');
    assert.equal(cellAt(sheet, 'F3').v, '原区', '已有非空字段不覆盖');
    assert.equal(cellAt(sheet, 'G3').v, '凤凰街道');
    assert.equal(cellAt(sheet, 'H3').v, '原路', '已有非空字段不覆盖');
    assert.equal(fs.existsSync(path.join(root, '.temp', '结果.处理日志.csv')), true);
  });
  test('Excel 输入改写 CSV 时日期取显示文本、数值坐标保满精度', async () => {
    const root = tempRoot('amap xlsx csv ');
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, { 出险记录: makeSheet(sourceRows()) });
    const output = path.join(root, '结果.csv');
    await runJob(source, output, path.join(root, 'cache/x.sqlite3'), { client: new FakeClient() });
    const { rows } = readCsv(output, null);
    assert.match(rows[0][2], /^2026-01-01 \d{2}:\d{2}:\d{2}$/, '不应写成序列号');
    assert.equal(rows[0][3], '113.936672');
    assert.equal(rows[1][3], '114.123456', '数值坐标不受显示格式取整影响');
  });

  test('CSV 输入改写 Excel 时逐格落文本,含换行与引号的地址不丢失', async () => {
    const root = tempRoot('amap csv xlsx ');
    const source = path.join(root, '资料.csv');
    atomicCsv(source, HEADER, [FIRST, FIRST.map((value, index) => (index === 0 ? '00000000000000000002' : value))]);
    const output = path.join(root, '结果.xlsx');
    await runJob(source, output, path.join(root, 'cache/x.sqlite3'), { client: new FakeClient() });
    const sheet = readSheet(output);
    assert.deepEqual([cellAt(sheet, 'A2').t, cellAt(sheet, 'A2').v], ['s', '00000000000000000001']);
    assert.deepEqual([cellAt(sheet, 'C2').t, cellAt(sheet, 'C2').v], ['s', '46023.1234567890']);
    assert.equal(cellAt(sheet, 'B2').v, FIRST[1], '原样保留逗号、引号与换行');
    assert.equal(cellAt(sheet, 'H2').v, '光源四路');
    assert.equal(cellAt(sheet, 'F3').v, '光明区');
  });

  test('表尾残留空行不产生记录也不写日志', async () => {
    const root = tempRoot('amap xlsx tail ');
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, { 出险记录: makeSheet(sourceRows(), 2) });
    assert.equal(readExcel(source, null).rows.length, 2);
    const client = new FakeClient();
    const output = path.join(root, '结果.xlsx');
    const report = await runJob(source, output, path.join(root, 'cache/x.sqlite3'), { client });
    assert.equal(report.rows, 2);
    const log = fs.readFileSync(path.join(root, '.temp', '结果.处理日志.csv'), 'utf8');
    assert.equal(log.trimEnd().split('\r\n').length, 3, '日志应只有表头与两条记录');
  });

  test('排序把未补齐的整行搬到末尾,日期单元格随行走', async () => {
    const root = tempRoot('amap xlsx sort ');
    const rows = sourceRows();
    rows.splice(1, 0, [text('00000000000000000003'), text('虚构地址丙'), number(46025.6, DATE_FORMAT),
      text('abc'), text('22.500000'), null, null, null]);
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, { 出险记录: makeSheet(rows) });
    const config = path.join(root, 'config.json');
    fs.writeFileSync(config, JSON.stringify({ ...DEFAULTS,
      input: '资料.xlsx', output: '结果.xlsx', cache: 'cache/x.sqlite3' }));
    assert.equal(await main(['--config', config], { clientFactory: () => new FakeClient() }), 2);

    const sheet = readSheet(path.join(root, '结果.xlsx'));
    assert.deepEqual([cellAt(sheet, 'A2').v, cellAt(sheet, 'A3').v, cellAt(sheet, 'A4').v],
      ['00000000000000000001', '00000000000000000002', '00000000000000000003']);
    assert.deepEqual([cellAt(sheet, 'C4').t, cellAt(sheet, 'C4').v, cellAt(sheet, 'C4').z],
      ['n', 46025.6, DATE_FORMAT]);
    assert.deepEqual([cellAt(sheet, 'F4').v, cellAt(sheet, 'G4').v, cellAt(sheet, 'H4').v],
      [undefined, undefined, undefined], '无效坐标行仍留空');
    const log = fs.readFileSync(path.join(root, '.temp', '结果.处理日志.csv'), 'utf8');
    assert.match(log, /无效坐标/);
  });

  test('模板缺三个补全列时自动追加,其余列的类型与格式不变', async () => {
    const root = tempRoot('amap xlsx append ');
    const narrow: Grid = [
      TABLE_HEADER.slice(0, 5).map((name) => text(name)),
      [text('00000000000000000001'), text('虚构地址甲'), number(46023.4, DATE_FORMAT),
        text('113.936672'), text('22.740500')],
      [text('00000000000000000002'), text('虚构地址乙'), number(46024.5, DATE_FORMAT),
        number(114.123456, '0.000000'), text('22.500000')],
    ];
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, { 经纬度深圳9月: makeSheet(narrow) });
    const output = path.join(root, '结果.xlsx');
    const report = await runJob(source, output, path.join(root, 'cache/x.sqlite3'),
      { client: new FakeClient() });
    assert.equal(report.exit_code, 0);
    const sheet = readSheet(output);
    assert.equal(sheet['!ref'], 'A1:H3');
    assert.deepEqual(['F1', 'G1', 'H1'].map((ref) => cellAt(sheet, ref).v), ['行政区', '街道', '道路']);
    assert.deepEqual(['F2', 'G2', 'H2'].map((ref) => cellAt(sheet, ref).v), ['光明区', '凤凰街道', '光源四路']);
    assert.deepEqual(['F3', 'G3', 'H3'].map((ref) => cellAt(sheet, ref).v), ['光明区', '凤凰街道', '光源四路']);
    assert.deepEqual([cellAt(sheet, 'C2').t, cellAt(sheet, 'C2').v, cellAt(sheet, 'C2').z],
      ['n', 46023.4, DATE_FORMAT], '原日期单元格不因追加列而改写');
    assert.deepEqual([cellAt(sheet, 'D3').t, cellAt(sheet, 'D3').v, cellAt(sheet, 'D3').z],
      ['n', 114.123456, '0.000000']);
  });

  test('缺补全列时追加后仍能把未补齐的整行排到末尾', async () => {
    const root = tempRoot('amap xlsx append sort ');
    const narrow: Grid = [
      TABLE_HEADER.slice(0, 5).map((name) => text(name)),
      [text('00000000000000000001'), text('虚构地址甲'), number(46023.4, DATE_FORMAT),
        text('113.936672'), text('22.740500')],
      [text('00000000000000000002'), text('虚构地址乙'), number(46025.6, DATE_FORMAT),
        text('abc'), text('22.500000')],
      [text('00000000000000000003'), text('虚构地址丙'), number(46024.5, DATE_FORMAT),
        number(114.123456, '0.000000'), text('22.500000')],
    ];
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, { 经纬度深圳9月: makeSheet(narrow) });
    fs.writeFileSync(path.join(root, 'config.json'), JSON.stringify({ ...DEFAULTS,
      input: '资料.xlsx', output: '结果.xlsx', cache: 'cache/x.sqlite3' }));
    const config = path.join(root, 'config.json');
    assert.equal(await main(['--config', config], { clientFactory: () => new FakeClient() }), 2);

    const sheet = readSheet(path.join(root, '结果.xlsx'));
    assert.deepEqual(['A2', 'A3', 'A4'].map((ref) => cellAt(sheet, ref).v),
      ['00000000000000000001', '00000000000000000003', '00000000000000000002'], '无效坐标行排到末尾');
    assert.deepEqual(['F1', 'G1', 'H1'].map((ref) => cellAt(sheet, ref).v), ['行政区', '街道', '道路']);
    assert.deepEqual(['F2', 'G2', 'H2'].map((ref) => cellAt(sheet, ref).v), ['光明区', '凤凰街道', '光源四路']);
    assert.deepEqual(['F4', 'G4', 'H4'].map((ref) => cellAt(sheet, ref).v),
      [undefined, undefined, undefined], '补不出的行仍留空');
    assert.deepEqual([cellAt(sheet, 'C4').t, cellAt(sheet, 'C4').v, cellAt(sheet, 'C4').z],
      ['n', 46025.6, DATE_FORMAT], '日期单元格随行搬移');
    assert.deepEqual([cellAt(sheet, 'D3').t, cellAt(sheet, 'D3').v, cellAt(sheet, 'D3').z],
      ['n', 114.123456, '0.000000'], '数值坐标随行搬移');
  });

  test('只重写第一个工作表,其余工作表内容保留', async () => {
    const root = tempRoot('amap xlsx multi ');
    const source = path.join(root, '资料.xlsx');
    saveWorkbook(source, {
      出险记录: makeSheet(sourceRows()),
      备注: makeSheet([[text('说明'), text('数值')], [text('甲'), number(1)]]),
    });
    const output = path.join(root, '结果.xlsx');
    await runJob(source, output, path.join(root, 'cache/x.sqlite3'), { client: new FakeClient() });
    const workbook = XLSX.readFile(output, { cellNF: true });
    assert.deepEqual(workbook.SheetNames, ['出险记录', '备注']);
    assert.deepEqual([workbook.Sheets['备注']['A2'].t, workbook.Sheets['备注']['B2'].v], ['s', 1]);
  });

  test('缺经纬度列、缺表头名称与无效文件都在联网前失败', async () => {
    const noCoordinates: Grid = [
      ['案件号', '出险地点', '报案时间', '经度'].map((name) => text(name)),
      [text('00000000000000000001'), text('虚构地址甲'), number(46023.4, DATE_FORMAT), text('113.936672')],
    ];
    const extraColumn = [TABLE_HEADER.map((name) => text(name)) as Grid[number],
      [text('00000000000000000001'), text('虚构地址甲'), text('原时间'), text('113.936672'),
        text('22.740500'), null, null, null, text('无名列数据')]];
    const cases: [string, (file: string) => void, RegExp][] = [
      ['缺经纬度列', (file) => saveWorkbook(file, { 出险记录: makeSheet(noCoordinates) }),
        /必须包含经度、纬度列/],
      ['数据超出表头宽度', (file) => saveWorkbook(file, { 出险记录: makeSheet(extraColumn) }),
        /缺少表头名称/],
      ['改名文本文件', (file) => fs.writeFileSync(file, '这不是 Excel 文件'),
        /不是有效的 Excel 工作簿/],
      ['截断的工作簿', (file) => {
        saveWorkbook(file, { 出险记录: makeSheet(sourceRows()) });
        fs.writeFileSync(file, fs.readFileSync(file).subarray(0, 600));
      }, /无法读取 Excel 文件/],
    ];
    for (const [title, prepare, expected] of cases) {
      const root = tempRoot(`amap xlsx ${title} `);
      const source = path.join(root, '资料.xlsx');
      prepare(source);
      const client = new FakeClient();
      await assert.rejects(() => runJob(source, path.join(root, '结果.xlsx'),
        path.join(root, 'cache/x.sqlite3'), { client }), { name: 'UserError', message: expected }, title);
      assert.deepEqual(client.calls, [], `${title} 不应发起请求`);
    }
  });
});