cmvr-wms/mobile-app/src/App.tsx
lixiaolong 95effeeff2 feat(app): 优化移动端应用配置和功能实现
- 添加生产环境服务器地址配置支持内外网切换
- 实现采购列表只看我创建的功能开关
- 更新构建脚本中的默认生产环境API地址
- 优化采购单表格单元格编辑体验改用自动补全组件
- 调整应用更新检查逻辑增强生产环境兼容性
- 修复开发服务器切换时的一些验证问题
- 增强应用启动时的服务地址配置灵活性
2026-10-29 17:27:46 +08:00

144 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {canViewPurchaseQuotes} from './core/purchase-quote-permission';
import {Text,ReadingContext,type ReadingSize} from './typography';
import {usePackageUpdates,PackageUpdateDialog,PackageUpdateStatus} from './PackageUpdates';
import {LoginView} from './screens/LoginView';
import {BusinessList} from './screens/BusinessList';
import {FileLibrary} from './screens/FileLibrary';
import {ArrivalHistory} from './screens/ArrivalHistory';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ActivityIndicator, AppState, BackHandler, FlatList, Image, KeyboardAvoidingView, Modal, Platform,
Keyboard, Pressable, ScrollView, View } from 'react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import Constants from 'expo-constants';
import * as SecureStore from 'expo-secure-store';
import * as Crypto from 'expo-crypto';
import { StatusBar } from 'expo-status-bar';
import { ApiClient, allows, internalUrl, productionServer, PRODUCTION_PUBLIC_URL, PRODUCTION_INTERNAL_URL } from './core/network';
import { AppUpdateDialog, useAppUpdates, type AppUpdateControls } from './AppUpdates';
import { modules, display, recordDisplay, routeComponents, validDate, type Module, type Row, localDate } from './core/modules';
import { AppearanceContext, Button, Card, Choice, Field, Heading, Icon, Note, s, useTheme, type Appearance, type IconName } from './ui';
import { Assistant } from './screens/Assistant';
import { ArrivalOperation } from './screens/ArrivalOperation';
import { ArrivalActions } from './screens/ArrivalActions';
import { ArrivalListTools, ArrivalCard } from './screens/ArrivalListParts';
import { arrivalListQuery } from './core/arrival-list';
import { Workspace, BusinessHub, Me, Settings } from './screens/Workspace';
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 || {};
const variant=String(config.environment || 'dev');
const nativeBase=variant==='prod'?productionServer(String(config.apiUrl || PRODUCTION_PUBLIC_URL)):internalUrl(String(config.apiUrl || 'http://127.0.0.1:8080'),true);
const base=Platform.OS==='web'?`${globalThis.location.origin}/native-api`:nativeBase;
type User={user:Row; roles?:string[]; permissions:string[]; pages?:string[];pwdChrtype?:string};
const preferences={get:async(key:string)=>Platform.OS==='web'?localStorage.getItem(key):SecureStore.getItemAsync(key),
put:async(key:string,value:string)=>{if(Platform.OS==='web')localStorage.setItem(key,value);else await SecureStore.setItemAsync(key,value);}};
export default function App(){
const updates=useAppUpdates();
const [mode,setMode]=useState<Appearance>('system');
const [reading,setReading]=useState<ReadingSize>('compact');
useEffect(()=>{void preferences.get('cmvr.reading-size').then(value=>{if(['compact','standard','large'].includes(value||''))setReading(value as ReadingSize);}).catch(()=>{});},[]);
const changeReading=useCallback((value:ReadingSize)=>{setReading(value);void preferences.put('cmvr.reading-size',value).catch(()=>{});},[]);
const [server,setServer]=useState<string|null>(null);
useEffect(()=>{let alive=true;const key=variant==='dev'?developmentServerKey:'cmvr.prod.connection';void preferences.get(key).then(value=>{if(!alive)return;try{setServer(value?(variant==='dev'?developmentServer(value):productionServer(value)):nativeBase);}catch{setServer(nativeBase);}}).catch(()=>{if(alive)setServer(nativeBase);});return()=>{alive=false;};},[]);
const saveServer=useCallback(async(value:string)=>{await preferences.put(variant==='dev'?developmentServerKey:'cmvr.prod.connection',value);setServer(value);},[]);
useEffect(()=>{void (Platform.OS==='web'?Promise.resolve(localStorage.getItem('cmvr.appearance')):SecureStore.getItemAsync('cmvr.appearance')).then(value=>{if(['system','light','dark'].includes(value||''))setMode(value as Appearance);}).catch(()=>{});},[]);
const change=useCallback((value:Appearance)=>{setMode(value);if(Platform.OS==='web')try{localStorage.setItem('cmvr.appearance',value);}catch{}else void SecureStore.setItemAsync('cmvr.appearance',value).catch(()=>{});},[]);
return <SafeAreaProvider><ReadingContext.Provider value={{size:reading,setSize:changeReading}}><AppearanceContext.Provider value={{mode,setMode:change}}>{server?<Root key={server} server={server} saveServer={saveServer} updates={updates}/>:<View style={[s.page,s.fill,{justifyContent:'center'}]}><ActivityIndicator/><Note>正在读取开发服务设置…</Note></View>}<PreviewDialogs/></AppearanceContext.Provider></ReadingContext.Provider></SafeAreaProvider>;
}
function Root({server,saveServer,updates}:{server:string;saveServer:(value:string)=>Promise<void>;updates:AppUpdateControls}){
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<User|null>(null),[starting,setStarting]=useState(true);
const [tab,setTab]=useState('home'),[stack,setStack]=useState<{key:string;query:Row}[]>([]),[aiVisited,setAiVisited]=useState(false),[keyboard,setKeyboard]=useState(false);
const [unreadMessages,setUnreadMessages]=useState({count:0,exact:true});const messageSerial=useRef(0);
const entry=stack[stack.length-1],page=entry?.key;
const scope=server+'|'+String(user?.user.userId||'anonymous');
const epoch=useRef(0),leave=useRef<LeaveGuard|null>(null);
const bindLeave=useCallback((guard:LeaveGuard|null)=>{leave.current=guard;},[]);
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(Platform.OS==='web'?base:server,reset),[reset,server]);
const packageUpdates=usePackageUpdates(api,scope,!!user);
const refreshMessages=useCallback(()=>{
const current=epoch.current,id=++messageSerial.current;if(!user){setUnreadMessages({count:0,exact:true});return;}
void Promise.all([api.request<Row>('/system/notifications/unread'),api.request<Row>('/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=variant==='dev'?await checkDevelopmentServer(value,Platform.OS==='web'?globalThis.location.origin:undefined):productionServer(value);
if(checked===server)return;
if(user){const confirmed=await new Promise<boolean>(resolve=>Alert.alert(variant==='dev'?'更换开发服务':'切换连接方式','切换后需要重新登录,未提交的表单和对话不会迁移。是否继续?',[{text:'取消',style:'cancel',onPress:()=>resolve(false)},{text:'更换并退出登录',onPress:()=>resolve(true)}]));if(!confirmed)throw new Error('已取消切换,当前服务保持不变。');}
await storage.clear();
if(Platform.OS!=='web')await SecureStore.deleteItemAsync(serverTokenKey(variant,checked));
await saveServer(checked);
epoch.current++;api.clear();
}
const connection=variant==='dev'?<ServerConnection address={server} onSave={changeServer}/>:<ProductionConnection address={server} onSave={changeServer}/>;
const identity=useCallback(async()=>{const [info,routes]=await Promise.all([api.request<User>('/getInfo'),api.request<Row>('/getRouters')]);return {...info,pages:routeComponents(routes.data||[])};},[api]);
useEffect(()=>{let alive=true;const current=epoch.current;
void storage.get().then(async token=>{if(!alive||!token)return;api.authenticate(token);try{const data=await identity();if(alive&&epoch.current===current)setUser(data);}catch{api.clear();await storage.clear();}})
.catch(()=>{}).finally(()=>{if(alive)setStarting(false);});return()=>{alive=false;};},[api,identity]);
const back=useCallback(()=>{const proceed=()=>{Keyboard.dismiss();setStack(old=>old.slice(0,-1));};if(leave.current)leave.current(proceed);else proceed();},[]);
useEffect(()=>{const sub=BackHandler.addEventListener('hardwareBackPress',()=>{if(page){back();return true;}if(tab!=='home'){setTab('home');return true;}return false;});return()=>sub.remove();},[page,tab,back]);
useEffect(()=>{const show=Keyboard.addListener('keyboardDidShow',()=>setKeyboard(true)),hide=Keyboard.addListener('keyboardDidHide',()=>setKeyboard(false));return()=>{show.remove();hide.remove();};},[]);
function open(name:string,query:Row={}){const proceed=()=>{Keyboard.dismiss();setStack(old=>[...old,{key:name,query}]);};if(leave.current)leave.current(proceed);else proceed();}
function go(name:string){Keyboard.dismiss();if(name==='assistant')setAiVisited(true);setTab(name);}
function logout(){Alert.alert('退出登录','确认退出当前账号?未发送的对话内容不会保留。',[{text:'取消',style:'cancel'},{text:'退出',style:'destructive',onPress:()=>{void api.request('/logout',{method:'POST'}).catch(()=>{});api.clear();reset();}}]);}
async function login(token:string){const current=epoch.current;api.authenticate(token);try{const data=await identity();
if(current!==epoch.current)return;await storage.put(token);if(current===epoch.current)setUser(data);}catch(error){api.clear();await storage.clear();throw error;}}
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<string,string>={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 <SafeAreaView style={[s.fill,{backgroundColor:!user?'#06152b':t.bg,width:'100%',alignSelf:'center',...(Platform.OS==='web'?{maxWidth:480}:{})}]}><StatusBar style={!user||t.bg==='#101722'?'light':'dark'}/>
{starting?<View style={[s.page,{flex:1,justifyContent:'center'}]}><ActivityIndicator/><Heading>正在连接你的工作空间</Heading><Note>正在恢复登录并核对当前账号信息,请稍候。</Note></View>:
!user?<Login api={api} onLogin={login} server={server} connection={connection}/>:<>
<View style={{paddingHorizontal:12,paddingVertical:7,minHeight:56,backgroundColor:t.bg,flexDirection:'row',alignItems:'center',gap:8}}>
{page&&<Pressable accessibilityRole="button" accessibilityLabel="返回上一页" onPress={back} style={{padding:12}}><Icon name="chevron-back" color={t.text}/></Pressable>}
<Text style={{flex:1,minWidth:0,fontSize:18,lineHeight:25,fontWeight:'700',color:t.text,paddingLeft:page?0:8}}>{selected?.title||titles[page||tab]}</Text>
{!!selected?.guide&&<Pressable accessibilityRole="button" accessibilityLabel={selected.title+'操作指引'} onPress={()=>Alert.alert(selected.title+' · 操作指引',selected.guide)} style={{padding:10}}><Icon name="alert-circle-outline" size={21} color={t.muted}/></Pressable>}
{page!=='messages'&&<Pressable accessibilityRole="button" accessibilityLabel="消息中心" onPress={()=>open('messages')} style={{padding:10,position:'relative'}}><Icon name="notifications-outline" color={t.text}/>{!!messageBadge(unreadMessages.count,unreadMessages.exact)&&<View style={{position:'absolute',top:0,right:0,borderRadius:10,paddingHorizontal:4,minWidth:17,backgroundColor:'#dc5b66'}}><Text style={{fontSize:10,lineHeight:17,textAlign:'center',color:'#fff'}}>{messageBadge(unreadMessages.count,unreadMessages.exact)}</Text></View>}</Pressable>}
{!page&&<View style={{borderRadius:12,backgroundColor:t.soft,paddingHorizontal:10,paddingVertical:5}}><Text style={{color:t.accent,fontSize:12,lineHeight:18}}>{variant==='prod'?'正式环境':'开发环境'}</Text></View>}
</View>
<View style={s.fill}>
{!page&&tab==='home'&&<Workspace api={api} scope={scope} user={user.user} modules={permitted} open={open} go={go} ai={ai}/>}
{!page&&tab==='business'&&<BusinessHub modules={permitted} open={open}/>}
{!page&&tab==='me'&&<Me api={api} user={user.user} open={open}/>}
{page==='messages'&&<MessageCenter api={api} onRead={refreshMessages}/>}
{aiVisited&&ai&&<View style={[s.fill,{display:!page&&tab==='assistant'?'flex':'none'}]}><Assistant api={api}/></View>}
{selected?.key==='files'?<FileLibrary api={api} scope={scope} permissions={user.permissions}/>:!!selected&&<BusinessList key={page} api={api} scope={scope} module={selected} permissions={user.permissions} canViewQuotes={canViewPurchaseQuotes(user.user.userId,user.roles)} initialQuery={entry?.query} onNavigate={open}/>}
{(page==='profile'||page==='password')&&<Account key={page} api={api} kind={page} policy={String(user.pwdChrtype||'0')} bindLeave={bindLeave} onSaved={profile=>setUser(old=>old?{...old,user:{...old.user,...profile}}:null)}/>}
{(page==='feedback'||page==='feedback-list')&&<Feedback key={page} api={api} mode={page==='feedback'?'create':'list'} bindLeave={bindLeave} open={open}/>}
{(page==='settings'||page==='about')&&<Settings updates={updates} environment={variant} baseUrl={server} connection={connection} packageUpdate={<PackageUpdateStatus control={packageUpdates}/>} logout={logout} about={page==='about'}/>}
</View>
{!page&&!keyboard&&<View accessibilityRole="tablist" style={{flexDirection:'row',backgroundColor:t.card,borderTopWidth:1,borderColor:t.line,paddingTop:6,paddingBottom:5}}>{tabs.map(([key,label,icon])=><Pressable key={key} accessibilityRole="tab" accessibilityLabel={label} accessibilityState={{selected:tab===key}} onPress={()=>go(key)} style={{flex:1,alignItems:'center',justifyContent:'center',minHeight:50,gap:3}}><View style={{paddingHorizontal:17,paddingVertical:4,borderRadius:18,backgroundColor:tab===key?t.soft:'transparent'}}><Icon name={icon} size={21} color={tab===key?t.accent:t.muted}/></View><Text style={{fontSize:12,lineHeight:18,color:tab===key?t.accent:t.muted,fontWeight:tab===key?'700':'400'}}>{label}</Text></Pressable>)}</View>}
</>}
<PackageUpdateDialog control={packageUpdates}/>{!packageUpdates.visible&&<AppUpdateDialog {...updates}/>}
</SafeAreaView>;
}
function ProductionConnection({address,onSave}:{address:string;onSave:(value:string)=>Promise<void>}){
const [busy,setBusy]=useState(false),[error,setError]=useState('');
async function select(value:string){if(busy||value===address)return;setBusy(true);setError('');try{await onSave(value);}catch(e){setError((e as Error).message);}finally{setBusy(false);}}
return <Card><Heading>连接方式</Heading><Note>切换后需重新登录,未提交内容不会迁移。</Note><View style={s.row}><Button title="外网" secondary={address!==PRODUCTION_PUBLIC_URL} disabled={busy} onPress={()=>void select(PRODUCTION_PUBLIC_URL)}/><Button title="公司内网" secondary={address!==PRODUCTION_INTERNAL_URL} disabled={busy} onPress={()=>void select(PRODUCTION_INTERNAL_URL)}/></View>{!!error&&<Note>{error}</Note>}</Card>;
}
function Login({api,onLogin,server,connection}:{api:ApiClient;onLogin:(token:string)=>Promise<void>;server:string;connection?:React.ReactNode}){
const [username,setUsername]=useState(''),[password,setPassword]=useState(''),[code,setCode]=useState('');
const [captcha,setCaptcha]=useState<Row|null>(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[connecting,setConnecting]=useState(true);
const lock=useRef(false),seq=useRef(0);
const refresh=useCallback(async()=>{const current=++seq.current;setConnecting(true);setCaptcha(null);setError('');try{let data:Row;try{data=await api.request<Row>('/captchaImage',{anonymous:true});}catch(e){if((e as {code?:number}).code!==409)throw e;data=await api.request<Row>('/captchaImage',{anonymous:true});}if(current===seq.current){setCaptcha(data);setCode('');}}catch(e){if(current===seq.current)setError((e as Error).message);}finally{if(current===seq.current)setConnecting(false);}},[api]);
useEffect(()=>{void refresh();return()=>{seq.current++;};},[refresh]);
async function submit(){if(lock.current)return;if(!captcha){setError('请先连接服务获取登录信息。');return;}
if(!username.trim()||!password||captcha.captchaEnabled!==false&&!code.trim()){setError('请填写账号、密码和验证码。');return;}
lock.current=true;setBusy(true);setError('');try{const data=await api.request<Row>('/login',{method:'POST',anonymous:true,body:{username:username.trim(),password,code,uuid:captcha.uuid}});await onLogin(data.token);setPassword('');}
catch(e){await refresh();setError((e as Error).message);}finally{lock.current=false;setBusy(false);}}
return <LoginView environment={variant} username={username} password={password} code={code} captcha={captcha} busy={busy} connecting={connecting} error={error} server={server} connection={connection} setUsername={setUsername} setPassword={setPassword} setCode={setCode} refresh={()=>void refresh()} submit={()=>void submit()}/>;
}