diff --git a/mobile-app/src/App.tsx b/mobile-app/src/App.tsx
index 7382508..9af2272 100644
--- a/mobile-app/src/App.tsx
+++ b/mobile-app/src/App.tsx
@@ -65,6 +65,7 @@ function Root(){
{page&&}
{selected?.title||titles[page||tab]}
+ {!!selected?.guide&&Alert.alert(selected.title+' · 操作指引',selected.guide)} style={{padding:10}}>}
{!page&&{variant==='prod'?'内网工作空间':'开发环境'}}
@@ -83,9 +84,9 @@ function Root(){
}
function Login({api,onLogin}:{api:ApiClient;onLogin:(token:string)=>Promise}){
const [username,setUsername]=useState(''),[password,setPassword]=useState(''),[code,setCode]=useState('');
- const [captcha,setCaptcha]=useState(null),[error,setError]=useState(''),[busy,setBusy]=useState(false);
+ const [captcha,setCaptcha]=useState(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('/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('/captchaImage',{anonymous:true});}catch(e){if((e as {code?:number}).code!==409)throw e;data=await api.request('/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
CMVR · 项目物资管理欢迎回到工作空间请连接公司内网,使用现有账号登录。
- {captcha?.captchaEnabled!==false&&<>
+ {connecting&&正在连接内网服务,准备登录信息…}
+ {!!captcha&&captcha.captchaEnabled!==false&&<>
{!!captcha?.img&&void refresh()}>}>}
{!!error&&{error}};
}
@@ -166,8 +168,9 @@ function StockOperation({api,row,kind,close,done}:{api:ApiClient;row:Row;kind:st
{kind==='borrow'&&}
{kind!=='check'&&}
- >:请核对本次{title}物品:{display(row.productName)}数量:{quantity} {display(row.unit)}
- {!!project&&借入项目:{project.projectName}}{!!area&&目标库区:{area.areaName||area.areaCode}}日期:{date}备注:{remark||'无'}
+ >:请核对本次{title}物品:{display(row.productName)}
+ {kind==='check'?<>账面数量:{display(row.stockNum)} {display(row.unit)}实际盘点数量:{quantity} {display(row.unit)}差异数量:{Number((Number(quantity)-Number(row.stockNum)).toFixed(4))} {display(row.unit)}登记后生成待确认盘点记录;确认生效后才会调整库存,当前不会直接扣减或增加库存。>:数量:{quantity} {display(row.unit)}}
+ {!!project&&借入项目:{project.projectName}}{!!area&&目标库区:{area.areaName||area.areaCode}}日期:{date}{kind==='check'?'差异原因':'备注'}:{remark||'无'}
void submit()}/>
setPreview(false)}/>}
{!!error&&{error}}
diff --git a/mobile-app/src/core/assistant-display.ts b/mobile-app/src/core/assistant-display.ts
new file mode 100644
index 0000000..39496ee
--- /dev/null
+++ b/mobile-app/src/core/assistant-display.ts
@@ -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(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 行,请减少选择;未选子表不计入。`:'';
+}
diff --git a/mobile-app/src/core/modules.ts b/mobile-app/src/core/modules.ts
index 8745480..6375ab7 100644
--- a/mobile-app/src/core/modules.ts
+++ b/mobile-app/src/core/modules.ts
@@ -1,22 +1,28 @@
export type Row = Record;
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(value)]||'待核对';
if (module.key === 'production' && key === 'status') return ({OPEN:'进行中',SETTLED:'已结算',CANCELLED:'已取消'} as Record)[String(value)] || display(value);
return display(value);
}
diff --git a/mobile-app/src/core/network.ts b/mobile-app/src/core/network.ts
index 317ddbf..32c4454 100644
--- a/mobile-app/src/core/network.ts
+++ b/mobile-app/src/core/network.ts
@@ -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 {
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: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);
diff --git a/mobile-app/src/core/search-query.ts b/mobile-app/src/core/search-query.ts
new file mode 100644
index 0000000..6527532
--- /dev/null
+++ b/mobile-app/src/core/search-query.ts
@@ -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));
+}
diff --git a/mobile-app/src/screens/Assistant.tsx b/mobile-app/src/screens/Assistant.tsx
index f20cdc8..b2421bc 100644
--- a/mobile-app/src/screens/Assistant.tsx
+++ b/mobile-app/src/screens/Assistant.tsx
@@ -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>(null),lock=useRef(false),alive=useRef(true);
const [session,setSession]=useState(null),[text,setText]=useState(''),[files,setFiles]=useState([]);
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[uncertain,setUncertain]=useState(false),[pending,setPending]=useState(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(`${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(`${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(`${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}){
{message.content}{message.attachments?.map((f:Row)=>f.type==='image'?:{f.name})}
{message.query?.errors?.map((e:string,j:number)=>{e})}
{message.query?.results?.map((result:Row,j:number)=>)}
- {message.draft&&{message.draft.label}{message.draft.status} · {message.draft.rows?.length||0} 项
+ {message.draft&&{message.draft.label}{draftStatus(message.draft.status)} · {message.draft.rows?.length||0} 项
{(message.draft.errors||[]).map((e:string,j:number)=>{e})}
{(message.draft.rows||[]).slice(0,20).map((row:Row,j:number)=>
- 第 {j+1} 行{(message.draft.fields||[]).map((f:Row)=>{f.label}:{display(row._labels?.[f.key]??row[f.key])})})}
+ 第 {j+1} 行{(message.draft.fields||[]).map((f:Row)=>{f.label}:{draftFieldText(row,f)})}
)}
{(message.draft.rows||[]).length>20&&此确认单超过 20 项,请在电脑端完整核对后办理;App 暂不开放截断确认。}
{!message.draft.readOnly&&String(message.draft.id)===String(session?.draft?.id)&&<>
需要更正时可继续在下方描述,原草稿由后端保留并重新核对。
@@ -61,15 +62,15 @@ export function Assistant({api}:{api:ApiClient}){
>}
}
)}
- {busy&&{session?'正在核对你的需求':'正在读取权限和最近对话'} · {seconds} 秒}
+ {busy&&{attachmentPhase==='selecting'?'请在文件选择窗口中选择附件':attachmentPhase==='uploading'?'正在上传附件并读取文件信息':session?'正在核对你的需求':'正在读取权限和最近对话'} · {seconds} 秒}
{!!error&&{error}}{(uncertain||session?.processing)&&上一项结果尚待核对。请刷新状态,确认处理已结束后继续。}
- {(uncertain||error||session?.processing)&&void refresh()}/>}
+ {(uncertain||session?.processing||(!session&&error))&&void refresh()}/>}
{!!files.length&&{files.map(f=>{f.name}{f.type==='excel'&&(f.sheets||[]).map((sheet:Row)=>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]}))}/>)})}}
- {!!files.length&&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]}));}}/>)})}}
+ {!!files.length&&{setFiles([]);setError('');}}/>}
=3} onPress={()=>void attach()} style={[s.row,{padding:8,opacity:busy||uncertain?.5:1}]}>图片 / 表格void send()}/>
diff --git a/mobile-app/tests/blackbox-followup.test.mjs b/mobile-app/tests/blackbox-followup.test.mjs
new file mode 100644
index 0000000..d496b21
--- /dev/null
+++ b/mobile-app/tests/blackbox-followup.test.mjs
@@ -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);
+});
diff --git a/mobile-app/tests/operation-guide.test.mjs b/mobile-app/tests/operation-guide.test.mjs
new file mode 100644
index 0000000..323cc3c
--- /dev/null
+++ b/mobile-app/tests/operation-guide.test.mjs
@@ -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.*生产任务/);
+});
diff --git a/mobile-app/tests/search-query.test.mjs b/mobile-app/tests/search-query.test.mjs
new file mode 100644
index 0000000..c4386c7
--- /dev/null
+++ b/mobile-app/tests/search-query.test.mjs
@@ -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);
+});
diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/service/assistant/AssistantConversationService.java b/ruoyi-admin/src/main/java/com/ruoyi/web/service/assistant/AssistantConversationService.java
index a2fbd57..c86d1dc 100644
--- a/ruoyi-admin/src/main/java/com/ruoyi/web/service/assistant/AssistantConversationService.java
+++ b/ruoyi-admin/src/main/java/com/ruoyi/web/service/assistant/AssistantConversationService.java
@@ -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 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 parked = parkedPlan(state, target);
+ Map context = new LinkedHashMap<>(parked); context.put("status", "NEEDS_INPUT");
+ Map 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 restored = restoreParked(state, longValue(proposal.get("draftId")), text);
+ Map restored = restoreParked(state, longValue(proposal.get("draftId")), text, proposal.containsKey("rows") ? maps(proposal.get("rows")) : null);
Map 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 restoreParked(Map state, Long id, String text) {
+ return restoreParked(state, id, text, null);
+ }
+
+ private Map parkedPlan(Map state, Long id) {
if (!parkedIds(state).contains(id)) throw new ServiceException("该暂存草稿当前不可恢复,请刷新会话后选择。", 403);
AiCommand source = requireCommand(id, false); Map 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 prepared = prepare(source.getAction(), maps(plan.get("rows")));
+ return plan;
+ }
+
+ private Map restoreParked(Map state, Long id, String text, List