2026-11-25 12:40:33 +08:00
import { getDatabase } from '@/lib/server/database' ;
import { AuthError , getCurrentUser , isSameOrigin , type AuthUser } from '@/lib/server/auth' ;
2026-09-16 14:46:32 +08:00
import { fieldSchema , missingFields , type Demand } from '@/lib/demand' ;
2026-11-25 12:40:33 +08:00
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' ;
2026-09-16 14:46:32 +08:00
export const dynamic = 'force-dynamic' ;
2026-11-25 12:40:33 +08:00
export const runtime = 'nodejs' ;
2026-09-16 14:46:32 +08:00
const fail = ( error :string , status = 400 ) => Response . json ({ error },{ status , headers : { 'Cache-Control' : 'no-store' }});
2026-11-25 12:40:33 +08:00
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 )}};};
2026-09-16 14:46:32 +08:00
export async function GET (){
2026-11-25 12:40:33 +08:00
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' }});}
2026-09-16 14:46:32 +08:00
catch ( e ){ console . error ( 'Demand load failed' , e ); return fail ( '需求暂时无法加载,请稍后重试。' , 503 );}
}
export async function POST ( request :Request ){
2026-11-25 12:40:33 +08:00
const user = await getCurrentUser (); if ( ! user ) return fail ( '登录已失效,请重新登录。' , 401 ); if ( user . mustChangePassword ) return fail ( '请先修改初始密码。' , 403 );
if ( ! isSameOrigin ( request )) return fail ( '请求来源无效。' , 403 );
2026-09-16 14:46:32 +08:00
try {
2026-11-25 12:40:33 +08:00
const raw = await request . text (); if ( raw . length > 600000 ) return fail ( '内容过长,请通过参考链接提供较大材料。' , 413 );
2026-09-16 14:46:32 +08:00
let body ; try { body = JSON . parse ( raw );} catch { return fail ( '提交内容格式无效。' );}
if ( ! body || typeof body !== 'object' ) return fail ( '提交内容格式无效。' );
2026-11-25 12:40:33 +08:00
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 ;
2026-09-16 14:46:32 +08:00
if ( action === 'create' ){
const parsed = fieldSchema . safeParse ( body . fields ); if ( ! parsed . success ) return fail ( '请检查字段格式及内容长度。' );
2026-11-25 12:40:33 +08:00
const fields = parsed . data ; if ( fields . scope || fields . outOfScope ) return fail ( '实施方案请由指定的开发责任人在需求评审中填写。' , 403 ); const mode = body . mode ; if ( ! [ 'draft' , 'register' , 'review' ]. includes ( mode )) return fail ( '登记方式无效。' );
2026-09-16 14:46:32 +08:00
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 );}
2026-11-25 12:40:33 +08:00
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 );
});
2026-09-16 14:46:32 +08:00
} else {
if ( typeof id !== 'string' ||! Number . isInteger ( revision )) return fail ( '需求编号或版本无效。' );
2026-11-25 12:40:33 +08:00
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' ){
2026-09-16 14:46:32 +08:00
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 );}
2026-11-25 12:40:33 +08:00
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 , '业务需求已修改,需开发责任人重新提交方案并由业务方确认。' );
2026-09-16 14:46:32 +08:00
record . fields = parsed . data ; record . status = mode === 'draft' ? '草稿' : '待评审' ; record . reviewReady = mode === 'review' ; label = mode === 'review' ? '补充材料并提交评审' : '更新需求' ; detail = '业务内容已更新,文档版本 ' + record . fields . version + '。' ;
} else if ( action === 'cancel' ){
2026-11-25 12:40:33 +08:00
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 ();
2026-09-16 14:46:32 +08:00
} else return fail ( '不支持的操作。' );
2026-11-25 12:40:33 +08:00
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 );
});
2026-09-16 14:46:32 +08:00
}
2026-11-25 12:40:33 +08:00
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 );}
2026-09-16 14:46:32 +08:00
}