Merge remote-tracking branch 'origin/project' into project

This commit is contained in:
zhanghao 2026-10-30 14:53:09 +08:00
commit 4af76792c8
45 changed files with 652 additions and 104 deletions

View File

@ -1,13 +1,13 @@
const { environment } = require('./config/environment.cjs');
module.exports = () => {
const env = environment();
const cleartextHosts = [...new Set([env.apiUrl, env.updateOrigin].filter(url => url.startsWith('http:')).map(url => new URL(url).hostname))];
const cleartextHosts = [...new Set([...([env.apiUrl, env.updateOrigin].filter(url => url.startsWith('http:')).map(url => new URL(url).hostname)), ...(env.variant === 'prod' ? ['192.168.28.10'] : [])])];
return {
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' ? 5 : 3,
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 7 : 5,
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 }],

View File

@ -1,12 +1,13 @@
const fs = require('node:fs');
const path = require('node:path');
const development = require('./development.json');
function internal(value, dev) {
function internal(value, dev, production = false) {
const url = new URL(value);
const p = url.hostname.split('.').map(Number);
const ipv4 = p.length === 4 && p.every(v => Number.isInteger(v) && v >= 0 && v <= 255);
const publicProduction = production && url.origin === 'https://wms.svc.cmvr-iot.icu';
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash
|| !(ipv4 && (p[0] === 10 || p[0] === 192 && p[1] === 168 || p[0] === 172 && p[1] >= 16 && p[1] <= 31)
|| !(publicProduction || ipv4 && (p[0] === 10 || p[0] === 192 && p[1] === 168 || p[0] === 172 && p[1] >= 16 && p[1] <= 31)
|| dev && ['localhost', '127.0.0.1'].includes(url.hostname))) throw Error('App 地址必须是内网 IPv4 地址;开发环境也可用 localhost。');
return url.toString().replace(/\/$/, '');
}
@ -14,10 +15,10 @@ function environment(env = process.env) {
const variant = env.APP_ENV || 'dev';
if (!['dev', 'prod'].includes(variant)) throw Error('APP_ENV 只能是 dev 或 prod');
const dev = variant === 'dev';
const apiUrl = internal(env.APP_API_URL || (dev ? development.apiUrl : ''), dev);
const apiUrl = internal(env.APP_API_URL || (dev ? development.apiUrl : 'https://wms.svc.cmvr-iot.icu/prod-api'), dev, !dev);
// Installed development apps reach the development PC, not the phone or production server.
// API selection remains independent and editable from the development app.
const updateOrigin = internal(env.APP_UPDATE_ORIGIN || (dev ? development.updateOrigin : ''), dev);
const updateOrigin = internal(env.APP_UPDATE_ORIGIN || (dev ? development.updateOrigin : 'https://wms.svc.cmvr-iot.icu'), dev, !dev);
if (new URL(updateOrigin).pathname !== '/') throw Error('APP_UPDATE_ORIGIN 只能包含协议、内网地址和端口。');
const certificate = path.resolve(__dirname, '../certs', `${variant}.pem`);
if (!dev && !fs.existsSync(certificate)) throw Error('正式构建必须先配置 certs/prod.pem 更新签名证书。');

View File

@ -7,7 +7,7 @@ const { environment } = require('../config/environment.cjs');
module.exports = (config, options) => {
const env = environment();
const hosts = [...new Set(options?.hosts || [])];
const expected = [...new Set([env.apiUrl, env.updateOrigin].filter(s => s.startsWith('http:')).map(s => new URL(s).hostname))];
const expected = [...new Set([...([env.apiUrl, env.updateOrigin].filter(s => s.startsWith('http:')).map(s => new URL(s).hostname)), ...(env.variant === 'prod' ? ['192.168.28.10'] : [])])];
if (JSON.stringify(hosts) !== JSON.stringify(expected)) throw Error('Native network hosts must match the environment config');
config = withAndroidManifest(config, cfg => {
const app = cfg.modResults.manifest.application[0];

View File

@ -1,4 +1,4 @@
param([string]$ApiUrl = 'http://192.168.28.10/prod-api', [string]$UpdateOrigin = 'http://192.168.28.10')
param([string]$ApiUrl = 'https://wms.svc.cmvr-iot.icu/prod-api', [string]$UpdateOrigin = 'https://wms.svc.cmvr-iot.icu')
$ErrorActionPreference = 'Stop'
$taskApp = Split-Path $PSScriptRoot -Parent
$taskRepo = Split-Path $taskApp -Parent

View File

@ -4,13 +4,14 @@ $taskApp = Split-Path $PSScriptRoot -Parent
$taskRepo = Split-Path $taskApp -Parent
$taskSigning = Join-Path $taskApp 'keys/production'
if (!$OutputDirectory) { $OutputDirectory = Join-Path $taskRepo '.codex-tmp/expo-prod-ota-staged' }
Add-Type -AssemblyName System.Security
$taskProtected = [IO.File]::ReadAllBytes((Join-Path $taskSigning 'credentials.machine.dpapi'))
$taskUnprotected = [System.Security.Cryptography.ProtectedData]::Unprotect($taskProtected, $null, [System.Security.Cryptography.DataProtectionScope]::LocalMachine)
try { $taskCredentials = [Text.Encoding]::UTF8.GetString($taskUnprotected) | ConvertFrom-Json }
finally { [Array]::Clear($taskUnprotected, 0, $taskUnprotected.Length) }
try {
$env:APP_ENV = 'prod'
$env:APP_UPDATE_ORIGIN = 'http://192.168.28.10'
$env:APP_UPDATE_ORIGIN = 'https://wms.svc.cmvr-iot.icu'
$env:OTA_PRIVATE_KEY = Join-Path $taskSigning 'ota-private-key.pem'
$env:OTA_KEY_PASSPHRASE = $taskCredentials.otaPassword
$env:OTA_CERTIFICATE = Join-Path $taskApp 'certs/prod.pem'

View File

@ -6,7 +6,7 @@ function assertInstallableConfig(config) {
if (!config.updates?.enabled || !config.updates.codeSigningCertificate) throw Error('Installable App requires signed updates');
const url = new URL(config.updates.url);
// Loopback is valid for local preview, never for an APK delivered to phones.
internal(url.origin, false);
internal(url.origin, false, variant === 'prod');
if (url.pathname !== `/updates/${variant}` || url.search || url.hash) throw Error('Update channel must match App environment');
if (config.updates.codeSigningMetadata?.keyid !== variant) throw Error('Update signing key must match App environment');
if (config.android?.package !== (variant === 'dev' ? 'cn.cmvr.wms.dev' : 'cn.cmvr.wms')) throw Error('App package/environment mismatch');

View File

@ -10,7 +10,7 @@ const types = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: '
export async function publishUpdate({ exportDir, root, origin, environment, runtimeVersion, keyFile, keyPassphrase, certificateFile, expoConfig }) {
if (!['dev', 'prod'].includes(environment) || !/^[\w.-]{1,200}$/.test(runtimeVersion || '')) throw Error('Explicit environment/runtime required');
origin = internal(origin, environment === 'dev');
origin = internal(origin, environment === 'dev', environment === 'prod');
if (new URL(origin).pathname !== '/') throw Error('OTA origin must not have a path');
exportDir = await realpath(exportDir); root = path.resolve(root);
const metadata = JSON.parse(await readFile(path.join(exportDir, 'metadata.json'), 'utf8'));

View File

@ -1,8 +1,8 @@
import assert from 'node:assert/strict';
import { readFile, writeFile } from 'node:fs/promises';
import { createHash, verify, X509Certificate } from 'node:crypto';
const origin = 'http://192.168.28.10';
const runtime = 'ac523f4137469f9f4b0faaca30982e68445686df';
const origin = 'https://wms.svc.cmvr-iot.icu';
const runtime = (await readFile(new URL('../android/app/build/generated/assets/createReleaseUpdatesResources/fingerprint', import.meta.url), 'utf8')).trim();
const headers = { 'expo-platform': 'android', 'expo-runtime-version': runtime,
'expo-protocol-version': '1', 'expo-expect-signature': 'sig, keyid="prod", alg="rsa-v1_5-sha256"',
accept: 'application/expo+json, application/json, multipart/mixed' };

View File

@ -13,7 +13,7 @@ import Constants from 'expo-constants';
import * as SecureStore from 'expo-secure-store';
import * as Crypto from 'expo-crypto';
import { StatusBar } from 'expo-status-bar';
import { ApiClient, allows, internalUrl } from './core/network';
import { ApiClient, allows, internalUrl, productionServer, PRODUCTION_PUBLIC_URL, PRODUCTION_INTERNAL_URL } from './core/network';
import { AppUpdateDialog, useAppUpdates, type AppUpdateControls } from './AppUpdates';
import { modules, display, recordDisplay, routeComponents, validDate, type Module, type Row, localDate } from './core/modules';
import { AppearanceContext, Button, Card, Choice, Field, Heading, Icon, Note, s, useTheme, type Appearance, type IconName } from './ui';
@ -33,7 +33,7 @@ import {developmentServerKey,developmentServer,serverTokenKey,connectionClient,c
const config=Constants.expoConfig?.extra || {};
const variant=String(config.environment || 'dev');
const nativeBase=internalUrl(String(config.apiUrl || 'http://127.0.0.1:8080'),variant==='dev');
const nativeBase=variant==='prod'?productionServer(String(config.apiUrl || PRODUCTION_PUBLIC_URL)):internalUrl(String(config.apiUrl || 'http://127.0.0.1:8080'),true);
const base=Platform.OS==='web'?`${globalThis.location.origin}/native-api`:nativeBase;
type User={user:Row; roles?:string[]; permissions:string[]; pages?:string[];pwdChrtype?:string};
const preferences={get:async(key:string)=>Platform.OS==='web'?localStorage.getItem(key):SecureStore.getItemAsync(key),
@ -44,9 +44,9 @@ export default function App(){
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);},[]);
const [server,setServer]=useState<string|null>(null);
useEffect(()=>{let alive=true;const key=variant==='dev'?developmentServerKey:'cmvr.prod.connection';void preferences.get(key).then(value=>{if(!alive)return;try{setServer(value?(variant==='dev'?developmentServer(value):productionServer(value)):nativeBase);}catch{setServer(nativeBase);}}).catch(()=>{if(alive)setServer(nativeBase);});return()=>{alive=false;};},[]);
const saveServer=useCallback(async(value:string)=>{await preferences.put(variant==='dev'?developmentServerKey:'cmvr.prod.connection',value);setServer(value);},[]);
useEffect(()=>{void (Platform.OS==='web'?Promise.resolve(localStorage.getItem('cmvr.appearance')):SecureStore.getItemAsync('cmvr.appearance')).then(value=>{if(['system','light','dark'].includes(value||''))setMode(value as Appearance);}).catch(()=>{});},[]);
const change=useCallback((value:Appearance)=>{setMode(value);if(Platform.OS==='web')try{localStorage.setItem('cmvr.appearance',value);}catch{}else void SecureStore.setItemAsync('cmvr.appearance',value).catch(()=>{});},[]);
return <SafeAreaProvider><ReadingContext.Provider value={{size:reading,setSize:changeReading}}><AppearanceContext.Provider value={{mode,setMode:change}}>{server?<Root key={server} server={server} saveServer={saveServer} updates={updates}/>:<View style={[s.page,s.fill,{justifyContent:'center'}]}><ActivityIndicator/><Note>正在读取开发服务设置…</Note></View>}<PreviewDialogs/></AppearanceContext.Provider></ReadingContext.Provider></SafeAreaProvider>;
@ -61,7 +61,7 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
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 api=useMemo(()=>variant==='dev'?connectionClient(server,reset,Platform.OS==='web'?globalThis.location.origin:undefined):new ApiClient(Platform.OS==='web'?base:server,reset),[reset,server]);
const packageUpdates=usePackageUpdates(api,scope,!!user);
const refreshMessages=useCallback(()=>{
const current=epoch.current,id=++messageSerial.current;if(!user){setUnreadMessages({count:0,exact:true});return;}
@ -72,15 +72,15 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
useEffect(()=>{refreshMessages();const timer=setInterval(()=>{if(AppState.currentState==='active')refreshMessages();},60000),listener=AppState.addEventListener('change',state=>{if(state==='active')refreshMessages();});return()=>{clearInterval(timer);listener.remove();messageSerial.current++;};},[refreshMessages]);
useEffect(()=>()=>{epoch.current++;api.clear();},[api]);
async function changeServer(value:string){
const checked=await checkDevelopmentServer(value,Platform.OS==='web'?globalThis.location.origin:undefined);
const checked=variant==='dev'?await checkDevelopmentServer(value,Platform.OS==='web'?globalThis.location.origin:undefined):productionServer(value);
if(checked===server)return;
if(user){const confirmed=await new Promise<boolean>(resolve=>Alert.alert('更换开发服务','切换后需要重新登录,未提交的表单和对话不会迁移。是否继续?',[{text:'取消',style:'cancel',onPress:()=>resolve(false)},{text:'更换并退出登录',onPress:()=>resolve(true)}]));if(!confirmed)throw new Error('已取消切换,当前服务保持不变。');}
if(user){const confirmed=await new Promise<boolean>(resolve=>Alert.alert(variant==='dev'?'更换开发服务':'切换连接方式','切换后需要重新登录,未提交的表单和对话不会迁移。是否继续?',[{text:'取消',style:'cancel',onPress:()=>resolve(false)},{text:'更换并退出登录',onPress:()=>resolve(true)}]));if(!confirmed)throw new Error('已取消切换,当前服务保持不变。');}
await storage.clear();
if(Platform.OS!=='web')await SecureStore.deleteItemAsync(serverTokenKey(variant,checked));
await saveServer(checked);
epoch.current++;api.clear();
}
const connection=variant==='dev'?<ServerConnection address={server} onSave={changeServer}/>:undefined;
const connection=variant==='dev'?<ServerConnection address={server} onSave={changeServer}/>:<ProductionConnection address={server} onSave={changeServer}/>;
const identity=useCallback(async()=>{const [info,routes]=await Promise.all([api.request<User>('/getInfo'),api.request<Row>('/getRouters')]);return {...info,pages:routeComponents(routes.data||[])};},[api]);
useEffect(()=>{let alive=true;const current=epoch.current;
void storage.get().then(async token=>{if(!alive||!token)return;api.authenticate(token);try{const data=await identity();if(alive&&epoch.current===current)setUser(data);}catch{api.clear();await storage.clear();}})
@ -106,7 +106,7 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
<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>}
{!page&&<View style={{borderRadius:12,backgroundColor:t.soft,paddingHorizontal:10,paddingVertical:5}}><Text style={{color:t.accent,fontSize:12,lineHeight:18}}>{variant==='prod'?'正式环境':'开发环境'}</Text></View>}
</View>
<View style={s.fill}>
{!page&&tab==='home'&&<Workspace api={api} scope={scope} user={user.user} modules={permitted} open={open} go={go} ai={ai}/>}
@ -124,6 +124,11 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
<PackageUpdateDialog control={packageUpdates}/>{!packageUpdates.visible&&<AppUpdateDialog {...updates}/>}
</SafeAreaView>;
}
function ProductionConnection({address,onSave}:{address:string;onSave:(value:string)=>Promise<void>}){
const [busy,setBusy]=useState(false),[error,setError]=useState('');
async function select(value:string){if(busy||value===address)return;setBusy(true);setError('');try{await onSave(value);}catch(e){setError((e as Error).message);}finally{setBusy(false);}}
return <Card><Heading>连接方式</Heading><Note>切换后需重新登录,未提交内容不会迁移。</Note><View style={s.row}><Button title="外网" secondary={address!==PRODUCTION_PUBLIC_URL} disabled={busy} onPress={()=>void select(PRODUCTION_PUBLIC_URL)}/><Button title="公司内网" secondary={address!==PRODUCTION_INTERNAL_URL} disabled={busy} onPress={()=>void select(PRODUCTION_INTERNAL_URL)}/></View>{!!error&&<Note>{error}</Note>}</Card>;
}
function Login({api,onLogin,server,connection}:{api:ApiClient;onLogin:(token:string)=>Promise<void>;server:string;connection?:React.ReactNode}){
const [username,setUsername]=useState(''),[password,setPassword]=useState(''),[code,setCode]=useState('');
const [captcha,setCaptcha]=useState<Row|null>(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[connecting,setConnecting]=useState(true);

View File

@ -5,11 +5,11 @@ import * as Application from 'expo-application';
import {Directory,File,FileMode,Paths} from 'expo-file-system';
import {fetch as expoFetch} from 'expo/fetch';
import type {ApiClient} from './core/network';
import {newerPackage,packageVerifier,verifyInstalledPackage,type PackageRelease} from './core/package-update';
import {newerPackage,packageVerifier,processPackageChunk,verifyInstalledPackage,type PackageRelease} from './core/package-update';
import {Button,Card,Heading,Icon,Note,s,useTheme} from './ui';
import {Text} from './typography';
export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
const [release,setRelease]=useState<PackageRelease|null>(null),[visible,setVisible]=useState(false),[phase,setPhase]=useState<'idle'|'checking'|'downloading'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState('');
const [release,setRelease]=useState<PackageRelease|null>(null),[visible,setVisible]=useState(false),[phase,setPhase]=useState<'idle'|'checking'|'downloading'|'verifying'|'installing'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState('');
const file=useRef<File|null>(null),fileHash=useRef(''),ctl=useRef<AbortController|null>(null),generation=useRef(0),busy=useRef(false),last=useRef(0),shown=useRef('');
// Read the installed native build, never the OTA manifest's version.
const current=Number(Application.nativeBuildVersion),environment=String(Constants.expoConfig?.extra?.environment||'dev');
@ -18,15 +18,15 @@ export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
useEffect(()=>{generation.current++;busy.current=false;shown.current='';last.current=0;file.current=null;fileHash.current='';setRelease(null);setVisible(false);setPhase('idle');setError('');void check();const listener=AppState.addEventListener('change',state=>{if(state==='active')void check();});return()=>{generation.current++;ctl.current?.abort();listener.remove();};},[scope,check]);
async function download(){if(!release||busy.current)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;setError('');setPhase('downloading');setProgress(0);const abort=new AbortController();ctl.current=abort;let output:File|null=null;
try{const dir=new Directory(Paths.cache,'app-updates');dir.create({idempotent:true,intermediates:true});output=new File(dir,release.sha256+'-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.apk');output.create();const handle=output.open(FileMode.WriteOnly),verify=packageVerifier(release);
try{await api.download(release.downloadPath,async bytes=>{verify.write(bytes);handle.writeBytes(bytes);},{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch,onProgress:n=>{if(valid())setProgress(Math.min(99,Math.round(n/release.size*100)));}});verify.finish();}finally{handle.close();}
let processed=0;try{await api.download(release.downloadPath,async bytes=>{await processPackageChunk(bytes,chunk=>{verify.write(chunk);handle.writeBytes(chunk);},length=>{processed+=length;if(valid())setProgress(Math.min(99,Math.floor(processed/release.size*100)));},abort.signal);},{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch});if(valid())setPhase('verifying');await new Promise<void>(resolve=>setTimeout(resolve,0));if(abort.signal.aborted||!valid())throw new Error('下载已取消');verify.finish();}finally{handle.close();}
if(abort.signal.aborted||!valid())throw new Error('下载已取消');file.current=output;fileHash.current=release.sha256;setPhase('ready');setProgress(100);
}catch(e){try{if(output?.exists)output.delete();}catch{}if(valid()){file.current=null;fileHash.current='';setPhase('idle');setError(abort.signal.aborted?'下载已取消,可重新下载':(e as Error).message);}}
finally{if(valid())busy.current=false;}
}
async function install(){if(!file.current||!release||busy.current)return;busy.current=true;try{await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);}catch{setError('安装包的包名、签名或版本不匹配,请联系管理员。');busy.current=false;return;}try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}catch{setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}finally{busy.current=false;}}
function later(){if(phase==='downloading')ctl.current?.abort();setVisible(false);}
async function install(){if(!file.current||!release||busy.current)return;busy.current=true;setError('');setPhase('installing');await new Promise<void>(resolve=>setTimeout(resolve,0));try{await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);}catch{setError('安装包的包名、签名或版本不匹配,请联系管理员。');busy.current=false;setPhase('ready');return;}try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}catch{setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}finally{busy.current=false;setPhase('ready');}}
function later(){if(phase==='downloading'||phase==='verifying')ctl.current?.abort();setVisible(false);}
return {release,visible,phase,progress,error,available,check:()=>void check(true),download:()=>void download(),install:()=>void install(),later};
}
export type PackageControls=ReturnType<typeof usePackageUpdates>;
export function PackageUpdateStatus({control:c}:{control:PackageControls}){return c.available?<Card><Heading>安装包更新</Heading><Note>{c.release?`新安装包 ${c.release.versionName}(${c.release.versionCode})`:'检查需要重新安装的新版本'}{c.phase==='downloading'?` · ${c.progress}%`:''}</Note>{!!c.error&&<Note>{c.error}</Note>}<Button title="检查安装包更新" secondary busy={c.phase==='checking'} disabled={c.phase==='downloading'} onPress={c.check}/></Card>:null;}
export function PackageUpdateDialog({control:c}:{control:PackageControls}){const t=useTheme();if(!c.visible||!c.release)return null;return <Modal transparent visible animationType="fade" onRequestClose={c.later}><View style={{flex:1,backgroundColor:'#0008',justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:380,alignSelf:'center',maxHeight:'85%',backgroundColor:t.card,borderRadius:20,padding:22,gap:16}}><ScrollView contentContainerStyle={{gap:12}}><Icon name="cloud-download-outline" size={30}/><Heading>发现新版安装包</Heading><Note>版本 {c.release.versionName}({c.release.versionCode}) · {(c.release.size/1024**2).toFixed(1)} MB</Note>{!!c.release.notes&&<Text style={{color:t.text,fontSize:14,lineHeight:22}}>{c.release.notes}</Text>}<Note>请先保存当前内容。下载完成后由手机系统确认安装;首次安装可能需要允许本应用安装未知应用。</Note>{c.phase==='downloading'&&<><View style={{height:6,backgroundColor:t.soft,borderRadius:3,overflow:'hidden'}}><View style={{height:6,width:`${c.progress}%`,backgroundColor:t.accent}}/></View><Note>正在下载并校验 {c.progress}%</Note></>}{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}</ScrollView><Button title={c.phase==='ready'?'安装新版':c.phase==='downloading'?'正在下载…':'下载新版'} disabled={c.phase==='downloading'} onPress={c.phase==='ready'?c.install:c.download}/><Button title={c.phase==='downloading'?'取消下载':'稍后再说'} secondary onPress={c.later}/></View></View></Modal>;}
export function PackageUpdateStatus({control:c}:{control:PackageControls}){return c.available?<Card><Heading>安装包更新</Heading><Note>{c.release?`新安装包 ${c.release.versionName}(${c.release.versionCode})`:'检查需要重新安装的新版本'}{c.phase==='downloading'?` · ${c.progress}%`:''}</Note>{!!c.error&&<Note>{c.error}</Note>}<Button title="检查安装包更新" secondary busy={c.phase==='checking'} disabled={['downloading','verifying','installing'].includes(c.phase)} onPress={c.check}/></Card>:null;}
export function PackageUpdateDialog({control:c}:{control:PackageControls}){const t=useTheme();if(!c.visible||!c.release)return null;return <Modal transparent visible animationType="fade" onRequestClose={c.later}><View style={{flex:1,backgroundColor:'#0008',justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:380,alignSelf:'center',maxHeight:'85%',backgroundColor:t.card,borderRadius:20,padding:22,gap:16}}><ScrollView contentContainerStyle={{gap:12}}><Icon name="cloud-download-outline" size={30}/><Heading>发现新版安装包</Heading><Note>版本 {c.release.versionName}({c.release.versionCode}) · {(c.release.size/1024**2).toFixed(1)} MB</Note>{!!c.release.notes&&<Text style={{color:t.text,fontSize:14,lineHeight:22}}>{c.release.notes}</Text>}<Note>请先保存当前内容。下载完成后由手机系统确认安装;首次安装可能需要允许本应用安装未知应用。</Note>{c.phase==='downloading'&&<><View style={{height:6,backgroundColor:t.soft,borderRadius:3,overflow:'hidden'}}><View style={{height:6,width:`${c.progress}%`,backgroundColor:t.accent}}/></View><Note>{c.progress===0?'正在连接并接收安装包…':`已接收并处理 ${c.progress}%`}</Note></>}{c.phase==='verifying'&&<Note>正在完成文件完整性校验…</Note>}{c.phase==='installing'&&<Note>正在验证安装包,请稍候…</Note>}{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}</ScrollView><Button title={c.phase==='ready'?'安装新版':c.phase==='downloading'?'正在下载…':c.phase==='verifying'?'正在校验…':c.phase==='installing'?'正在验证…':'下载新版'} disabled={['downloading','verifying','installing'].includes(c.phase)} onPress={c.phase==='ready'?c.install:c.download}/><Button title={['downloading','verifying'].includes(c.phase)?'取消下载':'稍后再说'} secondary onPress={c.later}/></View></View></Modal>;}

View File

@ -15,6 +15,13 @@ export function internalUrl(value: string, allowLoopback = false): string {
return url.toString().replace(/\/$/, '');
}
export const PRODUCTION_PUBLIC_URL = 'https://wms.svc.cmvr-iot.icu/prod-api';
export const PRODUCTION_INTERNAL_URL = 'http://192.168.28.10/prod-api';
export function productionServer(value: string): string {
if (value !== PRODUCTION_PUBLIC_URL && value !== PRODUCTION_INTERNAL_URL) throw new Error('无效的正式服务地址。');
return value;
}
export type Json = Record<string, unknown>;
export class ApiError extends Error {
code: number;
@ -111,7 +118,7 @@ export class ApiClient {
if (error instanceof ApiError) throw error;
if (options.signal?.aborted) throw new ApiError('请求已取消。', 499);
if (typeof __DEV__ !== 'undefined' && __DEV__) console.warn('Internal API transport failure:', error instanceof Error ? error.message : 'unknown');
throw new ApiError('暂时连接不上内网服务,请检查公司网络后重试。', 503);
throw new ApiError('暂时连接不上服务,请检查网络或切换连接方式后重试。', 503);
} finally {
clearTimeout(timer); options.signal?.removeEventListener('abort', abort);
}

View File

@ -8,6 +8,16 @@ export function newerPackage(value:any,current:number,environment:string):Packag
}
/** Hash incrementally; never install a partial file or merely trust its filename. */
export function packageVerifier(release:Pick<PackageRelease,'size'|'sha256'>){const hash=sha256.create();let size=0;return {write(bytes:Uint8Array){size+=bytes.length;if(size>release.size)throw new Error('安装包大小不匹配');hash.update(bytes);},finish(){if(size!==release.size||bytesToHex(hash.digest())!==release.sha256)throw new Error('安装包校验失败,请重新下载');}};}
/** Split even a buffered network response into bounded work and give the UI a turn. */
export async function processPackageChunk(bytes:Uint8Array,write:(chunk:Uint8Array)=>void,onChunk:(length:number)=>void,signal:AbortSignal,step=256*1024){
for(let offset=0;offset<bytes.length;offset+=step){
if(signal.aborted)throw new Error('下载已取消');
const part=bytes.subarray(offset,Math.min(offset+step,bytes.length));
write(part);onChunk(part.length);
await new Promise<void>(resolve=>setTimeout(resolve,0));
}
if(signal.aborted)throw new Error('下载已取消');
}
/** No fallback to the Android installer when the native trust check is absent. */
export async function verifyInstalledPackage(bridge:{verify:(uri:string,version:number)=>Promise<boolean>}|undefined,uri:string,version:number){
if(!bridge||!/^file:\/\//.test(uri)||!Number.isInteger(version)||version<1||await bridge.verify(uri,version)!==true)throw new Error('无法验证安装包的包名和签名,请联系管理员。');

View File

@ -1,4 +1,4 @@
import {ApiClient,internalUrl} from './network.ts';
import {ApiClient,internalUrl,productionServer,PRODUCTION_PUBLIC_URL} from './network.ts';
export const developmentServerKey='cmvr.dev.server';
@ -16,7 +16,9 @@ export function developmentServer(value:string):string {
/** No credentials are reused between development servers. SecureStore-safe, collision-free key. */
export function serverTokenKey(environment:string,address:string):string {
return environment==='dev'?`cmvr.dev.token.${Array.from(developmentServer(address)).map(c=>c.charCodeAt(0).toString(16).padStart(2,'0')).join('')}`:`cmvr.${environment}.token`;
if(environment==='dev')return `cmvr.dev.token.${Array.from(developmentServer(address)).map(c=>c.charCodeAt(0).toString(16).padStart(2,'0')).join('')}`;
if(environment==='prod')return `cmvr.prod.token.${productionServer(address)===PRODUCTION_PUBLIC_URL?'public':'internal'}`;
throw new Error('无效环境');
}
export function connectionClient(address:string,expired:()=>void,previewOrigin?:string,transport?:typeof fetch):ApiClient {

View File

@ -6,9 +6,16 @@ import {display,type Row} from '../core/modules';
import type {ArrivalKind} from '../core/arrival-actions';
import {arrivalLayout} from '../core/arrival-layout';
export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,reset,total,page}:{
export function OnlyMineToggle({value,onChange}:{value:boolean;onChange:(value:boolean)=>void}){
const t=useTheme();
return <Pressable accessibilityRole="checkbox" accessibilityLabel="只看我创建的采购明细" accessibilityState={{checked:value}} onPress={()=>onChange(!value)} style={{flexDirection:'row',alignItems:'center',gap:5,paddingVertical:6,paddingHorizontal:4}}>
<Icon name={value?'checkbox':'square-outline'} size={19} color={value?t.accent:t.muted}/><Text style={{fontSize:13,color:value?t.accent:t.text}}>只看我的</Text>
</Pressable>;
}
export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,reset,total,page,onlyMine,setOnlyMine}:{
query:string;setQuery:(v:string)=>void;queue:ArrivalKind;setQueue:(v:ArrivalKind)=>void;
busy:boolean;search:()=>void;reset:()=>void;total:number;page:number;
busy:boolean;search:()=>void;reset:()=>void;total:number;page:number;onlyMine:boolean;setOnlyMine:(v:boolean)=>void;
}){
const t=useTheme();
return <View style={{paddingHorizontal:14,paddingTop:8,paddingBottom:8,gap:8}}>
@ -30,7 +37,7 @@ export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,rese
{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:12,lineHeight:18}}>{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}</Text>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}><Text accessibilityLiveRegion="polite" style={{color:t.muted,fontSize:12,lineHeight:18}}>{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}</Text><OnlyMineToggle value={onlyMine} onChange={setOnlyMine}/></View>
</View>;
}

View File

@ -4,7 +4,7 @@ import {Text,TextInput} from '../typography';
import {ApiClient,allows} from '../core/network';
import {display,recordDisplay,type Module,type Row} from '../core/modules';
import {Button,Card,Icon,Note,s,useTheme} from '../ui';
import {ArrivalCard,ArrivalListTools} from './ArrivalListParts';
import {ArrivalCard,ArrivalListTools,OnlyMineToggle} from './ArrivalListParts';
import {arrivalListQuery} from '../core/arrival-list';
import {ArrivalActions} from './ArrivalActions';
import {ArrivalHistory} from './ArrivalHistory';
@ -15,26 +15,30 @@ import {LoanOperation} from './LoanOperation';
import type {OperationKind} from '../core/stock-operations';
import {Dialog as Alert} from '../dialogs';
type SavedList={query:string;applied:string;rows:Row[];total:number;page:number;offset:number;queue:'arrival'|'accept';compact:boolean};
type SavedList={query:string;applied:string;rows:Row[];total:number;page:number;offset:number;queue:'arrival'|'accept';compact:boolean;onlyMine:boolean};
const remembered=new Map<string,SavedList>();
export function BusinessList({api,module,permissions,canViewQuotes,scope,initialQuery={},onNavigate}:{api:ApiClient;module:Module;permissions:string[];canViewQuotes:boolean;scope:string;initialQuery?:Row;onNavigate?:(key:string,query?:Row)=>void}){
const t=useTheme(),cacheKey=scope+'|'+module.key+'|'+JSON.stringify(initialQuery),cached=useRef(remembered.get(cacheKey));
const [query,setQuery]=useState(cached.current?.query||''),[rows,setRows]=useState<Row[]>(cached.current?.rows||[]),[total,setTotal]=useState(cached.current?.total||0),[page,setPage]=useState(cached.current?.page||1),[arrivalQueue,setArrivalQueue]=useState<'arrival'|'accept'>(initialQuery.arrivalQueue||cached.current?.queue||'arrival');
const [onlyMine,setOnlyMine]=useState(cached.current?.onlyMine??false);
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[compactAmounts,setCompactAmounts]=useState(cached.current?.compact??true),[selected,setSelected]=useState<Row[]>([]),[picking,setPicking]=useState(!!initialQuery.borrow),[batch,setBatch]=useState<OperationKind|null>(null),[operation,setOperation]=useState<{row:Row;kind:string}|null>(null),[historyRow,setHistoryRow]=useState<Row|null>(null);
const serial=useRef(0),controller=useRef<AbortController|null>(null),busyRef=useRef(false),appliedQuery=useRef(cached.current?.applied||''),offset=useRef(cached.current?.offset||0),list=useRef<FlatList<Row>>(null),first=useRef(true),lastRequest=useRef({next:1,text:'',append:false});
const stockWrite=allows(permissions,['warehouse:stock:out'],['project:inventory:use']),stockRead=allows(permissions,['warehouse:stock:list']);
const initialFilters=Object.fromEntries(Object.entries(initialQuery).filter(([key])=>!['arrivalQueue','borrow'].includes(key)));
const load=useCallback(async(next:number,text:string,append=false)=>{
if(append&&busyRef.current)return;lastRequest.current={next,text,append};const id=++serial.current;controller.current?.abort();controller.current=new AbortController();busyRef.current=true;setBusy(true);setError('');appliedQuery.current=text.trim();
try{const [data,money]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...initialFilters,...(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)]);
try{const [data,money]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...initialFilters,...(module.key==='arrival'?arrivalListQuery(arrivalQueue):{}),...(['arrival','purchase'].includes(module.key)&&onlyMine?{onlyMine:true}:{}),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(money)setCompactAmounts(money.data.enabled===true);const result=data.data&&Array.isArray(data.data.rows)?data.data:data;
setRows(old=>{const fresh=result.rows||[];return append?[...old,...fresh.filter((r:Row)=>!old.some(v=>String(v.id||v.loanNo)===String(r.id||r.loanNo)))]:fresh;});setTotal(result.total||0);setPage(next);
if(!append){setSelected([]);offset.current=0;list.current?.scrollToOffset({offset:0,animated:false});}
}catch(e){if(id===serial.current)setError((e as Error).message);}finally{if(id===serial.current){busyRef.current=false;setBusy(false);}}
},[api,module,arrivalQueue,cacheKey]);
},[api,module,arrivalQueue,cacheKey,onlyMine]);
useEffect(()=>{if(first.current&&cached.current){first.current=false;}else{first.current=false;void load(1,appliedQuery.current);}return()=>{serial.current++;controller.current?.abort();};},[load]);
useEffect(()=>{remembered.set(cacheKey,{query,applied:appliedQuery.current,rows,total,page,offset:offset.current,queue:arrivalQueue,compact:compactAmounts});if(remembered.size>30)remembered.delete(remembered.keys().next().value!);},[cacheKey,query,rows,total,page,arrivalQueue,compactAmounts]);
useEffect(()=>{remembered.set(cacheKey,{query,applied:appliedQuery.current,rows,total,page,offset:offset.current,queue:arrivalQueue,compact:compactAmounts,onlyMine});if(remembered.size>30)remembered.delete(remembered.keys().next().value!);},[cacheKey,query,rows,total,page,arrivalQueue,compactAmounts,onlyMine]);
function refresh(){return load(1,appliedQuery.current);}
function clearListForFilter(){setSelected([]);setRows([]);setTotal(0);setPage(1);offset.current=0;cached.current=undefined;}
function changeOnlyMine(value:boolean){clearListForFilter();setOnlyMine(value);}
function changeArrivalQueue(value:'arrival'|'accept'){if(value!==arrivalQueue){clearListForFilter();setArrivalQueue(value);}}
function eligible(row:Row){return module.key==='pending'?allows(permissions,['warehouse:in:confirm'])&&(row.receiptRoot||allows(permissions,['warehouse:in:edit']))&&Number(row.inNum)>0:stockWrite&&Number(row.stockNum)>0;}
function toggle(row:Row){if(busy||!eligible(row))return;setSelected(old=>old.some(r=>String(r.id)===String(row.id))?old.filter(r=>String(r.id)!==String(row.id)):old.length>=100?old:[...old,row]);}
function confirmCheck(row:Row){if(busyRef.current)return;Alert.alert('确认盘点生效',`${display(row.productName)}:账面 ${display(row.bookNum)} → 实盘 ${display(row.realNum)}。确认后调整库存。`,[{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(refresh).catch(e=>setError((e as Error).message+' 请刷新核对结果。')).finally(()=>{busyRef.current=false;setBusy(false);});}}]);}
@ -51,9 +55,9 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
{module.key==='pending'&&eligible(item)&&<Button title="办理入库" disabled={busy} onPress={()=>setOperation({row:item,kind:'receive'})}/>}
</View>;
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={{paddingHorizontal:14,paddingVertical:8,gap:8}}>
{module.key==='arrival'?<ArrivalListTools query={query} setQuery={setQuery} queue={arrivalQueue} setQueue={changeArrivalQueue} busy={busy} total={total} page={page} onlyMine={onlyMine} setOnlyMine={changeOnlyMine} search={()=>void load(1,query)} reset={()=>{setQuery('');void load(1,'');}}/>:<View style={{paddingHorizontal:14,paddingVertical:8,gap:8}}>
{!!module.search&&<View style={{flexDirection:'row',gap:8,alignItems:'center'}}><View style={{flex:1,flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:t.line,borderRadius:9,backgroundColor:t.card,paddingLeft:10}}><Icon name="search-outline" size={18}/><TextInput accessibilityLabel="搜索物品或关键词" placeholder="搜索物品或关键词" placeholderTextColor={t.muted} value={query} onChangeText={setQuery} onSubmitEditing={()=>void load(1,query)} returnKeyType="search" style={{flex:1,minWidth:0,minHeight:42,fontSize:14,color:t.text,padding:8}}/>{!!query&&<Pressable accessibilityRole="button" accessibilityLabel="清除搜索" onPress={()=>{setQuery('');void load(1,'');}} style={{padding:10}}><Icon name="close-circle" size={17}/></Pressable>}</View><Button title="查询" busy={busy} onPress={()=>void load(1,query)}/></View>}
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}><Text style={{color:t.muted,fontSize:12}}>已加载 {rows.length} / 共 {total} 条</Text>{canSelect&&<Pressable accessibilityRole="button" accessibilityLabel={picking?'取消多选':'多选办理'} disabled={busy} onPress={()=>{setPicking(v=>!v);setSelected([]);}} style={{padding:8}}><Text style={{color:t.accent,fontSize:14}}>{picking?'取消多选':'多选办理'}</Text></Pressable>}{module.key==='loans'&&stockWrite&&stockRead&&onNavigate&&<Button title="发起借用" secondary onPress={()=>onNavigate('stock',{borrow:true})}/>}</View>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}><Text style={{color:t.muted,fontSize:12}}>已加载 {rows.length} / 共 {total} 条</Text>{module.key==='purchase'&&<OnlyMineToggle value={onlyMine} onChange={changeOnlyMine}/>} {canSelect&&<Pressable accessibilityRole="button" accessibilityLabel={picking?'取消多选':'多选办理'} disabled={busy} onPress={()=>{setPicking(v=>!v);setSelected([]);}} style={{padding:8}}><Text style={{color:t.accent,fontSize:14}}>{picking?'取消多选':'多选办理'}</Text></Pressable>}{module.key==='loans'&&stockWrite&&stockRead&&onNavigate&&<Button title="发起借用" secondary onPress={()=>onNavigate('stock',{borrow:true})}/>}</View>
</View>}
{!!error&&<View style={{paddingHorizontal:14,paddingBottom:8}}><Text accessibilityRole="alert" style={{fontSize:13,lineHeight:19,color:'#bd3636'}}>{error}</Text><Button title="重试" secondary onPress={()=>void load(lastRequest.current.next,lastRequest.current.text,lastRequest.current.append)}/></View>}
{picking&&<View style={{paddingHorizontal:14,paddingBottom:8}}><Button title={`选择已加载可办理项(最多 100 项)`} secondary disabled={busy} onPress={()=>setSelected(rows.filter(eligible).slice(0,100))}/></View>}

View File

@ -16,14 +16,15 @@ export function LoginView(p:Props){
<View style={styles.brand}><Image accessible={false} source={icon} style={styles.mark}/><View style={{flex:1,minWidth:0,gap:3}}><Text style={styles.brandName}>招商车研</Text><Text style={styles.department}>研发中心 · 设备仪器科</Text></View><View style={[styles.badge,{borderColor:dev?'#94724a':'#31696d'}]}><View style={{width:5,height:5,borderRadius:3,backgroundColor:accent}}/><Text style={{color:accent,fontSize:11,lineHeight:17}}>{dev?'开发环境':'正式环境'}</Text></View></View>
<View style={styles.intro}><Text style={styles.title}>设备科综合管理系统</Text><Text style={styles.subtitle}>连接研发现场,让每一项业务清晰有序</Text></View>
<View style={styles.card}>
<View style={{gap:4,marginBottom:4}}><Text style={styles.cardTitle}>登录工作空间</Text><Text style={styles.hint}>请连接公司内网,使用现有账号登录</Text></View>
<View style={{gap:4,marginBottom:4}}><Text style={styles.cardTitle}>登录工作空间</Text><Text style={styles.hint}>{dev?'请连接公司内网,使用现有账号登录':'使用现有账号登录,可选择外网或公司内网'}</Text></View>
{input('登录账号',p.username,p.setUsername,'person-outline')}
{input('密码',p.password,p.setPassword,'lock-closed-outline',true)}
{!!p.captcha&&p.captcha.captchaEnabled!==false&&<View style={{flexDirection:'row',gap:10,alignItems:'flex-end'}}>{input('验证码',p.code,p.setCode,'shield-checkmark-outline')}<Pressable accessibilityRole="button" accessibilityLabel="刷新验证码" disabled={p.busy} onPress={p.refresh} style={styles.captcha}>{p.captcha.img?<Image source={{uri:`data:image/png;base64,${p.captcha.img}`}} resizeMode="contain" style={{width:106,height:46}}/>:<Text style={styles.hint}>点击刷新</Text>}</Pressable></View>}
{!!p.error&&<View accessibilityRole="alert" style={styles.error}><Icon name="alert-circle-outline" size={18} color="#ce3e46"/><Text style={{flex:1,minWidth:0,color:'#ad3038',fontSize:13,lineHeight:20}}>{p.error}</Text></View>}
<Pressable accessibilityRole="button" accessibilityLabel="登录" accessibilityState={{disabled:!p.captcha||p.busy,busy:p.busy}} disabled={!p.captcha||p.busy} onPress={p.submit} style={({pressed})=>[styles.submit,{backgroundColor:'#216fc2',opacity:!p.captcha||p.busy?.5:pressed?.8:1}]}>{p.busy?<ActivityIndicator color="#ffffff"/>:<><Text style={styles.submitText}>登录</Text><Icon name="arrow-forward" size={18} color="#ffffff"/></>}</Pressable>
<View style={styles.statusRow}><View style={{flexDirection:'row',alignItems:'center',gap:6,flex:1,minWidth:0}}>{p.connecting?<ActivityIndicator size="small" color="#66829d"/>:<Icon name={p.captcha?'shield-checkmark-outline':'cloud-offline-outline'} size={15} color={p.captcha?'#298c73':'#8497a8'}/>}<Text style={styles.status}>{p.connecting?'正在连接内网服务…':p.captcha?'内网连接正常':'暂未连接服务'}</Text></View><Pressable accessibilityRole="button" accessibilityLabel="重新连接" disabled={p.busy||p.connecting} onPress={p.refresh} style={styles.reconnect}><Text style={{fontSize:12,color:'#246db4'}}>重新连接</Text></Pressable></View>
<View style={styles.statusRow}><View style={{flexDirection:'row',alignItems:'center',gap:6,flex:1,minWidth:0}}>{p.connecting?<ActivityIndicator size="small" color="#66829d"/>:<Icon name={p.captcha?'shield-checkmark-outline':'cloud-offline-outline'} size={15} color={p.captcha?'#298c73':'#8497a8'}/>}<Text style={styles.status}>{p.connecting?'正在连接服务…':p.captcha?'服务连接正常':'暂未连接服务'}</Text></View><Pressable accessibilityRole="button" accessibilityLabel="重新连接" disabled={p.busy||p.connecting} onPress={p.refresh} style={styles.reconnect}><Text style={{fontSize:12,color:'#246db4'}}>重新连接</Text></Pressable></View>
</View>
{!dev&&!!p.connection&&p.connection}
{dev&&!!p.connection&&<><Pressable accessibilityRole="button" accessibilityLabel="开发服务设置" accessibilityState={{expanded:settings}} onPress={()=>setSettings(v=>!v)} style={styles.settings}><Icon name="settings-outline" size={15} color="#66839f"/><Text style={{fontSize:12,color:'#4e7195'}}>开发服务设置</Text><Icon name={settings?'chevron-up':'chevron-down'} size={14} color="#66839f"/></Pressable>{settings&&<View style={{borderRadius:14,overflow:'hidden'}}>{p.connection}</View>}</>}
<View style={styles.footer}><View style={{height:1,width:24,backgroundColor:'#cddbe8'}}/><Text style={{fontSize:11,lineHeight:17,color:'#849bb1',textAlign:'center'}}>CMVR · 设备与研发同行</Text><View style={{height:1,width:24,backgroundColor:'#cddbe8'}}/></View>
</ScrollView>

View File

@ -1,5 +1,5 @@
import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';
import {newerPackage,packageVerifier,verifyInstalledPackage} from '../src/core/package-update.ts';import {ApiClient} from '../src/core/network.ts';
import {newerPackage,packageVerifier,processPackageChunk,verifyInstalledPackage} from '../src/core/package-update.ts';import {ApiClient} from '../src/core/network.ts';
import {readFileSync} from 'node:fs';import {createRequire} from 'node:module';import vm from 'node:vm';
const bytes=Buffer.from('isolated apk bytes'),hash=createHash('sha256').update(bytes).digest('hex');
const release={versionCode:4,versionName:'1.2.0',sha256:hash,size:bytes.length,notes:'说明',environment:'dev',downloadPath:`/system/mobile-release/${hash}/content`};
@ -13,6 +13,14 @@ test('only the complete byte-for-byte matching package is accepted',()=>{
v=packageVerifier(release);v.write(Buffer.alloc(bytes.length,1));assert.throws(()=>v.finish(),/校验/);
v=packageVerifier(release);assert.throws(()=>v.write(Buffer.alloc(bytes.length+1)),/大小/);
});
test('large buffered responses are processed incrementally with real byte progress and cancellation',async()=>{
const data=Buffer.alloc(700000,7), parts=[], progress=[], abort=new AbortController();let total=0;
await processPackageChunk(data,chunk=>parts.push(Buffer.from(chunk)),n=>{total+=n;progress.push(total)},abort.signal);
assert.deepEqual(Buffer.concat(parts),data);assert.deepEqual(progress,[262144,524288,700000]);
const cancelled=new AbortController();let written=0;
await assert.rejects(processPackageChunk(data,chunk=>{written+=chunk.length},()=>cancelled.abort(),cancelled.signal),/取消/);
assert.equal(written,262144);
});
test('native package verification is mandatory before invoking Android installer',async()=>{
await assert.rejects(verifyInstalledPackage(undefined,'file:///cache/one.apk',4),/无法验证/);
await assert.rejects(verifyInstalledPackage({verify:async()=>false},'file:///cache/one.apk',4),/无法验证/);

View File

@ -0,0 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createRequire} from 'node:module';
import {productionServer,PRODUCTION_PUBLIC_URL,PRODUCTION_INTERNAL_URL,internalUrl} from '../src/core/network.ts';
const require=createRequire(import.meta.url);
const {internal}=require('../config/environment.cjs');
test('production connection choices are fixed to trusted endpoints',()=>{
assert.equal(productionServer(PRODUCTION_PUBLIC_URL),PRODUCTION_PUBLIC_URL);
assert.equal(productionServer(PRODUCTION_INTERNAL_URL),PRODUCTION_INTERNAL_URL);
for(const value of ['http://wms.svc.cmvr-iot.icu/prod-api','https://wms.svc.cmvr-iot.icu.evil.test/prod-api','https://wms.svc.cmvr-iot.icu/other','https://wms.svc.cmvr-iot.icu/prod-api?x=1','http://192.168.0.1/prod-api']) assert.throws(()=>productionServer(value));
assert.throws(()=>internalUrl(PRODUCTION_PUBLIC_URL,true));
assert.equal(internal('https://wms.svc.cmvr-iot.icu',false,true),'https://wms.svc.cmvr-iot.icu');
assert.throws(()=>internal('https://wms.svc.cmvr-iot.icu',true,false));
assert.throws(()=>internal('http://wms.svc.cmvr-iot.icu',false,true));
assert.throws(()=>internal('https://wms.svc.cmvr-iot.icu.evil.test',false,true));
});

View File

@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {createRequire} from 'node:module';
import vm from 'node:vm';
const require=createRequire(import.meta.url);
const appConfig=require('../app.config.js');
const source=readFileSync(new URL('../plugins/with-internal-network.cjs',import.meta.url),'utf8');
async function generate(env,hosts){
let xml='',manifest;
const plugins={withAndroidManifest:(config,fn)=>{const result=fn({modResults:{manifest:{application:[{$:{}}]}}});manifest=result.modResults.manifest.application[0].$;return config},withDangerousMod:(config,args)=>({config,handler:args[1]})};
const module={exports:{}};
vm.runInNewContext(source,{module,exports:module.exports,require:name=>name==='expo/config-plugins'?plugins:name==='node:fs/promises'?{mkdir:async()=>{},writeFile:async(_path,data)=>{xml=data}}:name==='node:path'?require('node:path'):name==='../config/environment.cjs'?{environment:()=>env}:require(name)});
const result=module.exports({}, {hosts});await result.handler({modRequest:{platformProjectRoot:'dummy'}});return {manifest,xml};
}
test('production APK permits cleartext only for its fixed private endpoint',async()=>{
const original={...process.env};
try{
process.env.APP_ENV='prod';process.env.APP_API_URL='https://wms.svc.cmvr-iot.icu/prod-api';process.env.APP_UPDATE_ORIGIN='https://wms.svc.cmvr-iot.icu';
const config=appConfig(),plugin=config.plugins.find(x=>Array.isArray(x)&&x[0]==='./plugins/with-internal-network.cjs');
assert.deepEqual(plugin[1].hosts,['192.168.28.10']);
const {xml,manifest}=await generate({variant:'prod',apiUrl:process.env.APP_API_URL,updateOrigin:process.env.APP_UPDATE_ORIGIN},plugin[1].hosts);
assert.equal(manifest['android:usesCleartextTraffic'],'false');
assert.match(xml,/<base-config cleartextTrafficPermitted="false"\/>/);
assert.match(xml,/<domain includeSubdomains="false">192\.168\.28\.10<\/domain>/);
assert.equal((xml.match(/<domain /g)||[]).length,1);
await assert.rejects(generate({variant:'prod',apiUrl:process.env.APP_API_URL,updateOrigin:process.env.APP_UPDATE_ORIGIN},['evil.example']));
}finally{process.env=original;}
});

View File

@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {createRequire} from 'node:module';
import vm from 'node:vm';
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
const compiled=ts.transpileModule(readFileSync(new URL('../src/screens/ArrivalListParts.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
const result={};vm.runInNewContext(compiled,{exports:result,require:name=>({react:React,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Pressable:'Pressable'},'../typography':{Text:'Text',TextInput:'TextInput'},'../ui':{Icon:'Icon',useTheme:()=>({accent:'blue',muted:'gray',text:'black'})},'../core/modules':{},'../core/arrival-layout':{}}[name]||require(name))});
test('only-mine control toggles and exposes its state to accessibility',()=>{
const values=[];const off=result.OnlyMineToggle({value:false,onChange:v=>values.push(v)});assert.equal(off.props.accessibilityState.checked,false);off.props.onPress();
const on=result.OnlyMineToggle({value:true,onChange:v=>values.push(v)});assert.equal(on.props.accessibilityState.checked,true);on.props.onPress();assert.deepEqual(values,[true,false]);
});
test('purchase filter is retained in account-scoped cache and sent for every result page',()=>{
const app=readFileSync(new URL('../src/screens/BusinessList.tsx',import.meta.url),'utf8');
assert.match(app,/scope\+'\|'\+module\.key\+'\|'\+JSON\.stringify\(initialQuery\)/);
assert.match(app,/useState\(cached\.current\?\.onlyMine\?\?false\)/);
assert.match(app,/queue:arrivalQueue,compact:compactAmounts,onlyMine/);
assert.match(app,/\['arrival','purchase'\]\.includes\(module\.key\)&&onlyMine\?\{onlyMine:true\}/);
assert.match(app,/load\(page\+1,appliedQuery\.current,true\)/);
assert.match(app,/function clearListForFilter\(\)\{setSelected\(\[\]\);setRows\(\[\]\);setTotal\(0\);setPage\(1\);offset\.current=0/);
assert.match(app,/function changeArrivalQueue\(value:[^}]+clearListForFilter\(\);setArrivalQueue\(value\)/);
});

View File

@ -14,7 +14,9 @@ test('development address accepts private IP, port and API prefix with optional
test('saved native credentials are isolated by exact server address and environment',()=>{
assert.notEqual(serverTokenKey('dev','http://10.0.0.1:8080'),serverTokenKey('dev','http://10.0.0.2:8080'));
assert.notEqual(serverTokenKey('dev','http://10.0.0.1/a'),serverTokenKey('dev','http://10.0.0.1/b'));
assert.equal(serverTokenKey('prod','http://192.168.28.10/prod-api'),'cmvr.prod.token');
assert.equal(serverTokenKey('prod','http://192.168.28.10/prod-api'),'cmvr.prod.token.internal');
assert.notEqual(serverTokenKey('prod','http://192.168.28.10/prod-api'),serverTokenKey('prod','https://wms.svc.cmvr-iot.icu/prod-api'));
assert.throws(()=>serverTokenKey('prod','https://evil.example/prod-api'));
assert.match(serverTokenKey('dev','http://10.0.0.1:8080'),/^[a-z\d._-]+$/);
});
test('connection handshake is anonymous, read-only, validates system response and never retries writes',async()=>{

View File

@ -124,14 +124,18 @@ public class PurchaseRequestController extends BaseController
try(var input=file.getInputStream()){return success(SupplierQuoteImport.preview(input,sheet));}
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:export,warehouse:purchase:manage')")
public void inquiryExport(Long id,String version,HttpServletResponse response)throws Exception {
inquiryExport(id,version,null,response);
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:export,warehouse:purchase:manage')")
@PostMapping("/sheet/{id}/inquiry-export") @Log(title="导出供应商询价单",businessType=BusinessType.EXPORT)
public void inquiryExport(@PathVariable Long id,@org.springframework.web.bind.annotation.RequestParam String version,HttpServletResponse response)throws Exception {
public void inquiryExport(@PathVariable Long id,@org.springframework.web.bind.annotation.RequestParam String version,@org.springframework.web.bind.annotation.RequestParam(required=false) String selectedColumns,HttpServletResponse response)throws Exception {
var sheet=sheetService.load(id);
if(!java.util.Objects.equals(version,sheet.getVersion()))throw new com.ruoyi.common.exception.ServiceException("采购清单已变化,请刷新后重新导出询价单");
boolean compactAmounts=PurchaseQuoteAccess.allowed()&&amountDisplaySettings.enabled();
if(compactAmounts)sheet.setRows(sheet.getRows().stream().filter(row->row.getFinalUnitPrice()==null||row.getFinalUnitPrice().signum()!=0).toList());
sheet=PurchaseQuoteAccess.view(sheet);
try(var workbook=SupplierInquiryExport.workbook(sheet,!compactAmounts)) {
try(var workbook=SupplierInquiryExport.workbook(sheet,!compactAmounts,selectedColumns)) {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
com.ruoyi.common.utils.file.FileUtils.setAttachmentResponseHeader(response,"供应商询价单_"+sheet.getBatch().getBatchNo()+".xlsx");
workbook.write(response.getOutputStream());
@ -212,7 +216,7 @@ public class PurchaseRequestController extends BaseController
PurchaseQuoteAccess.require();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
com.ruoyi.common.utils.file.FileUtils.setAttachmentResponseHeader(response,"供应商采购汇总.xlsx");
var rows=purchaseRequestService.selectPurchaseRequestList(com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(query));
var rows=purchaseRequestService.selectPurchaseRequestList(purchaseDisplay(query));
if(ids!=null && ids.length>0){var selected=new java.util.HashSet<>(java.util.Arrays.asList(ids));rows=rows.stream().filter(row->selected.contains(row.getId())).toList();}
try(var workbook=SupplierPurchaseExport.workbook(rows)){workbook.write(response.getOutputStream());}
}
@ -356,6 +360,7 @@ public class PurchaseRequestController extends BaseController
@GetMapping("/batch/list")
public TableDataInfo batchList(PurchaseBatch batch)
{
batch.setCreateBy(Boolean.TRUE.equals(batch.getOnlyMine()) ? com.ruoyi.common.utils.SecurityUtils.getUsername() : null);
if(PurchaseQuoteAccess.allowed())com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(batch);
else batch.getParams().remove("amountDisplay");
startPage();
@ -419,6 +424,7 @@ public class PurchaseRequestController extends BaseController
}
private PurchaseRequest purchaseDisplay(PurchaseRequest query) {
query.setCreateBy(Boolean.TRUE.equals(query.getOnlyMine()) ? com.ruoyi.common.utils.SecurityUtils.getUsername() : null);
if(PurchaseQuoteAccess.allowed())com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(query);
else query.getParams().remove("amountDisplay");
return query;

View File

@ -17,7 +17,7 @@ public final class SupplierInquiryExport {
private SupplierInquiryExport() { }
public record Item(String productCode, String name, String spec, String brand, String unit,
BigDecimal quantity, String link, List<Long> rowIds, String snapshot, String previousPrice,
BigDecimal actualUnitPrice, BigDecimal actualAmount, boolean mixedActualPrices) { }
BigDecimal actualUnitPrice, BigDecimal actualAmount, boolean mixedActualPrices, String remark) { }
public static boolean eligible(PurchaseRequest row) {
return !Boolean.TRUE.equals(row.getHistorical()) && !Integer.valueOf(5).equals(row.getPurchaseStatus())
&& (row.getReceivedQuantity() == null || row.getReceivedQuantity().signum() <= 0);
@ -32,7 +32,7 @@ public final class SupplierInquiryExport {
List<Item> result = new ArrayList<>();
for (var entry : groups.entrySet()) {
var rows = entry.getValue(); var first = rows.get(0);
BigDecimal quantity = BigDecimal.ZERO; Set<String> links = new LinkedHashSet<>(), prices = new LinkedHashSet<>();
BigDecimal quantity = BigDecimal.ZERO; Set<String> links = new LinkedHashSet<>(), prices = new LinkedHashSet<>(), remarks = new LinkedHashSet<>();
BigDecimal actualAmount=BigDecimal.ZERO;Set<BigDecimal> actualPrices=new LinkedHashSet<>();boolean completeActual=true;
for (var row : rows) {
if (!identity(first).equals(identity(row)) || !Objects.equals(first.getProductId(), row.getProductId()))
@ -41,6 +41,7 @@ public final class SupplierInquiryExport {
throw new ServiceException("采购明细数量或编号无效,请保存并刷新后导出询价单");
quantity = quantity.add(row.getQuantity());
if (!clean(row.getPurchaseLink()).isEmpty()) links.add(clean(row.getPurchaseLink()));
if (!clean(row.getRemark()).isEmpty()) remarks.add(clean(row.getRemark()));
prices.add(row.getFinalUnitPrice() == null ? "未报价" : row.getFinalUnitPrice().stripTrailingZeros().toPlainString());
if(row.getActualUnitPrice()==null)completeActual=false;
else {actualPrices.add(row.getActualUnitPrice().stripTrailingZeros());actualAmount=actualAmount.add(row.getActualUnitPrice().multiply(row.getQuantity()).setScale(2,RoundingMode.HALF_UP));}
@ -53,7 +54,7 @@ public final class SupplierInquiryExport {
result.add(new Item(entry.getKey(), clean(first.getMaterialName()), clean(first.getMaterialParams()), clean(first.getMaterialBrand()),
clean(first.getUnit()), quantity, String.join("\n", links), rows.stream().map(PurchaseRequest::getId).toList(), snapshot,
prices.size() == 1 ? prices.iterator().next() : "多种原报价",
completeActual&&actualPrices.size()==1?actualPrices.iterator().next():null,completeActual?actualAmount:null,completeActual&&actualPrices.size()>1));
completeActual&&actualPrices.size()==1?actualPrices.iterator().next():null,completeActual?actualAmount:null,completeActual&&actualPrices.size()>1,String.join("\n",remarks)));
}
return result;
}
@ -64,6 +65,20 @@ public final class SupplierInquiryExport {
return workbook(purchase,true);
}
public static XSSFWorkbook workbook(PurchaseSheet purchase,boolean includeActualAmounts) {
return workbook(purchase,includeActualAmounts,null);
}
private static final Set<String> COLUMN_KEYS=Set.of("name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","actualUnitPrice","actualAmount","link","remark");
public static XSSFWorkbook workbook(PurchaseSheet purchase,boolean includeActualAmounts,String selectedColumns) {
Set<String> selected;
if(selectedColumns==null) selected=COLUMN_KEYS;
else {
selected=new HashSet<>();
for(String key:selectedColumns.split(",",-1)) {
if(!COLUMN_KEYS.contains(key)) throw new ServiceException("询价单导出列无效,请重新选择");
selected.add(key);
}
if(!selected.contains("quoteUnitPrice")) throw new ServiceException("报价单价是回填必需列,请保留");
}
var items = items(purchase);
if (items.isEmpty()) throw new ServiceException("当前批次暂无可询价明细,已入库、历史及取消明细不参与报价回填");
var book = new XSSFWorkbook(); var sheet = book.createSheet("供应商询价单"); sheet.setDisplayGridlines(false);
@ -87,40 +102,51 @@ public final class SupplierInquiryExport {
context.createCell(3).setCellValue("供应商"); context.createCell(4).setCellValue(supplier);
sheet.createRow(3).createCell(0).setCellValue("填写说明:仅填写黄色报价单价,未报价留空。请保留物品信息及隐藏匹配列,填写后将本文件回传。"+(includeActualAmounts?"实际金额仅供参考,未填齐时留空,不随报价回传修改。":""));
sheet.getRow(3).setHeightInPoints(22);
String[] headers = includeActualAmounts?new String[]{"序号","物品名称","规格型号","品牌","单位","采购数量","报价单价(元)","报价金额(元)","实际单价(元)","实际金额(元)","采购链接","采购批次","物品编码","清单校验"}:new String[]{"序号","物品名称","规格型号","品牌","单位","采购数量","报价单价(元)","报价金额(元)","采购链接","采购批次","物品编码","清单校验"};
int[] widths = includeActualAmounts?new int[]{8,26,40,18,9,14,18,18,18,18,38,20,20,68}:new int[]{8,26,40,18,9,14,18,18,38,20,20,68};
int linkColumn=includeActualAmounts?10:8,batchColumn=linkColumn+1,codeColumn=linkColumn+2,snapshotColumn=linkColumn+3;
String[] headers = includeActualAmounts?new String[]{"序号","物品名称","规格型号","品牌","单位","采购数量","报价单价(元)","报价金额(元)","实际单价(元)","实际金额(元)","采购链接","采购批次","物品编码","清单校验","备注"}:new String[]{"序号","物品名称","规格型号","品牌","单位","采购数量","报价单价(元)","报价金额(元)","采购链接","采购批次","物品编码","清单校验","备注"};
int[] widths = includeActualAmounts?new int[]{8,26,40,18,9,14,18,18,18,18,38,20,20,68,38}:new int[]{8,26,40,18,9,14,18,18,38,20,20,68,38};
int linkColumn=includeActualAmounts?10:8,batchColumn=linkColumn+1,codeColumn=linkColumn+2,snapshotColumn=linkColumn+3,remarkColumn=linkColumn+4;
String[] keys=includeActualAmounts?new String[]{"","name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","actualUnitPrice","actualAmount","link","","","","remark"}:new String[]{"","name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","link","","","","remark"};
var head = sheet.createRow(5); head.setHeightInPoints(28);
for (int c=0;c<headers.length;c++) { var cell=head.createCell(c);cell.setCellValue(headers[c]);cell.setCellStyle(headerStyle);sheet.setColumnWidth(c,widths[c]*256); }
int index=6;
for (var item : items) {
var row=sheet.createRow(index);row.setHeightInPoints(item.spec().length()>35 || item.name().length()>20 ? 44 : 32);
var row=sheet.createRow(index);row.setHeightInPoints(Math.min(409,Math.max(item.spec().length()>35 || item.name().length()>20 ? 44 : 32, selected.contains("remark") ? remarkHeight(item.remark()) : 0)));
for (int c=0;c<headers.length;c++) row.createCell(c).setCellStyle(body);
row.getCell(0).setCellValue(index-5);setText(row.getCell(1),item.name());setText(row.getCell(2),item.spec());
setText(row.getCell(3),item.brand());setText(row.getCell(4),item.unit());row.getCell(5).setCellValue(item.quantity().doubleValue());row.getCell(5).setCellStyle(item.quantity().stripTrailingZeros().scale()<=0?wholeQuantity:fractionalQuantity);
row.getCell(6).setCellStyle(input);
row.getCell(7).setCellFormula("IF(ISNUMBER(G"+(index+1)+"),ROUND(F"+(index+1)+"*G"+(index+1)+",2),\"\")");row.getCell(7).setCellStyle(amount);
if(selected.contains("quoteAmount"))row.getCell(7).setCellFormula("IF(ISNUMBER(G"+(index+1)+"),ROUND(F"+(index+1)+"*G"+(index+1)+",2),\"\")");row.getCell(7).setCellStyle(amount);
if(includeActualAmounts) {
row.getCell(8).setCellStyle(numeric);row.getCell(9).setCellStyle(amount);
if(item.mixedActualPrices())setText(row.getCell(8),"多种实际单价");else if(item.actualUnitPrice()!=null)row.getCell(8).setCellValue(item.actualUnitPrice().doubleValue());
if(item.actualAmount()!=null)row.getCell(9).setCellValue(item.actualAmount().doubleValue());
if(selected.contains("actualUnitPrice")){if(item.mixedActualPrices())setText(row.getCell(8),"多种实际单价");else if(item.actualUnitPrice()!=null)row.getCell(8).setCellValue(item.actualUnitPrice().doubleValue());}
if(selected.contains("actualAmount")&&item.actualAmount()!=null)row.getCell(9).setCellValue(item.actualAmount().doubleValue());
}
setText(row.getCell(linkColumn),item.link());row.getCell(batchColumn).setCellValue(purchase.getBatch().getBatchNo());row.getCell(codeColumn).setCellValue(item.productCode());row.getCell(snapshotColumn).setCellValue(item.snapshot());
if(selected.contains("link"))setText(row.getCell(linkColumn),item.link());if(selected.contains("remark"))setText(row.getCell(remarkColumn),item.remark());row.getCell(batchColumn).setCellValue(purchase.getBatch().getBatchNo());row.getCell(codeColumn).setCellValue(item.productCode());row.getCell(snapshotColumn).setCellValue(item.snapshot());
for(int c=batchColumn;c<=snapshotColumn;c++)row.getCell(c).setCellStyle(text);
index++;
}
var helper=sheet.getDataValidationHelper();
var validation=helper.createValidation(helper.createDecimalConstraint(DataValidationConstraint.OperatorType.BETWEEN,"0","999999999999.999999"),new org.apache.poi.ss.util.CellRangeAddressList(6,index-1,6,6));
validation.setEmptyCellAllowed(true);validation.setShowErrorBox(true);validation.createErrorBox("请填写有效单价","报价单价需为非负数,最多6位小数;不报价请留空。");sheet.addValidationData(validation);
sheet.createFreezePane(2,6);sheet.setAutoFilter(new CellRangeAddress(5,index-1,0,snapshotColumn));
sheet.createFreezePane(2,6);sheet.setAutoFilter(new CellRangeAddress(5,index-1,0,remarkColumn));
for(int c=batchColumn;c<=snapshotColumn;c++)sheet.setColumnHidden(c,true);
if(includeActualAmounts) {
var total=sheet.createRow(index);total.setHeightInPoints(28);total.createCell(8).setCellValue("实际金额合计");total.getCell(8).setCellStyle(body);
for(int c=1;c<keys.length;c++)if(!keys[c].isEmpty()&&!selected.contains(keys[c]))sheet.setColumnHidden(c,true);
if(includeActualAmounts && selected.contains("actualAmount")) {
var total=sheet.createRow(index);total.setHeightInPoints(28);int labelColumn=selected.contains("actualUnitPrice")?8:selected.contains("quoteAmount")?7:6;total.createCell(labelColumn).setCellValue("实际金额合计");total.getCell(labelColumn).setCellStyle(body);
total.createCell(9).setCellFormula("IF(COUNT(J7:J"+index+")="+items.size()+",SUM(J7:J"+index+"),\"\")");total.getCell(9).setCellStyle(amount);index++;
}
sheet.setRepeatingRows(new CellRangeAddress(5,5,-1,-1));sheet.getPrintSetup().setLandscape(true);sheet.getPrintSetup().setPaperSize(PrintSetup.A3_PAPERSIZE);sheet.getPrintSetup().setFitWidth((short)1);sheet.getPrintSetup().setFitHeight((short)0);sheet.setFitToPage(true);
book.setPrintArea(0,0,linkColumn,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true);
book.setPrintArea(0,0,remarkColumn,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true);
return book;
}
private static float remarkHeight(String remark) {
int lines=0;
for(String line:remark.split("\n",-1)) {
int width=0;
for(int i=0;i<line.length();i++) width+=line.charAt(i)>127?2:1;
lines+=Math.max(1,(width+35)/36);
}
return lines*16f+12f;
}
private static void setText(Cell cell,String value) {if(clean(value).isEmpty())cell.setBlank();else cell.setCellValue(value);}
}

View File

@ -0,0 +1,74 @@
package com.ruoyi.projectdev;
import com.ruoyi.warehouse.domain.PurchaseBatch;
import com.ruoyi.warehouse.domain.PurchaseRequest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PurchaseOnlyMineMapperTest {
@Test void creatorFilteringIsOptionalAndWorksWithArrivalQueues() throws Exception {
var config = AuthorizedDatabaseTestSupport.configuration("mapper/warehouse/PurchaseRequestMapper.xml");
var statement = config.getMappedStatement("com.ruoyi.warehouse.mapper.PurchaseRequestMapper.selectPurchaseRequestList");
var query = new PurchaseRequest();
query.setPendingAcceptance(true);
assertFalse(statement.getBoundSql(query).getSql().contains("pr.create_by = ?"));
query.setOnlyMine(true);
query.setCreateBy("authenticated-user");
var bound = statement.getBoundSql(query);
assertTrue(bound.getSql().contains("pr.create_by = ?"));
assertTrue(bound.getSql().contains("coalesce(pa.pending_quantity, 0) > 0"));
assertTrue(bound.getParameterMappings().stream().anyMatch(p -> p.getProperty().equals("createBy")));
}
@Test void batchFilterUsesExistingDetailWithoutTruncatingBatchAggregates() throws Exception {
var config = AuthorizedDatabaseTestSupport.configuration("mapper/warehouse/PurchaseBatchMapper.xml");
var statement = config.getMappedStatement("com.ruoyi.warehouse.mapper.PurchaseBatchMapper.selectPurchaseBatchList");
var query = new PurchaseBatch();
assertFalse(statement.getBoundSql(query).getSql().contains("mine.create_by"));
query.setOnlyMine(true);
query.setCreateBy("authenticated-user");
var bound = statement.getBoundSql(query);
assertTrue(bound.getSql().contains("mine.create_by=?"));
assertTrue(bound.getSql().contains("count(pr.id)"));
assertTrue(bound.getParameterMappings().stream().anyMatch(p -> p.getProperty().equals("createBy")));
}
@Test void batchCreatorProjectAndMaterialMustMatchTheSameDetail() throws Exception {
var config = AuthorizedDatabaseTestSupport.configuration("mapper/warehouse/PurchaseBatchMapper.xml");
var statement = config.getMappedStatement("com.ruoyi.warehouse.mapper.PurchaseBatchMapper.selectPurchaseBatchList");
try (var connection = java.sql.DriverManager.getConnection("jdbc:h2:mem:purchase_mine;MODE=MySQL;DB_CLOSE_DELAY=-1")) {
try (var sql = connection.createStatement()) {
sql.execute("create table purchase_batch(id bigint primary key)");
sql.execute("create table purchase_request(purchase_batch_id bigint, del_flag varchar(1), create_by varchar(64), project_id bigint, material_name varchar(80), material_brand varchar(80), material_params varchar(80))");
sql.execute("insert into purchase_batch values (1)");
sql.execute("insert into purchase_request values (1, '0', 'alice', 1, 'motor', '', ''), (1, '0', 'bob', 2, 'pump', '', ''), (1, '0', 'alice', 2, 'valve', '', '')");
}
var query = new PurchaseBatch(); query.setOnlyMine(true); query.setCreateBy("alice");
query.setProjectId(1L); query.setMaterialName("motor");
assertTrue(matchesBatch(connection, statement, query));
query.setProjectId(2L); query.setMaterialName("pump");
assertFalse(matchesBatch(connection, statement, query)); // project and material belong to another user
query.setMaterialName("motor");
assertFalse(matchesBatch(connection, statement, query)); // two owned rows, but neither matches both
query.setMaterialName(null);
assertTrue(matchesBatch(connection, statement, query));
query.setProjectId(null); query.setMaterialName("pump");
assertFalse(matchesBatch(connection, statement, query));
}
}
private boolean matchesBatch(java.sql.Connection connection, org.apache.ibatis.mapping.MappedStatement statement, PurchaseBatch query) throws Exception {
var bound = statement.getBoundSql(query);
String fullSql = bound.getSql();
int start = fullSql.indexOf("exists(select 1 from purchase_request mine");
int end = fullSql.indexOf("group by pb.id", start);
assertTrue(start >= 0 && end > start);
try (var prepared = connection.prepareStatement("select count(*) from purchase_batch pb where 1=1 and " + fullSql.substring(start, end))) {
int i = 1;
prepared.setString(i++, query.getCreateBy());
if (query.getProjectId() != null) prepared.setLong(i++, query.getProjectId());
if (query.getMaterialName() != null && !query.getMaterialName().isEmpty()) prepared.setString(i, query.getMaterialName());
try (var result = prepared.executeQuery()) { result.next(); return result.getLong(1) != 0; }
}
}
}

View File

@ -0,0 +1,45 @@
package com.ruoyi.web.controller.warehouse;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.warehouse.domain.PurchaseBatch;
import com.ruoyi.warehouse.domain.PurchaseRequest;
import com.ruoyi.warehouse.service.IPurchaseBatchService;
import com.ruoyi.warehouse.service.IPurchaseRequestService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
class PurchaseOnlyMineControllerTest {
@AfterEach void clear() { SecurityContextHolder.clearContext(); }
@Test void requestParametersCannotChooseAnotherCreator() throws Exception {
var user = new SysUser(); user.setUserId(12L); user.setUserName("current-user");
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(12L, 1L, user, Set.of()), null));
var controller = new PurchaseRequestController();
var purchases = mock(IPurchaseRequestService.class);
var batches = mock(IPurchaseBatchService.class);
ReflectionTestUtils.setField(controller, "purchaseRequestService", purchases);
ReflectionTestUtils.setField(controller, "purchaseBatchService", batches);
when(purchases.selectPurchaseRequestList(any())).thenReturn(List.of());
when(batches.selectPurchaseBatchList(any())).thenReturn(List.of());
var mvc = MockMvcBuilders.standaloneSetup(controller).build();
for (String endpoint : List.of("/warehouse/purchase/list", "/warehouse/purchase/filtered", "/warehouse/purchase/filtered-totals")) {
mvc.perform(get(endpoint).param("onlyMine", "true").param("createBy", "other-user")).andReturn();
}
verify(purchases, times(3)).selectPurchaseRequestList(argThat(q -> Boolean.TRUE.equals(q.getOnlyMine()) && "current-user".equals(q.getCreateBy())));
mvc.perform(get("/warehouse/purchase/batch/list").param("onlyMine", "true").param("createBy", "other-user")).andReturn();
verify(batches).selectPurchaseBatchList(argThat(q -> Boolean.TRUE.equals(q.getOnlyMine()) && "current-user".equals(q.getCreateBy())));
mvc.perform(get("/warehouse/purchase/filtered").param("onlyMine", "false").param("createBy", "other-user")).andReturn();
verify(purchases).selectPurchaseRequestList(argThat(q -> Boolean.FALSE.equals(q.getOnlyMine()) && q.getCreateBy() == null));
}
}

View File

@ -87,7 +87,7 @@ class SupplierInquiryRoundTripTest {
var tab=book.getSheetAt(0);assertEquals("实际单价(元)",tab.getRow(5).getCell(8).getStringCellValue());assertEquals("实际金额(元)",tab.getRow(5).getCell(9).getStringCellValue());
assertEquals(CellType.NUMERIC,tab.getRow(6).getCell(8).getCellType());assertEquals(12.345678,tab.getRow(6).getCell(8).getNumericCellValue());assertEquals(37.04,tab.getRow(6).getCell(9).getNumericCellValue());
assertEquals(0,tab.getRow(7).getCell(9).getNumericCellValue());assertEquals(37.04,tab.getRow(8).getCell(9).getNumericCellValue());assertTrue(tab.getRow(8).getCell(9).getCellFormula().contains("SUM(J7:J8)"));
assertEquals(CellType.BLANK,tab.getRow(6).getCell(6).getCellType());assertTrue(book.getPrintArea(0).contains("$K$"));
assertEquals(CellType.BLANK,tab.getRow(6).getCell(6).getCellType());assertTrue(book.getPrintArea(0).contains("$O$"));
var output=System.getProperty("inquiryActualSampleOutput");
if(output!=null){Path root=Path.of(System.getProperty("user.dir")).toAbsolutePath();if(!Files.isDirectory(root.resolve("ruoyi-admin")))root=root.getParent();Path target=Path.of(output).toAbsolutePath().normalize();assertTrue(target.startsWith(root.resolve(".codex-tmp")));Files.createDirectories(target);try(var stream=Files.newOutputStream(target.resolve("inquiry-actual-sample.xlsx"))){book.write(stream);}}
}
@ -109,10 +109,49 @@ class SupplierInquiryRoundTripTest {
var controller=new PurchaseRequestController();var sheets=org.mockito.Mockito.mock(com.ruoyi.warehouse.service.impl.PurchaseSheetService.class);var settings=org.mockito.Mockito.mock(com.ruoyi.warehouse.service.impl.AmountDisplaySettings.class);
org.springframework.test.util.ReflectionTestUtils.setField(controller,"sheetService",sheets);org.springframework.test.util.ReflectionTestUtils.setField(controller,"amountDisplaySettings",settings);org.mockito.Mockito.when(sheets.load(1L)).thenReturn(purchase);org.mockito.Mockito.when(settings.enabled()).thenReturn(true);
var response=new org.springframework.mock.web.MockHttpServletResponse();
try(var security=org.mockito.Mockito.mockStatic(com.ruoyi.common.utils.SecurityUtils.class)){
security.when(()->com.ruoyi.common.utils.SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
try(var security=org.mockito.Mockito.mockStatic(com.ruoyi.warehouse.util.PurchaseQuoteAccess.class,org.mockito.Mockito.CALLS_REAL_METHODS)){
security.when(com.ruoyi.warehouse.util.PurchaseQuoteAccess::allowed).thenReturn(true);
controller.inquiryExport(1L,"snapshot-1",response);
}
try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){var tab=book.getSheetAt(0);assertEquals("采购链接",tab.getRow(5).getCell(8).getStringCellValue());assertTrue(tab.isColumnHidden(9));for(var cell:tab.getRow(5))assertFalse(cell.getStringCellValue().contains("实际"));}
}
@Test void remarksAreMergedReadableAndSurviveRoundTripInBothLayouts() throws Exception {
var purchase=purchase();purchase.getRows().get(0).setRemark("优先交货\n需要合格证");purchase.getRows().get(1).setRemark("请单独包装,确认颜色和尺寸后再发货");
for(boolean includeActual:List.of(true,false))try(var book=SupplierInquiryExport.workbook(purchase,includeActual);var bytes=new ByteArrayOutputStream()) {
var tab=book.getSheetAt(0);int remark=includeActual?14:12;
assertEquals("备注",tab.getRow(5).getCell(remark).getStringCellValue());
assertEquals("优先交货\n需要合格证\n请单独包装,确认颜色和尺寸后再发货",tab.getRow(6).getCell(remark).getStringCellValue());
assertTrue(tab.getRow(6).getHeightInPoints()>32);assertTrue(tab.getRow(6).getCell(remark).getCellStyle().getWrapText());
assertTrue(book.getPrintArea(0).contains(includeActual?"$O$":"$M$"));
tab.getRow(6).getCell(6).setCellValue(9);book.write(bytes);
var result=preview(bytes.toByteArray(),purchase);assertTrue(ready(result.get(0)));assertEquals(List.of(1L,2L),result.get(0).get("rowIds"));
}
}
@Test void selectedColumnsHideRequiredIdentityButNeverWriteUnselectedOptionalValues() throws Exception {
var purchase=purchase();purchase.getRows().forEach(r->{r.setRemark("敏感备注");r.setActualUnitPrice(BigDecimal.TEN);});
for(boolean includeActual:List.of(true,false))try(var book=SupplierInquiryExport.workbook(purchase,includeActual,"name,quoteUnitPrice");var bytes=new ByteArrayOutputStream()) {
var tab=book.getSheetAt(0);int link=includeActual?10:8,remark=includeActual?14:12;
assertTrue(tab.isColumnHidden(2));assertFalse(tab.isColumnHidden(1));assertFalse(tab.isColumnHidden(6));
assertEquals(CellType.BLANK,tab.getRow(6).getCell(link).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(remark).getCellType());
assertEquals(CellType.BLANK,tab.getRow(6).getCell(7).getCellType());
if(includeActual){assertEquals(CellType.BLANK,tab.getRow(6).getCell(8).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(9).getCellType());}
tab.getRow(6).getCell(6).setCellValue(5);book.write(bytes);assertTrue(ready(preview(bytes.toByteArray(),purchase).get(0)));
}
assertThrows(ServiceException.class,()->SupplierInquiryExport.workbook(purchase,true,"name"));
assertThrows(ServiceException.class,()->SupplierInquiryExport.workbook(purchase,true,"quoteUnitPrice,bogus"));
}
@Test void totalLabelRemainsVisibleWhenActualUnitPriceIsOmitted() throws Exception {
var purchase=purchase();purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN));
try(var book=SupplierInquiryExport.workbook(purchase,true,"name,quoteUnitPrice,actualAmount,remark")) {
var sheet=book.getSheetAt(0);assertTrue(sheet.isColumnHidden(8));assertFalse(sheet.isColumnHidden(6));
assertEquals("实际金额合计",sheet.getRow(8).getCell(6).getStringCellValue());
assertEquals(60,sheet.getRow(8).getCell(9).getNumericCellValue());
assertEquals("A6:O8",sheet.getCTWorksheet().getAutoFilter().getRef());
}
try(var book=SupplierInquiryExport.workbook(purchase,false,"name,quoteUnitPrice,remark")) {
assertEquals("A6:M8",book.getSheetAt(0).getCTWorksheet().getAutoFilter().getRef());
}
}
}

View File

@ -7,6 +7,9 @@ public class PurchaseBatch extends BaseEntity
private static final long serialVersionUID = 1L;
private Long id;
private Boolean onlyMine;
public Boolean getOnlyMine() { return onlyMine; }
public void setOnlyMine(Boolean onlyMine) { this.onlyMine = onlyMine; }
private Long projectId;
private String materialName;
private String projectNames;

View File

@ -14,6 +14,11 @@ public class PurchaseRequest extends BaseEntity
private Long id;
/** Optional list filter, bound to the authenticated creator by the controller. */
private Boolean onlyMine;
public Boolean getOnlyMine() { return onlyMine; }
public void setOnlyMine(Boolean onlyMine) { this.onlyMine = onlyMine; }
private String requestNo;
private Long productId;

View File

@ -43,6 +43,11 @@
<if test="params.amountDisplay == true">and (not exists(select 1 from sys_config adc where adc.config_key='wms.display.compactAmounts' and adc.config_value='true') or pr.final_unit_price is null or pr.final_unit_price&lt;&gt;0)</if>
left join project_info pj on pj.id=pr.project_id
<where>
<if test="onlyMine == true">
and exists(select 1 from purchase_request mine where mine.purchase_batch_id=pb.id and mine.del_flag='0' and mine.create_by=#{createBy}
<if test="projectId != null">and mine.project_id=#{projectId}</if>
<if test="materialName != null and materialName != ''">and concat_ws(' ',mine.material_name,mine.material_brand,mine.material_params) like concat('%',#{materialName},'%')</if>)
</if>
<if test="params.amountDisplay == true">and (pr.id is not null or not exists(select 1 from purchase_request az where az.purchase_batch_id=pb.id and az.del_flag='0'))</if>
<if test="batchNo != null and batchNo != ''">and pb.batch_no like concat('%', #{batchNo}, '%')</if>
<if test="batchName != null and batchName != ''">and pb.batch_name like concat('%', #{batchName}, '%')</if>
@ -50,8 +55,8 @@
<if test="beginDate != null">and pb.business_date&gt;=#{beginDate}</if><if test="endDate != null">and pb.business_date&lt;=#{endDate}</if>
<if test="purchaseStatus != null">and pb.purchase_status = #{purchaseStatus}</if>
<if test="supplierId != null">and pb.supplier_id=#{supplierId}</if>
<if test="projectId != null">and exists(select 1 from purchase_request x where x.purchase_batch_id=pb.id and x.del_flag='0' and x.project_id=#{projectId})</if>
<if test="materialName != null and materialName != ''">and exists(select 1 from purchase_request x where x.purchase_batch_id=pb.id and x.del_flag='0' and concat_ws(' ',x.material_name,x.material_brand,x.material_params) like concat('%',#{materialName},'%'))</if>
<if test="onlyMine != true and projectId != null">and exists(select 1 from purchase_request x where x.purchase_batch_id=pb.id and x.del_flag='0' and x.project_id=#{projectId})</if>
<if test="onlyMine != true and materialName != null and materialName != ''">and exists(select 1 from purchase_request x where x.purchase_batch_id=pb.id and x.del_flag='0' and concat_ws(' ',x.material_name,x.material_brand,x.material_params) like concat('%',#{materialName},'%'))</if>
</where>
group by pb.id,pb.supplier_id,pb.business_date, pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
pb.create_by, pb.create_time, pb.update_by, pb.update_time

View File

@ -109,6 +109,7 @@
<include refid="selectPurchaseRequestVo"/>
<where>
pr.del_flag = '0'
<if test="onlyMine == true">and pr.create_by = #{createBy}</if>
<if test="params.amountDisplay == true">and (not exists(select 1 from sys_config adc where adc.config_key='wms.display.compactAmounts' and adc.config_value='true') or pr.final_unit_price is null or pr.final_unit_price&lt;&gt;0)</if>
<if test="requestNo != null and requestNo != ''">and pr.request_no like concat('%', #{requestNo}, '%')</if>
<if test="productId != null">and pr.product_id = #{productId}</if>

View File

@ -1,15 +1,15 @@
<template>
<div :class="['sheet-cell', {'cell-numeric':['quantity','actualUnitPrice','finalUnitPrice'].includes(column.field),'cell-invalid':owner.cellError(row,column.field),'cell-editable':owner.editableCell(row,column.field),'cell-active':active&&owner.editableCell(row,column.field),'cell-selected':owner.isGridSelected?.(row,column.field)}]" tabindex="0" @mousedown="owner.startCellSelection?.(row,column.field,$event)" @mouseenter="owner.extendCellSelection?.(row,column.field,$event)" @focus="owner.focusGridCell?.(row,column.field)" @dblclick="owner.activateCell(row,column.field,true,$event)" :data-row="index" :data-field="column.field" :aria-label="'第'+(index+1)+'行 '+column.label" :title="owner.cellError(row,column.field) || (owner.isEditing&&owner.fieldLocked(row,column.field)?column.field==='finalUnitPrice'?'已有到货,请退出编辑后选择该行,使用更正价格同步关联金额':'已有到货或入库,请先按流程退回后修改':String(owner.displayCell(row,column.field) ?? ''))" @focusin="active&&owner.rememberCell(index,column.field)" @copy="owner.copyGridEvent?.($event)" @paste="owner.paste($event,index,column.field)" @keydown.esc.capture.stop="owner.navigate($event,index,column.field)" @keydown="owner.navigate($event,index,column.field)">
<div :class="['sheet-cell', {'cell-numeric':['quantity','actualUnitPrice','finalUnitPrice'].includes(column.field),'cell-invalid':owner.cellError(row,column.field),'cell-editable':owner.editableCell(row,column.field),'cell-active':active&&owner.editableCell(row,column.field),'cell-selected':owner.isGridSelected?.(row,column.field)}]" tabindex="0" @mousedown="owner.startCellSelection?.(row,column.field,$event)" @mouseenter="owner.extendCellSelection?.(row,column.field,$event)" @focus="owner.focusGridCell?.(row,column.field)" @dblclick="owner.activateCell(row,column.field,true,$event)" :data-row="index" :data-field="column.field" :aria-label="'第'+(index+1)+'行 '+column.label" :title="owner.cellError(row,column.field) || (owner.isEditing&&owner.fieldLocked(row,column.field)?column.field==='finalUnitPrice'?'已有到货,请退出编辑后选择该行,使用更正价格同步关联金额':'已有到货或入库,请先按流程退回后修改':String(owner.displayCell(row,column.field) ?? ''))" @focusin="active&&owner.rememberCell(index,column.field)" @focusout="commitDraft" @copy="owner.copyGridEvent?.($event)" @paste="owner.paste($event,index,column.field)" @keydown.esc.capture.stop="owner.navigate($event,index,column.field)" @keydown="owner.navigate($event,index,column.field)">
<input v-if="!active && owner.isGridTypingCell?.(row,column.field)" class="sheet-keyboard-input" :aria-label="'输入第'+(index+1)+'行 '+column.label" autocomplete="off" @compositionstart="composing=true" @compositionend="compositionEnd" @input="typeInput" />
<template v-if="!owner.editableCell(row,column.field) || !active">
<a v-if="owner.readonly(row) && column.field==='purchaseLink' && owner.linkUrl(row.purchaseLink)" class="sheet-link" :href="owner.linkUrl(row.purchaseLink)" :title="row.purchaseLink" target="_blank" rel="noopener noreferrer" @click.stop>{{ row.purchaseLink }}</a>
<span v-else class="sheet-value" :title="String(owner.displayCell(row,column.field))">{{ owner.displayCell(row,column.field) }}</span>
<a v-if="owner.readonly(row) && column.field==='purchaseLink' && owner.linkUrl(row.purchaseLink)" class="sheet-link" :href="owner.linkUrl(row.purchaseLink)" :title="row.purchaseLink" target="_blank" rel="noopener noreferrer" @click.stop>{{ purchaseLinkLabel(row.purchaseLink) }}</a>
<span v-else class="sheet-value" :title="String(owner.displayCell(row,column.field))">{{ column.field==='purchaseLink' && row.purchaseLink ? purchaseLinkLabel(row.purchaseLink) : owner.displayCell(row,column.field) }}</span>
</template>
<el-select v-else-if="column.field==='projectId'" v-model="row.projectId" filterable :disabled="owner.saving || owner.fieldLocked(row,column.field) || !!(row.id && row.productionTaskId)" @visible-change="owner.menu(row,column.field,$event)" @change="owner.projectChanged(row)"><el-option v-for="p in owner.menuOpen(row,column.field)?owner.projects:owner.projects.filter(p=>String(p.id)===String(row.projectId))" :key="p.id" :value="p.id" :label="p.projectName" /></el-select>
<el-select v-else-if="column.field==='expenseCategoryId'" v-model="row.expenseCategoryId" filterable :disabled="owner.saving || owner.fieldLocked(row,column.field)" @visible-change="owner.menu(row,column.field,$event)"><el-option v-for="c in owner.menuOpen(row,column.field)?owner.categories:owner.categories.filter(c=>String(c.id)===String(row.expenseCategoryId))" :key="c.id" :value="c.id" :label="c.categoryName" /></el-select>
<el-select v-else-if="column.field==='materialName'" :model-value="row.productId?'@item:'+row.productId:row.materialName" filterable remote :remote-method="owner.searchNames" :loading="owner.nameLoading" allow-create default-first-option :disabled="owner.saving || owner.fieldLocked(row,column.field)" @visible-change="owner.nameMenu(row,$event)" @change="owner.nameChanged(row,$event)"><el-option v-for="item in nameOptions" :key="item.id||item.productName" :value="item.id?'@item:'+item.id:item.productName" :label="item.productName"><span :title="owner.itemLabel(item)">{{ owner.itemLabel(item) }}</span></el-option></el-select>
<el-select v-else-if="column.field==='materialBrand'" v-model="row.materialBrand" filterable allow-create clearable default-first-option :disabled="owner.saving || owner.fieldLocked(row,column.field)" @visible-change="owner.menu(row,column.field,$event)" @change="owner.brandChanged(row)"><el-option v-for="brand in owner.menuOpen(row,column.field)?owner.brands(row):(row.materialBrand?[row.materialBrand]:[])" :key="brand" :value="brand" :label="brand" /></el-select>
<el-select v-else-if="column.field==='materialParams'" :model-value="row.materialParams" filterable allow-create clearable default-first-option :disabled="owner.saving || owner.fieldLocked(row,column.field)" @visible-change="owner.menu(row,column.field,$event)" @change="owner.specChanged(row,$event)"><el-option v-for="item in owner.menuOpen(row,column.field)?owner.specs(row):owner.currentSpec(row)" :key="item.id" :value="'@item:'+item.id" :label="[item.spec || '无规格', item.brand, item.unit].filter(Boolean).join(' / ')" /></el-select>
<el-autocomplete v-else-if="column.field==='materialName'" v-model="nameDraft" :fetch-suggestions="nameSuggestions" :trigger-on-focus="true" :disabled="owner.saving || owner.fieldLocked(row,column.field)" @select="selectName"><template #default="{ item }"><span :title="owner.itemLabel(item)">{{ owner.itemLabel(item) }}</span></template></el-autocomplete>
<el-autocomplete v-else-if="column.field==='materialBrand'" v-model="brandDraft" :fetch-suggestions="brandSuggestions" :trigger-on-focus="true" clearable :disabled="owner.saving || owner.fieldLocked(row,column.field)" @select="selectBrand" />
<el-autocomplete v-else-if="column.field==='materialParams'" v-model="specDraft" :fetch-suggestions="specSuggestions" :trigger-on-focus="true" clearable :disabled="owner.saving || owner.fieldLocked(row,column.field)" @select="selectSpec"><template #default="{ item }"><span>{{ item.value }}</span></template></el-autocomplete>
<span v-else-if="column.field==='unit' && row.productId" class="sheet-value">{{ row.unit || '档案缺单位' }}</span>
<el-select v-else-if="column.field==='unit'" v-model="row.unit" filterable :disabled="owner.saving || owner.fieldLocked(row,column.field)" @visible-change="owner.menu(row,column.field,$event)"><el-option v-for="unit in owner.menuOpen(row,column.field)?owner.rowUnits(row):(row.unit?[row.unit]:[])" :key="unit" :value="unit" :label="unit" /></el-select>
<el-input-number v-else-if="column.field==='quantity'" v-model="row.quantity" :precision="4" :min="Math.max(0.0001,Number(row.acceptedQuantity||0)+Number(row.pendingArrivalQuantity||0))" :controls="false" :disabled="owner.saving || owner.fieldLocked(row,column.field)" />
@ -24,12 +24,42 @@
</div>
</template>
<script setup>
import { computed, ref, watch } from 'vue'
import { ref, watch } from 'vue'
import { purchaseLinkLabel } from '@/utils/purchase-link-label'
const props=defineProps({row:Object,column:Object,index:Number,owner:Object,active:Boolean})
const composing=ref(false)
const specDraft=ref(props.row?.materialParams || '')
const nameDraft=ref(props.row?.materialName || ''),brandDraft=ref(props.row?.materialBrand || '')
let nameSequence=0,specSequence=0
function typeInput(event){if(composing.value||event.isComposing)return;const value=event.target.value;event.target.value='';if(value)props.owner.typeGridCell(props.row,props.column.field,value)}
function compositionEnd(event){composing.value=false;typeInput(event)}
const nameOptions=computed(()=>props.column.field==='materialName'?props.owner.nameChoices(props.row):[])
async function nameSuggestions(query, callback){
const seq=++nameSequence
try{await props.owner.searchNames(query)}catch{if(seq===nameSequence)callback([]);return}
if(seq!==nameSequence)return
callback(props.owner.nameChoices(props.row,true).filter(item=>String(item.productName||'').toLocaleLowerCase().includes(String(query||'').toLocaleLowerCase())).map(item=>({...item,value:item.productName})))
}
function brandSuggestions(query, callback){const term=String(query||'').toLocaleLowerCase();callback(props.owner.brands(props.row).filter(brand=>String(brand).toLocaleLowerCase().includes(term)).map(brand=>({value:brand})))}
function commitName(){if(nameDraft.value!==String(props.row.materialName||''))void props.owner.nameChanged(props.row,nameDraft.value)}
function selectName(item){nameDraft.value=item.productName || '';void props.owner.nameChanged(props.row,item.id?'@item:'+item.id:item.productName)}
function commitBrand(){if(brandDraft.value!==String(props.row.materialBrand||'')){props.row.materialBrand=brandDraft.value;props.owner.brandChanged(props.row)}}
function selectBrand(item){brandDraft.value=item.value;commitBrand()}
async function specSuggestions(query, callback){
const seq=++specSequence,name=props.row.materialName
// A temporary lookup failure should not hide variants already in the local cache.
try{if(name)await props.owner.loadName(name)}catch{}
if(seq!==specSequence||name!==props.row.materialName)return
// On opening, show the available variants while retaining the editable value.
const term=String(query||'')===String(props.row.materialParams||'')?'':String(query||'').toLocaleLowerCase()
callback(props.owner.specs(props.row).filter(item=>!term||String(item.spec||'').toLocaleLowerCase().includes(term)).map(item=>({...item,value:[item.spec || '无规格',item.brand,item.unit].filter(Boolean).join(' / ')})))
}
function commitSpec(){props.owner.specChanged(props.row,specDraft.value)}
function selectSpec(item){specDraft.value=item.spec || '';props.owner.specChanged(props.row,'@item:'+item.id)}
// Element Plus defers its autocomplete blur event with a timer. Native focusout
// must commit first so save/undo/escape can flush or restore the cell atomically.
function commitDraft(event){if(!props.active || !event.target?.matches('input'))return;if(props.column.field==='materialName')commitName();else if(props.column.field==='materialBrand')commitBrand();else if(props.column.field==='materialParams')commitSpec()}
watch(()=>props.active, active=>{if(active && props.column.field==='materialParams')specDraft.value=props.row.materialParams || ''},{flush:'sync'})
watch(()=>props.active, active=>{if(active && props.column.field==='materialName')nameDraft.value=props.row.materialName || '';if(active && props.column.field==='materialBrand')brandDraft.value=props.row.materialBrand || ''},{flush:'sync'})
watch(()=>props.active,active=>{if(active&&props.column.field==='materialName')props.owner._openedName=null},{flush:'sync'})
</script>
<style scoped>

View File

@ -38,17 +38,17 @@ import GroupDialog from './GroupDialog.vue'
import {projectOptions} from '@/api/project/project'
import {amountDisplay,loadAmountDisplay} from '@/utils/amount-display'
export default {
props:{projectId:Number,unbatched:Boolean,embedded:Boolean},
props:{projectId:Number,unbatched:Boolean,embedded:Boolean,onlyMine:Boolean},
computed:{canViewQuotes(){return this.$auth.hasPermiOr(['warehouse:purchase:manage'])},compactAmounts(){return this.canViewQuotes&&amountDisplay.enabled}},
components:{GroupDialog,SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker'))},
data(){return {query:{pageNum:1,pageSize:20,materialName:'',purchaseBatchNo:'',projectId:this.projectId,supplierId:null,productionTaskId:Number(this.$route.query.productionTaskId)||undefined},rows:[],projects:[],total:0,selected:[],loading:false,saving:false}},
watch:{unbatched(){this.clearSelection();this.search()},projectId(id){this.query.projectId=id;this.clearSelection();this.search()},'$route.fullPath'(){if(!this.embedded){this.applyRoute();this.clearSelection();this.search()}}},
watch:{onlyMine(){this.clearSelection();this.rows=[];this.total=0;this.search()},unbatched(){this.clearSelection();this.search()},projectId(id){this.query.projectId=id;this.clearSelection();this.search()},'$route.fullPath'(){if(!this.embedded){this.applyRoute();this.clearSelection();this.search()}}},
created(){projectOptions('',true).then(r=>this.projects=r.data||[]);this.applyRoute();this.load()},
methods:{
canPrepare(r){return !r.purchaseBatchId&&!r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5&&Number(r.acceptedQuantity||0)<=0&&Number(r.pendingArrivalQuantity||0)<=0},
applyRoute(){if(this.embedded)return;this.query.productionTaskId=Number(this.$route.query.productionTaskId)||undefined;this.query.materialName=this.$route.query.materialName||'';this.query.requestNo=this.$route.query.requestNo||undefined},
selectionChanged(rows){this.selected=rows},clearSelection(){if(this.$refs.table)this.$refs.table.clearSelection();this.selected=[]},
async load(){const seq=this._sequence=(this._sequence||0)+1;this.loading=true;try{await loadAmountDisplay();const r=await listPurchase({...this.query,unbatched:this.unbatched});if(seq===this._sequence){this.rows=r.rows||[];this.total=r.total||0}}finally{if(seq===this._sequence)this.loading=false}},
async load(){const seq=this._sequence=(this._sequence||0)+1;this.loading=true;try{await loadAmountDisplay();const r=await listPurchase({...this.query,unbatched:this.unbatched,onlyMine:this.onlyMine});if(seq===this._sequence){this.rows=r.rows||[];this.total=r.total||0}}finally{if(seq===this._sequence)this.loading=false}},
search(){this.query.pageNum=1;this.load()},
reset(){this.clearSelection();this.query={pageNum:1,pageSize:20,projectId:this.projectId};this.load()},
open(row){if(row.purchaseBatchId)this.$emit('open',row);else if(this.canPrepare(row))this.$emit('edit',[row])},

View File

@ -35,6 +35,16 @@
</div>
<template #footer><el-button :disabled="busy" @click="emit('update:modelValue',false)">关闭</el-button><el-button v-if="results.length && canEdit" type="primary" :disabled="busy || disabled || !summary.ready || summary.errors>0 && !allowPartial" @click="apply">回填有效报价({{ summary.ready }} 项)</el-button></template>
</el-dialog>
<el-dialog v-model="exportOptionsOpen" title="选择询价单导出列" width="min(620px,94vw)" append-to-body :close-on-click-modal="!exporting" :close-on-press-escape="!exporting" :show-close="!exporting">
<div class="inquiry-options">
<div class="inquiry-options__top"><span>选择需要提供给供应商的内容</span><span><el-button link type="primary" @click="selectAllColumns">全选</el-button><el-button link type="primary" @click="resetColumns">恢复默认</el-button></span></div>
<el-checkbox-group v-model="selectedColumns" class="inquiry-options__grid">
<el-checkbox v-for="column in availableColumns" :key="column.key" :value="column.key" :disabled="column.required">{{ column.label }}<span v-if="column.required" class="inquiry-options__required">(必选)</span></el-checkbox>
</el-checkbox-group>
<p class="supplier-quotation__hint">报价单价用于供应商填写,必须保留。为支持报价回填,必要的物品匹配信息会保存在文件的隐藏列中;请勿将文件视为不含这些信息。</p>
</div>
<template #footer><el-button :disabled="exporting" @click="exportOptionsOpen=false">取消</el-button><el-button type="primary" :loading="exporting" @click="downloadInquiry">导出询价单</el-button></template>
</el-dialog>
</template>
<script setup>
@ -46,24 +56,34 @@ import { previewSupplierQuotes } from '@/api/warehouse/purchase'
import { supplierInquiryRows, quotationReady, quotationSummary, quotationUploadError } from '@/utils/supplier-quotation'
import {amountDisplay} from '@/utils/amount-display'
import {visibleAmountRow} from '@/utils/purchase-reference-amounts'
const props=defineProps({modelValue:Boolean,sheet:Object,supplierName:String,disabled:Boolean,canEdit:Boolean,canExport:Boolean})
const props=defineProps({modelValue:Boolean,sheet:Object,supplierName:String,disabled:Boolean,canEdit:Boolean,canExport:Boolean,compactAmounts:Boolean})
const emit=defineEmits(['update:modelValue','apply','busy'])
const results=ref([]),fileName=ref(''),exporting=ref(false),uploading=ref(false),allowPartial=ref(false)
const exportOptionsOpen=ref(false),selectedColumns=ref([])
const columns=[{key:'name',label:'物品名称'},{key:'spec',label:'规格型号'},{key:'brand',label:'品牌'},{key:'unit',label:'单位'},{key:'quantity',label:'采购数量'},{key:'quoteUnitPrice',label:'报价单价',required:true},{key:'quoteAmount',label:'报价金额'},{key:'actualUnitPrice',label:'实际单价',actual:true},{key:'actualAmount',label:'实际金额',actual:true},{key:'link',label:'采购链接'},{key:'remark',label:'备注'}]
const availableColumns=computed(()=>columns.filter(column=>!column.actual||!props.compactAmounts))
function selectAllColumns(){selectedColumns.value=availableColumns.value.map(column=>column.key)}
function resetColumns(){selectAllColumns()}
const items=computed(()=>supplierInquiryRows(props.sheet?.rows?.filter(row=>visibleAmountRow(row,amountDisplay.enabled)))),eligibleLines=computed(()=>items.value.reduce((sum,item)=>sum+item.rowCount,0))
const summary=computed(()=>quotationSummary(results.value)),busy=computed(()=>exporting.value||uploading.value)
let previewBatch,previewVersion,disposed=false,controller
let previewBatch,previewVersion,exportBatch,exportVersion,disposed=false,controller
watch(busy,value=>emit('busy',value))
watch(()=>props.modelValue,value=>{if(value){results.value=[];fileName.value='';allowPartial.value=false}})
function beforeUpload(file){const message=quotationUploadError(file);if(message){ElMessage.warning(message);return false}return true}
async function exportInquiry(){
function exportInquiry(){
if(!props.canExport || props.disabled || busy.value || !props.sheet?.batch?.id)return
exportBatch=props.sheet.batch.id;exportVersion=props.sheet.version;resetColumns();exportOptionsOpen.value=true
}
async function downloadInquiry(){
if(!props.canExport || props.disabled || busy.value || !props.sheet?.batch?.id)return
if(props.sheet.batch.id!==exportBatch||props.sheet.version!==exportVersion){exportOptionsOpen.value=false;ElMessage.warning('采购清单已变化,请重新选择导出列');return}
const {id,batchNo}=props.sheet.batch,version=props.sheet.version;exporting.value=true;controller=new AbortController()
try{
const blob=await request({url:`/warehouse/purchase/sheet/${id}/inquiry-export`,method:'post',params:{version},responseType:'blob',signal:controller.signal})
const blob=await request({url:`/warehouse/purchase/sheet/${id}/inquiry-export`,method:'post',params:{version,selectedColumns:selectedColumns.value.join(',')},responseType:'blob',signal:controller.signal})
if(disposed)return
if(!(blob instanceof Blob)||blob.type.includes('json')){let message='询价单导出失败,请刷新后重试';try{message=JSON.parse(await blob.text()).msg||message}catch{}throw new Error(message)}
const signature=new Uint8Array(await blob.slice(0,4).arrayBuffer());if(signature[0]!==0x50||signature[1]!==0x4b)throw new Error('收到的文件不是有效询价单,请刷新后重试')
saveAs(blob,`供应商询价单_${batchNo}.xlsx`)
saveAs(blob,`供应商询价单_${batchNo}.xlsx`);exportOptionsOpen.value=false
}catch(error){if(!disposed&&error.code!=='ERR_CANCELED')ElMessage.error(error.message||'询价单导出失败')}
finally{exporting.value=false}
}
@ -83,6 +103,7 @@ defineExpose({exportInquiry})
</script>
<style scoped>
.inquiry-options__top{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px}.inquiry-options__grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.inquiry-options__grid :deep(.el-checkbox){margin-right:0}.inquiry-options__required{font-size:12px;color:var(--el-text-color-secondary)}@media(max-width:600px){.inquiry-options__grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
.supplier-quotation__item{display:flex;flex-direction:column;gap:3px;line-height:1.5;overflow-wrap:anywhere}.supplier-quotation__item>span{font-size:12px;color:var(--el-text-color-secondary)}
.supplier-quotation__context{display:flex;gap:12px;flex-wrap:wrap;color:var(--el-text-color-regular);padding:12px 14px;background:var(--el-fill-color-light);border-radius:6px}.supplier-quotation__steps{display:flex;flex-wrap:wrap;gap:16px 32px;margin:18px 0 10px;padding-left:22px;font-weight:500}.supplier-quotation__hint{font-size:12px;line-height:1.7;color:var(--el-text-color-secondary);margin:10px 0}.supplier-quotation__tools{display:flex;align-items:center;flex-wrap:wrap;gap:10px;margin:16px 0}.supplier-quotation__tools>span{font-size:12px;color:var(--el-text-color-secondary);overflow-wrap:anywhere}.supplier-quotation__summary{margin:12px 0;font-size:13px}.supplier-quotation__error{color:var(--el-color-danger)}.supplier-quotation__partial{margin-top:12px;white-space:normal;height:auto;line-height:1.6}.supplier-quotation :deep(.quotation-invalid){--el-table-tr-bg-color:var(--el-color-danger-light-9)}
</style>

View File

@ -2,9 +2,9 @@
<div class="purchase-sheet" tabindex="-1" v-loading="loading||creating" @keydown.capture="editorShortcut">
<el-alert v-if="draftError" type="error" :closable="false" show-icon :title="draftError"><el-button link type="primary" @click="persistDraft">重试本机保存</el-button></el-alert>
<template v-if="!sheet">
<div class="sheet-list-tabs"><el-radio-group v-model="viewMode" size="small" class="mb8" @change="changeView"><el-radio-button value="batches">按批次</el-radio-button><el-radio-button value="details">明细搜索</el-radio-button><el-radio-button value="unbatched">待组批</el-radio-button></el-radio-group><el-button v-if="$can(['warehouse:purchase:import','warehouse:purchase:add','warehouse:purchase:export','warehouse:purchase:manage'])" size="small" icon="el-icon-download" @click="exportTemplate">导出模板</el-button><el-button v-if="$can(['warehouse:purchase:import','warehouse:purchase:manage'])" size="small" icon="el-icon-upload" @click="$refs.purchaseImport.open()">导入采购</el-button><el-dropdown v-if="drafts.length" trigger="click" @command="restoreDraft"><el-button size="small">恢复草稿({{ drafts.length }})<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu ><el-dropdown-item v-for="draft in drafts" :key="draft.key" :command="draft.key">{{ draft.title }}</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div>
<purchase-lookup v-if="viewMode!=='batches'" ref="lookup" :project-id="projectId||query.projectId" :embedded="embedded" :unbatched="viewMode==='unbatched'" @open="openLookupRow" @prepared="openPrepared" @create="create(true)" @edit="openUnbatched"/>
<template v-if="viewMode==='batches'">
<div class="sheet-list-tabs"><el-radio-group v-model="viewMode" size="small" class="mb8" @change="changeView"><el-radio-button value="batches">按批次</el-radio-button><el-radio-button value="details">明细搜索</el-radio-button><el-radio-button value="unbatched">待组批</el-radio-button></el-radio-group><el-tooltip content="筛选我创建的采购明细;批次列表筛出包含本人明细的批次" placement="top"><el-checkbox v-model="onlyMine" @change="changeOnlyMine">只看我的</el-checkbox></el-tooltip><el-button v-if="$can(['warehouse:purchase:import','warehouse:purchase:add','warehouse:purchase:export','warehouse:purchase:manage'])" size="small" icon="el-icon-download" @click="exportTemplate">导出模板</el-button><el-button v-if="$can(['warehouse:purchase:import','warehouse:purchase:manage'])" size="small" icon="el-icon-upload" @click="$refs.purchaseImport.open()">导入采购</el-button><el-dropdown v-if="drafts.length" trigger="click" @command="restoreDraft"><el-button size="small">恢复草稿({{ drafts.length }})<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu ><el-dropdown-item v-for="draft in drafts" :key="draft.key" :command="draft.key">{{ draft.title }}</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div>
<purchase-lookup v-if="viewMode!=='batches'" :only-mine="onlyMine" ref="lookup" :project-id="projectId||query.projectId" :embedded="embedded" :unbatched="viewMode==='unbatched'" @open="openLookupRow" @prepared="openPrepared" @create="create(true)" @edit="openUnbatched"/>
<template v-if="viewMode==='batches'"><div v-if="onlyMine" class="mine-batch-hint">只筛出包含我创建明细的批次;数量、金额及打开后的清单均为整批数据</div>
<el-form ref="query" :model="query" inline size="small" label-width="68px">
<query-toolbar :active-count="$filterCount([query.materialName,query.progress,queryDates])">
<el-form-item label="批次" prop="keyword"><el-input v-model="query.keyword" clearable placeholder="编号或名称" @keyup.enter="search" /></el-form-item>
@ -139,7 +139,7 @@
</el-alert>
</template>
</excel-import-dialog>
<supplier-quotation ref="quotation" v-model="quoteImportOpen" :sheet="sheet" :supplier-name="supplierName" :disabled="saving || dirty" :can-edit="!!canEdit&&canViewQuotes" :can-export="canExportInquiry" @apply="applyQuotes" @busy="quoteLoading=$event"/>
<supplier-quotation ref="quotation" v-model="quoteImportOpen" :sheet="sheet" :supplier-name="supplierName" :disabled="saving || dirty" :compact-amounts="compactAmounts" :can-edit="!!canEdit&&canViewQuotes" :can-export="canExportInquiry" @apply="applyQuotes" @busy="quoteLoading=$event"/>
<el-dialog :close-on-press-escape="!saving" :close-on-click-modal="!saving" :show-close="!saving" title="转采购批次" v-model="moveOpen" width="min(580px,96vw)" append-to-body>
<p>已选 {{ selected.length }} 项 · 只调整批次归组,不改变数量、报价、确认状态及到货/入库记录。</p>
<el-radio-group v-model="moveMode" :disabled="saving||moveAttempted"><el-radio-button value="existing">转入已有批次</el-radio-button><el-radio-button value="new">新建批次并转入</el-radio-button></el-radio-group>
@ -181,6 +181,7 @@ import { createPurchaseDraft } from '@/utils/purchase-sheet-create'
import { purchaseGridRange, selectedGridText, writeClipboardText } from '@/utils/purchase-grid-clipboard'
import { clearPurchaseGrid } from '@/utils/purchase-grid-edit'
import {purchaseSelectionStats} from '@/utils/purchase-selection-stats'
import {continuedPurchasePaste,purchasePasteMarker} from '@/utils/purchase-paste-continuation'
import {buildInsertedRows,clonePurchaseRows,canAutoAppend} from '@/utils/purchase-row-operations'
import PastePreview from './PastePreview.vue'
import {amountDisplay,loadAmountDisplay} from '@/utils/amount-display'
@ -197,7 +198,7 @@ export default {
setup(){const tableStage=ref(null),{height:gridHeight}=useContentHeight(tableStage),app=useAppStore();return {tableStage,gridHeight,pasteIssues:ref([]),cellSelection:ref(null),density:computed(()=>app.size),changedKeys:ref(new Set()),headerDirty:ref(false),structureDirty:ref(false),virtualStart:ref(0),virtualRowHeight:ref(40)}},
name:'PurchaseBatchSheet', props:{projectId:Number,embedded:Boolean}, dicts:['wms_item_category'],
components:{ArrivalPhotos:defineAsyncComponent(()=>import('@/components/ArrivalPhotos')),PurchaseCell,PriceCorrection,HistoryCorrection,PurchaseDocuments,SupplierQuotation,PastePreview,PurchaseLookup:defineAsyncComponent(()=>import('./Lookup')),SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),BatchArrival:defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')),CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')),ExcelImportDialog:defineAsyncComponent(()=>import('@/components/ExcelImportDialog'))},
data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,viewMode:'batches',loading:true,creating:false,saving:false,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,batches:[],total:0,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,onlyMine:false,viewMode:'batches',loading:true,creating:false,saving:false,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,batches:[],total:0,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
computed:{
documentKinds(){return purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||this.canViewQuotes)},
canViewQuotes(){const user=this.$store.getters;return canViewPurchaseQuotes(user.userId,user.roles)},
@ -296,6 +297,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
},
async applyRoute(){if(this.embedded||this.$route.path!=='/procurement/details')return;const stamp=this.$route.fullPath,identity=purchaseRouteStamp(this.$route);if(stamp===this._routeStamp)return;this._routeStamp=stamp;if(identity===this._routeIdentity)return;this._routeIdentity=identity;this.query.projectId=Number(this.$route.query.projectId)||this.projectId;this.query.progress=this.$route.query.progress||undefined;this.query.materialName=this.$route.query.materialName||undefined;this.viewMode=this.$route.query.view|| (this.$route.query.legacy==='1'?'unbatched':'batches');this.query.pageNum=1;if(this.$route.query.purchaseBatchId)await this.openBatch({id:Number(this.$route.query.purchaseBatchId)});else{this._sheetSequence=(this._sheetSequence||0)+1;this.sheet=null;this.editing=false;await this.loadBatches()}},
changeView(){if(this.viewMode==='batches')this.loadBatches();this.layout()},
changeOnlyMine(){if(this.viewMode==='batches'){this.batches=[];this.total=0;this.query.pageNum=1;this.loadBatches()}},
async openLookupRow(row){await this.openBatch({id:row.purchaseBatchId});if(!this.sheet||String(this.sheet.batch.id)!==String(row.purchaseBatchId))return;this.rowFilter=row.materialName;await this.$nextTick();const target=this.sheet.rows.find(r=>String(r.id)===String(row.id));if(target){await this.revealRow(target);const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(target)+'"]');cell?.scrollIntoView({block:'nearest',inline:'nearest'})}},
layout(){this.$nextTick(()=>{if(this.$refs.grid){this.$refs.grid.doLayout();const row=this.$refs.grid.$el.querySelector('.el-table__body tbody tr');if(row)this.virtualRowHeight=row.getBoundingClientRect().height||40}if(this.$refs.batches)this.$refs.batches.doLayout()})},
scrollGrid({scrollTop}){if(this.virtualized)this.virtualStart=Math.min(Math.max(0,this.visibleRows.length-this.virtualCount),Math.max(0,Math.floor(scrollTop/this.virtualRowHeight)-6))},
@ -371,7 +373,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
async focusError(error){if(!error)return;if(error.field==='projectId'&&!this.sheet.unbatched&&!this.batchProject.mixed){await this.$nextTick();this.$refs.batchProjectSelect?.focus();return}this.rowFilter='';if(['loanId','purchasePurpose','productionTaskId','remark'].includes(error.field))this.extras=true;await this.$nextTick();const row=this.sheet.rows.find(r=>r._key===error.rowKey);if(row)await this.activateCell(row,error.field)},
editableCell(row,field){if(field==='actualUnitPrice')return this.isEditing&&!this.saving&&!this.compactAmounts;return !this.saving&&!this.readonly(row)&&!this.fieldLocked(row,field)&&!(row.id&&field==='productionTaskId')&&!(row.id&&row.productionTaskId&&field==='projectId')&&!(row.productId&&field==='unit')&&!(field==='category'&&!this.canEditCategory(row))&&!(field==='loanId'&&row.purchasePurpose!=='REPAY')},
isGridSelected(row,field){const range=this.cellRange;if(!range)return false;const r=this.visibleRowIndexMap.get(row._key),c=this.columns.findIndex(column=>column.field===field);return r>=range.top&&r<=range.bottom&&c>=range.left&&c<=range.right},
focusGridCell(row,field){if(this._gridDragging)return;if(!this.cellSelection)this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}}},
focusGridCell(row,field){if(this._gridDragging)return;if(this._pasteContinuation&&(this._pasteContinuation.key!==row._key||this._pasteContinuation.field!==field))this._pasteContinuation=null;if(!this.cellSelection)this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}}},
startCellSelection(row,field,event){if(event.button!==0||this.saving)return;if(this.editCell===row._key+'|'+field&&!event.shiftKey&&event.target.closest('input,textarea,.el-select,.el-cascader'))return;event.preventDefault();document.activeElement?.blur?.();this._editor?.flush();this.editCell=null;this.activeMenu=null;this.nameMenuRow=null;const point={key:row._key,field};this.cellSelection={anchor:event.shiftKey&&this.cellSelection?this.cellSelection.anchor:point,focus:point};this._gridDragging=true;window.addEventListener('mouseup',this.endCellSelection,{once:true});event.currentTarget.focus({preventScroll:true})},
extendCellSelection(row,field,event){if(!this._gridDragging||event.buttons!==1||!this.cellSelection)return;this.cellSelection={...this.cellSelection,focus:{key:row._key,field}}},
endCellSelection(){const focus=this._gridDragging&&document.activeElement?.closest?.('.sheet-cell');this._gridDragging=false;window.removeEventListener('mouseup',this.endCellSelection);if(focus&&!this.editCell)this.$nextTick(()=>this.focusSelectedCell())},
@ -383,14 +385,14 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
selectionText(){return selectedGridText(this.cellRange,this.visibleRows,this.columns,(row,field)=>this.displayCell(row,field)==='—'?'':this.displayCell(row,field))},
copyGridEvent(event){if(!this.cellRange)return;const target=event.target,one=this.cellRange.top===this.cellRange.bottom&&this.cellRange.left===this.cellRange.right;if(one&&target.matches('input,textarea')&&target.selectionStart!==target.selectionEnd)return;event.preventDefault();event.clipboardData?.setData('text/plain',this.selectionText())},
async copySelection(){if(!this.cellRange||this.saving)return;await this.finishCellEdit();try{await writeClipboardText(this.selectionText());this.$modal.msgSuccess('选区已复制,可粘贴到 Excel')}catch(error){this.$modal.msgWarning(error.message)}},
async activateCell(row,field,openDropdown=false,event){if(!this.editableCell(row,field))return;await this.revealRow(row);const key=row._key+'|'+field,wasActive=this.editCell===key;this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}};this.rememberCell(this.originalIndex(row),field);this.editCell=key;await this.$nextTick();const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]');if(!cell)return;cell.scrollIntoView({block:'nearest',inline:'nearest'});const input=cell.querySelector('input:not([disabled]),textarea:not([disabled])');if(input&&!cell.contains(document.activeElement)){input.focus({preventScroll:true});input.select()}if(openDropdown&&!wasActive&&input?.getAttribute('aria-expanded')!=='true')cell.querySelector('.el-select__wrapper')?.click()},
async activateCell(row,field,openDropdown=false,event){if(!this.editableCell(row,field))return;await this.revealRow(row);const key=row._key+'|'+field,wasActive=this.editCell===key;this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}};this.rememberCell(this.originalIndex(row),field);this.editCell=key;await this.$nextTick();const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]');if(!cell)return;cell.scrollIntoView({block:'nearest',inline:'nearest'});const input=cell.querySelector('input:not([disabled]),textarea:not([disabled])');if(input&&!cell.contains(document.activeElement)){input.focus({preventScroll:true});if(['materialName','materialBrand','materialParams','purchaseLink','remark'].includes(field))input.setSelectionRange?.(input.value.length,input.value.length);else input.select()}if(openDropdown&&!wasActive&&input?.getAttribute('aria-expanded')!=='true')cell.querySelector('.el-select__wrapper')?.click()},
originalIndex(row){return this.rowIndexMap.get(row._key)??-1},
fieldLocked(row,field){if(field==='finalUnitPrice'&&!this.canViewQuotes)return true;const received=Number(row.receivedQuantity||0)>0,arrived=received||Number(row.acceptedQuantity||0)>0||Number(row.pendingArrivalQuantity||0)>0;return (received&&['projectId','expenseCategoryId','purchasePurpose','loanId'].includes(field))||(arrived&&['materialName','materialBrand','materialParams','unit','category','finalUnitPrice'].includes(field))},
mergeItems(items){const map=new Map(this.items.map(r=>[String(r.id),r]));items.forEach(r=>{const old=map.get(String(r.id))||{};map.set(String(r.id),{...old,...r,unit:r.unit||old.unit,category:r.category||old.category})});this.items=[...map.values()]},
async searchNames(keyword){const seq=this._nameSequence=(this._nameSequence||0)+1;this.nameLoading=true;try{const r=await purchaseSheetOptions({keyword});if(seq===this._nameSequence){this.mergeItems(r.data.items||[]);this.nameOptions=r.data.items||[]}}finally{if(seq===this._nameSequence)this.nameLoading=false}},
async loadName(name){const r=await purchaseSheetOptions({name});this.mergeItems(r.data.items||[])},
async references(){const [options,projects,categories]=await Promise.all([purchaseSheetOptions(),projectOptions('',true),categoryOptions(),loadAmountDisplay()]);this.mergeItems(options.data.items||[]);this.units=(options.data.units||[]).filter(u=>u.status==='0').map(u=>u.dictLabel);this.plans=options.data.plans||[];this.projects=projects.data||[];this.categories=categories.data||[];if(!this.commonCategory)this.commonCategory=(this.categories.find(c=>c.categoryCode==='MATERIAL')||this.categories[0]||{}).id},
async loadBatches(){await loadAmountDisplay();const query={...this.query,beginDate:(this.queryDates||[])[0],endDate:(this.queryDates||[])[1]};return runLatest(this,'batches',()=>listPurchaseBatch(query),{start:()=>{this.loading=true},success:result=>{this.batches=result.rows||[];this.total=result.total||0},error:()=>{this.batches=[];this.total=0},finish:()=>{this.loading=false}})},
async loadBatches(){await loadAmountDisplay();const query={...this.query,onlyMine:this.onlyMine,beginDate:(this.queryDates||[])[0],endDate:(this.queryDates||[])[1]};return runLatest(this,'batches',()=>listPurchaseBatch(query),{start:()=>{this.loading=true},success:result=>{this.batches=result.rows||[];this.total=result.total||0},error:()=>{this.batches=[];this.total=0},finish:()=>{this.loading=false}})},
search(){this.query.pageNum=1;this.loadBatches()},resetQuery(){this.resetForm('query');this.query.projectId=this.projectId;this.queryDates=[];this.search()},
emptyRow(){return {_key:'new-'+Date.now()+'-'+Math.random(),id:null,projectId:this.projectId||(this.sheet&&!this.sheet.unbatched?this.batchProject.value:this.commonProject)||null,expenseCategoryId:this.commonCategory||null,materialName:'',materialBrand:'',materialParams:'',productId:null,productCode:null,unit:'',category:'',quantity:1,finalUnitPrice:null,actualUnitPrice:null,purchaseLink:'',remark:'',purchasePurpose:'SELF',productionTaskId:null,purchaseStatus:0}},
async create(unbatched=false){return createPurchaseDraft(this,unbatched)},
@ -419,7 +421,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
// Mount the full catalog only for the open cell, not once per row (and fixed-pane copy).
nameMenu(row,visible){if(visible){this.nameMenuRow=row._key;if(this._openedName!==row._key){this._openedName=row._key;this.searchNames(row.materialName||'')}}else if(this.nameMenuRow===row._key)this.nameMenuRow=null},
itemLabel(item){return [item.productName,item.brand||'无品牌',item.spec||'无规格',item.unit].filter(Boolean).join(' / ')},
nameChoices(row){return purchaseNameChoices(row,this.nameMenuRow===row._key?this.nameItems:[])},
nameChoices(row,includeSearchResults=false){return purchaseNameChoices(row,includeSearchResults||this.nameMenuRow===row._key?this.nameItems:[])},
openPrepared(sheet){this.viewMode='batches';this.install(sheet)},
menu(row,field,visible){const key=row._key+'|'+field;if(visible){this._menu=key;if(field==='productionTaskId')this.searchPlans(row,'')}else if(this._menu===key)this._menu=null;this.activeMenu=this._menu},
menuOpen(row,field){return this.activeMenu===row._key+'|'+field},
@ -445,9 +447,18 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
displayCell(row,field){if(field==='projectId')return this.projectName(row.projectId);if(field==='expenseCategoryId')return this.categories.find(c=>String(c.id)===String(row[field]))?.categoryName || row.expenseCategoryName || '—';if(field==='productionTaskId')return this.plans.find(p=>String(p.id)===String(row[field]))?.taskNo || row.productionTaskNo || '—';return row[field]==null||row[field]===''?'—':row[field]},
async paste(event,index,field){
const text=event.clipboardData?.getData('text/plain');if(!text||!this.isEditing||this.saving||this.pasteApplying)return
const matrix=text.includes('\t')||/[\r\n]/.test(text);if(!matrix&&event.target.matches('input:not(.sheet-keyboard-input),textarea'))return
const matrix=text.includes('\t')||/[\r\n]/.test(text);if(!matrix&&event.target.matches('input:not(.sheet-keyboard-input),textarea')){this._pasteContinuation=null;return}
event.preventDefault()
if(!matrix)return this.applyGridText(text,index,field)
if(!matrix){
const range=this.cellRange,single=!range||range.top===range.bottom&&range.left===range.right
const row=range?this.visibleRows[range.top]:this.sheet.rows[index],targetField=range?this.columns[range.left]?.field:field
const previous=this._pasteContinuation;this._pasteContinuation=null
const value=continuedPurchasePaste(previous,row,targetField,text,single)
const applied=await this.applyGridText(value,index,field)
if(applied&&row){const updated=this.sheet.rows.find(item=>item._key===row._key);this._pasteContinuation=purchasePasteMarker(updated,targetField,single)}
return applied
}
this._pasteContinuation=null
await this.finishCellEdit()
const range=this.cellRange,row=range?this.visibleRows[range.top]:this.sheet.rows[index],column=range?this.columns[range.left]?.field:field
if(!row||!column)return this.$modal.msgWarning('请先选择粘贴起始单元格')
@ -572,6 +583,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.purchase-sheet{display:flex;flex-direction:column;flex:1;min-height:0;min-width:0;overflow:hidden}
.sheet-save-notice{flex:none;margin-bottom:10px}
.purchase-sheet>.el-form,.purchase-sheet>.el-row,.purchase-sheet>.sheet-list-tabs,.purchase-sheet>.pagination-container{flex:none}
.mine-batch-hint{flex:none;margin:0 0 8px;color:var(--el-text-color-secondary);font-size:12px;line-height:20px}
.sheet-table{flex:1;min-height:80px;min-width:0;overflow:hidden}
.purchase-sheet>.pagination-container[style*="display: none"]{display:block!important;visibility:hidden}
.sheet-toolbar{container-type:inline-size}
@ -618,6 +630,8 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.sheet-grid :deep(.sheet-cell.cell-editable:focus-within){outline:1px solid var(--el-color-primary);outline-offset:-1px}
.sheet-grid :deep(.sheet-cell.cell-active:has(.el-select,.el-input,.el-input-number,.el-cascader)){border-color:transparent;padding:0;outline:none}
.sheet-grid :deep(.sheet-value),.sheet-grid :deep(.sheet-link){display:block;width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sheet-grid :deep(a.sheet-link),.sheet-grid :deep(a.sheet-link:visited){color:var(--el-color-primary);cursor:pointer}
.sheet-grid :deep(a.sheet-link:hover),.sheet-grid :deep(a.sheet-link:focus-visible){text-decoration:underline}
.sheet-grid :deep(.sheet-cell .el-select),.sheet-grid :deep(.sheet-cell .el-input-number){width:100%}
.sheet-grid :deep(.cell-invalid){outline:1px solid var(--el-color-danger);outline-offset:-1px;background:var(--el-color-danger-light-9)}
.sheet-grid :deep(.sheet-cell){cursor:cell;min-height:var(--cmvr-grid-height,28px);outline:none;user-select:none}

View File

@ -0,0 +1,15 @@
/** Change only the visible label: the stored and copied URL remains unchanged. */
export function purchaseLinkLabel(value) {
const raw = value == null ? '' : String(value)
const candidate = raw.trim()
if (!candidate) return raw
try {
const url = new URL(candidate)
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return raw
const host = url.hostname.toLowerCase().replace(/\.$/, '')
const belongsTo = domain => host === domain || host.endsWith('.' + domain)
if (belongsTo('taobao.com') || belongsTo('tmall.com') || host === 'm.tb.cn' || host === 'e.tb.cn') return '淘宝'
if (belongsTo('jd.com') || host === '3.cn') return '京东'
} catch { /* Keep unrecognised input unchanged. */ }
return raw
}

View File

@ -0,0 +1,16 @@
// Consecutive single-cell pastes into a text cell continue the value entered by
// the previous paste. Other edits, targets and rectangular pastes keep their
// normal spreadsheet semantics.
const TEXT_FIELDS = new Set(['materialName', 'materialParams', 'materialBrand', 'purchaseLink', 'remark'])
export function continuedPurchasePaste(previous, row, field, text, singleCell) {
if (!singleCell || !row || !TEXT_FIELDS.has(field)) return text
const current = String(row[field] ?? '')
return previous && previous.key === row._key && previous.field === field && previous.value === current
? current + text : text
}
export function purchasePasteMarker(row, field, singleCell) {
return singleCell && row && TEXT_FIELDS.has(field)
? { key: row._key, field, value: String(row[field] ?? '') } : null
}

View File

@ -60,7 +60,7 @@ export function createRowIdentityEditor({ getItems, loadName, isCurrentRow, onDe
brandChanged(row) { detach(row); match(row) },
specChanged(row, value) {
const item = selected(value)
if (!item && same(value, row.materialParams)) return
if (!item && String(value ?? '') === String(row.materialParams ?? '')) return
detach(row)
if (item) applyItem(row, item)
else { row.materialParams = value || ''; match(row) }

View File

@ -16,6 +16,7 @@
<el-option v-for="item in projectOptionList" :key="item.id" :label="projectLabel(item)" :value="item.id" />
</el-select>
</el-form-item>
<el-form-item v-if="arrivalMode"><el-tooltip content="仅显示由当前账号创建的采购明细" placement="top"><el-checkbox v-model="queryParams.onlyMine" @change="changeArrivalOnlyMine">只看我的</el-checkbox></el-tooltip></el-form-item>
<template #actions><el-form-item>
<el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
@ -581,7 +582,7 @@ export default {
{ value: 4, label: '已归档', type: '' },
{ value: 5, label: '已取消', type: 'danger' }
],
queryParams: { pageNum: 1, pageSize: 20, unbatched:false, supplierId: undefined, priceLocked: undefined, notArrived: false, notReceived: false, materialName: undefined, purchaseStatus: undefined, pendingAcceptance: undefined, purchaseBatchNo: undefined, projectId: undefined, expenseCategoryId: undefined },
queryParams: { pageNum: 1, pageSize: 20, onlyMine:false, unbatched:false, supplierId: undefined, priceLocked: undefined, notArrived: false, notReceived: false, materialName: undefined, purchaseStatus: undefined, pendingAcceptance: undefined, purchaseBatchNo: undefined, projectId: undefined, expenseCategoryId: undefined },
form: {},
assignForm: {},
batchForm: {},
@ -905,7 +906,8 @@ export default {
},
cancel() { this.open = false; this.reset() },
handleQuery() { this.queryParams.pageNum = 1; this.getList() },
resetQuery() { this.clearQueryFilters(); if (this.arrivalMode) this.arrivalQueue = 'open'; this.getList() },
changeArrivalOnlyMine() { this.clearArrivalSelection(); this.purchaseList=[]; this.filteredTotals={}; this.total=0; this.handleQuery() },
resetQuery() { this.clearQueryFilters(); this.queryParams.onlyMine=false; if (this.arrivalMode) this.arrivalQueue = 'open'; this.getList() },
handleSelectionChange(selection) {
if(this.syncingArrivalSelection)return
invalidateQuery(this,"filteredSelection");this.choosingFiltered=false

View File

@ -0,0 +1,14 @@
import {it,expect,vi} from 'vitest'
import Arrival from '../../src/views/warehouse/purchase/index.vue'
vi.mock('@/router',()=>({default:{}}))
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
it('only-mine switch clears selections and stale data, resets page and keeps the active arrival queue and search',()=>{
const vm={queryParams:{onlyMine:true,pageNum:5,materialName:'电机',pendingAcceptance:true},arrivalQueue:'pendingAcceptance',purchaseList:[{id:8}],filteredTotals:{count:30},total:30,clearArrivalSelection:vi.fn(),getList:vi.fn(),handleQuery:Arrival.methods.handleQuery}
Arrival.methods.changeArrivalOnlyMine.call(vm)
expect(vm.clearArrivalSelection).toHaveBeenCalledOnce();expect(vm.purchaseList).toEqual([]);expect(vm.filteredTotals).toEqual({});expect(vm.total).toBe(0)
expect(vm.queryParams).toEqual({onlyMine:true,pageNum:1,materialName:'电机',pendingAcceptance:true});expect(vm.arrivalQueue).toBe('pendingAcceptance');expect(vm.getList).toHaveBeenCalledOnce()
Arrival.methods.applyArrivalQueue.call(vm,{key:'open'})
expect(vm.queryParams.onlyMine).toBe(true);expect(vm.queryParams.notArrived).toBe(true)
})

View File

@ -62,6 +62,7 @@ it('employee purchase views keep actual amounts, omit quote sorts and preserve q
const row={id:1,quoteAvailable:true,finalUnitPrice:null,priceLocked:false,purchaseStatus:0}
expect(Sheet.methods.hasPrice.call(vm,row)).toBe(true)
expect(queueMatches(row,'confirm')).toBe(true);expect(queueMatches(row,'quote')).toBe(false)
expect(Sheet.computed.canViewQuotes.call({$auth:{hasPermiOr:()=>false}})).toBe(false)
expect(Sheet.computed.canViewQuotes.call({$auth:{hasPermiOr:()=>true}})).toBe(true)
expect(Sheet.computed.canViewQuotes.call({$store:{getters:{userId:2,roles:['employee']}}})).toBe(false)
expect(Sheet.computed.canViewQuotes.call({$store:{getters:{userId:2,roles:['purchase_manager']}}})).toBe(true)
expect(Sheet.computed.canViewQuotes.call({$store:{getters:{userId:1,roles:[]}}})).toBe(true)
})

View File

@ -0,0 +1,45 @@
import { afterEach, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Cell from '@/components/PurchaseSheet/Cell.vue'
import Sheet from '@/components/PurchaseSheet/index.vue'
import { candidates } from '@/utils/purchase-sheet'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
const wrappers=[]
afterEach(()=>wrappers.splice(0).forEach(w=>w.unmount()))
function setup(field, row, items) {
const owner={saving:false,nameMenuRow:null,nameItems:items, items, fieldLocked:()=>false,cellError:()=>'',editableCell:()=>true,isEditing:true,displayCell:(r,f)=>r[f],
rememberCell:()=>{},paste:()=>{},navigate:()=>{},searchNames:vi.fn(async()=>{}),loadName:vi.fn(async()=>{}),
nameChoices:Sheet.methods.nameChoices,specs(r){return candidates(this.items,r,'spec')},brands:()=>[],
specChanged:vi.fn(),nameChanged:vi.fn(),brandChanged:vi.fn(),itemLabel:i=>[i.productName,i.spec].filter(Boolean).join(' / ')}
const w=mount(Cell,{props:{row,column:{field,label:field},index:0,owner,active:true},global:{plugins:[ElementPlus]}})
wrappers.push(w)
return {w,owner,autocomplete:w.findComponent({name:'ElAutocomplete'})}
}
it('产品远程搜索结果即使没有旧下拉状态也可选择档案',async()=>{
const items=[{id:1,productName:'电机',spec:'型号A'},{id:2,productName:'电机支架',spec:'型号B'}]
const {autocomplete,owner}=setup('materialName',{_key:'r',materialName:''},items)
let suggestions
await autocomplete.props('fetchSuggestions')('电机',value=>suggestions=value)
expect(suggestions.map(x=>x.id)).toEqual([1,2])
await autocomplete.vm.$emit('select',suggestions[1])
expect(owner.nameChanged).toHaveBeenCalledWith(expect.anything(),'@item:2')
})
it('规格保留原文本、展开可选其他规格并支持搜索和选择档案',async()=>{
const items=[{id:1,productName:'电机',brand:'甲',spec:'型号A',unit:'个'},{id:2,productName:'电机',brand:'甲',spec:'型号B',unit:'个'}]
const {autocomplete,owner}=setup('materialParams',{_key:'r',materialName:'电机',materialBrand:'甲',materialParams:'型号A'},items)
expect(autocomplete.props('modelValue')).toBe('型号A')
let suggestions
await autocomplete.props('fetchSuggestions')('型号A',value=>suggestions=value)
expect(owner.loadName).toHaveBeenCalledWith('电机')
expect(suggestions.map(x=>x.id)).toEqual([1,2])
await autocomplete.props('fetchSuggestions')('型号B',value=>suggestions=value)
expect(suggestions.map(x=>x.id)).toEqual([2])
await autocomplete.vm.$emit('select',suggestions[0])
expect(owner.specChanged).toHaveBeenCalledWith(expect.anything(),'@item:2')
})

View File

@ -36,8 +36,6 @@ it('a single selected cell accepts replacement text without double-click and Esc
expect(document.activeElement).toBe(proxy.element)
await proxy.setValue('新品牌');await flushPromises()
expect(cell(0,'materialBrand').find('input').element.value).toBe('新品牌')
await cell(0,'materialBrand').find('input').trigger('keydown',{key:'Enter',code:'Enter'});await flushPromises()
expect(vm.sheet.rows[0].materialBrand).toBe('新品牌')
await cell(0,'materialBrand').find('input').trigger('keydown',{key:'Escape'});await flushPromises()
expect(vm.sheet.rows[0].materialBrand).toBe('原品牌');expect(vm.history).toHaveLength(0)
})

View File

@ -0,0 +1,30 @@
import {describe,it,expect,vi} from 'vitest'
import Lookup from '../../src/components/PurchaseSheet/Lookup.vue'
import Sheet from '../../src/components/PurchaseSheet/index.vue'
import {listPurchase} from '../../src/api/warehouse/purchase'
vi.mock('@/router',()=>({default:{}}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/api/warehouse/purchase',()=>({listPurchase:vi.fn(),listPurchaseBatch:vi.fn(),getPurchaseSheet:vi.fn(),getUnbatchedSheet:vi.fn(),savePurchaseSheet:vi.fn(),getPurchaseSheetSubmission:vi.fn(),confirmPurchaseSheet:vi.fn(),purchaseSheetOptions:vi.fn(),listPurchaseArrival:vi.fn(),assignPurchaseBatch:vi.fn(),delPurchaseBatch:vi.fn(),purchasePlanOptions:vi.fn(),updatePurchaseStatus:vi.fn(),newPurchaseSheetSubmissionKey:vi.fn()}))
vi.mock('@/utils/amount-display',()=>({amountDisplay:{enabled:false},loadAmountDisplay:vi.fn()}))
describe('only mine purchase filter',()=>{
it('resets the detail page and selection when toggled, then requests filtered results and retains other filters',async()=>{
listPurchase.mockResolvedValue({rows:[{id:42}],total:1})
const vm={onlyMine:true,unbatched:false,query:{pageNum:4,pageSize:20,materialName:'电机',projectId:3},rows:[{id:1}],total:88,selected:[{id:1}],clearSelection(){this.selected=[]},search:Lookup.methods.search,load:Lookup.methods.load}
Lookup.watch.onlyMine.call(vm)
await vi.waitFor(()=>expect(vm.loading).toBe(false))
expect(vm.selected).toEqual([])
expect(listPurchase).toHaveBeenLastCalledWith(expect.objectContaining({onlyMine:true,pageNum:1,pageSize:20,materialName:'电机',projectId:3,unbatched:false}))
expect(vm.rows).toEqual([{id:42}]);expect(vm.total).toBe(1)
vm.onlyMine=false;vm.unbatched=true;vm.query.pageNum=3
Lookup.watch.onlyMine.call(vm)
await vi.waitFor(()=>expect(vm.loading).toBe(false))
expect(listPurchase).toHaveBeenLastCalledWith(expect.objectContaining({onlyMine:false,pageNum:1,unbatched:true,materialName:'电机'}))
})
it('clears stale batch results and returns to page 1 when the switch changes',()=>{
const vm={viewMode:'batches',query:{pageNum:4,keyword:'零件'},batches:[{id:5}],total:50,loadBatches:vi.fn()}
Sheet.methods.changeOnlyMine.call(vm)
expect(vm.query).toEqual({pageNum:1,keyword:'零件'});expect(vm.batches).toEqual([]);expect(vm.total).toBe(0);expect(vm.loadBatches).toHaveBeenCalledOnce()
})
})

View File

@ -0,0 +1,20 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { purchaseLinkLabel } from '../../src/utils/purchase-link-label.js'
test('recognises actual Taobao, Tmall and JD links without changing unknown content', () => {
assert.equal(purchaseLinkLabel('https://item.taobao.com/item.htm?id=123'), '淘宝')
assert.equal(purchaseLinkLabel('https://detail.tmall.com/item.htm?id=1'), '淘宝')
assert.equal(purchaseLinkLabel('https://m.tb.cn/h.test'), '淘宝')
assert.equal(purchaseLinkLabel('https://e.tb.cn/h.test'), '淘宝')
assert.equal(purchaseLinkLabel('https://item.jd.com/123.html'), '京东')
assert.equal(purchaseLinkLabel('https://3.cn/abc'), '京东')
assert.equal(purchaseLinkLabel('https://example.com/product'), 'https://example.com/product')
assert.equal(purchaseLinkLabel('其他备注'), '其他备注')
})
test('does not misidentify lookalike hosts or URLs with credentials', () => {
for (const text of ['https://taobao.com.example.com/item', 'https://notjd.com/', 'https://jd.com@evil.test/', 'javascript://jd.com/']) {
assert.equal(purchaseLinkLabel(text), text)
}
})

View File

@ -0,0 +1,23 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {continuedPurchasePaste,purchasePasteMarker} from '../../src/utils/purchase-paste-continuation.js'
import {createRowIdentityEditor} from '../../src/utils/purchase-sheet.js'
test('连续单格粘贴接续同一文本,切换单元格或内容变化时正常替换', () => {
const row={_key:'r1',materialParams:'长度 100'}
const marker=purchasePasteMarker(row,'materialParams',true)
assert.equal(continuedPurchasePaste(marker,row,'materialParams',' mm',true),'长度 100 mm')
assert.equal(continuedPurchasePaste(marker,{...row,_key:'r2'},'materialParams','新规格',true),'新规格')
assert.equal(continuedPurchasePaste(marker,{...row,materialParams:'人工修改'},'materialParams','新规格',true),'新规格')
assert.equal(continuedPurchasePaste(marker,row,'materialParams','批量',false),'批量')
assert.equal(purchasePasteMarker(row,'quantity',true),null)
})
test('规格编辑保留空格且选择档案时仍联动物品信息', () => {
const item={id:7,productCode:'P7',productName:'零件',spec:'A B',brand:'甲',unit:'个',category:'零件'}
const row={materialName:'零件',materialParams:'A',materialBrand:'甲',unit:'个',category:'零件',productId:8}
const editor=createRowIdentityEditor({getItems:()=>[item],loadName:async()=>{},isCurrentRow:()=>true})
editor.specChanged(row,'A '); assert.equal(row.materialParams,'A '); assert.equal(row.productId,null)
editor.specChanged(row,'A B'); assert.equal(row.productId,7)
editor.specChanged(row,'@item:7'); assert.equal(row.materialParams,'A B'); assert.equal(row.productCode,'P7')
})