支持自部署需求管理、交付流程与飞书集成
This commit is contained in:
1 parent
2149aeb6ed
commit
51a2e548f2
152 files changed
+8652
-6394
No files matched your search
@@ -0,0 +1,14 @@
|
||||
import { assertSameOrigin, authFailure, jsonResponse, readJsonObject, requireApiUser, sessionCookie } from '@/lib/server/auth';
|
||||
import { unbindFeishu } from '@/lib/server/feishu-auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const user = await requireApiUser();
|
||||
const body = await readJsonObject(request);
|
||||
const result = await unbindFeishu(user, body.password, request);
|
||||
return jsonResponse({ ok: true }, 200, sessionCookie(result.token, request));
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { assertSameOrigin, authFailure, AuthError, jsonResponse, readJsonObject, requireApiUser } from '@/lib/server/auth';
|
||||
import { feishuStatus, parseFeishuDeliveryQuery, retryFeishuNotification, testFeishuBot } from '@/lib/server/feishu-notifications';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
export async function GET(request: Request) {
|
||||
try { await requireApiUser({ admin: true }); return jsonResponse(feishuStatus(parseFeishuDeliveryQuery(new URL(request.url).searchParams))); }
|
||||
catch (error) { return authFailure(error); }
|
||||
}
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
await requireApiUser({ admin: true });
|
||||
const query = parseFeishuDeliveryQuery(new URL(request.url).searchParams);
|
||||
const body = await readJsonObject(request);
|
||||
if (body.action === 'test') await testFeishuBot();
|
||||
else if (body.action === 'retry') retryFeishuNotification(body.id);
|
||||
else throw new AuthError('不支持的操作。');
|
||||
return jsonResponse(feishuStatus(query));
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { assertSameOrigin, authFailure, createAccount, jsonResponse, listAccounts, readJsonObject, requireApiUser, updateAccount } from '@/lib/server/auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const admin = await requireApiUser({ admin: true });
|
||||
return jsonResponse({ users: listAccounts(admin.userId) });
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const admin = await requireApiUser({ admin: true });
|
||||
return jsonResponse({ user: await createAccount(admin.userId, await readJsonObject(request)) }, 201);
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const admin = await requireApiUser({ admin: true });
|
||||
return jsonResponse({ user: await updateAccount(admin.userId, await readJsonObject(request)) });
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { assertSameOrigin, jsonResponse, requireApiUser } from '@/lib/server/auth';
|
||||
import { deleteStagedAttachment, downloadAttachment, attachmentFailure } from '@/lib/server/attachments';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
type Context = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_request: Request, { params }: Context) {
|
||||
try {
|
||||
const user = await requireApiUser();
|
||||
const { id } = await params;
|
||||
const { file, bytes } = downloadAttachment(id, user);
|
||||
const filename = encodeURIComponent(file.name).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
||||
return new Response(new Uint8Array(bytes), { headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Disposition': `attachment; filename="attachment"; filename*=UTF-8''${filename}`,
|
||||
'Content-Length': String(file.size),
|
||||
'Cache-Control': 'private, no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': "sandbox; default-src 'none'",
|
||||
} });
|
||||
} catch (error) { return attachmentFailure(error); }
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, { params }: Context) {
|
||||
try {
|
||||
const user = await requireApiUser();
|
||||
assertSameOrigin(request);
|
||||
deleteStagedAttachment((await params).id, user.userId);
|
||||
return jsonResponse({ deleted: true });
|
||||
} catch (error) { return attachmentFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { MAX_ATTACHMENT_BYTES } from '@/lib/attachments';
|
||||
import { AuthError, assertSameOrigin, jsonResponse, requireApiUser } from '@/lib/server/auth';
|
||||
import { storeUpload, listStagedAttachments, attachmentFailure } from '@/lib/server/attachments';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const user = await requireApiUser();
|
||||
assertSameOrigin(request);
|
||||
const contentType = request.headers.get('content-type') || '';
|
||||
if (!contentType.toLowerCase().startsWith('multipart/form-data;')) throw new AuthError('请选择文件后上传。', 415);
|
||||
const limit = MAX_ATTACHMENT_BYTES + 65536;
|
||||
if (Number(request.headers.get('content-length')) > limit) throw new AuthError('单个文件不能超过 20 MB。', 413);
|
||||
const reader = request.body?.getReader();
|
||||
if (!reader) throw new AuthError('没有收到文件,请重新选择。');
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.byteLength;
|
||||
if (size > limit) { await reader.cancel(); throw new AuthError('单个文件不能超过 20 MB。', 413); }
|
||||
chunks.push(value);
|
||||
}
|
||||
let form: FormData;
|
||||
try { form = await new Response(new Uint8Array(Buffer.concat(chunks)), { headers: { 'Content-Type': contentType } }).formData(); }
|
||||
catch { throw new AuthError('上传内容不完整,请重新选择文件上传。'); }
|
||||
const files = form.getAll('file');
|
||||
if (files.length !== 1 || !(files[0] instanceof File)) throw new AuthError('每次上传一个文件。');
|
||||
const file = files[0];
|
||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new AuthError('单个文件不能超过 20 MB。', 413);
|
||||
return jsonResponse({ attachment: storeUpload(user.userId, file.name, new Uint8Array(await file.arrayBuffer())) }, 201);
|
||||
} catch (error) { return attachmentFailure(error); }
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try { return jsonResponse({ attachments: listStagedAttachments((await requireApiUser()).userId) }); }
|
||||
catch (error) { return attachmentFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { appPath } from '@/lib/base-path';
|
||||
import { sessionCookie } from '@/lib/server/auth';
|
||||
import { applicationOrigin } from '@/lib/server/database';
|
||||
import { completeFeishuAuth, consumeFeishuState, FeishuAuthError, feishuStateCookie } from '@/lib/server/feishu-auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
export async function GET(request: Request) {
|
||||
const headers = new Headers({ 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
|
||||
let binding = false;
|
||||
try {
|
||||
const state = consumeFeishuState(request);
|
||||
binding = Boolean(state.account_id);
|
||||
headers.append('Set-Cookie', feishuStateCookie(''));
|
||||
const result = await completeFeishuAuth(request, state);
|
||||
if (result.token) headers.append('Set-Cookie', sessionCookie(result.token, request));
|
||||
headers.set('Location', applicationOrigin() + appPath(result.returnTo + (result.bound ? '?bound=1' : '')));
|
||||
} catch (error) {
|
||||
const code = error instanceof FeishuAuthError ? error.code : 'failed';
|
||||
headers.set('Location', applicationOrigin() + appPath(`${binding ? '/account/feishu' : '/login'}?feishuError=${code}`));
|
||||
}
|
||||
return new Response(null, { status: 303, headers });
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { appPath } from '@/lib/base-path';
|
||||
import { assertSameOrigin, AuthError } from '@/lib/server/auth';
|
||||
import { applicationOrigin } from '@/lib/server/database';
|
||||
import { beginFeishuAuth, FeishuAuthError } from '@/lib/server/feishu-auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
export async function POST(request: Request) {
|
||||
let intent = 'login';
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const raw = await request.text();
|
||||
if (raw.length > 8192) throw new FeishuAuthError('failed');
|
||||
const form = new URLSearchParams(raw);
|
||||
intent = form.get('intent') || 'login';
|
||||
const result = beginFeishuAuth(request, intent, form.get('next'));
|
||||
return new Response(null, { status: 303, headers: { Location: result.url, 'Set-Cookie': result.cookie, 'Cache-Control': 'no-store' } });
|
||||
} catch (error) {
|
||||
const code = error instanceof FeishuAuthError ? error.code : error instanceof AuthError && error.status === 429 ? 'rate_limited' : error instanceof AuthError && error.status === 403 ? 'source' : 'failed';
|
||||
return new Response(null, { status: 303, headers: { Location: applicationOrigin() + appPath(`${intent === 'bind' ? '/account/feishu' : '/login'}?feishuError=${code}`), 'Cache-Control': 'no-store' } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { assertSameOrigin, authFailure, jsonResponse, loginWithPassword, readJsonObject, sessionCookie } from '@/lib/server/auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const body = await readJsonObject(request);
|
||||
const { user, token } = await loginWithPassword(body.username, body.password, request);
|
||||
return jsonResponse({ user }, 200, sessionCookie(token, request));
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { assertSameOrigin, authFailure, jsonResponse, logoutCurrentSession, sessionCookie } from '@/lib/server/auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
await logoutCurrentSession();
|
||||
return jsonResponse({ ok: true }, 200, sessionCookie('', request));
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { authFailure, jsonResponse, requireApiUser } from '@/lib/server/auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET() {
|
||||
try { return jsonResponse({ user: await requireApiUser({ allowPasswordChange: true }) }); }
|
||||
catch (error) { return authFailure(error); }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { assertSameOrigin, authFailure, changeAccountPassword, jsonResponse, readJsonObject, requireApiUser, sessionCookie } from '@/lib/server/auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const current = await requireApiUser({ allowPasswordChange: true });
|
||||
const body = await readJsonObject(request);
|
||||
const { user, token } = await changeAccountPassword(current.userId, body.currentPassword, body.newPassword);
|
||||
return jsonResponse({ user }, 200, sessionCookie(token, request));
|
||||
} catch (error) { return authFailure(error); }
|
||||
}
|
||||
+54
-26
@@ -1,50 +1,78 @@
|
||||
import { env } from 'cloudflare:workers';
|
||||
import { getChatGPTUser } from '../../chatgpt-auth';
|
||||
import { getDatabase } from '@/lib/server/database';
|
||||
import { AuthError, getCurrentUser, isSameOrigin, type AuthUser } from '@/lib/server/auth';
|
||||
import { fieldSchema, missingFields, type Demand } from '@/lib/demand';
|
||||
import { invalidateProposal } from '@/lib/demand-review';
|
||||
import { applyReviewAction } from '@/lib/server/demand-review';
|
||||
import { withDefaultDeveloper, canTakeOverDevelopment } from '@/lib/server/default-developer';
|
||||
import { attachmentIds, syncDemandAttachments, commitDemandAttachments } from '@/lib/server/attachments';
|
||||
import { readableDemandWhere, readableDemandBindings } from '@/lib/server/demand-access';
|
||||
import { workflowActions, applyWorkflowAction } from '@/lib/server/workflow';
|
||||
import { queueDemandNotification } from '@/lib/server/feishu-notifications';
|
||||
export const dynamic='force-dynamic';
|
||||
export const runtime='nodejs';
|
||||
const fail=(error:string,status=400)=>Response.json({error},{status,headers:{'Cache-Control':'no-store'}});
|
||||
function db(){if(!env.DB)throw new Error('Database unavailable');return env.DB;}
|
||||
const db=getDatabase;
|
||||
const reviewActions=new Set(['assign-developer','take-over-development','propose-solution','confirm-solution','return-solution']);
|
||||
const visibleDemand=(record:Demand,ownerId:string,user:AuthUser):Demand=>{const demand=withDefaultDeveloper(record);return {...demand,access:{business:ownerId===user.userId,developer:demand.status!=='草稿'&&demand.review?.developer.userId===user.userId,canTakeOverDevelopment:canTakeOverDevelopment(demand,user)}};};
|
||||
export async function GET(){
|
||||
const user=await getChatGPTUser();if(!user)return fail('请先登录后查看你的需求。',401);
|
||||
try{const result=await db().prepare('SELECT payload, revision FROM demands WHERE owner_id = ? ORDER BY updated_at DESC').bind(user.userId).all<{payload:string;revision:number}>();return Response.json({demands:result.results.map(r=>({...JSON.parse(r.payload),revision:r.revision}))},{headers:{'Cache-Control':'no-store'}});}
|
||||
const user=await getCurrentUser();if(!user)return fail('登录已失效,请重新登录。',401);if(user.mustChangePassword)return fail('请先修改初始密码。',403);
|
||||
try{const result=await db().prepare(`SELECT payload, revision, owner_id FROM demands WHERE ${readableDemandWhere} ORDER BY updated_at DESC`).bind(...readableDemandBindings(user)).all<{payload:string;revision:number;owner_id:string}>();return Response.json({demands:result.results.map(r=>visibleDemand({...JSON.parse(r.payload),revision:r.revision},r.owner_id,user))},{headers:{'Cache-Control':'no-store'}});}
|
||||
catch(e){console.error('Demand load failed',e);return fail('需求暂时无法加载,请稍后重试。',503);}
|
||||
}
|
||||
export async function POST(request:Request){
|
||||
const user=await getChatGPTUser();if(!user)return fail('请先登录后保存需求。',401);
|
||||
if(request.headers.get('origin')&&request.headers.get('origin')!==new URL(request.url).origin)return fail('请求来源无效。',403);
|
||||
const user=await getCurrentUser();if(!user)return fail('登录已失效,请重新登录。',401);if(user.mustChangePassword)return fail('请先修改初始密码。',403);
|
||||
if(!isSameOrigin(request))return fail('请求来源无效。',403);
|
||||
try{
|
||||
const raw=await request.text();if(raw.length>80000)return fail('内容过长,请通过参考链接提供较大材料。',413);
|
||||
const raw=await request.text();if(raw.length>600000)return fail('内容过长,请通过参考链接提供较大材料。',413);
|
||||
let body;try{body=JSON.parse(raw);}catch{return fail('提交内容格式无效。');}
|
||||
if(!body||typeof body!=='object')return fail('提交内容格式无效。');
|
||||
const {action,id,revision}=body;const now=new Date().toISOString();let record:Demand;
|
||||
const {action,id,revision}=body;const selectedAttachments=['create','update'].includes(action)?attachmentIds(body.attachmentIds):undefined;const now=new Date().toISOString();let record:Demand;let ownerId=user.userId;
|
||||
if(action==='create'){
|
||||
const parsed=fieldSchema.safeParse(body.fields);if(!parsed.success)return fail('请检查字段格式及内容长度。');
|
||||
const fields=parsed.data;const mode=body.mode;if(!['draft','register','review'].includes(mode))return fail('登记方式无效。');
|
||||
const fields=parsed.data;if(fields.scope||fields.outOfScope)return fail('实施方案请由指定的开发责任人在需求评审中填写。',403);const mode=body.mode;if(!['draft','register','review'].includes(mode))return fail('登记方式无效。');
|
||||
if(!fields.title)return fail('请先填写需求标题。');const missing=mode==='draft'?[]:missingFields(fields,mode==='review');if(missing.length)return fail('请补充:'+missing.join('、'));
|
||||
if(mode!=='draft'){const all=await db().prepare('SELECT payload FROM demands WHERE owner_id = ?').bind(user.userId).all<{payload:string}>();if(all.results.some(r=>{const d=JSON.parse(r.payload);return !['草稿','已取消','已完成'].includes(d.status)&&d.fields.title===fields.title;}))return fail('已存在同名需求,请先检查现有记录,避免重复登记。',409);}
|
||||
record={id:'REQ-'+now.slice(0,10).replaceAll('-','')+'-'+crypto.randomUUID().slice(0,8).toUpperCase(),revision:1,fields,status:mode==='draft'?'草稿':'待评审',reviewReady:mode==='review',createdAt:now,updatedAt:now,history:[{time:now,actor:user.displayName,action:mode==='draft'?'保存草稿':mode==='review'?'提交评审':'登记需求',detail:mode==='review'?'业务材料已齐备,等待负责人评审。':'已保存业务需求信息。'}],changes:[]};
|
||||
await db().prepare('INSERT INTO demands (id, owner_id, payload, revision, updated_at) VALUES (?, ?, ?, 1, ?)').bind(record.id,user.userId,JSON.stringify(record),now).run();
|
||||
record={id:'REQ-'+now.slice(0,10).replaceAll('-','')+'-'+crypto.randomUUID().slice(0,8).toUpperCase(),revision:1,fields,status:mode==='draft'?'草稿':'待评审',reviewReady:mode==='review',createdAt:now,updatedAt:now,history:[{time:now,actor:user.displayName,action:mode==='draft'?'保存草稿':mode==='review'?'提交评审':'登记需求',detail:mode==='review'?'业务材料已齐备,实施范围与功能说明、范围外事项待开发责任人在需求评审时提出方案,并与业务方确认。':'已保存业务需求信息。'}],changes:[]};
|
||||
record=withDefaultDeveloper(record);
|
||||
db().transaction(()=>{
|
||||
syncDemandAttachments(record,ownerId,selectedAttachments??[],now);
|
||||
db().prepare('INSERT INTO demands (id, owner_id, payload, revision, updated_at) VALUES (?, ?, ?, 1, ?)').bind(record.id,user.userId,JSON.stringify(record),now).run();
|
||||
commitDemandAttachments(record,ownerId);
|
||||
queueDemandNotification(record);
|
||||
});
|
||||
}else{
|
||||
if(typeof id!=='string'||!Number.isInteger(revision))return fail('需求编号或版本无效。');
|
||||
const row=await db().prepare('SELECT payload, revision FROM demands WHERE id = ? AND owner_id = ?').bind(id,user.userId).first<{payload:string;revision:number}>();if(!row)return fail('找不到该需求或你没有访问权限。',404);if(row.revision!==revision)return fail('需求已更新,请刷新后再操作;本次输入尚未保存。',409);
|
||||
record=JSON.parse(row.payload);let label='',detail='';
|
||||
if(action==='update'){
|
||||
const row=await db().prepare(`SELECT payload, revision, owner_id FROM demands WHERE id = ? AND ${readableDemandWhere}`).bind(id,...readableDemandBindings(user)).first<{payload:string;revision:number;owner_id:string}>();if(!row)return fail('找不到该需求或你没有访问权限。',404);
|
||||
record=withDefaultDeveloper(JSON.parse(row.payload));ownerId=row.owner_id;
|
||||
if(ownerId!==user.userId&&record.review?.developer.userId!==user.userId&&!(action==='take-over-development'&&canTakeOverDevelopment(record,user)))return fail('找不到该需求或你没有访问权限。',404);
|
||||
if(row.revision!==revision)return fail('需求已更新,请刷新后再操作;本次输入尚未保存。',409);
|
||||
let label='',detail='';
|
||||
if(ownerId!==user.userId&&!reviewActions.has(action)&&!workflowActions.has(action))return fail('开发责任人只能提交评审方案,业务操作由需求登记账号执行。',403);
|
||||
if(workflowActions.has(action)){
|
||||
({label,detail}=applyWorkflowAction(record,ownerId,user,body,now));
|
||||
}else if(reviewActions.has(action)){
|
||||
({label,detail}=applyReviewAction(record,ownerId,user,body,now));
|
||||
}else if(action==='update'){
|
||||
if(!['草稿','待评审'].includes(record.status))return fail('已确认的需求请通过「提出变更」进行调整。',409);
|
||||
const parsed=fieldSchema.safeParse(body.fields);if(!parsed.success)return fail('请检查字段格式及内容长度。');const mode=body.mode;if(!['draft','register','review'].includes(mode))return fail('保存方式无效。');if(record.status!=='草稿'&&mode==='draft')return fail('正式需求不能退回草稿。');if(!parsed.data.title)return fail('请填写需求标题。');const missing=mode==='draft'?[]:missingFields(parsed.data,mode==='review');if(missing.length)return fail('请补充:'+missing.join('、'));
|
||||
if(mode!=='draft'){const peers=await db().prepare('SELECT id, payload FROM demands WHERE owner_id = ? AND id != ?').bind(user.userId,id).all<{id:string;payload:string}>();if(peers.results.some(r=>{const p=JSON.parse(r.payload);return !['草稿','已取消','已完成'].includes(p.status)&&p.fields.title===parsed.data.title;}))return fail('已存在同名需求,请核对后合并到原记录。',409);}
|
||||
if(parsed.data.scope!==record.fields.scope||parsed.data.outOfScope!==record.fields.outOfScope)return fail('业务信息编辑不能修改评审方案,请由开发责任人提交。',403);
|
||||
const businessChanged=Object.entries(parsed.data).some(([key,value])=>value!==record.fields[key as keyof typeof record.fields]);
|
||||
if(businessChanged)invalidateProposal(record,now,'业务需求已修改,需开发责任人重新提交方案并由业务方确认。');
|
||||
record.fields=parsed.data;record.status=mode==='draft'?'草稿':'待评审';record.reviewReady=mode==='review';label=mode==='review'?'补充材料并提交评审':'更新需求';detail='业务内容已更新,文档版本 '+record.fields.version+'。';
|
||||
}else if(action==='cancel'){
|
||||
if(['已上线','已完成','已取消'].includes(record.status))return fail('当前状态不能取消。',409);if(typeof body.reason!=='string'||!body.reason.trim()||body.reason.length>3000)return fail('请填写终止原因(3000 字以内)。');record.status='已取消';label='确认取消需求';detail=body.reason.trim();
|
||||
}else if(action==='change'){
|
||||
if(!['已排期','开发中','待验收','待发布','已上线'].includes(record.status))return fail('当前状态不能提出变更;待评审需求请直接补充信息。',409);if(typeof body.content!=='string'||typeof body.reason!=='string'||!body.content.trim()||!body.reason.trim()||body.content.length>5000||body.reason.length>3000)return fail('请填写变更内容(5000 字以内)和原因(3000 字以内)。');record.changes.push({time:now,content:body.content.trim(),reason:body.reason.trim(),actor:user.displayName,status:'待开发评估与双方确认',originalVersion:record.fields.version,originalFields:structuredClone(record.fields)});label='提出需求变更';detail=body.content.trim()+';原因:'+body.reason.trim()+'。原范围与版本保留,待评估确认后实施。';
|
||||
}else if(action==='accept'){
|
||||
if(record.status!=='待验收'||!record.acceptance)return fail('该需求尚未进入可验收阶段。',409);
|
||||
const results=body.results;if(!Array.isArray(results)||results.length!==record.acceptance.items.length||!results.length||results.some(r=>!['通过','不通过'].includes(r)))return fail('请逐项填写验收结果。');if(typeof body.notes!=='string'||!body.notes.trim()||body.notes.length>5000)return fail('请填写遗留问题及处理计划,无则填“无”。');if(body.confirm!==true)return fail('请明确确认本次验收结论。');if(body.testVersion!==record.acceptance.testVersion||body.version!==record.fields.version)return fail('验收版本已变化,请重新核对。',409);
|
||||
const passed=results.every(r=>r==='通过');record.status=passed?'待发布':'开发中';record.acceptanceRecords??=[];record.acceptanceRecords.push({time:now,actor:user.displayName,version:record.fields.version,testVersion:record.acceptance.testVersion,results,notes:body.notes.trim(),passed,items:record.acceptance.items.map((item,i)=>({...item,result:results[i]})),environment:record.acceptance.environment});label=passed?'业务验收通过':'业务验收未通过';detail=`需求文档 ${record.fields.version};测试版本 ${record.acceptance.testVersion};${passed?'全部验收项通过,同意按约定计划上线。':'退回开发中修复,需重新提测。'}遗留问题及计划:${body.notes.trim()}`;
|
||||
if(['已上线','已完成','已取消'].includes(record.status))return fail('当前状态不能取消。',409);if(typeof body.reason!=='string'||!body.reason.trim()||body.reason.length>3000)return fail('请填写终止原因(3000 字以内)。');record.status='已取消';for(const change of record.changes){if(['待开发评估与双方确认','待开发评估','待业务确认'].includes(change.status))change.status='随需求取消';}delete record.blocked;if(record.delivery)delete record.delivery.blocker;label='确认取消需求';detail=body.reason.trim();
|
||||
}else return fail('不支持的操作。');
|
||||
record.revision=row.revision+1;record.updatedAt=now;record.history.push({time:now,actor:user.displayName,action:label,detail});
|
||||
const updated=await db().prepare('UPDATE demands SET payload = ?, revision = ?, updated_at = ? WHERE id = ? AND owner_id = ? AND revision = ?').bind(JSON.stringify(record),record.revision,now,id,user.userId,row.revision).run();if(updated.meta.changes!==1)return fail('需求已被更新,请刷新后重试。',409);
|
||||
record=withDefaultDeveloper(record);
|
||||
db().transaction(()=>{
|
||||
if(action==='update'&&syncDemandAttachments(record,ownerId,selectedAttachments,now))detail+='参考附件已更新;已有评审方案需重新提交确认。';
|
||||
record.revision=row.revision+1;record.updatedAt=now;record.history.push({time:now,actor:user.displayName,action:label,detail});
|
||||
const updated=db().prepare('UPDATE demands SET payload = ?, revision = ?, updated_at = ? WHERE id = ? AND owner_id = ? AND revision = ?').bind(JSON.stringify(record),record.revision,now,id,ownerId,row.revision).run();
|
||||
if(updated.meta.changes!==1)throw new AuthError('需求已被更新,请刷新后重试。',409);
|
||||
commitDemandAttachments(record,ownerId);
|
||||
queueDemandNotification(record);
|
||||
});
|
||||
}
|
||||
return Response.json({demand:record},{headers:{'Cache-Control':'no-store'}});
|
||||
}catch(e){console.error('Demand save failed',e);return fail('保存失败,你的输入仍保留在页面中,请稍后重试。',503);}
|
||||
return Response.json({demand:visibleDemand(record,ownerId,user)},{headers:{'Cache-Control':'no-store'}});
|
||||
}catch(e){if(e instanceof AuthError)return fail(e.message,e.status);console.error('Demand save failed',e);return fail('保存失败,你的输入仍保留在页面中,请稍后重试。',503);}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { getCurrentUser } from '@/lib/server/auth';
|
||||
import { findDocument } from '@/lib/documents';
|
||||
export const runtime='nodejs';
|
||||
export const dynamic='force-dynamic';
|
||||
export async function GET(request:Request,{params}:{params:Promise<{name:string}>}) {
|
||||
const user=await getCurrentUser();
|
||||
if(!user)return Response.json({error:'请先登录。'},{status:401,headers:{'Cache-Control':'no-store'}});
|
||||
if(user.mustChangePassword)return Response.json({error:'请先修改初始密码。'},{status:403,headers:{'Cache-Control':'no-store'}});
|
||||
const {name}=await params;const document=findDocument(name);
|
||||
if(!document)return Response.json({error:'找不到该文档。'},{status:404});
|
||||
const format=new URL(request.url).searchParams.get('format')||'markdown';
|
||||
if(!['json','markdown','docx'].includes(format))return Response.json({error:'不支持的文档格式。'},{status:400});
|
||||
try{
|
||||
if(format==='docx'){
|
||||
const filename=document.filename.replace(/\.md$/,'.docx');
|
||||
const data=await readFile(join(process.cwd(),'content','word',filename));
|
||||
return new Response(new Uint8Array(data),{headers:{'Content-Type':'application/vnd.openxmlformats-officedocument.wordprocessingml.document','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||||
}
|
||||
const content=await readFile(join(process.cwd(),'content','docs',document.filename),'utf8');
|
||||
if(format==='json')return Response.json({id:document.id,title:document.title,content},{headers:{'Cache-Control':'private, no-store'}});
|
||||
return new Response(content,{headers:{'Content-Type':'text/markdown; charset=utf-8','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(document.filename)}`,'Cache-Control':'private, no-store'}});
|
||||
}catch(error){console.error('Document read failed',error);return Response.json({error:'文档暂时无法打开或下载,请稍后重试。'},{status:503,headers:{'Cache-Control':'no-store'}});}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { getDatabase } from '@/lib/server/database';
|
||||
export const runtime='nodejs';
|
||||
export const dynamic='force-dynamic';
|
||||
export async function GET(){
|
||||
try{getDatabase().prepare('SELECT 1').first();return Response.json({status:'ok'},{headers:{'Cache-Control':'no-store'}});}
|
||||
catch{ return Response.json({status:'unavailable'},{status:503,headers:{'Cache-Control':'no-store'}});}
|
||||
}
|
||||
Reference in new issue
Block a user