@skillre/dsh-plugin-work-dashboard 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,611 +1,114 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * POC 信息收集表单生成器(v3)。
3
+ * POC 信息收集表单的薄 CLI(v3.1)。
4
4
  *
5
- * 生成一个自包含 HTML:组员双击即可填,离线可用,填完下载 JSON 交回。
6
- * 数据模型是 v3(身份 + gate0 + plan + progress[] + outcome);旧版的
7
- * `why_customer_test` / `result` / `timeline` 已不存在,本脚本不产出那些字段。
5
+ * ## 这个文件为什么这么短
8
6
  *
9
- * 三条设计约束,来自旧版 v1 生成器的经验:
7
+ * 表单的生成逻辑**不在**这里,在 `src/form.ts`(打包后 `lib/form.js`)。
8
+ * 本脚本只做三件事:解析命令行、读 YAML、把结果交给 `buildFormHtml` 写盘。
10
9
  *
11
- * 1. **一个文件,无服务器、无 CDN。** 组员可能在任何机器上、断网状态下打开。
12
- * 2. **草稿键由项目编号派生,不是时间戳。** 同一批项目重新生成表单后,
13
- * 仍能找到上一次的草稿;旧版把生成时间编进键里,导致草稿永远找不回。
14
- * 3. **进展是追加的。** 表单只收集「一条新进展」,提交时由 `poc-submit`
15
- * 追加到 `progress[]`,绝不覆盖历史。
10
+ * 这一点是硬约束,不是风格偏好。这个脚本曾经是一份 654 行的独立重写:
11
+ * 它自己实现了一遍 `projectForForm` / `buildFormHtml`,输出的是
12
+ * `{generatedAt, generatedBy, pocs:{...}}`,而 `poc-submit` 读的是
13
+ * `{changes:[...]}`。两边各自演化,结果就是**导出的表单根本交不回去**——
14
+ * 模型按 `poc-export/SKILL.md` 跑这个脚本,产出的文件 `poc-submit` 解析不了。
15
+ *
16
+ * 所以:任何表单行为(字段、意图分区、草稿键、变更集形状)的改动都只改
17
+ * `src/form.ts`,这里跟着 `lib/` 重新构建即可。**两处不能各自演化。**
18
+ *
19
+ * ## 为什么用动态 import
20
+ *
21
+ * `lib/` 是构建产物,可能不存在(刚 clone、刚 clean)。静态 import 失败时
22
+ * Node 只会抛一句 `ERR_MODULE_NOT_FOUND`,而这里需要告诉用户「先跑
23
+ * `npm run build`」。先探测再 import,才能给出可执行的提示,而不是让脚本
24
+ * 静默退回到某个旧实现。
16
25
  *
17
26
  * 用法:
18
- * node export-form.mjs --mode fill --poc <file|glob> --out <html>
19
- * node export-form.mjs --mode new --out <html>
27
+ * node export-form.mjs --mode fill --poc <file|glob> --intent progress --out <html>
28
+ * node export-form.mjs --mode new --intent new --out <html>
20
29
  *
21
- * 只读 YAML,只写 HTML。不改台账。
30
+ * 只读 YAML,只写 HTML。绝不改台账。
22
31
  */
23
32
 
24
- import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
25
- import { resolve } from 'node:path'
33
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
34
+ import { tmpdir } from 'node:os'
35
+ import { join, resolve } from 'node:path'
26
36
  import { parseArgs } from 'node:util'
27
37
  import YAML from 'yaml'
28
38
 
29
- /** v3 枚举,与 `schemas/enums.yaml` 一致。 */
30
- const ENUMS = {
31
- pocType: ['AI安全', '保护AI', 'ACG', 'SDL', '虚拟化', '大体量项目'],
32
- stage: ['G0-立项', 'G1-方案设计', 'G2-方案验证', 'G3-结果验证', 'G4-结果转化', 'closed'],
33
- status: ['进行中', '暂停', '已关闭', '已取消'],
34
- system: ['人保体系', '国寿体系'],
35
- achievement: ['达成', '部分达成', '未达成'],
36
- recognition: ['认可', '部分认可', '未认可', '待确认'],
37
- gate3_1: ['可证明', '待补证据'],
38
- gate3_2: ['已确认', '待确认'],
39
- progressType: ['内部Review', '客户阶段同步', 'Checkpoint'],
40
- completion: ['0%', '25%', '50%', '75%', '100%'],
41
- evidenceType: ['文档', '截图', '数据', '邮件', '链接'],
42
- riskLevel: ['high', 'medium', 'low'],
43
- businessStatus: ['已进入下一里程碑', '待推进', '补救中', '无后续动作'],
44
- }
45
-
46
- /** 读取一个 YAML 项目文件。 */
47
- function readProject(file) {
48
- const doc = YAML.parse(readFileSync(file, 'utf8')) ?? {}
49
- return doc
50
- }
39
+ /** 打包后的 `src/form.ts`。相对本脚本:skills/poc-export/scripts/ → 包根。 */
40
+ const FORM_MODULE = new URL('../../../lib/form.js', import.meta.url)
51
41
 
52
- /** 把 v3 记录裁剪成表单需要的形状(只保留可编辑的字段)。 */
53
- function projectForForm(record) {
54
- const org = record.org ?? {}
55
- const gate0 = record.gate0 ?? {}
56
- const plan = record.plan ?? {}
57
- const outcome = record.outcome ?? {}
58
- const progress = Array.isArray(record.progress) ? record.progress : []
59
- const lastSeq = progress.reduce((max, entry) => Math.max(max, Number(entry?.seq) || 0), 0)
60
- return {
61
- poc_id: record.poc_id ?? '',
62
- name: record.name ?? '',
63
- org: {
64
- system: org.system ?? '',
65
- company: org.company ?? '',
66
- department: org.department ?? '',
67
- },
68
- amount_wan: record.amount_wan ?? null,
69
- poc_type: record.poc_type ?? '',
70
- priority: record.priority ?? '',
71
- owner: record.owner ?? '',
72
- sales: record.sales ?? '',
73
- tech_owner: record.tech_owner ?? '',
74
- exec_sponsor: record.exec_sponsor ?? '',
75
- stage: record.stage ?? '',
76
- status: record.status ?? '',
77
- stage_since: record.stage_since ?? '',
78
- gate0: {
79
- why_customer: gate0.why_customer ?? '',
80
- why_us: gate0.why_us ?? '',
81
- decision_chain: gate0.decision_chain ?? '',
82
- post_poc_decision: gate0.post_poc_decision ?? '',
83
- competitor: gate0.competitor ?? '',
84
- conclusion: gate0.review?.conclusion ?? '',
85
- reviewer: gate0.review?.reviewer ?? '',
86
- },
87
- plan: {
88
- customer_pain: plan.customer_pain ?? '',
89
- expected_recognition: plan.expected_recognition ?? '',
90
- criteria: Array.isArray(plan.criteria) ? plan.criteria : [],
91
- scenarios: Array.isArray(plan.scenarios) ? plan.scenarios : [],
92
- our_edge: plan.our_edge ?? '',
93
- risks: Array.isArray(plan.risks) ? plan.risks : [],
94
- gate1_conclusion: plan.gate1?.conclusion ?? '',
95
- gate2_ready: plan.gate2?.ready ?? '',
96
- },
97
- outcome: {
98
- our_proof: outcome.our_proof ?? '',
99
- remaining_risks: outcome.remaining_risks ?? '',
100
- proved: outcome.conclusion?.proved ?? '',
101
- recognized: outcome.conclusion?.recognized ?? '',
102
- next_business: outcome.conclusion?.next_business ?? '',
103
- milestone: outcome.business?.milestone ?? '',
104
- business_owner: outcome.business?.owner ?? '',
105
- business_deadline: outcome.business?.deadline ?? '',
106
- business_status: outcome.business?.status ?? '',
107
- overall: outcome.overall ?? '',
108
- },
109
- // The form collects ONE new progress entry; its seq is assigned on submit.
110
- progress_count: progress.length,
111
- next_seq: lastSeq + 1,
112
- }
113
- }
114
-
115
- /** 空白项目,用于新建模式。 */
116
- function blankProject() {
117
- return projectForForm({})
118
- }
42
+ /** 表单能接受的意图,与 `src/form.ts` 的 `FormIntent` 一致。 */
43
+ const INTENTS = ['new', 'supplement', 'progress']
119
44
 
120
- /** 草稿键:由项目编号派生,不是时间戳(旧版的 bug)。 */
121
- function draftKeyFor(mode, pocIds) {
122
- const ids = pocIds.length === 0 ? ['__blank__'] : [...pocIds].sort()
123
- return `poc-form-v3-${mode}-${ids.join('-')}`
124
- }
125
-
126
- /** 生成 HTML。 */
127
- function buildFormHtml({ mode, projects }) {
128
- const pocIds = projects.map((project) => project.poc_id).filter((id) => id !== '')
129
- const draftKey = draftKeyFor(mode, pocIds)
130
- const title = mode === 'new' ? '新建 POC 项目' : `POC 信息收集(${projects.length} 个项目)`
131
- return `<!doctype html>
132
- <html lang="zh-CN">
133
- <head>
134
- <meta charset="utf-8">
135
- <meta name="viewport" content="width=device-width,initial-scale=1">
136
- <title>${escapeHtml(title)}</title>
137
- <style>${FORM_CSS}</style>
138
- </head>
139
- <body>
140
- <div class="shell">
141
- <header class="topbar">
142
- <div>
143
- <h1>${escapeHtml(title)}</h1>
144
- <p class="sub">填完点【提交并生成文件】,把下载的 <code>.json</code> 发回给发起人。数据模型 v3。</p>
145
- </div>
146
- <div class="actions">
147
- <button type="button" id="saveBtn">保存</button>
148
- <button type="button" id="clearBtn">清空草稿</button>
149
- </div>
150
- </header>
151
- <p class="notice" id="draftNotice" hidden></p>
152
- <p class="notice" id="restoreNotice" hidden>已恢复上次未提交的草稿。</p>
153
- <div id="projects"></div>
154
- <footer class="footer">
155
- <button type="button" id="previewBtn">预览 JSON</button>
156
- <button type="button" id="submitBtn" class="primary">提交并生成文件</button>
157
- </footer>
158
- <pre id="preview" hidden></pre>
159
- <div id="toast" hidden></div>
160
- </div>
161
- <script>var DATA = ${JSON.stringify({ mode, draftKey, enums: ENUMS, projects })};</script>
162
- <script>${FORM_SCRIPT}</script>
163
- </body>
164
- </html>
165
- `
45
+ /**
46
+ * 载入真正的生成器。
47
+ *
48
+ * 缺失时直接退出而不是降级:一个能跑但产出 `poc-submit` 读不了的文件的脚本,
49
+ * 比一个明确报错的脚本更糟——错误会推迟到组员填完之后才暴露。
50
+ */
51
+ async function loadFormModule() {
52
+ if (!existsSync(FORM_MODULE)) {
53
+ process.stderr.write(
54
+ `找不到 ${FORM_MODULE.pathname}\n` +
55
+ '表单生成器是构建产物,还没有编译。请先在包根目录执行:\n' +
56
+ ' npm run build\n' +
57
+ '然后重新运行本脚本。\n',
58
+ )
59
+ process.exit(1)
60
+ }
61
+ return import(FORM_MODULE.href)
166
62
  }
167
63
 
168
- /** HTML 转义。 */
169
- function escapeHtml(value) {
170
- return String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
64
+ /** 读取一个 YAML 项目文件。解析交给 `yaml`,形状交给 `projectForForm`。 */
65
+ function readProject(file) {
66
+ return YAML.parse(readFileSync(file, 'utf8')) ?? {}
171
67
  }
172
68
 
173
- const FORM_CSS = `
174
- *{box-sizing:border-box}
175
- body{margin:0;background:#F5F7FB;color:#192638;font:13px/1.6 'Avenir Next','PingFang SC',system-ui,sans-serif}
176
- .shell{max-width:980px;margin:0 auto;padding:24px 20px 80px}
177
- .topbar{display:flex;align-items:flex-start;gap:16px;padding:16px 18px;background:#fff;border:1px solid #E6EBF2;border-radius:12px;box-shadow:0 1px 2px rgba(20,32,52,.05)}
178
- .topbar h1{margin:0;font-size:19px}
179
- .sub{margin:4px 0 0;color:#5A6A80;font-size:12px}
180
- .actions{margin-left:auto;display:flex;gap:8px}
181
- button{height:30px;padding:0 12px;border-radius:8px;border:1px solid #E6EBF2;background:#fff;color:#5A6A80;font:inherit;cursor:pointer}
182
- button:hover{background:#F7F9FC;color:#192638}
183
- button.primary{background:#2864E8;border-color:transparent;color:#fff;font-weight:600}
184
- .notice{margin:10px 0 0;padding:8px 12px;border-radius:8px;background:#FBF1E2;color:#B77919;font-size:12px}
185
- .card{margin-top:14px;background:#fff;border:1px solid #E6EBF2;border-radius:12px;overflow:hidden;box-shadow:0 1px 2px rgba(20,32,52,.05)}
186
- .card-head{display:flex;align-items:baseline;gap:10px;padding:12px 16px;border-bottom:1px solid #E6EBF2;background:linear-gradient(180deg,#fff,#F7F9FC)}
187
- .card-title{margin:0;font-size:14px;font-weight:650}
188
- .card-id{font-family:ui-monospace,Menlo,monospace;font-size:10.5px;color:#8B99AC}
189
- .gaps{margin-left:auto;font-size:11px;color:#8B99AC}
190
- .gaps b{color:#C0392B}
191
- .section{padding:12px 16px;border-bottom:1px solid #E6EBF2}
192
- .section:last-child{border-bottom:0}
193
- .section-title{margin:0 0 8px;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:#8B99AC;font-weight:650}
194
- .row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
195
- .field{display:flex;flex-direction:column;gap:3px;min-width:0}
196
- .field.full{grid-column:1/-1}
197
- label{font-size:11px;color:#5A6A80}
198
- input,textarea,select{width:100%;padding:6px 9px;border:1px solid #E6EBF2;border-radius:7px;background:#fff;color:#192638;font:inherit}
199
- input:focus,textarea:focus,select:focus{outline:2px solid #2864E8;outline-offset:1px}
200
- textarea{min-height:64px;resize:vertical}
201
- .known{background:#F7F9FC;color:#5A6A80}
202
- .hint{font-size:10px;color:#8B99AC}
203
- .list-row{display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:6px;margin-bottom:6px}
204
- .list-row.risks{grid-template-columns:1fr 90px 1fr auto}
205
- .list-add{margin-top:4px}
206
- .footer{position:fixed;left:0;right:0;bottom:0;display:flex;gap:10px;justify-content:flex-end;padding:12px 24px;background:#fff;border-top:1px solid #E6EBF2}
207
- #preview{margin-top:14px;padding:14px;border-radius:10px;background:#fff;border:1px solid #E6EBF2;overflow:auto;font-family:ui-monospace,Menlo,monospace;font-size:11.5px;white-space:pre-wrap}
208
- #toast{position:fixed;left:50%;bottom:70px;transform:translateX(-50%);padding:9px 16px;border-radius:20px;background:#192638;color:#fff;font-size:12px}
209
- @media(max-width:640px){.row{grid-template-columns:1fr}.list-row,.list-row.risks{grid-template-columns:1fr}}
210
- `
211
-
212
- const FORM_SCRIPT = `
213
- (function () {
214
- var state = {};
215
- var storageAvailable = true;
216
- var saveTimer = null;
217
-
218
- function byId(id) { return document.getElementById(id); }
219
- function text(v) { return v === null || v === undefined ? '' : String(v); }
220
- function esc(v) { return text(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
221
-
222
- function toast(message) {
223
- var el = byId('toast');
224
- el.textContent = message;
225
- el.hidden = false;
226
- clearTimeout(toast.timer);
227
- toast.timer = setTimeout(function () { el.hidden = true; }, 2200);
228
- }
229
-
230
- function probeStorage() {
231
- try { localStorage.setItem('poc-form-v3-probe','1'); localStorage.removeItem('poc-form-v3-probe'); return true; }
232
- catch (e) { return false; }
233
- }
234
-
235
- function options(list, current) {
236
- var html = '<option value="">请选择</option>';
237
- for (var i = 0; i < list.length; i += 1) {
238
- html += '<option value="' + esc(list[i]) + '"' + (list[i] === current ? ' selected' : '') + '>' + esc(list[i]) + '</option>';
239
- }
240
- return html;
241
- }
242
-
243
- function field(key, label, value, opts) {
244
- opts = opts || {};
245
- var cls = 'field' + (opts.full ? ' full' : '');
246
- var id = 'f-' + key;
247
- if (opts.select) {
248
- return '<div class="' + cls + '"><label for="' + id + '">' + esc(label) + '</label>' +
249
- '<select id="' + id + '" data-key="' + key + '">' + options(opts.select, text(value)) + '</select></div>';
250
- }
251
- if (opts.area) {
252
- return '<div class="' + cls + '"><label for="' + id + '">' + esc(label) + '</label>' +
253
- '<textarea id="' + id + '" data-key="' + key + '">' + esc(value) + '</textarea></div>';
254
- }
255
- return '<div class="' + cls + '"><label for="' + id + '">' + esc(label) + '</label>' +
256
- '<input id="' + id + '" data-key="' + key + '" type="' + (opts.number ? 'number' : 'text') + '" value="' + esc(value) + '"></div>';
257
- }
258
-
259
- // ---- gap detection, mirroring the plugin's twelve rules on the FORM side.
260
- // Only the rules a colleague can actually fix from this form are shown; the
261
- // point is to tell them what is still blank, not to audit the ledger.
262
- function gapsFor(p) {
263
- var gaps = [];
264
- var g0 = p.gate0 || {};
265
- if (!g0.why_customer) gaps.push('客户为什么测 未填');
266
- if (!g0.why_us) gaps.push('我们为什么测 未填');
267
- if (!g0.decision_chain) gaps.push('决策链 未填');
268
- if (!g0.post_poc_decision) gaps.push('测后客户决策 未填');
269
- if (!p.tech_owner) gaps.push('客户技术责任人 未填');
270
- var plan = p.plan || {};
271
- var c = (plan.criteria || []).length;
272
- if (c > 0 && (c < 2 || c > 3)) gaps.push('成功指标 ' + c + ' 个(要求 2-3)');
273
- var s = (plan.scenarios || []).length;
274
- if (s > 0 && (s < 3 || s > 5)) gaps.push('场景 ' + s + ' 个(要求 3-5)');
275
- var r = (plan.risks || []).length;
276
- if (r > 3) gaps.push('风险 ' + r + ' 个(上限 3)');
277
- var o = p.outcome || {};
278
- if (o.achievement === '达成' && !o.milestone) gaps.push('已达成但无下一步里程碑');
279
- return gaps;
280
- }
281
-
282
- function render() {
283
- var host = byId('projects');
284
- var html = '';
285
- DATA.projects.forEach(function (project, index) {
286
- var id = project.poc_id || '__blank__';
287
- var p = state[id];
288
- var gaps = gapsFor(p);
289
- html += '<section class="card" data-index="' + index + '" data-id="' + esc(id) + '">';
290
- html += '<div class="card-head"><h2 class="card-title">' + esc(p.name || (DATA.mode === 'new' ? '新项目' : id)) + '</h2>';
291
- html += '<span class="card-id">' + esc(id === '__blank__' ? '' : id) + '</span>';
292
- html += '<span class="gaps">' + (gaps.length === 0 ? '未发现必填缺失' : '<b>' + gaps.length + '</b> 项待补:' + esc(gaps.slice(0,3).join('、')) + (gaps.length>3?'…':'')) + '</span></div>';
293
-
294
- html += '<div class="section"><h3 class="section-title">身份</h3><div class="row">';
295
- html += field('name', '项目名称', p.name, { full: true });
296
- html += field('system', '体系', p.org.system, { select: DATA.enums.system });
297
- html += field('company', '主业公司', p.org.company);
298
- html += field('department', '部门(可选)', p.org.department);
299
- html += field('amount_wan', '预计金额(万元)', p.amount_wan, { number: true });
300
- html += field('poc_type', '项目类型', p.poc_type, { select: DATA.enums.pocType });
301
- html += field('stage', '阶段', p.stage, { select: DATA.enums.stage });
302
- html += field('status', '状态', p.status, { select: DATA.enums.status });
303
- html += field('owner', 'POC Owner(我方)', p.owner);
304
- html += field('sales', '销售发起人', p.sales);
305
- html += field('tech_owner', '客户技术责任人', p.tech_owner);
306
- html += field('exec_sponsor', '客户业务决策人', p.exec_sponsor);
307
- html += '</div></div>';
308
-
309
- html += '<div class="section"><h3 class="section-title">G0 · 值不值得做</h3><div class="row">';
310
- html += field('why_customer', '客户为什么要测', p.gate0.why_customer, { area: true, full: true });
311
- html += field('why_us', '我们为什么测(含下一步动作和目标)', p.gate0.why_us, { area: true, full: true });
312
- html += field('decision_chain', '项目流程 / 决策链', p.gate0.decision_chain, { area: true, full: true });
313
- html += field('post_poc_decision', '测完后客户会做什么决策', p.gate0.post_poc_decision, { area: true, full: true });
314
- html += field('competitor', '主要竞争对手', p.gate0.competitor);
315
- html += '</div></div>';
316
-
317
- html += '<div class="section"><h3 class="section-title">计划 · G1 / G2</h3><div class="row">';
318
- html += field('customer_pain', '客户核心痛点', p.plan.customer_pain, { area: true, full: true });
319
- html += field('expected_recognition', '期望客户认可什么', p.plan.expected_recognition, { area: true, full: true });
320
- html += field('our_edge', '我方优势 / 赢点', p.plan.our_edge, { area: true, full: true });
321
- html += '</div>';
322
- html += '<h3 class="section-title" style="margin-top:12px">关键成功指标(2-3 项)</h3><div data-list="criteria">';
323
- (p.plan.criteria || []).forEach(function (c, i) {
324
- html += '<div class="list-row"><input data-list-key="criteria" data-i="' + i + '" data-f="name" placeholder="指标名称" value="' + esc(c.name) + '">' +
325
- '<input data-list-key="criteria" data-i="' + i + '" data-f="metric" placeholder="衡量标准" value="' + esc(c.metric) + '">' +
326
- '<input data-list-key="criteria" data-i="' + i + '" data-f="target" placeholder="目标值" value="' + esc(c.target) + '">' +
327
- '<button type="button" data-remove="criteria" data-i="' + i + '">删</button></div>';
328
- });
329
- html += '<button type="button" class="list-add" data-add="criteria">+ 加一项指标</button></div>';
330
- html += '<h3 class="section-title" style="margin-top:12px">验证场景(3-5 个)</h3><div data-list="scenarios">';
331
- (p.plan.scenarios || []).forEach(function (s, i) {
332
- html += '<div class="list-row" style="grid-template-columns:1fr auto"><input data-list-key="scenarios" data-i="' + i + '" data-f="value" placeholder="场景" value="' + esc(s) + '">' +
333
- '<button type="button" data-remove="scenarios" data-i="' + i + '">删</button></div>';
334
- });
335
- html += '<button type="button" class="list-add" data-add="scenarios">+ 加一个场景</button></div>';
336
- html += '<h3 class="section-title" style="margin-top:12px">风险(上限 3)</h3><div data-list="risks">';
337
- (p.plan.risks || []).forEach(function (r, i) {
338
- html += '<div class="list-row risks"><input data-list-key="risks" data-i="' + i + '" data-f="name" placeholder="风险描述" value="' + esc(r.name) + '">' +
339
- '<select data-list-key="risks" data-i="' + i + '" data-f="level">' + options(DATA.enums.riskLevel, text(r.level)) + '</select>' +
340
- '<input data-list-key="risks" data-i="' + i + '" data-f="mitigation" placeholder="应对措施" value="' + esc(r.mitigation) + '">' +
341
- '<button type="button" data-remove="risks" data-i="' + i + '">删</button></div>';
342
- });
343
- html += '<button type="button" class="list-add" data-add="risks">+ 加一条风险</button></div></div>';
344
-
345
- // ---- the new progress entry: the core of v3, and always an append
346
- html += '<div class="section"><h3 class="section-title">新增一条进展(第 ' + p.next_seq + ' 次,追加)</h3>';
347
- html += '<p class="hint">进展是追加的,不会覆盖历史。只填你这次真正推进了什么。</p><div class="row">';
348
- html += field('p_date', '日期', p.newProgress.date, { number: false, full: false });
349
- html += field('p_type', '类型', p.newProgress.type, { select: DATA.enums.progressType });
350
- html += field('p_goal', '这次的目标', p.newProgress.goal, { area: true, full: true });
351
- html += field('p_actual', '实际做到什么', p.newProgress.actual, { area: true, full: true });
352
- html += field('p_completion', '完成度', p.newProgress.completion, { select: DATA.enums.completion });
353
- html += field('p_synced', '同步的客户', p.newProgress.synced_with);
354
- html += field('p_feedback', '客户反馈', p.newProgress.feedback, { area: true, full: true });
355
- html += field('p_recognition', '客户认可', p.newProgress.recognition, { select: DATA.enums.recognition });
356
- html += field('p_gate3_1', 'G3-1', p.newProgress.gate3_1, { select: DATA.enums.gate3_1 });
357
- html += field('p_gate3_2', 'G3-2', p.newProgress.gate3_2, { select: DATA.enums.gate3_2 });
358
- html += field('p_ev_title', '证据标题', p.newProgress.evidence_title);
359
- html += field('p_ev_link', '证据链接', p.newProgress.evidence_link);
360
- html += field('p_next_goal', '下一步目标', p.newProgress.next_goal, { area: true, full: true });
361
- html += field('p_next_owner', '下一步负责人', p.newProgress.next_owner);
362
- html += field('p_next_deadline', '下一步截止', p.newProgress.next_deadline);
363
- html += '</div></div>';
364
-
365
- html += '<div class="section"><h3 class="section-title">结论</h3><div class="row">';
366
- html += field('o_proof', '我方证据', p.outcome.our_proof, { area: true, full: true });
367
- html += field('o_remaining', '剩余风险', p.outcome.remaining_risks, { area: true, full: true });
368
- html += field('o_proved', '我们证明了什么', p.outcome.proved, { area: true, full: true });
369
- html += field('o_recognized', '客户认可了什么', p.outcome.recognized, { area: true, full: true });
370
- html += field('o_next_business', '下一步业务动作', p.outcome.next_business, { area: true, full: true });
371
- html += field('o_milestone', 'Next Milestone', p.outcome.milestone);
372
- html += field('o_business_owner', '里程碑负责人', p.outcome.business_owner);
373
- html += field('o_business_deadline', '里程碑截止', p.outcome.business_deadline);
374
- html += field('o_business_status', '里程碑状态', p.outcome.business_status, { select: DATA.enums.businessStatus });
375
- html += field('o_overall', 'POC 总体结论', p.outcome.overall, { area: true, full: true });
376
- html += '</div></div>';
377
-
378
- html += '</section>';
379
- });
380
- host.innerHTML = html;
381
- }
382
-
383
- function initState() {
384
- DATA.projects.forEach(function (project) {
385
- var id = project.poc_id || '__blank__';
386
- state[id] = JSON.parse(JSON.stringify(project));
387
- if (!state[id].newProgress) state[id].newProgress = {};
388
- });
389
- storageAvailable = probeStorage();
390
- if (!storageAvailable) {
391
- byId('draftNotice').hidden = false;
392
- byId('draftNotice').textContent = '当前浏览器禁用了本地存储,本次填写不会被自动保存。填完请立刻下载。';
393
- return;
394
- }
395
- try {
396
- var saved = localStorage.getItem(DATA.draftKey);
397
- if (saved) {
398
- var parsed = JSON.parse(saved);
399
- Object.keys(parsed).forEach(function (key) { if (state[key]) state[key] = parsed[key]; });
400
- byId('restoreNotice').hidden = false;
401
- }
402
- } catch (e) {
403
- // A corrupt draft must never block the form: drop it and start clean.
404
- localStorage.removeItem(DATA.draftKey);
405
- }
406
- }
407
-
408
- function persist() {
409
- if (!storageAvailable) return;
410
- try { localStorage.setItem(DATA.draftKey, JSON.stringify(state)); }
411
- catch (e) { /* quota: the form still works, just without autosave */ }
412
- }
413
-
414
- function scheduleSave() {
415
- if (!storageAvailable) return;
416
- clearTimeout(saveTimer);
417
- saveTimer = setTimeout(persist, 2000);
418
- }
419
-
420
- // ---- read the DOM back into state, then re-render the gap counters
421
- function collect() {
422
- var cards = document.querySelectorAll('.card');
423
- for (var c = 0; c < cards.length; c += 1) {
424
- var card = cards[c];
425
- var id = card.getAttribute('data-id');
426
- var p = state[id];
427
- if (!p) continue;
428
-
429
- var inputs = card.querySelectorAll('[data-key]');
430
- for (var i = 0; i < inputs.length; i += 1) {
431
- var el = inputs[i];
432
- var key = el.getAttribute('data-key');
433
- var value = el.value;
434
- if (key.indexOf('p_') === 0) {
435
- p.newProgress[PROGRESS_KEY[key]] = value;
436
- } else if (key.indexOf('o_') === 0) {
437
- p.outcome[OUTCOME_KEY[key]] = value;
438
- } else if (key === 'system' || key === 'company' || key === 'department') {
439
- p.org[key] = value;
440
- } else if (key === 'why_customer' || key === 'why_us' || key === 'decision_chain' || key === 'post_poc_decision' || key === 'competitor') {
441
- p.gate0[key] = value;
442
- } else if (key === 'customer_pain' || key === 'expected_recognition' || key === 'our_edge') {
443
- p.plan[key] = value;
444
- } else if (key === 'amount_wan') {
445
- p.amount_wan = value === '' ? null : Number(value);
446
- } else {
447
- p[key] = value;
448
- }
449
- }
450
- }
451
- }
452
-
453
- var PROGRESS_KEY = {
454
- p_date: 'date', p_type: 'type', p_goal: 'goal', p_actual: 'actual', p_completion: 'completion',
455
- p_synced: 'synced_with', p_feedback: 'feedback', p_recognition: 'recognition',
456
- p_gate3_1: 'gate3_1', p_gate3_2: 'gate3_2',
457
- p_ev_title: 'evidence_title', p_ev_link: 'evidence_link',
458
- p_next_goal: 'next_goal', p_next_owner: 'next_owner', p_next_deadline: 'next_deadline'
459
- };
460
- var OUTCOME_KEY = {
461
- o_proof: 'our_proof', o_remaining: 'remaining_risks', o_proved: 'proved', o_recognized: 'recognized',
462
- o_next_business: 'next_business', o_milestone: 'milestone', o_business_owner: 'business_owner',
463
- o_business_deadline: 'business_deadline', o_business_status: 'business_status', o_overall: 'overall'
464
- };
465
-
466
- // Update ONLY the gap badge in place. Re-rendering the whole card on every
467
- // keystroke would steal focus and wipe the caret position, which is the
468
- // classic way an autosaving form becomes unusable.
469
- function refreshGapBadge(card) {
470
- var id = card.getAttribute('data-id');
471
- var p = state[id];
472
- if (!p) return;
473
- var gaps = gapsFor(p);
474
- var badge = card.querySelector('.gaps');
475
- if (!badge) return;
476
- badge.innerHTML = gaps.length === 0
477
- ? '未发现必填缺失'
478
- : '<b>' + gaps.length + '</b> 项待补:' + esc(gaps.slice(0, 3).join('、')) + (gaps.length > 3 ? '…' : '');
479
- }
480
-
481
- document.addEventListener('input', function (event) {
482
- var el = event.target;
483
- if (!el || !el.getAttribute) return;
484
- var key = el.getAttribute('data-key');
485
- var listKey = el.getAttribute('data-list-key');
486
- if (listKey) {
487
- var card = el.closest('.card');
488
- var p = state[card.getAttribute('data-id')];
489
- var idx = Number(el.getAttribute('data-i'));
490
- var f = el.getAttribute('data-f');
491
- if (listKey === 'scenarios') p.plan.scenarios[idx] = el.value;
492
- else {
493
- p.plan[listKey][idx] = p.plan[listKey][idx] || {};
494
- p.plan[listKey][idx][f] = el.value;
495
- }
496
- refreshGapBadge(card);
497
- } else if (key) {
498
- collect();
499
- var card2 = el.closest('.card');
500
- if (card2) refreshGapBadge(card2);
501
- }
502
- scheduleSave();
503
- });
504
-
505
- document.addEventListener('change', function (event) {
506
- if (event.target && event.target.getAttribute && (event.target.getAttribute('data-key') || event.target.getAttribute('data-list-key'))) {
507
- collect();
508
- scheduleSave();
509
- }
510
- });
511
-
512
- document.addEventListener('click', function (event) {
513
- var el = event.target;
514
- if (!el || !el.getAttribute) return;
515
- var add = el.getAttribute('data-add');
516
- var remove = el.getAttribute('data-remove');
517
- if (add) {
518
- var card = el.closest('.card');
519
- var p = state[card.getAttribute('data-id')];
520
- if (add === 'scenarios') p.plan.scenarios.push('');
521
- else p.plan[add].push(add === 'risks' ? { name: '', level: 'medium', mitigation: '' } : { name: '', metric: '', target: '' });
522
- collect(); render(); persist();
523
- } else if (remove) {
524
- var card2 = el.closest('.card');
525
- var p2 = state[card2.getAttribute('data-id')];
526
- var idx = Number(el.getAttribute('data-i'));
527
- p2.plan[remove].splice(idx, 1);
528
- collect(); render(); persist();
529
- }
530
- });
531
-
532
- function collectOutput() {
533
- collect();
534
- var out = { generatedAt: new Date().toISOString(), generatedBy: 'POC 表单 v3', pocs: {} };
535
- Object.keys(state).forEach(function (id) {
536
- var p = state[id];
537
- var np = p.newProgress || {};
538
- // A progress entry only counts when it says something actually happened.
539
- var hasProgress = !!(np.actual || np.goal);
540
- out.pocs[id === '__blank__' ? (p.poc_id || '') : id] = {
541
- identity: { name: p.name, org: p.org, amount_wan: p.amount_wan, poc_type: p.poc_type, stage: p.stage, status: p.status, owner: p.owner, sales: p.sales, tech_owner: p.tech_owner, exec_sponsor: p.exec_sponsor },
542
- gate0: p.gate0,
543
- plan: p.plan,
544
- outcome: p.outcome,
545
- progress: hasProgress ? [{
546
- date: np.date, type: np.type, goal: np.goal, actual: np.actual, completion: np.completion,
547
- evidence: np.evidence_title ? [{ title: np.evidence_title, link: np.evidence_link || '', type: '文档' }] : [],
548
- customer: { synced_with: np.synced_with, feedback: np.feedback, recognition: np.recognition },
549
- gate3_1: np.gate3_1, gate3_2: np.gate3_2,
550
- next: { goal: np.next_goal, owner: np.next_owner, deadline: np.next_deadline }
551
- }] : []
552
- };
553
- });
554
- return out;
555
- }
556
-
557
- byId('saveBtn').addEventListener('click', function () { collect(); persist(); toast('已保存到本地草稿'); });
558
-
559
- byId('clearBtn').addEventListener('click', function () {
560
- if (!confirm('清空本地草稿?台账数据不受影响。')) return;
561
- if (storageAvailable) localStorage.removeItem(DATA.draftKey);
562
- location.reload();
563
- });
564
-
565
- byId('previewBtn').addEventListener('click', function () {
566
- var pre = byId('preview');
567
- pre.textContent = JSON.stringify(collectOutput(), null, 2);
568
- pre.hidden = false;
569
- pre.scrollIntoView({ behavior: 'smooth', block: 'start' });
570
- });
571
-
572
- byId('submitBtn').addEventListener('click', function () {
573
- var out = collectOutput();
574
- var name = 'poc-changes-' + new Date().toISOString().slice(0, 10) + '.json';
575
- var blob = new Blob([JSON.stringify(out, null, 2)], { type: 'application/json' });
576
- var url = URL.createObjectURL(blob);
577
- var a = document.createElement('a');
578
- a.href = url; a.download = name; a.click();
579
- setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
580
- toast('已生成 ' + name + ',请发给发起人');
581
- });
582
-
583
- initState();
584
- render();
585
- // Seed the progress date with today so the field is never a blank trap.
586
- var cards = document.querySelectorAll('.card');
587
- for (var i = 0; i < cards.length; i += 1) {
588
- var id = cards[i].getAttribute('data-id');
589
- if (!state[id].newProgress.date) {
590
- state[id].newProgress.date = new Date().toISOString().slice(0, 10);
591
- var dateInput = cards[i].querySelector('[data-key="p_date"]');
592
- if (dateInput) dateInput.value = state[id].newProgress.date;
593
- }
69
+ /** 展开 `--poc` 参数:单个文件,或含 `*` 的通配符。 */
70
+ function expandPocPattern(pattern) {
71
+ const expanded = pattern.startsWith('~') ? pattern.replace(/^~/, process.env.HOME ?? '') : pattern
72
+ if (!expanded.includes('*')) return [expanded]
73
+ // Shell-style glob without a dependency: split on the last slash, then match
74
+ // the file names against the pattern's basename glob.
75
+ const dir = expanded.slice(0, expanded.lastIndexOf('/'))
76
+ const glob = expanded.slice(expanded.lastIndexOf('/') + 1)
77
+ const regex = new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`)
78
+ let names = []
79
+ try {
80
+ names = readdirSync(dir)
81
+ } catch {
82
+ return []
594
83
  }
595
- })();
596
- `
84
+ return names.filter((name) => regex.test(name)).map((name) => `${dir}/${name}`)
85
+ }
597
86
 
598
87
  /** 主流程。 */
599
- function main() {
88
+ async function main() {
600
89
  const { values } = parseArgs({
601
90
  options: {
602
91
  mode: { type: 'string', default: 'fill' },
92
+ intent: { type: 'string' },
603
93
  poc: { type: 'string' },
604
94
  out: { type: 'string' },
605
95
  },
606
96
  })
607
- const mode = values.mode === 'new' ? 'new' : 'fill'
608
- const out = values.out ?? `/tmp/poc-form-${mode}-${Date.now()}.html`
97
+
98
+ if (values.mode !== 'new' && values.mode !== 'fill') {
99
+ throw new Error(`--mode 只接受 fill 或 new,收到:${values.mode}`)
100
+ }
101
+ // 表单内部的 mode 只有 `blank`:它描述的是「页面从空白项目开始」,而命令行
102
+ // 的 `new` 描述的是「用户要新建项目」,两者是同一件事的两种叫法。
103
+ const mode = values.mode === 'new' ? 'blank' : 'fill'
104
+
105
+ // 意图决定表单问什么(见 `src/form.ts` 的 `resolveSections`)。默认值按模式
106
+ // 推导:新建项目必然是 `new`,填充已有项目默认是补全而不是记进展——记进展
107
+ // 是更窄的动作,不该由「没写参数」隐式选中。
108
+ const intent = values.intent ?? (mode === 'blank' ? 'new' : 'supplement')
109
+ if (!INTENTS.includes(intent)) {
110
+ throw new Error(`--intent 只接受 ${INTENTS.join(' / ')},收到:${intent}`)
111
+ }
609
112
 
610
113
  let files = []
611
114
  if (mode === 'fill') {
@@ -614,41 +117,37 @@ function main() {
614
117
  if (files.length === 0) throw new Error(`没有匹配到任何 YAML:${values.poc}`)
615
118
  }
616
119
 
617
- const projects = mode === 'new'
618
- ? [{ ...blankProject(), poc_id: '', newProgress: {} }]
619
- : files.map((file) => {
620
- const record = readProject(file)
621
- const project = projectForForm(record)
622
- return { ...project, newProgress: {} }
623
- })
120
+ const { buildFormHtml, projectForForm, formFileName } = await loadFormModule()
624
121
 
625
- const html = buildFormHtml({ mode, projects })
626
- writeFileSync(out, html, 'utf8')
122
+ // `blank` 模式的 HTML 由 `buildFormHtml` 自己造空白项目,`projects` 只是
123
+ // 为了类型和摘要而传;`fill` 模式才逐条转换台账记录。
124
+ const projects = mode === 'blank' ? [] : files.map((file) => projectForForm(readProject(file)))
125
+ const pocIds = projects.map((project) => project.pocId).filter((id) => id !== '')
627
126
 
628
- process.stdout.write(`已生成:${resolve(out)}\n 模式:${mode}\n 项目数:${projects.length}\n`)
629
- for (const project of projects) {
630
- const label = project.name === '' ? '(未命名)' : project.name
631
- process.stdout.write(` - ${project.poc_id === '' ? '(新建)' : project.poc_id} ${label}:已有 ${project.progress_count} 条进展\n`)
632
- }
633
- process.stdout.write(' 交给组员:双击打开 → 填写 → 点【提交并生成文件】→ 把 .json 发回\n')
634
- }
127
+ const now = new Date()
128
+ // 文件名由生成器决定,不在这里拼:日期戳格式和批量命名规则都属于表单契约,
129
+ // 两边各写一份就会出现「CLI 产出的名字 GUI 那边认不出」。
130
+ const out = values.out ?? join(tmpdir(), formFileName({ mode, pocIds, now }))
635
131
 
636
- /** 展开 `--poc` 参数:单个文件,或含 `*` 的通配符。 */
637
- function expandPocPattern(pattern) {
638
- const expanded = pattern.startsWith('~') ? pattern.replace(/^~/, process.env.HOME ?? '') : pattern
639
- if (!expanded.includes('*')) return [expanded]
640
- // Shell-style glob without a dependency: split on the last slash, then match
641
- // the file names against the pattern's basename glob.
642
- const dir = expanded.slice(0, expanded.lastIndexOf('/'))
643
- const glob = expanded.slice(expanded.lastIndexOf('/') + 1)
644
- const regex = new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`)
645
- let names = []
646
- try {
647
- names = readdirSync(dir)
648
- } catch {
649
- return []
132
+ const html = buildFormHtml({ mode, intent, projects, now })
133
+ writeFileSync(out, html, 'utf8')
134
+
135
+ const projectCount = mode === 'blank' ? 1 : projects.length
136
+ process.stdout.write(`已生成:${resolve(out)}\n 模式:${mode === 'blank' ? 'new' : 'fill'}\n 意图:${intent}\n 项目数:${projectCount}\n`)
137
+ if (mode === 'blank') {
138
+ process.stdout.write(' - (新建)空白项目:无已有进展\n')
139
+ } else {
140
+ for (const project of projects) {
141
+ const label = project.name === '' ? '(未命名)' : project.name
142
+ process.stdout.write(` - ${project.pocId === '' ? '(新建)' : project.pocId} ${label}:已有 ${project.existingProgressCount} 条进展\n`)
143
+ }
650
144
  }
651
- return names.filter((name) => regex.test(name)).map((name) => `${dir}/${name}`)
145
+ process.stdout.write(
146
+ ' 交给组员:双击打开 → 填写 → 点【生成回传文件 (.html)】→ 把 .html 发回(或点【下载变更集 (.json)】发 .json)\n',
147
+ )
652
148
  }
653
149
 
654
- main()
150
+ main().catch((error) => {
151
+ process.stderr.write(`生成失败:${error instanceof Error ? error.message : String(error)}\n`)
152
+ process.exit(1)
153
+ })