desktop-core.ts 18.9 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
/**
 * 图形界面的纯逻辑:默认值从哪来、目录怎么列、界面上的参数怎么校验、跑完怎么把数字说成人话。
 *
 * 这里不起服务、不碰接口、也不碰 worker —— desktop.ts 只把这几个函数搬到 HTTP 上,
 * 所以判据全能离线测。Key 不在这层的任何结构里:它只从界面上经过一次,不落盘、不进日志。
 */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { logPathFor } from './csv-store.ts';
import { isExcel } from './excel-store.ts';
import { UserError } from './errors.ts';
import type { Report } from './fill.ts';
import { LIST_KINDS, readOnlyList } from './lists.ts';
import { loadConfig, resolvePath } from './run-tool.ts';
import { SOURCES, TARGETS } from './targets.ts';
import type { NearbyField } from './targets.ts';

export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export const CONFIG_FILE = path.join(ROOT, 'config.json');
export const STATE_FILE = path.join(ROOT, 'ui-state.json');

/** 认得的表格后缀;界面上只列这些文件,省得把人往 .txt 上引 */
export const TABLE_SUFFIXES: readonly string[] = ['.csv', '.xlsx', '.xlsm', '.xlsb', '.xls'];

/** 缓存文件的后缀:浏览缓存时只列这些 */
export const CACHE_SUFFIXES: readonly string[] = ['.sqlite3'];

/** 清单文件的后缀:补齐工具只把清单写成 CSV,浏览清单时也只列这些 */
export const LIST_SUFFIXES: readonly string[] = ['.csv'];

export function metersOf(field: NearbyField): number {
  const target = TARGETS.find((item) => item.nearby === field);
  return target === undefined ? 0 : target.inferMeters;
}

/** 界面上邻近半径的出厂值 —— 判据只在 targets.ts 一处,这里跟着它走 */
export const DEFAULT_RADII = { street: metersOf('street'), road: metersOf('road') };

/** 界面上能改的所有东西。没有 Key:Key 只经过一次,不写进任何文件。 */
export type UiState = {
  input: string;
  outputDir: string;
  outputName: string;
  cache: string;
  /** 「只跑清单里的行」:这份清单之外的行本次不许问接口;空串表示整表照跑 */
  onlyList: string;
  workers: number;
  qps: number;
  limit: number | null;
  inferNearby: boolean;
  streetMeters: number;
  roadMeters: number;
  sortIncompleteLast: boolean;
};

/** 记在 ui-state.json 的东西。清单路径不在这里:它与生成它的那次输入配对,下次运行是另一件事。 */
const STATE_KEYS = ['input', 'outputDir', 'outputName', 'cache', 'workers', 'qps',
  'limit', 'inferNearby', 'streetMeters', 'roadMeters', 'sortIncompleteLast'] as const;

/** config.json 是出厂默认值;界面上的改动记在 ui-state.json,两边都不需要人手工同步。 */
export function configState(configFile: string = CONFIG_FILE): UiState {
  const config = loadConfig(configFile);
  const root = path.dirname(configFile);
  const output = config.output === '' ? '' : resolvePath(config.output, root);
  return {
    input: config.input === '' ? '' : resolvePath(config.input, root),
    outputDir: output === '' ? '' : path.dirname(output),
    outputName: output === '' ? '' : path.basename(output),
    cache: config.cache === '' ? '' : resolvePath(config.cache, root),
    onlyList: '',
    workers: config.workers,
    qps: config.qps,
    limit: config.limit,
    inferNearby: config.infer_nearby,
    streetMeters: metersOf('street'),
    roadMeters: metersOf('road'),
    sortIncompleteLast: config.sort_incomplete_last,
  };
}

/** 只认得上面那些键;文件缺失、格式坏了、多了别的东西都不会把界面卡住。 */
export function loadState(stateFile: string, fallback: UiState): UiState {
  let given: Record<string, unknown>;
  try {
    const raw: unknown = JSON.parse(fs.readFileSync(stateFile, 'utf8').replace(/^/, ''));
    if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return fallback;
    given = raw as Record<string, unknown>;
  } catch {
    return fallback;
  }
  const text = (key: 'input' | 'outputDir' | 'outputName' | 'cache'): string | undefined => {
    const value = given[key];
    return typeof value === 'string' ? value : undefined;
  };
  const whole = (key: 'workers' | 'qps' | 'streetMeters' | 'roadMeters'): number | undefined => {
    const value = given[key];
    return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
  };
  const flag = (key: 'inferNearby' | 'sortIncompleteLast'): boolean | undefined => {
    const value = given[key];
    return typeof value === 'boolean' ? value : undefined;
  };
  const state = { ...fallback };
  for (const key of ['input', 'outputDir', 'outputName', 'cache'] as const) {
    const value = text(key);
    if (value !== undefined) state[key] = value;
  }
  state.onlyList = '';
  for (const key of ['workers', 'qps', 'streetMeters', 'roadMeters'] as const) {
    const value = whole(key);
    if (value !== undefined) state[key] = value;
  }
  for (const key of ['inferNearby', 'sortIncompleteLast'] as const) {
    const value = flag(key);
    if (value !== undefined) state[key] = value;
  }
  if (given.limit === null || (typeof given.limit === 'number' && Number.isInteger(given.limit))) {
    state.limit = given.limit as number | null;
  }
  return state;
}

/** 逐键写回,别的东西(包括误粘进来的 Key)写不进去。 */
export function saveState(state: UiState, stateFile: string = STATE_FILE): void {
  const stored: Record<string, unknown> = {};
  for (const key of STATE_KEYS) stored[key] = state[key];
  fs.writeFileSync(stateFile, `${JSON.stringify(stored, null, 2)}\n`, 'utf8');
}

export function outputOf(state: UiState): string {
  // 正式交付的表格默认进源文件旁的 out/:工具目录不落运行产物,源文件所在文件夹也保持整洁
  const directory = state.outputDir === ''
    ? path.join(path.dirname(state.input), 'out')
    : resolvePath(state.outputDir, ROOT);
  const stem = path.basename(state.input, path.extname(state.input));
  // 只填了名字没填后缀时按输入格式补上:CSV 进就 .csv,Excel 进就 .xlsx
  const name = state.outputName === ''
    ? `${stem}.已补全${isExcel(state.input) ? '.xlsx' : '.csv'}`
    : state.outputName;
  const withSuffix = path.extname(name) === ''
    ? `${name}${isExcel(state.input) ? '.xlsx' : '.csv'}`
    : name;
  return path.join(directory, withSuffix);
}

/**
 * 本轮的临时目录:处理日志、三份清单都写在这里,紧跟源文件。
 * 不管操作员把表格输出到哪个盘,过程文件都留在源文件所在文件夹的 .temp 下,不散到别处,
 * 也不落进工具目录。
 */
export function tempDirOf(input: string): string {
  return path.join(path.dirname(input), '.temp');
}

/** 参数与路径能不能开工;返回第一条要说给人的理由,空串表示可以。 */
export function formIssue(state: UiState): string {
  if (state.input === '') return '先选择要处理的表格文件';
  if (sourceIssue(state.input) !== '') return sourceIssue(state.input);
  if (onlyListIssue(state.onlyList) !== '') return onlyListIssue(state.onlyList);
  if (!Number.isInteger(state.workers) || state.workers < 1) return '并发数量要是 1 以上的整数';
  if (state.workers > 200) return '并发数量最大 200,再高只是排队';
  if (!Number.isFinite(state.qps) || state.qps < 0) return '每秒请求上限要是 0 或更大的数(0 为不限)';
  if (state.limit !== null && (!Number.isInteger(state.limit) || state.limit < 1)) {
    return '只处理前几行时,行数要是 1 以上的整数';
  }
  if (state.inferNearby) {
    for (const [name, value] of [['街道半径', state.streetMeters], ['道路半径', state.roadMeters]] as const) {
      if (!Number.isInteger(value) || value < 1) return `${name}要是 1 米以上的整数`;
      if (value > 5000) return `${name}最大 5000 米,再远就不是「附近」了`;
    }
  }
  const output = outputOf(state);
  const suffix = path.extname(output).toLowerCase();
  if (suffix !== '.csv' && suffix !== '.xlsx' && suffix !== '.xlsm') {
    return '输出文件后缀只能是 .csv、.xlsx 或 .xlsm';
  }
  if (sameFile(output, state.input)) return '输出文件和输入文件是同一个,不允许直接覆盖源文件';
  return '';
}

/** 输入文件本身的毛病;界面在选完文件就报,不用等到跑失败。 */
export function sourceIssue(file: string): string {
  if (file === '') return '还没有选择输入文件';
  if (!fs.existsSync(file)) return `找不到文件:${file}`;
  if (!fs.statSync(file).isFile()) return `${file} 不是文件`;
  const suffix = path.extname(file).toLowerCase();
  if (!TABLE_SUFFIXES.includes(suffix)) {
    return `不认得的表格格式「${suffix}」,只支持 ${TABLE_SUFFIXES.join('、')}`;
  }
  return '';
}

/** 「只跑清单里的行」那份文件能不能用;空串表示没开这个开关。 */
export function onlyListIssue(file: string): string {
  if (file === '') return '';
  if (!fs.existsSync(file)) return `找不到清单:${file}`;
  if (!fs.statSync(file).isFile()) return `${file} 不是文件`;
  if (path.extname(file).toLowerCase() !== '.csv') return '清单只能用补齐工具生成的 CSV,扩展名不是 .csv 的一律不认';
  return '';
}

/** 界面上关于清单的一句话:里面记了多少行、按哪一列认行。 */
export function onlyListNotice(file: string): string {
  const issue = onlyListIssue(file);
  if (issue !== '') return issue;
  if (file === '') return '';
  try {
    const list = readOnlyList(path.resolve(file));
    return `清单里记了 ${list.values.size.toLocaleString('zh-CN')} 行,按「${list.column}」认行。`
      + '本次只有这些行允许问接口,其余行照旧用表内原值、地址与缓存补齐。';
  } catch (exc) {
    return exc instanceof UserError ? exc.message : '这份清单读不出来';
  }
}

function sameFile(a: string, b: string): boolean {
  const key = (file: string): string =>
    path.resolve(file).toLowerCase().replace(/\\/g, '/');
  return key(a) === key(b);
}

export type Entry = { name: string; path: string; directory: boolean; size: number };

/** 目录浏览:浏览器给不出本机绝对路径,所以列目录的活由本机来做。 */
export function browse(requested: string, suffixes: readonly string[] = TABLE_SUFFIXES): {
  dir: string; parent: string; entries: Entry[]; note: string;
} {
  const dir = requested === '' ? os.homedir() : resolvePath(requested, process.cwd());
  const target = fs.existsSync(dir) && fs.statSync(dir).isFile() ? path.dirname(dir) : dir;
  if (!fs.existsSync(target)) throw new UserError(`找不到目录:${target}`);
  let names: fs.Dirent[];
  try {
    names = fs.readdirSync(target, { withFileTypes: true });
  } catch {
    throw new UserError(`没有权限读取这个目录:${target}`);
  }
  const entries: Entry[] = [];
  for (const dirent of names) {
    if (dirent.name.startsWith('.') || dirent.name.startsWith('~$')) continue;
    const full = path.join(target, dirent.name);
    const directory = dirent.isDirectory();
    if (!directory && !suffixes.includes(path.extname(dirent.name).toLowerCase())) continue;
    let size = 0;
    try {
      size = directory ? 0 : fs.statSync(full).size;
    } catch {
      size = 0;
    }
    entries.push({ name: dirent.name, path: full, directory, size });
  }
  entries.sort((a, b) => (a.directory === b.directory
    ? a.name.localeCompare(b.name, 'zh-CN')
    : a.directory ? -1 : 1));
  const shown = entries.slice(0, 1000);
  return {
    dir: target,
    parent: path.dirname(target) === target ? '' : path.dirname(target),
    entries: shown,
    note: entries.length > shown.length ? `这里项目太多,只列出前 ${shown.length} 项` : '',
  };
}

/** 界面上的三个快捷入口,省得每次从家目录点进去 */
export function quickRoots(): { name: string; path: string }[] {
  const named = [
    ['桌面', 'Desktop'], ['文档', 'Documents'], ['下载', 'Downloads'], ['家目录', ''],
  ] as const;
  return named
    .map(([label, leaf]) => ({
      name: label, path: leaf === '' ? os.homedir() : path.join(os.homedir(), leaf),
    }))
    .filter((root) => fs.existsSync(root.path));
}

export type Job = {
  input: string;
  output: string;
  cache: string;
  options: {
    limit: number | null;
    workers: number;
    qps: number;
    inferNearby: boolean;
    nearbyMeters: { street: number; road: number };
    sortIncompleteLast: boolean;
    onlyList: string;
    tempDir: string;
  };
};

/** 缓存文件落在哪里:界面留空时跟着源文件走,放在源文件旁的 cache/;还没选文件时没有可放的位置。 */
export function cachePathOf(state: UiState): string {
  if (state.cache !== '') return resolvePath(state.cache, ROOT);
  return state.input === ''
    ? ''
    : path.join(path.dirname(state.input), 'cache', 'amap_regeo_cache.sqlite3');
}

/** 界面上的表单 → runJob 的入参;半径只在打开邻近时才带上。 */
export function jobOf(state: UiState): Job {
  const issue = formIssue(state);
  if (issue !== '') throw new UserError(issue);
  return {
    input: state.input,
    output: outputOf(state),
    cache: cachePathOf(state),
    options: {
      limit: state.limit,
      workers: state.workers,
      qps: state.qps,
      inferNearby: state.inferNearby,
      nearbyMeters: { street: state.streetMeters, road: state.roadMeters },
      sortIncompleteLast: state.sortIncompleteLast,
      onlyList: state.onlyList,
      tempDir: tempDirOf(state.input),
    },
  };
}

export type SummaryRow = { label: string; value: string };
export type Summary = {
  /** 一行先把最该看见的三个数说完;细账在 rows 里,两处不重复摆同一份数字 */
  headline: string;
  rows: SummaryRow[];
  files: SummaryRow[];
  caution: string;
};

const count = (value: number): string => value.toLocaleString('zh-CN');

function duration(seconds: number): string {
  const whole = Math.max(0, Math.round(seconds));
  if (whole < 60) return `${whole} 秒`;
  return `${Math.floor(whole / 60)} 分 ${whole % 60} 秒`;
}

/** 正在做的事 → 给人看的一句话。done/total 只在真有进度可报时有。 */
export function stageText(label: string, done?: number, total?: number): string {
  const part = done !== undefined && total !== undefined ? `(${count(done)} / ${count(total)})` : '';
  return {
    读取表格: '正在读取表格,文件大时要等一会儿',
    解析地址文本: '正在从地址文本里读行政区、街道、道路',
    查缓存: '正在翻本机已查过的坐标',
    邻近推断: '正在用附近已知地点推断',
    准备调用接口: `接下来要问地图接口 ${total === undefined ? '' : count(total)} 个坐标,先确认 Key`,
    调用地图接口: `正在问地图接口${part}`,
    写出表格: '正在写出补齐后的表格',
    写出处理日志: '正在写出处理日志',
    写出本次清单: `正在写出本次的清单${part}`,
  }[label] ?? `正在${label}`;
}

/**
 * 跑完之后的那一张总结。只报数:哪些行没花钱、哪些行是查来的、还差多少,
 * 判读留给看日志的人 —— 界面不替人下「合格 / 不合格」的结论。
 */
export function summaryOf(report: Report): Summary {
  const fromSource = (name: string): number => report.cells_by_source[name] ?? 0;
  const missing = report.rows - (report.statuses['完整'] ?? 0);
  const rows: SummaryRow[] = [
    { label: '处理多少行', value: `${count(report.rows)} 行` },
    { label: '三项都写着了', value: `${count(report.statuses['完整'] ?? 0)} 行` },
    { label: '还有空白', value: `${count(missing)} 行` },
    { label: '一行接口都没调', value: `${count(report.address_complete_rows)} 行(原值和地址文本就够了)` },
    {
      label: '问了地图接口',
      value: `${count(report.requests)} 次`
        + `(要查的坐标 ${count(report.lookup_coordinates)} 个,同一位置只问一次)`,
    },
    { label: '从已查过的坐标直接取', value: `${count(report.cache_hits)} 个坐标,没有花费` },
  ];
  if (report.nearby_rows > 0) {
    rows.push({
      label: '用附近地点推断',
      value: `${count(report.nearby_rows)} 行(推断值,日志里另标了来源)`,
    });
  }
  rows.push({
    label: `三列共 ${count(report.rows * TARGETS.length)} 格,分别来自`,
    value: `${SOURCES.original} ${count(fromSource(SOURCES.original))} 格、`
      + `${SOURCES.address} ${count(fromSource(SOURCES.address))} 格、`
      + `${SOURCES.cache} ${count(fromSource(SOURCES.cache))} 格、`
      + `${SOURCES.nearby} ${count(fromSource(SOURCES.nearby))} 格、`
      + `${SOURCES.api} ${count(fromSource(SOURCES.api))} 格、`
      + `仍空白 ${count(report.blank_cells)} 格`,
  });
  if (report.only_list_rows > 0) {
    rows.push({
      label: '本次按清单只跑',
      value: `${count(report.only_list_rows)} 行(清单里的行才允许问接口,其余行只用地址与缓存)`,
    });
  }
  for (const info of LIST_KINDS) {
    const total = report.list_rows[info.title] ?? 0;
    if (total === 0) continue;
    rows.push({ label: info.summaryLabel, value: `${count(total)} 行(${info.summaryHint})` });
  }
  rows.push({ label: '耗时', value: duration(report.elapsed_seconds) });

  const unfilled = Object.entries(report.statuses)
    .filter(([name, total]) => total > 0 && name !== '完整')
    .map(([name, total]) => `${name} ${count(total)} 行`);
  const files: SummaryRow[] = [
    { label: '补齐后的表格', value: report.output },
    { label: '处理日志', value: report.log },
    { label: '已查坐标缓存', value: report.cache },
  ];
  for (const info of LIST_KINDS) {
    const file = report.list_files[info.title] ?? '';
    if (file !== '') files.push({ label: info.title, value: file });
  }
  const caution = report.exit_code === 0 ? '' : report.stop_reason === ''
    ? `${unfilled.join(';')}。逐行的原因写在处理日志的「失败或缺失原因」与「备注」两列。`
    : `本次停在「${report.stop_reason}」。重跑同一个输入文件、用同一个缓存路径可以接着查,已查过的不再花钱。`;
  return {
    headline: `${count(report.rows)} 行 · ${count(report.requests)} 次接口调用 · 用时 ${duration(report.elapsed_seconds)}`,
    rows,
    files,
    caution,
  };
}

/** 界面上先替人看一眼的输出路径提示(已存在要说,静默覆盖最容易被误当成没跑) */
export function outputNotice(state: UiState): string {
  if (state.input === '') return '';
  const output = outputOf(state);
  if (sameFile(output, state.input)) return '输出与输入同名同目录,运行会被拒绝';
  if (fs.existsSync(output)) return `输出文件已存在,运行会覆盖它:${output}`;
  try {
    fs.mkdirSync(path.dirname(output), { recursive: true });
  } catch {
    return `输出目录创建不了:${path.dirname(output)}`;
  }
  return `输出:${output};日志:${logPathFor(output, tempDirOf(state.input))}`;
}