支持自部署需求管理、交付流程与飞书集成

This commit is contained in:
xyt committed 2026-11-25 12:40:33 +08:00
1 parent 2149aeb6ed
commit 51a2e548f2
152 files changed
+8652 -6394

No files matched your search

+55 -19
View File
@@ -1,24 +1,47 @@
'use client';
import { useState } from 'react';
import { X, ArrowLeft, ArrowRight, Save, Send, Info, Check, CircleAlert, FilePenLine } from 'lucide-react';
import { useId, useRef, useState, type ReactNode } from 'react';
import { X, ArrowLeft, ArrowRight, Save, Send, Info, Check, CircleAlert, FilePenLine, Paperclip } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogContent, AlertDialogTitle, AlertDialogDescription, AlertDialogCancel, AlertDialogAction } from '@/components/ui/alert-dialog';
import { emptyFields, missingFields, type Fields, type Demand } from '@/lib/demand';
import type { Attachment } from '@/lib/attachments';
import { appPath } from '@/lib/base-path';
import { AttachmentPicker } from './attachments';
import { TemplateActions, type OpenTemplatePreview } from './template-actions';
import TemplatePreview from './template-preview';
import type { DocumentId } from '@/lib/documents';
import { MAX_ATTACHMENTS } from '@/lib/attachments';
export type SaveInput={action:string;id?:string;revision?:number;fields?:Fields;mode?:string;[key:string]:unknown};
export function DemandForm({initial,onSave,onClose,busy,error,userName,existing}:{initial?:Demand;onSave:(body:SaveInput)=>Promise<void>;onClose:()=>void;busy:boolean;error:string;userName:string;existing:Demand[]}){
const [f,setF]=useState<Fields>(initial?.fields??{...emptyFields,proposer:userName,owner:userName});const [step,setStep]=useState(0);const [invalid,setInvalid]=useState<string[]>([]);const [exit,setExit]=useState(false);
export function DemandForm({initial,onSave,onClose,busy:saving,error,userName,existing}:{initial?:Demand;onSave:(body:SaveInput)=>Promise<void>;onClose:()=>void;busy:boolean;error:string;userName:string;existing:Demand[]}){
const inputPrefix=useId();const backgroundUpload=useRef<HTMLInputElement>(null);
// Guard the parent synchronously, before Radix registers the preview's layer.
const [templateId,setTemplateId]=useState<DocumentId|null>(null);const activePreview=useRef<DocumentId|null>(null);const templateTrigger=useRef<HTMLElement|null>(null);
const openPreview:OpenTemplatePreview=(id,trigger)=>{activePreview.current=id;templateTrigger.current=trigger;setTemplateId(id);};
function closePreview(){activePreview.current=null;setTemplateId(null);}
const [attachments,setAttachments]=useState<Attachment[]>(()=>initial?.attachments??[]);const [uploading,setUploading]=useState(false);const newUploads=useRef(new Set<string>());const busy=saving||uploading;
function releaseUploads(ids:Iterable<string>){for(const id of ids){void fetch(appPath('/api/attachments/'+id),{method:'DELETE',keepalive:true}).catch(()=>{});newUploads.current.delete(id);}}
function changeAttachments(next:Attachment[]){const kept=new Set(next.map(file=>file.id));releaseUploads(attachments.filter(file=>newUploads.current.has(file.id)&&!kept.has(file.id)).map(file=>file.id));setAttachments(next);}
function closeForm(){releaseUploads([...newUploads.current]);onClose();}
const [startingFields]=useState<Fields>(()=>({... (initial?.fields??{...emptyFields,proposer:userName,owner:userName})}));
const [f,setF]=useState<Fields>(startingFields);const [step,setStep]=useState(0);const [invalid,setInvalid]=useState<string[]>([]);const [exit,setExit]=useState(false);
const closeButton=useRef<HTMLButtonElement>(null);const returnFocus=useRef<HTMLElement|null>(null);
const changed=(Object.keys(startingFields) as (keyof Fields)[]).some(key=>f[key]!==startingFields[key])||attachments.map(file=>file.id).join(',')!==(initial?.attachments??[]).map(file=>file.id).join(',');
function requestClose(){if(activePreview.current){closePreview();return;}if(busy)return;if(changed){returnFocus.current=document.activeElement instanceof HTMLElement?document.activeElement:closeButton.current;setExit(true)}else closeForm();}
const set=(k:keyof Fields,v:string|boolean)=>setF(prev=>({...prev,[k]:v}));
const duplicate=existing.find(d=>d.id!==initial?.id&&f.title.trim().length>3&&d.fields.title.includes(f.title.trim()));
const field=(k:keyof Fields,label:string,placeholder:string,opts:{large?:boolean;full?:boolean;required?:boolean;type?:string;hint?:string;max?:number}={})=><label className={'form-field '+(opts.full?'span-two':'')} key={k}><span>{label}{opts.required&&<em>*</em>}</span>{opts.large?<textarea value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} rows={3} maxLength={opts.max??3000}/>:<input type={opts.type??'text'} value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} maxLength={opts.max??100}/>} {opts.hint&&<small>{opts.hint}</small>}</label>;
async function save(mode:string){const m=mode==='draft'?(f.title.trim()?[]:['需求标题']):missingFields(f,mode==='review');setInvalid(m);if(m.length){setStep(mode==='review'?step:m.some(x=>['需求标题','所属项目','业务模块','提出人','所属部门','需求来源','需求负责人'].includes(x))?0:1);return;}await onSave({action:initial&&!initial.demo?'update':'create',id:initial?.demo?undefined:initial?.id,revision:initial?.revision,fields:f,mode});}
return <Dialog open onOpenChange={open=>{if(!open&&!busy)setExit(true)}}><DialogContent className="demand-modal form-modal" showCloseButton={false} onInteractOutside={e=>e.preventDefault()}><div className="modal-heading"><div className="modal-icon"><FilePenLine size={23}/></div><div><DialogTitle className="modal-title">{initial?'完善需求信息':'登记新需求'}</DialogTitle><DialogDescription className="modal-subtitle">一个独立业务目标,对应一条需求。先登记,再逐步完善。</DialogDescription></div><button className="icon-button" aria-label="关闭登记窗口" onClick={()=>setExit(true)} disabled={busy}><X size={20}/></button></div>
<div className="form-steps">{['基本信息','业务背景与目标','范围与验收','数据与参考材料'].map((s,i)=><button key={s} className={i===step?'current':i<step?'done':''} onClick={()=>setStep(i)}><span>{i<step?<Check size={14}/>:i+1}</span><b>{s}</b></button>)}</div>
const field=(k:keyof Fields,label:string,placeholder:string,opts:{large?:boolean;full?:boolean;required?:boolean;type?:string;hint?:string;max?:number;actions?:ReactNode}={})=>{
const id=inputPrefix+'-'+k;
return <div className={'form-field '+(opts.full?'span-two':'')} key={k}><div className="form-field-heading"><label htmlFor={id}>{label}{opts.required&&<em>*</em>}</label>{opts.actions}</div>{opts.large?<textarea id={id} value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} rows={3} maxLength={opts.max??3000}/>:<input id={id} type={opts.type??'text'} value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} maxLength={opts.max??100}/>} {opts.hint&&<small>{opts.hint}</small>}</div>;
};
async function save(mode:string){const m=mode==='draft'?(f.title.trim()?[]:['需求标题']):missingFields(f,mode==='review');setInvalid(m);if(m.length){setStep(mode==='review'?step:m.some(x=>['需求标题','所属项目','业务模块','提出人','所属部门','需求来源','需求负责人'].includes(x))?0:1);return;}await onSave({action:initial?'update':'create',id:initial?.id,revision:initial?.revision,fields:f,mode,attachmentIds:attachments.map(file=>file.id)});}
return <><Dialog open onOpenChange={open=>{if(!open)requestClose()}}><DialogContent className="demand-modal form-modal" showCloseButton={false} aria-busy={busy} onInteractOutside={e=>e.preventDefault()} onEscapeKeyDown={e=>{if(e.defaultPrevented)return;if(activePreview.current){e.preventDefault();closePreview();}else if(busy)e.preventDefault();}}><div className="modal-heading"><div className="modal-icon"><FilePenLine size={23}/></div><div><DialogTitle className="modal-title">{initial?'完善需求信息':'登记新需求'}</DialogTitle><DialogDescription className="modal-subtitle">一个独立业务目标,对应一条需求。先登记,再逐步完善。</DialogDescription></div><button ref={closeButton} type="button" className="icon-button" aria-label="关闭登记窗口" onClick={requestClose} disabled={busy}><X size={20}/></button></div>
<div className="form-steps">{['基本信息','业务背景与目标','验收与优先级','数据与参考材料'].map((s,i)=><button key={s} className={i===step?'current':i<step?'done':''} onClick={()=>setStep(i)} disabled={busy}><span>{i<step?<Check size={14}/>:i+1}</span><b>{s}</b></button>)}</div>
<div className="modal-scroll"><div className="form-content">
{initial?.demo&&<div className="info-banner"><Info size={17}/>你正在参考示例填写,保存将创建一条属于你的新需求。</div>}
{exit&&<div className="exit-banner"><div><strong>本次编辑尚未保存</strong><p>你可以继续填写,或保存为草稿后离开。</p></div><button className="btn" onClick={()=>setExit(false)}>继续填写</button><button className="text-button danger-text" onClick={onClose}>放弃本次编辑</button></div>}
{(error||invalid.length>0)&&<div className="error-banner" role="alert"><CircleAlert size={18}/><span>{error||'请补充:'+invalid.join('、')}</span></div>}
<div className="form-section-heading"><h2>{['这是什么需求?','希望解决什么业务问题?','怎样才算做好了?','开发前,还需要哪些信息?'][step]}</h2><p>{['基本信息用于明确需求归属和联系人员。','用熟悉的业务语言描述,不需要填写技术实现方案。','这一部分可在登记后补充,提交评审前需填写完整。','材料可通过链接关联;简单需求可直接使用本表单作为需求正文。'][step]}</p></div>
<div className="form-grid">
<div className="form-section-heading"><h2>{['这是什么需求?','希望解决什么业务问题?','怎样才算做好了?','开发前,还需要哪些信息?'][step]}</h2><p>{['基本信息用于明确需求归属和联系人员。','用熟悉的业务语言描述,不需要填写技术实现方案。','这一部分可在登记后补充,提交评审前需填写完整。','参考材料可上传文件或填写链接;简单需求可直接使用本表单作为需求正文。'][step]}</p></div>
<fieldset className="form-grid" disabled={busy}>
{step===0&&<>
<div className="span-two contextual-template"><span>需要先整理基本信息?</span><TemplateActions documentId="registration" disabled={busy} onPreview={openPreview}/></div>
{field('title','需求标题','例如:订单管理—支持按订单状态导出',{full:true,required:true,hint:'建议使用“业务模块 + 动作或能力”,避免“页面优化”等笼统标题。'})}
{duplicate&&<div className="span-two info-banner"><Info size={16}/>已有相似需求「{duplicate.fields.title}」,请核对是否为同一目标。</div>}
{field('project','所属项目','例如:企业业务平台',{required:true})}{field('module','业务模块','例如:订单管理',{required:true})}
@@ -26,7 +49,9 @@ export function DemandForm({initial,onSave,onClose,busy,error,userName,existing}
{field('department','所属部门','例如:销售部',{required:true})}{field('proposer','提出人','填写实际提出人',{required:true})}{field('owner','需求负责人','负责确认范围和业务验收的人',{required:true})}{field('source','需求来源','例如:销售周会、客户反馈、日常操作问题',{full:true,required:true,max:200})}
</>}
{step===1&&<>
{field('background','业务背景与现有处理方式','现在怎么做?具体遇到了什么问题?请补充实际案例或数据依据。',{large:true,full:true,required:true,max:6000})}
{field('background','业务背景与现有处理方式','简要说明当前做法和主要问题;详细内容可上传文件或填写文档链接。',{large:true,full:true,required:true,max:6000,hint:'这里可以简短说明。详细需求可按模板整理后上传,或在下方关联飞书文档。',actions:<><button className="text-button" type="button" disabled={busy||attachments.length>=MAX_ATTACHMENTS} onClick={()=>backgroundUpload.current?.click()}><Paperclip size={14}/>{uploading?'正在上传…':'上传文件'}</button><TemplateActions documentId="requirement" disabled={busy} onPreview={openPreview}/></>})}
<AttachmentPicker files={attachments} onChange={changeAttachments} disabled={saving} uploading={uploading} onUploadingChange={setUploading} onNewUpload={file=>newUploads.current.add(file.id)} inputRef={backgroundUpload} compact/>
{field('references','需求说明文档链接(选填)','粘贴填写后的飞书文档或其他参考链接,每行一条。',{large:true,full:true,max:5000,hint:'上传文件与填写链接可任选,也可以同时使用;这些材料会随需求保存。'})}
{field('impact','影响对象与业务依据','哪些用户或岗位受影响?影响范围有多大?依据是什么?',{large:true,full:true,required:true})}
{field('goal','预期目标','完成后希望达到什么结果?有量化依据时,请说明目标值与统计口径。',{large:true,full:true,required:true})}
<label className="check-field span-two"><input type="checkbox" checked={f.noFixedDate} onChange={e=>set('noFixedDate',e.target.checked)}/>没有固定的上线日期</label>
@@ -34,21 +59,32 @@ export function DemandForm({initial,onSave,onClose,busy,error,userName,existing}
<div className="info-banner span-two"><Info size={17}/>这是业务期望时间,正式交付计划由需求负责人和开发负责人评审确认。</div>
</>}
{step===2&&<>
{field('scope','实施范围与功能说明','F-01:本次需要支持的功能、操作步骤和业务规则。\nF-02:另一项相关功能。',{large:true,full:true,required:true,max:6000})}
{field('outOfScope','范围外事项','明确这次不做什么,无相关事项可填写“无”。',{large:true,full:true,required:true})}
{field('criteria','验收标准','AC-01 / F-01:在什么场景下执行什么操作,应得到什么结果。\n请覆盖正常流程、空数据、非法输入等关键异常。',{large:true,full:true,required:true,max:6000,hint:'每一项都应能实际验证,避免仅写“使用正常”“体验良好”。'})}
<div className="info-banner span-two"><Info size={17}/><span>实施范围与功能说明、范围外事项由开发责任人在需求评审时提出方案,并与业务方确认。</span></div>
{field('criteria','验收标准','AC-01:在什么业务场景下执行什么操作,应得到什么结果。\n请覆盖正常流程、空数据、非法输入等关键异常。',{large:true,full:true,required:true,max:6000,hint:'每项结果都应能实际验证;需求说明模板中的“验收标准”章节可供参考。',actions:<TemplateActions documentId="requirement" disabled={busy} onPreview={openPreview}/>})}
<label className="form-field"><span>建议优先级<em>*</em></span><select value={f.priority} onChange={e=>set('priority',e.target.value)}><option value="P2">P2 · 常规优化或储备</option><option value="P1">P1 · 近期业务目标</option><option value="P0">P0 · 业务阻塞或关键节点</option></select><small>最终优先级以评审结论为准。</small></label>
{field('priorityReason','优先级依据','说明业务影响、时间要求及依赖',{required:true,max:1000})}
</>}
{step===3&&<>
<label className="check-field span-two"><input type="checkbox" checked={f.noData} onChange={e=>set('noData',e.target.checked)}/>本需求不涉及数据来源</label>
{!f.noData&&<>{field('dataSource','数据来自哪里','平时从哪个系统、页面、报表或文件获取?需要哪些内容、多久更新?多个来源不一致时以谁为准?',{large:true,full:true,required:true})}{field('dataContact','由谁提供数据','提供人、部门及联系方式',{full:true,required:true,max:300})}</>}
{!f.noData&&<>{field('dataSource','数据来自哪里','平时从哪个系统、页面、报表或文件获取?需要哪些内容、多久更新?多个来源不一致时以谁为准?',{large:true,full:true,required:true,actions:<TemplateActions documentId="data-source" disabled={busy} onPreview={openPreview}/>})}{field('dataContact','由谁提供数据','提供人、部门及联系方式',{full:true,required:true,max:300})}</>}
{field('risk','依赖与风险','需要哪些系统或人员配合?有无风险及应对方式?无则填“无”。',{large:true,full:true,required:true})}
{field('pending','待确认事项','待确认问题 + 责任人 + 计划确认时间;无则填“无”。',{large:true,full:true,required:true})}
{field('version','需求文档版本','例如:v1.0',{required:true})}
{field('references','参考材料与链接','可填写 PRD、原型、截图或业务规则的受限共享链接,每行一条。',{large:true,full:true,max:5000,hint:'复杂需求请关联独立 PRD;账号密码等敏感信息通过约定受限渠道提供。'})}
<AttachmentPicker files={attachments} onChange={changeAttachments} disabled={saving} uploading={uploading} onUploadingChange={setUploading} onNewUpload={file=>newUploads.current.add(file.id)}/>
</>}
</div></div></div>
<footer className="modal-footer"><div className="footer-left">{(!initial||initial.status==='草稿'||initial.demo)&&<button className="btn" onClick={()=>save('draft')} disabled={busy}><Save size={16}/>保存草稿</button>}{step>0&&<button className="text-button back-button" onClick={()=>setStep(step-1)} disabled={busy}><ArrowLeft size={15}/>上一步</button>}</div><div className="footer-right">{step>=1&&<button className="btn" onClick={()=>save('register')} disabled={busy}>{busy?'保存中…':'先登记,稍后补充'}</button>}{step<3?<button className="btn primary" onClick={()=>setStep(step+1)} disabled={busy}>下一步<ArrowRight size={16}/></button>:<button className="btn primary" onClick={()=>save('review')} disabled={busy}><Send size={16}/>{busy?'提交中…':'提交评审'}</button>}</div></footer>
</fieldset></div></div>
<footer className="modal-footer"><div className="footer-left">{(!initial||initial.status==='草稿')&&<button className="btn" onClick={()=>save('draft')} disabled={busy}><Save size={16}/>保存草稿</button>}{step>0&&<button className="text-button back-button" onClick={()=>setStep(step-1)} disabled={busy}><ArrowLeft size={15}/>上一步</button>}</div><div className="footer-right">{step>=1&&<button className="btn" onClick={()=>save('register')} disabled={busy}>{uploading?'附件上传中…':saving?'保存中…':'先登记,稍后补充'}</button>}{step<3?<button className="btn primary" onClick={()=>setStep(step+1)} disabled={busy}>下一步<ArrowRight size={16}/></button>:<button className="btn primary" onClick={()=>save('review')} disabled={busy}><Send size={16}/>{uploading?'附件上传中…':saving?'提交中…':'提交评审'}</button>}</div></footer>
</DialogContent></Dialog>
{templateId&&<TemplatePreview documentId={templateId} onClose={closePreview} returnFocus={templateTrigger}/>}
<AlertDialog open={exit} onOpenChange={open=>{if(!busy)setExit(open)}}>
<AlertDialogContent className="form-close-confirm" onEscapeKeyDown={e=>{if(busy)e.preventDefault()}} onCloseAutoFocus={e=>{e.preventDefault();const target=returnFocus.current?.isConnected?returnFocus.current:closeButton.current;target?.focus({preventScroll:true})}}>
<AlertDialogTitle>放弃未保存的修改?</AlertDialogTitle>
<AlertDialogDescription>关闭后,本次未保存的修改和本窗口新上传的附件将被清理。找回或已保存的附件会保留。你可以返回继续填写并保存。</AlertDialogDescription>
<div className="form-close-actions">
<AlertDialogCancel className="btn" disabled={busy}>继续填写</AlertDialogCancel>
<AlertDialogAction className="btn danger-button" onClick={()=>{if(!busy)closeForm()}} disabled={busy}>放弃修改并关闭</AlertDialogAction>
</div>
</AlertDialogContent>
</AlertDialog></>
}