lantern-harness 0.1.4 → 0.1.6
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.
- package/CHANGELOG.md +67 -0
- package/README.md +6 -6
- package/builtin/session/lh-nav-groups.mjs +3 -0
- package/cli/server.mjs +2 -0
- package/config/app.defaults.json +6 -1
- package/dist/500.html +22 -4
- package/dist/_astro/Base.DGaLtzMo.css +1 -0
- package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.-g0SuFCa.js → Base.astro_astro_type_script_index_0_lang.uhTNjhRY.js} +1 -1
- package/dist/_astro/CaseExecBoard.FJ1Y9b4e.js +1 -0
- package/dist/_astro/{CaseGenerateApp.BQalnGiC.js → CaseGenerateApp.CT2n4VOf.js} +1 -1
- package/dist/_astro/{CasesLibrary.u7ek8rOp.js → CasesLibrary.BjrehOiI.js} +1 -1
- package/dist/_astro/ChatApp.Dqfx4FcI.js +276 -0
- package/dist/_astro/ConfirmDialog.CBVsDJ8f.js +1 -0
- package/dist/_astro/DashboardBoard.wILBO_CD.js +5 -0
- package/dist/_astro/{DocsFileBrowser.CHVgH1vj.js → DocsFileBrowser.D32MgVAR.js} +1 -1
- package/dist/_astro/{DocsPager.DaiWchhj.js → DocsPager.BARD7JvD.js} +1 -1
- package/dist/_astro/DrawerField.CWMLhcPX.js +1 -0
- package/dist/_astro/{KnowledgeLibrary.DSxgeW4L.js → KnowledgeLibrary.C-Sg2R6B.js} +1 -1
- package/dist/_astro/NamePromptDialog.Dl5kSnQI.js +1 -0
- package/dist/_astro/NavLibraries.BzInZVDf.js +1 -0
- package/dist/_astro/PluginsPage.CS1GaJtR.js +1 -0
- package/dist/_astro/PluginsPage.CVyua_fb.js +39 -0
- package/dist/_astro/PmBugsBoard.BXUu0kNL.js +1 -0
- package/dist/_astro/PmIterationsBoard.Deso1uyK.js +1 -0
- package/dist/_astro/PmProjectDetail.CtQdpGes.js +1 -0
- package/dist/_astro/PmProjectsBoard.MM4vxneK.js +1 -0
- package/dist/_astro/PmRequirementsBoard.62ONLCH5.js +1 -0
- package/dist/_astro/PmRequirementsBoard.SLVDgspp.js +1 -0
- package/dist/_astro/PmShared.CwCmF-kI.js +1 -0
- package/dist/_astro/{PromptsLibrary.DWgox1du.js → PromptsLibrary.Z1DQBrFL.js} +1 -1
- package/dist/_astro/{ReportsPage.BlHA_AtE.js → ReportsPage.CGpIPPr9.js} +1 -1
- package/dist/_astro/RequirementsLibrary.D8078xLd.js +1 -0
- package/dist/_astro/{SearchableSelect.BMl1Bp59.js → SearchableSelect.BTJoZC_a.js} +1 -1
- package/dist/_astro/SelectDropdown.Buv7rQJ_.js +1 -0
- package/dist/_astro/SettingsDialog.BA57gp90.js +1 -0
- package/dist/_astro/SlideOverDrawer.TPbGEoWn.js +1 -0
- package/dist/_astro/SpaceSwitcher.DZ8b_85M.js +7 -0
- package/dist/_astro/TasksBoard.CL-sNPZN.js +1 -0
- package/dist/_astro/TemplatesLibrary.d6uIe7I-.js +1 -0
- package/dist/_astro/TestStatsBoard.CSdXWc4Q.js +1 -0
- package/dist/_astro/TodosBoard.nl23X5Gi.js +1 -0
- package/dist/_astro/app-config.huKxSIlN.js +1 -0
- package/dist/_astro/case-exec.BipZCK6G.js +1 -0
- package/dist/_astro/dialog.DXHznyjD.js +1 -0
- package/dist/_astro/i18n.Bbh04ngD.js +7 -0
- package/dist/_astro/{open-docs-in-session.BC5D-BoF.js → open-docs-in-session.B5cUxqHi.js} +1 -1
- package/dist/_astro/plugins.DaDJq-mn.js +1 -0
- package/dist/_astro/pm.CpFmMslU.js +4 -0
- package/dist/_astro/{settings.DBIYsQY-.js → settings.CMK4PEak.js} +2 -2
- package/dist/_astro/spaces-client.CoQfaOIO.js +1 -0
- package/dist/_astro/tasks.otRBFydq.js +1 -0
- package/dist/_astro/{test-stats.BIHEJz5c.js → test-stats.MEm3K2rB.js} +1 -1
- package/dist/_astro/{view-prefs.C9Mtta1E.js → view-prefs.Dhdh8Z5a.js} +1 -1
- package/dist/case-exec/index.html +23 -5
- package/dist/cases/generate/index.html +23 -5
- package/dist/cases/library/index.html +23 -5
- package/dist/cn-holidays.json +42 -0
- package/dist/dashboard/index.html +282 -0
- package/dist/docs/changelog/index.html +85 -6
- package/dist/docs/install/index.html +22 -4
- package/dist/docs/manual/index.html +117 -21
- package/dist/index.html +23 -5
- package/dist/knowledge/index.html +23 -5
- package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +22 -4
- package/dist/plugins/index.html +23 -5
- package/dist/pm/bugs/index.html +281 -0
- package/dist/pm/iterations/index.html +281 -0
- package/dist/pm/projects/detail/index.html +281 -0
- package/dist/pm/projects/index.html +281 -0
- package/dist/pm/requirements/index.html +281 -0
- package/dist/prompts/index.html +23 -5
- package/dist/reports/index.html +23 -5
- package/dist/requirements/index.html +23 -5
- package/dist/tasks/index.html +23 -5
- package/dist/templates/index.html +23 -5
- package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +22 -4
- package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +22 -4
- package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +22 -4
- package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +22 -4
- package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +22 -4
- package/dist/test-stats/index.html +23 -5
- package/dist/todos/index.html +23 -5
- package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +1 -1
- package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +91 -38
- package/lh-plugins/lh-memory.mjs +1 -3
- package/lh-plugins/lh-pm.mjs +949 -0
- package/lh-plugins/lh-reports.mjs +12 -12
- package/lh-plugins/lh-stats.mjs +6 -2
- package/lh-plugins/lh-tasks.mjs +6 -8
- package/lh-plugins/lh-todos.mjs +35 -8
- package/package.json +2 -1
- package/dist/_astro/Base.C_AmDbI9.css +0 -1
- package/dist/_astro/CaseExecBoard.CNZh0sre.js +0 -1
- package/dist/_astro/ChatApp.Dk5uOXr0.js +0 -273
- package/dist/_astro/ConfirmDialog.Dbyjb4-6.js +0 -1
- package/dist/_astro/DrawerField.KANqQwFl.js +0 -1
- package/dist/_astro/NamePromptDialog.DZSZ5Y16.js +0 -1
- package/dist/_astro/NavLibraries.BN5smOBt.js +0 -1
- package/dist/_astro/PluginsPage.BB18crT3.js +0 -1
- package/dist/_astro/PluginsPage.Oh8hWup8.js +0 -39
- package/dist/_astro/RequirementsLibrary.2o-KMk7K.js +0 -1
- package/dist/_astro/SelectDropdown.flhHcwyd.js +0 -1
- package/dist/_astro/SettingsDialog.Cs8z0Hhb.js +0 -1
- package/dist/_astro/SpaceSwitcher.DicPqrSH.js +0 -7
- package/dist/_astro/TasksBoard.dgJxOpVG.js +0 -1
- package/dist/_astro/TemplatesLibrary.BfC9HIuu.js +0 -1
- package/dist/_astro/TestStatsBoard.Dg23e0O_.js +0 -1
- package/dist/_astro/TodosBoard.CyvTZybr.js +0 -1
- package/dist/_astro/app-config.Crg0VdkS.js +0 -1
- package/dist/_astro/case-exec.HjGrOY_O.js +0 -1
- package/dist/_astro/i18n.C8FKLrB5.js +0 -7
- package/dist/_astro/plugins.CNOYmeAe.js +0 -1
- package/dist/_astro/tasks.WhfT-DnC.js +0 -1
- /package/dist/{apple-touch-icon.png → brand/apple-touch-icon.png} +0 -0
- /package/dist/{brand-mark.png → brand/brand-mark.png} +0 -0
- /package/dist/{favicon.png → brand/favicon.png} +0 -0
- /package/dist/{icon-192.png → brand/icon-192.png} +0 -0
|
@@ -0,0 +1,949 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 项目管理存储(空间级):四个插件各自的目录与数据文件。
|
|
3
|
+
*
|
|
4
|
+
* 数据落在 `<当前数据空间>/<插件目录>/<插件目录>.json`:跟空间走、不跟 git 走。
|
|
5
|
+
* 目录只在真的有数据时创建(首次写入),跟其它插件的「按开关懒建、空目录不铺」一致;
|
|
6
|
+
* 删项目这类跨实体级联会依次写回受影响的文件。
|
|
7
|
+
*
|
|
8
|
+
* 编号(REQ-001 / BUG-001)由服务端按 seq 递增分配,删除后不回收。
|
|
9
|
+
* 所有枚举与校验都在这里做一次,前端与 AI 工具只提交白名单字段。
|
|
10
|
+
*/
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
import { getDataRoot } from '../builtin/session/space-context.mjs';
|
|
16
|
+
|
|
17
|
+
const PREFIX = '/__tb_pm';
|
|
18
|
+
const VERSION = 1;
|
|
19
|
+
|
|
20
|
+
/** 四类实体各自的空间目录 / 数据文件 / id 前缀 */
|
|
21
|
+
export const PM_ENTITY_META = {
|
|
22
|
+
projects: { dir: '项目列表', file: '项目列表.json', idPrefix: 'pj', hasSeq: false },
|
|
23
|
+
iterations: { dir: '迭代管理', file: '迭代管理.json', idPrefix: 'it', hasSeq: false },
|
|
24
|
+
requirements: { dir: '需求管理', file: '需求管理.json', idPrefix: 'rq', hasSeq: true },
|
|
25
|
+
bugs: { dir: '缺陷管理', file: '缺陷管理.json', idPrefix: 'bg', hasSeq: true },
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** 四个固定数据目录:与导航分组同名时会被改名,避免冲突 */
|
|
29
|
+
export const PM_DIR_NAMES = Object.values(PM_ENTITY_META).map((m) => m.dir);
|
|
30
|
+
|
|
31
|
+
/** 旧版把四类数据放在同一个文件里,首次读取时按实体拆开 */
|
|
32
|
+
export const LEGACY_PM_DIR_NAME = '项目管理';
|
|
33
|
+
export const LEGACY_PM_STORE_FILE = '项目管理.json';
|
|
34
|
+
|
|
35
|
+
export const PROJECT_STATUSES = ['planning', 'in_progress', 'archived'];
|
|
36
|
+
export const ITERATION_STATUSES = ['planning', 'in_progress', 'done'];
|
|
37
|
+
export const REQUIREMENT_PRIORITIES = ['urgent', 'high', 'medium', 'low'];
|
|
38
|
+
export const REQUIREMENT_STATUSES = [
|
|
39
|
+
'pending',
|
|
40
|
+
'todo',
|
|
41
|
+
'in_progress',
|
|
42
|
+
'testing',
|
|
43
|
+
'done',
|
|
44
|
+
'cancelled',
|
|
45
|
+
];
|
|
46
|
+
export const BUG_SEVERITIES = ['critical', 'major', 'minor', 'trivial'];
|
|
47
|
+
export const BUG_STATUSES = ['pending', 'todo', 'in_progress', 'verifying', 'closed'];
|
|
48
|
+
|
|
49
|
+
/** 四类实体:接口里的 entity 参数 */
|
|
50
|
+
export const PM_ENTITIES = ['projects', 'iterations', 'requirements', 'bugs'];
|
|
51
|
+
|
|
52
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
53
|
+
|
|
54
|
+
/** 某个实体的数据文件路径:只算路径,不建目录 */
|
|
55
|
+
export function pmEntityPath(spaceDir, entity) {
|
|
56
|
+
const meta = PM_ENTITY_META[entity];
|
|
57
|
+
if (!meta) throw badRequest(`未知实体:${entity}`);
|
|
58
|
+
return path.join(path.resolve(spaceDir), meta.dir, meta.file);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 四个数据文件路径(health 探测用,不建目录) */
|
|
62
|
+
export function pmStorePaths(spaceDir) {
|
|
63
|
+
const out = {};
|
|
64
|
+
for (const entity of PM_ENTITIES) out[entity] = pmEntityPath(spaceDir, entity);
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function sendJson(res, status, body) {
|
|
69
|
+
res.statusCode = status;
|
|
70
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
71
|
+
res.end(JSON.stringify(body));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function readBody(req) {
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const chunks = [];
|
|
77
|
+
req.on('data', (c) => chunks.push(c));
|
|
78
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
79
|
+
req.on('error', reject);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 附件上传单独限流:超出上限直接断掉,不把整个请求读进内存 */
|
|
84
|
+
const UPLOAD_MAX_BYTES = 16 * 1024 * 1024;
|
|
85
|
+
|
|
86
|
+
function readBodyLimited(req, limit = UPLOAD_MAX_BYTES) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const chunks = [];
|
|
89
|
+
let size = 0;
|
|
90
|
+
let stopped = false;
|
|
91
|
+
req.on('data', (c) => {
|
|
92
|
+
if (stopped) return;
|
|
93
|
+
size += c.length;
|
|
94
|
+
if (size > limit) {
|
|
95
|
+
stopped = true;
|
|
96
|
+
const err = new Error(`附件太大(上限 ${Math.round(limit / 1024 / 1024)}MB)`);
|
|
97
|
+
err.statusCode = 413;
|
|
98
|
+
reject(err);
|
|
99
|
+
req.destroy();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
chunks.push(c);
|
|
103
|
+
});
|
|
104
|
+
req.on('end', () => {
|
|
105
|
+
if (!stopped) resolve(Buffer.concat(chunks).toString('utf8'));
|
|
106
|
+
});
|
|
107
|
+
req.on('error', reject);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function newId(prefix) {
|
|
112
|
+
return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function text(value, max = 2000) {
|
|
116
|
+
return typeof value === 'string' ? value.trim().slice(0, max) : '';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function dateOrEmpty(value) {
|
|
120
|
+
const s = text(value, 10);
|
|
121
|
+
return DATE_RE.test(s) ? s : '';
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function oneOf(value, allowed, fallback) {
|
|
125
|
+
const s = text(value, 40);
|
|
126
|
+
return allowed.includes(s) ? s : fallback;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function acceptanceCriteria(raw) {
|
|
130
|
+
if (!Array.isArray(raw)) return [];
|
|
131
|
+
const out = [];
|
|
132
|
+
for (const item of raw.slice(0, 50)) {
|
|
133
|
+
if (!item || typeof item !== 'object') continue;
|
|
134
|
+
const label = text(item.text, 500);
|
|
135
|
+
if (!label) continue;
|
|
136
|
+
out.push({ text: label, done: item.done === true });
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function emptyStore() {
|
|
142
|
+
return {
|
|
143
|
+
version: VERSION,
|
|
144
|
+
seq: { requirements: 0, bugs: 0 },
|
|
145
|
+
projects: [],
|
|
146
|
+
iterations: [],
|
|
147
|
+
requirements: [],
|
|
148
|
+
bugs: [],
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 读回来的旧数据也走一遍归一化,避免手工改坏的文件把页面拖垮 */
|
|
153
|
+
function normalizeStoredProject(raw) {
|
|
154
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
155
|
+
const name = text(raw.name, 200);
|
|
156
|
+
if (!name) return null;
|
|
157
|
+
const now = new Date().toISOString();
|
|
158
|
+
return {
|
|
159
|
+
id: text(raw.id, 64) || newId('pj'),
|
|
160
|
+
name,
|
|
161
|
+
description: text(raw.description),
|
|
162
|
+
status: oneOf(raw.status, PROJECT_STATUSES, 'planning'),
|
|
163
|
+
createdAt: text(raw.createdAt, 40) || now,
|
|
164
|
+
updatedAt: text(raw.updatedAt, 40) || now,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function normalizeStoredIteration(raw, projectIds) {
|
|
169
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
170
|
+
const name = text(raw.name, 200);
|
|
171
|
+
if (!name) return null;
|
|
172
|
+
const now = new Date().toISOString();
|
|
173
|
+
const projectId = text(raw.projectId, 64);
|
|
174
|
+
return {
|
|
175
|
+
id: text(raw.id, 64) || newId('it'),
|
|
176
|
+
projectId: projectIds.has(projectId) ? projectId : '',
|
|
177
|
+
name,
|
|
178
|
+
startDate: dateOrEmpty(raw.startDate),
|
|
179
|
+
endDate: dateOrEmpty(raw.endDate),
|
|
180
|
+
status: oneOf(raw.status, ITERATION_STATUSES, 'planning'),
|
|
181
|
+
remark: text(raw.remark),
|
|
182
|
+
createdAt: text(raw.createdAt, 40) || now,
|
|
183
|
+
updatedAt: text(raw.updatedAt, 40) || now,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function normalizeStoredRequirement(raw, projectIds, iterationIds) {
|
|
188
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
189
|
+
const title = text(raw.title, 200);
|
|
190
|
+
if (!title) return null;
|
|
191
|
+
const now = new Date().toISOString();
|
|
192
|
+
const projectId = text(raw.projectId, 64);
|
|
193
|
+
const iterationId = text(raw.iterationId, 64);
|
|
194
|
+
return {
|
|
195
|
+
id: text(raw.id, 64) || newId('rq'),
|
|
196
|
+
autoId: text(raw.autoId, 20),
|
|
197
|
+
projectId: projectIds.has(projectId) ? projectId : '',
|
|
198
|
+
iterationId: iterationIds.has(iterationId) ? iterationId : '',
|
|
199
|
+
title,
|
|
200
|
+
priority: oneOf(raw.priority, REQUIREMENT_PRIORITIES, 'medium'),
|
|
201
|
+
status: oneOf(raw.status, REQUIREMENT_STATUSES, 'pending'),
|
|
202
|
+
description: text(raw.description),
|
|
203
|
+
acceptanceCriteria: acceptanceCriteria(raw.acceptanceCriteria),
|
|
204
|
+
githubIssue: text(raw.githubIssue, 50),
|
|
205
|
+
attachment: text(raw.attachment),
|
|
206
|
+
createdAt: text(raw.createdAt, 40) || now,
|
|
207
|
+
updatedAt: text(raw.updatedAt, 40) || now,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function normalizeStoredBug(raw, projectIds, iterationIds, requirementIds) {
|
|
212
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
213
|
+
const title = text(raw.title, 200);
|
|
214
|
+
if (!title) return null;
|
|
215
|
+
const now = new Date().toISOString();
|
|
216
|
+
const projectId = text(raw.projectId, 64);
|
|
217
|
+
const iterationId = text(raw.iterationId, 64);
|
|
218
|
+
const requirementId = text(raw.requirementId, 64);
|
|
219
|
+
return {
|
|
220
|
+
id: text(raw.id, 64) || newId('bg'),
|
|
221
|
+
autoId: text(raw.autoId, 20),
|
|
222
|
+
projectId: projectIds.has(projectId) ? projectId : '',
|
|
223
|
+
iterationId: iterationIds.has(iterationId) ? iterationId : '',
|
|
224
|
+
requirementId: requirementIds.has(requirementId) ? requirementId : '',
|
|
225
|
+
title,
|
|
226
|
+
severity: oneOf(raw.severity, BUG_SEVERITIES, 'minor'),
|
|
227
|
+
status: oneOf(raw.status, BUG_STATUSES, 'pending'),
|
|
228
|
+
reproduceSteps: text(raw.reproduceSteps),
|
|
229
|
+
expectedResult: text(raw.expectedResult),
|
|
230
|
+
actualResult: text(raw.actualResult),
|
|
231
|
+
environment: text(raw.environment, 500),
|
|
232
|
+
githubIssue: text(raw.githubIssue, 50),
|
|
233
|
+
attachment: text(raw.attachment),
|
|
234
|
+
remark: text(raw.remark),
|
|
235
|
+
createdAt: text(raw.createdAt, 40) || now,
|
|
236
|
+
updatedAt: text(raw.updatedAt, 40) || now,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 最大编号 +1:删掉最后一条也不会把编号发回去 */
|
|
241
|
+
function maxSeq(items, prefix) {
|
|
242
|
+
let max = 0;
|
|
243
|
+
for (const item of items) {
|
|
244
|
+
const m = new RegExp(`^${prefix}-(\\d+)$`).exec(String(item?.autoId ?? ''));
|
|
245
|
+
if (m) max = Math.max(max, Number(m[1]));
|
|
246
|
+
}
|
|
247
|
+
return max;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function nextAutoId(store, entity) {
|
|
251
|
+
const prefix = entity === 'requirements' ? 'REQ' : 'BUG';
|
|
252
|
+
const key = entity;
|
|
253
|
+
const fromItems = maxSeq(store[key], prefix);
|
|
254
|
+
const seq = Math.max(Number(store.seq?.[key]) || 0, fromItems) + 1;
|
|
255
|
+
store.seq[key] = seq;
|
|
256
|
+
return `${prefix}-${String(seq).padStart(3, '0')}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function normalizeStore(raw) {
|
|
260
|
+
const base = emptyStore();
|
|
261
|
+
if (!raw || typeof raw !== 'object') return base;
|
|
262
|
+
base.projects = (Array.isArray(raw.projects) ? raw.projects : [])
|
|
263
|
+
.map(normalizeStoredProject)
|
|
264
|
+
.filter(Boolean);
|
|
265
|
+
const projectIds = new Set(base.projects.map((x) => x.id));
|
|
266
|
+
base.iterations = (Array.isArray(raw.iterations) ? raw.iterations : [])
|
|
267
|
+
.map((x) => normalizeStoredIteration(x, projectIds))
|
|
268
|
+
.filter(Boolean);
|
|
269
|
+
const iterationIds = new Set(base.iterations.map((x) => x.id));
|
|
270
|
+
base.requirements = (Array.isArray(raw.requirements) ? raw.requirements : [])
|
|
271
|
+
.map((x) => normalizeStoredRequirement(x, projectIds, iterationIds))
|
|
272
|
+
.filter(Boolean);
|
|
273
|
+
const requirementIds = new Set(base.requirements.map((x) => x.id));
|
|
274
|
+
base.bugs = (Array.isArray(raw.bugs) ? raw.bugs : [])
|
|
275
|
+
.map((x) => normalizeStoredBug(x, projectIds, iterationIds, requirementIds))
|
|
276
|
+
.filter(Boolean);
|
|
277
|
+
// 编号可能来自旧文件:补一遍,避免出现 AutoId 为空的需求 / 缺陷。
|
|
278
|
+
// seq 只增不减:即使最大编号的记录被删掉,也不能把编号发回去。
|
|
279
|
+
const storedSeq = (raw && typeof raw === 'object' ? raw.seq : null) ?? {};
|
|
280
|
+
base.seq.requirements = Math.max(
|
|
281
|
+
maxSeq(base.requirements, 'REQ'),
|
|
282
|
+
Number(storedSeq.requirements) || 0,
|
|
283
|
+
);
|
|
284
|
+
base.seq.bugs = Math.max(maxSeq(base.bugs, 'BUG'), Number(storedSeq.bugs) || 0);
|
|
285
|
+
for (const item of base.requirements) {
|
|
286
|
+
if (!item.autoId) item.autoId = nextAutoId(base, 'requirements');
|
|
287
|
+
}
|
|
288
|
+
for (const item of base.bugs) {
|
|
289
|
+
if (!item.autoId) item.autoId = nextAutoId(base, 'bugs');
|
|
290
|
+
}
|
|
291
|
+
return base;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function readEntityFile(root, entity) {
|
|
295
|
+
const fp = pmEntityPath(root, entity);
|
|
296
|
+
try {
|
|
297
|
+
const raw = JSON.parse(fs.readFileSync(fp, 'utf8'));
|
|
298
|
+
// 兼容手写成裸数组的文件
|
|
299
|
+
if (Array.isArray(raw)) return { items: raw, seq: 0, exists: true };
|
|
300
|
+
if (!raw || typeof raw !== 'object') return { items: [], seq: 0, exists: true };
|
|
301
|
+
return {
|
|
302
|
+
items: Array.isArray(raw.items) ? raw.items : [],
|
|
303
|
+
seq: Number(raw.seq) || 0,
|
|
304
|
+
exists: true,
|
|
305
|
+
};
|
|
306
|
+
} catch {
|
|
307
|
+
return { items: [], seq: 0, exists: false };
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** 先写临时文件再 rename:中途失败也不会留下半份 JSON */
|
|
312
|
+
function writeEntityFile(root, entity, items, seq = 0) {
|
|
313
|
+
const meta = PM_ENTITY_META[entity];
|
|
314
|
+
if (!meta) throw badRequest(`未知实体:${entity}`);
|
|
315
|
+
const fp = pmEntityPath(root, entity);
|
|
316
|
+
fs.mkdirSync(path.dirname(fp), { recursive: true });
|
|
317
|
+
const payload = meta.hasSeq
|
|
318
|
+
? { version: VERSION, seq: Number(seq) || 0, items }
|
|
319
|
+
: { version: VERSION, items };
|
|
320
|
+
const tmp = `${fp}.${process.pid}.tmp`;
|
|
321
|
+
fs.writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
|
|
322
|
+
fs.renameSync(tmp, fp);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** 旧版单文件:`<空间>/项目管理/项目管理.json` */
|
|
326
|
+
function legacyStorePath(root) {
|
|
327
|
+
return path.join(path.resolve(root), LEGACY_PM_DIR_NAME, LEGACY_PM_STORE_FILE);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* 旧版四类数据共用一个文件:第一次读到时按实体拆到各自目录,再删掉旧文件。
|
|
332
|
+
* 只给「确实有数据」的实体建目录;新文件已存在的,按 id 合并而不是覆盖。
|
|
333
|
+
*/
|
|
334
|
+
function migrateLegacyStore(root) {
|
|
335
|
+
const legacyPath = legacyStorePath(root);
|
|
336
|
+
let legacy;
|
|
337
|
+
try {
|
|
338
|
+
legacy = JSON.parse(fs.readFileSync(legacyPath, 'utf8'));
|
|
339
|
+
} catch {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
if (!legacy || typeof legacy !== 'object') return false;
|
|
343
|
+
|
|
344
|
+
let moved = 0;
|
|
345
|
+
for (const entity of PM_ENTITIES) {
|
|
346
|
+
const incoming = Array.isArray(legacy[entity]) ? legacy[entity] : [];
|
|
347
|
+
const current = readEntityFile(root, entity);
|
|
348
|
+
if (!incoming.length && !current.exists) continue;
|
|
349
|
+
const legacySeq = Number(legacy.seq?.[entity]) || 0;
|
|
350
|
+
const seen = new Set(current.items.map((x) => (x && typeof x === 'object' ? x.id : null)));
|
|
351
|
+
const merged = [...current.items];
|
|
352
|
+
for (const item of incoming) {
|
|
353
|
+
const id = item && typeof item === 'object' ? item.id : null;
|
|
354
|
+
if (id && seen.has(id)) continue;
|
|
355
|
+
merged.push(item);
|
|
356
|
+
}
|
|
357
|
+
// 没有新记录、seq 也没变化时不用重写
|
|
358
|
+
if (merged.length === current.items.length && legacySeq <= current.seq) continue;
|
|
359
|
+
writeEntityFile(root, entity, merged, Math.max(current.seq, legacySeq));
|
|
360
|
+
moved += merged.length - current.items.length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// 拆完就清理旧文件;只剩空目录时一并收掉
|
|
364
|
+
try {
|
|
365
|
+
fs.rmSync(legacyPath, { force: true });
|
|
366
|
+
fs.rmdirSync(path.dirname(legacyPath));
|
|
367
|
+
} catch {
|
|
368
|
+
// 目录里还有别的文件就留着
|
|
369
|
+
}
|
|
370
|
+
return moved > 0;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function readStore(root) {
|
|
374
|
+
migrateLegacyStore(root);
|
|
375
|
+
const raw = { seq: {}, projects: [], iterations: [], requirements: [], bugs: [] };
|
|
376
|
+
for (const entity of PM_ENTITIES) {
|
|
377
|
+
const file = readEntityFile(root, entity);
|
|
378
|
+
raw[entity] = file.items;
|
|
379
|
+
if (PM_ENTITY_META[entity].hasSeq) raw.seq[entity] = file.seq;
|
|
380
|
+
}
|
|
381
|
+
return normalizeStore(raw);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* 只写「这次真的变了」的实体。
|
|
386
|
+
* 没有数据、文件也不存在的实体不铺空目录;已经存在的文件即使被清空也保留。
|
|
387
|
+
*/
|
|
388
|
+
function writeStore(root, store, entities) {
|
|
389
|
+
for (const entity of entities) {
|
|
390
|
+
if (!PM_ENTITY_META[entity]) continue;
|
|
391
|
+
const exists = fs.existsSync(pmEntityPath(root, entity));
|
|
392
|
+
const items = store[entity] ?? [];
|
|
393
|
+
if (!exists && items.length === 0) continue;
|
|
394
|
+
writeEntityFile(root, entity, items, store.seq?.[entity] ?? 0);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function badRequest(message) {
|
|
399
|
+
const err = new Error(message);
|
|
400
|
+
err.statusCode = 400;
|
|
401
|
+
return err;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/* ------------------------------ 缺陷附件 ------------------------------ */
|
|
405
|
+
|
|
406
|
+
const ATTACHMENT_DIR = '缺陷管理';
|
|
407
|
+
const ATTACHMENT_SUBDIR = '附件';
|
|
408
|
+
const MIME_BY_EXT = {
|
|
409
|
+
'.png': 'image/png',
|
|
410
|
+
'.jpg': 'image/jpeg',
|
|
411
|
+
'.jpeg': 'image/jpeg',
|
|
412
|
+
'.gif': 'image/gif',
|
|
413
|
+
'.webp': 'image/webp',
|
|
414
|
+
'.svg': 'image/svg+xml',
|
|
415
|
+
'.bmp': 'image/bmp',
|
|
416
|
+
'.heic': 'image/heic',
|
|
417
|
+
'.pdf': 'application/pdf',
|
|
418
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
419
|
+
'.log': 'text/plain; charset=utf-8',
|
|
420
|
+
'.json': 'application/json; charset=utf-8',
|
|
421
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
422
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
423
|
+
'.zip': 'application/zip',
|
|
424
|
+
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
425
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
function attachmentDir(root) {
|
|
429
|
+
return path.join(path.resolve(root), ATTACHMENT_DIR, ATTACHMENT_SUBDIR);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 只留安全字符;空名兜底为 attachment */
|
|
433
|
+
function safeFileName(name) {
|
|
434
|
+
const base = String(name ?? '')
|
|
435
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
|
|
436
|
+
.replace(/^\.+/, '')
|
|
437
|
+
.trim()
|
|
438
|
+
.slice(0, 120);
|
|
439
|
+
return base || 'attachment';
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function saveUpload(root, raw) {
|
|
443
|
+
if (!raw || typeof raw !== 'object') throw badRequest('附件格式不正确');
|
|
444
|
+
const original = safeFileName(raw.name);
|
|
445
|
+
const data = typeof raw.data === 'string' ? raw.data.replace(/^data:[^,]*,/, '') : '';
|
|
446
|
+
if (!data) throw badRequest('附件内容为空');
|
|
447
|
+
let buffer;
|
|
448
|
+
try {
|
|
449
|
+
buffer = Buffer.from(data, 'base64');
|
|
450
|
+
} catch {
|
|
451
|
+
throw badRequest('附件内容无法解码');
|
|
452
|
+
}
|
|
453
|
+
if (!buffer.length) throw badRequest('附件内容为空');
|
|
454
|
+
if (buffer.length > UPLOAD_MAX_BYTES) {
|
|
455
|
+
throw badRequest(`附件太大(上限 ${Math.round(UPLOAD_MAX_BYTES / 1024 / 1024)}MB)`);
|
|
456
|
+
}
|
|
457
|
+
const storeName = `${Date.now()}-${crypto.randomBytes(3).toString('hex')}-${original}`;
|
|
458
|
+
const dir = attachmentDir(root);
|
|
459
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
460
|
+
fs.writeFileSync(path.join(dir, storeName), buffer);
|
|
461
|
+
const rel = path.posix.join(ATTACHMENT_DIR, ATTACHMENT_SUBDIR, storeName);
|
|
462
|
+
return {
|
|
463
|
+
name: original,
|
|
464
|
+
size: buffer.length,
|
|
465
|
+
type: typeof raw.type === 'string' ? raw.type.slice(0, 100) : '',
|
|
466
|
+
url: `${PREFIX}/file?p=${encodeURIComponent(rel)}`,
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** 把地址解析回空间内的附件路径;越界或不在附件目录里返回空 */
|
|
471
|
+
function attachmentPath(root, url) {
|
|
472
|
+
let rel = '';
|
|
473
|
+
try {
|
|
474
|
+
rel = new URL(String(url), 'http://127.0.0.1').searchParams.get('p') ?? '';
|
|
475
|
+
} catch {
|
|
476
|
+
return '';
|
|
477
|
+
}
|
|
478
|
+
if (!rel) return '';
|
|
479
|
+
const base = path.resolve(root);
|
|
480
|
+
const target = path.resolve(base, rel);
|
|
481
|
+
const allowed = path.resolve(base, ATTACHMENT_DIR, ATTACHMENT_SUBDIR);
|
|
482
|
+
if (target !== allowed && !target.startsWith(`${allowed}${path.sep}`)) return '';
|
|
483
|
+
return target;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** 删掉不再被引用的附件文件:只动「缺陷管理/附件」下的内容 */
|
|
487
|
+
function pruneAttachments(root, urls) {
|
|
488
|
+
for (const url of urls) {
|
|
489
|
+
const target = attachmentPath(root, url);
|
|
490
|
+
if (!target) continue;
|
|
491
|
+
try {
|
|
492
|
+
fs.rmSync(target, { force: true });
|
|
493
|
+
} catch {
|
|
494
|
+
// 文件已不在或没权限:忽略,不影响主流程
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function removedAttachments(before, after) {
|
|
500
|
+
const keep = new Set(
|
|
501
|
+
String(after ?? '')
|
|
502
|
+
.split('\n')
|
|
503
|
+
.map((x) => x.trim())
|
|
504
|
+
.filter(Boolean),
|
|
505
|
+
);
|
|
506
|
+
return String(before ?? '')
|
|
507
|
+
.split('\n')
|
|
508
|
+
.map((x) => x.trim())
|
|
509
|
+
.filter((x) => x && !keep.has(x));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** 当前所有需求 / 缺陷还在引用的附件地址:清理时只删没被引用的文件(excludeId 用来忽略正在编辑的那条) */
|
|
513
|
+
function referencedAttachments(store, excludeId = '') {
|
|
514
|
+
const keep = new Set();
|
|
515
|
+
for (const entity of ['requirements', 'bugs']) {
|
|
516
|
+
for (const item of store[entity] ?? []) {
|
|
517
|
+
if (excludeId && item.id === excludeId) continue;
|
|
518
|
+
for (const url of String(item.attachment ?? '').split('\n')) {
|
|
519
|
+
const s = url.trim();
|
|
520
|
+
if (s) keep.add(s);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return keep;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** GET 附件:只允许读附件目录内的文件 */
|
|
528
|
+
function sendAttachment(root, res, rel) {
|
|
529
|
+
const target = attachmentPath(root, `${PREFIX}/file?p=${encodeURIComponent(rel)}`);
|
|
530
|
+
if (!target) return sendJson(res, 400, { ok: false, error: '附件路径不合法' });
|
|
531
|
+
let stat;
|
|
532
|
+
try {
|
|
533
|
+
stat = fs.statSync(target);
|
|
534
|
+
} catch {
|
|
535
|
+
return sendJson(res, 404, { ok: false, error: '附件不存在' });
|
|
536
|
+
}
|
|
537
|
+
if (!stat.isFile()) return sendJson(res, 404, { ok: false, error: '附件不存在' });
|
|
538
|
+
const ext = path.extname(target).toLowerCase();
|
|
539
|
+
res.statusCode = 200;
|
|
540
|
+
res.setHeader('Content-Type', MIME_BY_EXT[ext] ?? 'application/octet-stream');
|
|
541
|
+
res.setHeader('Content-Length', String(stat.size));
|
|
542
|
+
res.setHeader('Cache-Control', 'private, max-age=300');
|
|
543
|
+
// 未知类型一律当下载,避免把用户上传的 html / svg 当页面渲染
|
|
544
|
+
const inline = MIME_BY_EXT[ext] && ext !== '.svg';
|
|
545
|
+
if (!inline) {
|
|
546
|
+
res.setHeader(
|
|
547
|
+
'Content-Disposition',
|
|
548
|
+
`attachment; filename*=UTF-8''${encodeURIComponent(path.basename(target))}`,
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
fs.createReadStream(target).pipe(res);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** 校验 projectId 存在 */
|
|
555
|
+
function requireProject(store, raw) {
|
|
556
|
+
const projectId = text(raw?.projectId, 64);
|
|
557
|
+
if (!projectId) throw badRequest('缺少所属项目');
|
|
558
|
+
if (!store.projects.some((p) => p.id === projectId)) throw badRequest('所属项目不存在');
|
|
559
|
+
return projectId;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** 校验迭代属于该项目;空串表示不关联 */
|
|
563
|
+
function pickIterationId(store, projectId, raw) {
|
|
564
|
+
const iterationId = text(raw?.iterationId, 64);
|
|
565
|
+
if (!iterationId) return '';
|
|
566
|
+
const it = store.iterations.find((x) => x.id === iterationId);
|
|
567
|
+
if (!it) throw badRequest('所属迭代不存在');
|
|
568
|
+
if (it.projectId !== projectId) throw badRequest('所属迭代不属于该项目');
|
|
569
|
+
return iterationId;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function pickRequirementId(store, projectId, raw) {
|
|
573
|
+
const requirementId = text(raw?.requirementId, 64);
|
|
574
|
+
if (!requirementId) return '';
|
|
575
|
+
const rq = store.requirements.find((x) => x.id === requirementId);
|
|
576
|
+
if (!rq) throw badRequest('关联需求不存在');
|
|
577
|
+
if (rq.projectId !== projectId) throw badRequest('关联需求不属于该项目');
|
|
578
|
+
return requirementId;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function checkIterationDates(startDate, endDate) {
|
|
582
|
+
if (startDate && endDate && endDate < startDate) {
|
|
583
|
+
throw badRequest('迭代结束日期不能早于开始日期');
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function buildItem(store, entity, raw) {
|
|
588
|
+
const now = new Date().toISOString();
|
|
589
|
+
if (entity === 'projects') {
|
|
590
|
+
const name = text(raw?.name, 200);
|
|
591
|
+
if (!name) throw badRequest('项目名称不能为空');
|
|
592
|
+
return {
|
|
593
|
+
id: newId('pj'),
|
|
594
|
+
name,
|
|
595
|
+
description: text(raw?.description),
|
|
596
|
+
status: oneOf(raw?.status, PROJECT_STATUSES, 'planning'),
|
|
597
|
+
createdAt: now,
|
|
598
|
+
updatedAt: now,
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
if (entity === 'iterations') {
|
|
602
|
+
const name = text(raw?.name, 200);
|
|
603
|
+
if (!name) throw badRequest('迭代名称不能为空');
|
|
604
|
+
const projectId = requireProject(store, raw);
|
|
605
|
+
const startDate = dateOrEmpty(raw?.startDate);
|
|
606
|
+
const endDate = dateOrEmpty(raw?.endDate);
|
|
607
|
+
checkIterationDates(startDate, endDate);
|
|
608
|
+
return {
|
|
609
|
+
id: newId('it'),
|
|
610
|
+
projectId,
|
|
611
|
+
name,
|
|
612
|
+
startDate,
|
|
613
|
+
endDate,
|
|
614
|
+
status: oneOf(raw?.status, ITERATION_STATUSES, 'planning'),
|
|
615
|
+
remark: text(raw?.remark),
|
|
616
|
+
createdAt: now,
|
|
617
|
+
updatedAt: now,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
if (entity === 'requirements') {
|
|
621
|
+
// 「需求描述」是多行文本,留足 2000 字;列表里仍会截断显示
|
|
622
|
+
const title = text(raw?.title, 2000);
|
|
623
|
+
if (!title) throw badRequest('需求描述不能为空');
|
|
624
|
+
const projectId = requireProject(store, raw);
|
|
625
|
+
return {
|
|
626
|
+
id: newId('rq'),
|
|
627
|
+
autoId: nextAutoId(store, 'requirements'),
|
|
628
|
+
projectId,
|
|
629
|
+
iterationId: pickIterationId(store, projectId, raw),
|
|
630
|
+
title,
|
|
631
|
+
priority: oneOf(raw?.priority, REQUIREMENT_PRIORITIES, 'medium'),
|
|
632
|
+
status: oneOf(raw?.status, REQUIREMENT_STATUSES, 'pending'),
|
|
633
|
+
description: text(raw?.description),
|
|
634
|
+
acceptanceCriteria: acceptanceCriteria(raw?.acceptanceCriteria),
|
|
635
|
+
githubIssue: text(raw?.githubIssue, 50),
|
|
636
|
+
attachment: text(raw?.attachment),
|
|
637
|
+
createdAt: now,
|
|
638
|
+
updatedAt: now,
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
if (entity === 'bugs') {
|
|
642
|
+
const title = text(raw?.title, 200);
|
|
643
|
+
if (!title) throw badRequest('缺陷标题不能为空');
|
|
644
|
+
const projectId = requireProject(store, raw);
|
|
645
|
+
return {
|
|
646
|
+
id: newId('bg'),
|
|
647
|
+
autoId: nextAutoId(store, 'bugs'),
|
|
648
|
+
projectId,
|
|
649
|
+
iterationId: pickIterationId(store, projectId, raw),
|
|
650
|
+
requirementId: pickRequirementId(store, projectId, raw),
|
|
651
|
+
title,
|
|
652
|
+
severity: oneOf(raw?.severity, BUG_SEVERITIES, 'minor'),
|
|
653
|
+
status: oneOf(raw?.status, BUG_STATUSES, 'pending'),
|
|
654
|
+
reproduceSteps: text(raw?.reproduceSteps),
|
|
655
|
+
expectedResult: text(raw?.expectedResult),
|
|
656
|
+
actualResult: text(raw?.actualResult),
|
|
657
|
+
environment: text(raw?.environment, 500),
|
|
658
|
+
githubIssue: text(raw?.githubIssue, 50),
|
|
659
|
+
attachment: text(raw?.attachment),
|
|
660
|
+
remark: text(raw?.remark),
|
|
661
|
+
createdAt: now,
|
|
662
|
+
updatedAt: now,
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
throw badRequest(`未知实体:${entity}`);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function validateTitle(entity, patch) {
|
|
669
|
+
const required = entity === 'projects' || entity === 'iterations' ? 'name' : 'title';
|
|
670
|
+
if (required in patch && !patch[required]) {
|
|
671
|
+
throw badRequest(
|
|
672
|
+
entity === 'projects'
|
|
673
|
+
? '项目名称不能为空'
|
|
674
|
+
: entity === 'iterations'
|
|
675
|
+
? '迭代名称不能为空'
|
|
676
|
+
: entity === 'requirements'
|
|
677
|
+
? '需求描述不能为空'
|
|
678
|
+
: '缺陷标题不能为空',
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function normalizePatch(store, entity, raw, base) {
|
|
684
|
+
const patch = {};
|
|
685
|
+
if (!raw || typeof raw !== 'object') return patch;
|
|
686
|
+
if (entity === 'projects') {
|
|
687
|
+
if ('name' in raw) patch.name = text(raw.name, 200);
|
|
688
|
+
if ('description' in raw) patch.description = text(raw.description);
|
|
689
|
+
if ('status' in raw) patch.status = oneOf(raw.status, PROJECT_STATUSES, base.status);
|
|
690
|
+
return patch;
|
|
691
|
+
}
|
|
692
|
+
if (entity === 'iterations') {
|
|
693
|
+
if ('name' in raw) patch.name = text(raw.name, 200);
|
|
694
|
+
if ('projectId' in raw) patch.projectId = requireProject(store, raw);
|
|
695
|
+
if ('startDate' in raw) patch.startDate = dateOrEmpty(raw.startDate);
|
|
696
|
+
if ('endDate' in raw) patch.endDate = dateOrEmpty(raw.endDate);
|
|
697
|
+
if ('status' in raw) patch.status = oneOf(raw.status, ITERATION_STATUSES, base.status);
|
|
698
|
+
if ('remark' in raw) patch.remark = text(raw.remark);
|
|
699
|
+
checkIterationDates(patch.startDate ?? base.startDate, patch.endDate ?? base.endDate);
|
|
700
|
+
return patch;
|
|
701
|
+
}
|
|
702
|
+
if (entity === 'requirements') {
|
|
703
|
+
if ('title' in raw) patch.title = text(raw.title, 2000);
|
|
704
|
+
const nextProject = 'projectId' in raw ? requireProject(store, raw) : base.projectId;
|
|
705
|
+
if ('projectId' in raw) patch.projectId = nextProject;
|
|
706
|
+
if ('iterationId' in raw) {
|
|
707
|
+
patch.iterationId = pickIterationId(store, nextProject, raw);
|
|
708
|
+
} else if (patch.projectId && patch.projectId !== base.projectId) {
|
|
709
|
+
patch.iterationId = ''; // 换项目后旧迭代不再属于它
|
|
710
|
+
}
|
|
711
|
+
if ('priority' in raw) {
|
|
712
|
+
patch.priority = oneOf(raw.priority, REQUIREMENT_PRIORITIES, base.priority);
|
|
713
|
+
}
|
|
714
|
+
if ('status' in raw) patch.status = oneOf(raw.status, REQUIREMENT_STATUSES, base.status);
|
|
715
|
+
if ('description' in raw) patch.description = text(raw.description);
|
|
716
|
+
if ('acceptanceCriteria' in raw) {
|
|
717
|
+
patch.acceptanceCriteria = acceptanceCriteria(raw.acceptanceCriteria);
|
|
718
|
+
}
|
|
719
|
+
if ('githubIssue' in raw) patch.githubIssue = text(raw.githubIssue, 50);
|
|
720
|
+
if ('attachment' in raw) patch.attachment = text(raw.attachment);
|
|
721
|
+
return patch;
|
|
722
|
+
}
|
|
723
|
+
if (entity === 'bugs') {
|
|
724
|
+
if ('title' in raw) patch.title = text(raw.title, 200);
|
|
725
|
+
const nextProject = 'projectId' in raw ? requireProject(store, raw) : base.projectId;
|
|
726
|
+
if ('projectId' in raw) patch.projectId = nextProject;
|
|
727
|
+
if ('iterationId' in raw) patch.iterationId = pickIterationId(store, nextProject, raw);
|
|
728
|
+
else if (patch.projectId && patch.projectId !== base.projectId) patch.iterationId = '';
|
|
729
|
+
if ('requirementId' in raw) {
|
|
730
|
+
patch.requirementId = pickRequirementId(store, nextProject, raw);
|
|
731
|
+
} else if (patch.projectId && patch.projectId !== base.projectId) {
|
|
732
|
+
patch.requirementId = '';
|
|
733
|
+
}
|
|
734
|
+
if ('severity' in raw) patch.severity = oneOf(raw.severity, BUG_SEVERITIES, base.severity);
|
|
735
|
+
if ('status' in raw) patch.status = oneOf(raw.status, BUG_STATUSES, base.status);
|
|
736
|
+
if ('reproduceSteps' in raw) patch.reproduceSteps = text(raw.reproduceSteps);
|
|
737
|
+
if ('expectedResult' in raw) patch.expectedResult = text(raw.expectedResult);
|
|
738
|
+
if ('actualResult' in raw) patch.actualResult = text(raw.actualResult);
|
|
739
|
+
if ('environment' in raw) patch.environment = text(raw.environment, 500);
|
|
740
|
+
if ('githubIssue' in raw) patch.githubIssue = text(raw.githubIssue, 50);
|
|
741
|
+
if ('attachment' in raw) patch.attachment = text(raw.attachment);
|
|
742
|
+
if ('remark' in raw) patch.remark = text(raw.remark);
|
|
743
|
+
return patch;
|
|
744
|
+
}
|
|
745
|
+
throw badRequest(`未知实体:${entity}`);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** 删除后的级联:删项目连带删子项,删迭代 / 需求只清空引用 */
|
|
749
|
+
function applyDelete(store, entity, ids, dirty) {
|
|
750
|
+
const drop = new Set(ids);
|
|
751
|
+
const before = store[entity].length;
|
|
752
|
+
store[entity] = store[entity].filter((x) => !drop.has(x.id));
|
|
753
|
+
let cascaded = 0;
|
|
754
|
+
if (entity === 'projects') {
|
|
755
|
+
for (const key of ['iterations', 'requirements', 'bugs']) {
|
|
756
|
+
const n = store[key].length;
|
|
757
|
+
store[key] = store[key].filter((x) => !drop.has(x.projectId));
|
|
758
|
+
const removed = n - store[key].length;
|
|
759
|
+
cascaded += removed;
|
|
760
|
+
if (removed) dirty.add(key);
|
|
761
|
+
}
|
|
762
|
+
} else if (entity === 'iterations') {
|
|
763
|
+
for (const key of ['requirements', 'bugs']) {
|
|
764
|
+
let touched = false;
|
|
765
|
+
for (const item of store[key]) {
|
|
766
|
+
if (drop.has(item.iterationId)) {
|
|
767
|
+
item.iterationId = '';
|
|
768
|
+
touched = true;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
if (touched) dirty.add(key);
|
|
772
|
+
}
|
|
773
|
+
} else if (entity === 'requirements') {
|
|
774
|
+
let touched = false;
|
|
775
|
+
for (const item of store.bugs) {
|
|
776
|
+
if (drop.has(item.requirementId)) {
|
|
777
|
+
item.requirementId = '';
|
|
778
|
+
touched = true;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (touched) dirty.add('bugs');
|
|
782
|
+
}
|
|
783
|
+
return { removed: before - store[entity].length, cascaded };
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* 改挂项目后的引用清理:迭代换了项目,原项目下挂它的需求 / 缺陷解除关联;
|
|
788
|
+
* 需求换了项目,原项目下关联它的缺陷解除关联。这样「子项必须与父项同项目」始终成立。
|
|
789
|
+
*/
|
|
790
|
+
function applyProjectMove(store, entity, id, before, after, dirty) {
|
|
791
|
+
if (before.projectId === after.projectId) return 0;
|
|
792
|
+
let cleared = 0;
|
|
793
|
+
if (entity === 'iterations') {
|
|
794
|
+
for (const key of ['requirements', 'bugs']) {
|
|
795
|
+
let touched = false;
|
|
796
|
+
for (const item of store[key]) {
|
|
797
|
+
if (item.iterationId === id) {
|
|
798
|
+
item.iterationId = '';
|
|
799
|
+
touched = true;
|
|
800
|
+
cleared += 1;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
if (touched) dirty.add(key);
|
|
804
|
+
}
|
|
805
|
+
} else if (entity === 'requirements') {
|
|
806
|
+
let touched = false;
|
|
807
|
+
for (const item of store.bugs) {
|
|
808
|
+
if (item.requirementId === id) {
|
|
809
|
+
item.requirementId = '';
|
|
810
|
+
touched = true;
|
|
811
|
+
cleared += 1;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
if (touched) dirty.add('bugs');
|
|
815
|
+
}
|
|
816
|
+
return cleared;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* @returns {import('vite').Plugin}
|
|
821
|
+
*/
|
|
822
|
+
export function lhPmPlugin() {
|
|
823
|
+
return {
|
|
824
|
+
name: 'lh-pm',
|
|
825
|
+
configureServer(server) {
|
|
826
|
+
server.middlewares.use(async (req, res, next) => {
|
|
827
|
+
const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
828
|
+
if (!parsed.pathname.startsWith(PREFIX)) return next();
|
|
829
|
+
// 数据根惰性读取:切换数据空间后无需重启
|
|
830
|
+
const root = getDataRoot();
|
|
831
|
+
|
|
832
|
+
try {
|
|
833
|
+
const method = req.method || 'GET';
|
|
834
|
+
|
|
835
|
+
if (method === 'GET' && parsed.pathname === `${PREFIX}/file`) {
|
|
836
|
+
return sendAttachment(root, res, parsed.searchParams.get('p') ?? '');
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (method === 'GET' && parsed.searchParams.get('health') === '1') {
|
|
840
|
+
// 探测不算读写:只算路径,不建目录
|
|
841
|
+
return sendJson(res, 200, { ok: true, files: pmStorePaths(root) });
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
if (method === 'GET') {
|
|
845
|
+
return sendJson(res, 200, { ok: true, ...readStore(root) });
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
if (method === 'POST') {
|
|
849
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
850
|
+
if (Array.isArray(body.upload)) {
|
|
851
|
+
const saved = body.upload.slice(0, 10).map((file) => saveUpload(root, file));
|
|
852
|
+
return sendJson(res, 200, { ok: true, files: saved });
|
|
853
|
+
}
|
|
854
|
+
// 抽屉没保存就关掉、或点了附件上的 X:把没人引用的文件删掉
|
|
855
|
+
if (Array.isArray(body.cleanup)) {
|
|
856
|
+
const store = readStore(root);
|
|
857
|
+
const keep = referencedAttachments(store, text(body.bugId, 64));
|
|
858
|
+
const urls = body.cleanup.map((x) => text(x, 2000)).filter((x) => x && !keep.has(x));
|
|
859
|
+
pruneAttachments(root, urls);
|
|
860
|
+
return sendJson(res, 200, { ok: true, removed: urls.length });
|
|
861
|
+
}
|
|
862
|
+
const entity = text(body.entity, 40);
|
|
863
|
+
if (!PM_ENTITIES.includes(entity)) {
|
|
864
|
+
return sendJson(res, 400, { ok: false, error: `未知实体:${entity || '(空)'}` });
|
|
865
|
+
}
|
|
866
|
+
const rawItems = Array.isArray(body.items) ? body.items : [body.item ?? body];
|
|
867
|
+
const store = readStore(root);
|
|
868
|
+
const created = [];
|
|
869
|
+
for (const raw of rawItems) {
|
|
870
|
+
created.push(buildItem(store, entity, raw));
|
|
871
|
+
}
|
|
872
|
+
store[entity].push(...created);
|
|
873
|
+
writeStore(root, store, [entity]);
|
|
874
|
+
return sendJson(res, 200, {
|
|
875
|
+
ok: true,
|
|
876
|
+
items: created,
|
|
877
|
+
total: store[entity].length,
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
if (method === 'PUT') {
|
|
882
|
+
const body = JSON.parse((await readBody(req)) || '{}');
|
|
883
|
+
const entity = text(body.entity, 40);
|
|
884
|
+
if (!PM_ENTITIES.includes(entity)) {
|
|
885
|
+
return sendJson(res, 400, { ok: false, error: `未知实体:${entity || '(空)'}` });
|
|
886
|
+
}
|
|
887
|
+
const id = text(body.id, 64);
|
|
888
|
+
if (!id) return sendJson(res, 400, { ok: false, error: '缺少记录 id' });
|
|
889
|
+
const store = readStore(root);
|
|
890
|
+
const idx = store[entity].findIndex((x) => x.id === id);
|
|
891
|
+
if (idx < 0) return sendJson(res, 404, { ok: false, error: '记录不存在' });
|
|
892
|
+
|
|
893
|
+
const base = store[entity][idx];
|
|
894
|
+
const patch = normalizePatch(store, entity, body, base);
|
|
895
|
+
validateTitle(entity, patch);
|
|
896
|
+
const next = { ...base, ...patch, updatedAt: new Date().toISOString() };
|
|
897
|
+
const dirty = new Set([entity]);
|
|
898
|
+
applyProjectMove(store, entity, id, base, next, dirty);
|
|
899
|
+
store[entity][idx] = next;
|
|
900
|
+
writeStore(root, store, dirty);
|
|
901
|
+
// 附件被换掉 / 移除:把不再引用的文件从磁盘清掉
|
|
902
|
+
if ((entity === 'bugs' || entity === 'requirements') && 'attachment' in body) {
|
|
903
|
+
pruneAttachments(root, removedAttachments(base.attachment, next.attachment));
|
|
904
|
+
}
|
|
905
|
+
return sendJson(res, 200, { ok: true, item: next });
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
if (method === 'DELETE') {
|
|
909
|
+
const body = JSON.parse((await readBody(req)) || '{}');
|
|
910
|
+
const entity = text(body.entity, 40);
|
|
911
|
+
if (!PM_ENTITIES.includes(entity)) {
|
|
912
|
+
return sendJson(res, 400, { ok: false, error: `未知实体:${entity || '(空)'}` });
|
|
913
|
+
}
|
|
914
|
+
const ids = (Array.isArray(body.ids) ? body.ids : [body.id])
|
|
915
|
+
.map((x) => text(x, 64))
|
|
916
|
+
.filter(Boolean);
|
|
917
|
+
if (!ids.length) return sendJson(res, 400, { ok: false, error: '缺少记录 id' });
|
|
918
|
+
const store = readStore(root);
|
|
919
|
+
const dirty = new Set([entity]);
|
|
920
|
+
const attachUrls = (list) =>
|
|
921
|
+
list
|
|
922
|
+
.flatMap((x) => String(x.attachment ?? '').split('\n'))
|
|
923
|
+
.map((x) => x.trim())
|
|
924
|
+
.filter(Boolean);
|
|
925
|
+
const removedFiles =
|
|
926
|
+
entity === 'bugs' || entity === 'requirements'
|
|
927
|
+
? attachUrls(store[entity].filter((x) => ids.includes(x.id)))
|
|
928
|
+
: entity === 'projects'
|
|
929
|
+
? // 删项目会连带删掉它的需求与缺陷,附件也要一起收掉
|
|
930
|
+
attachUrls([
|
|
931
|
+
...store.requirements.filter((x) => ids.includes(x.projectId)),
|
|
932
|
+
...store.bugs.filter((x) => ids.includes(x.projectId)),
|
|
933
|
+
])
|
|
934
|
+
: [];
|
|
935
|
+
const result = applyDelete(store, entity, ids, dirty);
|
|
936
|
+
writeStore(root, store, dirty);
|
|
937
|
+
pruneAttachments(root, removedFiles);
|
|
938
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
|
|
942
|
+
} catch (err) {
|
|
943
|
+
const status = Number(err?.statusCode) || 500;
|
|
944
|
+
return sendJson(res, status, { ok: false, error: String(err?.message ?? err) });
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
},
|
|
948
|
+
};
|
|
949
|
+
}
|