diff --git a/mobile-app/src/App.tsx b/mobile-app/src/App.tsx index 4fad015..ed73b14 100644 --- a/mobile-app/src/App.tsx +++ b/mobile-app/src/App.tsx @@ -1,5 +1,5 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { ActivityIndicator, BackHandler, FlatList, Image, KeyboardAvoidingView, Modal, Platform, +import { ActivityIndicator, AppState, BackHandler, FlatList, Image, KeyboardAvoidingView, Modal, Platform, Keyboard, Pressable, ScrollView, Text, View } from 'react-native'; import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'; import Constants from 'expo-constants'; @@ -18,6 +18,8 @@ import { Account, type LeaveGuard } from './screens/Account'; import { Feedback } from './screens/Feedback'; import { Dialog as Alert, PreviewDialogs } from './dialogs'; import {ServerConnection} from './screens/ServerConnection'; +import {MessageCenter} from './screens/MessageCenter'; +import {messageBadge} from './core/message-center'; import {developmentServerKey,developmentServer,serverTokenKey,connectionClient,checkDevelopmentServer} from './core/server-address'; const config=Constants.expoConfig?.extra || {}; @@ -40,11 +42,19 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom const storage=useMemo(()=>{const key=serverTokenKey(variant,server);return {get:()=>Platform.OS==='web'?Promise.resolve(null):SecureStore.getItemAsync(key),put:(token:string)=>Platform.OS==='web'?Promise.resolve():SecureStore.setItemAsync(key,token),clear:()=>Platform.OS==='web'?Promise.resolve():SecureStore.deleteItemAsync(key)};},[server]); const t=useTheme(); const [user,setUser]=useState(null),[starting,setStarting]=useState(true); const [tab,setTab]=useState('home'),[stack,setStack]=useState([]),[aiVisited,setAiVisited]=useState(false),[keyboard,setKeyboard]=useState(false),[update,setUpdate]=useState('disabled'); + const [unreadMessages,setUnreadMessages]=useState({count:0,exact:true});const messageSerial=useRef(0); const page=stack[stack.length-1]; const epoch=useRef(0),leave=useRef(null); const bindLeave=useCallback((guard:LeaveGuard|null)=>{leave.current=guard;},[]); - const reset=useCallback(()=>{epoch.current++;setUser(null);setTab('home');setStack([]);setAiVisited(false);leave.current=null;void storage.clear();},[storage]); + const reset=useCallback(()=>{epoch.current++;messageSerial.current++;setUnreadMessages({count:0,exact:true});setUser(null);setTab('home');setStack([]);setAiVisited(false);leave.current=null;void storage.clear();},[storage]); const api=useMemo(()=>variant==='dev'?connectionClient(server,reset,Platform.OS==='web'?globalThis.location.origin:undefined):new ApiClient(base,reset),[reset,server]); + const refreshMessages=useCallback(()=>{ + const current=epoch.current,id=++messageSerial.current;if(!user){setUnreadMessages({count:0,exact:true});return;} + void Promise.all([api.request('/system/notifications/unread'),api.request('/system/notice/listTop')]).then(([inbox,notices])=>{ + if(current===epoch.current&&id===messageSerial.current)setUnreadMessages({count:Math.max(0,Number(inbox.data?.count)||0)+(notices.data||[]).filter((item:Row)=>!item.isRead).length,exact:inbox.data?.exact!==false}); + }).catch(()=>{}); + },[api,user?.user.userId]); + useEffect(()=>{refreshMessages();const timer=setInterval(()=>{if(AppState.currentState==='active')refreshMessages();},60000),listener=AppState.addEventListener('change',state=>{if(state==='active')refreshMessages();});return()=>{clearInterval(timer);listener.remove();messageSerial.current++;};},[refreshMessages]); useEffect(()=>()=>{epoch.current++;api.clear();},[api]); async function changeServer(value:string){ const checked=await checkDevelopmentServer(value,Platform.OS==='web'?globalThis.location.origin:undefined); @@ -73,7 +83,7 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom const permitted=modules.filter(m=>allows(user?.permissions||[],...m.permissions)&&(!m.pages||m.pages.some(p=>user?.pages?.includes(p)))); const selected=permitted.find(m=>m.key===page); const ai=allows(user?.permissions||[],['ai:assistant:use']); - const titles:Record={home:'工作台',business:'业务中心',assistant:'AI 助手',me:'我的',profile:'个人资料',password:'账号与密码',feedback:'问题与建议','feedback-list':'我的反馈',settings:'设置',about:'关于应用'}; + const titles:Record={home:'工作台',business:'业务中心',assistant:'AI 助手',me:'我的',messages:'消息中心',profile:'个人资料',password:'账号与密码',feedback:'问题与建议','feedback-list':'我的反馈',settings:'设置',about:'关于应用'}; const tabs:[string,string,IconName][]=[['home','工作台','grid-outline'],['business','业务','layers-outline'],...(ai?[['assistant','AI','sparkles-outline'] as [string,string,IconName]]:[]),['me','我的','person-outline']]; return {starting?正在连接你的工作空间正在恢复登录并核对当前账号信息,请稍候。: @@ -82,12 +92,14 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom {page&&} {selected?.title||titles[page||tab]} {!!selected?.guide&&Alert.alert(selected.title+' · 操作指引',selected.guide)} style={{padding:10}}>} + {page!=='messages'&&open('messages')} style={{padding:10,position:'relative'}}>{!!messageBadge(unreadMessages.count,unreadMessages.exact)&&{messageBadge(unreadMessages.count,unreadMessages.exact)}}} {!page&&{variant==='prod'?'内网工作空间':'开发环境'}} {!page&&tab==='home'&&} {!page&&tab==='business'&&} {!page&&tab==='me'&&} + {page==='messages'&&} {aiVisited&&ai&&} {!!selected&&} {(page==='profile'||page==='password')&&setUser(old=>old?{...old,user:{...old.user,...profile}}:null)}/>} diff --git a/mobile-app/src/core/message-center.ts b/mobile-app/src/core/message-center.ts new file mode 100644 index 0000000..9168e52 --- /dev/null +++ b/mobile-app/src/core/message-center.ts @@ -0,0 +1,55 @@ +import type {ApiClient} from './network'; +import type {Row} from './modules'; + +export type MessageTab='inbox'|'notices'; +export type MessageState={tab:MessageTab;items:Row[];notices:Row[];detail:Row|null;busy:boolean;reading:boolean;error:string;hasMore:boolean;cursor:string|null;unreadOnly:boolean}; +export const initialMessageState=():MessageState=>({tab:'inbox',items:[],notices:[],detail:null,busy:false,reading:false,error:'',hasMore:false,cursor:null,unreadOnly:false}); +export function messageBadge(count:unknown,exact=true){const n=Math.max(0,Number(count)||0);return n>99?'99+':!exact?(n?n+'+':'…'):n?String(n):'';} +/** Never display raw announcement HTML in native Text or inject it into a WebView. */ +export function announcementText(html:unknown){return String(html||'').replace(/<(script|style|iframe|object)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,'').replace(/<(?:br\s*\/|br|\/p|\/div|\/li|\/h[1-6]|\/tr)>/gi,'\n').replace(/<[^>]*>/g,'').replace(/&(?:nbsp|lt|gt|amp|quot|#39);/g,value=>({' ':' ','<':'<','>':'>','&':'&','"':'"',''':"'"}[value]||value)).trim();} +/** UI controller: bounded manual pagination, stale response protection and explicit read acknowledgements. */ +export function createMessageCenter(api:Pick,changed:(state:MessageState)=>void,onRead=()=>{}){ + let state=initialMessageState(),serial=0,alive=true; + const emit=(patch:Partial)=>{if(alive){state={...state,...patch};changed(state);}}; + const valid=(id:number)=>alive&&id===serial; + const fail=(error:unknown)=>error instanceof Error?error.message:'暂时无法获取消息,请刷新重试。'; + async function load(more=false){ + if(state.reading||more&&(state.busy||!state.hasMore))return; + const id=++serial,tab=state.tab,cursor=more?state.cursor:null; + emit({busy:true,error:'',detail:null,...(!more?{items:[],notices:[],hasMore:false,cursor:null}:{})}); + try{ + if(tab==='notices'){ + const result=await api.request('/system/notice/listTop');if(!valid(id))return;emit({notices:result.data||[]}); + }else{ + const result=await api.request('/system/notifications',{query:{beforeId:cursor,limit:20,unreadOnly:state.unreadOnly}});if(!valid(id))return; + const page=result.data||{},next=page.nextCursor==null?null:String(page.nextCursor); + const advance=next!==null&&/^\d+$/.test(next)&&BigInt(next)>0n&&(cursor===null||BigInt(next)String(item.id))); + emit({items:[...state.items,...(page.items||[]).filter((item:Row)=>!seen.has(String(item.id)))],hasMore:page.hasMore===true&&advance,cursor:advance?next:null,error:page.hasMore&&!advance?'分页位置未更新,请刷新后继续。':''}); + } + }catch(error){if(valid(id))emit({error:fail(error)});}finally{if(valid(id))emit({busy:false});} + } + async function tab(value:MessageTab){if(state.reading)return;emit({tab:value});await load();} + async function filter(value:boolean){if(state.reading)return;emit({unreadOnly:value});await load();} + async function detail(item:Row){ + if(state.reading)return;const id=++serial,kind=state.tab;emit({busy:true,error:'',detail:null}); + try{ + const result=await api.request(kind==='inbox'?'/system/notifications/'+item.id:'/system/notice/'+item.noticeId);if(!valid(id))return; + const data=result.data||{}; + emit({detail:kind==='inbox'?{id:item.id,kind,title:data.title,content:data.content,time:data.deliveredAt,read:!!data.readAt}:{id:item.noticeId,kind,title:data.noticeTitle,content:announcementText(data.noticeContent),time:data.createTime,read:!!item.isRead}}); + }catch(error){if(valid(id))emit({error:fail(error)});}finally{if(valid(id))emit({busy:false});} + } + async function mark(detailOnly=false){ + if(state.reading||state.busy)return; + const kind=state.detail?.kind||state.tab; + const ids=detailOnly&&state.detail?[state.detail.id]:(kind==='inbox'?state.items.filter(item=>!item.readAt).map(item=>item.id):state.notices.filter(item=>!item.isRead).map(item=>item.noticeId)).slice(0,100); + if(!ids.length)return;const id=++serial;emit({reading:true,error:''}); + try{ + if(kind==='inbox')await api.request('/system/notifications/read-batch',{method:'PUT',body:ids}); + else await api.request('/system/notice/markReadAll',{method:'POST',query:{ids:ids.join(',')}}); + if(!valid(id))return;const selected=new Set(ids.map(String)); + emit({items:kind==='inbox'?state.items.map(item=>selected.has(String(item.id))?{...item,readAt:new Date().toISOString()}:item).filter(item=>!state.unreadOnly||!item.readAt):state.items,notices:kind==='notices'?state.notices.map(item=>selected.has(String(item.noticeId))?{...item,isRead:true}:item):state.notices,detail:state.detail&&state.detail.kind===kind&&selected.has(String(state.detail.id))?{...state.detail,read:true}:state.detail});onRead(); + }catch(error){if(valid(id))emit({error:fail(error)});}finally{if(valid(id))emit({reading:false});} + } + return {load,tab,filter,detail,mark,start:()=>{alive=true;serial++;emit(initialMessageState());void load();},back:()=>{if(!state.reading){serial++;emit({detail:null,busy:false,error:''});}},dispose:()=>{alive=false;serial++;},snapshot:()=>state}; +} diff --git a/mobile-app/src/screens/Assistant.tsx b/mobile-app/src/screens/Assistant.tsx index 964616a..9600285 100644 --- a/mobile-app/src/screens/Assistant.tsx +++ b/mobile-app/src/screens/Assistant.tsx @@ -76,7 +76,7 @@ function DraftCard({draft,currentId,busy,onAction,onInspect}:{draft:Row;currentI {expanded&&<> {(draft.errors||[]).map((e:string,j:number)=>{e})} {(draft.rows||[]).slice(0,20).map((row:Row,j:number)=>第 {j+1} 行{(draft.fields||[]).filter((f:Row)=>!f.hidden).map((f:Row)=>{f.label}:{draftFieldText(row,f)})}{draft.action==='purchase.correctPrice'&&(row._quotePreview||[]).map((q:Row,k:number)=>{q.name} · 数量 {q.quantity}报价:{q.previousPrice??'未报价'} → {q.unitPrice};金额:{q.oldAmount??'未计价'} → {q.newAmount}{q.notice})})} - {(draft.rows||[]).flatMap((row:Row)=>row._referencePricePreview||[]).slice(0,20).map((row:Row,index:number)=>{row.name} · {row.spec} · 数量 {row.quantity}实际单价:{row.oldActualPrice??'未填写'} → {row.newActualPrice??'未填写'};实际金额:{row.oldActualAmount??'未填写'} → {row.newActualAmount??'未填写'}{row.notice};不修改报价或成本)} + {(draft.rows||[]).flatMap((row:Row)=>row._referencePricePreview||[]).slice(0,20).map((row:Row,index:number)=>{row.name} · {row.spec} · 数量 {row.quantity}实际单价:{row.oldActualPrice??'未填写'} → {row.newActualPrice??'未填写'};实际金额:{row.oldActualAmount??'未填写'} → {row.newActualAmount??'未填写'}{row.clearQuote&&报价单价:{row.quotePrice??'未报价'} → {row.newQuotePrice??(row.changed?'清空(未报价)':'未报价')};报价金额:{row.oldQuoteAmount??'未报价'} → {row.newQuoteAmount??(row.changed?'清空(未报价)':'未报价')}}{row.notice};{row.clearQuote?'整批提交并同步金额与成本,清空不是0元':'不修改报价或成本'})} {(draft.rows||[]).filter((row:Row)=>row._historyPreview).slice(0,20).map((row:Row,index:number)=>{const h=row._historyPreview;return {h.name} · {h.spec}{(h.changes||[]).map((change:Row)=>{change.label} · 更正前:{change.beforeText??change.before??'未填写'}更正后:{change.afterText??change.after??'未填写'})}实际金额:{h.oldActualAmount??'未填写'} → {h.newActualAmount??'未填写'};报价金额:{h.oldAmount??'未计价'} → {h.newAmount??'未计价'}关联入库 {h.receiptCount||0} 条,成本来源 {h.costSourceCount||0} 条;实际收货数量不变。{h.createItem&&确认后匹配或新建物品档案。}{h.categoryUpdatesArchive&&类别更正会同步物品档案及其引用页面。}{h.priceImpact?.notice&&{h.priceImpact.notice}}{h.oldStatus!==h.newStatus&&采购状态将随需求数量重新核算,请在电脑端核对完整状态。}})} {reviewCount>20&&此确认单超过 20 项,请在电脑端完整核对后办理;App 暂不开放截断确认。} } diff --git a/mobile-app/src/screens/MessageCenter.tsx b/mobile-app/src/screens/MessageCenter.tsx new file mode 100644 index 0000000..34f4d1e --- /dev/null +++ b/mobile-app/src/screens/MessageCenter.tsx @@ -0,0 +1,27 @@ +import React,{useEffect,useMemo,useState} from 'react'; +import {Pressable,ScrollView,Text,View} from 'react-native'; +import {Button,Card,Heading,Icon,Note,s,useTheme} from '../ui'; +import type {ApiClient} from '../core/network'; +import {createMessageCenter,initialMessageState} from '../core/message-center'; + +export function MessageCenter({api,onRead}:{api:ApiClient;onRead:()=>void}){ + const t=useTheme(),[state,setState]=useState(initialMessageState); + const center=useMemo(()=>createMessageCenter(api,setState,onRead),[api,onRead]); + useEffect(()=>{center.start();return()=>center.dispose();},[center]); + const busy=state.busy||state.reading,detail=state.detail,items=state.tab==='inbox'?state.items:state.notices; + const unread=state.tab==='inbox'?state.items.some(item=>!item.readAt):state.notices.some(item=>!item.isRead); + return + {([['inbox','站内消息'],['notices','通知公告']] as const).map(([key,label])=>void center.tab(key)} style={{paddingVertical:12,paddingHorizontal:18,borderRadius:12,backgroundColor:state.tab===key?t.accent:t.soft}}>{label})} + {!!state.error&&{state.error}} + {detail?<> +