feat(ui): 添加操作指引功能并优化登录和盘点流程

- 在页面标题栏添加操作指引图标,显示相关功能说明
- 实现登录页面连接状态提示和验证码刷新机制
- 优化盘点功能,区分账面数量和实际盘点数量
- 改进AI助手附件上传状态反馈和错误处理
- 添加BOM编辑器和采购页面操作指引
- 实现登录页面连接状态提示和验证码刷新机制
This commit is contained in:
lixiaolong 2026-10-18 22:30:47 +08:00
parent a67a16ebb7
commit af36af4cab
37 changed files with 624 additions and 46 deletions

View File

@ -65,6 +65,7 @@ function Root(){
<View style={{paddingHorizontal:12,paddingVertical:7,minHeight:56,backgroundColor:t.bg,flexDirection:'row',alignItems:'center',gap:8}}>
{page&&<Pressable accessibilityRole="button" accessibilityLabel="返回上一页" onPress={back} style={{padding:12}}><Icon name="chevron-back" color={t.text}/></Pressable>}
<Text style={{flex:1,fontSize:page?18:20,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&&<View style={{borderRadius:12,backgroundColor:t.soft,paddingHorizontal:10,paddingVertical:5}}><Text style={{color:t.accent,fontSize:11}}>{variant==='prod'?'内网工作空间':'开发环境'}</Text></View>}
</View>
<View style={s.fill}>
@ -83,9 +84,9 @@ function Root(){
}
function Login({api,onLogin}:{api:ApiClient;onLogin:(token:string)=>Promise<void>}){
const [username,setUsername]=useState(''),[password,setPassword]=useState(''),[code,setCode]=useState('');
const [captcha,setCaptcha]=useState<Row|null>(null),[error,setError]=useState(''),[busy,setBusy]=useState(false);
const [captcha,setCaptcha]=useState<Row|null>(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[connecting,setConnecting]=useState(true);
const lock=useRef(false),seq=useRef(0);
const refresh=useCallback(async()=>{const current=++seq.current;try{const data=await api.request<Row>('/captchaImage',{anonymous:true});if(current===seq.current){setCaptcha(data);setCode('');setError('');}}catch(e){if(current===seq.current)setError((e as Error).message);}},[api]);
const refresh=useCallback(async()=>{const current=++seq.current;setConnecting(true);setCaptcha(null);setError('');try{let data:Row;try{data=await api.request<Row>('/captchaImage',{anonymous:true});}catch(e){if((e as {code?:number}).code!==409)throw e;data=await api.request<Row>('/captchaImage',{anonymous:true});}if(current===seq.current){setCaptcha(data);setCode('');}}catch(e){if(current===seq.current)setError((e as Error).message);}finally{if(current===seq.current)setConnecting(false);}},[api]);
useEffect(()=>{void refresh();return()=>{seq.current++;};},[refresh]);
async function submit(){if(lock.current)return;if(!captcha){setError('请先连接服务获取登录信息。');return;}
if(!username.trim()||!password||captcha.captchaEnabled!==false&&!code.trim()){setError('请填写账号、密码和验证码。');return;}
@ -94,10 +95,11 @@ function Login({api,onLogin}:{api:ApiClient;onLogin:(token:string)=>Promise<void
return <KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}><ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={[s.page,{flexGrow:1,justifyContent:'center',maxWidth:520,width:'100%',alignSelf:'center'}]}>
<Note>CMVR · 项目物资管理</Note><Heading>欢迎回到工作空间</Heading><Note>请连接公司内网,使用现有账号登录。</Note>
<Field label="登录账号" value={username} onChange={setUsername} disabled={busy}/><Field label="密码" value={password} onChange={setPassword} secure disabled={busy}/>
{captcha?.captchaEnabled!==false&&<><Field label="验证码" value={code} onChange={setCode} disabled={busy}/>
{connecting&&<View style={s.row}><ActivityIndicator/><Note>正在连接内网服务,准备登录信息…</Note></View>}
{!!captcha&&captcha.captchaEnabled!==false&&<><Field label="验证码" value={code} onChange={setCode} disabled={busy}/>
{!!captcha?.img&&<Pressable accessibilityRole="button" accessibilityLabel="刷新验证码" disabled={busy} onPress={()=>void refresh()}><Image source={{uri:`data:image/png;base64,${captcha.img}`}} style={{width:160,height:60}}/></Pressable>}</>}
{!!error&&<Note>{error}</Note>}<Button title="登录" busy={busy} disabled={!captcha} onPress={()=>void submit()}/>
<Button title="重新连接" secondary disabled={busy} onPress={()=>void refresh()}/><Note>{variant==='prod'?'正式环境':'开发环境'} · {nativeBase}</Note>
<Button title="重新连接" secondary disabled={busy||connecting} onPress={()=>void refresh()}/><Note>{variant==='prod'?'正式环境':'开发环境'} · {nativeBase}</Note>
{nativeBase.includes('127.0.0.1')&&<Note>真机测试前,请把开发配置的地址换成开发电脑的内网 IP;手机的 localhost 不是电脑。</Note>}
</ScrollView></KeyboardAvoidingView>;
}
@ -166,8 +168,9 @@ function StockOperation({api,row,kind,close,done}:{api:ApiClient;row:Row;kind:st
<Field label="业务日期(YYYY-MM-DD)" value={date} onChange={setDate}/><Field label={kind==='check'?'差异原因':'备注'} value={remark} onChange={setRemark} multiline/>
{kind==='borrow'&&<Choice label="借入项目" items={projects} value={project} onChange={setProject} nameKey="projectName"/>}
{kind!=='check'&&<Choice label="目标库区" items={areas} value={area} onChange={setArea} nameKey="areaName"/>}
<Button title="核对预览" disabled={!ready} onPress={prepare}/></>:<Card><Heading>请核对本次{title}</Heading><Note>物品:{display(row.productName)}</Note><Note>数量:{quantity} {display(row.unit)}</Note>
{!!project&&<Note>借入项目:{project.projectName}</Note>}{!!area&&<Note>目标库区:{area.areaName||area.areaCode}</Note>}<Note>日期:{date}</Note><Note>备注:{remark||'无'}</Note>
<Button title="核对预览" disabled={!ready} onPress={prepare}/></>:<Card><Heading>请核对本次{title}</Heading><Note>物品:{display(row.productName)}</Note>
{kind==='check'?<><Note>账面数量:{display(row.stockNum)} {display(row.unit)}</Note><Note>实际盘点数量:{quantity} {display(row.unit)}</Note><Note>差异数量:{Number((Number(quantity)-Number(row.stockNum)).toFixed(4))} {display(row.unit)}</Note><Note>登记后生成待确认盘点记录;确认生效后才会调整库存,当前不会直接扣减或增加库存。</Note></>:<Note>数量:{quantity} {display(row.unit)}</Note>}
{!!project&&<Note>借入项目:{project.projectName}</Note>}{!!area&&<Note>目标库区:{area.areaName||area.areaCode}</Note>}<Note>日期:{date}</Note><Note>{kind==='check'?'差异原因':'备注'}:{remark||'无'}</Note>
<Button title={submitted?'核对后重试原请求':'确认提交'} busy={busy} disabled={kind==='check'&&submitted} onPress={()=>void submit()}/>
<Button title="返回修改" secondary disabled={busy||submitted} onPress={()=>setPreview(false)}/></Card>}
{!!error&&<Note>{error}</Note>}<Button title="关闭" secondary disabled={busy} onPress={requestClose}/>

View File

@ -0,0 +1,26 @@
import type {Row} from './modules';
export function draftStatus(value:unknown) {
return ({WAIT_CONFIRM:'待确认',NEEDS_INPUT:'待补充',NEEDS_REVIEW:'待复核',EXPIRED:'需重新核对',SUCCEEDED:'已完成',CANCELLED:'已取消',PARTIAL:'部分完成',FAILED:'未成功',RUNNING:'办理中'} as Record<string,string>)[String(value)]||'待核对';
}
export function referenceText(value:unknown):string {
if(value==null||value==='')return '—';
if(Array.isArray(value))return value.map(referenceText).join(';');
if(typeof value!=='object')return String(value);
const row=value as Row;
const summary=['label','name','keyword','code','spec','brand','supplierName','projectName'].map(key=>row[key]).filter(v=>v!=null&&v!=='');
return [...new Set(summary.map(String))].join(' / ')||'尚未匹配,请补充名称或在电脑端选择';
}
export function draftFieldText(row:Row,field:Row) {
const value=row._labels?.[field.key]??row[field.key];
const option=(field.options||[]).find((o:Row)=>String(o.value)===String(value));
return option?.label??referenceText(value);
}
export function sheetSelectionError(files:Row[]) {
let count=0;
for(const file of files.filter(f=>f.type==='excel')) {
if(!file.selectedSheetIndexes?.length)return `请选择“${file.name}”本次读取的工作表。`;
count+=(file.sheets||[]).filter((sheet:Row)=>file.selectedSheetIndexes.includes(sheet.index)).reduce((n:number,sheet:Row)=>n+Number(sheet.rowCount||0),0);
}
return count>100?`本次所选工作表共 ${count} 行,超过 100 行,请减少选择;未选子表不计入。`:'';
}

View File

@ -1,22 +1,28 @@
export type Row = Record<string, any>;
export type Module = { key: string; title: string; path: string; permissions: string[][];
search: string; titleKey: string; fields: [string, string][]; query?: Row; pages?: string[] };
search: string; titleKey: string; fields: [string, string][]; query?: Row; pages?: string[]; guide?: string };
export const modules: Module[] = [
{ key: 'stock', title: '库存查询', path: '/warehouse/stock/list', permissions: [['warehouse:stock:list']], search: 'productName', titleKey: 'productName',
guide: '同项目换库区用「移库」,跨项目临时调配用「借用」;归还到「借用与归还」办理。',
fields: [['projectName','所属项目'],['areaName','库区'],['stockNum','库存数量'],['unit','单位'],['spec','规格型号'],['brand','品牌'],['averageUnitCost','平均单价'],['stockAmount','库存金额']] },
{ key: 'purchase', title: '采购明细', path: '/warehouse/purchase/list', permissions: [['warehouse:purchase:list','warehouse:purchase:manage']], search: 'materialName', titleKey: 'materialName',
fields: [['projectName','所属项目'],['purchaseBatchNo','采购批次'],['materialParams','规格型号'],['materialBrand','品牌'],['quantity','采购数量'],['unit','单位'],['finalUnitPrice','报价'],['acceptedQuantity','已验收数量']] },
guide: '一批采购对应一个项目;确认采购后再登记到货,验收合格后到「待入库」办理入库。',
fields: [['purchaseStatus','采购状态'],['projectName','所属项目'],['purchaseBatchNo','采购批次'],['materialParams','规格型号'],['materialBrand','品牌'],['quantity','采购数量'],['unit','单位'],['finalUnitPrice','报价'],['acceptedQuantity','已验收数量'],['remainingQuantity','未到数量']] },
{ key: 'pending', title: '待入库', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 0 },
guide: '采购验收合格或生产完工验收后,记录才会进入待入库;选择实际存放库区并确认后,才计入库存。',
fields: [['sourceProjectName','来源项目'],['purchaseBatchNo','采购批次'],['spec','规格型号'],['inNum','应入库数量'],['receivedQuantity','已入库数量'],['unit','单位'],['sourceNo','来源单号']] },
{ key: 'in', title: '入库记录', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 1 },
fields: [['sourceProjectName','所属项目'],['areaName','库区'],['inNum','入库数量'],['unit','单位'],['businessDate','业务日期'],['inNo','入库单号']] },
{ key: 'loans', title: '借用与归还', path: '/project/loans', permissions: [['project:project:list','warehouse:stock:list','warehouse:purchase:list','warehouse:purchase:manage']], search: '', titleKey: 'itemName',
guide: '先从「库存查询」选择物品办理跨项目借用,再在此查看待还数量;借用不等于领用。',
fields: [['lenderProjectName','借出项目'],['borrowerProjectName','借入项目'],['quantity','借用数量'],['returnedQuantity','已还数量'],['outstandingQuantity','未还数量'],['unit','单位'],['loanNo','借用编号']] },
{ key: 'check', title: '库存盘点', path: '/warehouse/check/list', permissions: [['warehouse:check:list']], search: 'productName', titleKey: 'productName',
guide: '从「库存查询」登记实际清点数量,不是差异数量;保存仅生成待确认记录,确认后才调整库存。',
fields: [['projectName','所属项目'],['areaName','库区'],['bookNum','账面数量'],['realNum','实际数量'],['diffNum','差异数量'],['checkNo','盘点单号'],['businessDate','业务日期']] },
{ key: 'out', title: '领用与退回记录', path: '/warehouse/out/list', permissions: [['warehouse:out:list']], search: 'productName', titleKey: 'productName',
fields: [['usageProjectName','使用项目'],['sourceProjectNames','来源项目'],['areaName','库区'],['outNum','数量'],['unit','单位'],['outNo','单号'],['outTime','出库时间']] },
{ key: 'production', title: '生产任务', path: '/production/tasks/page', permissions: [['project:project:list','warehouse:stock:list']],
guide: '先维护物品、产品和 BOM,再选择项目建立生产任务;完工验收后到「待入库」办理成品入库。',
pages: ['production/tasks/index','production/operations/index','production/cost/index'], search: 'keyword', titleKey: 'item_name',
fields: [['task_no','任务编号'],['project_name','所属项目'],['planned_quantity','计划数量'],['good_quantity','合格数量'],['version_tag','BOM版本'],['status','状态']] },
];
@ -31,6 +37,7 @@ export function validDate(value: string) {
return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0,10) === value;
}
export function recordDisplay(module: Module, key: string, value: unknown) {
if(module.key==='purchase'&&key==='purchaseStatus')return ({0:'待采购',1:'已下单',2:'采购中',3:'部分到货',4:'已到齐',5:'已取消'} as Record<string,string>)[String(value)]||'待核对';
if (module.key === 'production' && key === 'status') return ({OPEN:'进行中',SETTLED:'已结算',CANCELLED:'已取消'} as Record<string,string>)[String(value)] || display(value);
return display(value);
}

View File

@ -1,3 +1,4 @@
import {isSearchRequest,normalizeSearchQuery} from './search-query.ts';
export type Environment = 'dev' | 'prod';
// Do not let a pasted server address redirect credentials to an Internet host.
@ -35,7 +36,9 @@ export class ApiClient {
} = {}): Promise<T> {
if (!/^\/[a-zA-Z]/.test(path) || path.includes('://') || path.includes('..')) throw new Error('无效的接口地址');
const url = new URL(this.baseUrl + path);
for (const [key, value] of Object.entries(options.query || {})) {
const query=isSearchRequest(path,options.method)?normalizeSearchQuery(options.query||{}) as Record<string,unknown>:options.query||{};
const requestBody=isSearchRequest(path,options.method)&&options.method?.toUpperCase()==='POST'?normalizeSearchQuery(options.body):options.body;
for (const [key, value] of Object.entries(query)) {
if (value !== '' && value != null) url.searchParams.set(key, String(value));
}
const epoch = this.generation;
@ -45,12 +48,12 @@ export class ApiClient {
if (options.signal?.aborted) controller.abort();
const timer = setTimeout(abort, options.timeout || 30000);
try {
const multipart = typeof FormData !== 'undefined' && options.body instanceof FormData;
const multipart = typeof FormData !== 'undefined' && requestBody instanceof FormData;
const response = await this.transport(url.toString(), {
method: options.method || 'GET', redirect: 'error', signal: controller.signal,
headers: { Accept: 'application/json', ...(!multipart ? { 'Content-Type': 'application/json' } : {}),
...(!options.anonymous && this.token ? { Authorization: `Bearer ${this.token}` } : {}) },
body: options.body === undefined ? undefined : multipart ? options.body as FormData : JSON.stringify(options.body)
body: requestBody === undefined ? undefined : multipart ? requestBody as FormData : JSON.stringify(requestBody)
});
if(options.responseType==='image'&&response.ok&&/^image\/(png|jpeg|webp)$/.test(response.headers.get('content-type')?.split(';')[0]||'')){
if(Number(response.headers.get('content-length')||0)>6*1024*1024)throw new ApiError('图片较大,请在电脑端查看。',413);

View File

@ -0,0 +1,13 @@
const protectedField = (name:string) => /password$|token$|^(authorization|secret|secretkey|signature|sign|key|filename|filepath|path|url|redirect|redirecturl)$/i.test(name.split(/[.[\]]/).filter(Boolean).pop() || '');
export function normalizeSearchQuery(value:unknown, field=''):unknown {
if(protectedField(field))return value;
if(typeof value==='string')return value.replace(/^[\s\u0085\u200b]+|[\s\u0085\u200b]+$/gu,'');
if(Array.isArray(value))return value.map(item=>normalizeSearchQuery(item,field));
if(value&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null))return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,normalizeSearchQuery(item,key)]));
return value;
}
export function isSearchRequest(path:string, method='GET') {
path=path.split('?')[0];
const owned=/^\/(?:warehouse|production|system|monitor)\//.test(path)||/^\/project\/(?:info|loans)(?:\/|$)/.test(path);
return owned&&(method.toUpperCase()==='GET'||method.toUpperCase()==='POST'&&/\/export(?:\/[^/]*)?$/.test(path));
}

View File

@ -6,26 +6,27 @@ import { ApiClient } from '../core/network';
import { display, type Row } from '../core/modules';
import { Button, Card, Field, Heading, Icon, Note, s, useTheme } from '../ui';
import { ProtectedImage } from '../files';
import { draftStatus, draftFieldText, sheetSelectionError } from '../core/assistant-display';
const root='/warehouse/assistant';
export function Assistant({api}:{api:ApiClient}){
const t=useTheme(),scroll=useRef<React.ComponentRef<typeof ScrollView>>(null),lock=useRef(false),alive=useRef(true);
const [session,setSession]=useState<Row|null>(null),[text,setText]=useState(''),[files,setFiles]=useState<Row[]>([]);
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[uncertain,setUncertain]=useState(false),[pending,setPending]=useState<Row|null>(null),[seconds,setSeconds]=useState(0);
const [attachmentPhase,setAttachmentPhase]=useState<'selecting'|'uploading'|null>(null);
const refresh=useCallback(async()=>{if(lock.current)return;lock.current=true;setBusy(true);try{const data=await api.request<Row>(`${root}/session`);if(alive.current){setSession(data.data);setUncertain(Boolean(data.data.processing));setError('');setPending(null);}}
catch(e){if(alive.current)setError((e as Error).message);}finally{lock.current=false;if(alive.current)setBusy(false);}},[api]);
useEffect(()=>{alive.current=true;void refresh();return()=>{alive.current=false;};},[refresh]);
useEffect(()=>{if(!busy){setSeconds(0);return;}const started=Date.now(),timer=setInterval(()=>setSeconds(Math.floor((Date.now()-started)/1000)),1000);return()=>clearInterval(timer);},[busy]);
async function attach(){if(lock.current||files.length>=3)return;lock.current=true;setBusy(true);setError('');try{
async function attach(){if(lock.current||files.length>=3)return;lock.current=true;setBusy(true);setAttachmentPhase('selecting');setError('');try{
const selected=await DocumentPicker.getDocumentAsync({multiple:false,copyToCacheDirectory:true,type:['image/png','image/jpeg','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel','application/pdf']});
if(selected.canceled||!alive.current)return;const file=selected.assets[0];if(file.size!=null&&(file.size<=0||file.size>10*1024*1024)){setError('请选择非空附件,单个不超过 10 MB。');return;}
const body=new FormData();
setAttachmentPhase('uploading');const body=new FormData();
if(Platform.OS==='web'){const response=await fetch(file.uri);body.append('file',await response.blob(),file.name);}
else body.append('file',{uri:file.uri,name:file.name,type:file.mimeType||'application/octet-stream'} as unknown as Blob);
const data=await api.request<Row>(`${root}/attachments`,{method:'POST',body,timeout:120000});if(alive.current){const f=data.data;setFiles(old=>[...old,{...f,selectedSheetIndexes:f.sheets?.length===1?[f.sheets[0].index]:[]}]);}}
catch(e){if(alive.current)setError((e as Error).message);}finally{lock.current=false;if(alive.current)setBusy(false);}}
catch(e){if(alive.current)setError((e as Error).message);}finally{lock.current=false;if(alive.current){setBusy(false);setAttachmentPhase(null);}}}
async function send(){if(lock.current||!session||uncertain||(!text.trim()&&!files.length))return;
const selected=files.filter(f=>f.type==='excel');let count=0;for(const f of selected){if(!f.selectedSheetIndexes.length)return setError(`请选择“${f.name}”本次读取的工作表。`);count+=(f.sheets||[]).filter((sheet:Row)=>f.selectedSheetIndexes.includes(sheet.index)).reduce((n:number,sheet:Row)=>n+sheet.rowCount,0);}
if(count>100)return setError(`本次所选工作表共 ${count} 行,超过 100 行,请减少选择;未选子表不计入。`);
const selected=files.filter(f=>f.type==='excel'),selectionError=sheetSelectionError(files);if(selectionError)return setError(selectionError);
const submittedText=text,submittedFiles=files;lock.current=true;setBusy(true);setError('');setText('');setFiles([]);
setPending({content:submittedText||'请识别附件并协助处理',attachments:submittedFiles,role:'user'});
try{const data=await api.request<Row>(`${root}/message`,{method:'POST',body:{sessionId:session.id,text:submittedText,attachmentIds:submittedFiles.map(f=>f.id),
@ -49,10 +50,10 @@ export function Assistant({api}:{api:ApiClient}){
<View style={{alignSelf:message.role==='user'?'flex-end':'stretch',maxWidth:message.role==='user'?'92%':'100%',backgroundColor:message.role==='user'?t.soft:t.card,padding:15,borderRadius:16,borderTopRightRadius:message.role==='user'?4:16,borderTopLeftRadius:message.role==='user'?16:4,borderWidth:1,borderColor:t.line,gap:10}}><Text selectable style={{color:t.text,lineHeight:24}}>{message.content}</Text>{message.attachments?.map((f:Row)=>f.type==='image'?<ProtectedImage key={f.id} api={api} path={`${root}/attachments/${encodeURIComponent(f.id)}/content`} label={f.name}/>:<Note key={f.id}>{f.name}</Note>)}</View>
{message.query?.errors?.map((e:string,j:number)=><Note key={j}>{e}</Note>)}
{message.query?.results?.map((result:Row,j:number)=><Results key={j} data={result.data} title={result.title}/>)}
{message.draft&&<Card><Heading>{message.draft.label}</Heading><Note>{message.draft.status} · {message.draft.rows?.length||0} 项</Note>
{message.draft&&<Card><Heading>{message.draft.label}</Heading><Note>{draftStatus(message.draft.status)} · {message.draft.rows?.length||0} 项</Note>
{(message.draft.errors||[]).map((e:string,j:number)=><Note key={j}>{e}</Note>)}
{(message.draft.rows||[]).slice(0,20).map((row:Row,j:number)=><View key={j} style={{gap:6,paddingVertical:8,borderTopWidth:1,borderColor:t.line}}>
<Note>第 {j+1} 行</Note>{(message.draft.fields||[]).map((f:Row)=><Text key={f.key} style={{color:t.text,lineHeight:22}}>{f.label}:{display(row._labels?.[f.key]??row[f.key])}</Text>)}</View>)}
<Note>第 {j+1} 行</Note>{(message.draft.fields||[]).map((f:Row)=><Text key={f.key} style={{color:t.text,lineHeight:22}}>{f.label}:{draftFieldText(row,f)}</Text>)}</View>)}
{(message.draft.rows||[]).length>20&&<Note>此确认单超过 20 项,请在电脑端完整核对后办理;App 暂不开放截断确认。</Note>}
{!message.draft.readOnly&&String(message.draft.id)===String(session?.draft?.id)&&<>
<Note>需要更正时可继续在下方描述,原草稿由后端保留并重新核对。</Note>
@ -61,15 +62,15 @@ export function Assistant({api}:{api:ApiClient}){
</>}
</Card>}
</View>)}
{busy&&<View style={[s.row,{paddingVertical:10}]}><ActivityIndicator color={t.accent}/><Note>{session?'正在核对你的需求':'正在读取权限和最近对话'} · {seconds} 秒</Note></View>}
{busy&&<View style={[s.row,{paddingVertical:10}]}><ActivityIndicator color={t.accent}/><Note>{attachmentPhase==='selecting'?'请在文件选择窗口中选择附件':attachmentPhase==='uploading'?'正在上传附件并读取文件信息':session?'正在核对你的需求':'正在读取权限和最近对话'} · {seconds} 秒</Note></View>}
{!!error&&<Note>{error}</Note>}{(uncertain||session?.processing)&&<Note>上一项结果尚待核对。请刷新状态,确认处理已结束后继续。</Note>}
{(uncertain||error||session?.processing)&&<Button title="刷新处理状态" secondary disabled={busy} onPress={()=>void refresh()}/>}
{(uncertain||session?.processing||(!session&&error))&&<Button title="刷新处理状态" secondary disabled={busy} onPress={()=>void refresh()}/>}
</ScrollView>
<View style={[s.page,{paddingTop:12,paddingBottom:12,borderTopWidth:1,borderColor:t.line,backgroundColor:t.card}]}>
{!!files.length&&<ScrollView style={{maxHeight:170}}>{files.map(f=><View key={f.id} style={{gap:6}}><Note>{f.name}</Note>{f.type==='excel'&&(f.sheets||[]).map((sheet:Row)=><Button key={sheet.index}
title={`${f.selectedSheetIndexes.includes(sheet.index)?'✓ ':''}${sheet.name}(${sheet.rowCount} 行)`} secondary disabled={busy||uncertain}
onPress={()=>setFiles(old=>old.map(v=>v.id!==f.id?v:{...v,selectedSheetIndexes:v.selectedSheetIndexes.includes(sheet.index)?v.selectedSheetIndexes.filter((n:number)=>n!==sheet.index):[...v.selectedSheetIndexes,sheet.index]}))}/>)}</View>)}</ScrollView>}
{!!files.length&&<Button title="移除待发送附件" secondary disabled={busy||uncertain} onPress={()=>setFiles([])}/>}
onPress={()=>{setError('');setFiles(old=>old.map(v=>v.id!==f.id?v:{...v,selectedSheetIndexes:v.selectedSheetIndexes.includes(sheet.index)?v.selectedSheetIndexes.filter((n:number)=>n!==sheet.index):[...v.selectedSheetIndexes,sheet.index]}));}}/>)}</View>)}</ScrollView>}
{!!files.length&&<Button title="移除待发送附件" secondary disabled={busy||uncertain} onPress={()=>{setFiles([]);setError('');}}/>}
<Field label="描述需求或继续补充" value={text} onChange={setText} multiline disabled={busy||uncertain}/>
<View style={[s.row,{justifyContent:'space-between'}]}><Pressable accessibilityRole="button" accessibilityLabel="添加图片、表格或文件" disabled={busy||uncertain||files.length>=3} onPress={()=>void attach()} style={[s.row,{padding:8,opacity:busy||uncertain?.5:1}]}><Icon name="add-circle-outline"/><Text style={{color:t.muted,fontSize:12}}>图片 / 表格</Text></Pressable><Button title="发送 ↑" busy={busy} disabled={!session||uncertain||session.processing||(!text.trim()&&!files.length)} onPress={()=>void send()}/></View>
</View>

View File

@ -0,0 +1,25 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {draftStatus,draftFieldText,referenceText,sheetSelectionError} from '../src/core/assistant-display.ts';
import {modules,recordDisplay} from '../src/core/modules.ts';
test('draft statuses and field options use distinct business definitions',()=>{
assert.equal(draftStatus('CANCELLED'),'已取消');assert.equal(draftStatus('WAIT_CONFIRM'),'待确认');
assert.equal(draftFieldText({status:0},{key:'status',options:[{value:'0',label:'正常'}]}),'正常');
assert.equal(draftFieldText({status:0},{key:'status',options:[{value:'0',label:'待验收'}]}),'待验收');
assert.equal(draftFieldText({unit:'个',_labels:{unit:'个'}},{key:'unit'}),'个');
});
test('unmatched reference becomes readable identity, not raw JSON or an arbitrary ID',()=>{
assert.equal(referenceText({keyword:'螺丝',spec:'M6',brand:'测试牌'}),'螺丝 / M6 / 测试牌');
assert.match(referenceText({id:99}),/尚未匹配/);assert.equal(referenceText(null),'—');
});
test('Excel validity reflects current selection rather than the prior error',()=>{
const file={name:'分表.xlsx',type:'excel',selectedSheetIndexes:[1,2],sheets:[{index:0,rowCount:101},{index:1,rowCount:50},{index:2,rowCount:51}]};
assert.match(sheetSelectionError([file]),/101/);
assert.equal(sheetSelectionError([{...file,selectedSheetIndexes:[1]}]),'');
assert.match(sheetSelectionError([{...file,selectedSheetIndexes:[]}]),/请选择/);
});
test('purchase cards expose the same state enum as the real procurement page',()=>{
const purchase=modules.find(m=>m.key==='purchase');
assert.equal(purchase.fields[0][0],'purchaseStatus');
for(const [state,label] of Object.entries({0:'待采购',1:'已下单',2:'采购中',3:'部分到货',4:'已到齐',5:'已取消'}))assert.equal(recordDisplay(purchase,'purchaseStatus',state),label);
});

View File

@ -0,0 +1,23 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {modules} from '../src/core/modules.ts';
import {readFile} from 'node:fs/promises';
test('only dependency-sensitive mobile pages have concise operation guidance', () => {
assert.deepEqual(modules.filter(m=>m.guide).map(m=>m.key), ['stock','purchase','pending','loans','check','production']);
for(const m of modules.filter(m=>m.guide)) {
assert.ok(m.guide.length <= 80, `${m.key} should not become a manual`);
assert.ok(!m.guide.includes('\n'));
}
});
test('mobile guide belongs to a header action, not a permanent list banner', async()=>{
const app=await readFile(new URL('../src/App.tsx',import.meta.url),'utf8');
assert.ok(app.includes("accessibilityLabel={selected.title+'操作指引'}"));
assert.ok(app.includes("Alert.alert(selected.title+' · 操作指引',selected.guide)"));
assert.ok(!app.slice(app.indexOf('function BusinessList')).includes('module.guide'));
});
test('guidance distinguishes creating records from changing actual stock', () => {
assert.match(modules.find(m=>m.key==='pending').guide, /确认后,才计入库存/);
assert.match(modules.find(m=>m.key==='check').guide, /不是差异数量.*确认后才调整库存/);
assert.match(modules.find(m=>m.key==='production').guide, /物品、产品和 BOM.*生产任务/);
});

View File

@ -0,0 +1,20 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {normalizeSearchQuery,isSearchRequest} from '../src/core/search-query.ts';
import {ApiClient} from '../src/core/network.ts';
test('mobile and Web search normalization agree across Unicode boundaries and safe scope',async()=>{
const web=await import('../../ruoyi-ui-vue3/src/utils/search-query.js');
for(const edge of [' ','\t\r\n','\u3000','\u00a0','\u202f','\ufeff','\u200b','\u0085']){
const input={productName:edge+'路由器 AX 5400'+edge,params:{brands:[edge+'TP'+edge]},token:' token ',fileName:' a.pdf '};
assert.deepEqual(normalizeSearchQuery(input),web.normalizeSearchQuery(input));
}
assert.equal(isSearchRequest('/project/manage/projects'),false);assert.equal(isSearchRequest('/warehouse/product','POST'),false);
});
test('actual mobile transport sends clean search parameters without mutating business bodies',async()=>{
const calls=[];const api=new ApiClient('http://127.0.0.1:8080',()=>{},async(url,options)=>{calls.push({url,options});return new Response(JSON.stringify({code:200}),{status:200,headers:{'Content-Type':'application/json'}})});
const query={productName:' \u3000路由器\u200b ',empty:' \t ',pageNum:1,token:' token '};
await api.request('/warehouse/product/list',{query});
const params=new URL(calls[0].url).searchParams;
assert.equal(params.get('productName'),'路由器');assert.equal(params.has('empty'),false);assert.equal(params.get('token'),' token ');
assert.equal(query.productName,' \u3000路由器\u200b ');
const body={password:' secret ',remark:' 业务说明 '};await api.request('/system/user',{method:'POST',body});assert.deepEqual(JSON.parse(calls[1].options.body),body);
});

View File

@ -112,6 +112,16 @@ public class AssistantConversationService {
// Only the server-bound clarification chain of this attachment (or its frozen retry) is retained.
if (!files.isEmpty()) modelHistory = maps(input.get("attachmentConversation"));
Map<String, Object> proposal = files.isEmpty() ? resumeProposal(text, maps(state.get("parkedDrafts"))) : null;
if (proposal != null && "resume".equals(proposal.get("kind")) && Boolean.TRUE.equals(proposal.get("withChanges"))) {
Long target = longValue(proposal.get("draftId"));
Map<String,Object> parked = parkedPlan(state, target);
Map<String,Object> context = new LinkedHashMap<>(parked); context.put("status", "NEEDS_INPUT");
Map<String,Object> refinement = model.propose(modelHistory, definitions, context, pageContext(request.get("pageContext")), List.of());
if ("patch".equals(refinement.get("kind")) && Objects.equals(refinement.get("action"), parked.get("action"))) {
proposal = Map.of("kind", "resume", "draftId", target, "rows", expandPatch(refinement, context).get("rows"));
} else proposal = Map.of("kind", "clarify", "message", "原草稿仍已保留。请说明这次要统一补充的字段和值,我会在原任务上继续核对,不另建采购单。");
}
if (proposal == null && files.isEmpty()) proposal = areaFollowup(text, state.get("lastQuery"));
if (proposal == null) proposal = model.propose(modelHistory, definitions,
!files.isEmpty() ? Map.of() : taskContext(state),
pageContext(request.get("pageContext")), files);
@ -134,7 +144,7 @@ public class AssistantConversationService {
kind = "draft";
}
if ("resume".equals(kind)) {
Map<String, Object> restored = restoreParked(state, longValue(proposal.get("draftId")), text);
Map<String, Object> restored = restoreParked(state, longValue(proposal.get("draftId")), text, proposal.containsKey("rows") ? maps(proposal.get("rows")) : null);
Map<String, Object> reply = entry("assistant", "已恢复原业务草稿,之前的明细和附件来源均已保留,并重新核对当前业务状态。请检查待补充项;尚未执行业务。");
reply.put("draftId", restored.get("id")); history.add(reply);
} else if ("draft".equals(kind) || "query".equals(kind)) {
@ -165,7 +175,7 @@ public class AssistantConversationService {
// Existing query cards stay in history, but no longer hijack short follow-ups.
state.remove("lastQuery");
state.put("status", Boolean.TRUE.equals(draft.get("ready")) ? "WAIT_CONFIRM" : "NEEDS_INPUT");
String explanation = Objects.toString(proposal.get("message"), "请核对操作草稿");
String explanation = draftSummary(draft);
explanation += projectCandidateSummary(prepared);
if (!parkedIds(state).isEmpty()) explanation += "\n其他未完成草稿已暂存,可点击“继续处理”返回,不必重新录入。";
explanation += Boolean.TRUE.equals(draft.get("ready"))
@ -533,16 +543,26 @@ public class AssistantConversationService {
}
private Map<String, Object> restoreParked(Map<String, Object> state, Long id, String text) {
return restoreParked(state, id, text, null);
}
private Map<String,Object> parkedPlan(Map<String,Object> state, Long id) {
if (!parkedIds(state).contains(id)) throw new ServiceException("该暂存草稿当前不可恢复,请刷新会话后选择。", 403);
AiCommand source = requireCommand(id, false); Map<String, Object> plan = plan(source);
if (!Boolean.TRUE.equals(plan.get("paused")) || !Objects.equals(plan.get("sessionId"), state.get("id")))
throw new ServiceException("暂存任务已更新,请刷新会话后核对。");
verifyDraftPermissions(plan); actions.requireActionPermission(source.getAction());
Map<String, Object> prepared = prepare(source.getAction(), maps(plan.get("rows")));
return plan;
}
private Map<String, Object> restoreParked(Map<String, Object> state, Long id, String text, List<Map<String,Object>> updatedRows) {
Map<String,Object> plan = parkedPlan(state, id);
String action = Objects.toString(plan.get("action"), "");
Map<String, Object> prepared = prepare(action, updatedRows == null ? maps(plan.get("rows")) : updatedRows);
List<Long> remaining = new ArrayList<>(parkedIds(state)); remaining.remove(id);
state.put("parkedDraftIds", remaining);
Map<String, Object> restored;
try { restored = switchDraft(state, source.getAction(), prepared, text, maps(plan.get("sources")), false); }
try { restored = switchDraft(state, action, prepared, text, maps(plan.get("sources")), false); }
catch (RuntimeException error) { remaining.add(id); state.put("parkedDraftIds", remaining); throw error; }
// The original stays non-executable; only the freshly checked card can be confirmed.
cancelInternal(id, null);
@ -558,12 +578,41 @@ public class AssistantConversationService {
static Map<String, Object> resumeProposal(String text, List<Map<String, Object>> parked) {
String instruction = text.replaceAll("[\\s,,。.!!??]", "");
if (!instruction.matches("(?:(?:单位|类别)(?:已经|已)?(?:加好了|补好了|建好了))?(?:继续|恢复|回到|接着)(?:刚才的?|之前的?|原来的?|上一个)?(?:采购|移库|借用|入库|盘点|生产|任务|草稿)(?:清单|业务|草稿|任务)?")) return null;
var match = java.util.regex.Pattern.compile("^(?:(?:单位|类别)(?:已经|已)?(?:加好了|补好了|建好了))?(?:继续|恢复|回到|接着)(?:刚才的?|之前的?|原来的?|上一个)?(?:采购|移库|借用|入库|盘点|生产|任务|草稿)(?:清单|业务|草稿|任务)?").matcher(instruction);
if (!match.find() || instruction.matches(".*(?:怎么|如何|是否|吗).*")) return null;
String tail = instruction.substring(match.end());
String family = instruction.contains("采购") ? "purchase." : instruction.contains("移库") ? "stock.move" : instruction.contains("借用") ? "loan." : instruction.contains("入库") ? "receipt." : instruction.contains("盘点") ? "stockCheck." : instruction.contains("生产") ? "production." : "";
List<Map<String, Object>> matches = parked.stream().filter(task -> family.isBlank() || Objects.toString(task.get("action"), "").startsWith(family)).toList();
if (matches.isEmpty()) return null;
if (matches.size() > 1) return Map.of("kind", "clarify", "message", "有多份相关草稿已暂存,请在“暂存任务”中选择要继续的那一份;原数据都还在。");
return Map.of("kind", "resume", "draftId", matches.get(0).get("id"));
return Map.of("kind", "resume", "draftId", matches.get(0).get("id"), "withChanges", !tail.isBlank());
}
static String draftSummary(Map<String,Object> draft) {
return "已整理" + Objects.toString(draft.get("label"), "业务") + "草稿,共 " + maps(draft.get("rows")).size() + " 项。请以下方确认单为准,尚未执行业务。";
}
/** Resolve a short area alias only against this user's last visible stock result, then requery normally. */
static Map<String,Object> areaFollowup(String text, Object previous) {
if (!(previous instanceof Map<?,?> query) || !"stock.query".equals(query.get("action"))) return null;
var match = java.util.regex.Pattern.compile("^(?:那|现在|这次|请|帮我|就|只|仅|看|查一下|查询|查|筛选|一下|换成)*\\s*([A-Za-z0-9]+)\\s*区(?:呢|吧|的|就行)?[??。!!]*$").matcher(text.trim());
if (!match.matches()) return null;
List<Map<String,Object>> conditions = maps(query.get("rows"));
if (conditions.size()!=1) return null;
String alias=match.group(1).toLowerCase(Locale.ROOT);
Map<String,String> choices=new LinkedHashMap<>();
for (Map<String,Object> result:maps(query.get("results"))) {
if (!(result.get("data") instanceof Map<?,?> data)) continue;
for (Map<String,Object> row:maps(data.get("rows"))) {
String name=Objects.toString(row.get("areaName"), ""), normalized=name.toLowerCase(Locale.ROOT);
if (normalized.equals(alias+"区") || normalized.equals(alias) || normalized.endsWith("-"+alias) || normalized.endsWith("_"+alias) || normalized.endsWith("/"+alias) || normalized.endsWith("-"+alias+"区"))
choices.put(Objects.toString(row.get("areaId"), name), name);
}
}
if (choices.isEmpty()) return null;
if (choices.size()>1) return Map.of("kind","clarify","message","刚才结果中有多个相关库区:"+String.join("、", choices.values())+"。请补充完整库区名称,其他查询条件会保留。");
Map<String,Object> row=businessFields(conditions.get(0)); row.put("areaId", Map.of("keyword", choices.values().iterator().next())); row.put("pageNum", 1);
return Map.of("kind","query","action","stock.query","rows",List.of(row));
}
/** Read-only classification comes exclusively from the server registry, never the model's kind. */

View File

@ -51,6 +51,8 @@ public class AssistantModelClient {
messages = recentConversation(messages);
Map<String, Object> lastQuery = task.get("lastQuery") instanceof Map<?, ?> query ? stringKeyed(query) : Map.of();
String latestText = latestUserText(messages);
Map<String,Object> permissionExport = files.isEmpty() ? permissionExportReply(latestText, actions) : null;
if (permissionExport != null) return permissionExport;
Map<String, Object> participantReply = files.isEmpty() ? participantReply(latestText) : null;
if (participantReply != null) return participantReply;
// A module name alone in a new conversation never authorizes a list query or a write.
@ -190,6 +192,16 @@ public class AssistantModelClient {
throw new ServiceException("识别到的用户行数与要求的"+expected+"人不一致,尚未提交;请重新识别或提供逐行表格,系统不会只创建部分用户。");
}
static Map<String,Object> permissionExportReply(String text, List<Map<String,Object>> actions) {
if (!text.matches("(?s).*(?:导出|下载).*" ) || !text.contains("用户") || !text.contains("权限")
|| text.matches("(?s).*(?:不要|不用|无需|不需要|别)(?:导出|下载).*")) return null;
Map<String,Object> definition=actions.stream().filter(action->"user.permissions".equals(action.get("key"))).findFirst().orElse(null);
if (definition==null) return null;
if (Boolean.FALSE.equals(definition.get("allowed"))) return Map.of("kind","answer","message",
Objects.toString(definition.get("deniedReason"), AssistantMessages.NOT_ENABLED));
return Map.of("kind","clarify","intentAction","user.permissions","message","目前可以查询指定账号实际生效的菜单和按钮权限,暂不支持全部用户权限的Excel导出。你想先查看哪个账号?");
}
/** Business columns outside the clear item crop are read separately; original item cells stay fixed. */
private Map<String,Object> mapTranscribedRows(JSONObject context,Map<String,Object> selected,Map<String,Object> file,
List<Map<String,Object>> sourceRows,String instruction,String diagnosticId,long started) {

View File

@ -128,7 +128,7 @@ public class BusinessActionRegistry {
Action definition=action(key);
if(!definition.query())throw new ServiceException("该操作会修改业务数据,必须先预览并人工确认");
requireActionPermission(key);
Map<String,Object> row=prepareRow(definition,input);
Map<String,Object> row=prepareRow(definition,com.ruoyi.common.utils.SearchQueryNormalizer.normalize(input));
List<?> errors=(List<?>)row.get("_errors");
if(!errors.isEmpty())throw new ServiceException(errors.stream().map(Object::toString).collect(Collectors.joining(";")));
return tabular(definition,invoke(definition,payload(definition,row)),row);

View File

@ -0,0 +1,59 @@
package com.ruoyi.common;
import com.ruoyi.common.filter.SearchQueryFilter;
import com.ruoyi.common.utils.SearchQueryNormalizer;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.jupiter.api.Assertions.*;
class SearchQueryNormalizerTest {
@Test void unicodeEdgesOnly() {
for(String edge:List.of(" ","\t\r\n","\u3000","\u00a0","\u202f","\ufeff","\u200b","\u0085"))
assertEquals("TP-LINK 路由器 AX 5400",SearchQueryNormalizer.trimEdges(edge+"TP-LINK 路由器 AX 5400"+edge));
assertEquals("a b",SearchQueryNormalizer.trimEdges(" a b "));
assertEquals("",SearchQueryNormalizer.trimEdges(" \u3000\u200b "));
assertNull(SearchQueryNormalizer.trimEdges(null));
}
@Test void aiReadOnlyInputsAreCopiedAndSecretsProtected() {
Map<String,Object> original=Map.of("productName"," 路由器 ","params",Map.of("keyword"," TP "),"names",List.of(" A B ",0),"password"," secret ","fileName"," a.pdf ");
var normalized=SearchQueryNormalizer.normalize(original);
assertEquals("路由器",normalized.get("productName"));assertEquals(" 路由器 ",original.get("productName"));
assertEquals(Map.of("keyword","TP"),normalized.get("params"));assertEquals(List.of("A B",0),normalized.get("names"));
assertEquals(" secret ",normalized.get("password"));assertEquals(" a.pdf ",normalized.get("fileName"));
assertEquals(" keep ",SearchQueryNormalizer.parameter("params[accessToken]"," keep "));
}
@Test void directHttpSearchAndExportCannotBypassNormalization() throws Exception {
for(String method:List.of("GET","POST")){
var request=new MockHttpServletRequest(method,method.equals("GET")?"/warehouse/product/list":"/warehouse/product/export");
request.addParameter("productName"," \u3000路由器\u200b ");request.addParameter("brand"," TP "," AC ME ");request.addParameter("token"," token ");
new SearchQueryFilter().doFilter(request,new MockHttpServletResponse(),(incoming,response)->{
var clean=(HttpServletRequest)incoming;
assertEquals("路由器",clean.getParameter("productName"));assertArrayEquals(new String[]{"TP","AC ME"},clean.getParameterValues("brand"));
assertEquals(" token ",clean.getParameter("token"));assertEquals("路由器",clean.getParameterMap().get("productName")[0]);
var copy=clean.getParameterValues("brand");copy[0]="changed";assertEquals("TP",clean.getParameter("brand"));
assertEquals(" \u3000路由器\u200b ",request.getParameter("productName"));
});
}
}
@Test void mutationsLoginDownloadsAndCollaborationAreUntouched() throws Exception {
for(String path:List.of("/project/manage/projects","/warehouse/product","/system/user/resetPwd","/login","/common/download")){
String method=path.equals("/project/manage/projects")||path.equals("/common/download")?"GET":"POST";
var request=new MockHttpServletRequest(method,path);request.addParameter("keyword"," keep ");request.setContent("{\"password\":\" secret \"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
new SearchQueryFilter().doFilter(request,new MockHttpServletResponse(),(incoming,response)->assertSame(request,incoming));
}
assertTrue(SearchQueryNormalizer.applies("/project/loans","GET"));
assertTrue(SearchQueryNormalizer.applies("/system/user/list","GET"));
assertFalse(SearchQueryNormalizer.applies("/project/manage/projects","GET"));
}
@Test void earlierSecurityWrappersAreNotBypassed() throws Exception {
var raw=new MockHttpServletRequest("GET","/system/user/list");raw.addParameter("userName"," unsafe ");
var protectedRequest=new jakarta.servlet.http.HttpServletRequestWrapper(raw){
@Override public String[] getParameterValues(String name){return new String[]{" sanitized "};}
};
new SearchQueryFilter().doFilter(protectedRequest,new MockHttpServletResponse(),(incoming,response)->assertEquals("sanitized",incoming.getParameter("userName")));
}
}

View File

@ -0,0 +1,35 @@
package com.ruoyi.web.service.assistant;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class AssistantFollowupRegressionTest {
@Test void resumeWithChangesTargetsOneSavedTaskAndAmbiguityNeverGuesses() {
var tasks=List.<Map<String,Object>>of(Map.of("id",7L,"action","purchase.create"));
var request=AssistantConversationService.resumeProposal("回到刚才的采购,不要新建单。单位暂时用个,保留其他数据,只预览",tasks);
assertEquals(7L,request.get("draftId"));assertEquals(true,request.get("withChanges"));
assertEquals(false,AssistantConversationService.resumeProposal("继续采购",tasks).get("withChanges"));
assertNull(AssistantConversationService.resumeProposal("不要恢复采购",tasks));
assertNull(AssistantConversationService.resumeProposal("如何恢复采购",tasks));
assertEquals("clarify",AssistantConversationService.resumeProposal("继续采购,单位用个",List.of(tasks.get(0),Map.of("id",8L,"action","purchase.create"))).get("kind"));
}
@Test void shortAreaIsGroundedInVisibleResultsAndKeepsOtherFilters() {
var query=Map.<String,Object>of("action","stock.query","rows",List.of(Map.of("projectId",1,"productName","电机","pageNum",2)),
"results",List.of(Map.of("data",Map.of("rows",List.of(Map.of("areaId",2,"areaName","测试1017-B"),Map.of("areaId",3,"areaName","测试1017-A"))))));
var proposal=AssistantConversationService.areaFollowup("那只看B区呢?",query);
var row=AssistantConversationService.maps(proposal.get("rows")).get(0);
assertEquals(1,row.get("projectId"));assertEquals("电机",row.get("productName"));assertEquals(1,row.get("pageNum"));assertEquals(Map.of("keyword","测试1017-B"),row.get("areaId"));
assertNull(AssistantConversationService.areaFollowup("B区借给另一个项目",query));
assertNull(AssistantConversationService.areaFollowup("那只看C区呢",query));
var duplicate=new LinkedHashMap<>(query);duplicate.put("results",List.of(Map.of("data",Map.of("rows",List.of(Map.of("areaId",2,"areaName","一号-B"),Map.of("areaId",4,"areaName","二号-B"))))));
assertEquals("clarify",AssistantConversationService.areaFollowup("只看B区",duplicate).get("kind"));
}
@Test void countAndPermissionResponsesComeFromServerFacts() {
assertTrue(AssistantConversationService.draftSummary(Map.of("label","采购","rows",List.of(Map.of(),Map.of()))).contains("共 2 项"));
var denied=Map.<String,Object>of("key","user.permissions","allowed",false,"deniedReason","请管理员协助查询。");
assertEquals("请管理员协助查询。",AssistantModelClient.permissionExportReply("把刚才查不到的所有用户权限导出Excel",List.of(denied)).get("message"));
assertNull(AssistantModelClient.permissionExportReply("不要导出用户权限",List.of(denied)));
var allowed=Map.<String,Object>of("key","user.permissions","allowed",true);
assertTrue(AssistantModelClient.permissionExportReply("导出所有用户权限",List.of(allowed)).get("message").toString().contains("暂不支持"));
}
}

View File

@ -433,12 +433,36 @@ class AssistantSessionPermissionTest {
return input.stream().map(row -> { var copy = new LinkedHashMap<>(row); copy.put("_snapshot", Map.of()); return (Map<String,Object>) copy; }).toList();
}
@Test void restoreWithUnitChangeConsumesOriginalParkedTaskWithoutParallelDrafts() {
emptySession();
Map<Long,AiCommand> database=new HashMap<>();var sequence=new java.util.concurrent.atomic.AtomicLong(20);
when(commands.insertAiCommand(any())).thenAnswer(i->{AiCommand command=i.getArgument(0);command.setId(sequence.incrementAndGet());database.put(command.getId(),command);return 1;});
when(commands.selectAssistantCommand(anyLong(),eq(10L))).thenAnswer(i->database.get(i.getArgument(0)));
when(commands.selectAiCommandForUpdate(anyLong(),eq(10L))).thenAnswer(i->database.get(i.getArgument(0)));
when(actions.prepare(anyString(),anyList())).thenAnswer(i->Map.of("label","测试草稿","rows",mapsWithSnapshots(i.getArgument(1)),"ready",true,"fields",List.of(),"errors",List.of()));
when(model.propose(anyList(),anyList(),anyMap(),anyMap(),anyList()))
.thenReturn(Map.of("kind","draft","action","purchase.create","rows",List.of(Map.of("materialName","原支架","quantity",3,"finalUnitPrice",12,"materialParams","B18","unit","缺少单位"))))
.thenReturn(Map.of("kind","draft","action","dictionary.create","rows",List.of(Map.of("dictLabel","缺少单位"))))
.thenReturn(Map.of("kind","patch","action","purchase.create","changes",Map.of("unit","个")));
var original=service.message(Map.of("sessionId",sessionId,"text","采购3个支架,单位缺少单位"));
Long originalId=((Number)original.get("draftId")).longValue();
var unit=service.message(Map.of("sessionId",sessionId,"text","先新增缺少单位,保留采购"));
service.cancel(((Number)unit.get("draftId")).longValue(),1);
var resumed=service.message(Map.of("sessionId",sessionId,"text","回到刚才的采购,不要新建单,单位暂时用个,保留其他数据,只预览"));
assertTrue(AssistantConversationService.maps(resumed.get("parkedDrafts")).isEmpty());
var draft=(Map<?,?>)resumed.get("draft");var row=AssistantConversationService.maps(draft.get("rows")).get(0);
assertEquals("个",row.get("unit"));assertEquals("原支架",row.get("materialName"));assertEquals("B18",row.get("materialParams"));assertEquals(3,((Number)row.get("quantity")).intValue());assertEquals(12,((Number)row.get("finalUnitPrice")).intValue());
assertFalse(Boolean.TRUE.equals(JSON.parseObject(database.get(originalId).getPlanJson()).get("paused")));
assertEquals(1,database.values().stream().filter(command->!Set.of("CANCELLED","SUCCEEDED").contains(command.getCommandStatus())).count());
verify(actions,never()).execute(anyString(),anyMap());
}
@Test void resumeCannotReadArbitraryCommandAndAmbiguousSavedPurchasesNeedSelection() {
emptySession(); assertThrows(ServiceException.class, () -> service.resume(sessionId, 999L));
verify(commands, never()).selectAssistantCommand(eq(999L), anyLong());
var paused = List.<Map<String,Object>>of(Map.of("id", 7L, "action", "purchase.create"), Map.of("id", 8L, "action", "purchase.create"));
assertEquals("clarify", AssistantConversationService.resumeProposal("继续采购", paused).get("kind"));
assertNull(AssistantConversationService.resumeProposal("继续采购,全部数量改成20", paused));
assertEquals("clarify", AssistantConversationService.resumeProposal("继续采购,全部数量改成20", paused).get("kind"));
assertEquals(7L, AssistantConversationService.resumeProposal("单位加好了,继续采购", paused.subList(0,1)).get("draftId"));
}

View File

@ -0,0 +1,37 @@
package com.ruoyi.common.filter;
import com.ruoyi.common.utils.SearchQueryNormalizer;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.web.filter.OncePerRequestFilter;
/** Query/filter parameters only; collaboration routes and business writes stay untouched. */
public class SearchQueryFilter extends OncePerRequestFilter {
@Override protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI().substring(request.getContextPath().length());
return !SearchQueryNormalizer.applies(path,request.getMethod());
}
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
Map<String,String[]> values = new LinkedHashMap<>();
// Preserve any preceding security wrapper's sanitized parameter values.
request.getParameterMap().forEach((name,array) -> values.put(name,java.util.Arrays.stream(request.getParameterValues(name))
.map(value -> SearchQueryNormalizer.parameter(name,value)).toArray(String[]::new)));
chain.doFilter(new HttpServletRequestWrapper(request) {
@Override public String getParameter(String name) { String[] array=values.get(name);return array==null||array.length==0?null:array[0]; }
@Override public String[] getParameterValues(String name) { String[] array=values.get(name);return array==null?null:array.clone(); }
@Override public Enumeration<String> getParameterNames() { return Collections.enumeration(values.keySet()); }
@Override public Map<String,String[]> getParameterMap() {
Map<String,String[]> copy=new LinkedHashMap<>();values.forEach((name,array)->copy.put(name,array.clone()));return Collections.unmodifiableMap(copy);
}
},response);
}
}

View File

@ -0,0 +1,56 @@
package com.ruoyi.common.utils;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/** Search-only boundary whitespace cleanup. Never apply to mutation payloads. */
public final class SearchQueryNormalizer {
private SearchQueryNormalizer() { }
private static final Set<String> PROTECTED = Set.of("authorization", "secret", "secretkey", "signature", "sign", "key", "filename", "filepath", "path", "url", "redirect", "redirecturl");
public static boolean protectedField(String field) {
String[] parts = field.split("[.\\[\\]]");
String name = "";
for (String part : parts) if (!part.isEmpty()) name = part.toLowerCase(Locale.ROOT);
return name.endsWith("password") || name.endsWith("token") || PROTECTED.contains(name);
}
private static boolean edge(int codePoint) {
return Character.isWhitespace(codePoint) || Character.isSpaceChar(codePoint)
|| codePoint == 0x85 || codePoint == 0x200B || codePoint == 0xFEFF;
}
public static String trimEdges(String text) {
if (text == null) return null;
int start = 0, end = text.length();
while (start < end && edge(text.codePointAt(start))) start += Character.charCount(text.codePointAt(start));
while (end > start && edge(text.codePointBefore(end))) end -= Character.charCount(text.codePointBefore(end));
return text.substring(start, end);
}
public static String parameter(String name, String value) {
return protectedField(name) ? value : trimEdges(value);
}
public static Map<String,Object> normalize(Map<String,Object> source) {
if (source == null) return null;
Map<String,Object> result = new LinkedHashMap<>();
source.forEach((key,value) -> result.put(key, normalizeValue(key,value)));
return result;
}
private static Object normalizeValue(String name, Object value) {
if (protectedField(name)) return value;
if (value instanceof String text) return trimEdges(text);
if (value instanceof List<?> list) return list.stream().map(item -> normalizeValue(name,item)).toList();
if (value instanceof Map<?,?> map) {
Map<String,Object> result = new LinkedHashMap<>();
map.forEach((key,item) -> result.put(key.toString(),normalizeValue(key.toString(),item)));
return result;
}
return value;
}
public static boolean applies(String path, String method) {
boolean owned = path.matches("^/(warehouse|production|system|monitor)/.*")
|| path.matches("^/project/(info|loans)(/.*)?$");
return owned && ("GET".equalsIgnoreCase(method)
|| "POST".equalsIgnoreCase(method) && path.matches(".*/export(/[^/]*)?$"));
}
}

View File

@ -22,6 +22,16 @@ import com.ruoyi.common.utils.StringUtils;
@Configuration
public class FilterConfig
{
@Bean
public FilterRegistrationBean<com.ruoyi.common.filter.SearchQueryFilter> searchQueryFilterRegistration()
{
var registration = new FilterRegistrationBean<>(new com.ruoyi.common.filter.SearchQueryFilter());
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.addUrlPatterns("/*");
registration.setName("searchQueryFilter");
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 20);
return registration;
}
@Value("${xss.excludes}")
private String excludes;

View File

@ -1,11 +1,12 @@
<template>
<remote-picker :model-value="modelValue" :item="item" :disabled="disabled" :fetch-page="fetchPage" :option-key="optionKey" :label="label" :selected-label="p=>p.productName" placeholder="搜索名称、品牌或规格" @update:model-value="$emit('update:modelValue',$event)" @change="$emit('change',$event)" />
<remote-picker :model-value="modelValue" :item="item" :disabled="disabled" :fetch-page="fetchPage" :option-key="optionKey" :label="label" :selected-label="p=>p.productName" create-label="物品" :create-href="createHref" placeholder="搜索名称、品牌或规格" @update:model-value="$emit('update:modelValue',$event)" @change="$emit('change',$event)" />
</template>
<script>
import RemotePicker from './RemotePicker.vue'
import { itemOptionPage } from '@/api/production/bom'
export default {
name:'BomItemPicker',components:{RemotePicker},props:{modelValue:[Number,String],item:Object,disabled:Boolean},emits:['update:modelValue','change'],
computed:{createHref(){return this.$can(['warehouse:product:add'])?this.$router.resolve({path:'/businessBasics/product',query:{create:'1'}}).href:''}},
methods:{optionKey(p){return p.id},label(p){return [p.productName,p.brand,p.spec,p.unit].filter(Boolean).join(' / ')},fetchPage({keyword,...params}){return itemOptionPage({...params,productName:keyword})}}
}
</script>

View File

@ -1,12 +1,12 @@
<template>
<remote-picker :model-value="modelValue" :item="normalizedItem" :disabled="disabled" :fetch-page="fetchPage" :option-key="optionKey" :label="label" placeholder="搜索产品名称、品牌或规格" @update:model-value="$emit('update:modelValue',$event)" @change="$emit('change',$event)" />
<remote-picker :model-value="modelValue" :item="normalizedItem" :disabled="disabled" :fetch-page="fetchPage" :option-key="optionKey" :label="label" create-label="产品" :create-href="createHref" placeholder="搜索产品名称、品牌或规格" @update:model-value="$emit('update:modelValue',$event)" @change="$emit('change',$event)" />
</template>
<script>
import RemotePicker from './RemotePicker.vue'
import { productOptionPage } from '@/api/production/bom'
export default {
name:'ProductionProductPicker',components:{RemotePicker},props:{modelValue:[Number,String],item:Object,disabled:Boolean},emits:['update:modelValue','change'],
computed:{normalizedItem(){return this.item?this.normalize(this.item):null}},
computed:{normalizedItem(){return this.item?this.normalize(this.item):null},createHref(){return this.$can(['production:product:edit'])?this.$router.resolve({path:'/businessBasics/products',query:{create:'1'}}).href:''}},
methods:{normalize(p){return {...p,itemId:p.itemId??p.id,itemName:p.itemName||p.productName}},optionKey(p){return p.itemId},label(p){return [p.itemName,p.brand,p.spec,p.unit].filter(Boolean).join(' / ')},async fetchPage(params){const r=await productOptionPage(params);return {...r,rows:(r.rows||[]).map(this.normalize)}}}
}
</script>

View File

@ -1,20 +1,25 @@
<template>
<el-select :model-value="modelValue" filterable remote clearable :remote-method="search" :loading="loading && page===0" :disabled="disabled" :placeholder="placeholder" style="width:100%" @update:model-value="$emit('update:modelValue',$event)" @change="changed">
<el-select ref="select" :model-value="modelValue" filterable remote clearable :remote-method="search" :loading="loading && page===0" :disabled="disabled" :placeholder="placeholder" style="width:100%" @visible-change="open=>open&&loadPage(1)" @update:model-value="$emit('update:modelValue',$event)" @change="changed">
<el-option v-for="option in options" :key="optionKey(option)" :value="optionKey(option)" :label="(selectedLabel||label)(option)"><span :title="label(option)">{{ label(option) }}</span></el-option>
<template #empty><div class="picker-footer">{{ loading ? '正在加载' : failed ? '加载失败' : '没有匹配结果' }}</div></template>
<template #footer>
<div class="picker-footer" @mousedown.prevent>
<div v-if="failed || hasMore || total || !createLabel" class="picker-footer" @mousedown.prevent>
<el-button v-if="failed" link type="danger" @click="loadPage(page+1)">加载失败,重试</el-button>
<el-button v-else-if="hasMore" link type="primary" :loading="loading" @click="loadPage(page+1)">加载更多({{ loaded }} / {{ total }})</el-button>
<span v-else>{{ total ? '共 '+total+' 项' : '没有匹配结果' }}</span>
</div>
<div v-if="createLabel && !disabled" class="picker-create" @mousedown.prevent>
<span>没有合适的{{ createLabel }}?</span>
<a v-if="createHref" :href="createHref" target="_blank" rel="noopener noreferrer" title="在新标签页创建,当前填写内容会保留" @click="$refs.select.blur()">去创建<span class="create-hint">(新标签页)</span></a>
<span v-else>可请负责人协助维护</span>
</div>
</template>
</el-select>
</template>
<script>
import { runLatest, invalidateQuery } from '@/utils/query-session'
export default {
props:{modelValue:[Number,String],item:Object,disabled:Boolean,placeholder:String,fetchPage:{type:Function,required:true},optionKey:{type:Function,required:true},label:{type:Function,required:true},selectedLabel:Function},
props:{modelValue:[Number,String],item:Object,disabled:Boolean,placeholder:String,fetchPage:{type:Function,required:true},optionKey:{type:Function,required:true},label:{type:Function,required:true},selectedLabel:Function,createLabel:String,createHref:String},
emits:['update:modelValue','change'],
data:()=>({rows:[],selected:null,keyword:'',page:0,total:0,loaded:0,loading:false,failed:false}),
computed:{options(){const values=new Map(this.rows.map(row=>[String(this.optionKey(row)),row]));if(this.selected&&this.modelValue!=null)values.set(String(this.optionKey(this.selected)),this.selected);return [...values.values()]},hasMore(){return this.loaded<this.total}},
@ -27,4 +32,4 @@ export default {
}
}
</script>
<style scoped>.picker-footer{min-height:26px;color:var(--el-text-color-secondary);font-size:12px;text-align:center}</style>
<style scoped>.picker-footer{min-height:26px;color:var(--el-text-color-secondary);font-size:12px;text-align:center}.picker-create{display:flex;flex-wrap:wrap;justify-content:center;gap:4px;font-size:12px;line-height:22px;padding:6px 0 2px;color:var(--el-text-color-regular);border-top:1px solid var(--el-border-color-lighter)}.picker-create a{color:var(--el-color-primary);text-decoration:none}.picker-create a:hover{text-decoration:underline}.create-hint{color:var(--el-text-color-secondary);font-size:11px}</style>

View File

@ -14,6 +14,7 @@
</el-form>
<el-button v-if="!readonly" :disabled="saving || loading" size="small" type="primary" plain icon="el-icon-plus" class="mb8" @click="addLine">添加用料</el-button>
<el-button v-if="!readonly" :disabled="saving || loading" size="small" class="mb8" @click="$refs.excelLines.open(form)">导入</el-button>
<business-page-header v-if="!readonly" title="BOM填写" guide="找不到合适的产品或物品?在对应选择框底部点「去创建」,当前填写会保留;回来重新展开选项即可刷新。单台用量是生产 1 件产品所需的用量。" />
</template>
<template #default="{tableHeight}">
<el-table ref="linesTable" :data="form.lines" border :height="tableHeight" :row-class-name="({row})=>row._error?'bom-error-row':''">

View File

@ -1,5 +1,9 @@
<template>
<header v-if="$slots.actions" class="business-page-header">
<header v-if="guide || $slots.actions" class="business-page-header" :class="{ 'guide-only': guide && !$slots.actions }">
<el-popover v-if="guide" v-model:visible="guideOpen" :trigger="['hover','focus']" :show-after="120" :hide-after="100" placement="bottom-end" role="tooltip" :title="title+' · 操作指引'" :width="300" popper-class="business-guide-popover">
<p class="business-guide-content" role="note">{{ guide }}</p>
<template #reference><button type="button" class="guide-button" :aria-label="title+'操作指引'"><svg viewBox="0 0 20 20" width="16" height="16" fill="none" aria-hidden="true"><circle cx="10" cy="10" r="7.25" stroke="currentColor" stroke-width="1.3"/><path d="M10 6.4v4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><circle cx="10" cy="13.5" r=".85" fill="currentColor"/></svg></button></template>
</el-popover>
<div v-if="$slots.actions" class="business-page-header__actions"><slot name="actions" /></div>
</header>
</template>
@ -7,11 +11,24 @@
<script>
export default {
name: 'BusinessPageHeader',
data:()=>({guideOpen:false}),
watch:{guide(){this.guideOpen=false}},
props: {
title: { type: String, required: true },
description: { type: String, default: '' },
guide: { type: String, default: '' },
icon: { type: String, default: '' },
tone: { type: String, default: 'blue' }
}
}
</script>
<style scoped>
.guide-only { display: inline-flex; flex: none; min-height: 0; margin: 0 0 0 10px; vertical-align: middle; }
.guide-button { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; padding: 5px; border: 0; border-radius: 5px; background: transparent; color: var(--el-text-color-secondary); cursor: help; transition: color .15s, background-color .15s; }
.guide-button:hover, .guide-button:focus-visible { color: var(--el-color-primary); background: var(--el-color-primary-light-9); }
.guide-button:focus-visible { outline: 2px solid var(--el-color-primary-light-5); outline-offset: 2px; }
.business-guide-content { margin: 0; color: var(--el-text-color-regular); font-size: 13px; line-height: 21px; overflow-wrap: anywhere; }
:global(.business-guide-popover) { max-width: calc(100vw - 24px); padding: 12px 14px; border-radius: 6px; font-family: var(--el-font-family); }
:global(.business-guide-popover .el-popover__title) { margin-bottom: 6px; color: var(--el-text-color-primary); font-size: 13px; font-weight: 600; line-height: 20px; }
</style>

View File

@ -1,5 +1,5 @@
<template><el-dialog :title="fixedKind ? operationTitle : '批量操作'" v-model="visible" width="min(1000px,98vw)" :fullscreen="compact" class="stock-batch-dialog" append-to-body :close-on-click-modal="!saving" :close-on-press-escape="!saving" :show-close="!saving">
<dialog-workspace>
<dialog-workspace :style="workspaceStyle">
<template #header>
<el-form :inline="!compact" :disabled="saving" label-width="80px" class="stock-operation-form">
<el-form-item v-if="!fixedKind" label="操作">
@ -25,7 +25,8 @@
<el-input v-model="remark" maxlength="500"/>
</el-form-item>
</el-form>
<batch-progress :total="runRows.length" :completed="completedCount" :failed="failedCount" :running="saving" v-model:onlyFailed="onlyFailed"/>
<batch-progress v-if="runRows.length" :total="runRows.length" :completed="completedCount" :failed="failedCount" :running="saving" v-model:onlyFailed="onlyFailed"/>
<div v-else class="stock-card-meta">待处理 {{ rows.length }} 项,请核对数量和目标信息后确认。</div>
</template>
<template #default="{tableHeight}">
<template v-if="compact">
@ -101,6 +102,7 @@ export default {
data:()=>({visible:false,saving:false,opening:false,fixedKind:false,onlyFailed:false,runRows:[],kind:'USE',rows:[],areas:[],date:'',reason:'',remark:'',recipient:'',toAreaId:undefined,taskContext:null}),
computed:{
operationTitle(){return labels[this.kind]||'库存操作'},
workspaceStyle(){return this.compact?{}:{height:`min(${Math.max(230,Math.min(620,155+this.rows.length*90))}px,calc(100dvh - 180px))`}},
displayRows(){return this.rows.filter(r=>!this.onlyFailed||r.failed)},
completedCount(){return this.runRows.filter(r=>r.done||r.failed).length},
failedCount(){return this.runRows.filter(r=>r.failed).length},

View File

@ -16,6 +16,7 @@
<el-form-item label="日期"><el-date-picker v-model="queryDates" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始" end-placeholder="结束" @change="search"/></el-form-item>
</template>
<template #business>
<business-page-header title="采购" guide="一批采购对应一个项目;物品可选已有档案,也可填名称、规格、品牌和单位,保存时自动建档。" />
<el-button type="primary" plain size="small" icon="el-icon-plus" :disabled="loading||saving||creating" @click="create(false)" v-if="$can(['warehouse:purchase:add','warehouse:purchase:manage'])">新增采购批次</el-button>
<el-button size="small" icon="el-icon-plus" :disabled="loading||saving||creating" @click="create(true)" v-if="$can(['warehouse:purchase:add','warehouse:purchase:manage'])">新增未组批</el-button>

View File

@ -6,6 +6,7 @@ import { tansParams, blobValidate } from '@/utils/ruoyi'
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
import useUserStore from '@/store/modules/user'
import { isSearchRequest, normalizeSearchQuery } from '@/utils/search-query'
// 是否显示重新登录
export let isRelogin = { show: false }
@ -32,6 +33,10 @@ function releaseFailedSubmission(config) {
// request拦截器
service.interceptors.request.use(config => {
if (isSearchRequest(config.url, config.method)) {
if (config.params) config.params = normalizeSearchQuery(config.params)
if (config.method === 'post' && config.data) config.data = normalizeSearchQuery(config.data)
}
if (['post', 'put', 'delete'].includes(config.method) && config.timeout === 10000) config.timeout = 30000
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false

View File

@ -0,0 +1,17 @@
// Normalize search boundaries, not saved business text or credentials.
const protectedField = name => /password$|token$|^(authorization|secret|secretkey|signature|sign|key|filename|filepath|path|url|redirect|redirecturl)$/i.test(String(name).split(/[.[\]]/).filter(Boolean).pop() || '')
export const trimSearchText = text => text.replace(/^[\s\u0085\u200b]+|[\s\u0085\u200b]+$/gu, '')
export function normalizeSearchQuery(value, field = '') {
if (protectedField(field)) return value
if (typeof value === 'string') return trimSearchText(value)
if (Array.isArray(value)) return value.map(item => normalizeSearchQuery(item, field))
if (value && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeSearchQuery(item, key)]))
}
return value
}
export function isSearchRequest(url, method = 'get') {
const path = String(url || '').split('?')[0].replace(/^\/(?:dev-api|prod-api)(?=\/)/, '')
const owned = /^\/(?:warehouse|production|system|monitor)\//.test(path) || /^\/project\/(?:info|loans)(?:\/|$)/.test(path)
return owned && (method.toLowerCase() === 'get' || method.toLowerCase() === 'post' && /\/export(?:\/[^/]*)?$/.test(path))
}

View File

@ -10,6 +10,7 @@
<el-button type="primary" size="small" icon="el-icon-search" @click="search">搜索</el-button>
<el-button size="small" icon="el-icon-refresh" :loading="loading" @click="load">刷新</el-button>
<el-button size="small" type="primary" plain icon="el-icon-plus" v-if="$can(['production:bom:edit'])" @click="$refs.editor.open()">新增</el-button>
<business-page-header title="BOM管理" guide="先在「产品档案」添加产品,再新建 BOM;用料选自「物品档案」,数量填写生产 1 件产品所需的用量。找不到合适选项时,可在选择框底部点「去创建」。" />
</el-form-item>
</el-form>
<el-alert v-if="loadError" :title="loadError" type="error" :closable="false">

View File

@ -2,7 +2,7 @@
<business-list-page class="app-container">
<template #header>
<business-page-header title="产品档案" description="从已有物品中标记产品并维护产品说明和默认BOM,不重复录入物品基础字段。" icon="el-icon-cpu" />
<el-form :inline="true" size="small" :disabled="saving"><el-form-item label="产品" :disabled="saving"><el-input v-model="query.keyword" clearable placeholder="名称、品牌或规格" @keyup.enter="search" /></el-form-item><el-form-item :disabled="saving"><el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button><el-button size="small" icon="el-icon-refresh" :loading="loading" @click="load">刷新</el-button><el-button size="small" type="primary" plain icon="el-icon-plus" v-if="$can(['production:product:edit'])" @click="edit()">新增</el-button></el-form-item></el-form>
<el-form :inline="true" size="small" :disabled="saving"><el-form-item label="产品" :disabled="saving"><el-input v-model="query.keyword" clearable placeholder="名称、品牌或规格" @keyup.enter="search" /></el-form-item><el-form-item :disabled="saving"><el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button><el-button size="small" icon="el-icon-refresh" :loading="loading" @click="load">刷新</el-button><el-button size="small" type="primary" plain icon="el-icon-plus" v-if="$can(['production:product:edit'])" @click="edit()">新增</el-button><business-page-header title="产品档案" guide="先在「物品档案」维护物品,再添加为产品;找不到合适物品时,可在选择框底部点「去创建」。" /></el-form-item></el-form>
<el-alert v-if="loadError" :title="loadError" type="error" :closable="false"><el-button link @click="load">重试</el-button></el-alert>
</template>
<template #default="{tableHeight}"><business-table :height="tableHeight" :data="rows" v-loading="loading">
@ -30,9 +30,12 @@ export default {
name: 'ProductionProduct', components: { BomEditor, ItemPicker },
data() { return { rows: [], total: 0, loading: false, loadError: '', loaded:false, query: { pageNum: 1, pageSize: 20, keyword: '' }, open: false, form: {}, selectedItem: null, saving: false,bomOpen:false,bomProduct:{},bomRows:[],bomLoading:false,bomSequence:0,defaultBusy:null } },
created() { this.load() },
mounted(){this.openCreateFromRoute()},
watch:{'$route.fullPath'(){this.openCreateFromRoute()}},
activated(){if(this.loaded && !this.loading)this.load()},
beforeUnmount(){invalidateQuery(this,'list')},
methods: {
openCreateFromRoute(){if(this.$route.path==='/businessBasics/products'&&this.$route.query.create==='1'&&!this._createRouteHandled&&!this.open&&!this.saving&&this.$can(['production:product:edit'])){this._createRouteHandled=true;this.edit()}},
asItem(row) { return { id: row.itemId, productCode: row.itemCode, productName: row.itemName, brand: row.brand, spec: row.spec, unit: row.unit } },
load() { return runLatest(this,'list',()=>listProducts({...this.query}), {start:()=>{this.loading=true;this.loadError=''},success:result=>{this.rows=result.rows||[];this.total=result.total||0;this.loaded=true},error:error=>{this.loadError=queryError(error)},finish:()=>{this.loading=false}}) },
openBoms(row){this.bomProduct={...row};this.bomRows=[];this.bomOpen=true;this.loadBoms()},

View File

@ -6,7 +6,7 @@
<el-form-item label="项目"><el-select v-model="queryProject" clearable filterable :disabled="!!projectId" @change="search"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName" /></el-select></el-form-item>
<el-form-item v-if="initialTab==='tasks'" label="任务 / 产品"><el-input v-model="query.keyword" clearable @keyup.enter="search"/></el-form-item>
<el-form-item v-if="initialTab==='tasks'" label="状态"><el-select v-model="query.status" clearable @change="search"><el-option label="生产中" value="OPEN"/><el-option label="待结算" value="READY"/><el-option label="已结算" value="SETTLED"/></el-select></el-form-item>
<template #actions><el-button v-if="initialTab==='tasks'" type="primary" icon="el-icon-search" @click="search">搜索</el-button><el-button icon="el-icon-refresh" @click="load">刷新</el-button></template>
<template #actions><el-button v-if="initialTab==='tasks'" type="primary" icon="el-icon-search" @click="search">搜索</el-button><el-button icon="el-icon-refresh" @click="load">刷新</el-button><business-page-header v-if="initialTab==='tasks'" title="生产" guide="先准备产品和 BOM,再选择项目建立任务;缺料可采购或借用,完工验收后到「待入库」办理成品入库。" /></template>
<template v-if="initialTab==='tasks'" #business><el-button type="primary" plain icon="el-icon-plus" @click="edit()" v-if="$canAll([['project:inventory:use'],['project:project:edit','project:project:manage']])">新建生产任务</el-button></template>
</query-toolbar>
</el-form>

View File

@ -16,7 +16,7 @@
<template #actions><el-form-item>
<el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
</el-form-item><right-toolbar @queryTable="getList" /></template>
</el-form-item><right-toolbar @queryTable="getList" /><business-page-header v-if="pendingOnly" title="待入库" guide="采购验收合格或生产完工验收后,记录才会进入待入库;选择实际存放库区并确认入库后,才计入库存。" /></template>
<template #advanced>
<el-form-item v-if="pendingOnly" label="物品名称" prop="productName"><el-input v-model="queryParams.productName" clearable @keyup.enter="handleQuery"/></el-form-item>
<el-form-item v-if="pendingOnly" label="供应商" prop="supplierId"><supplier-picker :show-manage="false" v-model="queryParams.supplierId"/></el-form-item>

View File

@ -106,6 +106,7 @@
<script>
import { runLatest, queryError } from '@/utils/query-session'
import request from '@/utils/request'
import { normalizeSearchQuery } from '@/utils/search-query'
import { defineAsyncComponent } from 'vue'
import { listProduct, getProduct, delProduct, addProduct, updateProduct, optionselectProduct } from '@/api/warehouse/product'
@ -150,7 +151,10 @@ export default {
this.getList()
this.getProductOptions()
},
mounted(){this.openCreateFromRoute()},
watch:{'$route.fullPath'(){this.openCreateFromRoute()}},
methods: {
openCreateFromRoute(){if(this.$route.path==='/businessBasics/product'&&this.$route.query.create==='1'&&!this._createRouteHandled&&!this.open&&!this.saving&&this.$can(['warehouse:product:add'])){this._createRouteHandled=true;this.handleAdd()}},
async openCategorySummary(){this.summaryOpen=true;this.summaryLoading=true;this.summaryRows=[];try{const {data}=await request({url:'/warehouse/product/category-summary',method:'get'});const groups=new Map();for(const row of data||[]){const id=Number(row.parentId||0);if(!groups.has(id))groups.set(id,{key:'group-'+id,label:row.parentLabel,parentId:id,itemCount:0,children:[]});const group=groups.get(id);group.itemCount+=Number(row.itemCount);group.children.push({...row,key:'leaf-'+id+'-'+row.category,label:row.category,itemCount:Number(row.itemCount)})}this.summaryRows=[...groups.values()]}finally{this.summaryLoading=false}},
filterSummary(row){this.resetForm('queryForm');this.queryParams.categoryGroupId=row.children?row.parentId:undefined;this.queryParams.category=row.children?undefined:row.category;this.summaryOpen=false;this.showSearch=true;this.$refs.filters.expand();this.handleQuery()},
getList() {
@ -176,7 +180,7 @@ getList() {
this.form = { id: undefined, productCode: undefined, productName: undefined, brand: undefined, category: undefined, spec: undefined, unit: undefined, remark: undefined }
this.resetForm('form')
},
handleQuery() { this.queryParams.pageNum = 1; this.getList() },
handleQuery() { this.queryParams = normalizeSearchQuery(this.queryParams); this.queryParams.pageNum = 1; this.getList() },
resetQuery() { this.resetForm('queryForm'); this.handleQuery() },
handleSelectionChange(selection) {
this.ids = selection.map(item => item.id)

View File

@ -19,7 +19,7 @@
<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>
</el-form-item><right-toolbar :gutter="0" @queryTable="refreshPurchaseData()" /></template>
</el-form-item><right-toolbar :gutter="0" @queryTable="refreshPurchaseData()" /><business-page-header title="到货验收" guide="先确认采购,再登记实际到货数量并验收;验收合格后到「待入库」办理入库,支持分次到货。" /></template>
<template #advanced>
<el-form-item v-if="arrivalMode" label="到货队列"><el-radio-group v-model="arrivalQueue" size="small" @change="applyArrivalQueue(arrivalQueueCards.find(item=>item.key===$event))"><el-radio-button v-for="item in arrivalQueueCards" :key="item.key" :value="item.key">{{ item.label }}</el-radio-button></el-radio-group></el-form-item>
<el-form-item v-if="!arrivalMode" label="采购状态" prop="purchaseStatus">

View File

@ -16,7 +16,7 @@
<template #actions><el-form-item>
<el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
</el-form-item><right-toolbar @queryTable="getList" /></template>
</el-form-item><right-toolbar @queryTable="getList" /><business-page-header title="库存盘点" guide="填写实际清点数量,不是差异数量;保存仅生成待确认记录,确认后才调整库存。" /></template>
<template #advanced>
<el-form-item label="品牌" prop="brand">
<el-select v-model="queryParams.brand" placeholder="请选择品牌" clearable filterable>

View File

@ -0,0 +1,71 @@
import { expect, it, vi } from 'vitest'
vi.mock('../../src/api/production/bom',()=>({itemOptionPage:vi.fn(),productOptionPage:vi.fn()}))
import { mount, flushPromises } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Header from '../../src/components/BusinessPageHeader/index.vue'
import ItemPicker from '../../src/components/BomEditor/ItemPicker.vue'
import ProductPicker from '../../src/components/BomEditor/ProductPicker.vue'
import RemotePicker from '../../src/components/BomEditor/RemotePicker.vue'
it('only opted-in pages display a short guide, without restoring all old descriptions', () => {
const wrapper = mount(Header, { props: { title: '普通列表', description: '原有长说明' } })
expect(wrapper.find('header').exists()).toBe(false)
wrapper.unmount()
})
it('guide is a subtle hover/focus hint that hides on leave and coexists with actions', async () => {
const wrapper = mount(Header, { props: { title: '产品档案', guide: '先维护物品,再添加产品。' }, slots: { actions: '<button class="create-action">新增</button>' }, global:{plugins:[ElementPlus]}, attachTo:document.body })
const trigger=wrapper.get('button[aria-label="产品档案操作指引"]')
expect(trigger.find('svg').exists()).toBe(true)
expect(trigger.attributes('aria-describedby')).toBeUndefined()
expect(wrapper.find('[role="note"]').exists()).toBe(false)
await trigger.trigger('mouseenter'); await flushPromises()
await vi.waitFor(()=>expect(wrapper.vm.guideOpen).toBe(true))
expect(document.querySelector('.business-guide-content')?.textContent).toBe('先维护物品,再添加产品。')
expect(wrapper.get('.create-action').text()).toBe('新增')
await trigger.trigger('mouseleave');await vi.waitFor(()=>expect(wrapper.vm.guideOpen).toBe(false))
await trigger.trigger('focus');await vi.waitFor(()=>expect(wrapper.vm.guideOpen).toBe(true))
await trigger.trigger('blur');await vi.waitFor(()=>expect(wrapper.vm.guideOpen).toBe(false))
await wrapper.setProps({ guide: '' })
expect(wrapper.find('.guide-button').exists()).toBe(false)
expect(wrapper.get('.create-action').text()).toBe('新增')
wrapper.unmount()
})
it('creation shortcuts honor the actual item/product write permission and target existing pages',()=>{
for(const [Component,permission,path] of [[ItemPicker,'warehouse:product:add','/businessBasics/product'],[ProductPicker,'production:product:edit','/businessBasics/products']]){
for(const allowed of [true,false]){
const wrapper=mount(Component,{global:{stubs:{RemotePicker:true},mocks:{$can:values=>allowed&&values.includes(permission),$router:{resolve:route=>({href:route.path+'?create='+route.query.create})}}}})
expect(wrapper.findComponent(RemotePicker).props('createHref')).toBe(allowed?path+'?create=1':'')
wrapper.unmount()
}
}
})
it('picker refreshes once when reopened without dropping the current selection or emitting a change',async()=>{
const selected={id:7,name:'原来选择的物品'}, calls=[]
const wrapper=mount(RemotePicker,{props:{modelValue:7,item:selected,fetchPage:async query=>{calls.push(query);return {rows:[],total:0}},optionKey:r=>r.id,label:r=>r.name},global:{stubs:{'el-select':{name:'ElSelect',template:'<div><slot/><slot name="footer"/></div>',methods:{blur(){}}},'el-option':true,'el-button':true}}})
await wrapper.findComponent({name:'ElSelect'}).vm.$emit('visible-change',true)
await flushPromises()
expect(calls).toHaveLength(1)
expect(wrapper.vm.selected).toEqual(selected)
expect(wrapper.emitted('change')).toBeUndefined()
wrapper.vm.search('新物品');await flushPromises()
expect(calls).toHaveLength(2)
wrapper.vm.loadPage(1);await flushPromises()
expect(calls).toHaveLength(3)
expect(calls[2].keyword).toBe('新物品')
wrapper.unmount()
})
it('a new-tab creation link is only shown on enabled pickers, with a gentle fallback otherwise',async()=>{
const wrapper=mount(RemotePicker,{props:{createLabel:'物品',createHref:'/businessBasics/product?create=1',fetchPage:async()=>({rows:[],total:0}),optionKey:r=>r.id,label:r=>r.name},global:{stubs:{'el-select':{template:'<div><slot name="footer"/></div>',methods:{blur(){}}},'el-button':true}}})
expect(wrapper.get('a').attributes('target')).toBe('_blank')
expect(wrapper.get('a').attributes('rel')).toContain('noopener')
await wrapper.setProps({createHref:''})
expect(wrapper.find('a').exists()).toBe(false)
expect(wrapper.text()).toContain('可请负责人协助维护')
await wrapper.setProps({disabled:true})
expect(wrapper.find('.picker-create').exists()).toBe(false)
wrapper.unmount()
})

View File

@ -0,0 +1,26 @@
import {expect,it,vi} from 'vitest'
const capture=vi.hoisted(()=>({request:null}))
vi.mock('axios',()=>({default:{defaults:{headers:{}},create:()=>({interceptors:{request:{use:fn=>{capture.request=fn}},response:{use:()=>{}}}})}}))
vi.mock('@/utils/auth',()=>({getToken:()=>null}))
vi.mock('@/store/modules/user',()=>({default:()=>({})}))
vi.mock('@/plugins/cache',()=>({default:{session:{getJSON:()=>undefined,setJSON:()=>{}}}}))
import '@/utils/request'
it('actual Axios interceptor cleans every owned query before URL encoding',()=>{
for(const path of ['/warehouse/product/list','/warehouse/stock/list','/production/bom/list','/project/info/options','/system/user/list']){
const original={productName:' \u3000路由器\u200b ',spec:' AX 5400 ',params:{beginTime:' 2026-10-01 '},empty:' \t ',pageNum:1}
const config=capture.request({url:path,method:'get',headers:{},params:original})
const params=new URL(config.url,'http://localhost').searchParams
expect(params.get('productName')).toBe('路由器');expect(params.get('spec')).toBe('AX 5400')
expect(params.get('params[beginTime]')).toBe('2026-10-01');expect(params.has('empty')).toBe(false)
expect(original.productName).toBe(' \u3000路由器\u200b ')
}
})
it('filtered exports agree with lists without changing mutation, credentials, or collaboration payloads',()=>{
const exported=capture.request({url:'/warehouse/product/export',method:'post',headers:{},data:{productName:' 路由器 '}})
expect(exported.data.productName).toBe('路由器')
const body={productName:' 新物品 ',remark:' 保留说明 ',password:' password '}
expect(capture.request({url:'/warehouse/product',method:'post',headers:{},data:body}).data).toBe(body)
const collaborative=capture.request({url:'/project/manage/projects',method:'get',headers:{},params:{keyword:' 原样 '}})
expect(new URL(collaborative.url,'http://localhost').searchParams.get('keyword')).toBe(' 原样 ')
})

View File

@ -0,0 +1,21 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {normalizeSearchQuery,isSearchRequest,trimSearchText} from '../../src/utils/search-query.js'
test('all search boundary whitespace is ignored, but internal spaces and punctuation survive',()=>{
for(const edge of [' ','\t\r\n','\u3000','\u00a0','\u202f','\ufeff','\u200b','\u0085'])assert.equal(trimSearchText(edge+'TP-LINK 路由器 AX 5400'+edge),'TP-LINK 路由器 AX 5400')
assert.equal(trimSearchText('a b'),'a b')
assert.equal(trimSearchText(' \u3000 '),'')
})
test('normalization is immutable, recursive and preserves values and credentials',()=>{
const original={productName:' 路由器 ',params:{beginTime:' 2026-10-01 ',names:[' 物品 A ',null,0]},enabled:false,password:' secret ',fileName:' report.pdf ',token:' bearer '}
const normalized=normalizeSearchQuery(original)
assert.equal(normalized.productName,'路由器');assert.equal(original.productName,' 路由器 ')
assert.deepEqual(normalized.params,{beginTime:'2026-10-01',names:['物品 A',null,0]})
for(const key of ['password','fileName','token','enabled'])assert.equal(normalized[key],original[key])
assert.equal(normalizeSearchQuery({'params[password]':' keep '})['params[password]'],' keep ')
})
test('scope includes business searches and filtered exports, never collaboration or business writes',()=>{
for(const path of ['/warehouse/product/list','/production/products/options','/project/info/options','/project/loans','/system/user/list','/monitor/operlog/list','/prod-api/warehouse/stock/list'])assert.equal(isSearchRequest(path),true,path)
assert.equal(isSearchRequest('/warehouse/product/export','post'),true)
for(const [path,method] of [['/project/manage/projects','get'],['/warehouse/purchase','post'],['/login','post'],['/system/user/resetPwd','put'],['/common/download','get']])assert.equal(isSearchRequest(path,method),false,path)
})