2026-09-16 14:46:32 +08:00
'use client' ;
2026-11-25 12:40:33 +08:00
import { appPath } from '@/lib/base-path' ;
2026-09-16 14:46:32 +08:00
import { useState , useEffect , useRef , useCallback } from 'react' ;
2026-11-25 12:40:33 +08:00
import { House , Files , SquareCheck , Folder , BookOpen , CalendarDays , ChevronRight , UserRound , CheckCircle2 , CircleAlert , RotateCw , LogOut , KeyRound , UsersRound , ClipboardList } from 'lucide-react' ;
import { DropdownMenu , DropdownMenuTrigger , DropdownMenuContent , DropdownMenuItem , DropdownMenuLabel , DropdownMenuSeparator } from '@/components/ui/dropdown-menu' ;
2026-09-16 14:46:32 +08:00
import { Dashboard } from './dashboard' ;
import { DemandForm , type SaveInput } from './form' ;
import { DemandDetail } from './detail' ;
import { Guide } from './guide' ;
2026-11-25 12:40:33 +08:00
import { type Demand , needsAction , isMyDemand } from '@/lib/demand' ;
import { mergeDemandSnapshot , type SavedDemandWrite } from '@/lib/demand-snapshot' ;
2026-09-16 14:46:32 +08:00
const navItems = [{ icon :House , label : '我的工作台' },{ icon :Files , label : '我的需求' },{ icon :SquareCheck , label : '待我处理' },{ icon :Folder , label : '草稿箱' }];
2026-11-25 12:40:33 +08:00
export default function DemandApp ({ userName , role , today , initialDemandId = '' , passwordSet = true } : { passwordSet? :boolean ; initialDemandId? :string ; userName :string ; role : 'admin' | 'user' ; today :string }){
const [ signingOut , setSigningOut ] = useState ( false ); const [ view , setView ] = useState ( '我的工作台' ); const [ demands , setDemands ] = useState < Demand [] >([]); const [ loading , setLoading ] = useState ( true ); const [ loadError , setLoadError ] = useState ( '' ); const [ actionError , setActionError ] = useState ( '' ); const [ busy , setBusy ] = useState ( false ); const [ toast , setToast ] = useState ( '' ); const [ selected , setSelected ] = useState < Demand | null >( null ); const [ form , setForm ] = useState < { initial? :Demand } | null > ( null ); const [ dashboardKey , setDashboardKey ] = useState ( 0 );
const [ detailTab , setDetailTab ] = useState < string | undefined >();
const personalDemands = demands . filter ( isMyDemand );
const dashboardDemands = view === '全部需求' && role === 'admin' ? demands . filter ( d => d . status !== '草稿' ) : personalDemands ;
const navigation = role === 'admin' ? [... navItems . slice ( 0 , 2 ),{ icon :ClipboardList , label : '全部需求' },... navItems . slice ( 2 )] : navItems ;
const initialDemand = useRef ( initialDemandId );
const latest = useRef ( demands ); useEffect (() => { latest . current = demands },[ demands ]);
const mounted = useRef ( false ); const loadSequence = useRef ( 0 ); const loadController = useRef < AbortController | null >( null );
const writeVersion = useRef ( 0 ); const savedWrites = useRef ( new Map < string , SavedDemandWrite >());
const load = useCallback (() => {
const sequence =++ loadSequence . current ; const startedAtVersion = writeVersion . current ;
loadController . current ? . abort (); const controller = new AbortController (); loadController . current = controller ;
const current = () => mounted . current && sequence === loadSequence . current &&! controller . signal . aborted ;
return fetch ( appPath ( '/api/demands' ),{ cache : 'no-store' , signal :controller.signal })
. then ( async response => { const data = await response . json () as { error? :string ; demands :Demand []}; if ( ! response . ok ) throw new Error ( data . error || '无法加载需求,请重试。' ); return data . demands ;})
. then ( snapshot => { if ( ! current ()) return ; setDemands ( mergeDemandSnapshot ( snapshot , savedWrites . current . values (), startedAtVersion )); setLoadError ( '' );
if ( initialDemand . current ){ const requested = snapshot . find ( d => d . id === initialDemand . current ); initialDemand . current = '' ; if ( requested ){ setSelected ( requested ); setDetailTab ( undefined );} else setLoadError ( '找不到通知对应的需求,或当前账号没有查看权限。' );}
for ( const [ id , write ] of savedWrites . current ){ if ( write . version <= startedAtVersion ) savedWrites . current . delete ( id );}
})
. catch ( error => { if ( current ()) setLoadError ( error instanceof Error ? error . message : '无法加载需求,请重试。' );})
. finally (() => { if ( current ()){ setLoading ( false ); loadController . current = null ;}});
},[]);
function reload (){ setLoading ( true ); setLoadError ( '' ); void load ();}
useEffect (() => { mounted . current = true ; void load (); return () => { mounted . current = false ; loadController . current ? . abort ();};},[ load ]);
2026-09-16 14:46:32 +08:00
useEffect (() => { if ( ! toast ) return ; const t = setTimeout (() => setToast ( '' ), 4500 ); return () => clearTimeout ( t )},[ toast ]);
2026-11-25 12:40:33 +08:00
useEffect (() => { const mc = ( document as unknown as { modelContext ?: { registerTool : ( tool :unknown , options :unknown ) => Promise < void > | void }}). modelContext ; if ( ! mc ? . registerTool ) return ; const lifecycle = new AbortController (); const tools = [{ name : 'search_demands' , title : '搜索当前工作空间需求' , description : 'Read saved demands currently visible in this workspace. Does not change records.' , inputSchema : { type : 'object' , properties : { query : { type : 'string' }}, required : [ 'query' ], additionalProperties :false }, annotations : { readOnlyHint :true , untrustedContentHint :true }, execute ( input :unknown ){ if ( ! input || typeof ( input as { query :unknown }). query !== 'string' ) throw new Error ( 'query must be a string' ); const query = ( input as { query :string }). query . toLowerCase (); return latest . current . filter ( d => ( d . id + d . fields . title ). toLowerCase (). includes ( query )). map ( d => ({ id :d.id , title :d.fields.title , status :d.status }));}},{ name : 'start_demand_registration' , title : '打开需求登记表' , description : 'Open the registration form. This does not save or submit a demand.' , inputSchema : { type : 'object' , properties : {}, additionalProperties :false }, annotations : { readOnlyHint :false , untrustedContentHint :false }, execute ( input :unknown ){ if ( ! input || typeof input !== 'object' || Object . keys ( input ). length ) throw new Error ( 'Expected an empty object' ); setActionError ( '' ); setForm ({}); return { opened :true , saved :false };}}]; for ( const tool of tools ){ try { Promise . resolve ( mc . registerTool ( tool ,{ signal :lifecycle.signal })). catch (() => {})} catch {}} return () => lifecycle . abort ()},[]);
2026-09-16 14:46:32 +08:00
function navigate ( v :string ){ setView ( v ); setDashboardKey ( k => k + 1 ); setSelected ( null ); setActionError ( '' )}
2026-11-25 12:40:33 +08:00
function startNew (){ setActionError ( '' ); setDetailTab ( undefined ); setForm ({})}
async function signOut (){ setSigningOut ( true ); try { const response = await fetch ( appPath ( '/api/auth/logout' ),{ method : 'POST' }); if ( ! response . ok ) throw new Error ( '退出登录失败,请重试。' ); window . location . assign ( appPath ( '/login' ));} catch ( e ){ setLoadError ( e instanceof Error ? e . message : '退出登录失败。' ); setSigningOut ( false )}}
async function save ( body :SaveInput ){ setBusy ( true ); setActionError ( '' ); try { const response = await fetch ( appPath ( '/api/demands' ),{ method : 'POST' , headers : { 'Content-Type' : 'application/json' }, body :JSON.stringify ( body )}); const data = await response . json () as { error? :string ; demand :Demand }; if ( ! response . ok ) throw new Error ( data . error || '保存失败,请稍后重试。' ); if ( ! mounted . current ) return ; const updated = data . demand as Demand ; savedWrites . current . set ( updated . id ,{ version :++ writeVersion . current , demand :updated }); setDemands ( prev => [ updated ,... prev . filter ( d => d . id !== updated . id )]); setForm ( null ); setSelected ( updated ); setToast ( body . action === 'take-over-development' ? '已接手开发职责,请重新评审和排期' : body . action === 'assign-developer' ? '开发责任人已指定' : body . action === 'propose-solution' ? '方案已提交,等待业务方确认' : body . action === 'confirm-solution' ? '方案已确认,确认记录已保存' : body . action === 'return-solution' ? '已退回开发责任人修改' : body . mode === 'draft' ? '草稿已保存,可随时继续填写' : body . mode === 'review' ? '需求已提交评审,等待负责人确认' : '需求已保存' ); setView ( updated . status === '草稿' ? '草稿箱' : '我的需求' ); setDashboardKey ( k => k + 1 ); return ;} catch ( e ){ if ( mounted . current ) setActionError ( e instanceof Error ? e . message : '保存失败,请重试。' ); throw e ;} finally { if ( mounted . current ) setBusy ( false )}}
async function action ( body :SaveInput ){ if ( ! selected ) return ; await save ( body )}
return < div className = "app-shell" >{ loading && < div className = "loading-bar" role = "progressbar" aria-label = "正在加载需求" />}< aside className = { 'sidebar' + ( role === 'admin' ? ' admin-navigation' : '' )}>< div className = "brand" >< div className = "brand-mark" >< i />< i />< i />< i /></ div >< div >< strong > 需有序 </ strong >< span > 需求协作平台 </ span ></ div ></ div >< nav aria-label = "主导航" >{ navigation . map (({ icon :Icon , label }) => < button key = { label } title = { label } aria-label = { label } className = { view === label ? 'active' : '' } onClick = {() => navigate ( label )}>< Icon size = { 21 }/>< span >{ label }</ span >{ label === '待我处理' && personalDemands . filter ( needsAction ). length > 0 && < b className = "nav-count alert" >{ personalDemands . filter ( needsAction ). length }</ b >}{ label === '草稿箱' && personalDemands . filter ( d => d . status === '草稿' ). length > 0 && < b className = "nav-count" >{ personalDemands . filter ( d => d . status === '草稿' ). length }</ b >}</ button >)}</ nav >< div className = "sidebar-bottom" >< button className = { 'guide-nav ' + ( view === '流程与规范' ? 'guide-active' : '' )} onClick = {() => navigate ( '流程与规范' )}>< BookOpen size = { 21 }/> 流程与规范 </ button >< div className = "profile" title = { userName }>< span className = "avatar" >< UserRound size = { 21 }/></ span >< strong >{ userName }</ strong >< span className = "profile-label" >{ role === 'admin' ? '管理员' : '成员' }</ span ></ div ></ div ></ aside >< div className = "main-shell" >< header className = "topbar" >< span > 工作空间 < ChevronRight size = { 14 }/>< strong >{ view }</ strong ></ span >< div className = "topbar-right" >< span className = "top-date" >< CalendarDays size = { 17 }/>{ today }</ span >< DropdownMenu >< DropdownMenuTrigger asChild >< button className = "account-trigger" aria-label = "账号菜单" >< UserRound size = { 18 }/>< span >{ userName }</ span ></ button ></ DropdownMenuTrigger >< DropdownMenuContent className = "account-dropdown" align = "end" >< DropdownMenuLabel >{ userName }< small >{ role === 'admin' ? '系统管理员' : '协作成员' }</ small ></ DropdownMenuLabel >< DropdownMenuSeparator />{ role === 'admin' && < DropdownMenuItem asChild >< a href = { appPath ( '/admin/users' )}>< UsersRound size = { 16 }/> 账号管理 </ a ></ DropdownMenuItem >}{ role === 'admin' && < DropdownMenuItem asChild >< a href = { appPath ( '/admin/feishu' )}>< UsersRound size = { 16 }/> 飞书集成 </ a ></ DropdownMenuItem >}< DropdownMenuItem asChild >< a href = { appPath ( '/account/feishu' )}>< UserRound size = { 16 }/> 飞书绑定 </ a ></ DropdownMenuItem >< DropdownMenuItem asChild >< a href = { appPath ( '/account/password' )}>< KeyRound size = { 16 }/>{ passwordSet ? '修改密码' : '设置密码' }</ a ></ DropdownMenuItem >< DropdownMenuSeparator />< DropdownMenuItem disabled = { signingOut } onClick = { signOut }>< LogOut size = { 16 }/>{ signingOut ? '正在退出…' : '退出登录' }</ DropdownMenuItem ></ DropdownMenuContent ></ DropdownMenu ></ div ></ header >< main >
{ loadError && < div className = "error-banner page-error" role = "alert" >< CircleAlert size = { 18 }/>< span >{ loadError }</ span >< button className = "text-button" onClick = { reload } disabled = { loading }>< RotateCw size = { 14 }/> 重新加载 </ button ></ div >}
{ view === '流程与规范' ? < Guide onNew = { startNew }/> : < Dashboard key = { dashboardKey } demands = { dashboardDemands } view = { view } onView = { setView } onOpen = { d => { setSelected ( d ); setDetailTab ( undefined ); setActionError ( '' )}} onNew = { startNew } onGuide = {() => navigate ( '流程与规范' )} onRefresh = { reload } loading = { loading } unavailable = { Boolean ( loadError )}/>}
2026-09-16 14:46:32 +08:00
</ main ></ div >
2026-11-25 12:40:33 +08:00
{ selected &&! form && < DemandDetail key = { selected . id + '-' + selected . revision } d = { selected } initialTab = { detailTab } onTabChange = { setDetailTab } onClose = {() => setSelected ( null )} onEdit = { d => { setForm ({ initial :d }); setActionError ( '' )}} onAction = { action } busy = { busy } error = { actionError }/>}
{ form && < DemandForm initial = { form . initial } onSave = { async body => { try { await save ( body )} catch {}}} onClose = {() => setForm ( null )} busy = { busy } error = { actionError } userName = { userName } existing = { personalDemands . filter ( d => d . access ? . business ?? true )}/>}
2026-09-16 14:46:32 +08:00
{ toast && < div className = "toast" role = "status" >< CheckCircle2 size = { 18 }/>{ toast }</ div >}
</ div >;
}