// worktool.wiki 월간 공식 문서 변화 보고서 numbers.csv 다시 만들기 (한 파일 · 의존성 0 · Node 20+ · npx tsx 로 실행) // npx tsx month-numbers.ts --month 2026-11 [--dir ] [--out numbers.csv] // 읽는 것: https://worktool.wiki/data/history.csv · /data/quality.csv · /data/corrections.json (CC BY 4.0 · /data/LICENSE) import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; /** * K-204(D492) 월간 「업무툴 공식 문서 변화 보고서」 숫자 — 공개 파일 셋만 읽는다: * /data/history.csv · /data/quality.csv · /data/corrections.json * 이 파일은 import 0 · 시계·D1·네트워크 0 인 순수 함수다. 굽기(render)도 자기가 막 만든 같은 공개 파일 글을 넣고, * 누구나 이 파일 본문 그대로(사이트 /report/month-numbers.ts) 같은 숫자를 다시 만들 수 있다. * 규칙: 줄 순서 = id 고정(값 순 정렬 0) · 업체 이름 0 · 해석 글 0 · 매일 대조(basis=live)와 복원분(restored)을 한 숫자로 합치지 않는다(D312). * 원인은 history.csv cause 열 값 그대로(코드) · 판정 이동은 「A→B n건」 나열 · 품질 숫자는 그 달 주마다 값 나란히. */ /** 매일 대조 시작일(= src/services/history/record.ts VERSIONS_SINCE · cause_note 규칙). */ export const MONTH_LIVE_START = '2026-11-14'; /** history.csv cause 열 값(고정 순서 · 많은 순 아님). */ export const MONTH_CAUSES = ['vendor_doc_changed', 'evidence_found', 'evidence_lost', 'site_blocked', 'correction', 'method_change', 'unknown'] as const; /** history.csv kind 열 값(고정 순서). */ export const MONTH_KINDS = ['status', 'value', 'added', 'removed', 'price', 'free_limit'] as const; /** cause=unknown 줄의 cause_note 값(빈칸 = none). */ export const MONTH_NOTES = ['restored', 'before_live_start', 'source_not_read', 'none'] as const; export type MonthLang = 'ko' | 'en' | 'ja'; export interface MonthLine { id: string; /** M01 … M06 */ group: string; label: Record; /** 정수·날짜·소수 글 그대로(쉼표 0). 값이 없으면 ''(그때 note 에 까닭). */ value: string; unit: string; /** 표본 수(quality.csv n 열 등 · 없으면 '') */ n: string; formula: string; source: string; note: string; /** 셈에 들어간 줄의 실제 날짜 구간(없으면 '') */ window_from: string; window_to: string; } export interface MonthNumbers { month: string; from: string; to: string; /** 그 달 history.csv changed_on 의 마지막 날('' = 그 달 줄 없음) */ asOf: string; lines: MonthLine[]; } export interface MonthInput { /** 'YYYY-MM' */ month: string; historyCsv: string; qualityCsv: string; correctionsJson: string; } /** RFC 4180 글 → 줄 배열(따옴표 안 쉼표·줄바꿈·"" 처리). */ export function parseCsv(text: string): string[][] { const out: string[][] = []; let row: string[] = []; let cell = ''; let q = false; for (let i = 0; i < text.length; i++) { const ch = text[i]!; if (q) { if (ch === '"' && text[i + 1] === '"') { cell += '"'; i++; } else if (ch === '"') q = false; else cell += ch; } else if (ch === '"') q = true; else if (ch === ',') { row.push(cell); cell = ''; } else if (ch === '\n') { row.push(cell.endsWith('\r') ? cell.slice(0, -1) : cell); out.push(row); row = []; cell = ''; } else cell += ch; } if (cell !== '' || row.length) { row.push(cell); out.push(row); } return out; } function records(text: string): Record[] { const [head, ...rows] = parseCsv(text.replace(/^/, '')); if (!head) return []; return rows.filter((r) => r.length > 1 || r[0] !== '').map((r) => Object.fromEntries(head.map((h, i) => [h, r[i] ?? '']))); } /** cause_note — history.csv 에 열이 있으면 그 값, 없으면 같은 규칙으로 계산(src/services/history/cause-note.ts 와 같음). */ export function monthCauseNote(r: Record): string { if ('cause_note' in r) return r.cause_note ?? ''; if (r.cause !== 'unknown') return ''; if (r.basis === 'restored') return 'restored'; if (r.kind === 'added' || r.kind === 'removed') return ''; if (!r.last_same_on || r.last_same_on < MONTH_LIVE_START) return 'before_live_start'; return 'source_not_read'; } const lastDay = (month: string): string => { const [y, m] = month.split('-').map(Number) as [number, number]; return `${month}-${String(new Date(Date.UTC(y, m, 0)).getUTCDate()).padStart(2, '0')}`; }; const span = (dates: string[]): { window_from: string; window_to: string } => { const d = dates.filter(Boolean).sort(); return { window_from: d[0] ?? '', window_to: d.at(-1) ?? '' }; }; const L = (ko: string, en: string, ja: string): Record => ({ ko, en, ja }); const ordered = (fixed: readonly T[], seen: Iterable): string[] => [...fixed, ...[...new Set(seen)].filter((x) => !(fixed as readonly string[]).includes(x)).sort()]; export function computeMonthNumbers(input: MonthInput): MonthNumbers { const { month } = input; if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month)) throw new Error(`month 꼴은 YYYY-MM: ${month}`); const from = `${month}-01`; const to = lastDay(month); const hist = records(input.historyCsv); const inMonth = hist.filter((r) => r.changed_on >= from && r.changed_on <= to); const live = inMonth.filter((r) => r.basis === 'live'); const restored = inMonth.filter((r) => r.basis === 'restored'); const asOf = span(inMonth.map((r) => r.changed_on)).window_to; const lines: MonthLine[] = []; const H = '/data/history.csv'; const add = (l: Omit & Partial): void => { lines.push({ n: '', note: '', window_from: '', window_to: '', ...l }); }; // M01 구간·측정 시작일 add({ id: 'M01.from', group: 'M01', label: L('보고 달 첫날', 'First day of the month', '対象月の初日'), value: from, unit: 'date', formula: 'month + "-01"', source: '' }); add({ id: 'M01.to', group: 'M01', label: L('보고 달 마지막 날', 'Last day of the month', '対象月の末日'), value: to, unit: 'date', formula: '달의 마지막 날', source: '' }); add({ id: 'M01.as_of', group: 'M01', label: L('그 달 기록의 마지막 바뀐 날', 'Last change date recorded in the month', '当月の記録の最終変更日'), value: asOf, unit: 'date', formula: 'max(changed_on) · changed_on ∈ 그 달', source: H, note: asOf ? '' : '그 달 줄 없음' }); add({ id: 'M01.history_start', group: 'M01', label: L('history.csv 첫 바뀐 날', 'First change date in history.csv', 'history.csv の最初の変更日'), value: span(hist.map((r) => r.changed_on)).window_from, unit: 'date', formula: 'min(changed_on) · 전체', source: H }); add({ id: 'M01.live_start', group: 'M01', label: L('basis=live 첫 바뀐 날', 'First change date with basis=live', 'basis=live の最初の変更日'), value: span(hist.filter((r) => r.basis === 'live').map((r) => r.changed_on)).window_from, unit: 'date', formula: 'min(changed_on) · basis=live · 전체', source: H }); // M02 줄 수(매일 대조 / 복원분 따로) add({ id: 'M02.live.rows', group: 'M02', label: L('basis=live 줄', 'Rows with basis=live', 'basis=live の行'), value: String(live.length), unit: 'rows', formula: 'count · changed_on ∈ 그 달 · basis=live', source: H, ...span(live.map((r) => r.changed_on)) }); add({ id: 'M02.restored.rows', group: 'M02', label: L('basis=restored 줄', 'Rows with basis=restored', 'basis=restored の行'), value: String(restored.length), unit: 'rows', formula: 'count · changed_on ∈ 그 달 · basis=restored', source: H, ...span(restored.map((r) => r.changed_on)) }); add({ id: 'M02.live.services', group: 'M02', label: L('basis=live 줄의 service_slug 수', 'Distinct service_slug in basis=live rows', 'basis=live 行の service_slug 数'), value: String(new Set(live.map((r) => r.service_slug)).size), unit: 'services', formula: 'count distinct service_slug · basis=live', source: H }); // M03 cause 열 값별(basis=live) + cause=unknown 의 cause_note 값별 for (const c of ordered(MONTH_CAUSES, live.map((r) => r.cause))) { const rs = live.filter((r) => r.cause === c); add({ id: `M03.cause.${c}`, group: 'M03', label: L(`cause=${c}`, `cause=${c}`, `cause=${c}`), value: String(rs.length), unit: 'rows', formula: `count · basis=live · cause=${c}`, source: H, ...span(rs.map((r) => r.changed_on)) }); } const unk = live.filter((r) => r.cause === 'unknown'); for (const nv of MONTH_NOTES) { const rs = unk.filter((r) => (monthCauseNote(r) || 'none') === nv); if (nv === 'restored' && rs.length === 0) continue; // basis=live 에는 restored 가 없다 add({ id: `M03.note.${nv}`, group: 'M03', label: L(`cause=unknown · cause_note=${nv === 'none' ? '(빈칸)' : nv}`, `cause=unknown · cause_note=${nv === 'none' ? '(empty)' : nv}`, `cause=unknown · cause_note=${nv === 'none' ? '(空欄)' : nv}`), value: String(rs.length), unit: 'rows', formula: `count · basis=live · cause=unknown · cause_note=${nv === 'none' ? '""' : nv}`, source: H, ...span(rs.map((r) => r.changed_on)) }); } // M04 kind 값별 · from_status→to_status 나열(basis=live) for (const k of ordered(MONTH_KINDS, live.map((r) => r.kind))) { const rs = live.filter((r) => r.kind === k); add({ id: `M04.kind.${k}`, group: 'M04', label: L(`kind=${k}`, `kind=${k}`, `kind=${k}`), value: String(rs.length), unit: 'rows', formula: `count · basis=live · kind=${k}`, source: H, ...span(rs.map((r) => r.changed_on)) }); } const moves = new Map[]>(); for (const r of live) { if (!r.from_status && !r.to_status) continue; const key = `${r.from_status || '-'}→${r.to_status || '-'}`; const list = moves.get(key); if (list) list.push(r); else moves.set(key, [r]); } for (const key of [...moves.keys()].sort()) { const rs = moves.get(key)!; add({ id: `M04.move.${key.replace('→', '>')}`, group: 'M04', label: L(key, key, key), value: String(rs.length), unit: 'rows', formula: `count · basis=live · from_status→to_status = ${key}`, source: H, ...span(rs.map((r) => r.changed_on)) }); } // M05 quality.csv — metric 마다 그 달 주별 값 나란히(파일 순서 · week ∈ 그 달) const Q = '/data/quality.csv'; const quality = records(input.qualityCsv).filter((r) => r.week >= from && r.week <= to); const metrics = [...new Set(quality.map((r) => r.metric))]; for (const m of metrics) { for (const r of quality.filter((x) => x.metric === m).sort((a, b) => (a.week < b.week ? -1 : 1))) { add({ id: `M05.${m}.${r.week}`, group: 'M05', label: L(`${r.label} · ${r.week}`, `${m} · ${r.week}`, `${m} · ${r.week}`), value: r.value ?? '', unit: r.unit ?? '', n: r.n ?? '', formula: `quality.csv metric=${m} · week=${r.week} · value`, source: Q, note: r.note ?? '', window_from: r.week, window_to: r.week }); } } // M06 정정 · 바깥 정정 요청 const C = '/data/corrections.json'; const cj = JSON.parse(input.correctionsJson) as { corrections?: Array<{ fixed_on?: string }>; requests?: { months?: Record }; }; const fixed = (cj.corrections ?? []).filter((c) => (c.fixed_on ?? '') >= from && (c.fixed_on ?? '') <= to); add({ id: 'M06.corrections', group: 'M06', label: L('정정 기록 수', 'Corrections recorded', '訂正記録の数'), value: String(fixed.length), unit: 'corrections', formula: 'count · corrections[].fixed_on ∈ 그 달', source: C, ...span(fixed.map((c) => c.fixed_on ?? '')) }); const req = cj.requests?.months?.[month]; const noReq = cj.requests ? '' : 'corrections.json 에 requests 칸 없음'; add({ id: 'M06.requests.received', group: 'M06', label: L('바깥 정정 요청 접수(테스트 접수 제외)', 'Correction requests received (test entries excluded)', '外部からの訂正依頼の受付(テストを除く)'), value: req ? String(req.received ?? 0) : cj.requests ? '0' : '', unit: 'requests', formula: `corrections.json requests.months["${month}"].received`, source: C, note: noReq }); add({ id: 'M06.requests.decided', group: 'M06', label: L('그중 처리 상태가 정해진 요청', 'Of those, requests with a decided status', 'そのうち処理状態が決まった依頼'), value: req ? String(req.decided ?? 0) : cj.requests ? '0' : '', unit: 'requests', formula: `corrections.json requests.months["${month}"].decided`, source: C, note: noReq }); const avg = req?.avg_days; add({ id: 'M06.requests.avg_days', group: 'M06', label: L('평균 처리일', 'Average days to a decided status', '平均処理日数'), value: avg === null || avg === undefined ? '' : String(avg), unit: 'days', formula: `corrections.json requests.months["${month}"].avg_days`, source: C, note: noReq || (avg === null || avg === undefined ? '처리된 요청 0건' : '') }); return { month, from, to, asOf, lines }; } export const MONTH_COLUMNS = ['month', 'id', 'group', 'label_ko', 'label_en', 'label_ja', 'value', 'unit', 'n', 'formula', 'source', 'note', 'window_from', 'window_to', 'as_of'] as const; const field = (v: string): string => (/[",\r\n]/.test(v) ? `"${v.replaceAll('"', '""')}"` : v); /** numbers.csv 글(첫 줄 열 이름 · \n · 끝 줄바꿈 없음). */ export function monthNumbersCsv(m: MonthNumbers): string { return [ MONTH_COLUMNS.join(','), ...m.lines.map((l) => [m.month, l.id, l.group, l.label.ko, l.label.en, l.label.ja, l.value, l.unit, l.n, l.formula, l.source, l.note, l.window_from, l.window_to, m.asOf].map(field).join(',')), ].join('\n'); } // ---- 실행 ---- const FILES = { history: '/data/history.csv', quality: '/data/quality.csv', corrections: '/data/corrections.json' } as const; function argOf(name: string): string | undefined { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : undefined; } async function readInput(dir: string | undefined, origin: string, path: string): Promise { if (dir) return readFileSync(join(dir, path.split('/').at(-1)!), 'utf8'); const res = await fetch(`${origin}${path}`, { headers: { 'User-Agent': 'worktool-month-numbers/1.0' } }); if (!res.ok) throw new Error(`${path} HTTP ${res.status}`); return res.text(); } async function main(): Promise { const month = argOf('month'); if (!month) throw new Error('--month YYYY-MM 이 필요합니다'); const dir = argOf('dir'); const origin = (argOf('origin') ?? 'https://worktool.wiki').replace(/\/+$/, ''); const [historyCsv, qualityCsv, correctionsJson] = await Promise.all([ readInput(dir, origin, FILES.history), readInput(dir, origin, FILES.quality), readInput(dir, origin, FILES.corrections), ]); const csv = monthNumbersCsv(computeMonthNumbers({ month, historyCsv, qualityCsv, correctionsJson })); const out = argOf('out'); if (out) writeFileSync(out, csv + '\n'); else process.stdout.write(csv + '\n'); } main().catch((e: unknown) => { console.error(e instanceof Error ? e.message : e); process.exit(1); });