refactor(mobile): 重构移动端应用结构和配置

- 将 Account 组件中的 Text 导入移动到顶部
- 移除 App.tsx 中的 expo-updates 相关代码
- 添加 PackageUpdates 相关组件和 hooks
- 更新应用名称从 "CMVR 物资管理" 为 "车研物资"
- 添加应用图标和自适应图标配置
- 更新 Android 权限配置,添加 REQUEST_INSTALL_PACKAGES 权限
- 修改堆栈导航数据结构,支持路由参数传递
- 添加阅读尺寸偏好设置功能
- 重构登录界面为独立组件 LoginView
- 添加文件库界面组件 FileLibrary
- 更新状态栏样式逻辑
- 调整 Tab 栏样式和尺寸
- 集成包更新和应用更新对话框
- 修复导入语句顺序和类型引用
- 优化业务列表组件的路由参数处理
- 添加作用域参数用于 API 请求区分
This commit is contained in:
lixiaolong 2026-10-28 17:30:35 +08:00
parent 6973a391ac
commit d37b4ff379
77 changed files with 880 additions and 433 deletions

View File

@ -3,12 +3,14 @@ module.exports = () => {
const env = environment();
const cleartextHosts = [...new Set([env.apiUrl, env.updateOrigin].filter(url => url.startsWith('http:')).map(url => new URL(url).hostname))];
return {
name: env.variant === 'prod' ? 'CMVR 物资管理' : 'CMVR 物资管理·开发',
name: env.variant === 'prod' ? '车研物资' : '车研物资·开发',
icon: `./assets/brand/app-icon-blue-${env.variant}.png`,
slug: 'cmvr-wms', version: '1.0.0', orientation: 'portrait', userInterfaceStyle: 'automatic',
platforms: ['android', 'web'],
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 2 : 1,
permissions: [], blockedPermissions: ['android.permission.RECORD_AUDIO'] },
plugins: ['expo-secure-store', 'expo-status-bar', './plugins/with-short-cmake-paths.cjs', './plugins/with-private-build-inputs.cjs', ['./plugins/with-internal-network.cjs', { hosts: cleartextHosts }],
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 5 : 3,
adaptiveIcon: { foregroundImage: `./assets/brand/app-icon-blue-${env.variant}-adaptive.png`, backgroundColor: '#ffffff' },
permissions: ['android.permission.REQUEST_INSTALL_PACKAGES'], blockedPermissions: ['android.permission.RECORD_AUDIO'] },
plugins: ['./plugins/with-apk-installer.cjs', 'expo-sharing', 'expo-secure-store', 'expo-status-bar', './plugins/with-short-cmake-paths.cjs', './plugins/with-private-build-inputs.cjs', ['./plugins/with-internal-network.cjs', { hosts: cleartextHosts }],
...(env.variant === 'prod' ? ['./plugins/with-release-signing.cjs'] : [])],
runtimeVersion: { policy: 'fingerprint' },
updates: { enabled: env.updatesEnabled, url: `${env.updateOrigin}/updates/${env.variant}`,

View File

@ -9,16 +9,21 @@
"version": "0.1.0",
"dependencies": {
"@expo/vector-icons": "^15.1.1",
"@noble/hashes": "^2.4.0",
"expo": "~58.0.14",
"expo-application": "~58.1.2",
"expo-constants": "~58.0.12",
"expo-crypto": "~58.0.7",
"expo-document-picker": "~58.0.4",
"expo-file-system": "~58.0.12",
"expo-font": "~58.0.8",
"expo-image-picker": "~58.0.10",
"expo-secure-store": "~58.0.2",
"expo-sharing": "~58.0.20",
"expo-status-bar": "~58.0.3",
"expo-system-ui": "~58.0.6",
"expo-updates": "~58.0.17",
"htmlparser2": "^12.0.0",
"react": "19.3.0",
"react-dom": "19.3.0",
"react-native": "0.88.0",
@ -1107,9 +1112,9 @@
}
},
"node_modules/@expo/config-plugins": {
"version": "58.0.9",
"resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-58.0.9.tgz",
"integrity": "sha512-HyP7V1QgDxeHcOEh4qQH7cfK7cI7wNp0y9lszAu98SRYCshhDbwB9gWpFfnpX1GQUtgiqG4Hvgh1z3ntcGwAjw==",
"version": "58.0.10",
"resolved": "https://registry.npmmirror.com/@expo/config-plugins/-/config-plugins-58.0.10.tgz",
"integrity": "sha512-oW0geRREubSsqV2d0EwkK0rRcAoB7a68CnJx7s8Al33HoTtEg7KLTQNcKlSTmmwoUESQQvAmzNqAZy4ajuCBKA==",
"license": "MIT",
"dependencies": {
"@expo/config-types": "^58.0.3",
@ -1123,7 +1128,7 @@
"glob": "^13.0.0",
"semver": "^7.7.4",
"slugify": "^1.6.6",
"xcode": "^3.0.1",
"xcode": "^4.0.0",
"xml2js": "0.6.0"
}
},
@ -1528,6 +1533,18 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@noble/hashes": {
"version": "2.4.0",
"resolved": "https://registry.npmmirror.com/@noble/hashes/-/hashes-2.4.0.tgz",
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noxcturnal/noxcturnal-darwin-arm64": {
"version": "0.1.5",
"resolved": "https://registry.npmjs.org/@noxcturnal/noxcturnal-darwin-arm64/-/noxcturnal-darwin-arm64-0.1.5.tgz",
@ -2702,6 +2719,73 @@
"integrity": "sha512-Ndrrf6BMPalkQPd/zubL+4YghH2J9NspapQ09uDXwYbvOPkP0oaqf5CkcwJ0b50kS2O3ul6yVu+jz+RY62Cejg==",
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/dom-serializer/-/dom-serializer-3.1.1.tgz",
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/domelementtype": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/domelementtype/-/domelementtype-3.0.0.tgz",
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/domhandler": {
"version": "6.0.1",
"resolved": "https://registry.npmmirror.com/domhandler/-/domhandler-6.0.1.tgz",
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^3.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/domutils": {
"version": "4.0.2",
"resolved": "https://registry.npmmirror.com/domutils/-/domutils-4.0.2.tgz",
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^3.0.0",
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@ -2729,6 +2813,18 @@
"node": ">= 0.8"
}
},
"node_modules/entities": {
"version": "8.1.0",
"resolved": "https://registry.npmmirror.com/entities/-/entities-8.1.0.tgz",
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/error-stack-parser": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/error-stack-parser/-/error-stack-parser-2.1.4.tgz",
@ -2846,6 +2942,15 @@
}
}
},
"node_modules/expo-application": {
"version": "58.1.2",
"resolved": "https://registry.npmmirror.com/expo-application/-/expo-application-58.1.2.tgz",
"integrity": "sha512-WYFdNHGaxe/j69oYREhK0cKsKYszuIuz399WXYCP+M1grfO+FCWB/RbuMgaXJsLWlzqhNjA/zLgfJ+33FwrQvw==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-constants": {
"version": "58.0.12",
"resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-58.0.12.tgz",
@ -2884,6 +2989,16 @@
"integrity": "sha512-mhRYnE35MzGxR1Xnl9FAg7/yHaocy4xoVzgsDmS9cbK+1wM6l74/I/73/E4Kr6wChdVZfeS6S+Tv4I1qYbGY2g==",
"license": "MIT"
},
"node_modules/expo-file-system": {
"version": "58.0.12",
"resolved": "https://registry.npmmirror.com/expo-file-system/-/expo-file-system-58.0.12.tgz",
"integrity": "sha512-Ytua0iPjhacvM5eEpPFtrc2iWwdcIfQ3s/9ps0awxGCaHs54DI9weo8wPUJImfcKPmiseqVGM4TFg4lHfD0XmQ==",
"license": "MIT",
"peerDependencies": {
"expo": "*",
"react-native": "*"
}
},
"node_modules/expo-font": {
"version": "58.0.8",
"resolved": "https://registry.npmjs.org/expo-font/-/expo-font-58.0.8.tgz",
@ -3008,6 +3123,22 @@
"node": "^22.13.0 || ^24.3.0 || ^26.0.0 || >=27.0.0"
}
},
"node_modules/expo-sharing": {
"version": "58.0.20",
"resolved": "https://registry.npmmirror.com/expo-sharing/-/expo-sharing-58.0.20.tgz",
"integrity": "sha512-FxfBGaiWYNmV12bDbT81TAi08MGN1OdQtz9WLscN3He0We3w9RfIQNAhCSOJLKpcFvbNAXZ4nkOjpO8q3I8LRw==",
"license": "MIT",
"dependencies": {
"@expo/config-plugins": "^58.0.10",
"@expo/config-types": "^58.0.3",
"@expo/plist": "^0.10.1"
},
"peerDependencies": {
"expo": "*",
"react": "*",
"react-native": "*"
}
},
"node_modules/expo-status-bar": {
"version": "58.0.3",
"resolved": "https://registry.npmjs.org/expo-status-bar/-/expo-status-bar-58.0.3.tgz",
@ -3427,16 +3558,6 @@
"react-native": "*"
}
},
"node_modules/expo/node_modules/expo-file-system": {
"version": "58.0.9",
"resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-58.0.9.tgz",
"integrity": "sha512-JT0km3Wa+wDz/7Rli8ifreoMnmk68ulf/uaWzRA26xm/4K+jGTY+cDhnboRmpmXUCBkED6uqxWmNoXjaVU9VUw==",
"license": "MIT",
"peerDependencies": {
"expo": "*",
"react-native": "*"
}
},
"node_modules/expo/node_modules/expo-keep-awake": {
"version": "58.0.3",
"resolved": "https://registry.npmjs.org/expo-keep-awake/-/expo-keep-awake-58.0.3.tgz",
@ -3773,6 +3894,28 @@
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"license": "ISC"
},
"node_modules/htmlparser2": {
"version": "12.0.0",
"resolved": "https://registry.npmmirror.com/htmlparser2/-/htmlparser2-12.0.0.tgz",
"integrity": "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"domutils": "^4.0.2",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@ -5206,7 +5349,7 @@
},
"node_modules/plist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
"resolved": "https://registry.npmmirror.com/plist/-/plist-3.1.1.tgz",
"integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==",
"license": "MIT",
"dependencies": {
@ -5220,7 +5363,7 @@
},
"node_modules/plist/node_modules/@xmldom/xmldom": {
"version": "0.9.12",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
"resolved": "https://registry.npmmirror.com/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
"integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
"license": "MIT",
"engines": {
@ -5837,7 +5980,7 @@
},
"node_modules/simple-plist": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/simple-plist/-/simple-plist-1.3.1.tgz",
"resolved": "https://registry.npmmirror.com/simple-plist/-/simple-plist-1.3.1.tgz",
"integrity": "sha512-iMSw5i0XseMnrhtIzRb7XpQEXepa9xhWxGUojHBL43SIpQuDQkh3Wpy67ZbDzZVr6EKxvwVChnVpdl8hEVLDiw==",
"license": "MIT",
"dependencies": {
@ -6282,16 +6425,6 @@
"node": ">= 0.4.0"
}
},
"node_modules/uuid": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-7.0.3.tgz",
"integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==",
"deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/validate-npm-package-name": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-5.0.1.tgz",
@ -6416,16 +6549,15 @@
}
},
"node_modules/xcode": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz",
"integrity": "sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==",
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/xcode/-/xcode-4.0.0.tgz",
"integrity": "sha512-dDaoWzc9EP2fp9FS9PVZUkyvFxY4y1TOV9pcKaKLk++Ei/qb97XDFEVP7GnW7Osii/TzVABJ0jq2F+9/lq0TVA==",
"license": "Apache-2.0",
"dependencies": {
"simple-plist": "^1.1.0",
"uuid": "^7.0.3"
"simple-plist": "^1.3.1"
},
"engines": {
"node": ">=10.0.0"
"node": ">=14.17.0"
}
},
"node_modules/xml2js": {

View File

@ -16,16 +16,21 @@
},
"dependencies": {
"@expo/vector-icons": "^15.1.1",
"@noble/hashes": "^2.4.0",
"expo": "~58.0.14",
"expo-application": "~58.1.2",
"expo-constants": "~58.0.12",
"expo-crypto": "~58.0.7",
"expo-document-picker": "~58.0.4",
"expo-file-system": "~58.0.12",
"expo-font": "~58.0.8",
"expo-image-picker": "~58.0.10",
"expo-secure-store": "~58.0.2",
"expo-sharing": "~58.0.20",
"expo-status-bar": "~58.0.3",
"expo-system-ui": "~58.0.6",
"expo-updates": "~58.0.17",
"htmlparser2": "^12.0.0",
"react": "19.3.0",
"react-dom": "19.3.0",
"react-native": "0.88.0",

View File

@ -1,15 +1,19 @@
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, Text, View } from 'react-native';
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 Updates from 'expo-updates';
import * as Crypto from 'expo-crypto';
import { StatusBar } from 'expo-status-bar';
import { ApiClient, allows, internalUrl } from './core/network';
import { createUpdateCheck, type UpdateState } from './core/updates';
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';
@ -34,24 +38,30 @@ type User={user:Row; 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>(variant==='dev'?null:nativeBase);
useEffect(()=>{if(variant!=='dev')return;let alive=true;void preferences.get(developmentServerKey).then(value=>{if(alive)setServer(value?developmentServer(value):nativeBase);}).catch(()=>{if(alive)setServer(nativeBase);});return()=>{alive=false;};},[]);
const saveServer=useCallback(async(value:string)=>{await preferences.put(developmentServerKey,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><AppearanceContext.Provider value={{mode,setMode:change}}>{server?<Root key={server} server={server} saveServer={saveServer}/>:<View style={[s.page,s.fill,{justifyContent:'center'}]}><ActivityIndicator/><Note>正在读取开发服务设置…</Note></View>}<PreviewDialogs/></AppearanceContext.Provider></SafeAreaProvider>;
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}:{server:string;saveServer:(value:string)=>Promise<void>}){
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<string[]>([]),[aiVisited,setAiVisited]=useState(false),[keyboard,setKeyboard]=useState(false),[update,setUpdate]=useState<UpdateState>('disabled');
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 page=stack[stack.length-1];
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(base,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])=>{
@ -71,47 +81,46 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom
}
const connection=variant==='dev'?<ServerConnection address={server} onSave={changeServer}/>:undefined;
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]);
const check=useMemo(()=>createUpdateCheck({...Updates,isEnabled:Platform.OS==='android'&&!__DEV__&&Updates.isEnabled},setUpdate),[]);
useEffect(()=>{void check();let alive=true;const current=epoch.current;
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,check,identity]);
.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){const proceed=()=>{Keyboard.dismiss();setStack(old=>[...old,name]);};if(leave.current)leave.current(proceed);else proceed();}
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 updateText={disabled:'开发模式 · 未启用远程更新',checking:'正在检查内网更新…',current:'已是当前版本',downloading:'正在后台下载更新,不影响操作…',ready:'更新已备妥,下次启动生效',failed:'暂未连接更新服务,继续使用当前版本'}[update];
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:t.bg,width:'100%',alignSelf:'center',...(Platform.OS==='web'?{maxWidth:480}:{})}]}><StatusBar style={t.bg==='#101722'?'light':'dark'}/>
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:page?18:20,lineHeight:page?26:28,fontWeight:'700',color:t.text,paddingLeft:page?0:8}}>{selected?.title||titles[page||tab]}</Text>
<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} user={user.user} modules={permitted} open={open} go={go} ai={ai}/>}
{!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&&<BusinessList key={page} api={api} module={selected} permissions={user.permissions}/>}
{selected?.key==='files'?<FileLibrary api={api} scope={scope} permissions={user.permissions}/>:!!selected&&<BusinessList key={page} api={api} scope={scope} module={selected} permissions={user.permissions} 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 updateText={updateText} environment={variant} baseUrl={server} connection={connection} logout={logout} about={page==='about'}/>}
{(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:57,gap:3}}><View style={{paddingHorizontal:17,paddingVertical:4,borderRadius:18,backgroundColor:tab===key?t.soft:'transparent'}}><Icon name={icon} size={23} 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>}
{!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 Login({api,onLogin,server,connection}:{api:ApiClient;onLogin:(token:string)=>Promise<void>;server:string;connection?:React.ReactNode}){
@ -124,105 +133,5 @@ function Login({api,onLogin,server,connection}:{api:ApiClient;onLogin:(token:str
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 <KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}><ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={[s.page,{flexGrow:1,justifyContent:'center',maxWidth:520,width:'100%',alignSelf:'center'}]}>
<Note>CMVR · 项目物资管理</Note><Heading>欢迎回到工作空间</Heading><Note>请连接公司内网,使用现有账号登录。</Note>
<Field label="登录账号" value={username} onChange={setUsername} disabled={busy}/><Field label="密码" value={password} onChange={setPassword} secure disabled={busy}/>
{connecting&&<View style={s.row}><ActivityIndicator/><Note>正在连接内网服务,准备登录信息…</Note></View>}
{!!captcha&&captcha.captchaEnabled!==false&&<><Field label="验证码" value={code} onChange={setCode} disabled={busy}/>
{!!captcha?.img&&<Pressable accessibilityRole="button" accessibilityLabel="刷新验证码" disabled={busy} onPress={()=>void refresh()}><Image source={{uri:`data:image/png;base64,${captcha.img}`}} style={{width:160,height:60}}/></Pressable>}</>}
{!!error&&<Note>{error}</Note>}<Button title="登录" busy={busy} disabled={!captcha} onPress={()=>void submit()}/>
<Button title="重新连接" secondary disabled={busy||connecting} onPress={()=>void refresh()}/><Note>{variant==='prod'?'正式环境':'开发环境'} · {server}</Note>
{connection}
</ScrollView></KeyboardAvoidingView>;
}
function BusinessList({api,module,permissions}:{api:ApiClient;module:Module;permissions:string[]}){
const t=useTheme();const [query,setQuery]=useState(''),[rows,setRows]=useState<Row[]>([]),[total,setTotal]=useState(0),[page,setPage]=useState(1);
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[operation,setOperation]=useState<{row:Row;kind:string}|null>(null);
const [historyRow,setHistoryRow]=useState<Row|null>(null);
const [arrivalQueue,setArrivalQueue]=useState<'arrival'|'accept'>('arrival');
const [compactAmounts,setCompactAmounts]=useState(true);
const serial=useRef(0),controller=useRef<AbortController|null>(null),busyRef=useRef(false),appliedQuery=useRef('');
const load=useCallback(async(next:number,text:string)=>{const id=++serial.current;controller.current?.abort();controller.current=new AbortController();busyRef.current=true;setBusy(true);setError('');setRows([]);
appliedQuery.current=text.trim();
try{const [data,display]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...(module.key==='arrival'?arrivalListQuery(arrivalQueue):{}),pageNum:next,pageSize:20,...(module.search?{[module.search]:text.trim()}:{})},signal:controller.current.signal}),module.key==='purchase'?api.request<Row>('/warehouse/amount-display',{signal:controller.current.signal}):Promise.resolve(null)]);
if(id!==serial.current)return;if(display)setCompactAmounts(display.data.enabled===true);const result=data.data&&Array.isArray(data.data.rows)?data.data:data;setRows(result.rows||[]);setTotal(result.total||0);setPage(next);
}catch(e){if(id===serial.current)setError((e as Error).message);}finally{if(id===serial.current){busyRef.current=false;setBusy(false);}}},[api,module,arrivalQueue]);
useEffect(()=>{void load(1,appliedQuery.current);return()=>{serial.current++;controller.current?.abort();};},[load]);
const stockWrite=allows(permissions,['warehouse:stock:out'],['project:inventory:use']);
function confirmCheck(row:Row){if(busyRef.current)return;Alert.alert('确认盘点生效',`${display(row.productName)}:账面 ${display(row.bookNum)} → 实盘 ${display(row.realNum)};差异 ${display(row.diffNum)}。确认后将调整库存。`,[{text:'返回核对',style:'cancel'},{text:'确认生效',onPress:()=>{if(busyRef.current)return;busyRef.current=true;setBusy(true);void api.request(`/warehouse/check/confirm/${row.id}`,{method:'PUT'}).then(()=>load(page,query)).catch(e=>{setError((e as Error).message+' 请刷新列表核对结果。');}).finally(()=>{busyRef.current=false;setBusy(false);});}}]);}
const ListCard=module.key==='arrival'?ArrivalCard:RecordCard;
return <View style={s.fill}>{module.key==='arrival'?<ArrivalListTools query={query} setQuery={setQuery} queue={arrivalQueue} setQueue={setArrivalQueue} busy={busy} total={total} page={page} search={()=>void load(1,query)} reset={()=>{setQuery('');void load(1,'');}}/>:<View style={[s.page,{paddingBottom:12}]}>{!!module.search&&<Field label="名称或关键词" value={query} onChange={setQuery}/>}
<View style={s.row}><Button title="查询" busy={busy} onPress={()=>void load(1,query)}/><Button title="重置" secondary disabled={busy} onPress={()=>{setQuery('');void load(1,'');}}/></View>
<Note>{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}</Note></View>}
{!!error&&<View style={{paddingHorizontal:18,paddingBottom:10}}><Note>{error}</Note></View>}
<FlatList data={rows} keyExtractor={(row,index)=>`${row.id||row.loanNo||'row'}-${index}`} contentContainerStyle={[s.page,{paddingTop:0}]}
refreshing={busy} onRefresh={()=>void load(page,appliedQuery.current)} ListEmptyComponent={!busy?<Note>{error?'请重试查询。':module.key==='arrival'?arrivalQueue==='accept'?'暂无待验收记录。先登记实际到货,再回到这里验收。':'暂无待登记到货的采购。只有已确认采购、已选供应商且仍有未登记数量的明细会出现在这里。':'当前条件下暂无记录。'}</Note>:undefined}
renderItem={({item})=><ListCard module={module} item={item} queue={arrivalQueue} compactAmounts={compactAmounts}>
{['move','use'].includes(module.key)&&stockWrite&&<Button title={module.key==='move'?'移库':'领用出库'} secondary disabled={Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:module.key})}/>}
{module.key==='count'&&allows(permissions,['warehouse:check:add'])&&<Button title="登记盘点" secondary onPress={()=>setOperation({row:item,kind:'check'})}/>}
{module.key==='check'&&Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm'])&&<Button title="确认盘点生效" secondary disabled={busy} onPress={()=>confirmCheck(item)}/>}
{['arrival','purchase'].includes(module.key)&&<Button title="到货记录 / 照片" secondary onPress={()=>setHistoryRow(item)}/>}
{module.key==='arrival'&&<ArrivalActions row={item} permissions={permissions} queue={arrivalQueue}
onOpen={kind=>setOperation({row:item,kind})}/>}
{module.key==='pending'&&allows(permissions,['warehouse:in:confirm'])&&(item.receiptRoot||allows(permissions,['warehouse:in:edit']))&&<Button title="办理入库" secondary onPress={()=>setOperation({row:item,kind:'receive'})}/>}
</ListCard>}/>
<View style={[s.row,{padding:12,justifyContent:'space-between'}]}><Button title="上一页" secondary disabled={busy||page<=1} onPress={()=>void load(page-1,appliedQuery.current)}/><Button title="下一页" secondary disabled={busy||page*20>=total} onPress={()=>void load(page+1,appliedQuery.current)}/></View>
{!!historyRow&&<ArrivalHistory api={api} row={historyRow} close={()=>setHistoryRow(null)}/>}
{!!operation&&(operation.kind==='arrival'||operation.kind==='accept'?<ArrivalOperation api={api} row={operation.row} mode={operation.kind} close={()=>setOperation(null)} done={()=>{setOperation(null);void load(page,query);}}/>:<StockOperation api={api} row={operation.row} kind={operation.kind} close={()=>setOperation(null)} done={()=>{setOperation(null);void load(page,query);}}/>)}
</View>;
}
function RecordCard({module,item,children,compactAmounts=false}:{module:Module;item:Row;children:React.ReactNode;compactAmounts?:boolean}){
const t=useTheme(),[more,setMore]=useState(false),quantityKey={stock:'stockNum',move:'stockNum',use:'stockNum',count:'stockNum',arrival:'remainingQuantity',purchase:'quantity',pending:'inNum',in:'inNum',loans:'outstandingQuantity',check:'diffNum',out:'outNum',production:'planned_quantity'}[module.key];
const fields=module.fields.filter(([key])=>key!==quantityKey&&key!=='unit'&&(!compactAmounts||!['actualUnitPrice','actualAmount'].includes(key)));
return <Card><View style={{flexDirection:'row',alignItems:'flex-start',gap:12}}><Text style={{color:t.text,fontSize:18,fontWeight:'700',lineHeight:26,flex:1}}>{display(item[module.titleKey]||item.productName||item.taskNo)}</Text>{quantityKey&&<View style={{backgroundColor:t.soft,padding:10,borderRadius:12,alignItems:'flex-end',gap:3}}><Text style={{color:t.accent,fontWeight:'700',fontSize:20}}>{display(item[quantityKey])} <Text style={{fontSize:11}}>{display(item.unit)==='—'?'':display(item.unit)}</Text></Text><Text style={{color:t.muted,fontSize:10}}>{module.fields.find(([key])=>key===quantityKey)?.[1]}</Text></View>}</View>
{(more?fields:fields.slice(0,3)).map(([key,label])=><View key={key} style={s.pair}><Text style={[s.label,{color:t.muted}]}>{label}</Text><Text selectable style={[s.value,{color:t.text}]}>{recordDisplay(module,key,item[key])}</Text></View>)}
{fields.length>3&&<Pressable accessibilityRole="button" accessibilityLabel={more?'收起资料':'更多资料'} accessibilityState={{expanded:more}} onPress={()=>setMore(v=>!v)} style={{paddingVertical:8,flexDirection:'row',alignItems:'center',gap:5}}><Text style={{color:t.muted,fontSize:12}}>{more?'收起资料':'更多资料'}</Text><Icon name={more?'chevron-up':'chevron-down'} size={13} color={t.muted}/></Pressable>}{children}
</Card>;
}
function StockOperation({api,row,kind,close,done}:{api:ApiClient;row:Row;kind:string;close:()=>void;done:()=>void}){
const t=useTheme(); const title={move:'移库',use:'领用出库',borrow:'借用',check:'登记盘点',receive:'办理入库'}[kind]||'库存操作';
const [quantity,setQuantity]=useState(''),[remark,setRemark]=useState(''),[date,setDate]=useState(localDate());
const [areas,setAreas]=useState<Row[]>([]),[projects,setProjects]=useState<Row[]>([]),[area,setArea]=useState<Row|null>(null),[project,setProject]=useState<Row|null>(null);
const [preview,setPreview]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState(''),[submitted,setSubmitted]=useState(false),[ready,setReady]=useState(false);
const lock=useRef(false),key=useRef(Crypto.randomUUID()),frozen=useRef<Row|null>(null);
useEffect(()=>{const ctl=new AbortController();void(async()=>{try{if(!['use','check'].includes(kind)){const a=await api.request<Row>('/warehouse/area/optionselect',{signal:ctl.signal});setAreas(a.data||[]);}
if(kind==='borrow'){const p=await api.request<Row>('/project/info/options',{signal:ctl.signal});setProjects(p.data||[]);}setReady(true);
}catch(e){if(!ctl.signal.aborted)setError((e as Error).message);}})();return()=>ctl.abort();},[api,kind]);
function prepare(){const n=Number(quantity);if(!Number.isFinite(n)||(kind==='check'?n<0:n<=0)||!/^\d+(\.\d{1,4})?$/.test(quantity))return setError('请填写有效数量,最多 4 位小数。');
if(!validDate(date))return setError('请填写有效的业务日期,格式为 YYYY-MM-DD。');
if(remark.length>500)return setError('备注或差异原因请控制在 500 字以内。');
if(kind==='check'&&n!==Number(row.stockNum)&&!remark.trim())return setError('盘点数量与账面数量不同,请填写差异原因后继续。');
if((kind==='move'||kind==='receive'||kind==='borrow')&&!area)return setError('请选择目标库区。');
if(kind==='move'&&area?.id===row.areaId)return setError('目标库区不能与来源相同。');
if(kind==='borrow'&&(!project||project.id===row.projectId))return setError('请选择不同的借入项目。');
if(['move','borrow','use'].includes(kind)&&n>Number(row.stockNum))return setError(`本次数量超过当前可用库存(${display(row.stockNum)} ${display(row.unit)}),请重新核对。`);
if(kind==='receive'&&(n>Number(row.inNum)||!row.receiptRoot&&n!==Number(row.inNum)))return setError('本次数量不能超过待入库数量;历史待入库记录须整单办理。');
setError('');setPreview(true);}
async function submit(){if(lock.current||!preview||!ready)return;lock.current=true;setBusy(true);setSubmitted(true);setError('');
const data=frozen.current||{quantity:Number(quantity),key:key.current,date,remark};frozen.current=data;
try{if(kind==='move')await api.request('/warehouse/stock/move',{method:'POST',body:{...data,projectId:row.projectId,itemId:row.productId,fromAreaId:row.areaId,toAreaId:area?.id}});
if(kind==='borrow')await api.request('/project/loans',{method:'POST',body:{...data,lenderProjectId:row.projectId,borrowerProjectId:project?.id,itemId:row.productId,fromAreaId:row.areaId,toAreaId:area?.id}});
if(kind==='use')await api.request('/warehouse/stock/out',{method:'POST',body:{id:row.id,usageProjectId:row.projectId,outNum:data.quantity,outType:4,outNo:'MOUT-'+data.key,outTime:data.date+' 00:00:00',remark:data.remark}});
if(kind==='receive'){if(row.receiptRoot)await api.request(`/warehouse/in/receive/${row.id}`,{method:'POST',body:{...data,areaId:area?.id}});else{await api.request('/warehouse/in',{method:'PUT',body:{...row,areaId:area?.id,businessDate:data.date,remark:data.remark}});await api.request(`/warehouse/in/confirm/${row.id}`,{method:'PUT'});}}
if(kind==='check')await api.request('/warehouse/check',{method:'POST',body:{projectId:row.projectId,productId:row.productId,areaId:row.areaId,realNum:data.quantity,businessDate:date,reason:remark,remark}});
done();
}catch(e){setError((e as Error).message+(kind==='check'?' 请先到盘点列表核对是否已生成,勿重复提交。':' 重试会使用同一请求标识和内容。'));}
finally{lock.current=false;setBusy(false);}}
function requestClose(){if(busy)return;if(quantity||remark||area||project||preview)Alert.alert('结束本次填写?',submitted?'请先到业务记录中核对处理结果。':'尚未提交的内容不会保留。',[{text:'继续核对',style:'cancel'},{text:'关闭',onPress:close}]);else close();}
return <Modal visible animationType="slide" onRequestClose={requestClose}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}><ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={s.page}>
<Heading>{title}</Heading><Note>{display(row.productName)} · {display(row.projectName||row.sourceProjectName)} · {display(row.areaName)}</Note>
<Note>{kind==='receive'?'待入库数量':kind==='check'?'账面数量':'当前可用数量'}:{display(kind==='receive'?row.inNum:row.stockNum)} {display(row.unit)}</Note>
{submitted?<Note>已尝试提交。为避免不确定结果下更改重试内容,表单已锁定;请先核对业务结果。</Note>:null}
{!preview?<><Field label={kind==='check'?'实际盘点数量':'本次数量'} value={quantity} onChange={setQuantity} keyboard="decimal-pad"/>
{kind==='move'&&<Button title="全部移库" secondary disabled={busy||submitted||!Number.isFinite(Number(row.stockNum))||Number(row.stockNum)<=0} onPress={()=>{setQuantity(String(Number(row.stockNum)));setError('');}}/>}
<Field label="业务日期(YYYY-MM-DD)" value={date} onChange={setDate}/><Field label={kind==='check'?'差异原因':'备注'} value={remark} onChange={setRemark} multiline/>
{kind==='borrow'&&<Choice label="借入项目" items={projects} value={project} onChange={setProject} nameKey="projectName"/>}
{!['check','use'].includes(kind)&&<Choice label="目标库区" items={areas} value={area} onChange={setArea} nameKey="areaName"/>}
<Button title="核对预览" disabled={!ready} onPress={prepare}/></>:<Card><Heading>请核对本次{title}</Heading><Note>物品:{display(row.productName)}</Note>
{kind==='check'?<><Note>账面数量:{display(row.stockNum)} {display(row.unit)}</Note><Note>实际盘点数量:{quantity} {display(row.unit)}</Note><Note>差异数量:{Number((Number(quantity)-Number(row.stockNum)).toFixed(4))} {display(row.unit)}</Note><Note>登记后生成待确认盘点记录;确认生效后才会调整库存,当前不会直接扣减或增加库存。</Note></>:<Note>数量:{quantity} {display(row.unit)}</Note>}
{!!project&&<Note>借入项目:{project.projectName}</Note>}{!!area&&<Note>目标库区:{area.areaName||area.areaCode}</Note>}<Note>日期:{date}</Note><Note>{kind==='check'?'差异原因':'备注'}:{remark||'无'}</Note>
<Button title={submitted?'核对后重试原请求':'确认提交'} busy={busy} disabled={kind==='check'&&submitted} onPress={()=>void submit()}/>
<Button title="返回修改" secondary disabled={busy||submitted} onPress={()=>setPreview(false)}/></Card>}
{!!error&&<Note>{error}</Note>}<Button title="关闭" secondary disabled={busy} onPress={requestClose}/>
</ScrollView></KeyboardAvoidingView></SafeAreaView></Modal>;
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()}/>;
}

View File

@ -2,8 +2,8 @@ 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 type MessageState={tab:MessageTab;items:Row[];notices:Row[];detail:Row|null;busy:boolean;reading:boolean;error:string;hasMore:boolean;cursor:string|null;unreadOnly:boolean;keyword:string};
export const initialMessageState=():MessageState=>({tab:'inbox',items:[],notices:[],detail:null,busy:false,reading:false,error:'',hasMore:false,cursor:null,unreadOnly:false,keyword:''});
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=>({'&nbsp;':' ','&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"','&#39;':"'"}[value]||value)).trim();}
@ -19,7 +19,9 @@ export function createMessageCenter(api:Pick<ApiClient,'request'>,changed:(state
emit({busy:true,error:'',detail:null,...(!more?{items:[],notices:[],hasMore:false,cursor:null}:{})});
try{
if(tab==='notices'){
const result=await api.request<Row>('/system/notice/listTop');if(!valid(id))return;emit({notices:result.data||[]});
const result=await api.request<Row>('/system/notice/published',{query:{beforeId:cursor,limit:20,keyword:state.keyword,unreadOnly:state.unreadOnly}});if(!valid(id))return;
const page=result.data||{},next=page.nextCursor==null?null:String(page.nextCursor),advance=next!==null&&/^\d+$/.test(next)&&BigInt(next)>0n&&(cursor===null||BigInt(next)<BigInt(cursor));
const seen=new Set(state.notices.map(n=>String(n.noticeId)));emit({notices:[...state.notices,...(page.items||[]).filter((n:Row)=>!seen.has(String(n.noticeId)))],hasMore:page.hasMore===true&&advance,cursor:advance?next:null,error:page.hasMore&&!advance?'分页位置未更新,请刷新后继续。':''});
}else{
const result=await api.request<Row>('/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);
@ -31,12 +33,13 @@ export function createMessageCenter(api:Pick<ApiClient,'request'>,changed:(state
}
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 search(keyword:string){if(state.reading)return;emit({keyword:keyword.trim().slice(0,100)});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<Row>(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}});
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),html:data.noticeContent||'',attachments:data.attachments||[],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){
@ -51,5 +54,5 @@ export function createMessageCenter(api:Pick<ApiClient,'request'>,changed:(state
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};
return {load,tab,filter,search,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};
}

View File

@ -3,12 +3,13 @@ export type Row = Record<string, any>;
export type Module = { key: string; title: string; path: string; permissions: string[][];
search: string; titleKey: string; fields: [string, string][]; query?: Row; pages?: string[]; guide?: string };
export const modules: Module[] = [
{key:'files',title:'共享文件',path:'/system/files',permissions:[['system:file:list','system:file:manage']],search:'keyword',titleKey:'name',fields:[]},
{ key:'arrival',title:'到货验收',path:'/warehouse/purchase/list',permissions:[['warehouse:purchase:list','warehouse:purchase:manage'],['warehouse:purchase:edit','warehouse:purchase:manage']],search:'materialName',titleKey:'materialName',guide:'先确认采购、锁定报价,再登记实际到货,逐次验收合格/不合格数量;合格后进入待入库,不会直接增加库存。',fields:[['purchaseBatchNo','采购批次'],['projectName','所属项目'],['materialParams','规格型号'],['quantity','采购数量'],['remainingQuantity','未登记到货'],['pendingArrivalQuantity','待验收'],['unit','单位']] },
{ key:'use',title:'出库领用',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:stock:out'],['project:inventory:use']],search:'productName',titleKey:'productName',guide:'选择本项目库存,核对数量后领用;跨项目使用仍须先办理借用。',fields:[['projectName','所属项目'],['areaName','库区'],['stockNum','可用数量'],['unit','单位'],['spec','规格型号']] },
{ key:'move',title:'移库',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:stock:out'],['project:inventory:use']],search:'productName',titleKey:'productName',guide:'同项目更换存放库区,物品所属项目和总库存数量不变。',fields:[['projectName','所属项目'],['areaName','来源库区'],['stockNum','可用数量'],['unit','单位'],['spec','规格型号']] },
{ key:'count',title:'现场盘点',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:check:add']],search:'productName',titleKey:'productName',guide:'填写实际清点数量;登记后生成待确认记录,确认盘点后才调整库存。',fields:[['projectName','所属项目'],['areaName','库区'],['stockNum','账面数量'],['unit','单位'],['spec','规格型号']] },
{ key: 'stock', title: '库存查询', path: '/warehouse/stock/list', permissions: [['warehouse:stock:list']], search: 'productName', titleKey: 'productName',
guide: '这里用于查询;现场领用、移库、盘点请从对应入口办理。跨项目借用可在 Web 端办理。',
guide: '这里用于查询;现场领用、移库、盘点请从对应入口办理。可直接办理领用、移库或跨项目借用。',
fields: [['projectName','所属项目'],['areaName','库区'],['stockNum','库存数量'],['unit','单位'],['spec','规格型号'],['brand','品牌'],['averageUnitCost','平均单价'],['stockAmount','库存金额']] },
{ key: 'purchase', title: '采购明细', path: '/warehouse/purchase/list', permissions: [['warehouse:purchase:list','warehouse:purchase:manage']], search: 'materialName', titleKey: 'materialName',
guide: '一批采购对应一个项目;确认采购后再登记到货,验收合格后到「待入库」办理入库。',
@ -19,7 +20,7 @@ export const modules: Module[] = [
{ key: 'in', title: '入库记录', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 1 },
fields: [['sourceProjectName','所属项目'],['areaName','库区'],['inNum','入库数量'],['unit','单位'],['businessDate','业务日期'],['inNo','入库单号']] },
{ key: 'loans', title: '借用与归还', path: '/project/loans', permissions: [['project:project:list','warehouse:stock:list','warehouse:purchase:list','warehouse:purchase:manage']], search: '', titleKey: 'itemName',
guide: '这里查看借用与待还记录;跨项目借用、归还可在 Web 端办理,借用不等于领用。',
guide: '查看借还记录;从库存发起借用,可按实际数量部分归还或按多个库区全部归还。借用不等于领用。',
fields: [['lenderProjectName','借出项目'],['borrowerProjectName','借入项目'],['quantity','借用数量'],['returnedQuantity','已还数量'],['outstandingQuantity','未还数量'],['unit','单位'],['loanNo','借用编号']] },
{ key: 'check', title: '库存盘点', path: '/warehouse/check/list', permissions: [['warehouse:check:list']], search: 'productName', titleKey: 'productName',
guide: '从「现场盘点」登记实际清点数量,不是差异数量;这里核对盘点记录,确认后才调整库存。',

View File

@ -1,4 +1,5 @@
import {isSearchRequest,normalizeSearchQuery} from './search-query.ts';
import {readableMultipart} from './upload-file.ts';
export type Environment = 'dev' | 'prod';
// Do not let a pasted server address redirect credentials to an Internet host.
@ -32,9 +33,32 @@ export class ApiClient {
}
authenticate(token: string) { this.generation++; this.token = token; }
clear() { this.generation++; this.token = ''; }
captureSession() { return this.generation; }
isSessionCurrent(value: number) { return value === this.generation; }
/** Stream authenticated downloads into a caller-owned file, with bounded memory. */
async download(path:string, sink:(bytes:Uint8Array)=>Promise<void>, options:{signal?:AbortSignal;maxBytes?:number;onProgress?:(bytes:number,total:number)=>void;transport?:typeof fetch}={}) {
if(!/^\/system\/files\/[a-zA-Z0-9-]+\/content$/.test(path)&&!/^\/system\/mobile-release\/[a-f0-9]{64}\/content$/.test(path))throw new ApiError('下载地址无效',400);
const epoch=this.generation,ctl=new AbortController(),abort=()=>ctl.abort();
options.signal?.addEventListener('abort',abort,{once:true});if(options.signal?.aborted)ctl.abort();
const timer=setTimeout(abort,900000),max=Math.min(options.maxBytes??1024**3,1024**3);
let reader:ReadableStreamDefaultReader<Uint8Array>|undefined;
try{
const response=await(options.transport||this.transport)(this.baseUrl+path,{redirect:'error',signal:ctl.signal,headers:{Authorization:`Bearer ${this.token}`,...(this.devPreviewServer?{'X-CMVR-Dev-Server':this.devPreviewServer}:{})}});
if(epoch!==this.generation)throw new ApiError('账号已切换,下载取消',409);
if(!response.ok||/json/i.test(response.headers.get('content-type')||'')){
if(response.status===401){this.clear();this.expired();}throw new ApiError('无法下载,请重新登录或检查文件访问权限',response.status||403);
}
const total=Number(response.headers.get('content-length')||0);if(total>max)throw new ApiError('文件超过下载大小限制',413);
if(!response.body)throw new ApiError('当前运行环境不支持文件下载',503);
reader=response.body.getReader();let received=0;
for(;;){if(ctl.signal.aborted)throw new ApiError('下载已取消',499);const part=await reader.read();if(epoch!==this.generation)throw new ApiError('账号已切换,下载取消',409);if(part.done)break;received+=part.value.length;if(received>max)throw new ApiError('文件超过下载大小限制',413);await sink(part.value);options.onProgress?.(received,total);}
if(!received||total&&received!==total)throw new ApiError('文件下载不完整,请重试',503);
return received;
}finally{try{await reader?.cancel();}catch{}clearTimeout(timer);options.signal?.removeEventListener('abort',abort);}
}
async request<T = Json>(path: string, options: {
method?: string; body?: unknown; query?: Record<string, unknown>; anonymous?: boolean; timeout?: number;
signal?: AbortSignal; responseType?: 'image';
signal?: AbortSignal; responseType?: 'image'; imageMaxBytes?:number;
} = {}): Promise<T> {
if (!/^\/[a-zA-Z]/.test(path) || path.includes('://') || path.includes('..')) throw new Error('无效的接口地址');
const url = new URL(this.baseUrl + path);
@ -51,21 +75,27 @@ export class ApiClient {
const timer = setTimeout(abort, options.timeout || 30000);
try {
const multipart = typeof FormData !== 'undefined' && requestBody instanceof FormData;
let preparedBody=requestBody;
if(multipart)try{preparedBody=await readableMultipart(requestBody as FormData,controller.signal);}
catch(error){if(controller.signal.aborted)throw error;throw new ApiError(error instanceof Error?error.message:'无法读取本地附件,请重新选择文件。',400);}
const response = await this.transport(url.toString(), {
method: options.method || 'GET', redirect: 'error', signal: controller.signal,
headers: { Accept: 'application/json', ...(!multipart ? { 'Content-Type': 'application/json' } : {}),
...(this.devPreviewServer?{'X-CMVR-Dev-Server':this.devPreviewServer}:{}),
...(!options.anonymous && this.token ? { Authorization: `Bearer ${this.token}` } : {}) },
body: requestBody === undefined ? undefined : multipart ? requestBody as FormData : JSON.stringify(requestBody)
body: preparedBody === undefined ? undefined : multipart ? preparedBody as FormData : JSON.stringify(preparedBody)
});
if(options.responseType==='image'&&response.ok&&/^image\/(png|jpeg|webp)$/.test(response.headers.get('content-type')?.split(';')[0]||'')){
if(Number(response.headers.get('content-length')||0)>6*1024*1024)throw new ApiError('图片较大,请在电脑端查看。',413);
const limit=Math.max(1,Math.min(options.imageMaxBytes??6*1024*1024,20*1024*1024));
if(Number(response.headers.get('content-length')||0)>limit)throw new ApiError('图片超过预览大小限制,请在电脑端查看。',413);
const bytes=new Uint8Array(await response.arrayBuffer());
if(epoch!==this.generation)throw new ApiError('会话已切换,请重新查询。',409);
if(bytes.length>6*1024*1024)throw new ApiError('图片较大,请在电脑端查看。',413);
if(bytes.length>limit)throw new ApiError('图片超过预览大小限制,请在电脑端查看。',413);
return `data:${response.headers.get('content-type')?.split(';')[0]};base64,${base64(bytes)}` as T;
}
const data = await response.json();
let data;
try{data=await response.json();}
catch{if(response.ok)throw new ApiError('服务未返回有效结果,请先核对处理状态后重试。',503);data={code:response.status};}
if (epoch !== this.generation) throw new ApiError('会话已切换,请重新查询。', 409);
const code = Number(data.code ?? response.status);
if (code === 401 || response.status === 401) {
@ -73,6 +103,8 @@ export class ApiClient {
throw new ApiError(options.anonymous ? data.msg || '账号或密码未通过校验,请重新核对。' : '登录已过期,请重新登录。', 401);
}
if (code === 403 || response.status === 403) throw new ApiError('这项业务可请管理员协助办理或确认开通范围。', 403);
if (code === 413 || response.status === 413) throw new ApiError('文件超过上传大小限制,请缩小后重试。',413);
if (code === 408 || code === 504) throw new ApiError('文件上传或服务处理超时,请稍后重试。',code);
if (!response.ok || code !== 200) throw new ApiError(data.msg || '处理未完成,请核对后重试。', code);
return data as T;
} catch (error) {

View File

@ -1,19 +1,67 @@
export type UpdateState = 'disabled' | 'checking' | 'current' | 'downloading' | 'ready' | 'failed';
export type UpdateView = { state: UpdateState; visible: boolean; restarting: boolean; error: string };
export type UpdateDriver = {
isEnabled: boolean;
checkForUpdateAsync: () => Promise<{ isAvailable: boolean }>;
fetchUpdateAsync: () => Promise<unknown>;
checkForUpdateAsync: () => Promise<{ isAvailable: boolean; isRollBackToEmbedded?: boolean }>;
fetchUpdateAsync: () => Promise<{ isNew: boolean; isRollBackToEmbedded?: boolean }>;
reloadAsync: () => Promise<void>;
};
// One check per launch. No polling and deliberately no reloadAsync: never discard a form.
export function createUpdateCheck(driver: UpdateDriver, state: (value: UpdateState) => void) {
let running: Promise<void> | undefined;
return () => running ??= (async () => {
if (!driver.isEnabled) { state('disabled'); return; }
try {
state('checking');
const update = await driver.checkForUpdateAsync();
if (!update.isAvailable) { state('current'); return; }
state('downloading'); await driver.fetchUpdateAsync(); state('ready');
} catch { state('failed'); }
})();
export const updateMessages: Record<UpdateState, string> = {
disabled: '当前运行方式不支持热更新', checking: '正在检查内网更新…', current: '已是当前版本',
downloading: '正在后台下载更新,不影响操作…', ready: '更新已下载,可重启应用立即生效',
failed: '暂未连接更新服务,继续使用当前版本',
};
/** Background download; only an explicit confirmation may restart the app. */
export function createUpdateController(driver: UpdateDriver, changed: (view: UpdateView) => void,
options: { now?: () => number; active?: boolean } = {}) {
const now = options.now || Date.now;
let view: UpdateView = { state: driver.isEnabled ? 'current' : 'disabled', visible: false, restarting: false, error: '' };
let active = options.active !== false, deferred = false, disposed = false;
let lastCheck = -Infinity, inFlight: Promise<void> | undefined, reloading: Promise<void> | undefined;
function emit(patch: Partial<UpdateView>) { if (!disposed) { view = { ...view, ...patch }; changed({ ...view }); } }
function show() { if (!disposed && active && view.state === 'ready') { deferred = false; emit({ visible: true }); } }
function check(force = false): Promise<void> {
if (disposed) return Promise.resolve();
if (!driver.isEnabled) { emit({ state: 'disabled' }); return Promise.resolve(); }
if (inFlight) return inFlight;
if (view.state === 'ready') { if (force) show(); return Promise.resolve(); }
const interval = view.state === 'failed' ? 60_000 : 15 * 60_000;
if (!force && now() - lastCheck < interval) return Promise.resolve();
lastCheck = now(); emit({ state: 'checking', error: '' });
inFlight = Promise.resolve().then(async () => {
try {
if (disposed) return;
const update = await driver.checkForUpdateAsync();
if (disposed) return;
if (!update.isAvailable && !update.isRollBackToEmbedded) { emit({ state: 'current' }); return; }
emit({ state: 'downloading' });
const fetched = await driver.fetchUpdateAsync();
if (disposed) return;
if (!fetched.isNew && !fetched.isRollBackToEmbedded) { emit({ state: 'current' }); return; }
emit({ state: 'ready', visible: active && !deferred });
} catch { emit({ state: 'failed' }); }
finally { inFlight = undefined; }
});
return inFlight;
}
function foreground(value: boolean) {
if (disposed) return;
active = value;
if (!active) { if (view.visible) emit({ visible: false }); return; }
if (view.state === 'ready') { if (!deferred) show(); }
else void check();
}
function later() { if (!view.restarting) { deferred = true; emit({ visible: false, error: '' }); } }
function restart(): Promise<void> {
if (disposed || !active || !view.visible || view.state !== 'ready') return Promise.resolve();
if (reloading) return reloading;
emit({ restarting: true, error: '' });
// Success hands control to native reload; do not run application work afterwards.
reloading = Promise.resolve().then(() => { if (!disposed) return driver.reloadAsync(); }).catch(() => {
reloading = undefined;
emit({ restarting: false, error: '暂时无法重启更新,请重试,或关闭 App 后重新打开。' });
});
return reloading;
}
return { check, foreground, later, restart, dispose: () => { disposed = true; } };
}

View File

@ -1,5 +1,6 @@
import {Text} from './typography';
import React,{useEffect,useState} from 'react';
import {Alert,Modal,Platform,Text,View,type AlertButton} from 'react-native';
import {Alert,Modal,Platform,View,type AlertButton} from 'react-native';
import {Button,s,useTheme} from './ui';
type Prompt={title:string;message?:string;buttons:AlertButton[]};
let present:((prompt:Prompt)=>void)|undefined;
@ -15,5 +16,5 @@ export function PreviewDialogs(){
// its original DOM position and can sit underneath a later stock-operation Modal.
if(Platform.OS!=='web'||!prompt)return null;
function dismiss(){const cancel=prompt?.buttons.find(b=>b.style==='cancel');if(cancel){setPrompt(null);cancel.onPress?.();}}
return <Modal transparent visible={!!prompt} animationType="fade" onRequestClose={dismiss}><View style={{flex:1,backgroundColor:'rgba(10,20,35,.45)',justifyContent:'center',alignItems:'center',padding:24}}><View accessibilityRole="alert" style={{backgroundColor:t.card,borderRadius:22,padding:24,gap:18,maxWidth:380,width:'100%'}}><Text style={{color:t.text,fontSize:20,fontWeight:'700'}}>{prompt?.title}</Text><Text style={{color:t.muted,lineHeight:24}}>{prompt?.message}</Text>{prompt?.buttons.map((button,i)=><Button key={i} title={button.text||'确定'} secondary={button.style==='cancel'} onPress={()=>{setPrompt(null);button.onPress?.();}}/>)}</View></View></Modal>;
return <Modal transparent visible={!!prompt} animationType="fade" onRequestClose={dismiss}><View style={{flex:1,backgroundColor:'rgba(10,20,35,.45)',justifyContent:'center',alignItems:'center',padding:24}}><View accessibilityRole="alert" style={{backgroundColor:t.card,borderRadius:22,padding:24,gap:18,maxWidth:380,width:'100%'}}><Text style={{color:t.text,fontSize:18,fontWeight:'700'}}>{prompt?.title}</Text><Text style={{color:t.muted,lineHeight:24}}>{prompt?.message}</Text>{prompt?.buttons.map((button,i)=><Button key={i} title={button.text||'确定'} secondary={button.style==='cancel'} onPress={()=>{setPrompt(null);button.onPress?.();}}/>)}</View></View></Modal>;
}

View File

@ -1,22 +1,33 @@
import React,{useEffect,useState} from 'react';
import {ActivityIndicator,Image,Modal,Pressable,ScrollView,Text,View,useWindowDimensions} from 'react-native';
import {Text} from './typography';
import React,{useEffect,useState,useRef} from 'react';
import {ActivityIndicator,Image,Modal,PanResponder,Pressable,ScrollView,View,useWindowDimensions} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {ApiClient} from './core/network';
import {Button,Note,s,useTheme} from './ui';
function useImageResource(api:ApiClient,path:string|null){
function useImageResource(api:ApiClient,path:string|null,imageMaxBytes?:number){
const [uri,setUri]=useState<string|undefined>(),[error,setError]=useState(''),[loading,setLoading]=useState(!!path),[attempt,setAttempt]=useState(0);
useEffect(()=>{setUri(undefined);setError('');setLoading(!!path);if(!path)return;const ctl=new AbortController();void api.request<string>(path,{responseType:'image',signal:ctl.signal}).then(v=>{if(!ctl.signal.aborted)setUri(v);}).catch(e=>{if(!ctl.signal.aborted)setError(e.message);}).finally(()=>{if(!ctl.signal.aborted)setLoading(false);});return()=>ctl.abort();},[api,path,attempt]);
useEffect(()=>{setUri(undefined);setError('');setLoading(!!path);if(!path)return;const ctl=new AbortController();void api.request<string>(path,{responseType:'image',imageMaxBytes,signal:ctl.signal}).then(v=>{if(!ctl.signal.aborted)setUri(v);}).catch(e=>{if(!ctl.signal.aborted)setError(e.message);}).finally(()=>{if(!ctl.signal.aborted)setLoading(false);});return()=>ctl.abort();},[api,path,attempt,imageMaxBytes]);
return {uri,error,loading,retry:()=>setAttempt(n=>n+1)};
}
export function usePrivateImage(api:ApiClient,path:string|null){
return useImageResource(api,path).uri;
}
export function ProtectedImage({api,path,label}:{api:ApiClient;path:string;label:string}){
const t=useTheme(),{uri,loading,error,retry}=useImageResource(api,path),[open,setOpen]=useState(false),[zoom,setZoom]=useState(1),{width,height}=useWindowDimensions();
return <><Pressable accessibilityRole="button" accessibilityLabel={error?`重新加载图片:${label}`:`查看图片:${label}`} onPress={()=>{if(uri){setZoom(1);setOpen(true);}else if(error)retry();}} style={{width:118,borderWidth:1,borderColor:t.line,borderRadius:12,padding:8,gap:6}}>
export function ProtectedImage({api,path,label,maxBytes,gallery,initialIndex=0}:{api:ApiClient;path:string;label:string;maxBytes?:number;gallery?:PhotoSource[];initialIndex?:number}){
const t=useTheme(),{uri,loading,error,retry}=useImageResource(api,path,maxBytes),[open,setOpen]=useState(false);
return <><Pressable accessibilityRole="button" accessibilityLabel={error?`重新加载图片:${label}`:`查看图片:${label}`} onPress={()=>{if(uri){setOpen(true);}else if(error)retry();}} style={{width:118,borderWidth:1,borderColor:t.line,borderRadius:12,padding:8,gap:6}}>
{uri?<Image source={{uri}} style={{width:100,height:86,borderRadius:8}} resizeMode="cover"/>:<View style={{width:100,minHeight:86,alignItems:'center',justifyContent:'center',gap:6}}>{loading?<ActivityIndicator color={t.accent}/>:<Text style={{fontSize:12,color:t.muted,textAlign:'center',lineHeight:18}}>{error||'图片暂不可用'}</Text>}{!!error&&<Text style={{color:t.accent,fontSize:12}}>点击重试</Text>}</View>}
<Text style={{color:t.muted,fontSize:12}} numberOfLines={1}>{label}</Text></Pressable>
<Modal visible={open} onRequestClose={()=>setOpen(false)} animationType="fade"><SafeAreaView style={[s.fill,{backgroundColor:'#101722'}]}><View style={[s.row,{padding:14,justifyContent:'space-between'}]}><Button title="关闭预览" onPress={()=>setOpen(false)}/><Button title="缩小" secondary disabled={zoom<=1} onPress={()=>setZoom(v=>Math.max(1,v-.5))}/><Button title="放大" secondary disabled={zoom>=3} onPress={()=>setZoom(v=>Math.min(3,v+.5))}/></View><ScrollView><ScrollView horizontal>{uri&&<Image source={{uri}} resizeMode="contain" style={{width:width*zoom,height:(height-150)*zoom}}/>}</ScrollView></ScrollView></SafeAreaView></Modal>
{open&&<PhotoViewer api={api} photos={gallery?.length?gallery:[{path,label,maxBytes}]} initialIndex={initialIndex} close={()=>setOpen(false)}/>}
</>;
}
export type PhotoSource={path:string;label:string;maxBytes?:number};
function PhotoViewer({api,photos,initialIndex,close}:{api:ApiClient;photos:PhotoSource[];initialIndex:number;close:()=>void}){
const [index,setIndex]=useState(Math.max(0,Math.min(initialIndex,photos.length-1))),[zoom,setZoom]=useState(1),[position,setPosition]=useState({x:0,y:0}),{width,height}=useWindowDimensions();
const current=photos[index],{uri,error,loading,retry}=useImageResource(api,current.path,current.maxBytes),start=useRef({distance:0,zoom:1,x:0,y:0});
const didPinch=useRef(false);
const state=useRef({zoom,position,index});state.current={zoom,position,index};
useEffect(()=>{setZoom(1);setPosition({x:0,y:0});},[index]);
const responder=useRef(PanResponder.create({onStartShouldSetPanResponder:()=>true,onMoveShouldSetPanResponder:()=>true,onPanResponderGrant:event=>{const touches=event.nativeEvent.touches;didPinch.current=touches.length>1;start.current={distance:touches.length>1?Math.hypot(touches[0].pageX-touches[1].pageX,touches[0].pageY-touches[1].pageY):0,zoom:state.current.zoom,...state.current.position};},onPanResponderMove:(event,gesture)=>{const touches=event.nativeEvent.touches;if(touches.length>1){didPinch.current=true;const distance=Math.hypot(touches[0].pageX-touches[1].pageX,touches[0].pageY-touches[1].pageY);if(!start.current.distance)start.current.distance=distance;setZoom(Math.min(4,Math.max(1,start.current.zoom*distance/start.current.distance)));}else if(state.current.zoom>1)setPosition({x:start.current.x+gesture.dx,y:start.current.y+gesture.dy});},onPanResponderRelease:(_,gesture)=>{if(!didPinch.current&&state.current.zoom<=1&&Math.abs(gesture.dx)>55&&Math.abs(gesture.dx)>Math.abs(gesture.dy))setIndex(old=>Math.min(photos.length-1,Math.max(0,old+(gesture.dx<0?1:-1))));}})).current;
return <Modal visible animationType="fade" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:'#101722'}]}><View style={[s.row,{padding:12,justifyContent:'space-between'}]}><Button title="关闭预览" onPress={close}/><Text style={{color:'#fff'}}>{index+1} / {photos.length}</Text><Button title="恢复大小" secondary onPress={()=>{setZoom(1);setPosition({x:0,y:0});}}/></View><View {...responder.panHandlers} style={{flex:1,overflow:'hidden',justifyContent:'center',alignItems:'center'}}>{uri?<Image source={{uri}} resizeMode="contain" style={{width,height:height-180,transform:[{translateX:position.x},{translateY:position.y},{scale:zoom}]}}/>:loading?<ActivityIndicator color="#fff"/>:<View style={{padding:20,gap:12}}><Text style={{color:'#fff'}}>{error||'图片暂不可用'}</Text><Button title="重新加载" onPress={retry}/></View>}</View><View style={{padding:12,gap:8}}><Text style={{color:'#cbd5e1',textAlign:'center',fontSize:12}}>左右滑动切换 · 双指缩放 · 放大后拖动</Text><View style={[s.row,{justifyContent:'space-between'}]}><Button title="上一张" secondary disabled={index===0} onPress={()=>setIndex(n=>n-1)}/><Button title="放大" secondary disabled={zoom>=4} onPress={()=>setZoom(n=>Math.min(4,n+.5))}/><Button title="下一张" secondary disabled={index===photos.length-1} onPress={()=>setIndex(n=>n+1)}/></View></View></SafeAreaView></Modal>;
}

View File

@ -1,5 +1,6 @@
import {Text} from '../typography';
import React,{useEffect,useRef,useState} from 'react';
import {KeyboardAvoidingView,Platform,Pressable,ScrollView,Text,View} from 'react-native';
import {KeyboardAvoidingView,Platform,Pressable,ScrollView,View} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import {Dialog as Alert} from '../dialogs';
import {ApiClient,ApiError} from '../core/network';

View File

@ -1,16 +1,16 @@
import React from 'react';
import {View} from 'react-native';
import {Button, Note, s} from '../ui';
import {Button, Note} from '../ui';
import {arrivalActions, type ArrivalKind} from '../core/arrival-actions';
import type {Row} from '../core/modules';
export function ArrivalActions({row, permissions, queue, onOpen}: {
row: Row; permissions: string[]; queue: ArrivalKind; onOpen: (kind: ArrivalKind) => void;
export function ArrivalActions({row, permissions, queue, onOpen, onHistory}: {
row: Row; permissions: string[]; queue: ArrivalKind; onOpen: (kind: ArrivalKind) => void; onHistory?:()=>void;
}) {
const actions = arrivalActions(row, permissions, queue);
return <View style={{gap:8}}>
<View style={s.row}>{actions.map((action,index) => <Button key={action.kind} title={action.title} secondary={index>0||!action.enabled}
disabled={!action.enabled} onPress={() => {if(action.enabled) onOpen(action.kind);}}/>)}</View>
return <View style={{gap:8,width:'100%'}}>
<View style={{flexDirection:'row',alignItems:'stretch',gap:8}}>{actions.map((action,index) => <Button key={action.kind} title={action.title} secondary={index>0||!action.enabled} style={{flex:1,minWidth:0,paddingHorizontal:8}}
disabled={!action.enabled} onPress={() => {if(action.enabled) onOpen(action.kind);}}/>)}{onHistory&&<Button title="到货记录" secondary style={{flex:1,minWidth:0,paddingHorizontal:8}} onPress={onHistory}/>}</View>
{[...new Set(actions.map(action => action.reason).filter(Boolean))].map(reason => <Note key={reason}>{reason}</Note>)}
</View>;
}

View File

@ -1,5 +1,6 @@
import {Text,TextInput} from '../typography';
import React from 'react';
import {ActivityIndicator,Pressable,Text,TextInput,View,useWindowDimensions} from 'react-native';
import {ActivityIndicator,Pressable,View,useWindowDimensions} from 'react-native';
import {Card,Icon,useTheme} from '../ui';
import {display,type Row} from '../core/modules';
import type {ArrivalKind} from '../core/arrival-actions';
@ -10,26 +11,26 @@ export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,rese
busy:boolean;search:()=>void;reset:()=>void;total:number;page:number;
}){
const t=useTheme();
return <View style={{paddingHorizontal:18,paddingTop:8,paddingBottom:8,gap:8}}>
return <View style={{paddingHorizontal:14,paddingTop:8,paddingBottom:8,gap:8}}>
<View accessibilityRole="tablist" style={{flexDirection:'row',padding:4,borderRadius:12,backgroundColor:t.soft,gap:4}}>
{([['arrival','待登记到货'],['accept','待验收']] as const).map(([key,label])=><Pressable key={key} accessibilityRole="tab" accessibilityLabel={label}
accessibilityState={{selected:queue===key,disabled:busy}} disabled={busy} onPress={()=>setQueue(key)}
style={{flex:1,minHeight:44,paddingVertical:9,paddingHorizontal:6,borderRadius:9,alignItems:'center',justifyContent:'center',backgroundColor:queue===key?t.card:'transparent'}}>
<Text style={{color:queue===key?t.accent:t.muted,fontSize:15,lineHeight:22,fontWeight:queue===key?'700':'500',textAlign:'center'}}>{label}</Text>
<Text style={{color:queue===key?t.accent:t.muted,fontSize:14,lineHeight:22,fontWeight:queue===key?'700':'500',textAlign:'center'}}>{label}</Text>
</Pressable>)}
</View>
<View style={{flexDirection:'row',alignItems:'center',gap:8}}>
<View style={{flex:1,minWidth:0,flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:t.line,borderRadius:10,backgroundColor:t.card,paddingLeft:11}}>
<Icon name="search-outline" size={18} color={t.muted}/>
<TextInput accessibilityLabel="名称或关键词" placeholder="搜索物品、规格或品牌" placeholderTextColor={t.muted} value={query} onChangeText={setQuery}
onSubmitEditing={search} returnKeyType="search" autoCorrect={false} style={{flex:1,minWidth:0,minHeight:46,paddingHorizontal:9,color:t.text,fontSize:16}}/>
onSubmitEditing={search} returnKeyType="search" autoCorrect={false} style={{flex:1,minWidth:0,minHeight:46,paddingHorizontal:9,color:t.text,fontSize:14}}/>
{!!query&&<Pressable accessibilityRole="button" accessibilityLabel="清除搜索" disabled={busy} onPress={reset} style={{padding:12}}><Icon name="close-circle" size={18} color={t.muted}/></Pressable>}
</View>
<Pressable accessibilityRole="button" accessibilityLabel="查询" accessibilityState={{disabled:busy}} disabled={busy} onPress={search} style={{minHeight:46,minWidth:54,paddingHorizontal:12,justifyContent:'center',alignItems:'center',borderRadius:10,backgroundColor:t.accent}}>
{busy?<ActivityIndicator color={t.onAccent}/>:<Text style={{color:t.onAccent,fontWeight:'600',fontSize:15,lineHeight:22}}>查询</Text>}
{busy?<ActivityIndicator color={t.onAccent}/>:<Text style={{color:t.onAccent,fontWeight:'600',fontSize:14,lineHeight:22}}>查询</Text>}
</Pressable>
</View>
<Text accessibilityLiveRegion="polite" style={{color:t.muted,fontSize:13,lineHeight:18}}>{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}</Text>
<Text accessibilityLiveRegion="polite" style={{color:t.muted,fontSize:12,lineHeight:18}}>{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}</Text>
</View>;
}
@ -38,20 +39,20 @@ export function ArrivalCard({item,queue,children}:{item:Row;queue:ArrivalKind;ch
const {width,fontScale}=useWindowDimensions(),layout=arrivalLayout(width,fontScale);
return <Card style={{padding:14,gap:10}}>
<View style={{flexDirection:layout.stackedHeader?'column':'row',alignItems:layout.stackedHeader?'stretch':'flex-start',gap:8}}>
<View style={{flex:layout.stackedHeader?undefined:1,minWidth:0,gap:4}}><Text selectable style={{color:t.text,fontSize:17,fontWeight:'700',lineHeight:24}}>{display(item.materialName)}</Text>
<View style={{flex:layout.stackedHeader?undefined:1,minWidth:0,gap:4}}><Text selectable style={{color:t.text,fontSize:16,fontWeight:'700',lineHeight:24}}>{display(item.materialName)}</Text>
<Text selectable style={{color:t.muted,fontSize:14,lineHeight:20}}>{display(item.materialParams)}</Text>
</View>
<View style={{flexDirection:layout.stackedHeader?'row':'column',justifyContent:'space-between',alignItems:layout.stackedHeader?'center':'flex-end',flexShrink:0,gap:2,...(!layout.stackedHeader?{minWidth:78,maxWidth:130}:{})}}>
<Text style={{color:t.muted,fontSize:13,lineHeight:20}}>{queue==='accept'?'待验收':'待登记'}</Text>
<Text style={{color:t.muted,fontSize:12,lineHeight:20}}>{queue==='accept'?'待验收':'待登记'}</Text>
<View style={{flexDirection:'row',alignItems:'baseline',justifyContent:'flex-end',flexShrink:1,gap:5}}>
<Text selectable adjustsFontSizeToFit minimumFontScale={0.85} numberOfLines={1} style={{color:t.accent,fontSize:22,lineHeight:28,fontWeight:'700',flexShrink:1}}>{display(item[key])}</Text>
<Text selectable adjustsFontSizeToFit minimumFontScale={0.85} numberOfLines={1} style={{color:t.accent,fontSize:20,lineHeight:26,fontWeight:'700',flexShrink:1}}>{display(item[key])}</Text>
<Text style={{color:t.muted,fontSize:14,lineHeight:20,flexShrink:1,textAlign:'right'}}>{display(item.unit)}</Text>
</View>
</View>
</View>
<View style={{gap:6}}>{[['projectName','项目'],['purchaseBatchNo','采购批次'],['supplierName','供应商']].map(([field,label])=><View key={field} style={{flexDirection:layout.stackedDetails?'column':'row',alignItems:layout.stackedDetails?'stretch':'flex-start',gap:layout.stackedDetails?2:8}}>
<Text style={{...(!layout.stackedDetails?{width:layout.labelWidth}:{}),color:t.muted,fontSize:13,lineHeight:22,flexShrink:0}}>{label}</Text><Text selectable style={{...(!layout.stackedDetails?{flex:1}:{}),minWidth:0,color:t.text,fontSize:15,lineHeight:22}}>{display(item[field])}</Text>
<Text style={{...(!layout.stackedDetails?{width:layout.labelWidth}:{}),color:t.muted,fontSize:12,lineHeight:22,flexShrink:0}}>{label}</Text><Text selectable style={{...(!layout.stackedDetails?{flex:1}:{}),minWidth:0,color:t.text,fontSize:14,lineHeight:22}}>{display(item[field])}</Text>
</View>)}</View>
<View style={{alignItems:'flex-end'}}>{children}</View>
<View style={{alignItems:'stretch'}}>{children}</View>
</Card>;
}

View File

@ -6,48 +6,67 @@ import {SafeAreaView} from 'react-native-safe-area-context';
import * as Crypto from 'expo-crypto';
import {ApiClient} from '../core/network';
import {display,localDate,validDate,type Row} from '../core/modules';
import {Button,Card,Choice,Field,Heading,Note,s,useTheme} from '../ui';
import {Button,Card,Choice,DateField,Field,Heading,Note,s,useTheme} from '../ui';
import {Dialog as Alert} from '../dialogs';
import {useOperationDraft} from '../hooks/useOperationDraft';
export function ArrivalOperation({api,row,mode,close,done}:{api:ApiClient;row:Row;mode:'arrival'|'accept';close:()=>void;done:()=>void}){
export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;row:Row;mode:'arrival'|'accept';close:()=>void;done:()=>void;scope?:string}){
const t=useTheme(),accept=mode==='accept',lock=useRef(false),alive=useRef(true),requestKey=useRef(Crypto.randomUUID());
const [quantity,setQuantity]=useState(''),[date,setDate]=useState(localDate()),[remark,setRemark]=useState('');
const [records,setRecords]=useState<Row[]>([]),[record,setRecord]=useState<Row|null>(null),[loading,setLoading]=useState(accept);
const [preview,setPreview]=useState<Row|null>(null),[busy,setBusy]=useState(false),[attempted,setAttempted]=useState(false),[error,setError]=useState('');
const [photos,setPhotos]=useState<Row[]>([]),[photosPending,setPhotosPending]=useState(false);
const [checkingPhotos,setCheckingPhotos]=useState(false);
const restoredRecord=useRef<number|null>(null);
const snapshot={quantity,date,remark,record,preview,attempted,photos,requestKey:requestKey.current};
const draft=useOperationDraft({scope,kind:mode,id:row.id,value:snapshot,hasContent:v=>!!(v.quantity||v.remark||v.photos.length||v.preview),isPending:v=>v.attempted,onRestore:v=>{
setQuantity(String(v.quantity||''));setDate(String(v.date||localDate()));setRemark(String(v.remark||''));setRecord(v.record||null);restoredRecord.current=v.record?.id??null;
setPreview(v.attempted?v.preview:null);setAttempted(v.attempted===true);requestKey.current=v.requestKey||requestKey.current;
const restoredPhotos:Row[]=(v.photos||[]).slice(0,9).map(p=>p.id?{...p,uri:undefined}:{...p,uri:undefined,error:'照片未完成上传,请移除后重新选择'});
setPhotos(restoredPhotos);
if(!accept&&!v.attempted&&restoredPhotos.some(p=>p.id)){
setCheckingPhotos(true);void(async()=>{const checked=[];for(const photo of restoredPhotos){if(!photo.id){checked.push(photo);continue;}try{await api.request(`/warehouse/purchase/arrival/photos/${photo.id}/content`,{responseType:'image',imageMaxBytes:20*1024*1024});checked.push({...photo,error:''});}catch{checked.push({...photo,error:'照片已失效或暂时无法读取,请移除后重新上传'});}}if(alive.current){setPhotos(checked);setCheckingPhotos(false);}})();
}
if(v.attempted)setError('已恢复上次提交,请先核对结果,再决定是否重试原请求。');
}});
useEffect(()=>{alive.current=true;const controller=new AbortController();
if(accept)void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:controller.signal}).then(result=>{if(alive.current){const pending=(result.data||[]).filter((r:Row)=>Number(r.acceptanceStatus)===0).map((r:Row)=>({...r,label:`${r.arrivalNo} · ${r.arrivalQuantity} ${row.unit||''} · ${formatDateTime(r.arrivalDate)}`}));setRecords(pending);if(pending.length===1)setRecord(pending[0]);}}).catch(e=>{if(alive.current&&!controller.signal.aborted)setError((e as Error).message);}).finally(()=>{if(alive.current)setLoading(false);});
if(accept)void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:controller.signal}).then(result=>{if(alive.current){const pending=(result.data||[]).filter((r:Row)=>Number(r.acceptanceStatus)===0).map((r:Row)=>({...r,label:`${r.arrivalNo} · ${r.arrivalQuantity} ${row.unit||''} · ${formatDateTime(r.arrivalDate)}`}));setRecords(pending);if(!restoredRecord.current&&pending.length===1)setRecord(pending[0]);}}).catch(e=>{if(alive.current&&!controller.signal.aborted)setError((e as Error).message);}).finally(()=>{if(alive.current)setLoading(false);});
return()=>{alive.current=false;controller.abort();};},[api,row.id,accept]);
function prepare(){
if(!draft.ready||checkingPhotos)return;
if(!accept&&photosPending)return setError('有照片尚未上传完成,请重试或移除后继续。');
const amount=Number(quantity||'0');
if(!/^\d+(\.\d{1,4})?$/.test(quantity||'0')||!Number.isFinite(amount)||(accept?amount<0:amount<=0))return setError(accept?'请填写不合格数量,允许为 0,最多 4 位小数。':'请填写大于 0 的到货数量,最多 4 位小数。');
if(accept&&!record)return setError('请选择本次验收的到货记录。');
if(accept&&!records.some(r=>r.id===record?.id))return setError('该到货记录已不在待验收列表,请重新选择。');
if(amount>Number(accept?record?.arrivalQuantity:row.remainingQuantity))return setError(accept?'不合格数量不能超过本次到货数量。':'数量超过当前剩余可登记到货数量。');
if(!accept&&!validDate(date))return setError('请填写有效到货日期。');
setError('');setPreview(accept?{id:record!.id,body:{acceptanceStatus:1,defectiveQuantity:amount,acceptanceRemark:remark}}:{body:{purchaseRequestId:row.id,arrivalQuantity:amount,arrivalDate:date,remark,requestKey:requestKey.current,photoIds:photos.map(p=>p.id)}});
}
async function submit(){if(lock.current||!preview||accept&&attempted)return;lock.current=true;setBusy(true);setAttempted(true);setError('');
try{await api.request(accept?`/warehouse/purchase/arrival/${preview.id}/accept`:'/warehouse/purchase/arrival',{method:accept?'PUT':'POST',body:preview.body});if(alive.current)done();}
async function submit(){if(lock.current||!preview||!draft.ready||accept&&attempted)return;lock.current=true;setBusy(true);setError('');
try{await draft.saveNow({...snapshot,attempted:true});setAttempted(true);await api.request(accept?`/warehouse/purchase/arrival/${preview.id}/accept`:'/warehouse/purchase/arrival',{method:accept?'PUT':'POST',body:preview.body});await draft.clear();if(alive.current)done();}
catch(e){if(alive.current)setError((e as Error).message+(accept?' 请返回列表刷新到货记录,核对是否已经验收;不会自动重发。':' 请先核对到货记录。重试仅发送相同内容与请求标识,不会新建另一请求。'));}
finally{lock.current=false;if(alive.current)setBusy(false);}
}
function requestClose(){if(busy)return;if(preview||quantity||remark||photos.length)Alert.alert('结束本次填写?',attempted?'请先到到货记录核对处理结果。':'未提交内容不会写入业务。',[{text:'继续核对',style:'cancel'},{text:'关闭',onPress:close}]);else close();}
async function checkResult(){if(lock.current)return;lock.current=true;setBusy(true);try{const response=await api.request<Row>(`/warehouse/purchase/arrival/${row.id}`),items=response.data||[];const saved=accept?items.find((v:Row)=>v.id===preview?.id&&Number(v.acceptanceStatus)!==0):items.find((v:Row)=>v.requestKey===requestKey.current);if(saved){await draft.clear();done();}else setError(accept?'当前记录仍为待验收。请稍后刷新核对,避免重复操作。':'暂未查到本次登记,可继续用原请求重试。');}catch(e){setError((e as Error).message);}finally{lock.current=false;setBusy(false);}}
function requestClose(){if(busy)return;if(preview||quantity||remark||photos.length)Alert.alert('保留填写并返回?',attempted?'将保留原提交内容,下次继续核对结果。':'内容将保存在当前账号的本机草稿中,尚未提交业务。',[{text:'继续填写',style:'cancel'},{text:'保留并返回',onPress:()=>{void draft.saveNow().then(close).catch(()=>{});}}]);else close();}
const title=accept?'验收到货':'登记到货';
return <Modal visible animationType="slide" onRequestClose={requestClose}><SafeAreaView style={[s.fill,{backgroundColor:t.bg,width:'100%',maxWidth:Platform.OS==='web'?480:undefined,alignSelf:'center'}]}><KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}>
<View style={{paddingHorizontal:18,paddingVertical:10,flexDirection:'row',alignItems:'center',justifyContent:'space-between',borderBottomWidth:1,borderColor:t.line}}><Heading>{title}</Heading><Button title="关闭" secondary disabled={busy} onPress={requestClose}/></View>
<ScrollView style={s.fill} keyboardShouldPersistTaps="handled" contentContainerStyle={[s.page,{paddingBottom:18}]}>
<Note>{display(row.materialName)} · {display(row.materialParams)} · {display(row.unit)}</Note><Note>{display(row.projectName)} · {display(row.purchaseBatchNo)}</Note>
{!draft.ready&&<Note>{draft.error||'正在读取本机草稿…'}</Note>}{!!draft.error&&draft.ready&&<Note>{draft.error}</Note>}{draft.restored&&!attempted&&<Note>已恢复上次填写,请核对本次数量和照片。</Note>}{checkingPhotos&&<Note>正在核对草稿照片…</Note>}
{loading&&<Note>正在获取最新待验收到货记录…</Note>}
{!preview?<>
{accept?<><Choice label="到货记录" items={records} value={record} onChange={setRecord} nameKey="label"/>{!loading&&!records.length&&<Note>暂无待验收记录。尚未登记的货物,请先返回选择“登记到货”。</Note>}<Note>本次到货:{display(record?.arrivalQuantity)} {display(row.unit)};合格数量将按到货数量减去不合格数量计算。</Note></>:<><Note>剩余可登记:{display(row.remainingQuantity)} {display(row.unit)}</Note><Button title="本次全部到齐" secondary onPress={()=>setQuantity(String(row.remainingQuantity))}/><Field label="到货日期(YYYY-MM-DD)" value={date} onChange={setDate}/></>}
{accept?<><Choice label="到货记录" items={records} value={record} onChange={setRecord} nameKey="label"/>{!loading&&!records.length&&<Note>暂无待验收记录。尚未登记的货物,请先返回选择“登记到货”。</Note>}<Note>本次到货:{display(record?.arrivalQuantity)} {display(row.unit)};合格数量将按到货数量减去不合格数量计算。</Note></>:<><Note>剩余可登记:{display(row.remainingQuantity)} {display(row.unit)}</Note><Button title="本次全部到齐" secondary onPress={()=>setQuantity(String(row.remainingQuantity))}/><DateField label="到货日期" value={date} onChange={setDate}/></>}
<Field label={accept?'不合格数量(0 表示全部合格)':'本次到货数量'} value={quantity} onChange={setQuantity} keyboard="decimal-pad"/><Field label={accept?'验收说明':'到货备注'} value={remark} onChange={setRemark} multiline/>
</>:<Card><Heading>请核对本次{title}</Heading>{accept?<><Note>到货单:{display(record?.arrivalNo)}</Note><Note>到货数量:{display(record?.arrivalQuantity)} {display(row.unit)}</Note><Note>合格数量:{Number(record?.arrivalQuantity)-Number(preview.body.defectiveQuantity)} {display(row.unit)}</Note><Note>不合格数量:{preview.body.defectiveQuantity} {display(row.unit)}</Note><Note>验收合格后进入待入库,尚不会增加库存。</Note></>:<><Note>到货数量:{preview.body.arrivalQuantity} {display(row.unit)}</Note><Note>到货日期:{formatDateTime(preview.body.arrivalDate)}</Note><Note>本次仅登记到货,之后再办理验收。</Note></>}
<Note>说明:{remark||'无'}</Note>
</Card>}
<ArrivalPhotos api={api} requestId={row.id} photos={accept?(record?.photos||[]):photos} onChange={setPhotos} onPending={setPhotosPending} readonly={accept||!!preview} disabled={busy||attempted}/>
<ArrivalPhotos api={api} requestId={row.id} photos={accept?(record?.photos||[]):photos} onChange={setPhotos} onPending={setPhotosPending} readonly={accept||!!preview} disabled={busy||attempted||checkingPhotos||!draft.ready}/>
{!!error&&<Note>{error}</Note>}
{attempted&&<Button title="核对提交结果" secondary busy={busy} onPress={()=>void checkResult()}/>}
</ScrollView><View style={{padding:14,borderTopWidth:1,borderColor:t.line,backgroundColor:t.card}}>
{!preview?<Button title="核对预览" disabled={loading||photosPending||accept&&!record} onPress={prepare}/>:<View style={{flexDirection:'row',gap:10}}><View style={{flex:1}}><Button title="返回修改" secondary disabled={busy||attempted} onPress={()=>setPreview(null)}/></View><View style={{flex:1}}><Button title={attempted?'核对后重试原请求':'确认提交'} busy={busy} disabled={accept&&attempted} onPress={()=>void submit()}/></View></View>}
{!preview?<Button title="核对预览" disabled={!draft.ready||checkingPhotos||loading||photosPending||accept&&!record} onPress={prepare}/>:<View style={{flexDirection:'row',gap:10}}><View style={{flex:1}}><Button title="返回修改" secondary disabled={busy||attempted} onPress={()=>setPreview(null)}/></View><View style={{flex:1}}><Button title={attempted?'核对后重试原请求':'确认提交'} busy={busy} disabled={!draft.ready||accept&&attempted} onPress={()=>void submit()}/></View></View>}
</View></KeyboardAvoidingView></SafeAreaView></Modal>;
}

View File

@ -1,10 +1,10 @@
import React,{useEffect,useRef,useState} from 'react';
import {Image,Platform,View} from 'react-native';
import {Image,Platform,Pressable,View} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as Crypto from 'expo-crypto';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import {Button,Note,s} from '../ui';
import {Button,Icon,Note,s} from '../ui';
import {ProtectedImage} from '../files';
export function ArrivalPhotos({api,requestId,photos,onChange,onPending,readonly=false,disabled=false}:{api:ApiClient;requestId:number;photos:Row[];onChange?:(photos:Row[])=>void;onPending?:(pending:boolean)=>void;readonly?:boolean;disabled?:boolean}){
@ -33,7 +33,7 @@ export function ArrivalPhotos({api,requestId,photos,onChange,onPending,readonly=
if(result.canceled||!alive.current)return;
const asset=result.assets[0],type=asset.mimeType||'image/jpeg';
if(!['image/jpeg','image/png','image/webp'].includes(type)){setError('请选择 JPG、PNG 或 WebP 照片。');return;}
if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>5*1024*1024)){setError('每张照片不能超过5MB,请降低照片大小或重新拍摄。');return;}
if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>20*1024*1024)){setError('每张照片不能超过20MB,请降低照片大小或重新拍摄。');return;}
const extension=type==='image/png'?'png':type==='image/webp'?'webp':'jpg';
photo={clientKey:Crypto.randomUUID(),name:`arrival-${Date.now()}.${extension}`,contentType:type,uri:asset.uri};update([...current.current,photo]);
}catch(e){if(alive.current)setError((e as Error).message||'无法获取照片,请重试。');}
@ -46,11 +46,11 @@ export function ArrivalPhotos({api,requestId,photos,onChange,onPending,readonly=
catch(e){if(alive.current)setError((e as Error).message);}
finally{locked.current=false;if(alive.current)setWorking(false);}
}
return <View style={{gap:10}}><Note>到货照片{readonly?` · ${photos.length} 张`:`(选传)· ${photos.length}/9 · 每张不超过5MB`}</Note>
return <View style={{gap:10}}><Note>到货照片{readonly?` · ${photos.length} 张`:`(选传)· ${photos.length}/9 · 每张不超过20MB`}</Note>
{!readonly&&<View style={s.row}>{Platform.OS!=='web'&&<Button title="拍照" disabled={disabled||working||photos.length>=9} onPress={()=>void choose(true)}/>}<Button title={Platform.OS==='web'?'上传图片':'从相册选择'} secondary disabled={disabled||working||photos.length>=9} onPress={()=>void choose(false)}/></View>}
<View style={[s.row,{alignItems:'flex-start'}]}>{photos.map((photo,index)=><View key={photo.clientKey||photo.id} style={{width:120,gap:5}}>{photo.id?<ProtectedImage api={api} path={`/warehouse/purchase/arrival/photos/${photo.id}/content`} label={`到货照片 ${index+1}`}/>:photo.uri?<Image source={{uri:photo.uri}} style={{width:118,height:100,borderRadius:10}}/>:null}
<View style={[s.row,{alignItems:'flex-start'}]}>{photos.map((photo,index)=><View key={photo.clientKey||photo.id} style={{width:120,gap:5}}>{photo.id?<ProtectedImage api={api} path={`/warehouse/purchase/arrival/photos/${photo.id}/content`} label={`到货照片 ${index+1}`} maxBytes={20*1024*1024} gallery={photos.filter(p=>p.id).map((p,i)=>({path:`/warehouse/purchase/arrival/photos/${p.id}/content`,label:`到货照片 ${i+1}`,maxBytes:20*1024*1024}))} initialIndex={photos.filter(p=>p.id).findIndex(p=>p.id===photo.id)}/>:photo.uri?<Image source={{uri:photo.uri}} style={{width:118,height:100,borderRadius:10}}/>:null}
{!!photo.error&&<><Note>{photo.error}</Note><Button title="重试上传" secondary disabled={disabled||working} onPress={()=>void upload(photo)}/></>}
{!readonly&&<Button title={`移除第${index+1}张`} secondary disabled={disabled||working} onPress={()=>void remove(photo)}/>}</View>)}</View>
{!readonly&&<Pressable accessibilityRole="button" accessibilityLabel={`移除第${index+1}张`} disabled={disabled||working} onPress={()=>void remove(photo)} style={{position:'absolute',top:0,right:0,minWidth:44,minHeight:44,alignItems:'center',justifyContent:'center'}}><View style={{backgroundColor:'#fff',borderRadius:12}}><Icon name="close-circle" color="#b42335" size={23}/></View></Pressable>}</View>)}</View>
{working&&<Note>正在处理照片,请稍候…</Note>}{!!error&&<Note>{error}</Note>}{readonly&&!photos.length&&<Note>本次到货未上传照片</Note>}
</View>;
}

View File

@ -1,5 +1,7 @@
import {Text,TextInput} from '../typography';
import {draftReviewEntries,incompleteRecipientReview,reviewComplete,type ReviewEntry} from '../core/draft-review';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ActivityIndicator, Image, KeyboardAvoidingView, Platform, Pressable, ScrollView, Text, View } from 'react-native';
import { ActivityIndicator, Image, KeyboardAvoidingView, Platform, Pressable, ScrollView, View } from 'react-native';
import { Dialog as Alert } from '../dialogs';
import * as DocumentPicker from 'expo-document-picker';
import { ApiClient } from '../core/network';
@ -13,6 +15,7 @@ export function Assistant({api}:{api:ApiClient}){
const inspectHistory=()=>{followLatest.current=false;};
const [session,setSession]=useState<Row|null>(null),[text,setText]=useState(''),[files,setFiles]=useState<Row[]>([]);
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[uncertain,setUncertain]=useState(false),[pending,setPending]=useState<Row|null>(null),[seconds,setSeconds]=useState(0);
const [composerHeight,setComposerHeight]=useState(42);
const [attachmentPhase,setAttachmentPhase]=useState<'selecting'|'uploading'|null>(null);
const refresh=useCallback(async()=>{if(lock.current)return;lock.current=true;setBusy(true);try{const data=await api.request<Row>(`${root}/session`);if(alive.current){followLatest.current=true;setSession(data.data);setUncertain(Boolean(data.data.processing));setError('');setPending(null);}}
catch(e){if(alive.current)setError((e as Error).message);}finally{lock.current=false;if(alive.current)setBusy(false);}},[api]);
@ -43,7 +46,7 @@ export function Assistant({api}:{api:ApiClient}){
finally{lock.current=false;if(alive.current)setBusy(false);}}
async function newConversation(){if(lock.current||uncertain)return;lock.current=true;setBusy(true);setError('');try{const data=await api.request<Row>(`${root}/session/new`,{method:'POST'});if(alive.current){setSession(data.data);setPending(null);setText('');setFiles([]);setUncertain(Boolean(data.data.processing));}}catch(e){if(alive.current){setError((e as Error).message);setUncertain(true);}}finally{lock.current=false;if(alive.current)setBusy(false);}}
return <KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}>
<View style={[s.row,{paddingHorizontal:18,paddingBottom:10,justifyContent:'space-between'}]}><Text style={{color:t.muted,fontSize:11}}>查询即返回 · 操作先确认</Text><Pressable accessibilityRole="button" accessibilityLabel="开启新对话" disabled={busy||uncertain||!session} onPress={()=>Alert.alert('开启新对话','将开始新的对话,未发送的文字和附件会清空。已办理的业务不受影响。',[{text:'继续当前对话',style:'cancel'},{text:'新对话',onPress:()=>void newConversation()}])} style={{padding:9,flexDirection:'row',gap:5,opacity:busy||uncertain?.5:1}}><Icon name="create-outline" size={17}/><Text style={{color:t.accent,fontSize:12}}>新对话</Text></Pressable></View>
<View style={[s.row,{paddingHorizontal:14,paddingBottom:10,justifyContent:'space-between'}]}><Text style={{color:t.muted,fontSize:11}}>查询即返回 · 操作先确认</Text><Pressable accessibilityRole="button" accessibilityLabel="开启新对话" disabled={busy||uncertain||!session} onPress={()=>Alert.alert('开启新对话','将开始新的对话,未发送的文字和附件会清空。已办理的业务不受影响。',[{text:'继续当前对话',style:'cancel'},{text:'新对话',onPress:()=>void newConversation()}])} style={{padding:9,flexDirection:'row',gap:5,opacity:busy||uncertain?.5:1}}><Icon name="create-outline" size={17}/><Text style={{color:t.accent,fontSize:12}}>新对话</Text></Pressable></View>
<ScrollView ref={scroll} contentContainerStyle={s.page} keyboardShouldPersistTaps="handled" onContentSizeChange={()=>{if(followLatest.current)scroll.current?.scrollToEnd({animated:true});}}>
{!session?.messages?.length&&<View style={{paddingTop:18,gap:18}}><Image source={require('../../assets/assistant.png')} style={{width:66,height:66,borderRadius:22}}/><Text style={{fontSize:27,fontWeight:'700',lineHeight:38,color:t.text}}>把需求告诉我,{ '\n' }我们一起完成。</Text><Note>不知道从哪里开始也没关系。先说一部分,我会帮你核对,缺少的信息可以接着补充。</Note><View style={{gap:10}}>{['帮我查一下库存','我要登记到货,该怎么做?','我想借用物资'].map(prompt=><Pressable key={prompt} accessibilityRole="button" accessibilityLabel={prompt} disabled={busy||uncertain} onPress={()=>setText(prompt)} style={{padding:15,borderRadius:14,borderWidth:1,borderColor:t.line,backgroundColor:t.card,flexDirection:'row',alignItems:'center',gap:12}}><Icon name="sparkles-outline" size={17}/><Text style={{flex:1,color:t.text,fontSize:14}}>{prompt}</Text><Icon name="arrow-up-outline" size={16}/></Pressable>)}</View></View>}
{[...(session?.messages||[]),...(pending?[pending]:[])].map((message:Row,i:number)=><View key={message.id||`pending-${i}`} style={{gap:10}}>
@ -51,49 +54,62 @@ export function Assistant({api}:{api:ApiClient}){
<View style={{alignSelf:message.role==='user'?'flex-end':'stretch',maxWidth:message.role==='user'?'92%':'100%',backgroundColor:message.role==='user'?t.soft:t.card,padding:15,borderRadius:16,borderTopRightRadius:message.role==='user'?4:16,borderTopLeftRadius:message.role==='user'?16:4,borderWidth:1,borderColor:t.line,gap:10}}><Text selectable style={{color:t.text,lineHeight:24}}>{message.content}</Text>{message.attachments?.map((f:Row)=>f.type==='image'?<ProtectedImage key={f.id} api={api} path={`${root}/attachments/${encodeURIComponent(f.id)}/content`} label={f.name}/>:<Note key={f.id}>{f.name}</Note>)}</View>
{message.query?.errors?.map((e:string,j:number)=><Note key={j}>{e}</Note>)}
{message.query?.results?.map((result:Row,j:number)=><Results key={j} data={result.data} title={result.title} onInspect={inspectHistory}/>)}
{message.draft&&<DraftCard draft={message.draft} currentId={session?.draft?.id} busy={busy||uncertain} onAction={draftAction} onInspect={inspectHistory}/>}
{message.draft&&<DraftCard key={String(message.draft.id)+':'+String(message.draft.version)} draft={message.draft} currentId={session?.draft?.id} busy={busy||uncertain} onAction={draftAction} onInspect={inspectHistory}/>}
</View>)}
{busy&&<View style={[s.row,{paddingVertical:10}]}><ActivityIndicator color={t.accent}/><Note>{attachmentPhase==='selecting'?'请在文件选择窗口中选择附件':attachmentPhase==='uploading'?'正在上传附件并读取文件信息':session?'正在核对你的需求':'正在读取权限和最近对话'} · {seconds} 秒</Note></View>}
{!!error&&<Note>{error}</Note>}{(uncertain||session?.processing)&&<Note>上一项结果尚待核对。请刷新状态,确认处理已结束后继续。</Note>}
{!!(uncertain||session?.processing||(!session&&error))&&<Button title="刷新处理状态" secondary disabled={busy} onPress={()=>void refresh()}/>}
</ScrollView>
<View style={[s.page,{paddingTop:12,paddingBottom:12,borderTopWidth:1,borderColor:t.line,backgroundColor:t.card}]}>
{!!files.length&&<ScrollView style={{maxHeight:170}}>{files.map(f=><View key={f.id} style={{gap:6}}><Note>{f.name}</Note>{f.type==='excel'&&(f.sheets||[]).map((sheet:Row)=><Button key={sheet.index}
<View style={[s.page,{paddingTop:8,paddingBottom:8,borderTopWidth:1,borderColor:t.line,backgroundColor:t.card}]}>
{!!files.length&&<ScrollView style={{maxHeight:120}}>{files.map(f=><View key={f.id} style={{gap:6}}><Note>{f.name}</Note>{f.type==='excel'&&(f.sheets||[]).map((sheet:Row)=><Button key={sheet.index}
title={`${f.selectedSheetIndexes.includes(sheet.index)?'✓ ':''}${sheet.name}(${sheet.rowCount} 行)`} secondary disabled={busy||uncertain}
onPress={()=>{setError('');setFiles(old=>old.map(v=>v.id!==f.id?v:{...v,selectedSheetIndexes:v.selectedSheetIndexes.includes(sheet.index)?v.selectedSheetIndexes.filter((n:number)=>n!==sheet.index):[...v.selectedSheetIndexes,sheet.index]}));}}/>)}</View>)}</ScrollView>}
{!!files.length&&<Button title="移除待发送附件" secondary disabled={busy||uncertain} onPress={()=>{setFiles([]);setError('');}}/>}
<Field label="描述需求或继续补充" value={text} onChange={setText} multiline disabled={busy||uncertain}/>
<TextInput accessibilityLabel="描述需求或继续补充" placeholder="描述需求或继续补充…" placeholderTextColor={t.muted} value={text} onChangeText={setText} multiline editable={!busy&&!uncertain} onContentSizeChange={e=>setComposerHeight(Math.min(110,Math.max(42,e.nativeEvent.contentSize.height+12)))} style={{height:composerHeight,borderWidth:1,borderColor:t.line,borderRadius:10,paddingHorizontal:10,paddingVertical:8,fontSize:14,color:t.text,backgroundColor:t.bg}}/>
<View style={[s.row,{justifyContent:'space-between'}]}><Pressable accessibilityRole="button" accessibilityLabel="添加图片、表格或文件" disabled={busy||uncertain||files.length>=3} onPress={()=>void attach()} style={[s.row,{padding:8,opacity:busy||uncertain?.5:1}]}><Icon name="add-circle-outline"/><Text style={{color:t.muted,fontSize:12}}>图片 / 表格</Text></Pressable><Button title="发送 ↑" busy={busy} disabled={!session||uncertain||session.processing||(!text.trim()&&!files.length)} onPress={()=>void send()}/></View>
</View>
</KeyboardAvoidingView>;
}
function DraftCard({draft,currentId,busy,onAction,onInspect}:{draft:Row;currentId:unknown;busy:boolean;onAction:(draft:Row,operation:'execute'|'cancel')=>Promise<void>;onInspect:()=>void}){
const t=useTheme(),[historyOpen,setHistoryOpen]=useState(false),active=isActiveDraft(draft,currentId),expanded=active||historyOpen,outcome=draftOutcome(draft),reviewCount=draftReviewCount(draft);
const t=useTheme(),[historyOpen,setHistoryOpen]=useState(false),[page,setPage]=useState(0),[checked,setChecked]=useState<number[]>([]);
const active=isActiveDraft(draft,currentId),expanded=active||historyOpen,outcome=draftOutcome(draft),reviewCount=draftReviewCount(draft),entries=draftReviewEntries(draft),pages=Math.max(1,Math.ceil(entries.length/20));
const complete=reviewComplete(pages,checked),missingRecipients=incompleteRecipientReview(draft);
useEffect(()=>{setPage(0);setChecked([]);},[draft.id,draft.version]);
function changePage(next:number){onInspect();setPage(next);}
return <Card>{active?<Heading>{draft.label}</Heading>:<Pressable accessibilityRole="button" accessibilityLabel={`${historyOpen?'收起':'查看'}历史确认单:${draft.label}`} accessibilityState={{expanded:historyOpen}} onPress={()=>{onInspect();setHistoryOpen(v=>!v);}} style={[s.row,{justifyContent:'space-between'}]}><Text style={{color:t.text,fontWeight:'600',flex:1}}>{draft.label}</Text><Text style={{color:t.accent,fontSize:12}}>{historyOpen?'收起':'查看详情'}</Text></Pressable>}
<Note>{draftStatus(draft.status)} · {reviewCount} 项</Note>
{!!(outcome.succeeded||outcome.skipped||outcome.failed)&&<Note>成功 {outcome.succeeded} 项{outcome.skipped?` · 跳过 ${outcome.skipped} 项`:''}{outcome.failed?` · 未成功 ${outcome.failed} 项`:''}</Note>}
{outcome.labels.map((label:string,index:number)=><Note key={`skipped-${index}`}>本次已跳过,未更正:{label}</Note>)}
{expanded&&<>
{(draft.errors||[]).map((e:string,j:number)=><Note key={j}>{e}</Note>)}
{(draft.rows||[]).slice(0,20).map((row:Row,j:number)=><View key={j} style={{gap:6,paddingVertical:8,borderTopWidth:1,borderColor:t.line}}><Note>第 {j+1} 行</Note>{(draft.fields||[]).filter((f:Row)=>!f.hidden).map((f:Row)=><Text key={f.key} style={{color:t.text,lineHeight:22}}>{f.label}:{draftFieldText(row,f)}</Text>)}{draft.action==='purchase.correctPrice'&&(row._quotePreview||[]).map((q:Row,k:number)=><View key={k} style={{gap:4}}><Text style={{color:t.text}}>{q.name} · 数量 {q.quantity}</Text><Text style={{color:t.accent}}>报价:{q.previousPrice??'未报价'} → {q.unitPrice};金额:{q.oldAmount??'未计价'} → {q.newAmount}</Text><Note>{q.notice}</Note></View>)}</View>)}
{(draft.rows||[]).flatMap((row:Row)=>row._referencePricePreview||[]).slice(0,20).map((row:Row,index:number)=><View key={`reference-${index}`} style={{gap:5}}><Text style={{color:t.text}}>{row.name} · {row.spec} · 数量 {row.quantity}</Text><Text style={{color:t.accent}}>实际单价:{row.oldActualPrice??'未填写'} → {row.newActualPrice??'未填写'};实际金额:{row.oldActualAmount??'未填写'} → {row.newActualAmount??'未填写'}</Text>{row.clearQuote&&<Text style={{color:row.blocked?'#dc5b66':t.text}}>报价单价:{row.quotePrice??'未报价'} → {row.newQuotePrice??(row.changed?'清空(未报价)':'未报价')};报价金额:{row.oldQuoteAmount??'未报价'} → {row.newQuoteAmount??(row.changed?'清空(未报价)':'未报价')}</Text>}<Note>{row.notice};{row.clearQuote?'整批提交并同步金额与成本,清空不是0元':'不修改报价或成本'}</Note></View>)}
{draft.action==='notification.send'&&(draft.rows||[]).slice(0,20).map((row:Row,index:number)=>row._notificationPreview&&<View key={`notification-${index}`} style={{gap:5}}><Text style={{color:t.text}}>{row._notificationPreview.scope} · 实际接收 {row._notificationPreview.recipientCount} 人</Text>{(row._notificationPreview.recipients||[]).slice(0,20).map((person:Row)=><Text key={person.id} style={{color:t.text}}>{person.name||'未填写姓名'}({person.account}){row._notificationPreview.emailRequired?` · ${person.email}`:''}</Text>)}<Note>{row._notificationPreview.notice}</Note></View>)}
{(draft.rows||[]).filter((row:Row)=>row._historyPreview).slice(0,20).map((row:Row,index:number)=>{const h=row._historyPreview;return <View key={`history-${index}`} style={{gap:5,paddingVertical:8,borderTopWidth:1,borderColor:t.line}}><Text style={{color:t.text}}>{h.name} · {h.spec}</Text>{(h.changes||[]).map((change:Row)=><View key={change.field}><Note>{change.label} · 更正前:{change.beforeText??change.before??'未填写'}</Note><Text style={{color:t.accent}}>更正后:{change.afterText??change.after??'未填写'}</Text></View>)}<Note>实际金额:{h.oldActualAmount??'未填写'} → {h.newActualAmount??'未填写'};报价金额:{h.oldAmount??'未计价'} → {h.newAmount??'未计价'}</Note><Note>关联入库 {h.receiptCount||0} 条,成本来源 {h.costSourceCount||0} 条;实际收货数量不变。</Note>{h.createItem&&<Note>确认后匹配或新建物品档案。</Note>}{h.categoryUpdatesArchive&&<Note>类别更正会同步物品档案及其引用页面。</Note>}{h.priceImpact?.notice&&<Note>{h.priceImpact.notice}</Note>}{h.oldStatus!==h.newStatus&&<Note>采购状态将随需求数量重新核算,请在电脑端核对完整状态。</Note>}</View>})}
{reviewCount>20&&<Note>此确认单超过 20 项,请在电脑端完整核对后办理;App 暂不开放截断确认。</Note>}
{!!(outcome.succeeded||outcome.skipped||outcome.failed)&&<Note>成功 {outcome.succeeded} 项 · 跳过 {outcome.skipped} 项 · 未成功 {outcome.failed} 项</Note>}
{outcome.labels.map((label:string,index:number)=><Note key={index}>本次已跳过:{label}</Note>)}
{expanded&&<>{(draft.errors||[]).map((e:string,j:number)=><Text key={j} style={{color:'#c83a4c'}}>{e}</Text>)}
{entries.slice(page*20,(page+1)*20).map((entry,index)=><DraftEntry key={page*20+index} entry={entry} draft={draft}/>)}
{!!entries.length&&<View style={{gap:8,borderTopWidth:1,borderColor:t.line,paddingTop:10}}><Note>核对第 {page+1}/{pages} 页 · 已确认 {checked.length}/{pages} 页</Note>
{active&&<Pressable accessibilityRole="checkbox" accessibilityLabel="已核对本页内容" accessibilityState={{checked:checked.includes(page)}} onPress={()=>setChecked(old=>old.includes(page)?old.filter(n=>n!==page):[...old,page])} style={[s.row,{minHeight:44}]}><Icon name={checked.includes(page)?'checkbox':'square-outline'} size={20}/><Text style={{color:t.text}}>已核对本页内容</Text></Pressable>}
{pages>1&&<View style={[s.row,{justifyContent:'space-between'}]}><Button title="上一页" secondary disabled={page===0} onPress={()=>changePage(page-1)}/><Button title="下一页" secondary disabled={page+1>=pages} onPress={()=>changePage(page+1)}/></View>}
</View>}
</>}
{active&&<><Note>需要更正时可继续在下方描述,原草稿由后端保留并重新核对。</Note>
{draftNeedsRichNoticeReview(draft)&&<Note>图文公告请在电脑端核对完整正文和配图后发布。</Note>}
<Button title="确认执行" disabled={busy||!draft.ready||reviewCount>20||draftNeedsRichNoticeReview(draft)||draft.action==='user.resetPassword'} onPress={()=>Alert.alert('确认执行业务',`请确认已逐项核对“${draft.label}”,本次将真实提交。`,[{text:'返回核对',style:'cancel'},{text:'确认执行',onPress:()=>void onAction(draft,'execute')}])}/>
{active&&<>{missingRecipients&&<Note>服务返回的接收人名单不完整,请在电脑端核对完整名单后提交。</Note>}{draftNeedsRichNoticeReview(draft)&&<Note>图文公告的发布请在电脑端核对完整正文和配图。</Note>}
<Button title={complete?'确认执行':'请先核对全部页面'} disabled={busy||!draft.ready||!complete||missingRecipients||draftNeedsRichNoticeReview(draft)||draft.action==='user.resetPassword'} onPress={()=>Alert.alert('确认执行业务',`已核对“${draft.label}”的全部 ${pages} 页,本次将真实提交。`,[{text:'返回核对',style:'cancel'},{text:'确认执行',onPress:()=>void onAction(draft,'execute')}])}/>
<Button title="取消此操作" secondary disabled={busy} onPress={()=>void onAction(draft,'cancel')}/></>}
</Card>;
}
function DraftEntry({entry,draft}:{entry:ReviewEntry;draft:Row}){
const t=useTheme(),{kind,row,value:v,index}=entry;
const line=(label:string,value:unknown)=><Text style={{color:t.text}}>{label}:{display(value)}</Text>;
return <View style={{gap:5,paddingVertical:8,borderTopWidth:1,borderColor:t.line}}>
{kind==='row'&&<><Text style={{fontWeight:'600',color:t.text}}>第 {index+1} 项</Text>{(draft.fields||[]).filter((f:Row)=>!f.hidden).map((f:Row)=><Text key={f.key} style={{color:t.text}}>{f.label}:{draftFieldText(row,f)}</Text>)}{(row._errors||[]).map((error:string,i:number)=><Text key={i} style={{color:'#c83a4c'}}>{error}</Text>)}{row._notificationPreview&&<Note>{row._notificationPreview.scope} · 实际接收 {row._notificationPreview.recipientCount} 人 · {row._notificationPreview.notice}</Note>}</>}
{kind==='quote'&&<><Text style={{color:t.text,fontWeight:'600'}}>{v.name} · 数量 {v.quantity}</Text>{line('报价',`${v.previousPrice??'未报价'} → ${v.unitPrice}`)}{line('金额',`${v.oldAmount??'未计价'} → ${v.newAmount}`)}<Note>{v.notice}</Note></>}
{kind==='reference'&&<><Text style={{color:t.text,fontWeight:'600'}}>{v.name} · {v.spec} · 数量 {v.quantity}</Text>{line('实际单价',`${v.oldActualPrice??'未填写'} → ${v.newActualPrice??'未填写'}`)}{line('实际金额',`${v.oldActualAmount??'未填写'} → ${v.newActualAmount??'未填写'}`)}{v.clearQuote&&<>{line('报价单价',`${v.quotePrice??'未报价'} → ${v.newQuotePrice??(v.changed?'清空(未报价)':'未报价')}`)}{line('报价金额',`${v.oldQuoteAmount??'未报价'} → ${v.newQuoteAmount??(v.changed?'清空(未报价)':'未报价')}`)}</>}<Note>{v.notice};{v.clearQuote?'整批提交并同步金额与成本,清空不是0元':'不修改报价或成本'}</Note></>}
{kind==='recipient'&&<><Text style={{color:t.text}}>{v.name||'未填写姓名'}({v.account})</Text>{row._notificationPreview?.emailRequired&&line('邮箱',v.email)}</>}
{kind==='history'&&<><Text style={{color:t.text,fontWeight:'600'}}>{v.name} · {v.spec}</Text>{(v.changes||[]).map((c:Row)=><Text key={c.field} style={{color:t.text}}>{c.label}:{c.beforeText??c.before??'未填写'} → {c.afterText??c.after??'未填写'}</Text>)}{line('实际金额',`${v.oldActualAmount??'未填写'} → ${v.newActualAmount??'未填写'}`)}{line('报价金额',`${v.oldAmount??'未计价'} → ${v.newAmount??'未计价'}`)}<Note>关联入库 {v.receiptCount||0} 条,成本来源 {v.costSourceCount||0} 条;实际收货数量不变。</Note>{v.createItem&&<Note>确认后匹配或新建物品档案。</Note>}{v.categoryUpdatesArchive&&<Note>类别更正会同步物品档案及其引用页面。</Note>}{v.priceImpact?.notice&&<Note>{v.priceImpact.notice}</Note>}{v.oldStatus!==v.newStatus&&<Note>采购状态将随需求数量重新核算,请核对完整状态。</Note>}</>}
</View>;
}
function Results({data,title,onInspect}:{data:Row;title:string;onInspect:()=>void}){
const t=useTheme(),[page,setPage]=useState(1),[more,setMore]=useState(false);const rows=Array.isArray(data)?data:Array.isArray(data?.rows)?data.rows:null;
const t=useTheme(),[limit,setLimit]=useState(20),[more,setMore]=useState(false);const rows=Array.isArray(data)?data:Array.isArray(data?.rows)?data.rows:null;
const columns=data?.columns||[];
const groups=queryColumnGroups(columns,rows||[]),visibleColumns=more?[...groups.primary,...groups.details]:groups.primary;
return <Card><Heading>{title}</Heading>{rows?<><Note>本次返回 {rows.length} 条{data.total!=null?` / 共 ${data.total} 条`:''}</Note>
{!rows.length&&<Note>当前条件下暂无记录。</Note>}{rows.slice((page-1)*10,page*10).map((row:Row,i:number)=><View key={i} style={{gap:5,borderTopWidth:1,borderColor:t.line,paddingTop:10}}>
{!rows.length&&<Note>当前条件下暂无记录。</Note>}{rows.slice(0,limit).map((row:Row,i:number)=><View key={i} style={{gap:5,borderTopWidth:1,borderColor:t.line,paddingTop:10}}>
{visibleColumns.map((col:Row)=><Text key={col.key||col.prop} selectable style={{color:t.text,lineHeight:23}}>{col.label}:{display(row[col.key||col.prop])}</Text>)}
{!columns.length&&<Note>此结果尚未提供移动端字段定义,请补充查询条件或在电脑端查看。</Note>}
</View>)}{!!groups.details.length&&<Button title={more?'收起更多资料':`更多资料(${groups.details.length} 项)`} secondary onPress={()=>{onInspect();setMore(v=>!v);}}/>}{rows.length>10&&<View style={s.row}><Button title="上 10 条" secondary disabled={page===1} onPress={()=>{onInspect();setPage(page-1);}}/><Button title="下 10 条" secondary disabled={page*10>=rows.length} onPress={()=>{onInspect();setPage(page+1);}}/></View>}</>:<Note>查询已返回。此类型的详情展示仍在移动端迁移中,可在电脑端查看完整结果。</Note>}</Card>;
</View>)}{!!groups.details.length&&<Button title={more?'收起更多资料':`更多资料(${groups.details.length} 项)`} secondary onPress={()=>{onInspect();setMore(v=>!v);}}/>}{rows.length>limit&&<View style={s.row}><Button title="再显示 20 条" secondary onPress={()=>{onInspect();setLimit(n=>n+20);}}/><Button title="再显示 50 条" secondary onPress={()=>{onInspect();setLimit(n=>n+50);}}/></View>}</>:<Note>查询已返回。此类型的详情展示仍在移动端迁移中,可在电脑端查看完整结果。</Note>}</Card>;
}

View File

@ -1,6 +1,7 @@
import {Text} from '../typography';
import {formatDateTime} from '../core/date-display';
import React,{useCallback,useEffect,useRef,useState} from 'react';
import {Image,KeyboardAvoidingView,Platform,Pressable,ScrollView,Text,View} from 'react-native';
import {Image,KeyboardAvoidingView,Platform,Pressable,ScrollView,View} from 'react-native';
import {Dialog as Alert} from '../dialogs';
import * as ImagePicker from 'expo-image-picker';
import {ApiClient,ApiError} from '../core/network';

View File

@ -1,12 +1,15 @@
import {formatDateTime} from '../core/date-display';
import React,{useEffect,useMemo,useState} from 'react';
import {Pressable,ScrollView,Text,View} from 'react-native';
import {Pressable,ScrollView,View} from 'react-native';
import {Text,TextInput} from '../typography';
import {Button,Card,Heading,Icon,Note,s,useTheme} from '../ui';
import type {ApiClient} from '../core/network';
import {createMessageCenter,initialMessageState} from '../core/message-center';
import {NoticeContent} from './NoticeContent';
import {ManagedAttachments} from './ManagedAttachments';
export function MessageCenter({api,onRead}:{api:ApiClient;onRead:()=>void}){
const t=useTheme(),[state,setState]=useState(initialMessageState);
const t=useTheme(),[state,setState]=useState(initialMessageState),[search,setSearch]=useState('');
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;
@ -16,13 +19,14 @@ export function MessageCenter({api,onRead}:{api:ApiClient;onRead:()=>void}){
{!!state.error&&<Note>{state.error}</Note>}
{detail?<>
<Button title="返回消息列表" secondary disabled={state.reading} onPress={center.back}/>
<Card><Heading>{detail.title}</Heading><Note>{formatDateTime(detail.time)} · {detail.read?'已读':'未读'}</Note><Text selectable style={{color:t.text,lineHeight:27,fontSize:16}}>{detail.content||'暂无正文'}</Text>{!detail.read&&<Button title="标为已读" busy={state.reading} onPress={()=>void center.mark(true)}/>}</Card>
<Card><Heading>{detail.title}</Heading><Note>{formatDateTime(detail.time)} · {detail.read?'已读':'未读'}</Note>{detail.kind==='notices'?<NoticeContent html={detail.html} baseUrl={api.baseUrl}/>:<Text selectable style={{color:t.text,lineHeight:22,fontSize:14}}>{detail.content||'暂无正文'}</Text>}{!!detail.attachments?.length&&<ManagedAttachments api={api} files={detail.attachments}/>} {!detail.read&&<Button title="标为已读" busy={state.reading} onPress={()=>void center.mark(true)}/>}</Card>
</>:<>
<View style={s.row}>{state.tab==='inbox'?<Button title={state.unreadOnly?'✓ 只看未读':'只看未读'} secondary disabled={busy} onPress={()=>void center.filter(!state.unreadOnly)}/>:<Note>最近 5 条通知公告</Note>}<Button title="刷新" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load()}/></View>
{state.tab==='notices'&&<View style={{flexDirection:'row',gap:8}}><TextInput accessibilityLabel="搜索历史公告" placeholder="搜索公告标题" placeholderTextColor={t.muted} value={search} onChangeText={setSearch} onSubmitEditing={()=>void center.search(search)} returnKeyType="search" maxLength={100} style={{flex:1,minHeight:44,paddingHorizontal:10,borderWidth:1,borderColor:t.line,borderRadius:8,color:t.text,fontSize:14,backgroundColor:t.card}}/><Button title="搜索" disabled={busy} onPress={()=>void center.search(search)}/></View>}
<View style={s.row}><Button title={state.unreadOnly?'✓ 只看未读':'只看未读'} secondary disabled={busy} onPress={()=>void center.filter(!state.unreadOnly)}/><Button title="刷新" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load()}/></View>
{unread&&<Button title="已加载消息标为已读" secondary busy={state.reading} disabled={state.busy} onPress={()=>void center.mark()}/>}
{!items.length&&<Note>{state.busy?'正在获取消息…':state.hasMore?'本页暂无可查看的消息,可继续加载较早消息。':state.tab==='notices'?'暂无通知公告':state.unreadOnly?'暂无未读消息':'暂无站内消息'}</Note>}
{items.map(item=>{const read=state.tab==='inbox'?!!item.readAt:!!item.isRead;return <Pressable key={item.id??item.noticeId} accessibilityRole="button" accessibilityLabel={(read?'已读:':'未读:')+(item.title||item.noticeTitle)} disabled={busy} onPress={()=>void center.detail(item)}><Card><View style={[s.row,{flexWrap:'nowrap'}]}>{!read&&<View style={{width:7,height:7,borderRadius:4,backgroundColor:t.accent}}/>}<Text style={{flex:1,color:t.text,fontSize:16,fontWeight:read?'400':'700',lineHeight:24}}>{item.title||item.noticeTitle}</Text><Icon name="chevron-forward" size={18}/></View><Note>{formatDateTime(item.deliveredAt||item.createTime)}</Note>{state.tab==='inbox'&&<Text numberOfLines={2} style={{color:t.muted,lineHeight:21}}>{item.content}</Text>}</Card></Pressable>;})}
{state.tab==='inbox'&&state.hasMore&&<Button title="加载更早消息" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load(true)}/>}
{state.hasMore&&<Button title="加载更早消息" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load(true)}/>}
</>}
</ScrollView>;
}

View File

@ -1,5 +1,8 @@
import React,{useContext} from 'react';
import {Image,Pressable,ScrollView,Text,View,useWindowDimensions} from 'react-native';
import {Text,ReadingContext,useReadingScale} from '../typography';
import {workspaceTasks,shortcutOrder} from '../core/workspace-tasks';
import {readPreference,savePreference} from '../core/preferences';
import React,{useContext,useEffect,useState} from 'react';
import {AppState,Image,Modal,Pressable,ScrollView,View,useWindowDimensions} from 'react-native';
import Constants from 'expo-constants';
import * as Updates from 'expo-updates';
import {AppearanceContext,Avatar,Button,Card,Heading,Icon,MenuItem,Note,s,useTheme,type IconName} from '../ui';
@ -8,28 +11,37 @@ import {usePrivateImage} from '../files';
import {ApiClient} from '../core/network';
import type {Module,Row} from '../core/modules';
import {workspaceColumns} from '../core/workspace-layout';
import type {AppUpdateControls} from '../AppUpdates';
const icons:Record<string,IconName>={arrival:'checkmark-circle-outline',use:'file-tray-outline',move:'swap-horizontal-outline',count:'clipboard-outline',stock:'cube-outline',purchase:'cart-outline',pending:'download-outline',in:'file-tray-full-outline',loans:'swap-horizontal-outline',check:'clipboard-outline',out:'file-tray-outline',production:'construct-outline'};
const hints:Record<string,string>={arrival:'登记到货、逐次验收合格数量',use:'选择库存,核对后领用出库',move:'同项目库存更换实际存放库区',count:'现场清点,登记实际数量',stock:'查询物品、数量和所在库区',purchase:'采购明细与报价进展',pending:'核对物品,现场办理入库',in:'追溯每一次入库',loans:'查询项目间借还进度',check:'查看盘点记录、确认盘点',out:'查看领用与退回记录',production:'查询任务、产量与执行状态'};
type Props={api:ApiClient;user:Row;modules:Module[];open:(name:string)=>void;go:(tab:string)=>void;ai:boolean};
export function Workspace({api,user,modules,open,go,ai}:Props){
const t=useTheme(),uri=usePrivateImage(api,imagePath(user.avatar));const hour=new Date().getHours(),greeting=hour<11?'早上好':hour<14?'中午好':hour<18?'下午好':'晚上好';
const {width,fontScale}=useWindowDimensions(),columns=workspaceColumns(width,fontScale);
const quick=['arrival','pending','use','move','count'].map(k=>modules.find(m=>m.key===k)).filter((m):m is Module=>!!m);
return <ScrollView contentContainerStyle={[s.page,{paddingTop:8,paddingBottom:20,gap:12}]}>
<View style={{flexDirection:'row',alignItems:'center',padding:16,gap:12,borderRadius:16,backgroundColor:t.hero}}><View style={{gap:4,flex:1,minWidth:0}}><Text style={{color:'#dfeaff',fontSize:13,lineHeight:19}}>{new Date().toLocaleDateString('zh-CN',{month:'long',day:'numeric',weekday:'long'})}</Text><Text style={{color:'#fff',fontSize:20,lineHeight:28,fontWeight:'700'}}>{greeting},{user.nickName||user.userName}</Text></View><Pressable accessibilityRole="button" accessibilityLabel="打开我的" onPress={()=>go('me')} style={{minWidth:44,minHeight:44,alignItems:'center',justifyContent:'center'}}><Avatar name={user.nickName||user.userName} uri={uri} size={44}/></Pressable></View>
<View style={[s.row,{justifyContent:'space-between'}]}><Text style={{color:t.text,fontSize:17,lineHeight:24,fontWeight:'700'}}>常用操作</Text><Pressable accessibilityRole="button" accessibilityLabel="查看全部业务" onPress={()=>go('business')} style={{paddingHorizontal:4,minHeight:44,justifyContent:'center'}}><Text style={{color:t.accent,fontSize:14,lineHeight:21}}>全部业务 →</Text></Pressable></View>
<View style={{flexDirection:'row',flexWrap:'wrap',gap:12}}>{quick.map(m=><Pressable accessibilityRole="button" accessibilityLabel={m.title} key={m.key} onPress={()=>open(m.key)} style={({pressed})=>({flexBasis:columns===1?'100%':'47%',flexGrow:1,flexShrink:1,minWidth:0,padding:14,gap:8,borderRadius:14,backgroundColor:t.card,borderWidth:1,borderColor:t.line,opacity:pressed ? .7 : 1})}><View style={{flexDirection:'row',alignItems:'center',gap:8}}><View style={{padding:6,backgroundColor:t.soft,borderRadius:9,flexShrink:0}}><Icon name={icons[m.key]} size={22}/></View><Text style={{color:t.text,fontSize:16,fontWeight:'600',lineHeight:23,flex:1,minWidth:0}}>{m.title}</Text></View><Text style={{color:t.muted,fontSize:13,lineHeight:19}}>{hints[m.key]}</Text></Pressable>)}</View>
{!quick.length&&<Note>你的移动业务入口尚未配置,可请管理员协助确认工作范围。</Note>}
{ai&&<Pressable accessibilityRole="button" accessibilityLabel="与 AI 对话" onPress={()=>go('assistant')}><Card><View style={{flexDirection:'row',alignItems:'center',gap:12}}><Image source={require('../../assets/assistant.png')} style={{width:40,height:40,borderRadius:20}}/><View style={{flex:1,minWidth:0,gap:4}}><Text style={{color:t.text,fontSize:16,fontWeight:'700',lineHeight:23}}>不确定怎么操作?问我就好</Text><Text style={{color:t.muted,fontSize:13,lineHeight:19}}>说需求、传图片,也可以继续补充</Text></View><Icon name="arrow-forward" size={18}/></View></Card></Pressable>}
<Pressable accessibilityRole="button" accessibilityLabel="问题与建议" onPress={()=>open('feedback')} style={[s.row,{padding:10,justifyContent:'center',minHeight:44}]}><Icon name="chatbubble-ellipses-outline" size={17} color={t.muted}/><Text style={{color:t.muted,fontSize:13,lineHeight:20}}>遇到问题?告诉我们,让工作更顺畅</Text></Pressable>
const icons:Record<string,IconName>={arrival:'checkmark-circle-outline',use:'file-tray-outline',move:'swap-horizontal-outline',count:'clipboard-outline',stock:'cube-outline',purchase:'cart-outline',pending:'download-outline',in:'file-tray-full-outline',loans:'swap-horizontal-outline',check:'clipboard-outline',out:'file-tray-outline',production:'construct-outline',files:'folder-outline'};
const hints:Record<string,string>={arrival:'登记到货、逐次验收合格数量',use:'选择库存,核对后领用出库',move:'同项目库存更换实际存放库区',count:'现场清点,登记实际数量',stock:'查询物品、数量和所在库区',purchase:'采购明细与报价进展',pending:'核对物品,现场办理入库',in:'追溯每一次入库',loans:'查询项目间借还进度',check:'查看盘点记录、确认盘点',out:'查看领用与退回记录',production:'查询任务、产量与执行状态',files:'查看、上传和下载共享文件'};
type Props={api:ApiClient;user:Row;modules:Module[];scope:string;open:(name:string,query?:Row)=>void;go:(tab:string)=>void;ai:boolean};
export function Workspace({api,user,modules,scope,open,go,ai}:Props){
const t=useTheme(),scale=useReadingScale(),{width,fontScale}=useWindowDimensions(),columns=workspaceColumns(width,fontScale*scale);
const [order,setOrder]=useState<string[]>(()=>shortcutOrder(null,modules)),[editing,setEditing]=useState(false),[counts,setCounts]=useState<Record<string,number|null>>({}),[loading,setLoading]=useState(true),[retry,setRetry]=useState(0),[error,setError]=useState('');
const tasks=workspaceTasks(modules),signature=modules.map(m=>m.key).join(',');
useEffect(()=>{let alive=true;setOrder(shortcutOrder(null,modules));void readPreference(scope,'shortcuts').then(value=>{if(alive)setOrder(shortcutOrder(value,modules));}).catch(()=>{});return()=>{alive=false;};},[scope,signature]);
useEffect(()=>{const ctl=new AbortController();setLoading(true);setCounts({});void Promise.all(tasks.map(async task=>{try{const data=await api.request<Row>(task.path,{query:{...task.query,pageNum:1,pageSize:1},signal:ctl.signal});return [task.id,Math.max(0,Number(data.total??data.data?.total)||0)] as const;}catch{return [task.id,null] as const;}})).then(values=>{if(!ctl.signal.aborted){setCounts(Object.fromEntries(values));setLoading(false);}});return()=>ctl.abort();},[api,signature,retry]);
useEffect(()=>{const listener=AppState.addEventListener('change',state=>{if(state==='active')setRetry(n=>n+1);});return()=>listener.remove();},[]);
const quick=order.map(key=>modules.find(m=>m.key===key)).filter((m):m is Module=>!!m);
function reorder(key:string,delta:number){const i=order.indexOf(key),next=i+delta;if(i<0||next<0||next>=order.length)return;const values=[...order];[values[i],values[next]]=[values[next],values[i]];setOrder(values);}
async function save(){try{await savePreference(scope,'shortcuts',order);setEditing(false);setError('');}catch{setError('未能保存常用操作,请重试。');}}
return <ScrollView contentContainerStyle={[s.page,{paddingTop:4,gap:12}]}>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between',paddingVertical:4}}><Text numberOfLines={1} style={{flex:1,minWidth:0,fontSize:16,fontWeight:'600',color:t.text}}>{user.nickName||user.userName}</Text><Text style={{fontSize:12,color:t.muted}}>{new Date().toLocaleDateString('zh-CN',{month:'long',day:'numeric',weekday:'short'})}</Text></View>
{!!tasks.length&&<View><View style={[s.row,{justifyContent:'space-between',marginBottom:6}]}><Text style={{fontWeight:'600',color:t.text}}>待办事项</Text><Pressable accessibilityRole="button" accessibilityLabel="刷新待办" onPress={()=>setRetry(n=>n+1)} style={{minHeight:36,justifyContent:'center'}}><Text style={{fontSize:12,color:t.accent}}>{loading?'刷新中…':'刷新'}</Text></Pressable></View><View style={{flexDirection:'row',flexWrap:'wrap',gap:8}}>{tasks.map(task=><Pressable key={task.id} accessibilityRole="button" accessibilityLabel={task.label} onPress={()=>open(task.key,task.openQuery)} style={{flexBasis:columns===1?'100%':'47%',flexGrow:1,padding:12,borderWidth:1,borderColor:t.line,backgroundColor:t.card,borderRadius:10}}><Text style={{fontSize:22,lineHeight:28,fontWeight:'700',color:t.accent}}>{counts[task.id]??'—'}</Text><Text style={{fontSize:12,color:t.text}}>{task.label}{!loading&&counts[task.id]===null?' · 暂未获取':''}</Text></Pressable>)}</View></View>}
<View style={[s.row,{justifyContent:'space-between'}]}><Text style={{fontSize:15,fontWeight:'600',color:t.text}}>常用操作</Text><Pressable accessibilityRole="button" accessibilityLabel="编辑常用操作" onPress={()=>setEditing(true)} style={{minHeight:40,justifyContent:'center'}}><Text style={{fontSize:12,color:t.accent}}>编辑</Text></Pressable></View>
<View style={{flexDirection:'row',flexWrap:'wrap',gap:10}}>{quick.map(m=><Pressable accessibilityRole="button" accessibilityLabel={m.title} key={m.key} onPress={()=>open(m.key)} style={({pressed})=>({flexBasis:columns===1?'100%':'47%',flexGrow:1,minWidth:0,padding:12,gap:9,borderRadius:10,backgroundColor:t.card,borderWidth:1,borderColor:t.line,flexDirection:'row',alignItems:'center',minHeight:58,opacity:pressed?.7:1})}><Icon name={icons[m.key]||'grid-outline'} size={21}/><Text style={{color:t.text,fontSize:14,fontWeight:'500',flex:1}}>{m.title}</Text></Pressable>)}</View>
{!quick.length&&<Note>点击“编辑”添加常用操作。</Note>}
<Button title="全部业务" secondary onPress={()=>go('business')}/>
{ai&&<Pressable accessibilityRole="button" accessibilityLabel="与 AI 对话" onPress={()=>go('assistant')} style={{flexDirection:'row',alignItems:'center',gap:10,padding:12,borderRadius:10,backgroundColor:t.soft}}><Image source={require('../../assets/assistant.png')} style={{width:28,height:28,borderRadius:14}}/><Text style={{flex:1,color:t.text,fontSize:14}}>AI 助手</Text><Icon name="arrow-forward" size={18}/></Pressable>}
<Modal visible={editing} transparent animationType="slide" onRequestClose={()=>setEditing(false)}><View style={{flex:1,justifyContent:'flex-end',backgroundColor:'#0007'}}><View style={{maxHeight:'85%',backgroundColor:t.card,borderTopLeftRadius:18,borderTopRightRadius:18,padding:16,gap:12}}><Heading>常用操作</Heading><Note>勾选入口,使用上移、下移调整顺序。</Note><ScrollView>{[...quick,...modules.filter(m=>!order.includes(m.key))].map(m=><View key={m.key} style={{flexDirection:'row',alignItems:'center',borderBottomWidth:1,borderColor:t.line,gap:6}}><Pressable accessibilityRole="checkbox" accessibilityState={{checked:order.includes(m.key)}} accessibilityLabel={m.title} onPress={()=>setOrder(old=>old.includes(m.key)?old.filter(k=>k!==m.key):[...old,m.key])} style={{flex:1,minHeight:48,flexDirection:'row',alignItems:'center',gap:10}}><Icon name={order.includes(m.key)?'checkbox':'square-outline'} size={20}/><Text style={{color:t.text}}>{m.title}</Text></Pressable>{order.includes(m.key)&&<><Pressable accessibilityRole="button" accessibilityLabel={m.title+'上移'} disabled={order.indexOf(m.key)===0} onPress={()=>reorder(m.key,-1)} style={{padding:10}}><Icon name="arrow-up" size={18} color={order.indexOf(m.key)===0?t.muted:t.accent}/></Pressable><Pressable accessibilityRole="button" accessibilityLabel={m.title+'下移'} disabled={order.indexOf(m.key)===order.length-1} onPress={()=>reorder(m.key,1)} style={{padding:10}}><Icon name="arrow-down" size={18}/></Pressable></>}</View>)}</ScrollView>{!!error&&<Note>{error}</Note>}<View style={s.row}><Button title="关闭" secondary onPress={()=>setEditing(false)}/><Button title="保存常用操作" onPress={()=>void save()}/></View></View></View></Modal>
</ScrollView>;
}
export function BusinessHub({modules,open}:{modules:Module[];open:(name:string)=>void}){
const t=useTheme();return <ScrollView contentContainerStyle={s.page}><Heading>在现场,也能从容处理</Heading><Note>常用现场操作优先,其他业务随时查询;提交前均先核对。</Note>{[['现场办理',['arrival','pending','use','move','count']],['查询与记录',['stock','purchase','production','in','out','loans','check']]].map(([label,keys])=>{const entries=(keys as string[]).map(key=>modules.find(m=>m.key===key)).filter((m):m is Module=>!!m);return entries.length?<View key={label as string} style={{gap:10,marginTop:6}}><Text style={{color:t.muted,fontSize:13,fontWeight:'600',paddingLeft:4}}>{label as string}</Text><Card>{entries.map((m,i)=><MenuItem key={m.key} title={m.title} detail={hints[m.key]} icon={icons[m.key]} onPress={()=>open(m.key)} last={i===entries.length-1}/>)}</Card></View>:null;})}{!modules.length&&<Note>暂未分配移动业务,可请管理员协助确认。</Note>}</ScrollView>;
const t=useTheme();return <ScrollView contentContainerStyle={s.page}>{[['现场办理',['arrival','pending','use','move','count']],['查询与记录',['stock','purchase','production','in','out','loans','check','files']]].map(([label,keys])=>{const entries=(keys as string[]).map(key=>modules.find(m=>m.key===key)).filter((m):m is Module=>!!m);return entries.length?<View key={label as string} style={{gap:10,marginTop:6}}><Text style={{color:t.muted,fontSize:13,fontWeight:'600',paddingLeft:4}}>{label as string}</Text><Card>{entries.map((m,i)=><MenuItem key={m.key} title={m.title} detail={hints[m.key]} icon={icons[m.key]} onPress={()=>open(m.key)} last={i===entries.length-1}/>)}</Card></View>:null;})}{!modules.length&&<Note>暂未分配移动业务,可请管理员协助确认。</Note>}</ScrollView>;
}
export function Me({api,user,open}:{api:ApiClient;user:Row;open:(name:string)=>void}){
const t=useTheme(),uri=usePrivateImage(api,imagePath(user.avatar));return <ScrollView contentContainerStyle={s.page}><Pressable accessibilityRole="button" accessibilityLabel="个人资料" onPress={()=>open('profile')}><View style={[s.row,{paddingVertical:12,gap:16}]}><Avatar name={user.nickName||user.userName} uri={uri} size={70}/><View style={{flex:1,gap:7}}><Text style={{color:t.text,fontSize:24,fontWeight:'700'}}>{user.nickName||user.userName}</Text><Text style={{color:t.muted,fontSize:13}}>账号 {user.userName}</Text><Text style={{color:t.muted,fontSize:12}}>{user.dept?.deptName||'个人工作空间'}</Text></View><Icon name="chevron-forward" color={t.muted}/></View></Pressable>
const t=useTheme(),uri=usePrivateImage(api,imagePath(user.avatar));return <ScrollView contentContainerStyle={s.page}><Pressable accessibilityRole="button" accessibilityLabel="个人资料" onPress={()=>open('profile')}><View style={[s.row,{paddingVertical:12,gap:16}]}><Avatar name={user.nickName||user.userName} uri={uri} size={48}/><View style={{flex:1,gap:7}}><Text style={{color:t.text,fontSize:18,fontWeight:'700'}}>{user.nickName||user.userName}</Text><Text style={{color:t.muted,fontSize:13}}>账号 {user.userName}</Text><Text style={{color:t.muted,fontSize:12}}>{user.dept?.deptName||'个人工作空间'}</Text></View><Icon name="chevron-forward" color={t.muted}/></View></Pressable>
<Card><MenuItem title="个人资料" detail="昵称、手机号码和邮箱" icon="person-outline" onPress={()=>open('profile')}/><MenuItem title="账号与密码" detail="管理当前账号的登录密码" icon="lock-closed-outline" onPress={()=>open('password')} last/></Card>
<Card><MenuItem title="消息中心" detail="查看站内消息、通知公告和未读提醒" icon="notifications-outline" onPress={()=>open('messages')} last/></Card>
<Card><MenuItem title="问题与建议" detail="发现问题、提出需求,支持添加图片" icon="chatbubble-ellipses-outline" onPress={()=>open('feedback')}/><MenuItem title="我的反馈" detail="查看处理进展与负责人回复" icon="receipt-outline" onPress={()=>open('feedback-list')} last/></Card>
@ -37,12 +49,13 @@ export function Me({api,user,open}:{api:ApiClient;user:Row;open:(name:string)=>v
<Text style={{color:t.muted,fontSize:11,textAlign:'center',letterSpacing:2,marginTop:8}}>CMVR · 让工作更简单</Text>
</ScrollView>;
}
export function Settings({updateText,environment,baseUrl,connection,logout,about=false}:{updateText:string;environment:string;baseUrl:string;connection?:React.ReactNode;logout:()=>void;about?:boolean}){
const t=useTheme(),{mode,setMode}=useContext(AppearanceContext);
export function Settings({updates,environment,baseUrl,connection,packageUpdate,logout,about=false}:{updates:AppUpdateControls;environment:string;baseUrl:string;connection?:React.ReactNode;packageUpdate?:React.ReactNode;logout:()=>void;about?:boolean}){
const t=useTheme(),{mode,setMode}=useContext(AppearanceContext),reading=useContext(ReadingContext);
return <ScrollView contentContainerStyle={s.page}>{about?<><View style={{alignItems:'center',paddingVertical:24,gap:12}}><View style={{backgroundColor:t.accent,padding:20,borderRadius:25}}><Icon name="layers-outline" color="#fff" size={43}/></View><Heading>CMVR 移动工作空间</Heading><Note>把业务带到现场,让协作更轻松。</Note></View><Card><Note>应用版本 {Constants.expoConfig?.version}</Note><Note>当前环境 {environment==='prod'?'正式环境':'开发环境'}</Note><Note>更新标识 {Updates.updateId?.slice(0,8)||'内置版本'}</Note></Card><Card><Heading>数据与安全</Heading><Note>业务数据来自公司内网服务。可见数据和可用操作由后台权限决定;AI 操作须经人工确认,查询直接返回。</Note><Note>请仅在可信的公司网络使用。不要在反馈或 AI 对话中填写密码和授权码。</Note></Card></>:<>
<Card><Heading>外观</Heading><Note>选择适合你的阅读方式。</Note><View style={s.row}>{([['system','跟随系统'],['light','浅色'],['dark','深色']] as const).map(([value,label])=><Button key={value} title={`${mode===value?'✓ ':''}${label}`} secondary={mode!==value} onPress={()=>setMode(value)}/>)}</View></Card>
{connection||<Card><Heading>内网连接</Heading><Note>当前:{environment==='prod'?'正式环境':'开发环境'}</Note><Text selectable style={{color:t.text,lineHeight:22}}>{baseUrl}</Text><Note>正式服务由安装包固定,避免误切环境。</Note></Card>}
<Card><Heading>应用更新</Heading><Note>{updateText}</Note><Note>启动时自动检查内网更新。下载完成后下次启动生效,不会中断当前表单。原生能力变更仍需安装新版。</Note><Note>版本 {Constants.expoConfig?.version} · {Updates.updateId?.slice(0,8)||'内置版本'}</Note></Card>
<Card><Heading>文字大小</Heading><Note>默认紧凑字号,同时遵循手机系统字体设置。</Note><View style={s.row}>{([['compact','紧凑'],['standard','标准'],['large','大字']] as const).map(([key,label])=><Button key={key} title={label} secondary={reading.size!==key} onPress={()=>reading.setSize(key)}/>)}</View><Text style={{color:t.text}}>物品名称 · 库存数量 128 个</Text></Card>{connection||<Card><Heading>内网连接</Heading><Note>当前:{environment==='prod'?'正式环境':'开发环境'}</Note><Text selectable style={{color:t.text,lineHeight:22}}>{baseUrl}</Text><Note>正式服务由安装包固定,避免误切环境。</Note></Card>}
<Card><Heading>应用更新</Heading><Note>{updates.text}</Note><Note>打开 App 或回到前台时自动检查更新。下载完成会弹窗提示,由你选择何时重启;选择稍后也可在下次启动时生效。</Note><Note>版本 {Constants.expoConfig?.version} · {Updates.updateId?.slice(0,8)||'内置版本'}</Note>{updates.enabled&&<Button title={updates.view.state==='ready'?'立即更新':'检查更新'} secondary busy={['checking','downloading'].includes(updates.view.state)} onPress={updates.check}/>}</Card>
{packageUpdate}
<Button title="退出登录" secondary onPress={logout}/>
</>}</ScrollView>;
}

View File

@ -1,5 +1,8 @@
import React, { createContext, useContext } from 'react';
import { ActivityIndicator, Image, Pressable, ScrollView, StyleSheet, Text, TextInput, View, useColorScheme, type StyleProp, type ViewStyle } from 'react-native';
import { ActivityIndicator, Image, Pressable, ScrollView, StyleSheet, View, useColorScheme, type StyleProp, type ViewStyle } from 'react-native';
import {Text,TextInput} from './typography';
export {Choice} from './controls/Choice';
export {DateField} from './controls/DateField';
import Ionicons from '@expo/vector-icons/Ionicons';
import {darkTheme,lightTheme} from './core/appearance';
export type Appearance = 'system' | 'light' | 'dark';
@ -9,31 +12,23 @@ export function useTheme() { const {mode}=useContext(AppearanceContext),system=u
export type IconName=React.ComponentProps<typeof Ionicons>['name'];
export function Icon({name,size=22,color}:{name:IconName;size?:number;color?:string}){const t=useTheme();return <View aria-hidden accessibilityElementsHidden importantForAccessibility="no-hide-descendants"><Ionicons name={name} size={size} color={color||t.accent}/></View>;}
export function Avatar({name,uri,size=48}:{name:string;uri?:string;size?:number}){const t=useTheme();return <View style={{width:size,height:size,borderRadius:size/2,backgroundColor:t.soft,alignItems:'center',justifyContent:'center',overflow:'hidden'}}>{uri?<Image source={{uri}} style={{width:size,height:size}}/>:<Text style={{fontSize:size*.38,fontWeight:'700',color:t.accent}}>{name.slice(0,1)||'我'}</Text>}</View>;}
export function MenuItem({title,detail,icon,onPress,last=false}:{title:string;detail?:string;icon:IconName;onPress:()=>void;last?:boolean}){const t=useTheme();return <Pressable accessibilityRole="button" accessibilityLabel={title} onPress={onPress} style={({pressed})=>({flexDirection:'row',alignItems:'center',gap:13,minHeight:64,paddingVertical:12,opacity:pressed?.65:1,borderBottomWidth:last?0:1,borderColor:t.line})}><View style={{backgroundColor:t.soft,padding:9,borderRadius:12}}><Icon name={icon} size={21}/></View><View style={{flex:1,gap:4}}><Text style={{color:t.text,fontSize:16,fontWeight:'500'}}>{title}</Text>{!!detail&&<Text style={{color:t.muted,fontSize:12,lineHeight:18}}>{detail}</Text>}</View><Icon name="chevron-forward" size={17} color={t.muted}/></Pressable>;}
export function Button({ title, onPress, disabled, busy, secondary = false }: {
title: string; onPress: () => void; disabled?: boolean; busy?: boolean; secondary?: boolean;
export function MenuItem({title,detail,icon,onPress,last=false}:{title:string;detail?:string;icon:IconName;onPress:()=>void;last?:boolean}){const t=useTheme();return <Pressable accessibilityRole="button" accessibilityLabel={title} onPress={onPress} style={({pressed})=>({flexDirection:'row',alignItems:'center',gap:13,minHeight:56,paddingVertical:9,opacity:pressed?.65:1,borderBottomWidth:last?0:1,borderColor:t.line})}><View style={{backgroundColor:t.soft,padding:9,borderRadius:12}}><Icon name={icon} size={21}/></View><View style={{flex:1,gap:4}}><Text style={{color:t.text,fontSize:14,fontWeight:'500'}}>{title}</Text>{!!detail&&<Text style={{color:t.muted,fontSize:12,lineHeight:18}}>{detail}</Text>}</View><Icon name="chevron-forward" size={17} color={t.muted}/></Pressable>;}
export function Button({ title, onPress, disabled, busy, secondary = false, style }: {
title: string; onPress: () => void; disabled?: boolean; busy?: boolean; secondary?: boolean; style?:StyleProp<ViewStyle>;
}) { const t=useTheme(); return <Pressable accessibilityRole="button" accessibilityLabel={title}
accessibilityState={{ disabled: disabled || busy, busy }} onPress={onPress} disabled={disabled || busy}
style={({pressed})=>[s.button,{backgroundColor:secondary?t.soft:t.accent,opacity:disabled||busy?0.5:pressed?.75:1}]}>
{busy&&<ActivityIndicator color={secondary?t.accent:t.onAccent}/>}<Text style={{color:secondary?t.accent:t.onAccent,fontWeight:'600',fontSize:15,lineHeight:22,flexShrink:1,textAlign:'center'}}>{title}</Text></Pressable>; }
style={({pressed})=>[s.button,style,{backgroundColor:secondary?t.soft:t.accent,opacity:disabled||busy?0.5:pressed?.75:1}]}>
{busy&&<ActivityIndicator color={secondary?t.accent:t.onAccent}/>}<Text style={{color:secondary?t.accent:t.onAccent,fontWeight:'600',fontSize:14,lineHeight:22,flexShrink:1,textAlign:'center'}}>{title}</Text></Pressable>; }
export function Field({ label, value, onChange, secure, keyboard, multiline, disabled, maxLength }: {
label:string; value:string; onChange:(v:string)=>void; secure?:boolean; keyboard?:'decimal-pad'|'default'|'email-address'|'phone-pad'; multiline?:boolean; disabled?:boolean; maxLength?:number;
}) { const t=useTheme(); return <View style={{gap:7}}><Text style={{color:t.text,fontWeight:'500',fontSize:14,lineHeight:20}}>{label}</Text>
}) { const t=useTheme(); return <View style={{gap:7}}><Text style={{color:t.text,fontWeight:'500',fontSize:13,lineHeight:19}}>{label}</Text>
<TextInput accessibilityLabel={label} value={value} onChangeText={onChange} editable={!disabled} secureTextEntry={secure}
autoCapitalize="none" autoCorrect={false} keyboardType={keyboard} multiline={multiline} maxLength={maxLength}
style={[s.input,{color:t.text,borderColor:t.line,backgroundColor:t.card,minHeight:multiline?84:48}]}/></View>; }
style={[s.input,{color:t.text,borderColor:t.line,backgroundColor:t.card,minHeight:multiline?76:44}]}/></View>; }
export function Card({children,style}:{children:React.ReactNode;style?:StyleProp<ViewStyle>}) {const t=useTheme();return <View style={[s.card,{backgroundColor:t.card,borderColor:t.line},style]}>{children}</View>}
export function Note({children}:{children:React.ReactNode}) {const t=useTheme();return <Text accessibilityLiveRegion="polite" style={{color:t.muted,fontSize:15,lineHeight:22}}>{children}</Text>}
export function Heading({children}:{children:React.ReactNode}) {const t=useTheme();return <Text style={{color:t.text,fontSize:20,lineHeight:28,fontWeight:'700',flexShrink:1}}>{children}</Text>}
export function Choice({label,items,value,onChange,nameKey}:{label:string;items:Record<string,any>[];value:Record<string,any>|null;onChange:(item:Record<string,any>)=>void;nameKey:string}){
const t=useTheme(),[query,setQuery]=React.useState(''),[expanded,setExpanded]=React.useState(false);
const matches=items.filter(item=>String(item[nameKey]||item.areaCode||'').toLowerCase().includes(query.toLowerCase()));
return <View style={{gap:9}}><Text style={{color:t.text,fontWeight:'500'}}>{label}</Text><Pressable accessibilityRole="button" accessibilityLabel={`选择${label}`} accessibilityState={{expanded}} onPress={()=>setExpanded(v=>!v)} style={{flexDirection:'row',gap:12,alignItems:'center',padding:14,minHeight:50,borderWidth:1,borderColor:expanded?t.accent:t.line,borderRadius:10,backgroundColor:t.card}}><Text style={{flex:1,color:value?t.text:t.muted,lineHeight:22}}>{value?.[nameKey]||value?.areaCode||`请选择${label}`}</Text><Icon name={expanded?'chevron-up':'chevron-down'} size={17} color={t.muted}/></Pressable>
{expanded&&<Card><Field label={`搜索${label}`} value={query} onChange={setQuery}/><ScrollView nestedScrollEnabled keyboardShouldPersistTaps="handled" style={{maxHeight:240}}>{matches.slice(0,20).map(item=><Pressable accessibilityRole="button" accessibilityLabel={String(item[nameKey]||item.areaCode)} key={item.id} onPress={()=>{onChange(item);setExpanded(false);setQuery('');}} style={{paddingVertical:15,paddingHorizontal:4,borderBottomWidth:1,borderColor:t.line,flexDirection:'row',gap:10,alignItems:'center'}}><Text style={{color:value?.id===item.id?t.accent:t.text,flex:1,lineHeight:23}}>{item[nameKey]||item.areaCode}</Text>{value?.id===item.id&&<Icon name="checkmark" size={18}/>}</Pressable>)}</ScrollView>
{matches.length>20&&<Note>还有 {matches.length-20} 项,请输入名称缩小范围。</Note>}{!matches.length&&<Note>未找到匹配项。</Note>}</Card>}
</View>;
}
export const s=StyleSheet.create({fill:{flex:1},page:{padding:18,gap:16,paddingBottom:36},row:{flexDirection:'row',gap:10,alignItems:'center',flexWrap:'wrap'},
button:{minHeight:46,paddingHorizontal:16,paddingVertical:10,borderRadius:10,flexDirection:'row',gap:8,justifyContent:'center',alignItems:'center'},
input:{borderWidth:1,borderRadius:9,padding:12,fontSize:16},card:{padding:16,borderRadius:14,borderWidth:1,gap:12},header:{paddingHorizontal:18,paddingVertical:14,borderBottomWidth:1,gap:10},
pair:{flexDirection:'row',alignItems:'flex-start',gap:14},label:{width:96,flexShrink:0},value:{flex:1,lineHeight:22}});
export function Note({children}:{children:React.ReactNode}) {const t=useTheme();return <Text accessibilityLiveRegion="polite" style={{color:t.muted,fontSize:13,lineHeight:20}}>{children}</Text>}
export function Heading({children}:{children:React.ReactNode}) {const t=useTheme();return <Text style={{color:t.text,fontSize:18,lineHeight:25,fontWeight:'700',flexShrink:1}}>{children}</Text>}
export const s=StyleSheet.create({fill:{flex:1,minHeight:0},page:{padding:14,gap:12,paddingBottom:20},row:{flexDirection:'row',gap:10,alignItems:'center',flexWrap:'wrap'},
button:{minHeight:44,paddingHorizontal:14,paddingVertical:9,borderRadius:10,flexDirection:'row',gap:8,justifyContent:'center',alignItems:'center'},
input:{borderWidth:1,borderRadius:9,padding:12,fontSize:14},card:{padding:12,borderRadius:12,borderWidth:1,gap:10},header:{paddingHorizontal:18,paddingVertical:14,borderBottomWidth:1,gap:10},
pair:{flexDirection:'row',alignItems:'flex-start',gap:14},label:{width:72,fontSize:12,flexShrink:0},value:{flex:1,fontSize:14,lineHeight:21}});

View File

@ -67,12 +67,12 @@ const imports={react:React,'react/jsx-runtime':require('react/jsx-runtime'),'rea
'../ui':{Button:'Button',Note:'Note',s:{row:{}}},'../core/arrival-actions':{arrivalActions}};
const component={exports:{}};
vm.runInNewContext(compiled,{module:component,exports:component.exports,require:name=>imports[name]||require(name)});
function render(changes={},queue='arrival'){
function render(changes={},queue='arrival',onHistory){
const opened=[];
const tree=component.exports.ArrivalActions({row:{...ready,...changes},permissions:admin,queue,onOpen:kind=>opened.push(kind)});
const tree=component.exports.ArrivalActions({row:{...ready,...changes},permissions:admin,queue,onOpen:kind=>opened.push(kind),onHistory});
const nodes=[];
function walk(node){if(!node||typeof node!=='object')return;nodes.push(node);React.Children.toArray(node.props?.children).forEach(walk);}
walk(tree);return {opened,buttons:nodes.filter(n=>n.type==='Button'),notes:nodes.filter(n=>n.type==='Note')};
walk(tree);return {tree,nodes,opened,buttons:nodes.filter(n=>n.type==='Button'),notes:nodes.filter(n=>n.type==='Note')};
}
test('real rendered controls remain visible when unavailable; even direct handler calls cannot open them',()=>{
const s=render({priceLocked:false,pendingArrivalQuantity:3});assert.equal(s.buttons.length,2);
@ -86,3 +86,10 @@ test('real rendered controls open the correct form only; they never submit a req
const accept=render({remainingQuantity:0,pendingArrivalQuantity:2},'accept');
assert.equal(accept.buttons.length,1);assert.equal(accept.buttons[0].props.title,'验收到货');
});
test('history shares the same row as registration and acceptance with short labels and flexible widths',()=>{
let history=0;const s=render({pendingArrivalQuantity:2},'arrival',()=>history++);assert.deepEqual(s.buttons.map(b=>b.props.title),['登记到货','验收到货','到货记录']);
const row=s.nodes.find(n=>n.type==='View'&&n.props.style?.flexDirection==='row');assert.equal(row.props.style.flexWrap,undefined);assert.equal(React.Children.toArray(row.props.children).length,3);assert.equal(s.tree.props.style.width,'100%');
for(const button of s.buttons){assert.equal(button.props.style.flex,1);assert.equal(button.props.style.minWidth,0);assert.equal(button.props.style.paddingHorizontal,8);}
s.buttons[2].props.onPress();assert.equal(history,1);assert.deepEqual(s.opened,[]);
const accept=render({pendingArrivalQuantity:2,remainingQuantity:0},'accept',()=>{});assert.deepEqual(accept.buttons.map(b=>b.props.title),['验收到货','到货记录']);
});

View File

@ -15,7 +15,7 @@ const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.
const exports={};
vm.runInNewContext(compiled,{exports,require:name=>({react:React,'react/jsx-runtime':require('react/jsx-runtime'),
'react-native':{ActivityIndicator:'Loading',Pressable:'Pressable',Text:'Text',TextInput:'TextInput',View:'View',useWindowDimensions:()=>({width:393,fontScale:1})},
'../core/arrival-layout':{arrivalLayout},'../ui':{Card:'Card',Icon:'Icon',useTheme:()=>({})},'../core/modules':{display:v=>v==null?'—':String(v)}}[name]||require(name))});
'../typography':{Text:'Text',TextInput:'TextInput'},'../core/arrival-layout':{arrivalLayout},'../ui':{Card:'Card',Icon:'Icon',useTheme:()=>({})},'../core/modules':{display:v=>v==null?'—':String(v)}}[name]||require(name))});
function nodes(tree){const all=[];function walk(n){if(!n||typeof n!=='object')return;all.push(n);React.Children.toArray(n.props?.children).forEach(walk);}walk(tree);return all;}
test('compact queue tabs have equal width, correct state, accessible search and explicit clear',()=>{
const calls=[];const tree=exports.ArrivalListTools({query:'水冷',setQuery:v=>calls.push(v),queue:'accept',setQueue:v=>calls.push(v),busy:false,search:()=>calls.push('search'),reset:()=>calls.push('reset'),total:25,page:2});
@ -31,13 +31,13 @@ test('acceptance card keeps quantity and unit together without a tall fixed-size
assert.ok(all.some(n=>n.type==='Text'&&n.props.children==='很长的测试单位'&&n.props.style.fontSize===14));
assert.ok(all.some(n=>n.type==='Text'&&n.props.children==='待验收'));
assert.ok(all.some(n=>n.type==='View'&&n.props.style.flexDirection==='row'&&React.Children.toArray(n.props.children).some(c=>c.props?.children==='18')&&React.Children.toArray(n.props.children).some(c=>c.props?.children==='很长的测试单位')));
assert.ok(all.filter(n=>n.type==='Text').every(n=>n.props.style.fontSize>=13));
assert.ok(all.filter(n=>n.type==='Text').every(n=>n.props.style.fontSize>=12));
assert.ok(all.filter(n=>n.type==='View').every(n=>n.props.style.width!==94));
});
test('query state survives queue changes and pagination uses applied search rather than unsent text',()=>{
const app=readFileSync(new URL('../src/App.tsx',import.meta.url),'utf8');
const app=readFileSync(new URL('../src/screens/BusinessList.tsx',import.meta.url),'utf8');
assert.match(app,/arrivalListQuery\(arrivalQueue\)/);
assert.match(app,/load\(1,appliedQuery\.current\)/);
assert.match(app,/load\(page\+1,appliedQuery\.current\)/);
assert.match(app,/load\(page\+1,appliedQuery\.current,true\)/);
assert.doesNotMatch(app,/notArrived:arrivalQueue/);
});

View File

@ -4,11 +4,11 @@ import {readFile} from 'node:fs/promises';
import {createRequire} from 'node:module';
import vm from 'node:vm';
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
async function screen({permission=true,cancel=false,failOnce=false}={}){
async function screen({permission=true,cancel=false,failOnce=false,fileSize=1000}={}){
const source=await readFile(new URL('../src/screens/ArrivalPhotos.tsx',import.meta.url),'utf8'),compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
const values=[],refs=[],calls=[],camera=[],cleanup=[];let state=0,ref=0,photos=[],fail=failOnce;
const react={...React,useState:v=>{const i=state++;if(!(i in values))values[i]=v;return[values[i],v=>{values[i]=typeof v==='function'?v(values[i]):v;}];},useRef:v=>{const i=ref++;return refs[i]??={current:v};},useEffect:fn=>{const value=fn();if(value)cleanup.push(value);}};
const picker={async requestCameraPermissionsAsync(){return {granted:permission};},async launchCameraAsync(options){camera.push(options);return {canceled:cancel,assets:[{uri:'file:///camera.jpg',mimeType:'image/jpeg',fileSize:1000}]};},async launchImageLibraryAsync(){return {canceled:cancel,assets:[{uri:'file:///album.jpg',mimeType:'image/jpeg',fileSize:1000}]};}};
const picker={async requestCameraPermissionsAsync(){return {granted:permission};},async launchCameraAsync(options){camera.push(options);return {canceled:cancel,assets:[{uri:'file:///camera.jpg',mimeType:'image/jpeg',fileSize}]};},async launchImageLibraryAsync(){return {canceled:cancel,assets:[{uri:'file:///album.jpg',mimeType:'image/jpeg',fileSize}]};}};
class Form {values=new Map();append(k,v){this.values.set(k,v);}get(k){return this.values.get(k);}}
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Image:'Image',Platform:{OS:'android'}},'expo-image-picker':picker,'expo-crypto':{randomUUID:()=> '11111111-1111-4111-8111-111111111111'},'../ui':{Button:'Button',Note:'Note',s:{}},'../files':{ProtectedImage:'ProtectedImage'}};
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:n=>imports[n]||require(n),FormData:Form,AbortController});
@ -26,3 +26,6 @@ test('taking a photo sends an image-only camera request and private multipart up
test('album uploads can retry the same photo identifier after failure',async()=>{
const page=await screen({failOnce:true});await page.button('从相册选择').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.photos[0].error,'模拟上传失败');page.render();await page.button('重试上传').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls[0].options.body.get('uploadId'),page.calls[1].options.body.get('uploadId'));assert.ok(page.photos[0].id);page.cleanup();
});
test('camera photos above 5MB are accepted, while the new 20MB limit is enforced',async()=>{
for(const [size,allowed]of [[7*1024*1024,true],[20*1024*1024,true],[20*1024*1024+1,false]]){const page=await screen({fileSize:size});await page.button('拍照').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls.length,allowed?1:0);page.cleanup();}
});

View File

@ -15,8 +15,8 @@ async function screen({mode='arrival',failure=false}={}){
const record={id:101,arrivalNo:'DH-101',arrivalQuantity:3,acceptanceStatus:0,label:'DH-101 · 3 个'};
const react={...React,useState:initial=>{const i=cursor++;if(!(i in values))values[i]=initial;return[values[i],v=>values[i]=typeof v==='function'?v(values[i]):v];},useRef:initial=>{const i=refCursor++;return refs[i]??= {current:initial};},useEffect:()=>{}};
const native={Modal:'Modal',ScrollView:'ScrollView',View:'View',KeyboardAvoidingView:'KeyboardAvoidingView',Platform:{OS:'android'}};
const ui={useTheme:()=>({bg:'#fff'}),s:{},Button:'Button',Card:'Card',Choice:'Choice',Field:'Field',Heading:'Heading',Note:'Note'};
const imports={'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}}};
const ui={useTheme:()=>({bg:'#fff'}),s:{},Button:'Button',Card:'Card',Choice:'Choice',DateField:'DateField',Field:'Field',Heading:'Heading',Note:'Note'};
const imports={'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}},'../hooks/useOperationDraft':{useOperationDraft:()=>({ready:true,restored:false,error:'',saveNow:async()=>{},clear:async()=>{}})}};
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>imports[name]||require(name),AbortController});
const api={async request(path,options){calls.push({path,...options});if(failure)throw Error('timeout');return {data:{}};}};
const render=()=>{cursor=0;refCursor=0;return module.exports.ArrivalOperation({api,row:{id:10,materialName:'电机',remainingQuantity:2,unit:'个'},mode,close(){},done(){done++;}});};

View File

@ -29,7 +29,7 @@ test('a failed acknowledgement keeps unread messages intact and never changes ot
await center.load();await center.mark();assert.match(center.snapshot().error,/离线/);assert.equal(center.snapshot().items[0].readAt,null);assert.equal(calls.filter(call=>call.options?.method).length,1);
});
test('announcements use only their own read API, and remounting after disposal safely restarts',async()=>{
const {center,calls}=fixture(async path=>path==='/system/notifications'?{data:{items:[],hasMore:false}}:path==='/system/notice/listTop'?{data:[{noticeId:7,noticeTitle:'公告',isRead:false}]}:{code:200});
const {center,calls}=fixture(async path=>path==='/system/notifications'?{data:{items:[],hasMore:false}}:path==='/system/notice/published'?{data:{items:[{noticeId:7,noticeTitle:'公告',isRead:false}],hasMore:false}}:{code:200});
await center.tab('notices');await center.mark();assert.equal(calls.at(-1).path,'/system/notice/markReadAll');assert.deepEqual(calls.at(-1).options,{method:'POST',query:{ids:'7'}});
center.dispose();center.start();await new Promise(resolve=>setImmediate(resolve));assert.equal(center.snapshot().busy,false);assert.equal(center.snapshot().tab,'inbox');center.dispose();
});

View File

@ -5,6 +5,7 @@ import {readFileSync} from 'node:fs';
import vm from 'node:vm';
import {arrivalLayout} from '../src/core/arrival-layout.ts';
import {workspaceColumns} from '../src/core/workspace-layout.ts';
import {workspaceTasks,shortcutOrder} from '../src/core/workspace-tasks.ts';
import {modules} from '../src/core/modules.ts';
test('home tiles switch to a single column on narrow screens and larger system text',()=>{
@ -28,28 +29,28 @@ function compile(name,imports){const exports={};const code=ts.transpileModule(re
test('home keeps all allowed field-operation shortcuts without the oversized marketing block',()=>{
for(const width of [320,360,393])for(const fontScale of [1,1.3,1.6]){
const opened=[],visited=[];
const module=compile('screens/Workspace.tsx',{react:React,'react/jsx-runtime':require('react/jsx-runtime'),
const module=compile('screens/Workspace.tsx',{react:{...React,useState:v=>[typeof v==='function'?v():v,()=>{}],useEffect:()=>{}},'react/jsx-runtime':require('react/jsx-runtime'),
'react-native':{Image:'Image',Pressable:'Pressable',ScrollView:'ScrollView',Text:'Text',View:'View',useWindowDimensions:()=>({width,fontScale})},
'expo-constants':{},'expo-updates':{},'../ui':{Card:'Card',Icon:'Icon',Avatar:'Avatar',Heading:'Heading',Note:'Note',s:{row:{},page:{}},useTheme:()=>({})},
'../core/workspace-layout':{workspaceColumns},'../core/account':{imagePath:()=>''},'../files':{usePrivateImage:()=>undefined}});
'../typography':{Text:'Text',useReadingScale:()=>1},'../core/preferences':{},'../core/workspace-tasks':{workspaceTasks,shortcutOrder},'../core/workspace-layout':{workspaceColumns},'../core/account':{imagePath:()=>''},'../files':{usePrivateImage:()=>undefined}});
const all=nodes(module.Workspace({api:{},user:{userName:'测试管理员'},modules,ai:true,open:v=>opened.push(v),go:v=>visited.push(v)}));
for(const title of ['到货验收','待入库','出库领用','移库','现场盘点']){
const node=all.find(n=>n.props.accessibilityLabel===title);assert.ok(node);node.props.onPress();
const node=all.find(n=>n.props.accessibilityLabel===title&&typeof n.props.style==='function');assert.ok(node);node.props.onPress();
assert.equal(node.props.style({pressed:false}).flexBasis,workspaceColumns(width,fontScale)===1?'100%':'47%');
}
assert.deepEqual(opened,['arrival','pending','use','move','count']);
all.find(n=>n.props.accessibilityLabel==='查看全部业务').props.onPress();assert.deepEqual(visited,['business']);
assert.ok(all.filter(n=>n.type==='Text').every(n=>(n.props.style.fontSize||0)<=20));
all.find(n=>n.props.title==='全部业务').props.onPress();assert.deepEqual(visited,['business']);
assert.ok(all.filter(n=>n.type==='Text').every(n=>(n.props.style.fontSize||0)<=22));
}
});
test('shared reading and button text have explicit sizes, wrap safely and keep system scaling enabled',()=>{
const ui=compile('ui.tsx',{react:{...React,useContext:()=>({mode:'light'})},'react/jsx-runtime':require('react/jsx-runtime'),
'react-native':{ActivityIndicator:'Loading',Image:'Image',Pressable:'Pressable',ScrollView:'ScrollView',Text:'Text',TextInput:'TextInput',View:'View',StyleSheet:{create:v=>v},useColorScheme:()=> 'light'},
'@expo/vector-icons/Ionicons':'Icon','./core/appearance':{lightTheme:{},darkTheme:{}}});
'@expo/vector-icons/Ionicons':'Icon','./core/appearance':{lightTheme:{},darkTheme:{}},'./typography':{Text:'Text',TextInput:'TextInput'},'./controls/Choice':{Choice:'Choice'},'./controls/DateField':{DateField:'DateField'}});
const button=nodes(ui.Button({title:'核对后重试原请求',onPress(){}})).find(n=>n.type==='Text');
assert.equal(button.props.style.fontSize,15);assert.equal(button.props.style.flexShrink,1);
assert.equal(ui.Note({children:'说明'}).props.style.fontSize,15);
assert.equal(ui.Heading({children:'标题'}).props.style.fontSize,20);
assert.equal(button.props.style.fontSize,14);assert.equal(button.props.style.flexShrink,1);
assert.equal(ui.Note({children:'说明'}).props.style.fontSize,13);
assert.equal(ui.Heading({children:'标题'}).props.style.fontSize,18);
assert.ok(ui.s.button.minHeight>=44);assert.equal(ui.s.button.height,undefined);
for(const file of ['ui.tsx','screens/Workspace.tsx','screens/ArrivalListParts.tsx'])assert.doesNotMatch(readFileSync(new URL('../src/'+file,import.meta.url),'utf8'),/allowFontScaling=\{false\}/);
});

View File

@ -47,3 +47,16 @@ test('explicit cancellation is not reported as a server business failure',async(
if(opt.signal.aborted)throw Error('aborted');return response({code:200});});ctl.abort();
await assert.rejects(api.request('/getInfo',{signal:ctl.signal}),e=>e.code===499);
});
test('HTTP upload rejections and HTML proxy errors are not mislabeled as an offline network',async()=>{
for(const [status,expected]of [[413,'大小限制'],[504,'超时'],[500,'处理未完成']]){const api=new ApiClient('http://192.168.1.1',()=>{},async()=>new Response('<html>proxy response</html>',{status}));await assert.rejects(api.request('/warehouse/purchase/arrival/photos/1',{method:'POST'}),e=>e.code===status&&e.message.includes(expected)&&!e.message.includes('公司网络'));}
let expired=0;const api=new ApiClient('http://192.168.1.1',()=>expired++,async()=>new Response('',{status:401}));api.authenticate('fake');await assert.rejects(api.request('/getInfo'),e=>e.code===401);assert.equal(expired,1);
});
test('arrival photo preview accepts up to 20MB while other private images retain their existing limit',async()=>{
const api=new ApiClient('http://192.168.1.1',()=>{},async()=>new Response(new Uint8Array([1,2,3]),{headers:{'Content-Type':'image/jpeg','Content-Length':String(12*1024*1024)}}));
await assert.rejects(api.request('/image',{responseType:'image'}),e=>e.code===413);
assert.equal(await api.request('/image',{responseType:'image',imageMaxBytes:20*1024*1024}),'data:image/jpeg;base64,AQID');
});
test('an unreadable success response preserves uncertain-mutation handling without blaming the network',async()=>{
let calls=0;const api=new ApiClient('http://192.168.1.1',()=>{},async()=>{calls++;return new Response('<html>unexpected gateway page</html>');});
await assert.rejects(api.request('/system/feedback',{method:'POST',body:{title:'test'}}),e=>e.code===503&&e.message.includes('核对处理状态')&&!e.message.includes('公司网络'));assert.equal(calls,1);
});

View File

@ -4,11 +4,11 @@ import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=name=>readFileSync(new URL(`../src/${name}`,import.meta.url),'utf8');
test('mobile JSX has no unexpected literal text below a native View',()=>{
for(const file of ['App.tsx','ui.tsx','files.tsx','dialogs.tsx','screens/Account.tsx','screens/Feedback.tsx','screens/Workspace.tsx','screens/Assistant.tsx','screens/ArrivalOperation.tsx','screens/ArrivalActions.tsx','screens/ArrivalListParts.tsx','screens/ServerConnection.tsx']){
for(const file of ['App.tsx','AppUpdates.tsx','AppUpdateDialog.tsx','ui.tsx','files.tsx','dialogs.tsx','screens/Account.tsx','screens/Feedback.tsx','screens/Workspace.tsx','screens/Assistant.tsx','screens/ArrivalOperation.tsx','screens/ArrivalActions.tsx','screens/ArrivalListParts.tsx','screens/ServerConnection.tsx','screens/BusinessList.tsx','screens/BatchOperation.tsx','screens/NoticeContent.tsx','screens/FileLibrary.tsx','controls/Choice.tsx','controls/DateField.tsx']){
const parsed=ts.createSourceFile(file,source(file),ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
function walk(node){if(ts.isJsxElement(node)&&['View','ScrollView','Pressable','KeyboardAvoidingView','SafeAreaView'].includes(node.openingElement.tagName.getText(parsed)))for(const child of node.children)if(ts.isJsxText(child))assert.equal(child.text.trim(),'',`${file} has bare native text`);ts.forEachChild(node,walk);}walk(parsed);
}
assert.match(source('App.tsx'),/\{!!module\.search&&/,'an empty search key must not render a raw string in View');
assert.match(source('screens/BusinessList.tsx'),/\{!!module\.search&&/,'an empty search key must not render a raw string in View');
});
test('mobile feedback is always scoped to my records and never calls administrative handling',()=>{
const file=source('screens/Feedback.tsx');assert.match(file,/all:false/);assert.doesNotMatch(file,/all:true|\/handle/);

View File

@ -1,14 +1,53 @@
import test from 'node:test';import assert from 'node:assert/strict';
import { createUpdateCheck } from '../src/core/updates.ts';
test('one check per launch, one fetch, next launch only: never force reload',async()=>{
const states=[];let checks=0,fetches=0,finish;
const run=createUpdateCheck({isEnabled:true,checkForUpdateAsync:()=>{checks++;return new Promise(r=>finish=r);},fetchUpdateAsync:async()=>{fetches++;}},s=>states.push(s));
const first=run(),second=run();assert.equal(first,second);finish({isAvailable:true});await first;await run();
assert.equal(checks,1);assert.equal(fetches,1);assert.deepEqual(states,['checking','downloading','ready']);
import {createUpdateController} from '../src/core/updates.ts';
function fixture(overrides={},options={}){
const views=[],calls={checks:0,fetches:0,reloads:0};
const driver={isEnabled:true,checkForUpdateAsync:async()=>{calls.checks++;return {isAvailable:true};},fetchUpdateAsync:async()=>{calls.fetches++;return {isNew:true};},reloadAsync:async()=>{calls.reloads++;},...overrides};
const controller=createUpdateController(driver,v=>views.push(v),options);return {controller,views,calls,last:()=>views.at(-1)};
}
test('concurrent checks share one request, download then prompt, and never automatically reload',async()=>{
let finish;const f=fixture({checkForUpdateAsync:()=>{f.calls.checks++;return new Promise(r=>finish=r);}});
const one=f.controller.check(),two=f.controller.check(true);assert.equal(one,two);await Promise.resolve();finish({isAvailable:true});await one;await f.controller.check();
assert.deepEqual(f.calls,{checks:1,fetches:1,reloads:0});assert.deepEqual(f.views.map(v=>v.state),['checking','downloading','ready']);assert.equal(f.last().visible,true);
});
test('disabled, no update and offline preserve current app',async()=>{
for(const [enabled,result,expected] of [[false,false,['disabled']],[true,false,['checking','current']],[true,'error',['checking','failed']]]){
const states=[];const run=createUpdateCheck({isEnabled:enabled,checkForUpdateAsync:async()=>{if(result==='error')throw Error('offline');return{isAvailable:result};},fetchUpdateAsync:async()=>assert.fail('no fetch expected')},s=>states.push(s));
await run();assert.deepEqual(states,expected);
}
test('disabled, no update and offline retain the current app without a popup',async()=>{
for(const [enabled,result,expected]of [[false,false,['disabled']],[true,false,['checking','current']],[true,'error',['checking','failed']]]){
const f=fixture({isEnabled:enabled,checkForUpdateAsync:async()=>{if(result==='error')throw Error('offline');return {isAvailable:result};}});await f.controller.check();assert.deepEqual(f.views.map(v=>v.state),expected);assert.equal(f.last().visible,false);assert.equal(f.calls.fetches,0);assert.equal(f.calls.reloads,0);
}
});
test('foreground checks are throttled, while a manual check may retry immediately',async()=>{
let time=0;const f=fixture({checkForUpdateAsync:async()=>{f.calls.checks++;return {isAvailable:false};}},{now:()=>time});await f.controller.check();
time=100;f.controller.foreground(false);f.controller.foreground(true);await f.controller.check();assert.equal(f.calls.checks,1);
time=15*60_000;f.controller.foreground(true);await f.controller.check();assert.equal(f.calls.checks,2);await f.controller.check(true);assert.equal(f.calls.checks,3);
});
test('an offline launch can recover on returning to foreground after a minute',async()=>{
let time=0;const f=fixture({checkForUpdateAsync:async()=>{f.calls.checks++;if(f.calls.checks===1)throw Error('offline');return {isAvailable:true};}},{now:()=>time});await f.controller.check();assert.equal(f.last().state,'failed');
time=59_999;f.controller.foreground(true);await f.controller.check();assert.equal(f.calls.checks,1);time=60_000;f.controller.foreground(true);await f.controller.check();assert.equal(f.calls.checks,2);assert.equal(f.last().visible,true);
});
test('background downloads wait for foreground; postponing never prompts repeatedly or reloads',async()=>{
const f=fixture({},{active:false});await f.controller.check();assert.equal(f.last().state,'ready');assert.equal(f.last().visible,false);f.controller.foreground(true);assert.equal(f.last().visible,true);
f.controller.foreground(false);assert.equal(f.last().visible,false);f.controller.foreground(true);assert.equal(f.last().visible,true);
f.controller.later();f.controller.foreground(false);f.controller.foreground(true);assert.equal(f.last().visible,false);assert.equal(f.calls.reloads,0);await f.controller.restart();assert.equal(f.calls.reloads,0);
await f.controller.check(true);assert.equal(f.last().visible,true);assert.equal(f.calls.checks,1);
});
test('a download finishing while backgrounded does not show a hidden native dialog',async()=>{
let finish;const f=fixture({fetchUpdateAsync:()=>new Promise(r=>finish=r)});const pending=f.controller.check();await Promise.resolve();await Promise.resolve();f.controller.foreground(false);finish({isNew:true});await pending;assert.equal(f.last().visible,false);f.controller.foreground(true);assert.equal(f.last().visible,true);
});
test('only a confirmed ready visible prompt reloads, even on double taps',async()=>{
let finish;const f=fixture({reloadAsync:()=>{f.calls.reloads++;return new Promise(r=>finish=r);}});await f.controller.restart();assert.equal(f.calls.reloads,0);await f.controller.check();
const one=f.controller.restart(),two=f.controller.restart();assert.equal(one,two);assert.equal(f.last().restarting,true);f.controller.later();assert.equal(f.last().visible,true);await Promise.resolve();assert.equal(f.calls.reloads,1);finish();await one;
});
test('reload failure retains the downloaded update and allows a confirmed retry',async()=>{
const f=fixture({reloadAsync:async()=>{f.calls.reloads++;if(f.calls.reloads===1)throw Error('native error');}});await f.controller.check();await f.controller.restart();assert.equal(f.last().state,'ready');assert.equal(f.last().restarting,false);assert.match(f.last().error,/重试/);await f.controller.restart();assert.equal(f.calls.reloads,2);
});
test('a changed server response is not called a ready update and approved rollback works',async()=>{
const f=fixture({fetchUpdateAsync:async()=>({isNew:false})});await f.controller.check();assert.equal(f.last().state,'current');assert.equal(f.last().visible,false);
const rollback=fixture({checkForUpdateAsync:async()=>({isAvailable:false,isRollBackToEmbedded:true}),fetchUpdateAsync:async()=>({isNew:false,isRollBackToEmbedded:true})});await rollback.controller.check();assert.equal(rollback.last().state,'ready');assert.equal(rollback.calls.reloads,0);
});
test('failed downloads can retry without ever losing the current working app',async()=>{
const f=fixture({fetchUpdateAsync:async()=>{f.calls.fetches++;if(f.calls.fetches===1)throw Error('network');return {isNew:true};}});await f.controller.check();assert.equal(f.last().state,'failed');assert.equal(f.last().visible,false);await f.controller.check(true);assert.equal(f.last().state,'ready');assert.equal(f.calls.reloads,0);
});
test('unmount ignores late check/download callbacks and cannot start a reload',async()=>{
let finish;const f=fixture({checkForUpdateAsync:()=>new Promise(r=>finish=r)});const pending=f.controller.check();await Promise.resolve();f.controller.dispose();finish({isAvailable:true});await pending;assert.deepEqual(f.views.map(v=>v.state),['checking']);assert.equal(f.calls.fetches,0);
const ready=fixture();await ready.controller.check();const reload=ready.controller.restart();ready.controller.dispose();await reload;assert.equal(ready.calls.reloads,0);
});

View File

@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {createRequire} from 'node:module';
import vm from 'node:vm';
import * as review from '../src/core/draft-review.ts';
import * as helpers from '../src/core/assistant-display.ts';
const require=createRequire(import.meta.url),React=require('react'),{renderToStaticMarkup}=require('react-dom/server'),ts=require('typescript');
@ -32,7 +33,7 @@ async function renderAssistant(session=null){
const Text=({children})=>React.createElement('span',null,children);
let calls=0;const mockReact={...React,useState:initial=>React.useState(calls++===0?session:initial)};
const module={exports:{}};
const imports={react:mockReact,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View,Text,Pressable:View,ScrollView:View,KeyboardAvoidingView:View,ActivityIndicator:()=>null,Image:()=>null,Platform:{OS:'web'}},'../dialogs':{Dialog:{alert(){}}},'expo-document-picker':{},'../ui':{useTheme:()=>({text:'#000',muted:'#666',line:'#ddd'}),s:{},Button:({title})=>React.createElement(Text,null,title),Card:View,Heading:Text,Note:Text,Field:()=>null,Icon:()=>null},'../files':{ProtectedImage:()=>null},'../core/modules':{display:String},'../core/assistant-display':helpers};
const imports={'../typography':{Text,TextInput:()=>null},'../core/draft-review':review,react:mockReact,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View,Text,Pressable:View,ScrollView:View,KeyboardAvoidingView:View,ActivityIndicator:()=>null,Image:()=>null,Platform:{OS:'web'}},'../dialogs':{Dialog:{alert(){}}},'expo-document-picker':{},'../ui':{useTheme:()=>({text:'#000',muted:'#666',line:'#ddd'}),s:{},Button:({title})=>React.createElement(Text,null,title),Card:View,Heading:Text,Note:Text,Field:()=>null,Icon:()=>null},'../files':{ProtectedImage:()=>null},'../core/modules':{display:String},'../core/assistant-display':helpers};
vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>name.endsWith('.png')?'asset':name in imports?imports[name]:require(name),setInterval,clearInterval});
return renderToStaticMarkup(React.createElement(module.exports.Assistant,{api:{}}));
}
@ -48,10 +49,10 @@ test('preview confirmation portal is not mounted beneath later business dialogs'
assert.match(source,/if\(Platform\.OS!=='web'\|\|!prompt\)return null/);
});
test('move form shows availability, has fill-all action, and keeps overstock validation',async()=>{
const source=await readFile(new URL('../src/App.tsx',import.meta.url),'utf8');
assert.match(source,/当前可用数量/);assert.match(source,/title="全部移库"/);
assert.match(source,/n>Number\(row.stockNum\)/);
assert.match(source,/本次数量超过当前可用库存(\$\{display\(row.stockNum\)\}/);
const form=await readFile(new URL('../src/screens/BatchOperation.tsx',import.meta.url),'utf8');
assert.match(form,/全部填入可用数量/);assert.match(form,/available\(kind,row\)/);
const core=await readFile(new URL('../src/core/stock-operations.ts',import.meta.url),'utf8');
assert.match(core,/quantity>available\(kind,row\)/);assert.match(core,/当前可用数量/);
});
test('expanding history and more fields does not force readers back to the latest message',async()=>{
const source=await readFile(new URL('../src/screens/Assistant.tsx',import.meta.url),'utf8');

View File

@ -38,6 +38,16 @@ public class SysNoticeController extends BaseController
@Autowired
private ISysNoticeReadService noticeReadService;
/** Authenticated reader history; the query only returns published announcements. */
@GetMapping("/published")
public AjaxResult published(@org.springframework.web.bind.annotation.RequestParam(required = false) Long beforeId,
@org.springframework.web.bind.annotation.RequestParam(defaultValue = "") String keyword,
@org.springframework.web.bind.annotation.RequestParam(defaultValue = "false") boolean unreadOnly,
@org.springframework.web.bind.annotation.RequestParam(defaultValue = "20") int limit)
{
return success(noticeReadService.publishedPage(getUserId(), beforeId, keyword, unreadOnly, limit));
}
/**
* 获取通知公告列表
*/

View File

@ -17,7 +17,7 @@ public class ArchiveAnalytics {
private final JdbcTemplate db; private final ArchiveAccess access; private final ObjectMapper json;
public ArchiveAnalytics(JdbcTemplate db,ArchiveAccess access,ObjectMapper json){this.db=db;this.access=access;this.json=json.copy().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);}
public void authorize(){access.refresh();if(!access.analyze())throw new ServiceException("仅项目资料管理员可查看成本汇总",403);}
public List<Map<String,Object>> people(String keyword){authorize();String k="%"+ArchiveService.text(keyword,80,false)+"%";return db.queryForList("select u.user_id id,u.nick_name name,u.user_name account from sys_user u where u.del_flag='0' and "+ArchiveAccess.businessPersonPredicate("u")+" and exists(select 1 from project_archive_project p where p.manager_id=u.user_id) and (u.nick_name like ? or u.user_name like ?) order by u.user_id limit 100",k,k);}
public List<Map<String,Object>> people(String keyword){authorize();String k="%"+ArchiveService.text(keyword,80,false)+"%";return db.queryForList("select u.user_id id,u.nick_name name,u.user_name account from sys_user u where u.del_flag='0' and "+ArchiveAccess.businessPersonPredicate("u")+" and exists(select 1 from project_archive_project p where p.manager_id=u.user_id) and (u.nick_name like ? or u.user_name like ?) order by "+com.ruoyi.common.utils.PersonNameOrder.sql("u")+" limit 100",k,k);}
public record Filter(LocalDate from,LocalDate to,String basis,Long managerId,String state,String mode,Integer page,Integer size) {}
@Transactional(readOnly=true,isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public Map<String,Object> report(Filter f){

View File

@ -13,8 +13,9 @@ public final class ArchiveCosts {
public Labor(Long userId,String duty,BigDecimal days,BigDecimal rate){this(userId,duty,days,rate,null);}
}
public record Material(String supplier,String content,BigDecimal gross,BigDecimal tax) {}
public record Travel(String purpose,Long userId,LocalDate date,BigDecimal amount,String name) {
public Travel(String purpose,Long userId,LocalDate date,BigDecimal amount){this(purpose,userId,date,amount,null);}
public record Travel(String purpose,Long userId,LocalDate date,BigDecimal amount,String name,List<Long> userIds) {
public Travel(String purpose,Long userId,LocalDate date,BigDecimal amount){this(purpose,userId,date,amount,null,null);}
public Travel(String purpose,Long userId,LocalDate date,BigDecimal amount,String name){this(purpose,userId,date,amount,name,null);}
}
public record Entertainment(Long userId,LocalDate date,BigDecimal amount,String name) {
public Entertainment(Long userId,LocalDate date,BigDecimal amount){this(userId,date,amount,null);}
@ -50,7 +51,9 @@ public final class ArchiveCosts {
if(row.supplier()==null||row.supplier().isBlank()||row.content()==null||row.content().isBlank()||row.gross()==null||!template&&row.tax()==null)complete=false;
if(row.gross()!=null&&(template||row.tax()!=null))material=material.add(template?row.gross():row.gross().subtract(row.tax()));}
if(template)material=material.divide(new BigDecimal("1.13"),2,RoundingMode.HALF_UP);
for(var row:list(input.travel())){boolean named=person(row.name(),row.userId(),template&&!Objects.equals(input.formatVersion(),3),db,names);checkText(row.purpose(),250);number(row.amount());
var travelers=new LinkedHashSet<Long>();for(var row:list(input.travel()))if(row.userIds()!=null)travelers.addAll(travelerIds(row));
if(!travelers.isEmpty()){var values=db.queryForList("select user_id,nick_name,user_name from sys_user where del_flag='0' and user_id in ("+String.join(",",Collections.nCopies(travelers.size(),"?"))+")",travelers.toArray());for(var row:values)names.put(((Number)row.get("user_id")).longValue(),Objects.toString(row.get("nick_name"),row.get("user_name").toString()));if(!names.keySet().containsAll(travelers))throw new ServiceException("所选出差人已不可用,请重新选择");}
for(var row:list(input.travel())){boolean named;if(row.userIds()!=null){checkText(row.name(),10100);named=!travelerIds(row).isEmpty();}else named=person(row.name(),row.userId(),template&&!Objects.equals(input.formatVersion(),3),db,names);checkText(row.purpose(),250);number(row.amount());
if(!named||row.date()==null||row.amount()==null||row.purpose()==null||row.purpose().isBlank())complete=false;
if(row.amount()!=null)travel=travel.add(row.amount());}
for(var row:list(input.entertainment())){boolean named=person(row.name(),row.userId(),template&&!Objects.equals(input.formatVersion(),3),db,names);number(row.amount());
@ -72,6 +75,11 @@ public final class ArchiveCosts {
result.put("profit",net!=null?net.subtract(total):null);
result.put("margin",net!=null&&net.signum()>0?net.subtract(total).divide(net,8,RoundingMode.HALF_UP):null);return result;
}
public static List<Long> travelerIds(Travel row){
var ids=row.userIds()!=null?row.userIds():row.userId()==null?List.<Long>of():List.of(row.userId());
if(ids.size()>100||ids.stream().anyMatch(id->id==null||id<=0))throw new ServiceException("每条差旅明细请选择最多100位有效的系统人员");
return List.copyOf(new LinkedHashSet<>(ids));
}
private static boolean person(String name,Long id,boolean template,JdbcTemplate db,Map<Long,String> names){checkText(name,100);
if(template){if(id!=null)throw new ServiceException("人员请手工填写姓名,不再关联系统账号");return name!=null&&!name.isBlank();}
if(name!=null&&!name.isBlank())return true;if(id==null)return false;if(names.containsKey(id))return true;

View File

@ -78,7 +78,7 @@ public class ArchiveExporter {
for(int i=0;i<Math.max(4,maps(data.get("materials")).size());i++){var row=i<maps(data.get("materials")).size()?maps(data.get("materials")).get(i):Map.<String,Object>of();costValues(s,r++,List.of(row.isEmpty()?"":i+1,value(row,"supplier"),value(row,"content"),value(row,"gross")));}
int materialEnd=r;costValues(s,r++,List.of("","","",""));if(!maps(data.get("materials")).isEmpty()){s.getRow(r-1).getCell(8).setCellFormula("SUM(I"+(materialStart+1)+":I"+materialEnd+")");if(current)s.getRow(8).getCell(2).setCellFormula("ROUND(I"+r+"/1.13,2)");}
r=costHeading(s,r+1,"差旅费",List.of("","出差事项","出差人","出差日期","差旅费用"));
for(int i=0;i<Math.max(5,maps(data.get("travel")).size());i++){var row=i<maps(data.get("travel")).size()?maps(data.get("travel")).get(i):Map.<String,Object>of();costValues(s,r++,List.of(row.isEmpty()?"":i+1,value(row,"purpose"),personName(names,row),"",value(row,"amount")));costDate(s,r-1,8,row.get("date"));}
for(int i=0;i<Math.max(5,maps(data.get("travel")).size());i++){var row=i<maps(data.get("travel")).size()?maps(data.get("travel")).get(i):Map.<String,Object>of();String travelers=personName(names,row);costValues(s,r++,List.of(row.isEmpty()?"":i+1,value(row,"purpose"),travelers,"",value(row,"amount")));costDate(s,r-1,8,row.get("date"));double units=travelers.codePoints().map(c->c>255?2:1).sum(),width=Math.max(6,s.getColumnWidth(7)/256d-2);s.getRow(r-1).setHeightInPoints((float)Math.min(409,Math.max(s.getRow(r-1).getHeightInPoints(),Math.ceil(units/width)*16)));}
r=costHeading(s,r+2,"招待费",List.of("","申请人","日期","费用"));
for(int i=0;i<Math.max(5,maps(data.get("entertainment")).size());i++){var row=i<maps(data.get("entertainment")).size()?maps(data.get("entertainment")).get(i):Map.<String,Object>of();costValues(s,r++,List.of(row.isEmpty()?"":i+1,personName(names,row),"",value(row,"amount")));costDate(s,r-1,7,row.get("date"));}
for(int row=4;row<=marginRow;row++){var c=s.getRow(row).getCell(2);var num=book.createCellStyle();num.cloneStyleFrom(c.getCellStyle());num.setDataFormat(book.createDataFormat().getFormat(row==marginRow?"0.00%":"#,##0.00"));c.setCellStyle(num);}
@ -87,7 +87,7 @@ public class ArchiveExporter {
private int costHeading(XSSFSheet s,int row,String title,List<String> headers){cell(s,row,5,title);s.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(row,row,5,title.equals("材料费用统计")?10:4+headers.size()));var h=costStyle(s.getWorkbook(),true);s.getRow(row).getCell(5).setCellStyle(h);costValues(s,row+1,headers);s.getRow(row+1).setHeightInPoints(Math.max(36,s.getRow(row+1).getHeightInPoints()));return row+2;}
private void costValues(XSSFSheet s,int row,List<?> values){var body=costStyle(s.getWorkbook(),false);for(int i=0;i<values.size();i++){cell(s,row,5+i,values.get(i));s.getRow(row).getCell(5+i).setCellStyle(body);if(i==0){var index=s.getWorkbook().createCellStyle();index.cloneStyleFrom(body);index.setDataFormat(s.getWorkbook().createDataFormat().getFormat("0"));s.getRow(row).getCell(5).setCellStyle(index);}}s.getRow(row).setHeightInPoints(Math.max(28,s.getRow(row).getHeightInPoints()));}
private XSSFCellStyle costStyle(XSSFWorkbook book,boolean title){var style=book.createCellStyle();var font=book.createFont();font.setFontName("宋体");font.setFontHeightInPoints((short)11);style.setFont(font);style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setWrapText(true);if(!title){style.setBorderBottom(BorderStyle.THIN);style.setBorderTop(BorderStyle.THIN);style.setBorderLeft(BorderStyle.THIN);style.setBorderRight(BorderStyle.THIN);style.setDataFormat(book.createDataFormat().getFormat("#,##0.00"));}return style;}
private static String personName(Map<String,Object> names,Map<String,Object> row){return row.get("name")!=null?row.get("name").toString():person(names,row.get("userId"));}
private static String personName(Map<String,Object> names,Map<String,Object> row){if(row.get("name")!=null)return row.get("name").toString();if(row.get("userIds") instanceof List<?> ids)return String.join("、",ids.stream().map(id->person(names,id)).toList());return person(names,row.get("userId"));}
private XSSFWorkbook template(String sheetName,boolean leftLabels)throws Exception{
try(InputStream input=getClass().getResourceAsStream("/templates/archive/reference.xlsx");var source=new XSSFWorkbook(Objects.requireNonNull(input))){
var out=new XSSFWorkbook();var sheet=out.createSheet(sheetName);var original=source.getSheet(sheetName);var styles=new HashMap<Short,XSSFCellStyle>();

View File

@ -18,7 +18,7 @@ final class ArchivePersonnel {
@SuppressWarnings("unchecked") private Map<String,Object> rates(Map<String,Object> setting){return (Map<String,Object>)setting.getOrDefault("rates",Map.of());}
private BigDecimal rate(Map<String,Object> rates,long id){return rates.containsKey(Long.toString(id))?new BigDecimal(rates.get(Long.toString(id)).toString()):DEFAULT_RATE;}
Map<String,Object> page(String keyword,int page,int size){String like="%"+ArchiveService.text(keyword,80,false)+"%";String visible=ArchiveAccess.businessPersonPredicate("");size=Math.max(1,Math.min(size,100));int total=db.queryForObject("select count(*) from sys_user where del_flag='0' and "+visible+" and (nick_name like ? or user_name like ?)",Integer.class,like,like);page=Math.max(1,Math.min(page,Math.max(1,(total+size-1)/size)));
var setting=setting();var rows=db.queryForList("select user_id id,nick_name name,user_name account from sys_user where del_flag='0' and "+visible+" and (nick_name like ? or user_name like ?) order by user_id limit ? offset ?",like,like,size,(page-1)*size);for(var row:rows)row.put("rate",rate(rates(setting),((Number)row.get("id")).longValue()));return Map.of("rows",rows,"total",total,"page",page,"version",setting.get("version"),"defaultRate",DEFAULT_RATE);}
var setting=setting();var rows=db.queryForList("select user_id id,nick_name name,user_name account from sys_user where del_flag='0' and "+visible+" and (nick_name like ? or user_name like ?) order by "+com.ruoyi.common.utils.PersonNameOrder.sql("")+" limit ? offset ?",like,like,size,(page-1)*size);for(var row:rows)row.put("rate",rate(rates(setting),((Number)row.get("id")).longValue()));return Map.of("rows",rows,"total",total,"page",page,"version",setting.get("version"),"defaultRate",DEFAULT_RATE);}
List<Map<String,Object>> people(String keyword,List<Long> ids){if(ids!=null&&(ids.size()>600||ids.stream().anyMatch(Objects::isNull)))throw new ServiceException("所选人员过多或无效");
var found=new LinkedHashMap<Long,Map<String,Object>>();for(var row:ArchiveService.maps(page(keyword,1,100).get("rows")))found.put(((Number)row.get("id")).longValue(),row);
if(ids!=null&&!ids.isEmpty()){String marks=String.join(",",Collections.nCopies(ids.size(),"?"));for(var row:db.queryForList("select user_id id,nick_name name,user_name account from sys_user where del_flag='0' and "+ArchiveAccess.businessPersonPredicate("")+" and user_id in ("+marks+")",ids.toArray()))found.put(((Number)row.get("id")).longValue(),row);}
@ -29,10 +29,10 @@ final class ArchivePersonnel {
db.queryForList("select version from project_archive_setting where setting_key='laborRates' for update");var setting=setting();if(((Number)setting.get("version")).intValue()!=version)throw new ServiceException("人员费用标准已更新,请刷新后再保存",409);
var values=new LinkedHashMap<>(rates(setting));values.put(Long.toString(userId),rate);try{db.update("update project_archive_setting set content_json=?,version=version+1 where setting_key='laborRates'",json.writeValueAsString(Map.of("rates",values)));}catch(com.fasterxml.jackson.core.JsonProcessingException e){throw new ServiceException("费用标准保存失败");}}
ArchiveCosts.Data prepare(ArchiveCosts.Data data){if(data==null)throw new ServiceException("请填写成本分析内容");if(data.formatVersion()!=null&&!Set.of(2,3).contains(data.formatVersion()))throw new ServiceException("成本分析格式版本不正确");
var ids=new LinkedHashSet<Long>();for(var r:list(data.labor()))if(r.userId()!=null)ids.add(r.userId());for(var r:list(data.travel()))if(r.userId()!=null)ids.add(r.userId());for(var r:list(data.entertainment()))if(r.userId()!=null)ids.add(r.userId());
var ids=new LinkedHashSet<Long>();for(var r:list(data.labor()))if(r.userId()!=null)ids.add(r.userId());for(var r:list(data.travel()))ids.addAll(ArchiveCosts.travelerIds(r));for(var r:list(data.entertainment()))if(r.userId()!=null)ids.add(r.userId());
var people=new HashMap<Long,String>();if(!ids.isEmpty()){String marks=String.join(",",Collections.nCopies(ids.size(),"?"));for(var row:db.queryForList("select user_id id,nick_name name,user_name account from sys_user where del_flag='0' and user_id in ("+marks+")",ids.toArray()))people.put(((Number)row.get("id")).longValue(),Objects.toString(row.get("name"),row.get("account").toString()));}
var rates=rates(setting());var labor=new ArrayList<ArchiveCosts.Labor>();for(var r:list(data.labor()))labor.add(new ArchiveCosts.Labor(r.userId(),r.duty(),r.days(),r.userId()==null?null:rate(rates,r.userId()),person(r.userId(),r.name(),people)));
var travel=new ArrayList<ArchiveCosts.Travel>();for(var r:list(data.travel()))travel.add(new ArchiveCosts.Travel(r.purpose(),r.userId(),r.date(),r.amount(),person(r.userId(),r.name(),people)));
var travel=new ArrayList<ArchiveCosts.Travel>();for(var r:list(data.travel())){var selected=ArchiveCosts.travelerIds(r);String name=selected.isEmpty()?person(null,r.name(),people):String.join("、",selected.stream().map(id->person(id,null,people)).toList());travel.add(new ArchiveCosts.Travel(r.purpose(),null,r.date(),r.amount(),name,selected));}
var entertainment=new ArrayList<ArchiveCosts.Entertainment>();for(var r:list(data.entertainment()))entertainment.add(new ArchiveCosts.Entertainment(r.userId(),r.date(),r.amount(),person(r.userId(),r.name(),people)));
return new ArchiveCosts.Data(data.incomeGross(),data.incomeTax(),labor,data.materials(),travel,entertainment,data.expenses(),Map.of(),data.income(),data.remarks(),data.formatVersion()==null?null:3);}
private String person(Long id,String name,Map<Long,String> people){if(id==null){if(name!=null&&!name.isBlank())throw new ServiceException("请从系统人员下拉框选择人员,历史手填姓名需重新选择");return "";}if(!people.containsKey(id))throw new ServiceException("所选系统人员已不可用,请重新选择");return people.get(id);}

View File

@ -46,7 +46,7 @@ final class ArchiveReview {
}
private static boolean same(Object a,Object b){if(a instanceof Number x&&b instanceof Number y)return new BigDecimal(x.toString()).compareTo(new BigDecimal(y.toString()))==0;return Objects.equals(a,b);}
private static String label(String path){
var names=Map.ofEntries(Map.entry("income","项目收入"),Map.entry("incomeGross","原含税收入"),Map.entry("incomeTax","原收入税额"),Map.entry("labor","预估人工成本"),Map.entry("materials","材料费用统计"),Map.entry("travel","差旅费"),Map.entry("entertainment","招待费"),Map.entry("expenses","其他成本费用"),Map.entry("signers","审核人员"),Map.entry("remarks","备注"),Map.entry("name","姓名/项目名称"),Map.entry("duty","职责分工"),Map.entry("days","投入工时(天)"),Map.entry("rate","费用标准"),Map.entry("supplier","供应商名称"),Map.entry("content","采购项目"),Map.entry("gross","采购成本(含税)"),Map.entry("tax","原税额"),Map.entry("purpose","出差事项"),Map.entry("date","日期"),Map.entry("amount","金额"),Map.entry("note","备注"),Map.entry("preparer","编制人"),Map.entry("finance","财务部门审核人"),Map.entry("projectOwner","项目负责人"),Map.entry("outsourcing","外包外协/佣金代理"),Map.entry("demand","需求部门负责人"),Map.entry("management","管理部门审核人"));
var names=Map.ofEntries(Map.entry("income","项目收入"),Map.entry("incomeGross","原含税收入"),Map.entry("incomeTax","原收入税额"),Map.entry("labor","预估人工成本"),Map.entry("materials","材料费用统计"),Map.entry("travel","差旅费"),Map.entry("entertainment","招待费"),Map.entry("expenses","其他成本费用"),Map.entry("signers","审核人员"),Map.entry("remarks","备注"),Map.entry("name","姓名/项目名称"),Map.entry("userIds","出差人"),Map.entry("duty","职责分工"),Map.entry("days","投入工时(天)"),Map.entry("rate","费用标准"),Map.entry("supplier","供应商名称"),Map.entry("content","采购项目"),Map.entry("gross","采购成本(含税)"),Map.entry("tax","原税额"),Map.entry("purpose","出差事项"),Map.entry("date","日期"),Map.entry("amount","金额"),Map.entry("note","备注"),Map.entry("preparer","编制人"),Map.entry("finance","财务部门审核人"),Map.entry("projectOwner","项目负责人"),Map.entry("outsourcing","外包外协/佣金代理"),Map.entry("demand","需求部门负责人"),Map.entry("management","管理部门审核人"));
var parts=new ArrayList<String>();for(String part:path.split("\\.")){int bracket=part.indexOf('[');if(part.matches(".+\\[[0-9]+\\]$")){int index=Integer.parseInt(part.substring(bracket+1,part.length()-1));parts.add(names.getOrDefault(part.substring(0,bracket),part.substring(0,bracket))+" · 第"+(index+1)+"行");}else parts.add(names.getOrDefault(part,part));}return String.join(" · ",parts);
}
}

View File

@ -75,9 +75,9 @@ public class ArchiveService {
var items=db.queryForList("select i.id,i.project_id,i.item_key,i.category,i.title,i.required,i.sort_order,i.applicable,i.state,case when i.item_key='costAnalysis' and exists(select 1 from project_archive_cost c where c.project_id=i.project_id) then 1 else 0 end has_cost_saved,(select count(*) from project_archive_document d where d.item_id=i.id and d.deleted=0 and d.current_file_id is not null) document_count from project_archive_item i where i.project_id in ("+placeholders+") order by i.project_id,i.sort_order,i.id",ids.toArray());
for(var i:items){@SuppressWarnings("unchecked") var own=(List<Map<String,Object>>)result.get(i.get("project_id").toString());own.add(i);}return result;}
public List<Map<String,Object>> managers(String keyword){access.refresh();String own=access.all()?"":" and u.user_id="+access.actor();String value="%"+text(keyword,80,false)+"%";
return db.queryForList("select u.user_id id,u.nick_name name,u.user_name account from sys_user u where u.status='0' and u.del_flag='0' and "+ArchiveAccess.businessPersonPredicate("u")+" and "+ArchiveAccess.managerPredicate("u")+own+" and (u.nick_name like ? or u.user_name like ?) order by u.user_id limit 50",value,value);}
return db.queryForList("select u.user_id id,u.nick_name name,u.user_name account from sys_user u where u.status='0' and u.del_flag='0' and "+ArchiveAccess.businessPersonPredicate("u")+" and "+ArchiveAccess.managerPredicate("u")+own+" and (u.nick_name like ? or u.user_name like ?) order by "+com.ruoyi.common.utils.PersonNameOrder.sql("u")+" limit 50",value,value);}
public List<Map<String,Object>> people(Long project,String keyword){if(project==null)return managers(keyword);else access.project(project,false,false);
return db.queryForList("select user_id id,nick_name name,user_name account from sys_user where status='0' and del_flag='0' and "+ArchiveAccess.businessPersonPredicate("")+" and (nick_name like ? or user_name like ?) order by user_id limit 100","%"+text(keyword,80,false)+"%","%"+text(keyword,80,false)+"%");}
return db.queryForList("select user_id id,nick_name name,user_name account from sys_user where status='0' and del_flag='0' and "+ArchiveAccess.businessPersonPredicate("")+" and (nick_name like ? or user_name like ?) order by "+com.ruoyi.common.utils.PersonNameOrder.sql("")+" limit 100","%"+text(keyword,80,false)+"%","%"+text(keyword,80,false)+"%");}
@Transactional public void manager(long id,ManagerInput input){var p=access.project(id,false,true);access.require("assign");if(!access.all())throw ArchiveAccess.unavailable();ArchiveAccess.version(p,input.version());
if(!"EDITING".equals(p.get("archive_state")))throw new ServiceException("请先退回维护或重新开放,再交接项目经理");
String reason=text(input.reason(),1000,true);if(input.managerId()==null)throw new ServiceException("请选择新的项目经理");access.activeManager(input.managerId());

View File

@ -33,7 +33,7 @@ public class ResumableUploadService {
@Transactional public Info start(Start input) {
if(input==null)throw new ServiceException("请选择文件");
int max=targets.authorize(input.target()); requireStorage();
String name=validateName(input.name()); requireHash(input.sha256()); targets.validateName(input.target(),name);
String name=Set.of("fileLibrary","noticeAttachment").contains(input.target().purpose())?com.ruoyi.system.service.impl.ManagedFileService.safeName(input.name()):validateName(input.name()); requireHash(input.sha256()); targets.validateName(input.target(),name);
if(input.size()<=0 || input.size()>max)throw new ServiceException("附件为空或超过当前业务大小限制");
long owner=SecurityUtils.getUserId();
// Serializes same-owner init/quota checks across tabs AND backend instances.
@ -47,7 +47,7 @@ public class ResumableUploadService {
db.update("update sys_file_upload set fingerprint=null where id=?",row.get("id"));
}
var quota=db.queryForMap("select count(*) n,coalesce(sum(byte_size),0) bytes from sys_file_upload where owner_id=? and status='OPEN' and expires_at>current_timestamp",owner);
long pendingLimit="projectArchiveDocument".equals(input.target().purpose())?5L*1024*1024*1024:250L*1024*1024;
long pendingLimit=Set.of("projectArchiveDocument","fileLibrary","noticeAttachment").contains(input.target().purpose())?5L*1024*1024*1024:250L*1024*1024;
if(((Number)quota.get("n")).intValue()>=5 || ((Number)quota.get("bytes")).longValue()+input.size()>pendingLimit)throw new ServiceException("有较多未完成的上传,请先继续或取消已有文件");
String id=UUID.randomUUID().toString();
db.update("insert into sys_file_upload(id,owner_id,fingerprint,target_json,original_name,byte_size,sha256,expires_at) values(?,?,?,?,?,?,?,date_add(current_timestamp,interval 24 hour))",id,owner,fingerprint,encode(input.target()),name,input.size(),input.sha256());
@ -92,7 +92,7 @@ public class ResumableUploadService {
int size=((Number)row.get("byte_size")).intValue(), total=total(size);
var chunks=db.queryForList("select chunk_index,sha256 from sys_file_upload_chunk where upload_id=? order by chunk_index",id);
if(chunks.size()!=total)throw new ServiceException("文件尚未传完,请继续上传剩余分片");
if(Set.of("projectDocument","projectArchiveDocument").contains(target.purpose())) {
if(Set.of("projectDocument","projectArchiveDocument","fileLibrary","noticeAttachment").contains(target.purpose())) {
Object result=completeProjectFile(target,id,row,chunks,size);
db.update("update sys_file_upload set status='DONE',result_json=? where id=?",encode(result),id);
row.put("status","DONE");row.put("result_json",encode(result));return info(row);

View File

@ -34,6 +34,7 @@ public class UploadTargets {
@Autowired private JdbcTemplate db;
@Autowired private ObjectMapper json;
@Autowired private com.ruoyi.common.storage.BusinessFileStorage storage;
@Autowired private com.ruoyi.system.service.impl.ManagedFileService managedFiles;
public int authorize(Target target) {
if (target == null || target.purpose() == null) throw new ServiceException("请选择附件所属业务");
@ -43,6 +44,9 @@ public class UploadTargets {
if(user==null || !"0".equals(user.getStatus()) || !"0".equals(user.getDelFlag())) throw new ServiceException("登录状态已失效,请重新登录",401);
login.setUser(user); login.setDeptId(user.getDeptId()); login.setPermissions(currentPermissions.getMenuPermission(user));
switch (target.purpose()) {
case "fileLibrary", "noticeAttachment" -> {
plain(target,false);return managedFiles.authorizeUpload(target.purpose().equals("noticeAttachment"));
}
case "projectArchiveDocument" -> {
plain(target,true);archiveDocuments.authorize(target.targetId(),true,false);
return com.ruoyi.web.service.archive.ArchiveDocuments.MAX_BYTES;
@ -71,6 +75,7 @@ public class UploadTargets {
}
}
public void validateName(Target target, String name) {
if(Set.of("fileLibrary","noticeAttachment").contains(target.purpose())){com.ruoyi.system.service.impl.ManagedFileService.safeName(name);return;}
String extension=name.substring(name.lastIndexOf('.')+1).toLowerCase(Locale.ROOT);
Set<String> standard=Set.of("pdf","png","jpg","jpeg","doc","docx","xls","xlsx","txt","zip");
Set<String> cad=Set.of("step","stp","stl","iges","igs","dxf","dwg","sldprt","sldasm","slddrw");
@ -88,6 +93,7 @@ public class UploadTargets {
public Object finish(Target target, String id, MultipartFile file) {
authorize(target);
return switch(target.purpose()) {
case "fileLibrary", "noticeAttachment" -> managedFiles.upload(target.purpose().equals("noticeAttachment"),id,file);
case "projectArchiveDocument" -> archiveDocuments.upload(target.targetId(),id,file);
case "projectDocument" -> projectDocuments.upload(target.targetId(),id,file);
case "product" -> products.upload(target.targetId(),id,file);
@ -104,6 +110,7 @@ public class UploadTargets {
Object id=meta.get("id"); if (id==null) return false;
Long owner=SecurityUtils.getUserId();
boolean active=switch(target.purpose()) {
case "fileLibrary", "noticeAttachment" -> managedFiles.alive(target.purpose().equals("noticeAttachment"),id.toString());
case "projectArchiveDocument" -> archiveDocuments.alive(target.targetId(),id.toString());
case "projectDocument" -> projectDocuments.alive(target.targetId(),id.toString());
case "product" -> count("select count(*) from production_product_attachment where id=? and product_id=? and owner_id=? and deleted=0",id,target.targetId(),owner);
@ -114,7 +121,7 @@ public class UploadTargets {
default -> false;
};
if(!active)return false;
String area=switch(target.purpose()){case "projectArchiveDocument"->"project-archive";case "projectDocument"->"project-workspace";case "product"->"product";case "purchase"->"purchase";case "supplier"->"supplier-license";case "feedback"->"feedback";default->"assistant";};
String area=switch(target.purpose()){case "fileLibrary","noticeAttachment"->"managed-file";case "projectArchiveDocument"->"project-archive";case "projectDocument"->"project-workspace";case "product"->"product";case "purchase"->"purchase";case "supplier"->"supplier-license";case "feedback"->"feedback";default->"assistant";};
try{return storage.exists(area+"/"+id+".bin",null);}catch(java.io.IOException error){throw new ServiceException("文件存储暂时不可用,请稍后继续");}
}
private boolean assistantAlive(Object id) { try { return !assistant.available(null,id).isEmpty(); } catch(ServiceException expired) { return false; } }

View File

@ -53,7 +53,7 @@ public class KpiService {
db.update("update kpi_period set closed=?,phase=?,workflow_state=?,version=version+1 where id=?","ENDED".equals(target)?1:0,KpiWorkflow.phase(target),target,id);
stageNotifications.started(id,target,input.version()+1);
}
public List<Map<String,Object>> users(String keyword){requireManager();String key="%"+text(keyword,100,"搜索条件")+"%";return db.queryForList("select u.user_id as id,u.user_name as account,coalesce(nullif(u.nick_name,''),u.user_name) as name,u.email,coalesce(d.dept_name,'') as deptName from sys_user u left join sys_dept d on d.dept_id=u.dept_id where u.del_flag='0' and u.status='0' and (u.user_name like ? or u.nick_name like ? or d.dept_name like ?) order by u.user_id limit 100",key,key,key);}
public List<Map<String,Object>> users(String keyword){requireManager();String key="%"+text(keyword,100,"搜索条件")+"%";return db.queryForList("select u.user_id as id,u.user_name as account,coalesce(nullif(u.nick_name,''),u.user_name) as name,u.email,coalesce(d.dept_name,'') as deptName from sys_user u left join sys_dept d on d.dept_id=u.dept_id where u.del_flag='0' and u.status='0' and (u.user_name like ? or u.nick_name like ? or d.dept_name like ?) order by "+com.ruoyi.common.utils.PersonNameOrder.sql("u")+" limit 100",key,key,key);}
@Transactional
public Map<String,Integer> assign(Long periodId,Assignment input){
requireManager();var p=period(periodId,true);open(p);if(!KpiWorkflow.canAssign(Objects.toString(p.get("workflowState"))))throw new ServiceException("当前阶段的参与人员已确定,不能继续分配");if(input.userIds()==null||input.userIds().isEmpty()||input.userIds().size()>200||input.userIds().stream().anyMatch(Objects::isNull))throw new ServiceException("请选择1至200名员工");

View File

@ -20,7 +20,7 @@ import static org.mockito.Mockito.*;
class ProjectWorkspaceFlowTest {
JdbcTemplate db;ProjectWorkspaceAccess access;ProjectTeamService teams;ProjectAchievementService achievements;ProjectDocumentService documents;BusinessFileStorage storage;ProjectWorkspaceNotifications notices;com.ruoyi.common.notification.NotificationGateway gateway;
@BeforeEach void setup()throws Exception {
db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa",""));
db=new com.ruoyi.projectdev.PinyinJdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa",""));
db.execute("create table sys_user(user_id bigint primary key,user_name varchar(64),nick_name varchar(64),status varchar(1) default '0',del_flag varchar(1) default '0')");
db.execute("insert into sys_user(user_id,user_name,nick_name) values(1,'admin','管理员'),(2,'manager','经理'),(3,'member','成员'),(4,'other','其他人')");
db.execute("create table project_info(id bigint primary key,project_name varchar(100),project_code varchar(64),project_type varchar(20) default 'RESEARCH',project_status int,version int default 0,total_amount decimal(16,2) default 0,del_flag varchar(1) default '0',currency varchar(10) default 'CNY',remark varchar(1000),create_by varchar(64),create_time timestamp,update_by varchar(64),update_time timestamp)");

View File

@ -22,6 +22,13 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class PurchaseArrivalPhotosTest {
@Test void cameraImagesAboveFiveMegabytesCanBeStoredAndRead()throws Exception{
var raster=new BufferedImage(1600,1600,BufferedImage.TYPE_INT_RGB);var random=new Random(73);
for(int y=0;y<1600;y++)for(int x=0;x<1600;x++)raster.setRGB(x,y,random.nextInt(1<<24));
var out=new ByteArrayOutputStream();ImageIO.write(raster,"png",out);raster.flush();byte[] bytes=out.toByteArray();
assertTrue(bytes.length>5*1024*1024);assertTrue(bytes.length<20*1024*1024);
service.upload(10L,A,new MockMultipartFile("file","camera.png","image/png",bytes));assertArrayEquals(bytes,service.content(A).bytes());
}
static final String A="11111111-1111-4111-8111-111111111111",B="22222222-2222-4222-8222-222222222222";
@TempDir Path temp;
JdbcTemplate db;PurchaseArrivalPhotoService service;TransactionTemplate tx;MockedStatic<SecurityUtils> security;BusinessFileStorage storage;Map<String,byte[]> files;
@ -64,7 +71,7 @@ class PurchaseArrivalPhotosTest {
@Test void rejectsBadFilesLimitsAndUnconfirmedPurchasesBeforeStoring()throws Exception{
assertThrows(ServiceException.class,()->service.upload(30L,A,image()));
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","fake.png","image/png","not an image".getBytes())));
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","large.png","image/png",new byte[5*1024*1024+1])));
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","large.png","image/png",new byte[20*1024*1024+1])));
assertThrows(ServiceException.class,()->PurchaseArrivalPhotoService.ids(List.of(A,A)));assertThrows(ServiceException.class,()->PurchaseArrivalPhotoService.ids(Collections.nCopies(10,A)));
assertThrows(ServiceException.class,()->service.content("../private"));verifyNoInteractions(storage);
}

View File

@ -22,10 +22,27 @@ import static org.mockito.Mockito.*;
/** Entirely isolated schema and mock storage. No development/prod business data or notifications. */
class ArchiveFlowTest {
@Test void travelSupportsMultipleSystemPeopleWithSingleAmountAndUnchangedExportColumns()throws Exception{
long p=create("MULTI-TRAVEL");int[] widths;
try(var before=new ArchiveExporter().cost(archive.detail(p))){widths=java.util.stream.IntStream.range(0,11).map(i->before.getSheetAt(0).getColumnWidth(i)).toArray();}
var travel=new ArchiveCosts.Travel("共同出差",null,java.time.LocalDate.of(2026,10,28),new BigDecimal("125.50"),"伪造姓名",List.of(2L,2L,5L));
var input=new ArchiveCosts.Data(null,null,List.of(),List.of(),List.of(travel),List.of(),List.of(),Map.of(),new BigDecimal("1000"),Map.of(),3);
var parsed=new ObjectMapper().findAndRegisterModules().readValue(new ObjectMapper().findAndRegisterModules().writeValueAsString(input),ArchiveCosts.Data.class);
archive.cost(p,new ArchiveService.CostInput(version(p),parsed));var detail=archive.detail(p);var saved=(Map<?,?>)detail.get("cost");var data=(Map<?,?>)saved.get("data");var row=ArchiveService.maps(data.get("travel")).get(0);
assertEquals(List.of(2L,5L),((List<?>)row.get("userIds")).stream().map(v->((Number)v).longValue()).toList());assertNull(row.get("userId"));assertEquals("经理甲、普通成员",row.get("name"));assertEquals(true,saved.get("complete"));assertEquals(0,new BigDecimal("125.50").compareTo(new BigDecimal(saved.get("totalCost").toString())));assertEquals(0,new BigDecimal("874.50").compareTo(new BigDecimal(saved.get("profit").toString())));
try(var book=new ArchiveExporter().cost(detail)){var sheet=book.getSheetAt(0);assertArrayEquals(widths,java.util.stream.IntStream.range(0,11).map(sheet::getColumnWidth).toArray());boolean found=false;for(var line:sheet){var cell=line.getCell(7);if(cell!=null&&cell.getCellType()==org.apache.poi.ss.usermodel.CellType.STRING&&cell.getStringCellValue().equals("经理甲、普通成员")){found=true;assertTrue(line.getHeightInPoints()>=28);}}assertTrue(found);}
var invalid=new ArchiveCosts.Data(null,null,List.of(),List.of(),List.of(new ArchiveCosts.Travel("出差",null,java.time.LocalDate.now(),BigDecimal.ONE,"任意姓名",List.of(2L,99999L))),List.of(),List.of(),Map.of(),BigDecimal.TEN,Map.of(),3);
assertThrows(ServiceException.class,()->archive.cost(p,new ArchiveService.CostInput(version(p),invalid)));assertEquals(saved,archive.detail(p).get("cost"));
}
@Test void travelClearDoesNotRestoreAnOldSinglePersonAndInvalidIdsAreRejected(){
long p=create("CLEAR-TRAVEL");var input=new ArchiveCosts.Data(null,null,List.of(),List.of(),List.of(new ArchiveCosts.Travel("出差",2L,java.time.LocalDate.now(),BigDecimal.ONE,"",List.of())),List.of(),List.of(),Map.of(),BigDecimal.TEN,Map.of(),3);
archive.cost(p,new ArchiveService.CostInput(version(p),input));var saved=(Map<?,?>)archive.detail(p).get("cost");assertEquals(false,saved.get("complete"));assertEquals(List.of(),ArchiveService.maps(((Map<?,?>)saved.get("data")).get("travel")).get(0).get("userIds"));
assertThrows(ServiceException.class,()->ArchiveCosts.travelerIds(new ArchiveCosts.Travel("",null,null,null,"",Arrays.asList(2L,null))));assertThrows(ServiceException.class,()->ArchiveCosts.travelerIds(new ArchiveCosts.Travel("",null,null,null,"",List.of(-1L))));
}
JdbcTemplate db;ArchiveAccess access;ArchiveService archive;ArchiveDocuments docs;BusinessFileStorage storage;ISysUserService users;SysPermissionService permissions;
Map<Long,Set<String>> grants=new HashMap<>();
@BeforeEach void setup()throws Exception{
db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa",""));
db=new com.ruoyi.projectdev.PinyinJdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa",""));
db.execute("create table sys_user(user_id bigint primary key,user_name varchar(64),nick_name varchar(64),status varchar(1) default '0',del_flag varchar(1) default '0')");
db.execute("insert into sys_user(user_id,user_name,nick_name) values(1,'admin','管理员'),(2,'manager','经理甲'),(3,'leader','领导'),(4,'other','经理乙'),(5,'member','普通成员')");
db.execute("insert into sys_user(user_id,user_name,nick_name) values(6,'archiveAdmin','资料管理员')");

View File

@ -26,7 +26,7 @@ import org.springframework.stereotype.Component;
@Component
public class BusinessFileStorage {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BusinessFileStorage.class);
private static final Set<String> AREAS = Set.of("public", "purchase", "supplier-license", "feedback", "assistant", "batch-import", "export", "collaboration", "product", "upload", "project-workspace", "project-archive");
private static final Set<String> AREAS = Set.of("public", "purchase", "supplier-license", "feedback", "assistant", "batch-import", "export", "collaboration", "product", "upload", "project-workspace", "project-archive", "managed-file");
private final MinioProperties properties;
private final MinioClient client;
@ -95,7 +95,7 @@ public class BusinessFileStorage {
/** Bounded business uploads. Caller owns the input and must authenticate the target first. */
public void saveStream(String key,InputStream input,long size,String contentType) throws IOException {
checked(key);
long maximum=key.startsWith("project-archive/")?1024L*1024*1024:100L*1024*1024;
long maximum=key.startsWith("project-archive/")||key.startsWith("managed-file/")?1024L*1024*1024:100L*1024*1024;
if(!isEnabled()||size<1||size>maximum)throw new IOException("文件存储配置或大小不正确");
try {
client.putObject(PutObjectArgs.builder().bucket(properties.getBucketName()).object(key)

View File

@ -4,6 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import jakarta.servlet.DispatcherType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@ -98,6 +99,9 @@ public class SecurityConfig
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// 注解标记允许匿名访问的url
.authorizeHttpRequests((requests) -> {
// Only the container's continuation is exempt. The initial REQUEST and
// business file authorization still run before any stream is opened.
requests.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll();
permitAllUrl.getUrls().forEach(url -> requests.requestMatchers(url).permitAll());
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
requests.requestMatchers("/login", "/register", "/captchaImage").permitAll()

View File

@ -4,7 +4,8 @@
<!--suppress SqlNoDataSourceInspection -->
<mapper namespace="com.ruoyi.project.manage.mapper.PmUserMapper">
<select id="selectCandidates" resultType="java.util.LinkedHashMap">
SELECT user_id AS userId,nick_name AS name FROM sys_user WHERE status='0' AND del_flag='0' AND nick_name LIKE #{nicknamePattern} ORDER BY user_id LIMIT 30
<bind name="personNameOrder" value="@com.ruoyi.common.utils.PersonNameOrder@sql('')"/>
SELECT user_id AS userId,nick_name AS name FROM sys_user WHERE status='0' AND del_flag='0' AND nick_name LIKE #{nicknamePattern} ORDER BY ${personNameOrder} LIMIT 30
</select>
<select id="selectActiveUser" resultType="java.util.LinkedHashMap">

View File

@ -17,6 +17,13 @@
<dependencies>
<!-- Verify Android APK v1/v2/v3 signatures before offering a package to users. -->
<dependency>
<groupId>com.android.tools.build</groupId>
<artifactId>apksig</artifactId>
<version>8.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
@ -30,4 +37,8 @@
</dependencies>
<repositories>
<repository><id>google-android</id><url>https://dl.google.com/dl/android/maven2/</url></repository>
</repositories>
</project>

View File

@ -32,7 +32,7 @@ public class ProjectAchievementService {
access.permission("project:achievement:edit","project:project:manage");access.member(project,false,false);
String q=text(keyword,80,"人员关键字").replace("!","!!").replace("%","!%").replace("_","!_");
// Minimal directory data only; participation does not grant project membership or edit rights.
return db.queryForList("select user_id userId,user_name userName,nick_name name from sys_user where status='0' and del_flag='0' and (user_name like ? escape '!' or nick_name like ? escape '!') order by user_id limit 50","%"+q+"%","%"+q+"%").stream().map(row->{Map<String,Object> user=new LinkedHashMap<>();user.put("userId",((Number)row.get("userId")).longValue());user.put("userName",Objects.toString(row.get("userName"),""));user.put("name",Objects.toString(row.get("name"),row.get("userName").toString()));return user;}).toList();
return db.queryForList("select user_id userId,user_name userName,nick_name name from sys_user where status='0' and del_flag='0' and (user_name like ? escape '!' or nick_name like ? escape '!') order by "+com.ruoyi.common.utils.PersonNameOrder.sql("")+" limit 50","%"+q+"%","%"+q+"%").stream().map(row->{Map<String,Object> user=new LinkedHashMap<>();user.put("userId",((Number)row.get("userId")).longValue());user.put("userName",Objects.toString(row.get("userName"),""));user.put("name",Objects.toString(row.get("name"),row.get("userName").toString()));return user;}).toList();
}
public Map<String,Object> page(Long project,String kind,String keyword,int page,int size){
access.permission("project:achievement:list","project:achievement:edit","project:project:manage");access.requireReady();if(page<1||page>100000||size<1||size>100)throw new ServiceException("分页范围不正确");

View File

@ -28,7 +28,7 @@ public class ProjectTeamService {
var meta=db.queryForList("select amount_confirmed amountConfirmed,award_date awardDate,award_amount awardAmount,start_reason startReason from project_workspace_meta where project_id=?",id);row.put("meta",meta.isEmpty()?Map.of("amountConfirmed",true):meta.get(0));return row;
}
public List<Map<String,Object>> members(long id){access.member(id,false,false);return db.queryForList("select m.user_id userId,u.user_name userName,u.nick_name name,m.member_role role,u.status from pm_collab_project_member m join sys_user u on u.user_id=m.user_id where m.project_id=? order by (m.member_role='MANAGER') desc,m.id",id);}
public List<Map<String,Object>> users(long id,String keyword){access.permission("project:project:edit","project:project:manage");access.member(id,true,false);String q=text(keyword,80,"人员关键字").replace("!","!!").replace("%","!%").replace("_","!_");return db.queryForList("select user_id userId,user_name userName,nick_name name from sys_user where status='0' and del_flag='0' and (user_name like ? escape '!' or nick_name like ? escape '!') order by user_id limit 50","%"+q+"%","%"+q+"%");}
public List<Map<String,Object>> users(long id,String keyword){access.permission("project:project:edit","project:project:manage");access.member(id,true,false);String q=text(keyword,80,"人员关键字").replace("!","!!").replace("%","!%").replace("_","!_");return db.queryForList("select user_id userId,user_name userName,nick_name name from sys_user where status='0' and del_flag='0' and (user_name like ? escape '!' or nick_name like ? escape '!') order by "+com.ruoyi.common.utils.PersonNameOrder.sql("")+" limit 50","%"+q+"%","%"+q+"%");}
@Transactional public void initialize(long id,boolean confirmed){
access.requireReady();long actor=access.actor();

View File

@ -31,6 +31,18 @@ public class SysNotice extends BaseEntity
/** 公告状态(0正常 1关闭) */
private String status;
@JsonProperty(access=JsonProperty.Access.WRITE_ONLY)
private java.util.List<String> attachmentIds;
@JsonProperty(access=JsonProperty.Access.READ_ONLY)
private java.util.List<ManagedFileInfo> attachments=java.util.List.of();
@JsonProperty(access=JsonProperty.Access.READ_ONLY)
private int attachmentCount;
public java.util.List<String> getAttachmentIds(){return attachmentIds;}
public void setAttachmentIds(java.util.List<String> ids){this.attachmentIds=ids;}
public java.util.List<ManagedFileInfo> getAttachments(){return attachments;}
public void setAttachments(java.util.List<ManagedFileInfo> files){this.attachments=files;}
public int getAttachmentCount(){return attachmentCount;}
public void setAttachmentCount(int count){this.attachmentCount=count;}
/** 是否已读 */
@JsonProperty("isRead")

View File

@ -13,6 +13,8 @@ import com.ruoyi.system.domain.SysNoticeRead;
*/
public interface SysNoticeReadMapper
{
List<SysNotice> selectPublishedPage(@Param("userId") Long userId, @Param("beforeId") Long beforeId,
@Param("keyword") String keyword, @Param("unreadOnly") boolean unreadOnly, @Param("limit") int limit);
/**
* 新增已读记录(忽略重复)
*

View File

@ -11,6 +11,7 @@ import com.ruoyi.system.domain.SysNotice;
*/
public interface ISysNoticeReadService
{
Map<String, Object> publishedPage(Long userId, Long beforeId, String keyword, boolean unreadOnly, int limit);
/**
* 标记已读(幂等,重复调用不报错)
*

View File

@ -17,6 +17,23 @@ import com.ruoyi.system.service.ISysNoticeReadService;
@Service
public class SysNoticeReadServiceImpl implements ISysNoticeReadService
{
@Override
public Map<String, Object> publishedPage(Long userId, Long beforeId, String keyword, boolean unreadOnly, int limit)
{
if (userId == null || userId <= 0) throw new com.ruoyi.common.exception.ServiceException("请先登录", 401);
if (beforeId != null && beforeId <= 0) throw new com.ruoyi.common.exception.ServiceException("分页位置无效");
int size = Math.max(1, Math.min(limit, 50));
String search = keyword == null ? "" : keyword.trim();
if (search.length() > 100) throw new com.ruoyi.common.exception.ServiceException("搜索内容最多100字");
List<SysNotice> found = noticeReadMapper.selectPublishedPage(userId, beforeId, search, unreadOnly, size + 1);
boolean more = found.size() > size;
List<SysNotice> items = more ? found.subList(0, size) : found;
Map<String, Object> result = new java.util.LinkedHashMap<>();
result.put("items", items);
result.put("hasMore", more);
result.put("nextCursor", items.isEmpty() ? null : items.get(items.size() - 1).getNoticeId());
return result;
}
@Autowired
private SysNoticeReadMapper noticeReadMapper;

View File

@ -17,6 +17,7 @@ public class SysNoticeServiceImpl implements ISysNoticeService
{
@Autowired
private SysNoticeMapper noticeMapper;
@Autowired private ManagedFileService files;
/**
* 查询公告信息
@ -27,7 +28,9 @@ public class SysNoticeServiceImpl implements ISysNoticeService
@Override
public SysNotice selectNoticeById(Long noticeId)
{
return noticeMapper.selectNoticeById(noticeId);
var notice=noticeMapper.selectNoticeById(noticeId);
if(notice!=null)notice.setAttachments(files.noticeFiles(noticeId));
return notice;
}
/**
@ -49,9 +52,12 @@ public class SysNoticeServiceImpl implements ISysNoticeService
* @return 结果
*/
@Override
@org.springframework.transaction.annotation.Transactional
public int insertNotice(SysNotice notice)
{
return noticeMapper.insertNotice(notice);
int rows=noticeMapper.insertNotice(notice);
if(rows>0&&notice.getAttachmentIds()!=null)files.bindNotice(notice.getNoticeId(),notice.getAttachmentIds());
return rows;
}
/**
@ -61,9 +67,12 @@ public class SysNoticeServiceImpl implements ISysNoticeService
* @return 结果
*/
@Override
@org.springframework.transaction.annotation.Transactional
public int updateNotice(SysNotice notice)
{
return noticeMapper.updateNotice(notice);
int rows=noticeMapper.updateNotice(notice);
if(rows>0&&notice.getAttachmentIds()!=null)files.bindNotice(notice.getNoticeId(),notice.getAttachmentIds());
return rows;
}
/**

View File

@ -24,7 +24,7 @@ import java.util.*;
/** Private, owner-bound draft photos become immutable evidence when an arrival is saved. */
@Service
public class PurchaseArrivalPhotoService {
public static final int MAX_BYTES=5*1024*1024,MAX_PHOTOS=9;
public static final int MAX_BYTES=20*1024*1024,MAX_PHOTOS=9;
private final JdbcTemplate db;
private final BusinessFileStorage storage;
public PurchaseArrivalPhotoService(JdbcTemplate db,BusinessFileStorage storage){this.db=db;this.storage=storage;}
@ -36,7 +36,7 @@ public class PurchaseArrivalPhotoService {
String extension=WarehouseFileUtils.validateUpload(file,MAX_BYTES,Set.of("jpg","jpeg","png","webp"));
byte[] bytes;
try(var input=file.getInputStream()){bytes=input.readNBytes(MAX_BYTES+1);}catch(IOException e){throw new ServiceException("照片读取失败,请重新选择");}
if(bytes.length==0||bytes.length>MAX_BYTES)throw new ServiceException("每张照片不能超过5MB");
if(bytes.length==0||bytes.length>MAX_BYTES)throw new ServiceException("每张照片不能超过20MB");
String type=FeedbackImageStorage.validateContent(bytes,extension),name=PurchaseDocumentService.safeName(file.getOriginalFilename()),sha=digest(bytes);
var existing=db.queryForList("select * from purchase_arrival_photo where id=?",id);
if(!existing.isEmpty()){

View File

@ -15,12 +15,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<result property="attachmentCount" column="attachment_count" />
</resultMap>
<sql id="selectNoticeVo">
select sn.notice_id, sn.notice_title, sn.notice_type, cast(sn.notice_content as char) as notice_content,
sn.status, coalesce(cu.nick_name, sn.create_by) as create_by, sn.create_time,
coalesce(uu.nick_name, sn.update_by) as update_by, sn.update_time, sn.remark
coalesce(uu.nick_name, sn.update_by) as update_by, sn.update_time, sn.remark,
(select count(*) from sys_notice_attachment a join sys_managed_file f on f.id=a.file_id where a.notice_id=sn.notice_id and f.deleted=0) as attachment_count
from sys_notice sn
left join sys_user cu on cu.user_name = sn.create_by
left join sys_user uu on uu.user_name = sn.update_by
@ -48,7 +50,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
order by sn.notice_id desc
</select>
<insert id="insertNotice" parameterType="SysNotice">
<insert id="insertNotice" parameterType="SysNotice" useGeneratedKeys="true" keyProperty="noticeId">
insert into sys_notice (
<if test="noticeTitle != null and noticeTitle != '' ">notice_title, </if>
<if test="noticeType != null and noticeType != '' ">notice_type, </if>

View File

@ -3,6 +3,18 @@
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.SysNoticeReadMapper">
<select id="selectPublishedPage" resultType="SysNotice">
select n.notice_id as noticeId, n.notice_title as noticeTitle, n.notice_type as noticeType,
n.create_time as createTime, n.create_by as createBy,
case when r.notice_id is not null then true else false end as isRead
from sys_notice n
left join sys_notice_read r on r.notice_id = n.notice_id and r.user_id = #{userId}
where n.status = '0'
<if test="beforeId != null">and n.notice_id &lt; #{beforeId}</if>
<if test="keyword != null and keyword != ''">and locate(#{keyword}, n.notice_title) &gt; 0</if>
<if test="unreadOnly">and r.notice_id is null</if>
order by n.notice_id desc limit #{limit}
</select>
<resultMap type="SysNoticeRead" id="SysNoticeReadResult">
<id property="readId" column="read_id" />

View File

@ -91,6 +91,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
<bind name="personNameOrder" value="@com.ruoyi.common.utils.PersonNameOrder@sql('u')"/>
order by ${personNameOrder}
</select>
<select id="selectAllocatedList" parameterType="SysUser" resultMap="SysUserResult">
@ -108,6 +110,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
<bind name="personNameOrder" value="@com.ruoyi.common.utils.PersonNameOrder@sql('u')"/>
order by ${personNameOrder}
</select>
<select id="selectUnallocatedList" parameterType="SysUser" resultMap="SysUserResult">
@ -126,6 +130,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
<bind name="personNameOrder" value="@com.ruoyi.common.utils.PersonNameOrder@sql('u')"/>
order by ${personNameOrder}
</select>
<select id="selectUserByUserName" parameterType="String" resultMap="SysUserResult">

View File

@ -19,6 +19,7 @@
"@vueuse/core": "14.1.0",
"axios": "1.13.2",
"clipboard": "2.0.11",
"dompurify": "^3.4.17",
"echarts": "5.6.0",
"element-plus": "2.13.1",
"file-saver": "2.0.5",
@ -2024,6 +2025,13 @@
"@types/node": "*"
}
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@types/web-bluetooth": {
"version": "0.0.21",
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
@ -3881,6 +3889,15 @@
"domelementtype": "1"
}
},
"node_modules/dompurify": {
"version": "3.4.17",
"resolved": "https://registry.npmmirror.com/dompurify/-/dompurify-3.4.17.tgz",
"integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/domutils": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-1.7.0.tgz",

View File

@ -32,6 +32,7 @@
"@vueuse/core": "14.1.0",
"axios": "1.13.2",
"clipboard": "2.0.11",
"dompurify": "^3.4.17",
"echarts": "5.6.0",
"element-plus": "2.13.1",
"file-saver": "2.0.5",

View File

@ -10,10 +10,11 @@ export function listNotice(query) {
}
// 查询公告详细
export function getNotice(noticeId) {
export function getNotice(noticeId,signal) {
return request({
url: '/system/notice/' + noticeId,
method: 'get'
method: 'get',
signal
})
}

View File

@ -1,8 +1,8 @@
import request from '@/utils/request'
export const ARRIVAL_PHOTO_LIMIT=9,ARRIVAL_PHOTO_BYTES=5*1024*1024
export const ARRIVAL_PHOTO_LIMIT=9,ARRIVAL_PHOTO_BYTES=20*1024*1024
export function arrivalPhotoError(file){
if(!['image/jpeg','image/png','image/webp'].includes(file.type)||! /\.(jpe?g|png|webp)$/i.test(file.name||''))return '请选择 JPG、PNG 或 WebP 图片'
if(!file.size||file.size>ARRIVAL_PHOTO_BYTES)return '每张照片不能超过5MB'
if(!file.size||file.size>ARRIVAL_PHOTO_BYTES)return '每张照片不能超过20MB'
return ''
}
export function uploadArrivalPhoto(requestId,uploadId,file,signal){const data=new FormData();data.append('file',file);data.append('uploadId',uploadId);return request({url:'/warehouse/purchase/arrival/photos/'+requestId,method:'post',headers:{'Content-Type':'multipart/form-data',repeatSubmit:false},data,signal,timeout:120000})}

View File

@ -2,7 +2,7 @@
<span v-if="compact" class="arrival-photos-trigger"><el-button v-if="!readonly||modelValue.length" link type="primary" :disabled="disabled&&!readonly" @click="open=true">{{ readonly?'查看照片':'到货照片' }}<span v-if="modelValue.length">({{ modelValue.length }})</span><span v-else>(选传)</span></el-button><span v-else>—</span></span>
<component :is="compact?'el-dialog':'div'" v-if="!compact||open" v-model="open" :title="title||'到货照片'" width="min(720px,94vw)" append-to-body class="arrival-photos-dialog" :close-on-click-modal="!busy" :show-close="!busy" :close-on-press-escape="!busy">
<section class="arrival-photos" :aria-busy="busy">
<div v-if="!readonly" class="arrival-photos-toolbar"><input ref="input" type="file" accept="image/jpeg,image/png,image/webp" multiple hidden :disabled="disabled||busy" @change="choose"/><el-button :disabled="disabled||busy||modelValue.length>=9" :loading="busy" @click="input.click()"><el-icon><Upload/></el-icon>上传照片</el-button><span>选传 · {{ modelValue.length }}/9 张 · 每张不超过5MB</span></div>
<div v-if="!readonly" class="arrival-photos-toolbar"><input ref="input" type="file" accept="image/jpeg,image/png,image/webp" multiple hidden :disabled="disabled||busy" @change="choose"/><el-button :disabled="disabled||busy||modelValue.length>=9" :loading="busy" @click="input.click()"><el-icon><Upload/></el-icon>上传照片</el-button><span>选传 · {{ modelValue.length }}/9 张 · 每张不超过20MB</span></div>
<div v-if="modelValue.length" class="arrival-photos-grid">
<article v-for="photo in modelValue" :key="photo.clientKey||photo.id" class="arrival-photo" :class="{'is-failed':photo.error}">
<el-image v-if="url(photo)" :src="url(photo)" fit="cover" :preview-src-list="previewUrls" :initial-index="Math.max(0,previewUrls.indexOf(url(photo)))" preview-teleported :alt="photo.name||'到货照片'"/>

View File

@ -42,11 +42,12 @@
</div>
<div class="notice-body">
<div v-if="hasContent" class="notice-content" v-html="detail.noticeContent" />
<notice-content v-if="hasContent" :html="detail.noticeContent" />
<div v-else class="notice-empty notice-empty--inner">
<el-icon><Document /></el-icon> 暂无内容
</div>
</div>
<section v-if="detail.attachments?.length" class="notice-attachments"><h3>附件({{ detail.attachments.length }})</h3><managed-attachments :model-value="detail.attachments"/></section>
</div>
</div>
</el-drawer>
@ -55,10 +56,14 @@
<script setup>
import { formatDateTime } from '@/utils/display-format'
import { getNotice } from '@/api/system/notice'
import ManagedAttachments from '@/components/ManagedFiles/Attachments.vue'
import NoticeContent from '@/components/NoticeContent/index.vue'
import {computed,onBeforeUnmount,ref} from 'vue'
const visible = ref(false)
const loading = ref(false)
const detail = ref(null)
let controller,generation=0
const isStatusNormal = computed(() => {
const status = detail.value && detail.value.status
@ -70,7 +75,8 @@ const hasContent = computed(() => {
return content != null && String(content).trim() !== ''
})
function open(payload) {
async function open(payload) {
const current=++generation;controller?.abort();controller=new AbortController()
let id = null
let preset = null
if (payload != null && typeof payload === 'object') {
@ -82,30 +88,24 @@ function open(payload) {
id = payload
}
visible.value = true
if (preset) {
detail.value = preset
return
}
detail.value=preset
if (id == null || id === '') {
detail.value = null
loading.value=false
return
}
loading.value = true
detail.value = null
getNotice(id).then(res => {
detail.value = res.data
}).catch(() => {
detail.value = null
}).finally(() => {
loading.value = false
})
try{const res=await getNotice(id,controller.signal);if(current===generation)detail.value=res.data}
catch{if(current===generation)detail.value=null}
finally{if(current===generation)loading.value=false}
}
function handleClose() {
generation++;controller?.abort()
visible.value = false
detail.value = null
loading.value = false
}
onBeforeUnmount(()=>{generation++;controller?.abort()})
defineExpose({
open
@ -113,6 +113,7 @@ defineExpose({
</script>
<style lang="scss" scoped>
.notice-attachments{margin-top:24px;padding-top:18px;border-top:1px solid var(--el-border-color-lighter)}.notice-attachments h3{font-size:14px;font-weight:600;margin:0 0 10px}
.notice-page {
max-width: 760px;
margin: 0 auto;

View File

@ -17,7 +17,12 @@
<el-button link type="primary" :disabled="reading" @click="backToList">← 返回列表</el-button>
<h2>{{ detail.title }}</h2>
<div class="detail-meta">{{ formatDateTime(detail.time) }} · {{ detail.read ? '已读' : '未读' }}</div>
<p class="message-content">{{ detail.content || '暂无正文' }}</p>
<notice-content v-if="detail.kind==='notices'" class="message-richcontent" :html="detail.content" />
<p v-else class="message-content">{{ detail.content || '暂无正文' }}</p>
<section v-if="detail.kind==='notices'&&detail.attachments?.length" class="message-attachments" aria-label="公告附件">
<h3>附件({{ detail.attachments.length }})</h3>
<managed-attachments :model-value="detail.attachments" />
</section>
<el-button v-if="kpiTarget" type="primary" plain @click="openKpi">查看KPI</el-button>
<el-button v-if="!detail.read" type="primary" :loading="reading" @click="markDetailRead">标为已读</el-button>
</section>
@ -64,6 +69,8 @@ import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { listNotifications, notificationUnread, getNotification, readNotificationBatch } from '@/api/system/notification'
import { listNoticeTop, getNotice, markNoticeReadAll } from '@/api/system/notice'
import ManagedAttachments from '@/components/ManagedFiles/Attachments.vue'
import NoticeContent from '@/components/NoticeContent/index.vue'
const router = useRouter(), user = useUserStore(), { proxy } = getCurrentInstance()
const visible = ref(false), tab = ref('inbox'), unreadOnly = ref(false), messages = ref([]), notices = ref([])
@ -115,10 +122,9 @@ async function openMessage(item) {
catch (cause) { if (epoch === generation && serial === detailSerial) failure(cause) }
finally { if (epoch === generation && serial === detailSerial) detailLoading.value = false }
}
function plainNotice(html) { const doc = new DOMParser().parseFromString(String(html || ''), 'text/html'); doc.querySelectorAll('script,style,iframe,object').forEach(item => item.remove()); doc.body.querySelectorAll('br,p,div,h1,h2,h3,h4,li,tr').forEach(item => item.append(doc.createTextNode('\n'))); return (doc.body.textContent || '').trim() }
async function openNotice(item) {
const epoch = generation, serial = ++detailSerial; detail.value = null; detailLoading.value = true; error.value = ''
try { const result = await getNotice(item.noticeId); if (epoch === generation && serial === detailSerial && visible.value) detail.value = { kind: 'notices', id: item.noticeId, title: result.data.noticeTitle, content: plainNotice(result.data.noticeContent), time: result.data.createTime, read: !!item.isRead } }
try { const result = await getNotice(item.noticeId); if (epoch === generation && serial === detailSerial && visible.value) detail.value = { kind: 'notices', id: item.noticeId, title: result.data.noticeTitle, content: result.data.noticeContent, attachments: result.data.attachments || [], time: result.data.createTime, read: !!item.isRead } }
catch (cause) { if (epoch === generation && serial === detailSerial) failure(cause) }
finally { if (epoch === generation && serial === detailSerial) detailLoading.value = false }
}
@ -171,5 +177,8 @@ onBeforeUnmount(() => { clearInterval(timer); reset() })
.center-footer { display:flex; justify-content:center; padding:20px 0; }
.message-detail h2 { font-size:20px; line-height:1.7; overflow-wrap:anywhere; margin:22px 0 10px; }
.message-content { white-space:pre-wrap; overflow-wrap:anywhere; line-height:1.9; margin:24px 0; color:var(--el-text-color-primary); }
.message-richcontent{margin:24px 0}
.message-attachments{margin:0 0 24px;padding-top:16px;border-top:1px solid var(--el-border-color-lighter)}
.message-attachments h3{margin:0 0 10px;font-size:14px;font-weight:600;color:var(--el-text-color-primary)}
@media(max-width:480px) { .message-item { grid-template-columns:minmax(0,1fr); } .message-excerpt { grid-column:auto; } .center-toolbar { gap:10px; } }
</style>

View File

@ -16,7 +16,7 @@ export function hashUploadFile(file,signal,onProgress){
export async function resumableUpload(file,target,{request,signal,onProgress=()=>{},hash=hashUploadFile,identity}={}){
const owner=identity?.()
const active=()=>{check(signal);if(identity&&identity()!==owner)throw Object.assign(new Error('登录账号已变化,上传已暂停,请在原账号重新选择文件继续'),{code:401})}
const max=target?.purpose==='projectArchiveDocument'?1024:target?.purpose==='projectDocument'?100:50
const max=['projectArchiveDocument','fileLibrary','noticeAttachment'].includes(target?.purpose)?1024:target?.purpose==='projectDocument'?100:50
if(!file?.size||file.size>max*1024*1024)throw new Error(`请选择非空附件,单个不能超过${max} MB`)
active();onProgress({phase:'hashing',percent:0,bytes:0})
const sha256=await hash(file,signal,bytes=>onProgress({phase:'hashing',percent:Math.floor(bytes/file.size*100),bytes}))

View File

@ -26,6 +26,7 @@
<span v-if="field.type==='calculated'">{{ row.days!=null&&row.rate!=null?money(round(Number(row.days)*Number(row.rate))):'—' }}</span>
<el-input-number v-else-if="field.type==='number'" v-model="row[field.key]" :min="0" :max="maxAmount" :precision="field.key==='days'?4:2" :controls="false" :disabled="!editable||saving" :aria-label="field.label"/>
<el-date-picker v-else-if="field.type==='date'" v-model="row[field.key]" type="date" value-format="YYYY-MM-DD" :disabled="!editable||saving" placeholder="选择日期"/>
<el-select v-else-if="field.multiple&&editable" v-model="row.userIds" multiple filterable remote clearable collapse-tags collapse-tags-tooltip :max-collapse-tags="2" :multiple-limit="100" :reserve-keyword="false" :remote-method="loadPeople" :loading="peopleLoading" :disabled="saving" :aria-label="field.label" placeholder="选择出差人(可多选)" @focus="loadPeople()" @change="ids=>selectTravelPeople(row,ids)"><el-option v-for="person in travelOptions(row)" :key="person.id" :label="person.name+(person.account?' / '+person.account:'')" :value="person.id"/></el-select>
<el-select v-else-if="field.person&&editable" v-model="row.userId" filterable remote clearable :remote-method="loadPeople" :loading="peopleLoading" :disabled="saving" :aria-label="field.label" :placeholder="row.name?row.name+'(请关联系统用户)':'选择系统人员'" @focus="loadPeople()" @change="id=>selectPerson(row,id,section.key)"><template #label="{label}">{{ row.name||label }}</template><el-option v-for="person in matchingPeople" :key="person.id" :label="person.name+' / '+person.account" :value="person.id"/></el-select>
<span v-else-if="field.person">{{ row.name||'—' }}</span>
<el-input v-else v-model="row[field.key]" :maxlength="field.max||180" :disabled="!editable||saving" :aria-label="field.label"/>
@ -40,11 +41,12 @@
</section>
</template>
<script setup>
import {sortPeople} from '@/utils/person-order'
import {ref,computed,watch,onBeforeUnmount,nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {archiveCost,archiveCostPeople} from '@/api/archive'
import {emptyCost,normalizeCost,costCategories} from './archive-model'
import {emptyCost,normalizeCost,costCategories,travelUserIds} from './archive-model'
import {costIssues,matchesPerson} from './archive-cost-validation'
const props=defineProps({projectId:Number,version:Number,cost:Object,editable:Boolean,footerActions:Boolean})
const emit=defineEmits(['changed','busy','dirty'])
@ -55,7 +57,7 @@ const dirty=computed(()=>JSON.stringify(form.value)!==baseline.value)
const sections=[
{key:'labor',title:'预估人工成本',fields:[{key:'name',label:'项目参与人员',person:true,width:180},{key:'duty',label:'职责分工',max:160},{key:'days',label:'投入工时(天)',type:'number',width:100},{key:'subtotal',label:'费用小计(元)',type:'calculated'}]},
{key:'materials',title:'材料费用统计',fields:[{key:'supplier',label:'供应商名称'},{key:'content',label:'采购项目',width:180,max:250},{key:'gross',label:'采购成本(含税)',type:'number',width:160}]},
{key:'travel',title:'差旅费',fields:[{key:'purpose',label:'出差事项',width:180,max:250},{key:'name',label:'出差人',person:true,max:100},{key:'date',label:'出差日期',type:'date',width:160},{key:'amount',label:'差旅费用',type:'number'}]},
{key:'travel',title:'差旅费',fields:[{key:'purpose',label:'出差事项',width:180,max:250},{key:'name',label:'出差人',person:true,multiple:true,width:220},{key:'date',label:'出差日期',type:'date',width:160},{key:'amount',label:'差旅费用',type:'number'}]},
{key:'entertainment',title:'招待费',fields:[{key:'name',label:'申请人',person:true,max:100},{key:'date',label:'日期',type:'date',width:160},{key:'amount',label:'费用',type:'number'}]}
]
const round=n=>Math.round((n+Number.EPSILON)*100)/100
@ -68,16 +70,18 @@ const summaryRows=computed(()=>{const f=form.value,derived={
const extras=f.expenses.filter(row=>!costCategories.includes(row.name)).map((expense,i)=>({key:expense.name||'extra',label:expense.name||'补充费用',seq:14+i,expense,extra:true}));const total=round([...items,...extras].reduce((n,row)=>n+Number(row.expense?.amount??row.amount??0),0))
const rows=[{key:'income',label:'项目收入',seq:'一',kind:'summary'},{key:'totalCost',label:'项目成本费用',seq:'二',kind:'summary',amount:total},...items,...extras]
rows.push({key:'profit',label:'毛利润',seq:'三',kind:'summary',calculation:'项目收入 − 项目成本费用',amount:f.income!=null?round(Number(f.income)-total):null},{key:'margin',label:'利润率',seq:'四',kind:'summary',calculation:'毛利润 ÷ 项目收入',amount:f.income!=null&&Number(f.income)>0?(Number(f.income)-total)/Number(f.income):null,percent:true});return rows})
function add(key){if(form.value[key].length>=200){ElMessage.warning('每类最多200行');return}const row=Object.fromEntries(sections.find(s=>s.key===key).fields.filter(f=>f.type!=='calculated').map(f=>[f.key,['number','date'].includes(f.type)?null:'']));if(key!=='materials')row.userId=null;if(key==='labor')row.rate=null;form.value[key].push(row)}
function add(key){if(form.value[key].length>=200){ElMessage.warning('每类最多200行');return}const row=Object.fromEntries(sections.find(s=>s.key===key).fields.filter(f=>f.type!=='calculated').map(f=>[f.key,['number','date'].includes(f.type)?null:'']));if(key!=='materials')row.userId=null;if(key==='travel')row.userIds=[];if(key==='labor')row.rate=null;form.value[key].push(row)}
function selectPerson(row,id,key){const person=people.value.find(p=>p.id===id);row.name=person?.name||'';if(key==='labor')row.rate=person?Number(person.rate??1000):null}
async function loadPeople(keyword='',resolveSelected=false){if(!props.editable||!props.projectId)return;personKeyword.value=keyword;peopleController?.abort();const generation=++peopleGeneration;peopleController=new AbortController();peopleLoading.value=true;const ids=resolveSelected?[...new Set(['labor','travel','entertainment'].flatMap(key=>form.value[key].map(row=>row.userId).filter(id=>id!=null)))]:[];try{const r=await archiveCostPeople(props.projectId,{keyword,ids:ids.length?ids.join(','):undefined},peopleController.signal);if(disposed||generation!==peopleGeneration)return;const cache=new Map(people.value.map(person=>[person.id,person]));for(const person of r.data)cache.set(person.id,person);people.value=[...cache.values()];peopleError.value=false;if(resolveSelected)for(const row of form.value.labor){const person=people.value.find(p=>p.id===row.userId);if(person)row.rate=Number(person.rate??1000)}}catch(e){if(!disposed&&generation===peopleGeneration&&e?.code!=='ERR_CANCELED')peopleError.value=true}finally{if(generation===peopleGeneration)peopleLoading.value=false}}
function travelOptions(row){const values=new Map(matchingPeople.value.map(person=>[person.id,person]));for(const id of travelUserIds(row))if(!values.has(id))values.set(id,people.value.find(person=>person.id===id)||{id,name:props.cost?.userNames?.[id]||(travelUserIds(row).length===1?row.name:'历史人员 #'+id),account:''});return sortPeople([...values.values()])}
function selectTravelPeople(row,ids){row.userId=null;row.userIds=[...new Set(ids)];row.name=row.userIds.map(id=>travelOptions(row).find(person=>person.id===id)?.name||'').filter(Boolean).join('、')}
async function loadPeople(keyword='',resolveSelected=false){if(!props.editable||!props.projectId)return;personKeyword.value=keyword;peopleController?.abort();const generation=++peopleGeneration;peopleController=new AbortController();peopleLoading.value=true;const ids=resolveSelected?[...new Set(['labor','travel','entertainment'].flatMap(key=>form.value[key].flatMap(row=>key==='travel'?travelUserIds(row):row.userId!=null?[row.userId]:[])))]:[];try{const r=await archiveCostPeople(props.projectId,{keyword,ids:ids.length?ids.join(','):undefined},peopleController.signal);if(disposed||generation!==peopleGeneration)return;const cache=new Map(people.value.map(person=>[person.id,person]));for(const person of r.data)cache.set(person.id,person);people.value=sortPeople([...cache.values()]);peopleError.value=false;if(resolveSelected)for(const row of form.value.labor){const person=people.value.find(p=>p.id===row.userId);if(person)row.rate=Number(person.rate??1000)}}catch(e){if(!disposed&&generation===peopleGeneration&&e?.code!=='ERR_CANCELED')peopleError.value=true}finally{if(generation===peopleGeneration)peopleLoading.value=false}}
async function jumpToIssue(issue){issuesOpen.value=false;await nextTick();const element=costRoot.value?.querySelector('[data-cost-field="'+issue.key+'"]');element?.scrollIntoView({behavior:'smooth',block:'center'});element?.querySelector('input,textarea')?.focus({preventScroll:true})}
async function prepareConfirmation(){if(!props.editable||saving.value)return false;if(issues.value.length){issuesOpen.value=true;return false}if(peopleLoading.value||peopleError.value){ElMessage.warning(peopleLoading.value?'人员信息正在加载,请稍候确认':'请先重新加载系统人员');return false}return dirty.value||!props.cost?.complete?await save({force:true}):true}
function addExtra(){if(form.value.expenses.length>=200){ElMessage.warning('费用项目最多200行');return}form.value.expenses.push({name:'',amount:null,note:''})}
function removeExtra(row){form.value.expenses.splice(form.value.expenses.indexOf(row),1)}
function money(value,percent){return value==null?'—':percent?(Number(value)*100).toFixed(2)+'%':Number(value).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})}
async function save(options={}){if(saving.value||!props.editable||!dirty.value&&!options.force||peopleLoading.value)return false
if(peopleError.value){ElMessage.warning('请先重新加载系统人员');return}if(['labor','travel','entertainment'].some(key=>form.value[key].some(row=>row.name&&!row.userId))){ElMessage.warning('请从下拉框选择系统人员,历史手填姓名需重新选择');return}
if(peopleError.value){ElMessage.warning('请先重新加载系统人员');return}if(['labor','travel','entertainment'].some(key=>form.value[key].some(row=>row.name&&!(key==='travel'?travelUserIds(row).length:row.userId)))){ElMessage.warning('请从下拉框选择系统人员,历史手填姓名需重新选择');return}
const names=form.value.expenses.map(r=>r.name?.trim());if(names.some(n=>!n)||new Set(names).size!==names.length||names.some(n=>['预估人工成本','材料及耗材','差旅费','业务招待费'].includes(n))){ElMessage.warning('补充费用请填写不重复的项目名称,明细汇总项目不能重复添加');return}
saving.value=true;emit('busy',true)
try{await archiveCost(props.projectId,{version:props.version,data:form.value});baseline.value=JSON.stringify(form.value);ElMessage.success('成本分析已保存');emit('changed');return true}catch{return false}finally{saving.value=false;emit('busy',false)}}

View File

@ -28,7 +28,7 @@ const props=defineProps({review:{type:Object,default:()=>({})},items:{type:Array
const changesOnly=ref(true),keyword=ref(''),filePage=ref(1),costPage=ref(1)
const kinds={ADDED:'新增文件',REPLACED:'替换了文件',REMOVED:'删除文件',NEW_VERSION:'上传了新版本'}
const fields={applicable:'是否需要提交',exception_reason:'不适用原因',state:'完成情况',expected_count:'要求份数',note:'资料备注'}
const documents=computed(()=>props.review.documents||[]),costs=computed(()=>(props.review.costChanges||[]).filter(row=>!row.path?.endsWith('.userId')||!(props.review.costChanges||[]).some(other=>other.path===row.path.replace(/userId$/,'name'))).map(row=>({...row,label:String(row.label||'成本内容').replace(/\buserId\b/g,'关联人员')}))),itemChanges=computed(()=>props.review.itemChanges||[])
const documents=computed(()=>props.review.documents||[]),costs=computed(()=>(props.review.costChanges||[]).filter(row=>!(row.path?.endsWith('.userId')||row.path?.includes('.userIds'))||!(props.review.costChanges||[]).some(other=>other.path===row.path.replace(/userId$/,'name'))).map(row=>({...row,label:String(row.label||'成本内容').replace(/\buserId\b/g,'关联人员')}))),itemChanges=computed(()=>props.review.itemChanges||[])
const currentLabel=computed(()=>props.state==='EDITING'?'当前维护中的资料(尚未再次提交)':props.state==='ARCHIVED'?'当前归档资料':'这次提交的资料')
const changedItemCount=computed(()=>new Set([...documents.value.map(row=>row.itemKey),...itemChanges.value.map(row=>row.itemKey),...(costs.value.length?['costAnalysis']:[])]).size),costSaved=computed(()=>props.history.find(row=>row.event_type==='COST_SAVED'))
const matches=values=>values.some(value=>String(value??'').toLocaleLowerCase().includes(keyword.value.trim().toLocaleLowerCase()))
@ -38,8 +38,8 @@ const filteredCosts=computed(()=>costs.value.filter(row=>matches([row.label,row.
const fileRows=computed(()=>filteredDocuments.value.slice((filePage.value-1)*50,filePage.value*50)),costRows=computed(()=>filteredCosts.value.slice((costPage.value-1)*50,costPage.value*50))
const value=v=>v==null||v===''?'—':String(v),time=v=>formatDateTime(v).slice(0,16)
const itemValue=(field,v)=>field==='state'?(itemNames[v]||value(v)):field==='applicable'?(Number(v)?'适用':'不适用'):value(v)
function costValue(row,side){const v=row[side];if(v==null||v==='')return '未填写';if(row.path?.endsWith('.userId'))return side==='before'?'原关联人员':'已更换人员,请查看明细';if(typeof v==='number'){const n=v.toLocaleString('zh-CN',{maximumFractionDigits:4});if(row.path?.endsWith('.days'))return n+' 天';if(/(?:income|rate|gross|tax|amount)$/.test(row.path||'')||/(收入|金额|费用标准|采购成本|差旅费用|费用)$/.test(row.label||''))return v.toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})+(row.path?.endsWith('.rate')?' 元/人日':' 元');return n}return String(v)}
function costChange(row){if(row.path?.endsWith('.userId'))return '已更换关联人员';if(row.before==null||row.before==='')return '新增填写';if(row.after==null||row.after==='')return '已清空';if(typeof row.before==='number'&&typeof row.after==='number')return (row.after>row.before?'增加 ':'减少 ')+costValue({...row,after:Math.abs(row.after-row.before)},'after');return '已修改'}
function costValue(row,side){const v=row[side];if(v==null||v==='')return '未填写';if((row.path?.endsWith('.userId')||row.path?.includes('.userIds')))return side==='before'?'原关联人员':'已更换人员,请查看明细';if(typeof v==='number'){const n=v.toLocaleString('zh-CN',{maximumFractionDigits:4});if(row.path?.endsWith('.days'))return n+' 天';if(/(?:income|rate|gross|tax|amount)$/.test(row.path||'')||/(收入|金额|费用标准|采购成本|差旅费用|费用)$/.test(row.label||''))return v.toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})+(row.path?.endsWith('.rate')?' 元/人日':' 元');return n}return String(v)}
function costChange(row){if((row.path?.endsWith('.userId')||row.path?.includes('.userIds')))return '已更换关联人员';if(row.before==null||row.before==='')return '新增填写';if(row.after==null||row.after==='')return '已清空';if(typeof row.before==='number'&&typeof row.after==='number')return (row.after>row.before?'增加 ':'减少 ')+costValue({...row,after:Math.abs(row.after-row.before)},'after');return '已修改'}
function fileEditor(row){const doc=props.items.flatMap(item=>item.documents||[]).find(doc=>String(doc.id)===String(row.documentId));const file=doc?.files?.find(file=>String(file.id)===String(doc.current_file_id));return file?.create_by?'最近上传:'+file.create_by+' · '+time(file.create_time):''}
watch(keyword,()=>{filePage.value=1;costPage.value=1})
watch(()=>props.review,()=>{filePage.value=1;costPage.value=1;keyword.value=''})

View File

@ -1,10 +1,11 @@
import {travelUserIds} from './archive-model.js'
const present=value=>value!=null&&value!==''
const numeric=value=>present(value)&&Number.isFinite(Number(value))&&Number(value)>=0
export function costIssues(form){
const issues=[],add=(key,label)=>issues.push({key,label})
if(!numeric(form.income))add('income','项目收入:请填写有效金额(可以为 0)')
const definitions={labor:['预估人工成本',[['userId','系统人员','person'],['duty','职责分工','text'],['days','投入工时','number'],['rate','人员费用标准','number']]],materials:['材料费用统计',[['supplier','供应商名称','text'],['content','采购项目','text'],['gross','采购成本','number']]],travel:['差旅费',[['purpose','出差事项','text'],['userId','系统人员','person'],['date','出差日期','date'],['amount','差旅费用','number']]],entertainment:['招待费',[['userId','系统人员','person'],['date','日期','date'],['amount','费用','number']]]}
for(const [section,[title,fields]] of Object.entries(definitions))for(const [index,row] of (form[section]||[]).entries())for(const [field,label,type] of fields){const value=row[field];if(!(type==='number'?numeric(value):type==='person'?Number(value)>0:type==='date'?/^\d{4}-\d{2}-\d{2}$/.test(value||''):typeof value==='string'&&!!value.trim()))add(`${section}:${index}:${field==='rate'?'name':field==='userId'?'name':field}`,`${title}第 ${index+1} 行:请${type==='person'||type==='date'?'选择':'填写'}${label}`)}
const definitions={labor:['预估人工成本',[['userId','系统人员','person'],['duty','职责分工','text'],['days','投入工时','number'],['rate','人员费用标准','number']]],materials:['材料费用统计',[['supplier','供应商名称','text'],['content','采购项目','text'],['gross','采购成本','number']]],travel:['差旅费',[['purpose','出差事项','text'],['userIds','出差人','people'],['date','出差日期','date'],['amount','差旅费用','number']]],entertainment:['招待费',[['userId','系统人员','person'],['date','日期','date'],['amount','费用','number']]]}
for(const [section,[title,fields]] of Object.entries(definitions))for(const [index,row] of (form[section]||[]).entries())for(const [field,label,type] of fields){const value=row[field];if(!(type==='number'?numeric(value):type==='person'?Number(value)>0:type==='people'?travelUserIds(row).length>0&&travelUserIds(row).every(id=>Number(id)>0):type==='date'?/^\d{4}-\d{2}-\d{2}$/.test(value||''):typeof value==='string'&&!!value.trim()))add(`${section}:${index}:${field==='rate'?'name':field==='userId'||field==='userIds'?'name':field}`,`${title}第 ${index+1} 行:请${type==='person'||type==='people'||type==='date'?'选择':'填写'}${label}`)}
const standard=new Set(['佣金代理费','外协费','技术服务费','外包费','运输装卸费','汽车费','印刷费','培训费','保险费']),seen=new Set()
for(const [index,row] of (form.expenses||[]).entries()){
if(!row.name?.trim()||seen.has(row.name.trim())||['预估人工成本','材料及耗材','差旅费','业务招待费'].includes(row.name.trim()))add(`expenses:${index}:name`,`补充费用第 ${index+1} 项:请填写不重复的费用名称`)

View File

@ -9,12 +9,13 @@ export const costNames=['佣金代理费','外协费','技术服务费','外包
export const costCategories=['预估人工成本','佣金代理费','材料及耗材','外协费','技术服务费','外包费','运输装卸费','差旅费','业务招待费','汽车费','印刷费','培训费','保险费']
export const costSignerFields=[['preparer','编制人'],['finance','财务部门审核人'],['projectOwner','项目负责人'],['outsourcing','外包外协/佣金代理'],['demand','需求部门负责人'],['management','管理部门审核人']]
export function emptyCost(){return {formatVersion:3,income:null,labor:[],materials:[],travel:[],entertainment:[],expenses:costNames.map(name=>({name,amount:null,note:''})),signers:{},remarks:{income:'应剔除增值税。','佣金代理费':'包含佣金代理手续费',extra:'根据具体项目成本费用发生情况,补充列示。'}}}
export const travelUserIds=row=>Array.isArray(row.userIds)?[...new Set(row.userIds)]:row.userId!=null?[row.userId]:[]
// Read compatibility only: resolve historical account IDs from the saved snapshot, never mutate stored data.
export function normalizeCost(cost={}){cost||={};const data=cost.data||{},form=emptyCost(),names=cost.userNames||{};const person=row=>row.name??names[row.userId]??''
form.income=data.formatVersion>=2?(data.income??null):(data.incomeGross!=null&&data.incomeTax!=null?Number(data.incomeGross)-Number(data.incomeTax):null)
form.labor=(data.labor||[]).map(row=>({userId:row.userId??null,name:person(row),duty:row.duty||'',days:row.days,rate:row.rate}))
form.materials=(data.materials||[]).map(row=>({supplier:row.supplier||'',content:row.content||'',gross:row.gross}))
form.travel=(data.travel||[]).map(row=>({userId:row.userId??null,name:person(row),purpose:row.purpose||'',date:row.date,amount:row.amount}))
form.travel=(data.travel||[]).map(row=>({userId:null,userIds:travelUserIds(row),name:row.name??travelUserIds(row).map(id=>names[id]).filter(Boolean).join('、'),purpose:row.purpose||'',date:row.date,amount:row.amount}))
form.entertainment=(data.entertainment||[]).map(row=>({userId:row.userId??null,name:person(row),date:row.date,amount:row.amount}))
const combined=new Map();for(const row of data.expenses||[]){const existing=combined.get(row.name);if(!existing)combined.set(row.name,{...row});else{if(row.amount!=null)existing.amount=Number(existing.amount||0)+Number(row.amount);existing.note=[existing.note,row.note].filter(Boolean).join(';')}}const expenses=[...combined.values()];form.expenses=form.expenses.map(row=>expenses.find(e=>e.name===row.name)||row).concat(expenses.filter(row=>!costNames.includes(row.name)))
form.remarks={...form.remarks,...data.remarks};for(const row of expenses)if(row.note&&!Object.hasOwn(data.remarks||{},row.name))form.remarks[row.name]=row.note

View File

@ -45,6 +45,7 @@
</main>
</template>
<script setup>
import {sortPeople} from '@/utils/person-order'
import {ref,reactive,computed,nextTick,onMounted,onBeforeUnmount,watch} from 'vue'
import * as echarts from 'echarts/core'
import {BarChart,LineChart} from 'echarts/charts'
@ -70,7 +71,7 @@ function selectYear(){if(year.value)range.value=[year.value+'-01-01',year.value+
function search(){query.page=1;load()}
function reset(){year.value=thisYear();selectYear();Object.assign(query,defaults());options.manager=[];search()}
async function load(){if(!range.value?.[0]||!range.value?.[1]){error.value='请选择完整的时间范围';return}const key=filterKey(),g=++generation;controller?.abort();controller=new AbortController();loading.value=true;error.value='';try{const r=await archiveAnalysis({...query,from:range.value[0],to:range.value[1]},controller.signal);if(disposed||g!==generation)return;report.value=r.data;appliedFilters.value=key;await nextTick();drawChart()}catch(e){if(!disposed&&g===generation&&e?.code!=='ERR_CANCELED'){error.value=e?.message||'汇总加载失败,请重试';report.value=null;chart?.dispose();chart=null}}finally{if(g===generation)loading.value=false}}
function findPeople(keyword,kind='manager'){clearTimeout(personTimers[kind]);personControls[kind]?.abort();const g=personGenerations[kind]=(personGenerations[kind]||0)+1;personTimers[kind]=setTimeout(async()=>{personControls[kind]=new AbortController();peopleBusy[kind]=true;try{const r=await archiveAnalysisPeople(keyword,personControls[kind].signal);if(disposed||g!==personGenerations[kind])return;const selected=options[kind].find(p=>p.id===query.managerId);options[kind]=[...(selected?[selected]:[]),...r.data.filter(p=>p.id!==1&&p.account?.toLowerCase()!=='admin'&&p.id!==selected?.id)]}catch{}finally{if(g===personGenerations[kind])peopleBusy[kind]=false}},250)}
function findPeople(keyword,kind='manager'){clearTimeout(personTimers[kind]);personControls[kind]?.abort();const g=personGenerations[kind]=(personGenerations[kind]||0)+1;personTimers[kind]=setTimeout(async()=>{personControls[kind]=new AbortController();peopleBusy[kind]=true;try{const r=await archiveAnalysisPeople(keyword,personControls[kind].signal);if(disposed||g!==personGenerations[kind])return;const selected=options[kind].find(p=>p.id===query.managerId);options[kind]=sortPeople([...(selected?[selected]:[]),...r.data.filter(p=>p.id!==1&&p.account?.toLowerCase()!=='admin'&&p.id!==selected?.id)])}catch{}finally{if(g===personGenerations[kind])peopleBusy[kind]=false}},250)}
function drawChart(){if(!trendEl.value||!report.value?.included){chart?.dispose();chart=null;return}if(chart&&chart.getDom()!==trendEl.value){chart.dispose();chart=null}chart??=echarts.init(trendEl.value);chart.setOption({animation:false,color:['#3566d6','#9cafce','#2e9f89'],tooltip:{trigger:'axis',valueFormatter:money},legend:{bottom:0,data:['收入','成本','毛利润']},grid:{left:70,right:20,top:24,bottom:62},xAxis:{type:'category',data:report.value.trend.map(r=>r.period),axisLine:{lineStyle:{color:'#dce3ef'}},axisLabel:{color:'#7b8799'}},yAxis:{type:'value',axisLabel:{color:'#7b8799',formatter:v=>Math.abs(v)>=10000?(v/10000)+'万':v},splitLine:{lineStyle:{color:'#eef2f7'}}},series:[{name:'收入',type:'bar',barMaxWidth:24,data:report.value.trend.map(r=>r.income)},{name:'成本',type:'bar',barMaxWidth:24,data:report.value.trend.map(r=>r.cost)},{name:'毛利润',type:'line',smooth:false,data:report.value.trend.map(r=>r.profit)}]},true);observer?.disconnect();observer=new ResizeObserver(()=>chart?.resize());observer.observe(trendEl.value)}
async function openCost(row){const g=++detailGeneration;detailController?.abort();detailController=new AbortController();detail.value=null;detailError.value='';detailBusy.value=true;detailOpen.value=true;try{const r=await archiveDetail(row.id,detailController.signal);if(!disposed&&g===detailGeneration)detail.value=r.data}catch(e){if(g===detailGeneration&&e?.code!=='ERR_CANCELED')detailError.value=e.message||'成本明细加载失败'}finally{if(g===detailGeneration)detailBusy.value=false}}
async function exportCost(){if(exporting.value||!detail.value)return;exporting.value=true;try{saveAs(await archiveCostExport(detail.value.id),detail.value.name+'-项目成本分析表.xlsx')}catch{}finally{exporting.value=false}}

View File

@ -166,6 +166,7 @@
</div>
</template>
<script setup>
import {sortPeople} from '@/utils/person-order'
import { formatDateTime } from '@/utils/display-format'
import {ref,computed,watch,onBeforeUnmount,nextTick} from 'vue'
import {ElMessage,ElMessageBox} from 'element-plus'
@ -263,8 +264,8 @@ async function beforeTab(){if(materialBusy.value){ElMessage.warning('请先完
async function confirmCost(){if(costConfirming.value||materialBusy.value||busy.value||detailLoading.value||!detail.value?.canEdit||!costEditor.value)return;const id=detail.value.id;costConfirming.value=true;try{if(!await costEditor.value.prepareConfirmation())return;await reloadDetail();await nextTick();if(!drawer.value||detail.value?.id!==id||!detail.value.canEdit)return;if(costDirty.value){ElMessage.warning('人员费用标准发生变化,请核对后重新确认');return}if(!detail.value.cost?.complete){ElMessage.warning('成本分析仍有未填内容,请检查缺项提示');return}await setItemState(costItem.value,'DONE')}finally{costConfirming.value=false}}
async function beforeClose(done){if(materialBusy.value||busy.value){ElMessage.warning('请先完成或暂停当前操作');return}if(costDirty.value){try{await ElMessageBox.confirm('成本分析还有未保存内容,确定放弃并关闭?','离开确认')}catch{return}}detailGeneration++;detailController?.abort();done()}
function closeDrawer(){beforeClose(()=>{drawer.value=false})}
async function searchPeople(keyword=''){const g=++peopleGeneration;peopleController?.abort();peopleController=new AbortController();try{const r=await api.archiveManagers(keyword,peopleController.signal);if(!disposed&&g===peopleGeneration){const selectedIds=[projectDialog.value?projectForm.value.managerId:null,assignDialog.value?assignment.value.managerId:null];people.value=[...r.data,...people.value.filter(p=>selectedIds.includes(p.id)&&!r.data.some(v=>v.id===p.id))]}}catch{}}
async function searchManagers(keyword=''){if(!metadata.value?.all)return;const g=++managerGeneration;managerController?.abort();managerController=new AbortController();managersLoading.value=true;try{const r=await api.archiveManagers(keyword,managerController.signal);if(!disposed&&g===managerGeneration)managerOptions.value=[...r.data,...managerOptions.value.filter(p=>p.id===query.value.managerId&&!r.data.some(v=>v.id===p.id))]}catch{}finally{if(g===managerGeneration)managersLoading.value=false}}
async function searchPeople(keyword=''){const g=++peopleGeneration;peopleController?.abort();peopleController=new AbortController();try{const r=await api.archiveManagers(keyword,peopleController.signal);if(!disposed&&g===peopleGeneration){const selectedIds=[projectDialog.value?projectForm.value.managerId:null,assignDialog.value?assignment.value.managerId:null];people.value=sortPeople([...r.data,...people.value.filter(p=>selectedIds.includes(p.id)&&!r.data.some(v=>v.id===p.id))])}}catch{}}
async function searchManagers(keyword=''){if(!metadata.value?.all)return;const g=++managerGeneration;managerController?.abort();managerController=new AbortController();managersLoading.value=true;try{const r=await api.archiveManagers(keyword,managerController.signal);if(!disposed&&g===managerGeneration)managerOptions.value=sortPeople([...r.data,...managerOptions.value.filter(p=>p.id===query.value.managerId&&!r.data.some(v=>v.id===p.id))])}catch{}finally{if(g===managerGeneration)managersLoading.value=false}}
function editProject(p){projectForm.value=p?{id:p.id,...projectPayload(p)}:{code:'',name:'',customerType:'',businessCategory:'',scopeType:'EXTERNAL',phase:'INITIATION',startTime:currentArchiveTime(),expectedEndTime:null,managerId:metadata.value.canBeManager?metadata.value.actorId:null};people.value=p?[{id:p.manager_id,name:p.manager_name||'当前项目经理',account:'',legacy:true}]:metadata.value.canBeManager?[{id:metadata.value.actorId,name:metadata.value.actorName||'本人',account:''}]:[];projectDialog.value=true;if(metadata.value.canAssign)searchPeople()}
async function saveProject(){if(busy.value)return;if(!projectForm.value.name?.trim()||!projectForm.value.code?.trim()||!projectForm.value.managerId){ElMessage.warning('请填写项目名称、编号和项目经理');return}busy.value=true
try{const r=await api.archiveSave(projectForm.value.id,projectForm.value);projectDialog.value=false;ElMessage.success('资料项目已保存');await load();if(drawer.value)await reloadDetail();else{busy.value=false;await open(r.data.id)}}catch{}finally{busy.value=false}}

View File

@ -90,6 +90,7 @@
</template>
</el-table-column>
<el-table-column label="创建者" align="center" prop="createBy" width="100" show-overflow-tooltip/>
<el-table-column label="附件" align="center" width="85" class-name="business-control-cell"><template #default="{row}"><el-button v-if="row.attachmentCount" link type="primary" @click="handleViewData(row)">{{ row.attachmentCount }} 个</el-button><span v-else>—</span></template></el-table-column>
<el-table-column label="创建时间" align="center" prop="createTime" width="100" show-overflow-tooltip>
<template #default="scope">
<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
@ -110,7 +111,7 @@
v-model:limit="queryParams.pageSize"
@pagination="getList"
/></template>
<template #dialogs><!-- 添加或修改公告对话框 --><el-dialog :title="title" v-model="open" width="780px" append-to-body>
<template #dialogs><!-- 添加或修改公告对话框 --><el-dialog :title="title" v-model="open" width="min(860px,95vw)" append-to-body destroy-on-close :close-on-click-modal="false" :close-on-press-escape="!submitting" :before-close="beforeCloseNotice">
<el-form class="business-responsive-form" ref="noticeRef" :model="form" :rules="rules" label-width="auto">
<el-row>
<el-col :span="12">
@ -146,12 +147,13 @@
<editor v-model="form.noticeContent" :min-height="192"/>
</el-form-item>
</el-col>
<el-col :span="24"><el-form-item label="附件"><div class="notice-attachment-editor"><managed-upload ref="uploadRef" v-model="form.attachments" purpose="noticeAttachment" :show-completed="false" button-text="上传附件" :disabled="submitting" @pending="attachmentPending=$event"/><managed-attachments v-model="form.attachments" editable :disabled="submitting"/><small>选传,最多20个附件,保存公告后生效。</small></div></el-form-item></el-col>
</el-row>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" :loading="submitting" :disabled="attachmentPending" @click="submitForm">{{ attachmentPending?'请先完成附件上传':'保 存' }}</el-button>
<el-button :disabled="submitting" @click="cancel">取 消</el-button>
</div>
</template>
</el-dialog><notice-detail-view ref="noticeViewRef" /><read-users-dialog ref="readUsersRef" /></template>
@ -162,6 +164,8 @@
import NoticeDetailView from "@/layout/components/HeaderNotice/DetailView"
import ReadUsersDialog from "./ReadUsers"
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/system/notice"
import ManagedUpload from '@/components/ManagedFiles/Upload.vue'
import ManagedAttachments from '@/components/ManagedFiles/Attachments.vue'
const { proxy } = getCurrentInstance()
const { sys_notice_status, sys_notice_type } = useDict("sys_notice_status", "sys_notice_type")
@ -175,6 +179,7 @@ const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const uploadRef=ref(),attachmentPending=ref(false),submitting=ref(false)
const data = reactive({
form: {},
@ -205,9 +210,9 @@ function getList() {
/** 取消按钮 */
function cancel() {
open.value = false
reset()
beforeCloseNotice(()=>{open.value=false;reset()})
}
async function beforeCloseNotice(done){if(submitting.value)return;if(uploadRef.value?.running)try{await proxy.$modal.confirm('附件正在上传,关闭后可重新选择同一文件继续。确定关闭吗?')}catch{return}done()}
/** 表单重置 */
function reset() {
@ -216,8 +221,10 @@ function reset() {
noticeTitle: undefined,
noticeType: undefined,
noticeContent: undefined,
attachments: [],
status: "0"
}
attachmentPending.value=false
proxy.resetForm("noticeRef")
}
@ -253,30 +260,17 @@ function handleUpdate(row) {
const noticeId = row.noticeId || ids.value
getNotice(noticeId).then(response => {
form.value = response.data
form.value.attachments=response.data.attachments||[]
open.value = true
title.value = "修改公告"
})
}
/** 提交按钮 */
function submitForm() {
proxy.$refs["noticeRef"].validate(valid => {
if (valid) {
if (form.value.noticeId != undefined) {
updateNotice(form.value).then(response => {
proxy.$modal.msgSuccess("修改成功")
open.value = false
getList()
})
} else {
addNotice(form.value).then(response => {
proxy.$modal.msgSuccess("新增成功")
open.value = false
getList()
})
}
}
})
async function submitForm() {
if(submitting.value||attachmentPending.value)return
submitting.value=true
try{await proxy.$refs.noticeRef.validate();const payload={...form.value,attachmentIds:(form.value.attachments||[]).map(f=>f.id)};await(form.value.noticeId!=undefined?updateNotice(payload):addNotice(payload));proxy.$modal.msgSuccess('公告已保存');open.value=false;getList()}catch{}finally{submitting.value=false}
}
/** 查看公告详情 */
@ -302,3 +296,4 @@ function handleDelete(row) {
getList()
</script>
<style scoped>.notice-attachment-editor{width:100%;min-width:0}.notice-attachment-editor>small{display:block;margin-top:8px;font-size:12px;line-height:1.6;color:var(--el-text-color-secondary)}</style>

View File

@ -1,7 +1,7 @@
import {beforeEach,expect,test,vi} from 'vitest'
import {shallowMount,flushPromises} from '@vue/test-utils'
import {shallowMount,flushPromises,mount as realMount} from '@vue/test-utils'
import {defineComponent,provide,inject,computed,h,onBeforeUnmount} from 'vue'
import {ElMessageBox} from 'element-plus'
import ElementPlus,{ElMessageBox} from 'element-plus'
import Archive from '@/views/archive/index.vue'
import Cost from '@/views/archive/ArchiveCost.vue'
import Files from '@/views/archive/ArchiveFiles.vue'
@ -236,6 +236,14 @@ test('cost confirmation reports the exact missing date, still calculates profit,
expect(await state.prepareConfirmation()).toBe(false);expect(state.issuesOpen).toBe(true);expect(state.issues.map(issue=>issue.label)).toEqual(['差旅费第 1 行:请选择出差日期']);expect(api.archiveCost).not.toHaveBeenCalled();expect(w.find('.cost-top').exists()).toBe(false);expect(w.find('.summary-add').text()).toBe('补充费用项目')
state.form.travel[0].date='2026-10-26';expect(await state.prepareConfirmation()).toBe(true);expect(api.archiveCost).toHaveBeenCalledWith(21,expect.objectContaining({version:3}));expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
})
test('travel uses a multi-person picker, resolves all selected ids, saves one expense and clears without restoring a legacy person',async()=>{
api.archiveCost.mockResolvedValue({code:200});api.archiveCostPeople.mockResolvedValue({data:[{id:2,name:'经理甲',account:'manager'},{id:5,name:'普通成员',account:'member'}]});
const w=realMount(Cost,{props:{projectId:21,version:3,editable:true,cost:{complete:true,userNames:{2:'经理甲'},data:{formatVersion:3,income:1000,travel:[{userId:2,name:'经理甲',purpose:'出差',date:'2026-10-28',amount:125.5}]}}},global:{plugins:[ElementPlus]}});await flushPromises();const state=w.vm.$.setupState,row=state.form.travel[0];expect(row.userIds).toEqual([2]);expect(row.userId).toBeNull();
const person=w.findAllComponents({name:'ElSelect'}).find(s=>s.props('ariaLabel')==='出差人');expect(person.props('multiple')).toBe(true);expect(person.props('clearable')).toBe(true);
person.vm.$emit('update:modelValue',[2,5]);person.vm.$emit('change',[2,5]);await flushPromises();expect(row.name).toBe('经理甲、普通成员');expect(state.summaryRows.find(r=>r.key==='totalCost').amount).toBe(125.5);expect(state.summaryRows.find(r=>r.key==='profit').amount).toBe(874.5);expect(await state.prepareConfirmation()).toBe(true);expect(api.archiveCost.mock.calls.at(-1)[1].data.travel[0].userIds).toEqual([2,5]);
await w.setProps({cost:{complete:true,userNames:{2:'经理甲',5:'普通成员'},data:{formatVersion:3,income:1000,travel:[{userIds:[2,5],name:'经理甲、普通成员',purpose:'出差',date:'2026-10-28',amount:125.5}]}}});await flushPromises();expect(api.archiveCostPeople).toHaveBeenLastCalledWith(21,expect.objectContaining({ids:'2,5'}),expect.anything());expect(state.form.travel[0].userIds).toEqual([2,5]);
state.selectTravelPeople(state.form.travel[0],[]);await flushPromises();expect(state.form.travel[0].name).toBe('');expect(state.issues.map(i=>i.label)).toEqual(['差旅费第 1 行:请选择出差人']);expect(await state.prepareConfirmation()).toBe(false);w.unmount();
})
test('cost confirmation is clickable for incomplete forms and uses the refreshed project version after preparation',async()=>{
const prepare=vi.fn().mockResolvedValue(false),costStub=defineComponent({setup(_,{expose}){expose({prepareConfirmation:prepare});return()=>h('div')}})
const button=defineComponent({props:['disabled','loading'],template:'<button :disabled="disabled"><slot/></button>'}),dialog=defineComponent({template:'<div><slot/><footer><slot name="footer"/></footer></div>'})

View File

@ -24,7 +24,7 @@ it('read-only saved photos load privately on demand and never expose upload or r
await wrapper.find('button').trigger('click');await flushPromises();expect(request).toHaveBeenCalledOnce();expect(request.mock.calls[0][0].url).toContain('/content');expect(document.body.textContent).not.toContain('上传照片');expect(document.body.textContent).not.toContain('移除')
})
it('non-images and oversized files do not upload; each arrival is limited to nine photos',async()=>{
request.mockImplementation(async c=>({data:{id:c.data.get('uploadId'),name:'到货.png'}}));page();await choose([new File(['not image'],'file.txt',{type:'text/plain'}),new File([new Uint8Array(5*1024*1024+1)],'large.png',{type:'image/png'})]);expect(request).not.toHaveBeenCalled()
request.mockImplementation(async c=>({data:{id:c.data.get('uploadId'),name:'到货.png'}}));page();await choose([new File(['not image'],'file.txt',{type:'text/plain'}),new File([new Uint8Array(20*1024*1024+1)],'large.png',{type:'image/png'})]);expect(request).not.toHaveBeenCalled()
await choose(Array.from({length:10},picture));expect(wrapper.props('modelValue')).toHaveLength(9);expect(request).toHaveBeenCalledTimes(9)
})
it('saved photo loading errors can retry without editing the arrival or its photo metadata',async()=>{

View File

@ -5,12 +5,14 @@ import ElementPlus from 'element-plus'
import Center from '@/layout/components/HeaderNotice/index.vue'
const api = vi.hoisted(() => ({ list: vi.fn(), unread: vi.fn(), detail: vi.fn(), read: vi.fn(), notices: vi.fn(), notice: vi.fn(), readNotices: vi.fn() }))
const files = vi.hoisted(() => ({ download: vi.fn() }))
const identity = reactive({ id: 1 })
const navigation = vi.hoisted(() => ({ push: vi.fn() }))
vi.mock('@/store/modules/user', () => ({ default: () => identity }))
vi.mock('vue-router', () => ({ useRouter: () => navigation }))
vi.mock('@/api/system/notification', () => ({ listNotifications: api.list, notificationUnread: api.unread, getNotification: api.detail, readNotificationBatch: api.read }))
vi.mock('@/api/system/notice', () => ({ listNoticeTop: api.notices, getNotice: api.notice, markNoticeReadAll: api.readNotices }))
vi.mock('@/api/system/files', () => ({ downloadFile: files.download, fileSize: bytes => bytes+' B' }))
let wrapper
const dom = () => new DOMWrapper(document.body)
const message = (id = 7) => ({ id, title: '模拟站内消息', content: '<img src=x onerror="alert(1)">\n纯文本正文', readAt: null, deliveredAt: '2026-10-20 11:00' })
@ -21,6 +23,7 @@ async function open() {
}
beforeEach(() => {
vi.clearAllMocks(); identity.id = 1
files.download.mockResolvedValue()
api.unread.mockResolvedValue({ data: { count: 1, exact: true } })
api.notices.mockResolvedValue({ data: [] })
api.list.mockResolvedValue({ data: { items: [message()], hasMore: false, nextCursor: null } })
@ -72,6 +75,24 @@ it('announcement and message read operations stay separate and the badge respect
await button('标为已读').trigger('click'); await flushPromises()
expect(api.readNotices).toHaveBeenCalledExactlyOnceWith('7'); expect(api.read).not.toHaveBeenCalled()
})
it('ordinary recipients can see and download saved announcement attachments without management permission', async () => {
const attachment={id:'notice-file',name:'库存管理.apk',size:26400542}
api.notices.mockResolvedValue({data:[{noticeId:8,noticeTitle:'下载公告',isRead:false}]})
api.notice.mockResolvedValue({data:{noticeTitle:'下载公告',noticeContent:'请下载附件',attachments:[attachment]}})
await open();await dom().findAll('input[type="radio"]').find(item=>item.element.value==='notices').setValue();await flushPromises();await dom().find('.message-item').trigger('click');await flushPromises()
expect(dom().find('[aria-label="公告附件"]').text()).toContain('库存管理.apk');expect(dom().text()).toContain('附件(1)');expect(button('移除')).toBeUndefined();expect(button('公告管理')).toBeUndefined()
await button('下载').trigger('click');await flushPromises();expect(files.download).toHaveBeenCalledWith(attachment,expect.anything());expect(api.read).not.toHaveBeenCalled();expect(api.readNotices).not.toHaveBeenCalled()
await button('← 返回列表').trigger('click');await flushPromises();expect(dom().find('[aria-label="公告附件"]').exists()).toBe(false)
})
it('empty announcements and inbox messages do not display stale announcement attachments', async () => {
api.notices.mockResolvedValue({data:[{noticeId:8,noticeTitle:'无附件公告',isRead:false}]});api.notice.mockResolvedValue({data:{noticeTitle:'无附件公告',noticeContent:'正文',attachments:[]}})
await open();await dom().findAll('input[type="radio"]').find(item=>item.element.value==='notices').setValue();await flushPromises();await dom().find('.message-item').trigger('click');await flushPromises();expect(dom().find('[aria-label="公告附件"]').exists()).toBe(false)
})
it('announcement detail retains numbered steps and bullets instead of flattening editor HTML',async()=>{
api.notices.mockResolvedValue({data:[{noticeId:9,noticeTitle:'操作步骤',isRead:false}]});api.notice.mockResolvedValue({data:{noticeTitle:'操作步骤',noticeContent:'<p><strong>使用说明</strong></p><ol><li>安装</li><li>登录</li><li>下载附件</li></ol><ul><li>补充说明</li></ul><script>hidden-script</script>'}})
await open();await dom().findAll('input[type="radio"]').find(item=>item.element.value==='notices').setValue();await flushPromises();await dom().find('.message-item').trigger('click');await flushPromises()
expect(dom().findAll('.message-richcontent ol>li')).toHaveLength(3);expect(dom().findAll('.message-richcontent ul>li')).toHaveLength(1);expect(dom().find('.message-richcontent strong').text()).toBe('使用说明');expect(dom().text()).not.toContain('hidden-script');expect(api.readNotices).not.toHaveBeenCalled()
})
it('KPI reminders expose a validated personal assessment link only after opening the message', async () => {
api.detail.mockResolvedValue({data:{...message(),businessType:'KPI_REMINDER',sourcePath:'/kpi/assessment/42'}})
await open();expect(button('查看KPI')).toBeUndefined()

View File

@ -36,7 +36,9 @@ const {checkForms}=require('./vue3-form-display-check.cjs')
await page.evaluate(async url=>{await document.querySelector('#app').__vue_app__.config.globalProperties.$router.push(url)},route.url);assert.equal(new URL(page.url()).pathname,route.url,'actual router must display the audited route');await settled()
const checks=[]
for(const viewport of [{width:1366,height:768},{width:1024,height:600}]){
await page.setViewportSize(viewport);await page.waitForTimeout(180)
await page.setViewportSize(viewport);await settled()
// ResizeObserver and table layout finish asynchronously, especially during parallel builds.
await page.waitForFunction(()=>[...document.querySelectorAll('.business-list-page__table > .el-table')].filter(e=>e.getClientRects().length).every(e=>Math.abs(e.getBoundingClientRect().height-e.parentElement.clientHeight)<=2))
checks.push(await page.evaluate(()=>{const stage=document.querySelector('.desktop-viewport'),visible=e=>e.getClientRects().length&&getComputedStyle(e).visibility!=='hidden',box=e=>{const r=e.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right}};return {viewport:[innerWidth,innerHeight],document:[document.documentElement.scrollWidth,document.documentElement.scrollHeight],root:stage?.firstElementChild?.className,rootScroll:stage?.firstElementChild?{height:stage.firstElementChild.clientHeight,scroll:stage.firstElementChild.scrollHeight}:null,tables:[...(stage?.querySelectorAll('div.el-table')||[])].filter(e=>visible(e)&&e.querySelector('.el-table__body-wrapper')).map(e=>{const b=box(e);let lastRowReachable=b.bottom<=innerHeight+1;if(!lastRowReachable){let parent=e.parentElement;while(parent&&!(parent.scrollHeight>parent.clientHeight+1&&/auto|scroll/.test(getComputedStyle(parent).overflowY)))parent=parent.parentElement;if(parent&&box(parent).bottom<=innerHeight+1){const before=parent.scrollTop;parent.scrollTop=parent.scrollHeight;const last=e.querySelector('.el-table__body tbody tr:last-child')||e;lastRowReachable=box(last).bottom<=Math.min(innerHeight,box(parent).bottom)+1;parent.scrollTop=before}}return {...b,lastRowReachable,columns:[...e.querySelectorAll('.el-table__header th')].map(c=>({text:c.innerText,width:c.getBoundingClientRect().width}))}}),headers:[...(stage?.querySelectorAll('.query-toolbar,.business-list-page__header')||[])].filter(visible).map(e=>({...box(e),overflow:e.scrollWidth-e.clientWidth})),loading:[...document.querySelectorAll('.el-loading-mask')].filter(e=>visible(e)&&Number(getComputedStyle(e).opacity)>.1).length}}))
await checkControlCells(page,route.title+' '+viewport.width)
await checkForms(page,route.title+' '+viewport.width,'.desktop-viewport')