fill.test.ts 35.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
/**
 * 取值顺序与判据的离线测试。运行:npm test
 *
 * 这一组钉的是「钱花在哪」:地址读得出就不查接口,读出来可疑的照样要查,域外坐标不查接口,
 * 邻近推断默认关着;同时钉住日志里的来源与备注 —— 交付方是照着这两列决定要不要复核的。
 */
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { describe, test } from 'node:test';
import { DatabaseSync } from 'node:sqlite';
import { Cache, QueryError, extractFields } from '../src/client.ts';
import type { ResultFields } from '../src/client.ts';
import { atomicCsv, logPathFor, readCsv } from '../src/csv-store.ts';
import { LOG_HEADERS, runJob } from '../src/fill.ts';
import { CONSISTENCY } from '../src/consistency.ts';
import { listHeader, readOnlyList } from '../src/lists.ts';
import { FakeClient, NEAREST, failBehavior, tempRoot } from './helpers.ts';
import type { Behavior } from './helpers.ts';

/** 第三方件只有这 5 列;三个目标列由 readTable 追加 */
const THIN_HEADER = ['案件号', '出险地点', '报案时间', '经度', '纬度'];
/** 地址里三项都明写着:区在第 3 段、街道是段首、路名跟在后面 */
const FULL_ADDRESS = '广东省-深圳市-光明区-凤凰街道光源四路';
const LNG = '113.936672';
const LAT = '22.740500';
/** 沿经度方向挪 0.001° ≈ 103 米,落在道路档 150 米与街道档 300 米之内 */
const NEAR_LNG = '113.937672';

function offline(): never {
  throw new Error('这一行本不该花钱:地址或邻近已经补全');
}

function workspace(prefix: string) {
  const root = tempRoot(prefix);
  const src = path.join(root, 'input.csv');
  const out = path.join(root, 'out.csv');
  const cache = path.join(root, 'cache.sqlite3');
  const temp = path.join(root, '.temp');
  const log = path.join(temp, 'out.处理日志.csv');
  return {
    root, src, out, cache, temp, log,
    write: (rows: string[][]) => atomicCsv(src, THIN_HEADER, rows),
    /** 日志按列名取值,避免断言跟着列序一起改 */
    readLog: (): Record<string, string>[] => {
      const { header, rows } = readCsv(log, null);
      assert.deepEqual(header, LOG_HEADERS, '日志列序即交付方读表的顺序,改动要同步使用说明');
      return rows.map((row) => Object.fromEntries(header.map((name, i) => [name, row[i] ?? ''])));
    },
    readOut: (): string[][] => {
      const { rows } = readCsv(out, null);
      return rows;
    },
  };
}

describe('地址优先', () => {
  test('三项都写在地址里的行不创建客户端,也不留缓存痕迹', async () => {
    const files = workspace('fill address ');
    files.write([['00000000000000000001', FULL_ADDRESS, '46023.1', LNG, LAT]]);
    const report = await runJob(files.src, files.out, files.cache, { clientFactory: offline });
    assert.equal(report.exit_code, 0);
    assert.equal(report.lookup_coordinates, 0);
    assert.equal(report.requests, 0);
    assert.equal(report.address_complete_rows, 1);
    assert.deepEqual(files.readOut()[0].slice(5), ['光明区', '凤凰街道', '光源四路', CONSISTENCY.same, '', '广东省-深圳市-光明区-凤凰街道-光源四路']);
    const log = files.readLog()[0];
    assert.deepEqual([log['行政区来源'], log['街道来源'], log['道路来源']],
      ['地址解析', '地址解析', '地址解析']);
    const fresh = new Cache(files.cache);
    assert.equal(fresh.count(), 0, '没查过的坐标不该占缓存');
    fresh.close();
  });

  test('地址只读出区:其余两档查接口,来源各自记明', async () => {
    const files = workspace('fill partial address ');
    files.write([['00000000000000000002', '广东省-深圳市-光明区', '46023.1', LNG, LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    assert.equal(report.exit_code, 0);
    assert.equal(report.lookup_coordinates, 1);
    assert.equal(report.address_complete_rows, 0);
    const log = files.readLog()[0];
    assert.deepEqual([log['行政区来源'], log['街道来源'], log['道路来源']],
      ['地址解析', '地图接口', '地图接口']);
    assert.deepEqual([log['地址行政区'], log['地址街道'], log['地址道路']], ['光明区', '', '']);
    assert.equal(log['处理状态'], '完整');
  });

  test('地址明写的路名不被接口答案盖掉:接口给的是半径 1000 米内最近的一条路', async () => {
    const files = workspace('fill road first ');
    // 区与道路都明写在地址上,街道没写 → 只有街道这一档花钱查;
    // 接口同时给出的道路(默认答案光源四路)留在日志里可对照,但不许写进表。
    // 地址路名与实测路名对不上,本批又没有同街道分布可依 → 区保持地址读的值、标不一致。
    files.write([['00000000000000000015', '广东省-深圳市-南山区-科技园南路 18 号', '46023.1', LNG, LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const log = files.readLog()[0];
    assert.deepEqual([log['行政区'], log['街道'], log['道路']], ['南山区', '凤凰街道', '科技园南路']);
    assert.deepEqual([log['行政区来源'], log['街道来源'], log['道路来源']],
      ['地址解析', '地图接口', '地址解析']);
    assert.equal(log['接口道路'], '光源四路');
    assert.match(log['备注'], /属光明区,与行政区「南山区」不一致/);
    assert.equal(report.reconciled_rows, 0, '地图街道无独立佐证时不改区');
    assert.equal(report.exit_code, 0);
  });

  test('表内原有值不被地址与接口覆盖,来源记「表内原有」', async () => {
    const root = tempRoot('fill original ');
    const src = path.join(root, 'input.csv');
    const out = path.join(root, 'out.csv');
    const header = [...THIN_HEADER, '行政区', '街道', '道路'];
    atomicCsv(src, header, [['00000000000000000003', FULL_ADDRESS, '46023.1', LNG, LAT, '光明区', '自定义街道', '']]);
    const client = new FakeClient();
    await runJob(src, out, path.join(root, 'cache.sqlite3'), { client, workers: 1 });
    const row = readCsv(out, null).rows[0];
    assert.deepEqual(row.slice(5), ['光明区', '自定义街道', '光源四路', CONSISTENCY.noBasis, '', '广东省-深圳市-光明区-自定义街道-光源四路'], '街道保留交付方原值,只补空的那一格');
  });

  test('标准地址列:查过接口的写接口完整地址,没查的按省市加三列拼', async () => {
    const files = workspace('fill standard address ');
    files.write([
      ['00000000000000000001', FULL_ADDRESS, '46023.1', LNG, LAT],
      ['00000000000000000002', '广东省-深圳市-光明区', '46023.1', '113.940000', '22.745000'],
    ]);
    const client = new FakeClient();
    await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const out = files.readOut();
    assert.equal(out[0].at(-1), '广东省-深圳市-光明区-凤凰街道-光源四路', '没查接口就按已有字段拼,不再花一次钱');
    assert.equal(out[1].at(-1), '广东省-深圳市-光明区-凤凰街道-光源四路', '查过接口就写它给的完整地址(含门牌)');
    assert.equal(out[1][1], '广东省-深圳市-光明区', '原「出险地点」是报案原文,不动');
    assert.equal(client.requests, 1);
  });

  test('v2 旧缓存没有完整地址字段,直接拒绝换缓存路径', async () => {
    const root = tempRoot('fill cache schema ');
    const src = path.join(root, 'input.csv');
    const out = path.join(root, 'out.csv');
    const cache = path.join(root, 'cache.sqlite3');
    atomicCsv(src, THIN_HEADER, [['00000000000000000001', '广东省-深圳市-光明区', '46023.1', LNG, LAT]]);
    const saved = new Cache(cache);
    saved.put([LNG, LAT], {
      ...NEAREST,
      formatted_address: '', // 模拟 v2 记录:字段根本没存下来
    });
    saved.close();
    const db = new DatabaseSync(cache);
    db.prepare("UPDATE meta SET value = '2' WHERE key = 'schema'").run();
    db.close();
    await assert.rejects(
      () => runJob(src, out, cache, { client: new FakeClient(), workers: 1 }),
      /缓存文件是 v2 结构,本工具需要 v3/,
      '旧结果没有完整地址,静默沿用会让新列空白',
    );
  });
});

describe('域外坐标', () => {
  test('合理盒外的坐标不查接口,交代理由写在失败原因里', async () => {
    const files = workspace('fill outside ');
    files.write([['00000000000000000004', '广东省-深圳市', '46023.1', '113.000000', LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    assert.equal(report.exit_code, 2);
    assert.deepEqual(client.calls, []);
    const log = files.readLog()[0];
    assert.equal(log['处理状态'], '域外坐标');
    assert.match(log['失败或缺失原因'], /不在深圳合理范围/);
  });
});

describe('可疑读法', () => {
  test('开头带方位关系词的路名不采用:这一格交给坐标去问接口', async () => {
    const files = workspace('fill distrust road ');
    // 「旁边的深南大道」后缀扫取到的是整句方位描述,不是路名
    files.write([['00000000000000000016', '广东省-深圳市-南山区-旁边的深南大道', '46023.1', LNG, LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const log = files.readLog()[0];
    assert.equal(log['道路'], '光源四路', '可疑读法作废,道路取接口给的最近命名道路');
    assert.equal(log['道路来源'], '地图接口');
    assert.equal(log['地址道路'], '旁边的深南大道', '地址读出了什么仍留在日志里可对照');
    assert.match(log['备注'], /道路「旁边的深南大道」读出来的是方位关系,不采用,改用坐标查询/);
    assert.deepEqual(client.calls, [[LNG, LAT]]);
    assert.equal(report.lookup_coordinates, 1);
  });

  test('区名没写在地址里但街道明写:按街道属区补区,不必为区查接口', async () => {
    const files = workspace('fill district from street ');
    // 第 3 段只写了「宝安」,短名归并出的区名整行没有 → 区这一格不采用;
    // 但「新安街道」是地址明写、词表认得属宝安区,按它补区(来源街道属区)
    files.write([['00000000000000000018', '广东省-深圳市-宝安-新安街道甲路1号', '46023.1', LNG, LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const log = files.readLog()[0];
    assert.deepEqual([log['行政区'], log['街道'], log['道路']], ['宝安区', '新安街道', '光源四路'],
      '区按地址明写的街道属区补,道路仍问接口');
    assert.deepEqual([log['行政区来源'], log['街道来源'], log['道路来源']],
      ['街道属区', '地址解析', '地图接口']);
    assert.equal(log['地址行政区'], '宝安区');
    assert.match(log['备注'], /地址未写行政区,按街道「新安街道」属区补为「宝安区」/);
    assert.equal(report.lookup_coordinates, 1, '省下一次区的查询,但道路仍要问');
  });

  test('街道也靠接口补时不拿它反推区:接口街道推区等于绕一圈自证', async () => {
    const files = workspace('fill district from api street ');
    // 第 3 段只写「宝安」、地址也没写街道 → 街道由接口补;
    // 这时不能用接口给的街道去推区,区照旧取接口给的值(FakeClient 默认光明区)
    files.write([['00000000000000000019', '广东省-深圳市-宝安-甲路1号', '46023.1', LNG, LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const log = files.readLog()[0];
    assert.deepEqual([log['行政区来源'], log['街道来源']], ['地图接口', '地图接口']);
    assert.equal(log['行政区'], '光明区');
    assert.doesNotMatch(log['备注'], /按街道.*属区补/);
    assert.equal(report.exit_code, 0);
  });

  test('坐标问不了接口时,可疑读法回写进表并标注未复核', async () => {
    const files = workspace('fill distrust fallback ');
    files.write([['00000000000000000017', '旁边的深南大道', '46023.1', '113.000000', LAT]]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    assert.deepEqual(client.calls, [], '域外坐标一次都不问');
    const log = files.readLog()[0];
    assert.equal(log['处理状态'], '域外坐标');
    assert.equal(log['道路'], '旁边的深南大道', '没有接口答案可对照时,可疑读法比空白有用');
    assert.equal(log['道路来源'], '地址解析');
    assert.doesNotMatch(log['备注'], /不采用,改用坐标查询/, '回写后不该留下一句自相矛盾的「不采用」');
    assert.match(log['备注'], /但这一行的坐标问不了接口,先按地址写入,需复核/);
    assert.equal(report.exit_code, 2);
  });
});

describe('邻近推断', () => {
  test('默认关闭:地址读不出的行仍然查接口', async () => {
    const files = workspace('fill nearby off ');
    files.write([
      ['00000000000000000005', FULL_ADDRESS, '46023.1', LNG, LAT],
      ['00000000000000000006', '广东省-深圳市-光明区', '46023.2', NEAR_LNG, LAT],
    ]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    assert.equal(report.nearby_rows, 0);
    assert.deepEqual(client.calls, [[NEAR_LNG, LAT]]);
    assert.equal(files.readLog()[1]['道路来源'], '地图接口');
  });

  test('打开后用同批已知点补空白,来源记「邻近地点」并写明参照距离', async () => {
    const files = workspace('fill nearby on ');
    files.write([
      ['00000000000000000005', FULL_ADDRESS, '46023.1', LNG, LAT],
      ['00000000000000000006', '广东省-深圳市-光明区', '46023.2', NEAR_LNG, LAT],
    ]);
    const report = await runJob(files.src, files.out, files.cache, {
      inferNearby: true, clientFactory: offline, workers: 1,
    });
    assert.equal(report.exit_code, 0);
    assert.equal(report.nearby_rows, 1);
    assert.equal(report.lookup_coordinates, 0);
    const log = files.readLog()[1];
    assert.deepEqual([log['街道来源'], log['道路来源']], ['邻近地点', '邻近地点']);
    const meters = Number(log['邻近参照距离(米)']);
    assert.ok(meters > 90 && meters < 120, `参照距离应在百米上下,实际 ${meters}`);
  });

  test('参照点也可以来自缓存:本批没有完整行时照样省一次查询', async () => {
    const files = workspace('fill nearby cache ');
    const cache = new Cache(files.cache);
    cache.put([LNG, LAT], extractFields({
      addressComponent: { district: '光明区', township: '凤凰街道' },
      roads: [{ name: '光源四路', distance: '12' }],
    }));
    cache.close();
    files.write([['00000000000000000007', '广东省-深圳市-光明区', '46023.2', NEAR_LNG, LAT]]);
    const report = await runJob(files.src, files.out, files.cache, {
      inferNearby: true, clientFactory: offline, workers: 1,
    });
    assert.equal(report.lookup_coordinates, 0);
    assert.deepEqual(files.readOut()[0].slice(5), ['光明区', '凤凰街道', '光源四路', CONSISTENCY.same, '', '广东省-深圳市-光明区-凤凰街道-光源四路']);
  });

  test('行政区永不靠邻近补:区界是几公里的面,这一列只接地址与接口的答案', async () => {
    const files = workspace('fill nearby district ');
    files.write([
      ['00000000000000000008', '广东省-深圳市-光明区-凤凰街道光源四路', '46023.1', LNG, LAT],
      // 这一行地址里连区都没有:街道由邻近补、道路由地址读,区只能花钱查
      ['00000000000000000009', '科技园一路 8 号', '46023.2', NEAR_LNG, LAT],
    ]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, {
      client, inferNearby: true, workers: 1,
    });
    assert.equal(report.exit_code, 0);
    assert.equal(report.nearby_rows, 1);
    assert.deepEqual(client.calls, [[NEAR_LNG, LAT]], '只有区还空着的那一行进队列');
    const log = files.readLog()[1];
    assert.deepEqual([log['行政区来源'], log['街道来源'], log['道路来源']],
      ['地图接口', '邻近地点', '地址解析'], '三种来源在同一行里各记各的');
  });

  test('参照点的区与本行已知的区不一致时不用:不把案件记到隔壁区头上', async () => {
    const files = workspace('fill nearby mismatch ');
    files.write([
      ['00000000000000000010', '广东省-深圳市-龙华区-民治街道民丰路', '46023.1', LNG, LAT],
      ['00000000000000000011', '广东省-深圳市-光明区', '46023.2', NEAR_LNG, LAT],
    ]);
    const client = new FakeClient();
    const report = await runJob(files.src, files.out, files.cache, {
      client, inferNearby: true, workers: 1,
    });
    assert.equal(report.nearby_rows, 0);
    assert.deepEqual(client.calls, [[NEAR_LNG, LAT]], '区不一致 → 邻近答案作废,回到接口');
  });
});

describe('日志与状态', () => {
  test('邻市真名进列,备注只陈述事实:不判对错、不给分数', async () => {
    const files = workspace('fill note ');
    const dongguan: ResultFields = extractFields({
      addressComponent: { district: '东莞市', township: '凤岗镇' },
      roads: [{ name: '永东路', distance: '30' }],
    });
    const client = new FakeClient(() => dongguan);
    files.write([['00000000000000000012', '广东省-深圳市', '46023.1', LNG, LAT]]);
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const log = files.readLog()[0];
    assert.equal(report.exit_code, 0);
    assert.deepEqual([log['行政区'], log['街道']], ['东莞市', '凤岗镇'], '写真实归属,不改写成深圳的区');
    assert.match(log['备注'], /不在深圳辖区名单内/);
  });

  test('街道与行政区分属两区时记一条错配备注,取值不改', async () => {
    const files = workspace('fill street mismatch ');
    const answer: ResultFields = extractFields({
      addressComponent: { district: '光明区', township: '民治街道' },
      roads: [{ name: '光源四路', distance: '20' }],
    });
    const client = new FakeClient(() => answer);
    files.write([['00000000000000000013', '广东省-深圳市-光明区', '46023.1', LNG, LAT]]);
    await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    const log = files.readLog()[0];
    assert.equal(log['街道'], '民治街道');
    assert.match(log['备注'], /属龙华区,与行政区「光明区」不一致/);
  });

  test('请求失败的行不改状态口径,并写明仍缺哪几档', async () => {
    const files = workspace('fill failure ');
    files.write([['00000000000000000014', '广东省-深圳市-光明区', '46023.1', LNG, LAT]]);
    const client = new FakeClient(failBehavior('高德请求失败:10004'));
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    assert.equal(report.exit_code, 2);
    const log = files.readLog()[0];
    assert.equal(log['处理状态'], '请求失败');
    assert.equal(log['失败或缺失原因'], '高德请求失败:10004');
    assert.equal(log['备注'], '仍缺 街道、道路', '区已由地址补上,备注只列还空的档位');
  });
});

/** 把清单读成「列名 → 值」,断言不跟着列序改 */
function readList(file: string): Record<string, string>[] {
  const { header, rows } = readCsv(file, null);
  return rows.map((row) => Object.fromEntries(header.map((name, i) => [name, row[i] ?? ''])));
}

describe('跑完的三份清单', () => {
  const failAt = (lng: string): Behavior => (given): ResultFields => {
    if (given === lng) throw new QueryError('高德请求失败:10021');
    return NEAREST;
  };
  const ID = (tail: string): string => `00000000000000000${tail}`;

  test('限流、补不出、待复核各写一份,行内容带上原表全部列与「怎么办」', async () => {
    const files = workspace('fill lists ');
    files.write([
      // 地址只读得出区,接口又被限流 → 再跑一次就有
      [ID('101'), '广东省-深圳市-光明区', '46023.1', LNG, LAT],
      // 坐标问不了接口 → 怎么跑都空着
      [ID('102'), '广东省-深圳市-光明区', '46023.1', '', LAT],
      // 三项填满,接口街道与本区对不上但自洽 → 区按实测订正,备注留痕仍值得看一眼
      [ID('103'), '广东省-深圳市-南山区-科技园南路 18 号', '46023.1', NEAR_LNG, LAT],
    ]);
    const client = new FakeClient(failAt(LNG));
    const report = await runJob(files.src, files.out, files.cache, { client, workers: 1 });
    assert.equal(report.log, files.log, '处理日志写进 .temp,不落在表格旁边');
    assert.equal(fs.existsSync(path.join(files.root, 'out.处理日志.csv')), false);
    assert.equal(fs.existsSync(path.join(files.root, 'out.限流待重试.csv')), false);
    assert.deepEqual(report.list_rows, { 限流待重试: 1, 补不出: 1, 待复核: 1 });
    assert.deepEqual(report.list_files, {
      限流待重试: path.join(files.temp, 'out.限流待重试.csv'),
      补不出: path.join(files.temp, 'out.补不出.csv'),
      待复核: path.join(files.temp, 'out.待复核.csv'),
    });

    const retry = readList(report.list_files['限流待重试']);
    assert.deepEqual(retry.map((row) => row['案件号']), [ID('101')]);
    assert.equal(retry[0]['原表行号'], '2');
    assert.deepEqual([retry[0]['行政区'], retry[0]['处理状态']], ['光明区', '请求失败']);
    assert.match(retry[0]['怎么办'], /再点一次开始/);

    const stuck = readList(report.list_files['补不出']);
    assert.deepEqual([stuck[0]['案件号'], stuck[0]['缺哪些列']], [ID('102'), '街道、道路']);
    assert.match(stuck[0]['原因'], /经度\/纬度 缺失/);

    const review = readList(report.list_files['待复核']);
    assert.deepEqual([review[0]['案件号'], review[0]['缺哪些列']], [ID('103'), '']);
    assert.match(review[0]['备注'], /不一致/, '单行样本无路名互证又无分布佐证,只标不改');
  });

  test('一行清单都不需要时不写空表', async () => {
    const files = workspace('fill lists none ');
    files.write([[ID('104'), FULL_ADDRESS, '46023.1', LNG, LAT]]);
    const report = await runJob(files.src, files.out, files.cache, { clientFactory: offline });
    assert.deepEqual(report.list_rows, { 限流待重试: 0, 补不出: 0, 待复核: 0 });
    assert.deepEqual(report.list_files, {});
    for (const suffix of ['.限流待重试.csv', '.补不出.csv', '.待复核.csv']) {
      assert.equal(fs.existsSync(path.join(files.temp, `out${suffix}`)), false, `不该生成 out${suffix}`);
    }
  });

  test('清单留空(空串或空白)就是整张表都可以问,不是跑去读当前目录', async () => {
    const files = workspace('fill lists blank ');
    files.write([[ID('108'), '广东省-深圳市-光明区', '46023.1', LNG, LAT]]);
    for (const [index, onlyList] of ['', '   '].entries()) {
      const client = new FakeClient();
      const report = await runJob(files.src, path.join(files.root, `blank-${index}.csv`),
        path.join(files.root, `blank-${index}.sqlite3`), { client, workers: 1, onlyList });
      assert.equal(report.only_list_rows, 0);
      assert.deepEqual(client.calls, [[LNG, LAT]], '留空时该问的照问');
    }
  });

  test('按清单重跑:清单里的行才问接口,其余行照实用地址,输出仍是整张表', async () => {
    const files = workspace('fill lists only ');
    files.write([
      [ID('105'), '广东省-深圳市-光明区', '46023.1', LNG, LAT],
      [ID('106'), '广东省-深圳市-光明区', '46023.1', NEAR_LNG, LAT],
    ]);
    const failed = new FakeClient(failBehavior('高德请求失败:10021'));
    const first = await runJob(files.src, files.out, files.cache, { client: failed, workers: 1 });
    assert.equal(first.list_rows['限流待重试'], 2);
    // 人在表格里删掉一行,只留下想先重试的那一行
    const listFile = first.list_files['限流待重试'];
    const { header, rows } = readCsv(listFile, null);
    const at = header.indexOf('案件号');
    atomicCsv(listFile, header, rows.filter((row) => row[at] === ID('105')));

    const client = new FakeClient();
    const second = path.join(files.root, 'again.csv');
    const report = await runJob(files.src, second, files.cache, {
      client, workers: 1, onlyList: listFile,
    });
    assert.equal(report.rows, 2, '输出还是整张表,不是清单那几行');
    assert.equal(report.only_list_rows, 1);
    assert.deepEqual(client.calls, [[LNG, LAT]], '清单外的那个坐标一次都没问');
    const log = readCsv(logPathFor(second, files.temp), null);
    const byLine = log.rows.map((row) => Object.fromEntries(log.header.map((name, i) => [name, row[i] ?? ''])));
    const done = byLine.find((row) => row['原始记录号(含表头)'] === '2') as Record<string, string>;
    assert.equal(done['处理状态'], '完整');
    assert.equal(done['街道来源'], '地图接口');
    const skipped = byLine.find((row) => row['原始记录号(含表头)'] === '3') as Record<string, string>;
    assert.deepEqual([skipped['行政区'], skipped['处理状态']], ['光明区', '未处理'], '地址读出的值照旧写进表');
    assert.match(skipped['失败或缺失原因'], /不在本次清单里/);
    assert.equal(report.list_rows['限流待重试'], 1, '被跳过的行下一轮还会回到清单里');
  });

  test('清单与输入表配不上时直接拒绝,不让人拿着旧清单以为跑完了', async () => {
    const files = workspace('fill lists mismatch ');
    files.write([[ID('107'), '广东省-深圳市-光明区', '46023.1', LNG, LAT]]);
    const listFile = path.join(files.root, '旧的.限流待重试.csv');
    atomicCsv(listFile, listHeader([...THIN_HEADER, '行政区', '街道', '道路']), [
      ['2', '2', ID('999'), '广东省-深圳市-光明区-光明大道', '46023.1', LNG, LAT,
        '光明区', '', '', '街道、道路', '请求失败', '高德请求失败:10021', '', '再点一次开始'],
    ]);
    await assert.rejects(
      () => runJob(files.src, files.out, files.cache, { clientFactory: offline, onlyList: listFile }),
      /没有任何一行在这份表里找得到/,
    );
  });
});

describe('区街道错配的源头订正', () => {
  /** 真表那 24 条的共同形状:龙井路实测在南山区桃源街道,地址第 3 段却写了宝安区 */
  const WRONG_ADDRESS = '广东省-深圳市-宝安区-龙井路';
  const truth = (): ResultFields => ({
    ...NEAREST, district: '南山区', township: '桃源街道', road: '龙井路',
    formatted_address: '广东省深圳市南山区桃源街道龙井路',
  });

  test('区名是工具从地址读错、街道来自实测时,按实测订正区名并留痕', async () => {
    const files = workspace('fill reconcile ');
    files.write([['00000000000000000031', WRONG_ADDRESS, '46023.1', LNG, LAT]]);
    const report = await runJob(files.src, files.out, files.cache, {
      client: new FakeClient(truth), workers: 1,
    });
    assert.equal(report.reconciled_rows, 1);
    assert.deepEqual(files.readOut()[0].slice(5), ['南山区', '桃源街道', '龙井路', CONSISTENCY.same, '', '广东省-深圳市-南山区-桃源街道-龙井路']);
    const log = files.readLog()[0];
    assert.equal(log['地址行政区'], '宝安区', '原地址文本照旧留痕,可追溯');
    assert.deepEqual([log['行政区'], log['行政区来源']], ['南山区', '地图接口']);
    assert.match(log['备注'], /地址所写「宝安区」与实测坐标不符,行政区按实测订正为「南山区」/);
  });

  test('表内原有的区名不改写,仍标不一致交人工判断', async () => {
    const root = tempRoot('fill reconcile original ');
    const src = path.join(root, 'input.csv');
    const out = path.join(root, 'out.csv');
    const header = [...THIN_HEADER, '行政区', '街道', '道路'];
    atomicCsv(src, header, [
      ['00000000000000000032', WRONG_ADDRESS, '46023.1', LNG, LAT, '宝安区', '', ''],
    ]);
    const report = await runJob(src, out, path.join(root, 'cache.sqlite3'), {
      client: new FakeClient(truth), workers: 1,
    });
    assert.equal(report.reconciled_rows, 0, '交付方填的区不能由工具擅自改');
    assert.deepEqual(readCsv(out, null).rows[0].slice(5),
      ['宝安区', '桃源街道', '龙井路', CONSISTENCY.different, '', '广东省-深圳市-南山区-桃源街道-龙井路']);
  });

  test('两通道都不通过:路名对不上、本批又都是少数派,宁可留不一致', async () => {
    const files = workspace('fill reconcile no evidence ');
    // 地址不写路名,只写错区;接口却说在「科技园南路」——坐标落在哪条路上无法互证;
    // 本批只有这一行,街道分布也没有众数可依。
    const noRoadAddress = '广东省-深圳市-宝安区';
    files.write([['00000000000000000033', noRoadAddress, '46023.1', LNG, LAT]]);
    const misleading = (): ResultFields => ({
      ...truth(), road: '科技园南路',
    });
    const report = await runJob(files.src, files.out, files.cache, {
      client: new FakeClient(misleading), workers: 1,
    });
    assert.equal(report.reconciled_rows, 0, '地图街道无独立佐证时不能拿它改区');
    assert.deepEqual(files.readOut()[0].slice(5),
      ['宝安区', '桃源街道', '科技园南路', CONSISTENCY.different, '', '广东省-深圳市-南山区-桃源街道-龙井路']);
  });

  test('本批分布作独立佐证:路名对不上,街道压倒性属候选区仍可订正', async () => {
    const files = workspace('fill reconcile batch ');
    // 9 行南山/桃源街道作参照(地址三项齐全,不查接口),1 行地址错写宝安、
    // 街道与道路靠接口补、接口给了不同路名(通道乙不成立)
    const rows = Array.from({ length: 9 }, (_, i) => [
      `0000000000000000004${i}`, '广东省-深圳市-南山区-桃源街道龙井路',
      '46023.1', LNG, LAT,
    ]);
    rows.push(['00000000000000000049', '广东省-深圳市-宝安区', '46023.1', NEAR_LNG, LAT]);
    files.write(rows);
    const misleading = (): ResultFields => ({ ...truth(), road: '科技园南路' });
    const report = await runJob(files.src, files.out, files.cache, {
      client: new FakeClient(misleading), workers: 1,
    });
    assert.equal(report.reconciled_rows, 1, '本批 9/10 属南山区,压倒性佐证成立');
    const out = files.readOut();
    assert.deepEqual(out[9].slice(5), ['南山区', '桃源街道', '科技园南路', CONSISTENCY.same, '', '广东省-深圳市-南山区-桃源街道-龙井路']);
    assert.match(files.readLog()[9]['备注'], /订正依据:本批 9\/10 行属南山区/);
  });
});

describe('来源冲突:接口与本批分布相悖', () => {
  /** 9 行地址三项齐全的参照:桃源街道在本批 9/10 属南山区 */
  const referenceRows = () => Array.from({ length: 9 }, (_, i) => [
    `0000000000000000005${i}`, '广东省-深圳市-南山区-桃源街道龙井路',
    '46023.1', LNG, LAT,
  ]);
  /** 接口给的区与街道属区相悖:龙井路实测是南山区桃源街道,接口却答龙岗区 */
  const wrongDistrict = (): ResultFields => ({
    ...NEAREST, district: '龙岗区', township: '桃源街道', road: '龙井路',
  });

  test('接口区与街道属区相悖:按本批定区,街道/道路保留接口值并写复核提示', async () => {
    const files = workspace('fill conflict district ');
    files.write([
      ...referenceRows(),
      ['00000000000000000059', '广东省-深圳市-宝安区', '46023.1', NEAR_LNG, LAT],
    ]);
    const report = await runJob(files.src, files.out, files.cache, {
      client: new FakeClient(wrongDistrict), workers: 1,
    });
    assert.equal(report.reconciled_rows, 1, '按本批定区也算一次订正');
    assert.equal(report.review_hint_rows, 1);
    const out = files.readOut();
    assert.deepEqual(out[9].slice(5, 9), ['南山区', '桃源街道', '龙井路', CONSISTENCY.same]);
    const hint = String(out[9].at(-2) ?? '');
    assert.match(hint, /接口返回「龙岗区 · 桃源街道 · 龙井路」与本批分布不符/);
    assert.match(hint, /本批桃源街道属南山区(9\/10)/);
    assert.match(hint, /行政区已按本批定为「南山区」,街道\/道路未改;请人工复核/);
    assert.equal(files.readLog()[9]['行政区来源'], '本批分布');
  });

  test('表内原有的区不改写,只写「请人工复核」', async () => {
    const root = tempRoot('fill conflict original ');
    const src = path.join(root, 'input.csv');
    const out = path.join(root, 'out.csv');
    const header = [...THIN_HEADER, '行政区', '街道', '道路'];
    atomicCsv(src, header, [
      ...referenceRows().map((row) => [...row, '', '', '']),
      ['00000000000000000059', '广东省-深圳市-宝安区', '46023.1', NEAR_LNG, LAT, '福田区', '', ''],
    ]);
    const report = await runJob(src, out, path.join(root, 'cache.sqlite3'), {
      client: new FakeClient(wrongDistrict), workers: 1,
    });
    assert.equal(report.reconciled_rows, 0, '交付方的数据不擅自改');
    assert.equal(report.review_hint_rows, 1);
    const row = readCsv(out, null).rows[9];
    assert.deepEqual(row.slice(5, 9), ['福田区', '桃源街道', '龙井路', CONSISTENCY.different]);
    assert.match(String(row.at(-2) ?? ''), /行政区为表内原有值「福田区」未改/);
  });

  test('接口街道与本批路名主街道相悖:只提示,不覆盖街道/道路', async () => {
    const files = workspace('fill conflict street ');
    const refs = Array.from({ length: 9 }, (_, i) => [
      `0000000000000000006${i}`, '广东省-深圳市-龙华区-民治街道民塘路',
      '46023.1', LNG, LAT,
    ]);
    files.write([
      ...refs,
      ['00000000000000000069', '广东省-深圳市-龙华区-民塘路', '46023.1', NEAR_LNG, LAT],
    ]);
    const api = (): ResultFields => ({
      ...NEAREST, district: '龙华区', township: '大浪街道', road: '民塘路',
    });
    const report = await runJob(files.src, files.out, files.cache, {
      client: new FakeClient(api), workers: 1,
    });
    assert.equal(report.reconciled_rows, 0);
    assert.equal(report.review_hint_rows, 1);
    const row = files.readOut()[9];
    assert.deepEqual(row.slice(5, 9), ['龙华区', '大浪街道', '民塘路', CONSISTENCY.same]);
    const hint = String(row.at(-2) ?? '');
    assert.match(hint, /接口返回「龙华区 · 大浪街道 · 民塘路」与本批分布不符/);
    assert.match(hint, /本批「民塘路」9\/10 行落在「民治街道」/);
    assert.match(hint, /街道\/道路未改(路名可能跨街道,仅供参考)/);
  });

  test('两通道都不成立:接口区与本批相悖但无佐证,不改值也不写提示', async () => {
    const files = workspace('fill conflict no evidence ');
    files.write([['00000000000000000070', '广东省-深圳市-宝安区', '46023.1', LNG, LAT]]);
    const api = (): ResultFields => ({
      ...NEAREST, district: '龙岗区', township: '桃源街道', road: '科技园南路',
    });
    const report = await runJob(files.src, files.out, files.cache, {
      client: new FakeClient(api), workers: 1,
    });
    assert.equal(report.reconciled_rows, 0);
    assert.equal(report.review_hint_rows, 0);
    assert.deepEqual(files.readOut()[0].slice(5),
      ['宝安区', '桃源街道', '科技园南路', CONSISTENCY.different, '', '广东省-深圳市-光明区凤凰街道光源四路']);
  });
});