feat(app): 添加消息中心功能并优化AI助手体验
- 集成消息中心屏幕和未读消息徽章显示 - 实现消息中心后台轮询和应用状态监听 - 添加应用启动时的消息刷新逻辑 - 更新导航标题配置增加消息中心选项 - 在助手界面改进报价更正说明显示 - 增强AI助手报价单处理和文档识别功能 - 添加管理员消息发送权限控制和验证 - 优化采购参考价格操作的业务规则说明 - 修复AI助手权限验证中的通知操作检查
This commit is contained in:
parent
eb492b09b5
commit
966df3ed57
@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ActivityIndicator, BackHandler, FlatList, Image, KeyboardAvoidingView, Modal, Platform,
|
||||
import { ActivityIndicator, AppState, BackHandler, FlatList, Image, KeyboardAvoidingView, Modal, Platform,
|
||||
Keyboard, Pressable, ScrollView, Text, View } from 'react-native';
|
||||
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
|
||||
import Constants from 'expo-constants';
|
||||
@ -18,6 +18,8 @@ import { Account, type LeaveGuard } from './screens/Account';
|
||||
import { Feedback } from './screens/Feedback';
|
||||
import { Dialog as Alert, PreviewDialogs } from './dialogs';
|
||||
import {ServerConnection} from './screens/ServerConnection';
|
||||
import {MessageCenter} from './screens/MessageCenter';
|
||||
import {messageBadge} from './core/message-center';
|
||||
import {developmentServerKey,developmentServer,serverTokenKey,connectionClient,checkDevelopmentServer} from './core/server-address';
|
||||
|
||||
const config=Constants.expoConfig?.extra || {};
|
||||
@ -40,11 +42,19 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom
|
||||
const storage=useMemo(()=>{const key=serverTokenKey(variant,server);return {get:()=>Platform.OS==='web'?Promise.resolve(null):SecureStore.getItemAsync(key),put:(token:string)=>Platform.OS==='web'?Promise.resolve():SecureStore.setItemAsync(key,token),clear:()=>Platform.OS==='web'?Promise.resolve():SecureStore.deleteItemAsync(key)};},[server]);
|
||||
const t=useTheme(); const [user,setUser]=useState<User|null>(null),[starting,setStarting]=useState(true);
|
||||
const [tab,setTab]=useState('home'),[stack,setStack]=useState<string[]>([]),[aiVisited,setAiVisited]=useState(false),[keyboard,setKeyboard]=useState(false),[update,setUpdate]=useState<UpdateState>('disabled');
|
||||
const [unreadMessages,setUnreadMessages]=useState({count:0,exact:true});const messageSerial=useRef(0);
|
||||
const page=stack[stack.length-1];
|
||||
const epoch=useRef(0),leave=useRef<LeaveGuard|null>(null);
|
||||
const bindLeave=useCallback((guard:LeaveGuard|null)=>{leave.current=guard;},[]);
|
||||
const reset=useCallback(()=>{epoch.current++;setUser(null);setTab('home');setStack([]);setAiVisited(false);leave.current=null;void storage.clear();},[storage]);
|
||||
const reset=useCallback(()=>{epoch.current++;messageSerial.current++;setUnreadMessages({count:0,exact:true});setUser(null);setTab('home');setStack([]);setAiVisited(false);leave.current=null;void storage.clear();},[storage]);
|
||||
const api=useMemo(()=>variant==='dev'?connectionClient(server,reset,Platform.OS==='web'?globalThis.location.origin:undefined):new ApiClient(base,reset),[reset,server]);
|
||||
const refreshMessages=useCallback(()=>{
|
||||
const current=epoch.current,id=++messageSerial.current;if(!user){setUnreadMessages({count:0,exact:true});return;}
|
||||
void Promise.all([api.request<Row>('/system/notifications/unread'),api.request<Row>('/system/notice/listTop')]).then(([inbox,notices])=>{
|
||||
if(current===epoch.current&&id===messageSerial.current)setUnreadMessages({count:Math.max(0,Number(inbox.data?.count)||0)+(notices.data||[]).filter((item:Row)=>!item.isRead).length,exact:inbox.data?.exact!==false});
|
||||
}).catch(()=>{});
|
||||
},[api,user?.user.userId]);
|
||||
useEffect(()=>{refreshMessages();const timer=setInterval(()=>{if(AppState.currentState==='active')refreshMessages();},60000),listener=AppState.addEventListener('change',state=>{if(state==='active')refreshMessages();});return()=>{clearInterval(timer);listener.remove();messageSerial.current++;};},[refreshMessages]);
|
||||
useEffect(()=>()=>{epoch.current++;api.clear();},[api]);
|
||||
async function changeServer(value:string){
|
||||
const checked=await checkDevelopmentServer(value,Platform.OS==='web'?globalThis.location.origin:undefined);
|
||||
@ -73,7 +83,7 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom
|
||||
const permitted=modules.filter(m=>allows(user?.permissions||[],...m.permissions)&&(!m.pages||m.pages.some(p=>user?.pages?.includes(p))));
|
||||
const selected=permitted.find(m=>m.key===page);
|
||||
const ai=allows(user?.permissions||[],['ai:assistant:use']);
|
||||
const titles:Record<string,string>={home:'工作台',business:'业务中心',assistant:'AI 助手',me:'我的',profile:'个人资料',password:'账号与密码',feedback:'问题与建议','feedback-list':'我的反馈',settings:'设置',about:'关于应用'};
|
||||
const titles:Record<string,string>={home:'工作台',business:'业务中心',assistant:'AI 助手',me:'我的',messages:'消息中心',profile:'个人资料',password:'账号与密码',feedback:'问题与建议','feedback-list':'我的反馈',settings:'设置',about:'关于应用'};
|
||||
const tabs:[string,string,IconName][]=[['home','工作台','grid-outline'],['business','业务','layers-outline'],...(ai?[['assistant','AI','sparkles-outline'] as [string,string,IconName]]:[]),['me','我的','person-outline']];
|
||||
return <SafeAreaView style={[s.fill,{backgroundColor:t.bg,width:'100%',alignSelf:'center',...(Platform.OS==='web'?{maxWidth:480}:{})}]}><StatusBar style={t.bg==='#101722'?'light':'dark'}/>
|
||||
{starting?<View style={[s.page,{flex:1,justifyContent:'center'}]}><ActivityIndicator/><Heading>正在连接你的工作空间</Heading><Note>正在恢复登录并核对当前账号信息,请稍候。</Note></View>:
|
||||
@ -82,12 +92,14 @@ function Root({server,saveServer}:{server:string;saveServer:(value:string)=>Prom
|
||||
{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!=='messages'&&<Pressable accessibilityRole="button" accessibilityLabel="消息中心" onPress={()=>open('messages')} style={{padding:10,position:'relative'}}><Icon name="notifications-outline" color={t.text}/>{!!messageBadge(unreadMessages.count,unreadMessages.exact)&&<View style={{position:'absolute',top:0,right:0,borderRadius:10,paddingHorizontal:4,minWidth:17,backgroundColor:'#dc5b66'}}><Text style={{fontSize:10,lineHeight:17,textAlign:'center',color:'#fff'}}>{messageBadge(unreadMessages.count,unreadMessages.exact)}</Text></View>}</Pressable>}
|
||||
{!page&&<View style={{borderRadius:12,backgroundColor:t.soft,paddingHorizontal:10,paddingVertical:5}}><Text style={{color:t.accent,fontSize:11}}>{variant==='prod'?'内网工作空间':'开发环境'}</Text></View>}
|
||||
</View>
|
||||
<View style={s.fill}>
|
||||
{!page&&tab==='home'&&<Workspace api={api} user={user.user} modules={permitted} open={open} go={go} ai={ai}/>}
|
||||
{!page&&tab==='business'&&<BusinessHub modules={permitted} open={open}/>}
|
||||
{!page&&tab==='me'&&<Me api={api} user={user.user} open={open}/>}
|
||||
{page==='messages'&&<MessageCenter api={api} onRead={refreshMessages}/>}
|
||||
{aiVisited&&ai&&<View style={[s.fill,{display:!page&&tab==='assistant'?'flex':'none'}]}><Assistant api={api}/></View>}
|
||||
{!!selected&&<BusinessList key={page} api={api} module={selected} permissions={user.permissions}/>}
|
||||
{(page==='profile'||page==='password')&&<Account key={page} api={api} kind={page} policy={String(user.pwdChrtype||'0')} bindLeave={bindLeave} onSaved={profile=>setUser(old=>old?{...old,user:{...old.user,...profile}}:null)}/>}
|
||||
|
||||
55
mobile-app/src/core/message-center.ts
Normal file
55
mobile-app/src/core/message-center.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import type {ApiClient} from './network';
|
||||
import type {Row} from './modules';
|
||||
|
||||
export type MessageTab='inbox'|'notices';
|
||||
export type MessageState={tab:MessageTab;items:Row[];notices:Row[];detail:Row|null;busy:boolean;reading:boolean;error:string;hasMore:boolean;cursor:string|null;unreadOnly:boolean};
|
||||
export const initialMessageState=():MessageState=>({tab:'inbox',items:[],notices:[],detail:null,busy:false,reading:false,error:'',hasMore:false,cursor:null,unreadOnly:false});
|
||||
export function messageBadge(count:unknown,exact=true){const n=Math.max(0,Number(count)||0);return n>99?'99+':!exact?(n?n+'+':'…'):n?String(n):'';}
|
||||
/** Never display raw announcement HTML in native Text or inject it into a WebView. */
|
||||
export function announcementText(html:unknown){return String(html||'').replace(/<(script|style|iframe|object)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,'').replace(/<(?:br\s*\/|br|\/p|\/div|\/li|\/h[1-6]|\/tr)>/gi,'\n').replace(/<[^>]*>/g,'').replace(/&(?:nbsp|lt|gt|amp|quot|#39);/g,value=>({' ':' ','<':'<','>':'>','&':'&','"':'"',''':"'"}[value]||value)).trim();}
|
||||
/** UI controller: bounded manual pagination, stale response protection and explicit read acknowledgements. */
|
||||
export function createMessageCenter(api:Pick<ApiClient,'request'>,changed:(state:MessageState)=>void,onRead=()=>{}){
|
||||
let state=initialMessageState(),serial=0,alive=true;
|
||||
const emit=(patch:Partial<MessageState>)=>{if(alive){state={...state,...patch};changed(state);}};
|
||||
const valid=(id:number)=>alive&&id===serial;
|
||||
const fail=(error:unknown)=>error instanceof Error?error.message:'暂时无法获取消息,请刷新重试。';
|
||||
async function load(more=false){
|
||||
if(state.reading||more&&(state.busy||!state.hasMore))return;
|
||||
const id=++serial,tab=state.tab,cursor=more?state.cursor:null;
|
||||
emit({busy:true,error:'',detail:null,...(!more?{items:[],notices:[],hasMore:false,cursor:null}:{})});
|
||||
try{
|
||||
if(tab==='notices'){
|
||||
const result=await api.request<Row>('/system/notice/listTop');if(!valid(id))return;emit({notices:result.data||[]});
|
||||
}else{
|
||||
const result=await api.request<Row>('/system/notifications',{query:{beforeId:cursor,limit:20,unreadOnly:state.unreadOnly}});if(!valid(id))return;
|
||||
const page=result.data||{},next=page.nextCursor==null?null:String(page.nextCursor);
|
||||
const advance=next!==null&&/^\d+$/.test(next)&&BigInt(next)>0n&&(cursor===null||BigInt(next)<BigInt(cursor));
|
||||
const seen=new Set(state.items.map(item=>String(item.id)));
|
||||
emit({items:[...state.items,...(page.items||[]).filter((item:Row)=>!seen.has(String(item.id)))],hasMore:page.hasMore===true&&advance,cursor:advance?next:null,error:page.hasMore&&!advance?'分页位置未更新,请刷新后继续。':''});
|
||||
}
|
||||
}catch(error){if(valid(id))emit({error:fail(error)});}finally{if(valid(id))emit({busy:false});}
|
||||
}
|
||||
async function tab(value:MessageTab){if(state.reading)return;emit({tab:value});await load();}
|
||||
async function filter(value:boolean){if(state.reading)return;emit({unreadOnly:value});await load();}
|
||||
async function detail(item:Row){
|
||||
if(state.reading)return;const id=++serial,kind=state.tab;emit({busy:true,error:'',detail:null});
|
||||
try{
|
||||
const result=await api.request<Row>(kind==='inbox'?'/system/notifications/'+item.id:'/system/notice/'+item.noticeId);if(!valid(id))return;
|
||||
const data=result.data||{};
|
||||
emit({detail:kind==='inbox'?{id:item.id,kind,title:data.title,content:data.content,time:data.deliveredAt,read:!!data.readAt}:{id:item.noticeId,kind,title:data.noticeTitle,content:announcementText(data.noticeContent),time:data.createTime,read:!!item.isRead}});
|
||||
}catch(error){if(valid(id))emit({error:fail(error)});}finally{if(valid(id))emit({busy:false});}
|
||||
}
|
||||
async function mark(detailOnly=false){
|
||||
if(state.reading||state.busy)return;
|
||||
const kind=state.detail?.kind||state.tab;
|
||||
const ids=detailOnly&&state.detail?[state.detail.id]:(kind==='inbox'?state.items.filter(item=>!item.readAt).map(item=>item.id):state.notices.filter(item=>!item.isRead).map(item=>item.noticeId)).slice(0,100);
|
||||
if(!ids.length)return;const id=++serial;emit({reading:true,error:''});
|
||||
try{
|
||||
if(kind==='inbox')await api.request('/system/notifications/read-batch',{method:'PUT',body:ids});
|
||||
else await api.request('/system/notice/markReadAll',{method:'POST',query:{ids:ids.join(',')}});
|
||||
if(!valid(id))return;const selected=new Set(ids.map(String));
|
||||
emit({items:kind==='inbox'?state.items.map(item=>selected.has(String(item.id))?{...item,readAt:new Date().toISOString()}:item).filter(item=>!state.unreadOnly||!item.readAt):state.items,notices:kind==='notices'?state.notices.map(item=>selected.has(String(item.noticeId))?{...item,isRead:true}:item):state.notices,detail:state.detail&&state.detail.kind===kind&&selected.has(String(state.detail.id))?{...state.detail,read:true}:state.detail});onRead();
|
||||
}catch(error){if(valid(id))emit({error:fail(error)});}finally{if(valid(id))emit({reading:false});}
|
||||
}
|
||||
return {load,tab,filter,detail,mark,start:()=>{alive=true;serial++;emit(initialMessageState());void load();},back:()=>{if(!state.reading){serial++;emit({detail:null,busy:false,error:''});}},dispose:()=>{alive=false;serial++;},snapshot:()=>state};
|
||||
}
|
||||
@ -76,7 +76,7 @@ function DraftCard({draft,currentId,busy,onAction,onInspect}:{draft:Row;currentI
|
||||
{expanded&&<>
|
||||
{(draft.errors||[]).map((e:string,j:number)=><Note key={j}>{e}</Note>)}
|
||||
{(draft.rows||[]).slice(0,20).map((row:Row,j:number)=><View key={j} style={{gap:6,paddingVertical:8,borderTopWidth:1,borderColor:t.line}}><Note>第 {j+1} 行</Note>{(draft.fields||[]).filter((f:Row)=>!f.hidden).map((f:Row)=><Text key={f.key} style={{color:t.text,lineHeight:22}}>{f.label}:{draftFieldText(row,f)}</Text>)}{draft.action==='purchase.correctPrice'&&(row._quotePreview||[]).map((q:Row,k:number)=><View key={k} style={{gap:4}}><Text style={{color:t.text}}>{q.name} · 数量 {q.quantity}</Text><Text style={{color:t.accent}}>报价:{q.previousPrice??'未报价'} → {q.unitPrice};金额:{q.oldAmount??'未计价'} → {q.newAmount}</Text><Note>{q.notice}</Note></View>)}</View>)}
|
||||
{(draft.rows||[]).flatMap((row:Row)=>row._referencePricePreview||[]).slice(0,20).map((row:Row,index:number)=><View key={`reference-${index}`} style={{gap:5}}><Text style={{color:t.text}}>{row.name} · {row.spec} · 数量 {row.quantity}</Text><Text style={{color:t.accent}}>实际单价:{row.oldActualPrice??'未填写'} → {row.newActualPrice??'未填写'};实际金额:{row.oldActualAmount??'未填写'} → {row.newActualAmount??'未填写'}</Text><Note>{row.notice};不修改报价或成本</Note></View>)}
|
||||
{(draft.rows||[]).flatMap((row:Row)=>row._referencePricePreview||[]).slice(0,20).map((row:Row,index:number)=><View key={`reference-${index}`} style={{gap:5}}><Text style={{color:t.text}}>{row.name} · {row.spec} · 数量 {row.quantity}</Text><Text style={{color:t.accent}}>实际单价:{row.oldActualPrice??'未填写'} → {row.newActualPrice??'未填写'};实际金额:{row.oldActualAmount??'未填写'} → {row.newActualAmount??'未填写'}</Text>{row.clearQuote&&<Text style={{color:row.blocked?'#dc5b66':t.text}}>报价单价:{row.quotePrice??'未报价'} → {row.newQuotePrice??(row.changed?'清空(未报价)':'未报价')};报价金额:{row.oldQuoteAmount??'未报价'} → {row.newQuoteAmount??(row.changed?'清空(未报价)':'未报价')}</Text>}<Note>{row.notice};{row.clearQuote?'整批提交并同步金额与成本,清空不是0元':'不修改报价或成本'}</Note></View>)}
|
||||
{(draft.rows||[]).filter((row:Row)=>row._historyPreview).slice(0,20).map((row:Row,index:number)=>{const h=row._historyPreview;return <View key={`history-${index}`} style={{gap:5,paddingVertical:8,borderTopWidth:1,borderColor:t.line}}><Text style={{color:t.text}}>{h.name} · {h.spec}</Text>{(h.changes||[]).map((change:Row)=><View key={change.field}><Note>{change.label} · 更正前:{change.beforeText??change.before??'未填写'}</Note><Text style={{color:t.accent}}>更正后:{change.afterText??change.after??'未填写'}</Text></View>)}<Note>实际金额:{h.oldActualAmount??'未填写'} → {h.newActualAmount??'未填写'};报价金额:{h.oldAmount??'未计价'} → {h.newAmount??'未计价'}</Note><Note>关联入库 {h.receiptCount||0} 条,成本来源 {h.costSourceCount||0} 条;实际收货数量不变。</Note>{h.createItem&&<Note>确认后匹配或新建物品档案。</Note>}{h.categoryUpdatesArchive&&<Note>类别更正会同步物品档案及其引用页面。</Note>}{h.priceImpact?.notice&&<Note>{h.priceImpact.notice}</Note>}{h.oldStatus!==h.newStatus&&<Note>采购状态将随需求数量重新核算,请在电脑端核对完整状态。</Note>}</View>})}
|
||||
{reviewCount>20&&<Note>此确认单超过 20 项,请在电脑端完整核对后办理;App 暂不开放截断确认。</Note>}
|
||||
</>}
|
||||
|
||||
27
mobile-app/src/screens/MessageCenter.tsx
Normal file
27
mobile-app/src/screens/MessageCenter.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import React,{useEffect,useMemo,useState} from 'react';
|
||||
import {Pressable,ScrollView,Text,View} from 'react-native';
|
||||
import {Button,Card,Heading,Icon,Note,s,useTheme} from '../ui';
|
||||
import type {ApiClient} from '../core/network';
|
||||
import {createMessageCenter,initialMessageState} from '../core/message-center';
|
||||
|
||||
export function MessageCenter({api,onRead}:{api:ApiClient;onRead:()=>void}){
|
||||
const t=useTheme(),[state,setState]=useState(initialMessageState);
|
||||
const center=useMemo(()=>createMessageCenter(api,setState,onRead),[api,onRead]);
|
||||
useEffect(()=>{center.start();return()=>center.dispose();},[center]);
|
||||
const busy=state.busy||state.reading,detail=state.detail,items=state.tab==='inbox'?state.items:state.notices;
|
||||
const unread=state.tab==='inbox'?state.items.some(item=>!item.readAt):state.notices.some(item=>!item.isRead);
|
||||
return <ScrollView contentContainerStyle={s.page}>
|
||||
<View accessibilityRole="tablist" style={s.row}>{([['inbox','站内消息'],['notices','通知公告']] as const).map(([key,label])=><Pressable key={key} accessibilityRole="tab" accessibilityState={{selected:state.tab===key,disabled:state.reading}} accessibilityLabel={label} disabled={state.reading} onPress={()=>void center.tab(key)} style={{paddingVertical:12,paddingHorizontal:18,borderRadius:12,backgroundColor:state.tab===key?t.accent:t.soft}}><Text style={{color:state.tab===key?t.onAccent:t.text,fontWeight:'600'}}>{label}</Text></Pressable>)}</View>
|
||||
{!!state.error&&<Note>{state.error}</Note>}
|
||||
{detail?<>
|
||||
<Button title="返回消息列表" secondary disabled={state.reading} onPress={center.back}/>
|
||||
<Card><Heading>{detail.title}</Heading><Note>{detail.time||'—'} · {detail.read?'已读':'未读'}</Note><Text selectable style={{color:t.text,lineHeight:27,fontSize:16}}>{detail.content||'暂无正文'}</Text>{!detail.read&&<Button title="标为已读" busy={state.reading} onPress={()=>void center.mark(true)}/>}</Card>
|
||||
</>:<>
|
||||
<View style={s.row}>{state.tab==='inbox'?<Button title={state.unreadOnly?'✓ 只看未读':'只看未读'} secondary disabled={busy} onPress={()=>void center.filter(!state.unreadOnly)}/>:<Note>最近 5 条通知公告</Note>}<Button title="刷新" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load()}/></View>
|
||||
{unread&&<Button title="已加载消息标为已读" secondary busy={state.reading} disabled={state.busy} onPress={()=>void center.mark()}/>}
|
||||
{!items.length&&<Note>{state.busy?'正在获取消息…':state.hasMore?'本页暂无可查看的消息,可继续加载较早消息。':state.tab==='notices'?'暂无通知公告':state.unreadOnly?'暂无未读消息':'暂无站内消息'}</Note>}
|
||||
{items.map(item=>{const read=state.tab==='inbox'?!!item.readAt:!!item.isRead;return <Pressable key={item.id??item.noticeId} accessibilityRole="button" accessibilityLabel={(read?'已读:':'未读:')+(item.title||item.noticeTitle)} disabled={busy} onPress={()=>void center.detail(item)}><Card><View style={[s.row,{flexWrap:'nowrap'}]}>{!read&&<View style={{width:7,height:7,borderRadius:4,backgroundColor:t.accent}}/>}<Text style={{flex:1,color:t.text,fontSize:16,fontWeight:read?'400':'700',lineHeight:24}}>{item.title||item.noticeTitle}</Text><Icon name="chevron-forward" size={18}/></View><Note>{item.deliveredAt||item.createTime||'—'}</Note>{state.tab==='inbox'&&<Text numberOfLines={2} style={{color:t.muted,lineHeight:21}}>{item.content}</Text>}</Card></Pressable>;})}
|
||||
{state.tab==='inbox'&&state.hasMore&&<Button title="加载更早消息" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load(true)}/>}
|
||||
</>}
|
||||
</ScrollView>;
|
||||
}
|
||||
@ -30,6 +30,7 @@ export function BusinessHub({modules,open}:{modules:Module[];open:(name:string)=
|
||||
export function Me({api,user,open}:{api:ApiClient;user:Row;open:(name:string)=>void}){
|
||||
const t=useTheme(),uri=usePrivateImage(api,imagePath(user.avatar));return <ScrollView contentContainerStyle={s.page}><Pressable accessibilityRole="button" accessibilityLabel="个人资料" onPress={()=>open('profile')}><View style={[s.row,{paddingVertical:12,gap:16}]}><Avatar name={user.nickName||user.userName} uri={uri} size={70}/><View style={{flex:1,gap:7}}><Text style={{color:t.text,fontSize:24,fontWeight:'700'}}>{user.nickName||user.userName}</Text><Text style={{color:t.muted,fontSize:13}}>账号 {user.userName}</Text><Text style={{color:t.muted,fontSize:12}}>{user.dept?.deptName||'个人工作空间'}</Text></View><Icon name="chevron-forward" color={t.muted}/></View></Pressable>
|
||||
<Card><MenuItem title="个人资料" detail="昵称、手机号码和邮箱" icon="person-outline" onPress={()=>open('profile')}/><MenuItem title="账号与密码" detail="管理当前账号的登录密码" icon="lock-closed-outline" onPress={()=>open('password')} last/></Card>
|
||||
<Card><MenuItem title="消息中心" detail="查看站内消息、通知公告和未读提醒" icon="notifications-outline" onPress={()=>open('messages')} last/></Card>
|
||||
<Card><MenuItem title="问题与建议" detail="发现问题、提出需求,支持添加图片" icon="chatbubble-ellipses-outline" onPress={()=>open('feedback')}/><MenuItem title="我的反馈" detail="查看处理进展与负责人回复" icon="receipt-outline" onPress={()=>open('feedback-list')} last/></Card>
|
||||
<Card><MenuItem title="设置" detail="外观、内网连接及应用更新" icon="settings-outline" onPress={()=>open('settings')}/><MenuItem title="关于应用" icon="information-circle-outline" onPress={()=>open('about')} last/></Card>
|
||||
<Text style={{color:t.muted,fontSize:11,textAlign:'center',letterSpacing:2,marginTop:8}}>CMVR · 让工作更简单</Text>
|
||||
|
||||
35
mobile-app/tests/message-center.test.mjs
Normal file
35
mobile-app/tests/message-center.test.mjs
Normal file
@ -0,0 +1,35 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createMessageCenter,messageBadge,announcementText} from '../src/core/message-center.ts';
|
||||
|
||||
const item={id:7,title:'模拟消息',content:'<script>literal text only</script>',readAt:null};
|
||||
function fixture(handler){const calls=[],states=[];const api={request:async(path,options)=>{calls.push({path,options});return handler(path,options);}};const center=createMessageCenter(api,state=>states.push(state));return {center,calls,states};}
|
||||
test('message badges keep bounded counts honest and native announcement text cannot execute HTML',()=>{
|
||||
assert.equal(messageBadge(0),'');assert.equal(messageBadge(0,false),'…');assert.equal(messageBadge(7,false),'7+');assert.equal(messageBadge(150),'99+');
|
||||
assert.equal(announcementText('<p>说明</p><script>hidden</script><p>第二段 <内容></p>'),'说明\n第二段 <内容>');
|
||||
});
|
||||
test('list and detail are read-only until the user explicitly acknowledges reading',async()=>{
|
||||
const {center,calls}=fixture(async path=>path==='/system/notifications'?{data:{items:[item],hasMore:false}}:path.endsWith('/read-batch')?{code:200}:{data:item});
|
||||
await center.load();await center.detail(item);assert.equal(calls.length,2);assert.ok(calls.every(call=>!call.options?.method));assert.equal(center.snapshot().detail.content,item.content);
|
||||
await center.mark(true);assert.deepEqual(calls[2],{path:'/system/notifications/read-batch',options:{method:'PUT',body:[7]}});assert.equal(center.snapshot().detail.read,true);
|
||||
center.back();assert.ok(center.snapshot().items[0].readAt);center.dispose();
|
||||
});
|
||||
test('permission-filtered empty pages advance manually and a non-advancing cursor ends pagination',async()=>{
|
||||
const {center,calls}=fixture(async()=>({data:{items:[],hasMore:true,nextCursor:100}}));await center.load();assert.equal(calls.length,1);assert.equal(center.snapshot().hasMore,true);
|
||||
await center.load(true);assert.equal(calls.length,2);assert.equal(calls[1].options.query.beforeId,'100');assert.equal(center.snapshot().hasMore,false);assert.match(center.snapshot().error,/分页位置/);
|
||||
await center.load(true);assert.equal(calls.length,2);
|
||||
});
|
||||
test('late inbox responses cannot overwrite a different tab or a disposed screen',async()=>{
|
||||
let resolve;const {center}=fixture(path=>path==='/system/notifications'?new Promise(done=>{resolve=done;}):Promise.resolve({data:[{noticeId:7,noticeTitle:'模拟公告',isRead:false}]}));
|
||||
const pending=center.load();await center.tab('notices');resolve({data:{items:[item],hasMore:false}});await pending;assert.equal(center.snapshot().tab,'notices');assert.equal(center.snapshot().items.length,0);
|
||||
const other=center.tab('inbox');center.dispose();resolve({data:{items:[item]}});await other;assert.equal(center.snapshot().items.length,0);
|
||||
});
|
||||
test('a failed acknowledgement keeps unread messages intact and never changes other message families',async()=>{
|
||||
const {center,calls}=fixture(async path=>{if(path.endsWith('/read-batch'))throw new Error('离线');return {data:{items:[item],hasMore:false}};});
|
||||
await center.load();await center.mark();assert.match(center.snapshot().error,/离线/);assert.equal(center.snapshot().items[0].readAt,null);assert.equal(calls.filter(call=>call.options?.method).length,1);
|
||||
});
|
||||
test('announcements use only their own read API, and remounting after disposal safely restarts',async()=>{
|
||||
const {center,calls}=fixture(async path=>path==='/system/notifications'?{data:{items:[],hasMore:false}}:path==='/system/notice/listTop'?{data:[{noticeId:7,noticeTitle:'公告',isRead:false}]}:{code:200});
|
||||
await center.tab('notices');await center.mark();assert.equal(calls.at(-1).path,'/system/notice/markReadAll');assert.deepEqual(calls.at(-1).options,{method:'POST',query:{ids:'7'}});
|
||||
center.dispose();center.start();await new Promise(resolve=>setImmediate(resolve));assert.equal(center.snapshot().busy,false);assert.equal(center.snapshot().tab,'inbox');center.dispose();
|
||||
});
|
||||
@ -19,12 +19,13 @@ public final class AssistantBusinessRules {
|
||||
if(action.equals("product.versionCreate"))return List.of("从明确来源产品新增任意名称的产品版本,不是只复制BOM。先生成确认单,确认才真正新建。原产品未归档时需用户明确系列名称和原版本名称;已有系列沿用系列名称。", "新版本必须使用独立物品。用户明确新建或复制物品时cloneItem=true,并提供新物品名称及能区分旧版本的规格;否则需选已有独立itemId,不能暗自复用原物品、猜规格或编号。新建物品另需物品新增权限。", "copyBomId仅在明确要复制某公共BOM时填写,bomTag为新BOM名称;复制另需BOM维护权限。只复制根BOM及用料,下级BOM仍引用原下级,库存、成本、旧任务和附件不复制、不合并。缺字段留在确认单补充,连续对话保留已给信息。");
|
||||
if(action.startsWith("product.attachment"))return List.of("附件明确归属某个产品版本,不能只凭系列名猜版本。查询product.attachments、查看下载product.attachmentDownload只读直接返回;保存product.attachmentUpload、移除product.attachmentRemove需先生成确认单,人工确认才执行。", "上传使用当前用户已上传的assistantFile,移除下载使用已保存的productAttachment,不能混用ID。产品附件单个50 MB,普通AI识别附件10 MB;大文件和CAD请用产品附件入口上传,仅保存文件、不读取正文,不当作OCR结果、不更新BOM或价格。读取需产品查看权限,写入需产品维护权限。");
|
||||
if(action.equals("purchase.correctHistory"))return List.of("维护已到齐、已入库、历史采购的非单价字段或同时更正多个字段用此操作。每条采购一行,id通过明细名称/批次/规格准确匹配,不是物品档案ID;不猜内部ID,同名请用户选择。仅提交用户明确要改的字段,未提及字段必须省略,不能填null、0或空字符串来凑齐表格;只有用户明确清空时才填null。批量使用同一更正原因。", "数量指采购需求数量,不代表改写到货数量、入库数量或出库事实;减少到货或库存要由相应业务流程办理。物品或项目变更由后端核对库存链,无法安全联动时说明具体阻止原因,不绕过校验、不建议直接改库。需要新物品时由原生服务核对字典和档案权限后建档,不能直接修改共享物品的单位。", "先展示每个字段原值/新值、实际金额/报价金额及下游影响,人工确认后整批原子执行。不得自行将acknowledgeArchiveOnly设为true,须用户阅读成本链不完整说明后本人勾选。仅改单价仍优先使用purchase.correctPrice或purchase.referencePrice。");
|
||||
if(action.equals("purchase.referencePrice"))return List.of("维护实际单价/实际金额(内部参考)使用此操作,不是更正报价。COPY_QUOTE表示每条实际单价取该条当前报价,不要编造统一数值;SET才填写actualUnitPrice;明确清空用CLEAR,不能用0代替空值。实际金额由数量乘单价自动计算,不参与成本。", "整批修改仅填purchaseBatchId,如CG2026100001;只改单条时填id,必要时带批次限定,不能把批次号塞入明细id。后端读取当前全部采购,逐项展示新旧实际金额;用户只需给批次或物品名称,无须逐行重录。未报价保留原实际单价,0报价是有效0,历史已到货同样可以维护。不能声称不支持实际单价,也不能把这项请求转成改报价。", "如果用户只说实际和报价改为相同,且没有说明以谁为准,询问方向。若上轮已经确认实际单价与现有报价一致,用户答确定/是,直接生成COPY_QUOTE草稿,不再重复确认语义。生成草稿不等于执行,仍需用户点击人工确认,执行时重新校验报价和金额。");
|
||||
if(action.equals("purchase.referencePrice"))return List.of("维护实际单价/实际金额(内部参考)使用此操作。COPY_QUOTE表示每条实际单价取该条当前报价;SET才填写actualUnitPrice;清空实际单价用CLEAR。复制原报价到实际单价再清空报价用COPY_QUOTE_CLEAR_QUOTE;仅清空报价保留实际金额用CLEAR_QUOTE,不能用0代替空值。已明确两项操作不再反复追问先后,生成一张整批原子确认单。", "整批修改仅填purchaseBatchId;只改单条填id并可带批次限定,不把批次号填入明细id。未报价保留原实际单价;0报价是有效0。清空报价使用采购管理员价格更正流程,支持历史、锁价、到货和入库;同步清空报价金额、解除对应费用锁定,明确关联成本变为待补全而非0元,不改变数量及业务状态。必须展示逐项联动影响,任何错误整批不执行。acknowledgeArchiveOnly必须留false,由本人阅读历史链不完整说明后勾选,不能代替用户确认。单独维护实际金额不影响成本。", "实际和报价改为相同而未说明方向时才询问以谁为准。续答两个一起/两项都做/确定须保留原批次和两项操作;若明确改为只清空报价则用CLEAR_QUOTE,不复活先前复制操作。生成草稿不等于执行,仍需点击确认并重新校验报价、实际金额和成本版本。");
|
||||
if(action.equals("purchase.correctPrice"))return List.of("用户要求更新、更正已有采购报价或按报价文件改价时使用此操作;PDF、图片、Excel都可以,每件物品一行,不新增采购。综合全部报价页,忽略营业执照、银行资料及小计合计,单价不能用总金额替代,不擅自含税换算。缺单价留null请用户补充,不填0。最多100条,不得截断。", "projectId和purchaseBatchId使用用户指定的项目、批次,没有就留空;id使用采购明细名称或{name,spec,brand,projectName,batchNo}定位,不是物品档案ID,保留规格和品牌限定,禁止猜内部ID。同名多行必须由用户选择,不按行号猜测。attachmentId使用原附件ID。原因可填写用户要求或'依据供应商报价文件更正'。", "已到货或历史数据也可以更正报价,原生服务联动金额、已锁费用及可追溯库存成本;实际单价和实际金额不变,不改变数量和状态。必须先展示新旧报价及金额、影响范围,用户点击确认后整批原子执行。acknowledgeArchiveOnly不能由模型主动设为true,须用户阅读不完整成本链提示后亲自勾选。报价与原价相同可省略该项,但需说明未变项目。");
|
||||
if(action.startsWith("feedbackNotification."))return List.of("仅系统管理员可查询或配置反馈通知,按现有角色配置解析接收人,不能由AI编造邮箱或直接指定任意收件人。反馈归属标记可以涉及项目协作,但不修改协作业务。", "settings/detail/preview只读直接返回;route、analyze、module和send均须人工确认。send确认单必须展示实际收件人、邮件主题和正文,执行前重新核对通知版本、路由及收件人;失败或未知发送状态须用户确认未收到才重试。autoSend必须由用户明确决定,不能擅自开启后续自动邮件。");
|
||||
if(action.startsWith("purchase.document" )||action.equals("purchase.detailDocuments"))return List.of("采购批次与采购明细附件分开管理,先选明确已有采购记录;按文件名选择本人上传的附件,attachmentId使用系统提供的真实文件ID,不编造路径或编码。流程资料支持申请REQUEST、报价QUOTE、合同CONTRACT、验收ACCEPTANCE、付款PAYMENT、其他OTHER,明细附件固定OTHER。", "流程资料必须PDF;其他附件按原上传规则校验。上传批次资料时,用户同时提供的流程编号必须一并填number,确认时原子保存文件和编号;留空保留旧编号,不代表清空。单独清空编号使用documentNumber。保存编号和附件不改变锁价、到货、验收、库存或实际付款状态。删除需明确所选附件并人工确认,不删除单据;查询和下载直接返回,文件访问仍校验权限。");
|
||||
if(action.equals("purchase.importQuote"))return List.of("读取供应商回传的原始询价Excel,明确采购批次并选择本人上传的文件;不按行号猜物品。后端使用原页面报价匹配规则,展示每行物品、规格、原报价及新单价;有匹配错误或报价无效时不能提交。", "留空单价保留原值,不自动确认采购或锁价;人工确认后整表保存,采购清单或文件发生变化时必须重新预览。不得改数量、项目或物品信息。");
|
||||
if(action.startsWith("notification."))return List.of("只处理当前登录人的站内通知,不是通知公告,不允许指定其他用户或查看其收件箱。查询、详情和未读数量直接返回,按原通知服务校验每条消息的接收人与当前业务权限。", "查询可按unreadOnly筛选和翻页;标记已读属于业务变更,选择明确消息并人工确认,不代表已办理消息提到的业务。");
|
||||
if(action.equals("notification.send"))return List.of("主动向系统用户发送消息或邮件用此操作,不是通知公告notice.create,也不是反馈通知feedbackNotification.send。管理员权限由服务端核对。按用户姓名或账号匹配userIds,同名必须选择,不能编造ID或读他人收件箱。站内消息不要求接收人有邮箱;发邮件必须已登记有效邮箱,不能代替用户修改邮箱。", "只说发消息/通知默认channel=INBOX,明确发邮件用EMAIL,明确两种渠道都发送用BOTH。区分发送渠道和正文主题:'给张浩发个消息通知,告诉他怎么使用消息通知和邮件'是INBOX,邮件一词属于正文主题。title/content可根据用户明确要求拟稿,最终展示供用户核对,不得因此发两种渠道或声称所有用户都有主动发送权限。", "用户缺少收件人或内容时保留已有信息,在确认单补充。用户续说部门/邮箱/正文只是补充,不能擅自改变接收人、渠道、账号资料。发送必须人工点击确认;最终通过原通知中心投递和去重。邮件排队不代表送达,超时不能盲目重发。通知内容不包含密码、密钥、其他用户私有记录或未授权业务数据。");
|
||||
if(action.startsWith("notification."))return List.of("只查询或处理当前登录人的站内通知,不是通知公告,不允许指定其他用户或查看其收件箱。主动发送给其他用户请使用独立的notification.send,由服务端核对管理员权限。查询、详情和未读数量直接返回,按原通知服务校验每条消息的接收人与当前业务权限。", "查询可按unreadOnly筛选和翻页;标记已读属于业务变更,选择明确消息并人工确认,不代表已办理消息提到的业务。");
|
||||
if(Set.of("supplier.licenseUpload","supplier.licensePreview").contains(action))return List.of("营业执照支持本人上传的PNG/JPG/PDF,先明确已有供应商;预览直接返回,保存或替换执照须人工确认,保留未修改的供应商名称、联系人、邮箱等信息。OCR文字不能代替真实文件,不自动将任意聊天图片认作营业执照。");
|
||||
if(Set.of("notice.top","notice.read","notice.readers").contains(action))return List.of("近期公告和阅读人员只读查询直接返回;阅读人员需公告管理权限。标记公告已读须人工确认,只标记当前登录用户,不修改正文、不替其他用户标记。");
|
||||
if(Set.of("department.create","department.update","department.delete").contains(action))return List.of("按原部门管理新增、修改或删除;上级部门、名称及排序按实际输入核对,不自动移动用户或授予角色权限。修改保留未提及的负责人、联系方式、状态及层级。", "使用当前账号可见的部门,并执行原部门数据范围校验;有子部门或用户的部门不能删除。变更必须人工确认,不能修改菜单或系统参数。");
|
||||
|
||||
@ -84,7 +84,7 @@ public class AssistantConversationService {
|
||||
resetIfPermissionsChanged(state);
|
||||
rememberPendingDraftMessage(state);
|
||||
String requestFingerprint = currentPermissionFingerprint();
|
||||
Map<String, Object> input = messageInput(state, request);
|
||||
Map<String, Object> input = quotationFollowupInput(messageInput(state, request));
|
||||
String text = input.get("text").toString();
|
||||
List<Map<String, Object>> files = attachments.forModel(attachmentIds(input.get("attachmentIds")), maps(input.get("attachmentSelections")));
|
||||
state.remove("pendingAttachmentMessageId");
|
||||
@ -253,6 +253,21 @@ public class AssistantConversationService {
|
||||
}
|
||||
|
||||
/** A retry uses only an owned session's server-frozen source message, never caller-supplied replacement files/text. */
|
||||
Map<String,Object> quotationFollowupInput(Map<String,Object> input) {
|
||||
if(!attachmentIds(input.get("attachmentIds")).isEmpty()||!explicitQuotationFile(Objects.toString(input.get("text"),"")))return input;
|
||||
// An older card may still point to a cached source after its upload turn left the ten-turn window.
|
||||
// Reuse only a unique currently owned PDF. Never guess across several quotations or accept a client path.
|
||||
var candidates=attachments.available(null,null).stream()
|
||||
.filter(file->Objects.toString(file.get("name"),"").toLowerCase(Locale.ROOT).endsWith(".pdf")).toList();
|
||||
if(candidates.size()!=1)throw new ServiceException(candidates.isEmpty()?"没有找到仍可读取的本人报价PDF,请重新上传报价单后继续;采购数据未修改":"你上传过多个PDF,请选择本次报价单后继续,避免使用错文件;采购数据未修改");
|
||||
var result=new LinkedHashMap<>(input);result.put("attachmentIds",List.of(candidates.get(0).get("id")));
|
||||
result.put("attachmentSelections",List.of());result.put("attachmentConversation",List.of(Map.of("role","user","content",input.get("text"))));return result;
|
||||
}
|
||||
private static boolean explicitQuotationFile(String text) {
|
||||
return text.matches("(?is).*(?:根据|按照|按|用|依据).*(?:pdf|这个报价单|刚才的报价单|上面的报价单).*" )
|
||||
&&text.matches("(?s).*(?:回填|更新|修改|更正|录入).*(?:报价|价格).*" )
|
||||
&&!text.matches("(?s).*(?:不要|不用|不使用|取消|怎么|如何|能否|是否).*" );
|
||||
}
|
||||
static Map<String, Object> messageInput(Map<String, Object> state, Map<String, Object> request) {
|
||||
String text = Objects.toString(request.get("text"), "").trim();
|
||||
String retryId = Objects.toString(request.get("retryMessageId"), "").trim();
|
||||
@ -273,9 +288,23 @@ public class AssistantConversationService {
|
||||
|| Set.of("取消", "取消识别", "不用附件", "不使用附件", "不用这个附件", "清空附件", "换个问题", "新问题").contains(text);
|
||||
String sourceId = !retryId.isBlank() ? retryId : ids.isEmpty() && !discardContext
|
||||
? Objects.toString(state.get("pendingAttachmentMessageId"), "") : "";
|
||||
// An explicit reference to the previous PDF quotation can reuse that owned source, not a model-guessed file id.
|
||||
if(sourceId.isBlank()&&retryId.isBlank()&&ids.isEmpty()&&!discardContext&&explicitQuotationFile(text)) {
|
||||
for(int i=history.size()-1;i>=0;i--) {
|
||||
var previous=history.get(i);
|
||||
if(!"user".equals(previous.get("role")))continue;
|
||||
var previousFiles=maps(previous.get("attachments"));
|
||||
if(previousFiles.isEmpty())continue;
|
||||
var pdfs=previousFiles.stream().filter(file->Objects.toString(file.get("name"),"").toLowerCase(Locale.ROOT).endsWith(".pdf")).toList();
|
||||
if(pdfs.size()>1)throw new ServiceException("上次上传了多个PDF,请选择本次要使用的报价单后继续;原采购数据未修改");
|
||||
if(pdfs.size()==1&&previousFiles.size()==1)sourceId=Objects.toString(previous.get("id"),"");
|
||||
break; // Never reach past a newer unrelated attachment to revive an old quotation.
|
||||
}
|
||||
}
|
||||
final String boundSourceId=sourceId;
|
||||
if (!sourceId.isBlank()) {
|
||||
Map<String, Object> source = history.stream().filter(message -> "user".equals(message.get("role"))
|
||||
&& Objects.equals(sourceId, message.get("id"))).findFirst()
|
||||
&& Objects.equals(boundSourceId, message.get("id"))).findFirst()
|
||||
.orElseThrow(() -> new ServiceException("原消息不在当前会话或已过期,请重新上传附件并说明需要办理的业务"));
|
||||
if (!retryId.isBlank()) text = Objects.toString(source.get("content"), "");
|
||||
ids = new ArrayList<>(); selections = new ArrayList<>();
|
||||
@ -294,7 +323,7 @@ public class AssistantConversationService {
|
||||
// Preserve only the clarification explicitly linked to this source; unrelated assistant replies are excluded.
|
||||
history.stream().filter(message -> "assistant".equals(message.get("role"))
|
||||
&& Boolean.TRUE.equals(message.get("requiresClarification"))
|
||||
&& Objects.equals(sourceId, message.get("sourceMessageId")))
|
||||
&& Objects.equals(boundSourceId, message.get("sourceMessageId")))
|
||||
.reduce((first, last) -> last)
|
||||
.ifPresent(message -> conversation.add(Map.of("role", "assistant", "content", Objects.toString(message.get("content"), ""))));
|
||||
conversation.add(Map.of("role", "user", "content", text));
|
||||
|
||||
@ -30,6 +30,7 @@ public class AssistantExtendedActions {
|
||||
@Autowired private ObjectMapper json;
|
||||
@Autowired private PurchasePriceCorrectionService priceCorrections;
|
||||
@Autowired private AssistantReferencePriceService referencePrices;
|
||||
@Autowired private AssistantNotificationService assistantNotifications;
|
||||
@Autowired private PurchaseHistoryCorrectionService historyCorrections;
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
@ -117,6 +118,8 @@ public class AssistantExtendedActions {
|
||||
data.put("summary",Boolean.TRUE.equals(result.get("hasMore"))?"还有消息,分页位置:"+result.get("nextCursor")+";可发送下一页":"已到当前查询末尾");
|
||||
return AjaxResult.success(data);
|
||||
}
|
||||
@PreAuthorize("T(com.ruoyi.common.utils.SecurityUtils).isAdmin()")
|
||||
public AjaxResult messageSend(Map<String,Object> row) {return AjaxResult.success(assistantNotifications.send(row));}
|
||||
@GetMapping @PreAuthorize("isAuthenticated()") public AjaxResult inboxDetail(Long id){return AjaxResult.success(notifications.inboxDetail(id));}
|
||||
@GetMapping @PreAuthorize("isAuthenticated()") public AjaxResult inboxUnread(){var count=notifications.unread();return AjaxResult.success(Map.of("rows",List.of(count),"summary",Boolean.FALSE.equals(count.get("exact"))?"未读消息较多,本次数量是下限,不是完整总数":"当前账号可查看的未读消息数量"));}
|
||||
@PreAuthorize("isAuthenticated()") public AjaxResult inboxRead(Map<String,Object> row){notifications.markRead(List.of(id(row,"id")));return AjaxResult.success();}
|
||||
@ -152,6 +155,7 @@ public class AssistantExtendedActions {
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
public AjaxResult quoteImport(Map<String,Object> row)throws Exception {
|
||||
requireExcelQuote(row);
|
||||
var sheet=sheets.load(id(row,"id"));
|
||||
if(!Objects.equals(sheet.getVersion(),row.get("sheetVersion")))throw new ServiceException("采购清单已变化,请重新预览报价");
|
||||
List<Map<String,Object>> quotes;
|
||||
@ -171,9 +175,15 @@ public class AssistantExtendedActions {
|
||||
return purchases.saveSheet(sheet);
|
||||
}
|
||||
private List<Map<String,Object>> quotePreview(Map<String,Object> row)throws Exception {
|
||||
requireExcelQuote(row);
|
||||
var sheet=sheets.load(id(row,"id"));
|
||||
try(var input=attachments.businessFile(str(row,"attachmentId")).getInputStream()){return SupplierQuoteImport.preview(input,sheet);}
|
||||
}
|
||||
private void requireExcelQuote(Map<String,Object> row) {
|
||||
var file=attachments.available(null,row.get("attachmentId")).get(0);
|
||||
String name=Objects.toString(file.get("name"),"").toLowerCase(Locale.ROOT);
|
||||
if(!name.endsWith(".xlsx")&&!name.endsWith(".xls"))throw new ServiceException("此入口仅回填系统导出的Excel询价单;PDF或图片报价请使用“根据报价单更正采购报价”,会逐项识别并匹配采购明细");
|
||||
}
|
||||
private Map<String,Object> supplier(Long id) {
|
||||
return suppliers.list(null).stream().filter(value->id.toString().equals(value.get("id").toString())).findFirst().orElseThrow(()->new ServiceException("供应商不存在或已停用"));
|
||||
}
|
||||
@ -196,6 +206,12 @@ public class AssistantExtendedActions {
|
||||
public Map<String,Object> prepare(String action,Map<String,Object> row,Map<String,Object> snapshots,Map<String,Object> labels,List<String> errors) {
|
||||
var choices=new LinkedHashMap<String,Object>();
|
||||
try {
|
||||
if(action.equals("notification.send")) {
|
||||
var plan=assistantNotifications.preview(row);snapshots.put("messageRecipients",plan);
|
||||
row.put("recipientSummary",AssistantConversationService.maps(plan.get("recipients")).stream()
|
||||
.map(user->user.get("name")+"("+user.get("account")+")"+(user.containsKey("email")?" <"+user.get("email")+">":"")).collect(java.util.stream.Collectors.joining(";")));
|
||||
row.put("deliveryNotice",plan.get("notice"));
|
||||
}
|
||||
if(action.equals("purchase.correctHistory")){
|
||||
var preview=historyCorrections.previewEntry(historyCommand(List.of(row),null));snapshots.put("historyCorrection",preview);row.put("historyVersion",preview.get("version"));row.put("_historyPreview",preview);
|
||||
if(preview.get("priceImpact") instanceof Map<?,?> impact&&impact.get("archiveOnlyCount") instanceof Number count&&count.intValue()>0&&!Boolean.TRUE.equals(row.get("acknowledgeArchiveOnly")))errors.add("历史成本链不完整:请阅读影响说明,由本人勾选核对确认");
|
||||
@ -203,6 +219,7 @@ public class AssistantExtendedActions {
|
||||
if(action.equals("purchase.referencePrice")) {
|
||||
var preview=referencePrices.preview(row);snapshots.put("referencePrices",preview);
|
||||
row.put("referenceVersion",preview.get("version"));row.put("_referencePricePreview",preview.get("rows"));row.put("quoteSummary",preview.get("notice"));
|
||||
if(((Number)preview.get("blocked")).longValue()>0)errors.add("请处理逐项核对说明(如本人确认历史成本链影响),再重新预览;确认前整批不执行");
|
||||
if(((Number)preview.get("changed")).longValue()==0)errors.add("所选实际金额已经符合要求,或尚未报价,无需修改;未报价项不会按0处理");
|
||||
}
|
||||
if(action.equals("purchase.correctPrice")) {
|
||||
@ -280,7 +297,7 @@ public class AssistantExtendedActions {
|
||||
}catch(ServiceException e){errors.add(e.getMessage());}catch(Exception e){errors.add("请核对所选记录、附件和业务状态后重新预览");}
|
||||
return choices;
|
||||
}
|
||||
static boolean preparedAction(String action) {return action.startsWith("purchase.documentUpload")||action.startsWith("purchase.documentRemove")||action.startsWith("purchase.documentDownload")||Set.of("purchase.correctHistory","purchase.referencePrice","purchase.correctPrice","purchase.documentNumber","supplier.licenseUpload","notification.read","feedbackNotification.route","feedbackNotification.analyze","feedbackNotification.module","feedbackNotification.send","purchase.importQuote").contains(action);}
|
||||
static boolean preparedAction(String action) {return action.startsWith("purchase.documentUpload")||action.startsWith("purchase.documentRemove")||action.startsWith("purchase.documentDownload")||Set.of("purchase.correctHistory","purchase.referencePrice","purchase.correctPrice","purchase.documentNumber","supplier.licenseUpload","notification.read","notification.send","feedbackNotification.route","feedbackNotification.analyze","feedbackNotification.module","feedbackNotification.send","purchase.importQuote").contains(action);}
|
||||
static Long id(Map<String,Object> row,String key){Object value=row.get(key);if(value==null)throw new ServiceException("请明确业务记录");try{long id=new BigDecimal(value.toString()).longValueExact();if(id<=0)throw new ArithmeticException();return id;}catch(ArithmeticException|NumberFormatException e){throw new ServiceException("请选择有效的业务记录编号");}}
|
||||
static String str(Map<String,Object> row,String key){return Objects.toString(row.get(key),"");}
|
||||
}
|
||||
|
||||
@ -9,9 +9,10 @@ public final class AssistantMessages {
|
||||
|
||||
/** Identity-only restrictions cannot be lifted by granting a menu/button permission. */
|
||||
public static boolean administratorOnly(String action) {
|
||||
return java.util.Objects.toString(action,"").startsWith("feedbackNotification.")||java.util.Set.of("role.dataScope", "feedback.all", "feedback.handle").contains(java.util.Objects.toString(action, ""));
|
||||
return java.util.Objects.toString(action,"").startsWith("feedbackNotification.")||java.util.Set.of("notification.send", "role.dataScope", "feedback.all", "feedback.handle").contains(java.util.Objects.toString(action, ""));
|
||||
}
|
||||
public static String forAction(String action) {
|
||||
if ("notification.send".equals(action)) return "主动发送系统通知或邮件由管理员协助办理;你仍可以查看和处理自己的站内消息。";
|
||||
if ("user.create".equals(action)) return "用户账号由管理员统一维护,可以请管理员协助添加这个用户。";
|
||||
if (java.util.Set.of("user.update", "user.delete", "user.status", "user.roles", "user.resetPassword").contains(java.util.Objects.toString(action, "")))
|
||||
return "账号资料和角色授权建议由管理员协助核实处理,确保调整到正确的用户。";
|
||||
@ -25,7 +26,7 @@ public final class AssistantMessages {
|
||||
}
|
||||
public static String safeAuthorizationMessage(String message) {
|
||||
if (java.util.Set.of(NOT_ENABLED, REQUEST_ACCESS, forAction("role.dataScope"), forAction("feedback.all"), forAction("feedback.handle"),
|
||||
forAction("user.create"), forAction("user.update"), forAction("role.create"),forAction("feedbackNotification.send"))
|
||||
forAction("user.create"), forAction("user.update"), forAction("role.create"),forAction("feedbackNotification.send"),forAction("notification.send"))
|
||||
.contains(java.util.Objects.toString(message, ""))) return message;
|
||||
return NOT_ENABLED;
|
||||
}
|
||||
|
||||
@ -53,6 +53,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> priceCombination = files.isEmpty() ? AssistantPriceInstructions.propose(messages,actions,task) : null;
|
||||
if(priceCombination!=null)return priceCombination;
|
||||
Map<String,Object> entryReply = files.isEmpty() ? businessEntryReply(latestText, actions) : null;
|
||||
if (entryReply != null) return entryReply;
|
||||
Map<String,Object> priceDirection = priceDirectionReply(latestText,actions);
|
||||
@ -114,6 +116,7 @@ public class AssistantModelClient {
|
||||
route = call(routingPrompt(), content(routingContext, images), actions, "ROUTE_IMAGE", diagnosticId,
|
||||
routingRemaining, 768, true, images);
|
||||
}
|
||||
route = quotationRoute(route, files, actions);
|
||||
if ("patch".equals(route.get("kind"))) {
|
||||
if (!files.isEmpty()) throw new ServiceException("新附件不能直接修改旧确认单,请按本次附件重新生成草稿");
|
||||
if (!Objects.equals(taskInput.get("action"), route.get("action"))
|
||||
@ -187,6 +190,8 @@ public class AssistantModelClient {
|
||||
verifyUserBatchCount(proposal,latestText);
|
||||
if("purchase.correctHistory".equals(selectedAction))
|
||||
for(var row:AssistantConversationService.maps(proposal.get("rows")))row.put("acknowledgeArchiveOnly",false);
|
||||
if("purchase.referencePrice".equals(selectedAction))
|
||||
for(var row:AssistantConversationService.maps(proposal.get("rows")))row.put("acknowledgeArchiveOnly",false);
|
||||
if("purchase.correctPrice".equals(selectedAction)) {
|
||||
var targets=AssistantConversationService.maps(context.get("quotationTargets"));
|
||||
var batches=targets.stream().map(row->row.get("purchaseBatchId")).distinct().toList();
|
||||
@ -204,6 +209,18 @@ public class AssistantModelClient {
|
||||
return source.restore(proposal);
|
||||
}
|
||||
|
||||
/** Native round-trip import accepts Excel only. Never send a PDF/image to its workbook parser. */
|
||||
static Map<String,Object> quotationRoute(Map<String,Object> route,List<Map<String,Object>> files,List<Map<String,Object>> actions) {
|
||||
boolean quoteImport="purchase.importQuote".equals(route.get("action"))||"purchase.importQuote".equals(route.get("intentAction"));
|
||||
boolean document=files.stream().anyMatch(file->"image".equals(file.get("type"))
|
||||
||Objects.toString(file.get("name"),"").toLowerCase(Locale.ROOT).endsWith(".pdf")||"pdf".equals(file.get("extension")));
|
||||
if(!quoteImport||!document)return route;
|
||||
var definition=actions.stream().filter(action->"purchase.correctPrice".equals(action.get("key"))).findFirst().orElse(null);
|
||||
if(definition==null||!Boolean.TRUE.equals(definition.get("allowed")))
|
||||
return Map.of("kind","answer","message",definition==null?"PDF报价请采购管理员协助核对更正。":Objects.toString(definition.get("deniedReason"),AssistantMessages.forAction("purchase.correctPrice")));
|
||||
return Map.of("kind","draft","action","purchase.correctPrice","message","按报价文件逐项识别并匹配采购明细,生成价格更正核对单;尚未执行。");
|
||||
}
|
||||
|
||||
private Map<String,Object> quotationProposal(JSONObject context,Map<String,Object> selected,List<Map<String,Object>> files,
|
||||
String instruction,String trace,long started) {
|
||||
var sourceDefinition=new LinkedHashMap<>(selected);
|
||||
@ -214,14 +231,26 @@ public class AssistantModelClient {
|
||||
+"sourceName为物品名,sourceSpec为型号规格,sourceBrand为品牌,sourceQuantity为报价数量;finalUnitPrice是原文含税单价,不是合计或总价,不换算税率。"
|
||||
+"sourceAmount是每一行含税小计,也要抄录;单价×数量应与小计相符,不相符要回看原文,不得自行调价凑数。必须结合左右列放大图逐格读取,不能将整行小计作为1件单价。原文缺失或模糊的单价留null,不猜0。attachmentId填该行的原文件ID。建议用columns和二维rows压缩输出,attachmentId放defaults。输出purchase.correctPrice的draft,rows仅包含这些原文列和_sourceRow。",
|
||||
content(reading,files),List.of(sourceDefinition),"QUOTE_TRANSCRIBE",trace,Math.min(90000,remaining(started)),Math.max(4096,Math.min(maxOutputTokens,16384)),false,files);
|
||||
var source=AssistantQuotationRows.literal(literal);
|
||||
var source=AssistantQuotationRows.keyed(AssistantQuotationRows.literal(literal));
|
||||
var matching=new JSONObject(context);matching.put("literalQuotationRows",source);
|
||||
var mapped=call(instruction+"literalQuotationRows是已经完整读取的报价原文,不再读取图片。请逐项匹配quotationTargets或保留原名称待选择。"
|
||||
+"必须返回全部"+source.size()+"行,每行保留对应_sourceRow,不允许遗漏未匹配、未改价或信息不完整的行。"
|
||||
+"不能因系统里没有相应物品就忽略该报价。不新增采购。匹配明确时id用目标采购明细的真实id;否则id保留原文名称,供确认表进一步选择。"
|
||||
+"本阶段不得改变finalUnitPrice、原报价数量或原规格;输出原有采购更正字段即可,源价格及来源说明由服务端保留。",
|
||||
content(matching,List.of()),List.of(selected),"QUOTE_MATCH",trace,Math.min(60000,remaining(started)),Math.max(4096,Math.min(maxOutputTokens,16384)),false,List.of());
|
||||
return AssistantQuotationRows.ground(mapped,source);
|
||||
var matchDefinition=new LinkedHashMap<>(selected);
|
||||
matchDefinition.put("fields",List.of(Map.of("key","sourceKey","type","text"),Map.of("key","id","type","number")));
|
||||
matching.put("allowedActionDefinitions",modelDefinitions(List.of(matchDefinition)));
|
||||
Map<String,Object> mapped;
|
||||
try {
|
||||
mapped=call(prompt()+"本阶段只给literalQuotationRows附加采购匹配建议,不再转写文件,不输出单价、金额、原因等业务字段。"
|
||||
+"sourceKey是服务器给每条原报价分配的不可变标识,必须原样返回,不能用序号替代、重排编号或合并相似物品。"
|
||||
+"逐项按名称、规格、品牌匹配quotationTargets,唯一明确时id填其真实采购明细ID;不确定或系统中不存在则id填null,仍保留该sourceKey。"
|
||||
+"输出purchase.correctPrice的draft,仅有sourceKey和id两列。总共"+source.size()+"项,禁止新增采购;原报价与行数由服务器保留。",
|
||||
content(matching,List.of()),List.of(matchDefinition),"QUOTE_MATCH",trace,Math.min(60000,remaining(started)),Math.max(4096,Math.min(maxOutputTokens,16384)),false,List.of());
|
||||
} catch(ModelFailure failure) {
|
||||
log.warn("Assistant quotation matching needs manual review trace={} category={} sourceRows={}",trace,failure.category,source.size());
|
||||
mapped=Map.of("rows",List.of());
|
||||
}
|
||||
var targets=AssistantConversationService.maps(context.get("quotationTargets"));
|
||||
var grounded=AssistantQuotationRows.ground(mapped,source,targets);
|
||||
log.info("Assistant quotation ledger trace={} sourceRows={} suggestedRows={} retainedRows={}",trace,source.size(),AssistantConversationService.maps(mapped.get("rows")).size(),source.size());
|
||||
return grounded;
|
||||
}
|
||||
|
||||
/** A clear business with no object needs one concrete next question, not a fresh intent questionnaire. */
|
||||
@ -654,6 +683,8 @@ public class AssistantModelClient {
|
||||
/** A conversational patch applies to every row, so partial-row and ambiguous numeric edits must not reach it. */
|
||||
static Map<String, Object> guardDraftPatch(Map<String, Object> route, Map<String, Object> task, String text) {
|
||||
if (!"patch".equals(route.get("kind"))) return route;
|
||||
if(route.get("changes") instanceof Map<?,?> changes&&changes.containsKey("acknowledgeArchiveOnly"))
|
||||
return Map.of("kind","clarify","message","请在确认表中阅读历史成本链影响,并由本人勾选核对;聊天回复不会代替勾选,也尚未执行业务。");
|
||||
String scopeText = patchScopeText(text, route.get("changes"));
|
||||
int count = task.get("rows") instanceof List<?> rows ? rows.size() : task.get("rowCount") instanceof Number number ? number.intValue() : 0;
|
||||
if (count>1 && scopeText.matches("(?s).*(?:第[0-9零一二两三四五六七八九十百]+(?:[行条项笔]|[个种台位名]?(?:物品|设备|材料|用户|账号|记录))|[这那](?:一)?[行条项笔个台种]|[前后][0-9零一二两三四五六七八九十百]+[行条项笔个台种]|选中行|部分行|单独).*"))
|
||||
@ -1011,8 +1042,8 @@ public class AssistantModelClient {
|
||||
private String routingPrompt() {
|
||||
return "你是项目采购库存生产系统的业务意图分类器,只输出JSON,不执行任何操作。"
|
||||
+ participantRules()
|
||||
+ "区分新增业务入口:当前登录人收到的站内消息/未读消息用notification系列,不是面向全员发布的notice通知公告。反馈负责人角色、归属分析、邮件预览或发送用feedbackNotification系列,普通账号不得因此查看全部反馈。"
|
||||
+ "必须区分采购报价与内部参考实际单价:修改实际单价、实际金额,或把实际单价与当前报价一致,使用purchase.referencePrice,不是purchase.correctPrice。同一批每条以各自报价为准用COPY_QUOTE,后端读取全批次,无需用户逐行提供价格;指定实际单价值用SET;明确清空用CLEAR。仅说两种价格改相同而方向不明可追问以谁为准;但上一轮已经询问实际单价改为与报价一致、用户答确定,应直接整理purchase.referencePrice/COPY_QUOTE确认单,不得再说不支持实际单价或切换成改报价。语义确认不代表执行业务,最终仍点击确认卡。"
|
||||
+ "区分新增业务入口:当前登录人收到的站内消息/未读消息用notification.query/detail/unread,不是面向全员发布的notice通知公告。主动给指定人发消息或邮件用notification.send,已接入通用通知中心,不得回答助手不能发送;旧对话中声称不支持的回答不是当前能力依据,以本次actionIndex为准。普通消息默认站内INBOX,明确邮件用EMAIL,明确两种都发用BOTH。'给张浩发个消息通知,告诉他怎么使用消息通知和邮件'是站内消息,正文主题提到邮件不能擅自添加邮件渠道。可按要求拟标题和说明正文,生成收件人、渠道、标题、正文确认单;allowed=false交服务端温和提示;缺收件人或内容保留已有信息,重名由用户选择。不能自动发送或查看对方收件箱。反馈负责人角色、归属分析、邮件预览或发送用feedbackNotification系列,普通账号不得因此查看全部反馈。"
|
||||
+ "必须区分采购报价与内部参考实际单价:修改实际单价、实际金额,或把实际单价与当前报价一致,使用purchase.referencePrice,不是purchase.correctPrice。同一批每条以各自报价为准用COPY_QUOTE,后端读取全批次,无需用户逐行提供价格;指定实际单价值用SET;清空实际单价用CLEAR。用户要求先复制当前报价到实际单价再清空报价,使用同一purchase.referencePrice的COPY_QUOTE_CLEAR_QUOTE模式,是已支持的一项组合操作,不拆成两项业务、不反问已明确的顺序。结合上文答'两个一起/两项都做/确定'应继续同一组合确认单,不能只保留复制部分。服务端会核对报价能否清空并逐项说明;不能把清空替换成0元或自行跳过受限记录。仅说两种价格改相同而方向不明可追问以谁为准;但上一轮已经询问实际单价改为与报价一致、用户答确定,应直接整理purchase.referencePrice/COPY_QUOTE确认单,不得再说不支持实际单价或切换成改报价。语义确认不代表执行业务,最终仍点击确认卡。"
|
||||
+ "更新、更正、修改已有采购价格,或按PDF/图片/Excel报价文件更新某项目或某批次价格,使用purchase.correctPrice(支持多物品,也支持历史已到货采购)。不要因PDF仅元信息而追问全部价格:选中此操作后服务端会读取PDF正文再提取。采购资料保存、合同PDF、流程编号用purchase.document系列;保存文件不等于采购导入、不等于验收或付款。供应商营业执照用supplier.license系列。供应商询价单导出用purchase.inquiryExport,特定询价模板Excel原样回传可用purchase.importQuote,不用purchase.create重新采购。Excel导出和模板下载选对应export/template查询能力,不能用普通列表查询冒充生成文件。"
|
||||
+ "保存文件只需要附件元信息,不需要读取文档正文。例如'把这个PDF保存为采购批次CG_TEST01的合同附件'配合合同.pdf附件,已明确purchase.documentUploadbatch,应直接draft,不要求用户把PDF转换为图片或补充正文,不因批次尚未查库而追问编号。批次用原文交系统匹配,资料类型为CONTRACT;同句指定合同、申请、报价、验收或付款编号时一并填number,未指定则省略,不能漏掉已提供编号。"
|
||||
+ "产品系列的不同产品版本有独立物品和库存。新增试制版、量产版等产品版本选product.versionCreate,不是bom.copy;改系列或产品版本名称选product.save,查同系列选product.versions。明确来源产品版本用引用对象{keyword:'产品名称',editionTag:'原有版本'},指定系列也可补seriesName;不要把产品名称和版本名拼成不存在的物品名称。产品版本附件查询/保存/移除/查看下载分别用product.attachments/product.attachmentUpload/product.attachmentRemove/product.attachmentDownload。产品附件50MB仅保存,不读取正文,不能让用户重抄内容;明确要复制物品才cloneItem=true,明确复制哪个BOM才copyBomId,缺信息交确认表补充。"
|
||||
|
||||
@ -0,0 +1,80 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.util.*;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.notification.NotificationGateway;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.system.notification.NotificationMailSender;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Confirmed assistant messages reuse the existing SYSTEM_MESSAGE policy and transactional outbox. */
|
||||
@Component
|
||||
public class AssistantNotificationService {
|
||||
@Autowired private JdbcTemplate db;
|
||||
@Autowired private NotificationGateway notifications;
|
||||
@Autowired private NotificationMailSender mail;
|
||||
@Value("${notification-center.enabled:false}") private boolean enabled;
|
||||
|
||||
private void permission() {
|
||||
if(!SecurityUtils.isAdmin())throw new ServiceException(AssistantMessages.forAction("notification.send"),403);
|
||||
if(!enabled)throw new ServiceException("消息服务暂未启用,可以请管理员核对通知中心配置");
|
||||
}
|
||||
private Set<Long> recipients(Map<String,Object> row) {
|
||||
if(!(row.get("userIds") instanceof List<?> values)||values.isEmpty()||values.size()>50)
|
||||
throw new ServiceException("请选择1至50名接收人;同名用户请按账号或部门明确选择");
|
||||
var ids=new LinkedHashSet<Long>();
|
||||
for(var value:values)ids.add(AssistantExtendedActions.id(Map.of("id",Objects.toString(value,"")),"id"));
|
||||
return ids;
|
||||
}
|
||||
private Set<NotificationGateway.Channel> channels(Map<String,Object> row) {
|
||||
return switch(Objects.toString(row.get("channel"),"")) {
|
||||
case "INBOX" -> Set.of(NotificationGateway.Channel.INBOX);
|
||||
case "EMAIL" -> Set.of(NotificationGateway.Channel.EMAIL);
|
||||
case "BOTH" -> Set.of(NotificationGateway.Channel.INBOX,NotificationGateway.Channel.EMAIL);
|
||||
default -> throw new ServiceException("请选择站内消息、邮件或两种都发送");
|
||||
};
|
||||
}
|
||||
private String text(Map<String,Object> row,String key,String label,int maximum) {
|
||||
String value=Objects.toString(row.get(key),"").trim();
|
||||
if(value.isBlank()||value.length()>maximum||value.indexOf('\0')>=0||key.equals("title")&&value.chars().anyMatch(Character::isISOControl))
|
||||
throw new ServiceException("请填写"+label+",最多"+maximum+"字;标题不能包含换行");
|
||||
return value;
|
||||
}
|
||||
public Map<String,Object> preview(Map<String,Object> row) {
|
||||
permission();var ids=recipients(row);var selected=channels(row);
|
||||
String title=text(row,"title","消息标题",240),content=text(row,"content","消息内容",10000);
|
||||
boolean email=selected.contains(NotificationGateway.Channel.EMAIL);
|
||||
if(email&&!mail.ready())throw new ServiceException("邮件服务暂未就绪,可以先选择站内消息,或请管理员核对发件配置");
|
||||
var users=new ArrayList<Map<String,Object>>();var problems=new ArrayList<String>();
|
||||
for(Long id:ids) {
|
||||
var found=db.queryForList("select user_id,user_name,nick_name,email,status,del_flag from sys_user where user_id=?",id);
|
||||
if(found.size()!=1||!"0".equals(found.get(0).get("status"))||!"0".equals(found.get(0).get("del_flag")))
|
||||
throw new ServiceException("所选接收人已不存在或停用,请重新选择;尚未发送消息");
|
||||
var user=found.get(0);String address=Objects.toString(user.get("email"),"").trim();
|
||||
var target=new LinkedHashMap<String,Object>();target.put("id",id);target.put("account",user.get("user_name"));target.put("name",user.get("nick_name"));
|
||||
if(email) {
|
||||
target.put("email",address);
|
||||
if(!NotificationMailSender.validAddress(address))problems.add(Objects.toString(user.get("nick_name"),user.get("user_name").toString()));
|
||||
}
|
||||
users.add(target);
|
||||
}
|
||||
if(!problems.isEmpty())throw new ServiceException("以下接收人尚未填写有效邮箱:"+String.join("、",problems)+"。请补充邮箱后重新预览,或明确改用站内消息;本次未发送");
|
||||
return Map.of("recipients",users,"channel",row.get("channel"),"title",title,"content",content,
|
||||
"notice",email?"人工确认后提交通知中心;邮件进入发送队列不代表已送达,响应不明确时先核对,勿重复发送。":"人工确认后发送到所选用户的站内消息,不会发送邮件。", "emailRequired",email);
|
||||
}
|
||||
public Map<String,Object> send(Map<String,Object> row) {
|
||||
preview(row); // Also rechecks permissions, active accounts and current email on every attempt.
|
||||
String key=Objects.toString(row.get("_executionKey"),"");
|
||||
if(!key.matches("[A-Za-z0-9_-]{8,90}"))throw new ServiceException("请通过待确认消息卡片提交,不能直接发送");
|
||||
var command=new NotificationGateway.Command("SYSTEM_MESSAGE","assistant:"+SecurityUtils.getUserId(),
|
||||
"AI:"+SecurityUtils.getUserId()+":"+key,text(row,"title","消息标题",240),text(row,"content","消息内容",10000),
|
||||
recipients(row),Set.of(),channels(row),"");
|
||||
var receipt=notifications.publish(command);
|
||||
return Map.of("eventId",receipt.eventId(),"duplicate",receipt.duplicate(),"inboxDelivered",receipt.inboxDelivered(),
|
||||
"emailQueued",receipt.emailQueued(),"emailBlocked",receipt.emailBlocked(),
|
||||
"message",receipt.duplicate()?"本次通知此前已提交,未重复发送。":"通知已提交:站内消息"+receipt.inboxDelivered()+"条;邮件排队"+receipt.emailQueued()+"条,待核对"+receipt.emailBlocked()+"条。邮件排队不代表已送达。");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,65 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Only grounds one explicit, supported combination. No reads/writes, guessed ids or automatic execution. */
|
||||
final class AssistantPriceInstructions {
|
||||
private AssistantPriceInstructions() { }
|
||||
private static final String ACTION="purchase.referencePrice";
|
||||
private static final Pattern BATCH=Pattern.compile("(?i)(?<![A-Z0-9])CG[0-9]{6,20}(?![A-Z0-9])");
|
||||
private static String compact(String text) { return text.replaceAll("[\\s,,。!!;;::]",""); }
|
||||
private static boolean continuation(String text) {
|
||||
return compact(text).matches("(?:确定|确认|是|对|两个一起|两项一起|两个都做|两项都做|都做|一起做|1和2都做|1、2都做|全部一起)(?:执行|做|办理)?");
|
||||
}
|
||||
private static boolean combination(String text) {
|
||||
String value=compact(text);
|
||||
if(value.matches("(?s).*(?:不要|不用|不需要|不必|不是|不把|不能|先不|暂不|不做|不执行|别|不清空|不复制|取消|撤销|撤回|停止|查询|怎么|如何|能不能|是否|[??]|发邮件|入库|出库|新增|创建|删除批次|转批次|修改数量|修改项目).*"))return false;
|
||||
var copy=Pattern.compile("报价(?:单价)?.{0,8}(?:复制|拷贝|改到|转到|转入|填入|写入|作为|放到|移到).{0,8}实际单价|实际单价.{0,6}(?:取|以|使用|等于|设为|改为).{0,8}报价(?:单价)?").matcher(value);
|
||||
var clear=Pattern.compile("(?:清空|清除|去掉|删掉).{0,4}报价(?:单价)?").matcher(value);
|
||||
// An explicitly reversed/destructive sequence or opposite assignment is not this fixed operation.
|
||||
return copy.find()&&clear.find()&©.start()<clear.start();
|
||||
}
|
||||
static Map<String,Object> propose(List<Map<String,Object>> messages,List<Map<String,Object>> definitions,Map<String,Object> task) {
|
||||
if("CANCELLED".equals(task.get("status")))return null;
|
||||
var users=messages.stream().filter(row->"user".equals(row.get("role"))).map(row->Objects.toString(row.get("content"),"")).toList();
|
||||
if(users.isEmpty())return null;
|
||||
String text=users.get(users.size()-1);
|
||||
boolean clearOnly=compact(text).matches("(?i)(?:CG[0-9]{6,20})?(?:走|用|通过|按)?(?:更正(?:价格|报价)(?:的)?(?:方式|流程))?(?:仅|只)?清空报价(?:单价)?(?:即可)?");
|
||||
if(clearOnly) {
|
||||
Object batch=null;var explicit=BATCH.matcher(text);if(explicit.find())batch=explicit.group().toUpperCase(Locale.ROOT);
|
||||
if(batch==null&&ACTION.equals(task.get("action"))) {
|
||||
var scopes=AssistantConversationService.maps(task.get("rows"));
|
||||
if(scopes.size()==1)batch=scopes.get(0).get("purchaseBatchId");
|
||||
}
|
||||
if(batch!=null) {
|
||||
var definition=definitions.stream().filter(row->ACTION.equals(row.get("key"))).findFirst().orElse(null);
|
||||
if(definition==null)return null;
|
||||
if(!Boolean.TRUE.equals(definition.get("allowed")))return Map.of("kind","answer","message",Objects.toString(definition.get("deniedReason"),AssistantMessages.forAction(ACTION)));
|
||||
return Map.of("kind","draft","action",ACTION,"message","仅清空指定批次报价,保留实际金额;请核对金额与成本联动影响,确认后才执行。",
|
||||
"rows",List.of(Map.of("purchaseBatchId",batch,"mode","CLEAR_QUOTE","acknowledgeArchiveOnly",false)));
|
||||
}
|
||||
}
|
||||
if(continuation(text)) {
|
||||
// Do not revive a price request across an unrelated user instruction or another active draft.
|
||||
if(task.get("action")!=null&&!ACTION.equals(task.get("action")))return null;
|
||||
int i=users.size()-2;while(i>=0&&continuation(users.get(i)))i--;
|
||||
if(i<0)return null;text=users.get(i);
|
||||
}
|
||||
if(!combination(text))return null;
|
||||
var definition=definitions.stream().filter(row->ACTION.equals(row.get("key"))).findFirst().orElse(null);
|
||||
if(definition==null)return null;
|
||||
if(!Boolean.TRUE.equals(definition.get("allowed")))return Map.of("kind","answer","message",Objects.toString(definition.get("deniedReason"),AssistantMessages.forAction(ACTION)));
|
||||
var batches=new LinkedHashSet<String>();var matcher=BATCH.matcher(text);while(matcher.find())batches.add(matcher.group().toUpperCase(Locale.ROOT));
|
||||
if(batches.isEmpty()&&(task.get("action")==null||ACTION.equals(task.get("action")))&&compact(text).matches("(?:两项都做|两个一起|两个都做|都做).*")) {
|
||||
for(int i=users.size()-2;i>=0;i--) {
|
||||
String previous=users.get(i);if(continuation(previous))continue;
|
||||
if(combination(previous)) {var priorBatch=BATCH.matcher(previous);while(priorBatch.find())batches.add(priorBatch.group().toUpperCase(Locale.ROOT));}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(batches.size()!=1)return null; // Other scopes still go through normal grounded extraction.
|
||||
return Map.of("kind","draft","action",ACTION,"message","将先按每条修改前的报价设置实际单价,再清空报价,合并为一张确认单。请核对前后金额及受限项,点击确认后才会保存。",
|
||||
"rows",List.of(Map.of("purchaseBatchId",batches.iterator().next(),"mode","COPY_QUOTE_CLEAR_QUOTE","acknowledgeArchiveOnly",false)));
|
||||
}
|
||||
}
|
||||
@ -20,8 +20,10 @@ public class AssistantQuotationContext {
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))
|
||||
throw new ServiceException("价格更正请由采购管理员协助办理",403);
|
||||
var codes=new LinkedHashSet<String>();var pattern=Pattern.compile("(?i)(?<![A-Za-z0-9])CG[0-9]{8,20}(?![A-Za-z0-9])");
|
||||
for(var message:messages)if("user".equals(message.get("role"))) {
|
||||
var matcher=pattern.matcher(Objects.toString(message.get("content"),""));while(matcher.find())codes.add(matcher.group().toUpperCase(Locale.ROOT));
|
||||
// The latest explicit scope replaces previous batches, rather than silently combining old tasks.
|
||||
for(int i=messages.size()-1;i>=0;i--)if("user".equals(messages.get(i).get("role"))) {
|
||||
var matcher=pattern.matcher(Objects.toString(messages.get(i).get("content"),""));while(matcher.find())codes.add(matcher.group().toUpperCase(Locale.ROOT));
|
||||
if(!codes.isEmpty())break;
|
||||
}
|
||||
if(codes.size()>3)throw new ServiceException("本次涉及多个采购批次,请明确本次要更正的批次后继续");
|
||||
var result=new ArrayList<Map<String,Object>>();
|
||||
|
||||
@ -30,18 +30,39 @@ final class AssistantQuotationRows {
|
||||
for(int n=1;n<=rows.size();n++)if(!ordered.containsKey(n))throw invalid();
|
||||
return new ArrayList<>(ordered.values());
|
||||
}
|
||||
static Map<String,Object> ground(Map<String,Object> proposal,List<Map<String,Object>> source) {
|
||||
var rows=AssistantConversationService.maps(proposal.get("rows"));if(!"draft".equals(proposal.get("kind"))||rows.size()!=source.size())throw invalid();
|
||||
var indexes=new HashMap<Integer,Map<String,Object>>();source.forEach(row->indexes.put(index(row),row));
|
||||
var seen=new HashSet<Integer>();var output=new ArrayList<Map<String,Object>>();
|
||||
for(var row:rows) {
|
||||
int n=index(row);if(!seen.add(n)||!indexes.containsKey(n))throw invalid();var original=indexes.get(n);var result=new LinkedHashMap<>(row);
|
||||
static List<Map<String,Object>> keyed(List<Map<String,Object>> source) {
|
||||
return source.stream().map(row->{var copy=new LinkedHashMap<>(row);copy.put("sourceKey","q"+UUID.randomUUID().toString().replace("-","").substring(0,12));return (Map<String,Object>)copy;}).toList();
|
||||
}
|
||||
/** The source ledger owns row count/order/prices. The model may only suggest an existing scoped target. */
|
||||
static Map<String,Object> ground(Map<String,Object> proposal,List<Map<String,Object>> source,List<Map<String,Object>> targets) {
|
||||
var suggestions=new HashMap<String,List<Map<String,Object>>>();
|
||||
for(var row:AssistantConversationService.maps(proposal.get("rows"))) {
|
||||
String key=Objects.toString(row.get("sourceKey"),"");
|
||||
if(!key.isBlank())suggestions.computeIfAbsent(key,unused->new ArrayList<>()).add(row);
|
||||
}
|
||||
var allowed=new HashMap<String,Object>();
|
||||
for(var target:targets)if(target.get("id")!=null)allowed.put(target.get("id").toString(),target.get("id"));
|
||||
var sourceKeys=new HashSet<String>();var sourceIndexes=new HashSet<Integer>();var output=new ArrayList<Map<String,Object>>();int unresolved=0;
|
||||
for(var original:source) {
|
||||
int n=index(original);String key=Objects.toString(original.get("sourceKey"),"");
|
||||
if(key.isBlank()||!sourceKeys.add(key)||!sourceIndexes.add(n))throw invalid();
|
||||
var matches=suggestions.getOrDefault(key,List.of());Object id=matches.size()==1?matches.get(0).get("id"):null;
|
||||
// Never join by a row number the model can renumber after omitting an item.
|
||||
Object target=allowed.get(Objects.toString(id,""));
|
||||
var result=new LinkedHashMap<String,Object>();result.put("_sourceRow",n);
|
||||
if(target!=null)result.put("id",target);
|
||||
else {
|
||||
unresolved++;
|
||||
var reference=new LinkedHashMap<String,Object>();reference.put("name",original.get("sourceName"));
|
||||
if(original.get("sourceSpec")!=null&&!original.get("sourceSpec").toString().isBlank())reference.put("spec",original.get("sourceSpec"));
|
||||
result.put("id",reference);
|
||||
}
|
||||
result.put("finalUnitPrice",original.get("finalUnitPrice"));result.put("attachmentId",original.get("attachmentId"));
|
||||
result.put("_sourceText","报价第"+n+"项:"+original.get("sourceName")+";规格:"+Objects.toString(original.get("sourceSpec"),"")+";品牌:"+Objects.toString(original.get("sourceBrand"),"")+";报价数量:"+Objects.toString(original.get("sourceQuantity"),"未识别")+";含税单价:"+Objects.toString(original.get("finalUnitPrice"),"待核对"));
|
||||
if(result.get("id")==null)result.put("id",original.get("sourceName"));
|
||||
result.putIfAbsent("reason","依据供应商报价文件更正");output.add(result);
|
||||
result.put("reason","依据供应商报价文件更正");output.add(result);
|
||||
}
|
||||
var result=new LinkedHashMap<>(proposal);result.put("rows",output);return result;
|
||||
return Map.of("kind","draft","action","purchase.correctPrice","rows",output,"message",
|
||||
"已完整保留报价文件的"+source.size()+"项,未执行改价。"+(unresolved>0?"其中"+unresolved+"项尚需核对匹配,请在确认表选择对应采购,或勾选本项暂不更正;不会遗漏或新增采购。":"请核对逐项报价与金额后确认。"));
|
||||
}
|
||||
private static int index(Map<String,Object> row){try{return new BigDecimal(Objects.toString(row.get("_sourceRow"),"")).intValueExact();}catch(Exception e){throw invalid();}}
|
||||
private static ServiceException invalid(){return new ServiceException("报价明细识别不完整或匹配时遗漏了原文件行,尚未生成可执行确认单,请重新识别或拆分报价文件");}
|
||||
|
||||
@ -12,14 +12,16 @@ import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseSheetService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchasePriceCorrectionService;
|
||||
import com.ruoyi.warehouse.util.PurchaseReferenceAmounts;
|
||||
|
||||
/** Changes internal reference amounts through the native sheet save, never cost prices. */
|
||||
/** Reference-only changes use the native sheet; clearing quotes uses the audited native cost correction. */
|
||||
@Component
|
||||
public class AssistantReferencePriceService {
|
||||
@Autowired private PurchaseSheetService sheets;
|
||||
@Autowired private PurchaseRequestMapper requests;
|
||||
@Autowired private IProjectInfoService projects;
|
||||
@Autowired private PurchasePriceCorrectionService corrections;
|
||||
|
||||
private void permission() {
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:edit")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))
|
||||
@ -46,44 +48,78 @@ public class AssistantReferencePriceService {
|
||||
}
|
||||
private BigDecimal target(Map<String,Object> row,PurchaseRequest value) {
|
||||
return switch(Objects.toString(row.get("mode"),"")) {
|
||||
case "COPY_QUOTE" -> value.getFinalUnitPrice();
|
||||
case "COPY_QUOTE", "COPY_QUOTE_CLEAR_QUOTE" -> value.getFinalUnitPrice();
|
||||
case "SET" -> {if(row.get("actualUnitPrice")==null)throw new ServiceException("请补充要设置的实际单价");yield new BigDecimal(row.get("actualUnitPrice").toString());}
|
||||
case "CLEAR" -> null;
|
||||
case "CLEAR_QUOTE" -> value.getActualUnitPrice();
|
||||
default -> throw new ServiceException("请选择以报价为准、指定实际单价或清空实际单价");
|
||||
};
|
||||
}
|
||||
private boolean equal(BigDecimal a,BigDecimal b) { return a==null||b==null?a==b:a.compareTo(b)==0; }
|
||||
private BigDecimal amount(BigDecimal price,BigDecimal quantity) { return price==null?null:price.multiply(quantity).setScale(2,RoundingMode.HALF_UP); }
|
||||
private boolean clearsQuote(Map<String,Object> input) { return Set.of("COPY_QUOTE_CLEAR_QUOTE","CLEAR_QUOTE").contains(Objects.toString(input.get("mode"),"")); }
|
||||
private void correctionPermission(Map<String,Object> input) {
|
||||
if(clearsQuote(input)&&!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))
|
||||
throw new ServiceException("清空报价涉及金额及成本更正,请采购管理员协助办理",403);
|
||||
}
|
||||
private PurchasePriceCorrectionService.Correction correction(Map<String,Object> input,String version) {
|
||||
return new PurchasePriceCorrectionService.Correction(null,
|
||||
"COPY_QUOTE_CLEAR_QUOTE".equals(input.get("mode"))?"按确认指令复制原报价到实际单价并清空报价":"按确认指令清空采购报价",
|
||||
version,Boolean.TRUE.equals(input.get("acknowledgeArchiveOnly")),true,"COPY_QUOTE_CLEAR_QUOTE".equals(input.get("mode")));
|
||||
}
|
||||
private List<Map<String,Object>> previewRows(Map<String,Object> input,Scope scope) {
|
||||
var rows=new ArrayList<Map<String,Object>>();
|
||||
for(var value:scope.selected()) {
|
||||
BigDecimal price=target(input,value);PurchaseReferenceAmounts.validate(price);
|
||||
boolean unquoted="COPY_QUOTE".equals(input.get("mode"))&&price==null;
|
||||
boolean unquoted=("COPY_QUOTE".equals(input.get("mode"))&&price==null)||(clearsQuote(input)&&value.getFinalUnitPrice()==null);
|
||||
boolean cancelled=Integer.valueOf(5).equals(value.getPurchaseStatus());
|
||||
String note=cancelled?"已取消,本次跳过":unquoted?"尚未报价,保留原实际单价":equal(value.getActualUnitPrice(),price)?"已一致,无需修改":"待确认,仅修改内部参考金额";
|
||||
boolean changed=!cancelled&&!unquoted&&!equal(value.getActualUnitPrice(),price);
|
||||
String restriction="";Map<String,Object> impact=Map.of();
|
||||
if(clearsQuote(input)&&!cancelled&&!unquoted) {
|
||||
try {
|
||||
impact=corrections.preview(value.getId(),correction(input,null));
|
||||
if(((Number)impact.get("archiveOnlyCount")).intValue()>0&&!Boolean.TRUE.equals(input.get("acknowledgeArchiveOnly")))
|
||||
restriction="历史成本链不完整,请阅读影响说明并本人勾选确认";
|
||||
} catch(ServiceException failure) {restriction=failure.getMessage();}
|
||||
}
|
||||
String note=cancelled?"已取消,本次跳过":unquoted?"尚未报价,保留原实际单价":!restriction.isEmpty()?restriction:clearsQuote(input)?"待确认:先复制原报价,再清空报价;两项一起提交":equal(value.getActualUnitPrice(),price)?"已一致,无需修改":"待确认,仅修改内部参考金额";
|
||||
boolean changed=!cancelled&&!unquoted&&(clearsQuote(input)||!equal(value.getActualUnitPrice(),price));
|
||||
var row=new LinkedHashMap<String,Object>();row.put("id",value.getId());row.put("requestNo",value.getRequestNo());row.put("name",value.getMaterialName());row.put("spec",value.getMaterialParams());row.put("brand",value.getMaterialBrand());row.put("quantity",value.getQuantity());
|
||||
row.put("quotePrice",value.getFinalUnitPrice());row.put("oldActualPrice",value.getActualUnitPrice());row.put("newActualPrice",changed?price:value.getActualUnitPrice());
|
||||
row.put("oldActualAmount",value.getActualAmount());row.put("newActualAmount",amount(changed?price:value.getActualUnitPrice(),value.getQuantity()));row.put("changed",changed);row.put("notice",note);rows.add(row);
|
||||
row.put("clearQuote",clearsQuote(input));row.put("newQuotePrice",changed&&clearsQuote(input)?null:value.getFinalUnitPrice());
|
||||
row.put("oldQuoteAmount",amount(value.getFinalUnitPrice(),value.getQuantity()));row.put("newQuoteAmount",changed&&clearsQuote(input)?null:amount(value.getFinalUnitPrice(),value.getQuantity()));
|
||||
row.put("blocked",!restriction.isEmpty());row.put("correctionImpact",impact);
|
||||
if(!impact.isEmpty())row.put("notice",(restriction.isEmpty()?"":restriction+";")+impact.get("notice"));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
public Map<String,Object> preview(Map<String,Object> input) {
|
||||
var scope=scope(input);var rows=previewRows(input,scope);var result=new LinkedHashMap<String,Object>();
|
||||
correctionPermission(input);var scope=scope(input);var rows=previewRows(input,scope);var result=new LinkedHashMap<String,Object>();
|
||||
result.put("version",scope.sheet().getVersion());result.put("rows",rows);
|
||||
result.put("changed",rows.stream().filter(row->Boolean.TRUE.equals(row.get("changed"))).count());
|
||||
result.put("notice","实际金额=采购数量×实际单价;只作内部参考,不修改报价、采购金额、费用锁定或库存成本,不触发采购确认、到货或入库。");return result;
|
||||
result.put("blocked",rows.stream().filter(row->Boolean.TRUE.equals(row.get("blocked"))).count());
|
||||
result.put("notice",clearsQuote(input)?("COPY_QUOTE_CLEAR_QUOTE".equals(input.get("mode"))?"先复制每条原报价到实际单价,再清空报价。":"保留实际金额,仅清空报价。")+"使用价格更正流程,历史、锁价、到货和入库数据均可核对;解除对应费用锁定,关联成本重算为待补全,不是0元。数量与状态不变,整批确认后原子提交。":"实际金额=采购数量×实际单价;只作内部参考,不修改报价、采购金额、费用锁定或库存成本,不触发采购确认、到货或入库。");return result;
|
||||
}
|
||||
@Transactional
|
||||
public Map<String,Object> apply(Map<String,Object> input,String executionKey) {
|
||||
var scope=scope(input);
|
||||
correctionPermission(input);var scope=scope(input);
|
||||
if(!Objects.equals(scope.sheet().getVersion(),input.get("referenceVersion")))throw new ServiceException("采购报价或实际金额已变化,请重新预览后确认");
|
||||
var changes=previewRows(input,scope);var ids=new HashSet<Long>();
|
||||
if(changes.stream().anyMatch(row->Boolean.TRUE.equals(row.get("blocked"))))throw new ServiceException("部分明细暂不能清空报价,请核对逐项说明;实际单价和报价均未修改");
|
||||
for(var value:changes)if(Boolean.TRUE.equals(value.get("changed")))ids.add(((Number)value.get("id")).longValue());
|
||||
if(ids.isEmpty())throw new ServiceException("实际金额已经符合要求,无需重复修改");
|
||||
if(clearsQuote(input)) {
|
||||
var entries=new ArrayList<PurchasePriceCorrectionService.Entry>();
|
||||
for(var change:changes)if(Boolean.TRUE.equals(change.get("changed"))) {
|
||||
var impact=(Map<?,?>)change.get("correctionImpact");
|
||||
entries.add(new PurchasePriceCorrectionService.Entry(((Number)change.get("id")).longValue(),correction(input,Objects.toString(impact.get("version"),null))));
|
||||
}
|
||||
corrections.correctBatch(entries);
|
||||
return Map.of("message","已更正"+ids.size()+"项报价及关联金额,明细核对见确认记录","changed",ids.size(),"rows",changes);
|
||||
}
|
||||
for(var value:scope.selected())if(ids.contains(value.getId()))value.setActualUnitPrice(target(input,value));
|
||||
scope.sheet().setDeletedIds(List.of());scope.sheet().setSubmissionKey(executionKey);sheets.save(scope.sheet());
|
||||
return Map.of("message","已更新"+ids.size()+"项实际单价及实际金额;报价和成本未改变","changed",ids.size(),"rows",changes,
|
||||
"columns",List.of(Map.of("key","name","label","物品"),Map.of("key","spec","label","规格"),Map.of("key","oldActualPrice","label","原实际单价"),Map.of("key","newActualPrice","label","新实际单价"),Map.of("key","newActualAmount","label","新实际金额"),Map.of("key","notice","label","核对说明")));
|
||||
"columns",List.of(Map.of("key","name","label","物品"),Map.of("key","spec","label","规格"),Map.of("key","oldActualPrice","label","原实际单价"),Map.of("key","newActualPrice","label","新实际单价"),Map.of("key","newActualAmount","label","新实际金额"),Map.of("key","quotePrice","label","原报价"),Map.of("key","newQuotePrice","label","新报价"),Map.of("key","newQuoteAmount","label","新报价金额"),Map.of("key","notice","label","核对说明")));
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,7 +46,7 @@ public class BusinessActionRegistry {
|
||||
private static final TypeReference<Map<String,Object>> MAP = new TypeReference<>() {};
|
||||
private static final String BOM_LINES_QUERY="select item_id itemId,unit_quantity unitQuantity,child_bom_id childBomId,remark from bom_line where bom_id=? and del_flag='0' order by sort_order,id";
|
||||
private static final Set<String> PURCHASE_ACTIONS=Set.of("purchase.create","purchase.update");
|
||||
private static final Set<String> SYSTEM_DERIVED_FIELDS=Set.of("previousRoleNames","previousPermissionNames","resultRoleNames","resultPermissionNames","quoteSummary","recipients","subject","body","previousValue","operationNotice");
|
||||
private static final Set<String> SYSTEM_DERIVED_FIELDS=Set.of("previousRoleNames","previousPermissionNames","resultRoleNames","resultPermissionNames","quoteSummary","recipients","subject","body","previousValue","operationNotice","recipientSummary","deliveryNotice");
|
||||
private static final Set<String> PURCHASE_COMMON_FIELDS=Set.of("projectId","expenseCategoryId","purchaseBatchId","batchName","supplierId","businessDate","purchasePurpose","productionTaskId","unit","category");
|
||||
|
||||
record Field(String key, String label, String type, boolean required, String ref, Map<String,String> options) {
|
||||
@ -95,7 +95,7 @@ public class BusinessActionRegistry {
|
||||
if("purchase.correctPrice".equals(action.key())&&"skipCorrection".equals(field.key()))result.put("batch",true);
|
||||
if("text".equals(field.type())) {
|
||||
result.put("maxLength",textLimit(action,field));
|
||||
result.put("multiline",Set.of("description","reply","noticeContent","remark","reason","acceptanceRemark","quoteSummary","body","recipients","operationNotice").contains(field.key()));
|
||||
result.put("multiline",Set.of("description","reply","noticeContent","remark","reason","acceptanceRemark","quoteSummary","body","recipients","operationNotice","content","recipientSummary","deliveryNotice").contains(field.key()));
|
||||
}
|
||||
if(PURCHASE_ACTIONS.contains(action.key()) && PURCHASE_COMMON_FIELDS.contains(field.key())) {
|
||||
if("purchase.update".equals(action.key()) && Set.of("purchaseBatchId","batchName","supplierId","businessDate").contains(field.key()))result.put("readonly",true);
|
||||
@ -414,6 +414,7 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
if("purchase.referencePrice".equals(action)) {
|
||||
context.getBean(CatalogWriteLock.class).acquire();
|
||||
context.getBean(com.ruoyi.warehouse.service.impl.InventoryCostJournal.class).lockInventory();
|
||||
var preview=prepare(action,rows);
|
||||
if(!Boolean.TRUE.equals(preview.get("ready")))throw new ServiceException("请先核对实际单价及修改范围");
|
||||
var checked=(List<Map<String,Object>>)preview.get("rows");var ids=new HashSet<String>();
|
||||
@ -635,6 +636,7 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
|
||||
private static int textLimit(Action action,Field field) {
|
||||
if("notification.send".equals(action.key()))return switch(field.key()){case "title"->240;case "content"->10000;default->2000;};
|
||||
if(action.key().startsWith("product."))return switch(field.key()){case "seriesName"->160;case "editionTag","originalEditionTag","bomTag"->64;case "itemName"->100;case "itemSpec","remark"->500;default->2000;};
|
||||
if("purchase.correctPrice".equals(action.key())&&"reason".equals(field.key()))return 300;
|
||||
if(action.key().equals("feedback.create"))return switch(field.key()) {case "description"->5000;case "title","pageTitle"->100;case "pagePath"->500;default->2000;};
|
||||
@ -884,6 +886,7 @@ public class BusinessActionRegistry {
|
||||
private int businessFieldOrder(Action action,String key,boolean editor) {
|
||||
// In an edit/delete preview, id is a labelled business-record selector, not an internal-ID column.
|
||||
if(editor&&"id".equals(key))return 0;
|
||||
if(editor&&"notification.send".equals(action.key())){var order=List.of("userIds","channel","title","content","recipientSummary","deliveryNotice");int position=order.indexOf(key);if(position>=0)return position;}
|
||||
if(editor&&"product.versionCreate".equals(action.key())){var order=List.of("sourceProductId","seriesName","originalEditionTag","editionTag","cloneItem","itemId","itemName","itemSpec","copyBomId","bomTag","remark","operationNotice");int position=order.indexOf(key);if(position>=0)return position+1;}
|
||||
if(editor&&Set.of("purchaseRequestId","requestId","arrivalId").contains(key))return 5;
|
||||
String family="role.users".equals(action.key())?"user":Set.of("user.me","user.permissions").contains(action.key())?"menu":action.key().split("\\.")[0];
|
||||
@ -1027,9 +1030,9 @@ public class BusinessActionRegistry {
|
||||
text("materialName","新物品名称",false),text("materialParams","新规格型号",false),text("materialBrand","新品牌",false),ref("unit","新单位","unit",false),ref("category","新物品类别","category",false),
|
||||
number("quantity","新采购数量",false),number("actualUnitPrice","新实际单价",false),number("finalUnitPrice","新报价单价",false),ref("projectId","新所属项目","project",false),ref("expenseCategoryId","新经费科目","expense",false),
|
||||
text("purchaseLink","新采购链接",false),text("remark","新备注",false),ref("productionTaskId","新生产计划","task",false),select("purchasePurpose","新采购用途",false,"SELF","本项目使用","REPAY","归还借用"),ref("loanId","新归还借用","loan",false),flag("acknowledgeArchiveOnly","本人已核对历史成本链不完整的更正影响"));
|
||||
register("purchase.referencePrice","修改采购实际单价","批量或单条维护内部参考实际单价与自动计算的实际金额,支持以当前报价为准、指定数值或清空;历史已到货也可维护。不修改报价、采购金额和任何成本。先逐项展示新旧实际单价、金额再人工确认。",extra,"referencePrice","$body",false,Map.of(),
|
||||
register("purchase.referencePrice","维护采购实际金额与报价","批量或单条维护实际单价与实际金额;支持先复制原报价到实际单价再清空报价,或仅清空报价。清空使用采购管理员的价格更正流程,支持历史、锁价、到货和入库记录,解除对应费用锁定,关联成本变为待补全而非0元;逐项展示影响,整批原子提交,不改变数量和业务状态。单独维护实际金额不影响成本。",extra,"referencePrice","$body",false,Map.of(),
|
||||
ref("purchaseBatchId","采购批次(整批修改时选择)","batch",false),ref("id","采购明细(仅修改指定明细时选择)","purchase",false),
|
||||
select("mode","实际单价设置方式",true,"COPY_QUOTE","以当前报价为准","SET","指定实际单价","CLEAR","清空实际单价"),number("actualUnitPrice","指定实际单价",false),text("quoteSummary","内部参考金额说明",false));
|
||||
select("mode","金额设置方式",true,"COPY_QUOTE","以当前报价为准","COPY_QUOTE_CLEAR_QUOTE","复制报价到实际单价并清空报价","CLEAR_QUOTE","仅清空报价(保留实际金额)","SET","指定实际单价","CLEAR","清空实际单价"),number("actualUnitPrice","指定实际单价",false),flag("acknowledgeArchiveOnly","本人已核对历史成本链不完整的更正影响"),text("quoteSummary","金额及操作说明",false));
|
||||
register("purchase.correctPrice","更正采购报价","读取PDF、图片或Excel的多物品报价,逐项匹配已有采购明细并预览金额和成本联动;人工确认后整批更正,不新增采购、不改变数量、项目、到货状态或实际金额。历史和已到货报价也使用此操作。",extra,"correctPrice","$body",false,Map.of(),
|
||||
ref("projectId","所属项目","project",false),ref("purchaseBatchId","采购批次","batch",false),
|
||||
ref("id","采购明细","purchase",true),number("finalUnitPrice","新报价单价",true),text("reason","更正原因",true),
|
||||
@ -1055,6 +1058,9 @@ public class BusinessActionRegistry {
|
||||
query("notification.detail","站内消息详情",extra,"inboxDetail","id",number("id","消息编号",true));
|
||||
query("notification.unread","我的未读消息数量",extra,"inboxUnread","");
|
||||
add("notification.read","标记本人消息已读",extra,"inboxRead","$body",number("id","消息编号",true));
|
||||
register("notification.send","发送站内消息或邮件","由管理员向明确选择的系统用户发送站内消息、邮件或两者,一张确认单预览接收人、渠道、主题和正文后人工确认。消息通知默认站内;正文提到邮件不等于要求发邮件。不读取他人收件箱、不改账号或邮箱、不广播全员。邮件沿用账号邮箱及现有通知中心队列,缺邮箱需补充;重名先选择。不允许自动发送。",extra,"messageSend","$body",false,Map.of(),
|
||||
refs("userIds","接收人","sysUser"),select("channel","发送渠道",true,"INBOX","站内消息","EMAIL","邮件","BOTH","站内消息及邮件"),
|
||||
text("title","消息标题",true),text("content","消息正文",true),text("recipientSummary","实际接收人",false),text("deliveryNotice","投递说明",false));
|
||||
query("notice.top","我可查看的近期公告",extra,"noticeTop","");
|
||||
add("notice.read","标记公告已读",extra,"noticeRead","$body",ref("id","公告","readableNotice",true));
|
||||
query("notice.readers","公告阅读人员",SysNoticeController.class,"readUsersList","noticeId,searchValue",ref("noticeId","公告","notice",true),text("searchValue","用户关键词",false));
|
||||
|
||||
@ -57,6 +57,16 @@ class MovingAverageCostTest {
|
||||
Result unknownReturn = MovingAverageCost.replay(List.of(receipt(1,"1",null), issue(2,"1"), receipt(3,"2","20"), returned(4,"1",2)));
|
||||
assertNull(unknownReturn.balance().amount());
|
||||
}
|
||||
@Test void clearingExistingQuoteReplaysConsumedAndReturnedCostsAsUnknownAndCanBeRequoted() {
|
||||
var events=List.of(receipt(1,"10","100"),issue(2,"6"),returned(3,"2",2));
|
||||
var original=MovingAverageCost.replay(events);var cleared=MovingAverageCost.replay(events,Collections.singletonMap(1L,null));
|
||||
assertEquals(original.balance().quantity(),cleared.balance().quantity());
|
||||
assertNull(cleared.balance().amount());assertTrue(cleared.events().stream().allMatch(row->row.amount()==null));
|
||||
assertTrue(MovingAverageCost.differences(original,cleared).stream().allMatch(row->row.newAmount()==null&&row.delta()==null));
|
||||
assertEquals(n("100"),events.get(0).amount());
|
||||
var requoted=MovingAverageCost.replay(events,Map.of(1L,n("200")));assertEquals(n("120.000000"),requoted.balance().amount());
|
||||
assertEquals(n("120.000000"),requoted.events().get(1).amount());assertEquals(n("40.000000"),requoted.events().get(2).amount());
|
||||
}
|
||||
@Test void negativeInventoryOverReturnsInvalidSourcesAndOrderAreRejected() {
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(issue(1,"1"))));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(receipt(1,"1","1"), issue(2,"1"), returned(3,"2",2))));
|
||||
|
||||
@ -0,0 +1,94 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.production.service.ProductionService;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import com.ruoyi.warehouse.service.impl.*;
|
||||
import com.ruoyi.warehouse.service.impl.PurchasePriceCorrectionService.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Isolated service doubles only: no live database, no business records are changed. */
|
||||
class PurchaseQuoteClearTest {
|
||||
PurchasePriceCorrectionService service;JdbcTemplate db;PurchaseRequestMapper requests;
|
||||
InventoryCostJournal journal;PurchasePriceService prices;ProductionService production;
|
||||
IPurchaseOperationLogService logs;MockedStatic<SecurityUtils> security;
|
||||
@BeforeEach void setup() {
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(SecurityUtils::getUsername).thenReturn("isolated-test");
|
||||
service=new PurchasePriceCorrectionService();db=mock(JdbcTemplate.class);requests=mock(PurchaseRequestMapper.class);
|
||||
journal=mock(InventoryCostJournal.class);prices=mock(PurchasePriceService.class);production=mock(ProductionService.class);logs=mock(IPurchaseOperationLogService.class);
|
||||
ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"requests",requests);
|
||||
ReflectionTestUtils.setField(service,"projects",mock(IProjectInfoService.class));ReflectionTestUtils.setField(service,"journal",journal);
|
||||
ReflectionTestUtils.setField(service,"prices",prices);ReflectionTestUtils.setField(service,"production",production);ReflectionTestUtils.setField(service,"logs",logs);
|
||||
var purchase=new PurchaseRequest();purchase.setId(1L);purchase.setProjectId(10L);purchase.setProductId(20L);purchase.setQuantity(new BigDecimal("4"));
|
||||
purchase.setMaterialName("历史物品");purchase.setRequestNo("TEST-ONLY");purchase.setFinalUnitPrice(new BigDecimal("12.50"));
|
||||
purchase.setActualUnitPrice(new BigDecimal("9"));purchase.setHistorical(true);purchase.setPurchaseStatus(3);purchase.setPriceLocked(true);purchase.setLockedAmount(new BigDecimal("50"));
|
||||
when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(purchase);
|
||||
when(db.queryForList(startsWith("select id,in_no"),any(Object[].class))).thenReturn(List.of(Map.of("id",30L,"in_status",1,"receipt_root",0,"cost_event_id",40L)));
|
||||
when(db.queryForList(startsWith("select l.*"),any(Object[].class))).thenReturn(List.of(Map.of("id",50L,"product_id",20L,"purchase_request_id",1L)));
|
||||
when(db.queryForList(startsWith("select e.*"),any(Object[].class))).thenReturn(List.of(Map.of("id",40L,"project_id",10L,"item_id",20L,"event_type","RECEIPT","active",1,"quantity",new BigDecimal("4"),"cost_version",3)));
|
||||
when(db.update(anyString(),any(Object[].class))).thenReturn(1);
|
||||
var balance=new ProjectItemCost();balance.setVersion(3);when(journal.balance(10L,20L)).thenReturn(balance);
|
||||
}
|
||||
@AfterEach void close(){security.close();}
|
||||
Correction clear(boolean copy,String version){return new Correction(null,"隔离测试更正",version,false,true,copy);}
|
||||
@Test void clearPreviewShowsUnknownCostAndUnlockImpactWithoutWriting() {
|
||||
var view=service.preview(1L,clear(true,null));assertNull(view.get("newPrice"));assertNull(view.get("newAmount"));
|
||||
assertEquals(BigDecimal.ZERO,view.get("newLockedAmount"));assertEquals(1,view.get("costSourceCount"));
|
||||
assertTrue(view.get("notice").toString().contains("不是0元"));assertTrue(view.get("notice").toString().contains("复制"));
|
||||
verify(db,never()).update(anyString(),any(Object[].class));verify(journal,never()).reviseReceipt(anyLong(),any(),anyString(),anyInt());verifyNoInteractions(prices,production,logs);
|
||||
}
|
||||
@Test void combinationCopiesOriginalQuoteClearsQuoteAndRepricesDownstreamToUnknownNeverZero() {
|
||||
String version=service.preview(1L,clear(true,null)).get("version").toString();
|
||||
service.correctBatch(List.of(new Entry(1L,clear(true,version))));
|
||||
verify(journal).reviseReceipt(eq(40L),isNull(),anyString(),eq(3));
|
||||
verify(db).update(startsWith("update stock_lot"),isNull(),eq("isolated-test"),eq(50L));
|
||||
verify(db).update(startsWith("update in_record"),isNull(),eq(1L));
|
||||
verify(db).update(startsWith("update purchase_request set final_unit_price"),isNull(),isNull(),isNull(),eq("isolated-test"),eq(1L));
|
||||
verify(db).update(startsWith("update purchase_request set actual_unit_price"),eq(new BigDecimal("12.50")),eq(1L));
|
||||
verify(prices).releaseLock(any(),any());verify(prices,never()).refreshLockedAmount(any(),any(),anyString());verify(production).recalculateSettled();
|
||||
verify(logs).record(eq(1L),eq("TEST-ONLY"),eq("PRICE_CORRECTION"),anyString(),contains("原报价已复制"));
|
||||
}
|
||||
@Test void clearOnlyDoesNotModifyActualPriceAndPreviewModeCannotBeChangedAtConfirmation() {
|
||||
String version=service.preview(1L,clear(false,null)).get("version").toString();
|
||||
assertThrows(ServiceException.class,()->service.correct(1L,clear(true,version)));
|
||||
verify(db,never()).update(anyString(),any(Object[].class));
|
||||
service.correct(1L,clear(false,version));verify(db,never()).update(startsWith("update purchase_request set actual_unit_price"),any(Object[].class));
|
||||
}
|
||||
@Test void entireBatchBaselineAndArchiveAcknowledgmentAreCheckedBeforeAnyWrites() {
|
||||
String version=service.preview(1L,clear(true,null)).get("version").toString();
|
||||
assertThrows(ServiceException.class,()->service.correctBatch(List.of(new Entry(1L,clear(true,version)),new Entry(2L,clear(true,"stale")))));
|
||||
verify(db,never()).update(anyString(),any(Object[].class));
|
||||
when(db.queryForList(startsWith("select id,in_no"),any(Object[].class))).thenReturn(List.of(Map.of("id",30L,"in_status",1,"receipt_root",0)));
|
||||
var preview=service.preview(1L,clear(true,null));assertEquals(1,preview.get("archiveOnlyCount"));
|
||||
assertThrows(ServiceException.class,()->service.correct(1L,clear(true,preview.get("version").toString())));
|
||||
verify(db,never()).update(anyString(),any(Object[].class));
|
||||
}
|
||||
@Test void conflictingClearAndNewPriceCannotReachBusinessData() {
|
||||
assertThrows(ServiceException.class,()->service.preview(1L,new Correction(BigDecimal.ZERO,"原因",null,false,true,false)));
|
||||
assertThrows(ServiceException.class,()->service.preview(1L,new Correction(BigDecimal.ONE,"原因",null,false,false,true)));
|
||||
verifyNoInteractions(requests,db,journal);
|
||||
}
|
||||
@Test void legacyFifoAdapterCannotTurnNewlyUnknownCostsIntoAFreeIssue() throws Exception {
|
||||
var legacy=new StockLotServiceImpl();var lots=mock(com.ruoyi.warehouse.mapper.StockLotMapper.class);
|
||||
var projectAccess=mock(IProjectInfoService.class);when(projectAccess.selectLegacyProjectId()).thenReturn(10L);
|
||||
ReflectionTestUtils.setField(legacy,"stockLotMapper",lots);ReflectionTestUtils.setField(legacy,"projectInfoService",projectAccess);
|
||||
var lot=new StockLot();lot.setId(50L);lot.setSourceProjectId(10L);lot.setAvailableQuantity(BigDecimal.TEN);lot.setUnitCost(null);
|
||||
when(lots.selectAvailableLotsForUpdate(1L,20L)).thenReturn(List.of(lot));
|
||||
var out=new OutRecord();out.setId(60L);out.setUsageProjectId(10L);out.setAreaId(1L);out.setProductId(20L);out.setOutNum(BigDecimal.ONE);
|
||||
assertTrue(assertThrows(ServiceException.class,()->legacy.allocateOutboundLots(out)).getMessage().contains("不会按0元"));
|
||||
verify(lots,never()).deductStockLot(anyLong(),any());verify(lots,never()).insertOutRecordLot(any(),any(),any(),any(),any(),any(),any());
|
||||
assertNotNull(StockLotServiceImpl.class.getMethod("allocateOutboundLots",OutRecord.class).getAnnotation(org.springframework.transaction.annotation.Transactional.class));
|
||||
}
|
||||
}
|
||||
@ -7,7 +7,7 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AssistantAuthorizationNoticeTest {
|
||||
@Test void identityOnlyActionsExplainAdministratorHandlingRatherThanRequestingAccess() {
|
||||
for (String key : List.of("role.dataScope", "feedback.all", "feedback.handle")) {
|
||||
for (String key : List.of("notification.send", "role.dataScope", "feedback.all", "feedback.handle")) {
|
||||
assertTrue(AssistantMessages.administratorOnly(key));
|
||||
String notice = AssistantMessages.forAction(key);
|
||||
assertTrue(notice.contains("管理员"));
|
||||
|
||||
@ -199,8 +199,9 @@ class AssistantExtensionsTest {
|
||||
beans.getBeanFactory().registerSingleton("ss",new PermissionService());
|
||||
var guard=new AssistantPermissionGuard(users,grants,beans,mock(SysDeptMapper.class));
|
||||
var secured=new BusinessActionRegistry(beans,new ObjectMapper(),database,mock(Validator.class),guard);
|
||||
for(var action:secured.catalog())if(action.get("key").toString().startsWith("feedbackNotification."))assertEquals(false,action.get("allowed"));
|
||||
for(var action:secured.catalog())if(action.get("key").toString().startsWith("feedbackNotification.")||"notification.send".equals(action.get("key")))assertEquals(false,action.get("allowed"));
|
||||
assertThrows(ServiceException.class,()->secured.prepare("feedbackNotification.send",List.of(Map.of("id",1))));
|
||||
assertThrows(ServiceException.class,()->secured.prepare("notification.send",List.of(Map.of("userIds",List.of(1),"channel","EMAIL","title","test","content","test"))));
|
||||
verifyNoInteractions(database);
|
||||
}
|
||||
}
|
||||
|
||||
@ -17,6 +17,11 @@ import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AssistantModelRoutingTest {
|
||||
@Test void conversationalPatchCannotAcknowledgeHistoricalCostRiskOnBehalfOfTheUser() {
|
||||
var proposal=Map.<String,Object>of("kind","patch","action","purchase.referencePrice","changes",Map.of("acknowledgeArchiveOnly",true));
|
||||
var reply=AssistantModelClient.guardDraftPatch(proposal,Map.of("action","purchase.referencePrice","rows",List.of(Map.of("purchaseBatchId",316))),"确定");
|
||||
assertEquals("clarify",reply.get("kind"));assertFalse(reply.containsKey("changes"));assertTrue(reply.get("message").toString().contains("本人勾选"));
|
||||
}
|
||||
@Test void opaqueProductFileCanRouteToConfirmedProductStorageWithoutExcelParsing()throws Exception {
|
||||
HttpClient http=mock(HttpClient.class);
|
||||
var route=response(Map.of("kind","draft","action","product.attachmentUpload","message","保存产品附件"));
|
||||
@ -65,15 +70,20 @@ class AssistantModelRoutingTest {
|
||||
var pages=List.<Map<String,Object>>of(Map.of("id","owned-pdf","name","报价第1页","type","image","pdfPage",1,"pdfText","Pump P100 123.45","dataUrl","data:image/png;base64,AAAA"),
|
||||
Map.of("id","owned-pdf","name","营业执照第2页","type","image","pdfPage",2,"pdfText","Business license","dataUrl","data:image/png;base64,AAAA"));
|
||||
when(attachments.quotationInputs(anyList())).thenReturn(pages);
|
||||
var definition=List.<Map<String,Object>>of(Map.of("key","purchase.correctPrice","allowed",true,"fields",List.of(Map.of("key","id","ref","purchase"),Map.of("key","finalUnitPrice"),Map.of("key","reason"),Map.of("key","attachmentId"),Map.of("key","acknowledgeArchiveOnly"))));
|
||||
var routing=response(Map.of("kind","draft","action","purchase.correctPrice","message","准备更新报价"));
|
||||
var definition=List.<Map<String,Object>>of(Map.of("key","purchase.correctPrice","allowed",true,"fields",List.of(Map.of("key","id","ref","purchase"),Map.of("key","finalUnitPrice"),Map.of("key","reason"),Map.of("key","attachmentId"),Map.of("key","acknowledgeArchiveOnly"))),Map.of("key","purchase.importQuote","allowed",true));
|
||||
// Reproduce the bad model route from the user's screenshot, then verify structural recovery.
|
||||
var routing=response(Map.of("kind","draft","action","purchase.importQuote","message","准备回填报价"));
|
||||
var transcription=response(Map.of("kind","draft","action","purchase.correctPrice","message","完整读取两项报价","rows",List.of(
|
||||
Map.of("_sourceRow",1,"sourceName","水泵","sourceSpec","P100","sourceQuantity",1,"finalUnitPrice",123.45,"attachmentId","owned-pdf"),
|
||||
Map.of("_sourceRow",2,"sourceName","软管","sourceQuantity",2,"finalUnitPrice",5,"attachmentId","owned-pdf"))));
|
||||
var extracted=response(Map.of("kind","draft","action","purchase.correctPrice","message","请核对两项报价","rows",List.of(
|
||||
Map.of("_sourceRow",1,"id",Map.of("name","水泵","spec","P100"),"finalUnitPrice",999,"reason","供应商报价","attachmentId","owned-pdf","acknowledgeArchiveOnly",true),
|
||||
Map.of("_sourceRow",2,"id","软管","finalUnitPrice",999,"reason","供应商报价","attachmentId","owned-pdf"))));
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenReturn(routing,transcription,extracted);
|
||||
var callCount=new java.util.concurrent.atomic.AtomicInteger();
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenAnswer(call->{
|
||||
int n=callCount.getAndIncrement();if(n==0)return routing;if(n==1)return transcription;
|
||||
var context=JSON.parseObject(contextText(requestBody(call.getArgument(0))));
|
||||
var key=context.getJSONArray("literalQuotationRows").getJSONObject(0).get("sourceKey");
|
||||
// Reproduce a model that omits the second source row entirely.
|
||||
return response(Map.of("kind","draft","action","purchase.correctPrice","message","匹配到一项","rows",List.of(Map.of("sourceKey",key,"id",7))));
|
||||
});
|
||||
var client=configured(http);ReflectionTestUtils.setField(client,"attachmentService",attachments);
|
||||
var result=client.propose(List.of(Map.of("role","user","content","按这个PDF更新水冷采购报价")),definition,Map.of(),Map.of(),original);
|
||||
assertEquals("purchase.correctPrice",result.get("action"));var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(2,rows.size());
|
||||
@ -83,6 +93,29 @@ class AssistantModelRoutingTest {
|
||||
String extraction=requestBody(requests.getAllValues().get(1)).toJSONString();assertTrue(extraction.contains("123.45"));assertTrue(extraction.contains("Business license"));assertTrue(extraction.contains("data:image"));
|
||||
verify(attachments).quotationInputs(anyList());
|
||||
}
|
||||
@Test void pdfRouteRecoveryChecksCorrectionPermissionAndDoesNotChangeExcelOrDocumentStorage() {
|
||||
var importRoute=Map.<String,Object>of("kind","draft","action","purchase.importQuote");
|
||||
var pdf=List.<Map<String,Object>>of(Map.of("type","document","name","报价.PDF"));
|
||||
var allowed=List.<Map<String,Object>>of(Map.of("key","purchase.correctPrice","allowed",true));
|
||||
assertEquals("purchase.correctPrice",AssistantModelClient.quotationRoute(importRoute,pdf,allowed).get("action"));
|
||||
var denied=AssistantModelClient.quotationRoute(importRoute,pdf,List.of(Map.of("key","purchase.correctPrice","allowed",false,"deniedReason","请采购管理员协助")));
|
||||
assertEquals("answer",denied.get("kind"));assertFalse(denied.containsKey("action"));
|
||||
assertEquals(importRoute,AssistantModelClient.quotationRoute(importRoute,List.of(Map.of("name","询价单.xlsx","type","excel")),allowed));
|
||||
var save=Map.<String,Object>of("kind","draft","action","purchase.documentUploadbatch");assertEquals(save,AssistantModelClient.quotationRoute(save,pdf,allowed));
|
||||
}
|
||||
@Test void matchingModelFailureStillProducesEveryReadSourceRowForManualReview() throws Exception {
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);
|
||||
when(attachments.quotationInputs(anyList())).thenReturn(List.of(Map.of("type","image","dataUrl","data:image/png;base64,AAAA","pdfPage",1)));
|
||||
var route=response(Map.of("kind","draft","action","purchase.correctPrice","message","报价更正"));
|
||||
var literal=response(Map.of("kind","draft","action","purchase.correctPrice","message","读取一项","rows",List.of(Map.of("_sourceRow",1,"sourceName","水泵","sourceSpec","P100","finalUnitPrice",12,"attachmentId","owned-pdf"))));
|
||||
HttpResponse<String> unavailable=mock(HttpResponse.class);when(unavailable.statusCode()).thenReturn(503);when(unavailable.body()).thenReturn("service unavailable");
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenReturn(route,literal,unavailable);
|
||||
var client=configured(http);ReflectionTestUtils.setField(client,"attachmentService",attachments);
|
||||
var definition=List.<Map<String,Object>>of(Map.of("key","purchase.correctPrice","allowed",true,"fields",List.of(Map.of("key","id"),Map.of("key","finalUnitPrice"),Map.of("key","reason"),Map.of("key","attachmentId"))));
|
||||
var result=client.propose(List.of(Map.of("role","user","content","根据PDF更新采购报价")),definition,Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","name","报价.pdf","type","document")));
|
||||
assertEquals("draft",result.get("kind"));var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(1,rows.size());
|
||||
assertEquals(12,rows.get(0).get("finalUnitPrice"));assertEquals(Map.of("name","水泵","spec","P100"),rows.get(0).get("id"));assertEquals(false,rows.get(0).get("skipCorrection"));
|
||||
}
|
||||
@Test void bareWarehouseRequestsAskForConcreteBusinessDetailsWithoutModelGuessingOrWriting() {
|
||||
HttpClient http=mock(HttpClient.class);
|
||||
var entries=Map.of("我要入库","receipt.receive","帮我登记到货","arrival.register","我要领用","material.issue","我想移库","stock.move","我要盘点","stockCheck.create");
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.projectdev.ProfileConfiguration;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Only model inference against synthetic capability metadata. No session, user lookup, outbox or SMTP. */
|
||||
@EnabledIfSystemProperty(named="assistantNotificationModelLive",matches="true")
|
||||
class AssistantNotificationModelLiveTest {
|
||||
List<Map<String,Object>> definition(){return List.of(Map.of("key","notification.send","label","发送站内消息或邮件","allowed",true,"query",false,"fields",List.of(
|
||||
Map.of("key","userIds","label","接收人","type","references","ref","sysUser","required",true),
|
||||
Map.of("key","channel","label","渠道","type","select","required",true,"options",List.of(Map.of("value","INBOX","label","站内消息"),Map.of("value","EMAIL","label","邮件"),Map.of("value","BOTH","label","两种都发"))),
|
||||
Map.of("key","title","label","消息标题","type","text","required",true),Map.of("key","content","label","消息正文","type","text","required",true))));}
|
||||
AssistantModelClient client(){var settings=ProfileConfiguration.load("druid");var client=new AssistantModelClient();
|
||||
ReflectionTestUtils.setField(client,"baseUrl",settings.getProperty("agent.model.base-url"));ReflectionTestUtils.setField(client,"apiKey",settings.getProperty("agent.model.api-key",""));
|
||||
ReflectionTestUtils.setField(client,"model",settings.getProperty("agent.model.model"));
|
||||
ReflectionTestUtils.setField(client,"timeoutMs",180000L);ReflectionTestUtils.setField(client,"maxOutputTokens",4096);ReflectionTestUtils.setField(client,"businessTimeZone","Asia/Shanghai");return client;}
|
||||
@Test void messageDiscussingEmailIsOneInboxDraftNotAnActualSend(){
|
||||
var result=client().propose(List.of(Map.of("role","user","content","给张浩发个消息通知,告诉他怎么使用消息通知和邮件")),definition(),Map.of(),Map.of(),List.of());
|
||||
assertEquals("draft",result.get("kind"));assertEquals("notification.send",result.get("action"));
|
||||
var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(1,rows.size());assertEquals("INBOX",rows.get(0).get("channel"));
|
||||
assertTrue(rows.get(0).get("userIds").toString().contains("张浩"));assertNotNull(rows.get(0).get("title"));assertNotNull(rows.get(0).get("content"));
|
||||
assertFalse(result.containsKey("eventId"));
|
||||
}
|
||||
@Test void explicitEmailUsesEmailButAnOldUnsupportedReplyCannotOverrideTheNewCapability(){
|
||||
var result=client().propose(List.of(Map.of("role","user","content","给模拟用户发邮件,提醒他明天检查采购清单"),
|
||||
Map.of("role","assistant","content","旧版本暂不支持发送邮件"),Map.of("role","user","content","现在给模拟用户发一封邮件,提醒他明天检查采购清单,先生成确认单")),definition(),Map.of(),Map.of(),List.of());
|
||||
assertEquals("draft",result.get("kind"));assertEquals("notification.send",result.get("action"));
|
||||
assertEquals("EMAIL",AssistantConversationService.maps(result.get("rows")).get(0).get("channel"));assertFalse(result.containsKey("eventId"));
|
||||
}
|
||||
@Test void actualFullCapabilityIndexStillRoutesTheScreenshotToOneInboxDraftWithoutAnyBusinessReadOrWrite(){
|
||||
var db=mock(org.springframework.jdbc.core.JdbcTemplate.class);var guard=mock(AssistantPermissionGuard.class);when(guard.allows(any())).thenReturn(true);
|
||||
List<Map<String,Object>> catalog;
|
||||
try(var security=mockStatic(com.ruoyi.common.utils.SecurityUtils.class)) {
|
||||
var login=new com.ruoyi.common.core.domain.model.LoginUser();login.setPermissions(Set.of("*:*:*"));
|
||||
security.when(com.ruoyi.common.utils.SecurityUtils::getLoginUser).thenReturn(login);security.when(com.ruoyi.common.utils.SecurityUtils::isAdmin).thenReturn(true);
|
||||
catalog=new BusinessActionRegistry(mock(org.springframework.context.ApplicationContext.class),new com.fasterxml.jackson.databind.ObjectMapper(),db,mock(jakarta.validation.Validator.class),guard).catalog();
|
||||
}
|
||||
var result=client().propose(List.of(Map.of("role","user","content","给张浩发个消息通知,告诉他怎么使用消息通知和邮件")),catalog,Map.of(),Map.of(),List.of());
|
||||
assertEquals("draft",result.get("kind"));assertEquals("notification.send",result.get("action"));
|
||||
assertEquals("INBOX",AssistantConversationService.maps(result.get("rows")).get(0).get("channel"));verifyNoInteractions(db);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.notification.NotificationGateway;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.system.notification.NotificationMailSender;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** No real database, notification enqueue or SMTP. */
|
||||
class AssistantNotificationServiceTest {
|
||||
AssistantNotificationService service;JdbcTemplate db;NotificationGateway gateway;NotificationMailSender mail;MockedStatic<SecurityUtils> security;
|
||||
Map<String,Object> row(String channel){return new LinkedHashMap<>(Map.of("userIds",List.of(7L),"channel",channel,"title","通知使用说明","content","请从页面顶部的消息入口查看站内消息。邮件会发送到账号登记的邮箱。","_executionKey","isolated-test-event"));}
|
||||
Map<String,Object> user(String email){return Map.of("user_id",7L,"user_name","isolated-user","nick_name","模拟收件人","email",email,"status","0","del_flag","0");}
|
||||
@BeforeEach void setup(){
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
service=new AssistantNotificationService();db=mock(JdbcTemplate.class);gateway=mock(NotificationGateway.class);mail=mock(NotificationMailSender.class);
|
||||
ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"notifications",gateway);ReflectionTestUtils.setField(service,"mail",mail);ReflectionTestUtils.setField(service,"enabled",true);
|
||||
when(db.queryForList(anyString(),eq(7L))).thenReturn(List.of(user("person@example.invalid")));when(mail.ready()).thenReturn(true);
|
||||
when(gateway.publish(any())).thenReturn(new NotificationGateway.Receipt("isolated-event",false,1,0,0));
|
||||
}
|
||||
@AfterEach void close(){security.close();}
|
||||
@Test void previewNeverEnqueuesAndInboxNeedsNoEmailEvenWhenTheMessageDiscussesMail(){
|
||||
when(db.queryForList(anyString(),eq(7L))).thenReturn(List.of(user("")));when(mail.ready()).thenReturn(false);
|
||||
var result=service.preview(row("INBOX"));assertEquals("INBOX",result.get("channel"));assertFalse(result.get("recipients").toString().contains("email"));verifyNoInteractions(gateway,mail);
|
||||
}
|
||||
@Test void administratorPolicyIsCheckedBeforeLookingUpRecipientsOrSenderConfiguration(){
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(false);
|
||||
assertThrows(ServiceException.class,()->service.preview(row("BOTH")));assertThrows(ServiceException.class,()->service.send(row("INBOX")));verifyNoInteractions(db,gateway,mail);
|
||||
}
|
||||
@Test void emailRequiresReadySenderAndValidExistingAddressAndNeverSilentlyFallsBack(){
|
||||
when(mail.ready()).thenReturn(false);assertThrows(ServiceException.class,()->service.preview(row("EMAIL")));verifyNoInteractions(db,gateway);
|
||||
when(mail.ready()).thenReturn(true);when(db.queryForList(anyString(),eq(7L))).thenReturn(List.of(user("")));
|
||||
var failure=assertThrows(ServiceException.class,()->service.send(row("BOTH")));assertTrue(failure.getMessage().contains("邮箱"));verifyNoInteractions(gateway);
|
||||
}
|
||||
@Test void confirmedNotificationUsesSystemPolicyStableServerExecutionKeyAndOnlySelectedChannels(){
|
||||
var values=row("INBOX");service.send(values);service.send(values);var capture=ArgumentCaptor.forClass(NotificationGateway.Command.class);verify(gateway,times(2)).publish(capture.capture());
|
||||
var command=capture.getValue();assertEquals("SYSTEM_MESSAGE",command.businessType());assertEquals(Set.of(7L),command.userIds());assertTrue(command.roleIds().isEmpty());assertEquals(Set.of(NotificationGateway.Channel.INBOX),command.channels());assertEquals("",command.sourcePath());
|
||||
assertEquals(capture.getAllValues().get(0).eventKey(),command.eventKey());assertTrue(command.eventKey().startsWith("AI:1:"));
|
||||
}
|
||||
@Test void duplicateReceiptIsNotReportedAsANewSendAndQueuedMailIsNotClaimedDelivered(){
|
||||
when(gateway.publish(any())).thenReturn(new NotificationGateway.Receipt("e",true,1,1,0));
|
||||
assertTrue(service.send(row("BOTH")).get("message").toString().contains("未重复发送"));
|
||||
when(gateway.publish(any())).thenReturn(new NotificationGateway.Receipt("e2",false,0,1,0));
|
||||
assertTrue(service.send(row("EMAIL")).get("message").toString().contains("不代表已送达"));
|
||||
}
|
||||
@Test void missingConfirmationKeyInactiveUsersMissingContentAndHeaderInjectionStopBeforePublish(){
|
||||
var missingKey=row("INBOX");missingKey.remove("_executionKey");assertThrows(ServiceException.class,()->service.send(missingKey));
|
||||
var injected=row("INBOX");injected.put("title","title\r\nBcc: injected@example.invalid");assertThrows(ServiceException.class,()->service.send(injected));
|
||||
var blank=row("INBOX");blank.put("content","");assertThrows(ServiceException.class,()->service.send(blank));
|
||||
when(db.queryForList(anyString(),eq(7L))).thenReturn(List.of());assertThrows(ServiceException.class,()->service.send(row("INBOX")));verifyNoInteractions(gateway);
|
||||
}
|
||||
@Test void genericRuntimeContractKeepsThisAManualWriteAndTheAdminRestrictionCannotBeOpenedByOrdinaryPermissions()throws Exception{
|
||||
assertTrue(AssistantExtendedActions.preparedAction("notification.send"));assertTrue(AssistantMessages.administratorOnly("notification.send"));
|
||||
assertEquals(AssistantMessages.forAction("notification.send"),AssistantMessages.safeAuthorizationMessage(AssistantMessages.forAction("notification.send")));
|
||||
assertEquals("T(com.ruoyi.common.utils.SecurityUtils).isAdmin()",AssistantExtendedActions.class.getMethod("messageSend",Map.class).getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class).value());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.util.*;
|
||||
import java.net.http.HttpClient;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AssistantPriceInstructionsTest {
|
||||
final String original="CG2026100001将这批采购明细的报价单价改到实际单价,然后清空报价单价";
|
||||
final List<Map<String,Object>> allowed=List.of(Map.of("key","purchase.referencePrice","allowed",true));
|
||||
List<Map<String,Object>> messages(String... text){return Arrays.stream(text).map(value->Map.<String,Object>of("role","user","content",value)).toList();}
|
||||
void assertCombination(Map<String,Object> proposal){assertNotNull(proposal);assertEquals("draft",proposal.get("kind"));assertEquals("purchase.referencePrice",proposal.get("action"));var rows=AssistantConversationService.maps(proposal.get("rows"));assertEquals(1,rows.size());assertEquals("CG2026100001",rows.get(0).get("purchaseBatchId"));assertEquals("COPY_QUOTE_CLEAR_QUOTE",rows.get(0).get("mode"));assertFalse(proposal.containsKey("execute"));}
|
||||
@Test void explicitOrderProducesOneDraftAndEveryScreenshotFollowupKeepsBothSteps() {
|
||||
assertCombination(AssistantPriceInstructions.propose(messages(original),allowed,Map.of()));
|
||||
for(String followup:List.of("两个一起","两项都做","确定","确认"))assertCombination(AssistantPriceInstructions.propose(messages(original,"两个一起",followup),allowed,Map.of()));
|
||||
assertCombination(AssistantPriceInstructions.propose(messages("CG2026100001 两项都做,先将当前报价复制到实际单价,再清空报价,生成一张确认单"),allowed,Map.of()));
|
||||
assertCombination(AssistantPriceInstructions.propose(messages("CG2026100001 实际单价以报价为准,然后清空报价"),allowed,Map.of()));
|
||||
}
|
||||
@Test void doesNotInventScopeDropOtherRequestsIgnoreNegationOrReviveCancelledTasks() {
|
||||
for(String text:List.of("CG2026100001 报价复制到实际单价,不要清空报价","CG2026100001 查询报价,然后清空报价","CG2026100001 报价复制到实际单价再清空报价?","CG2026100001 报价复制到实际单价,再清空报价并入库",original+",还有CG2026100002","把报价复制到实际单价然后清空报价"))
|
||||
assertNull(AssistantPriceInstructions.propose(messages(text),allowed,Map.of()),text);
|
||||
assertNull(AssistantPriceInstructions.propose(messages(original,"查库存","确定"),allowed,Map.of()));
|
||||
assertNull(AssistantPriceInstructions.propose(messages(original,"确定"),allowed,Map.of("status","CANCELLED")));
|
||||
assertNull(AssistantPriceInstructions.propose(messages(original,"确定"),allowed,Map.of("action","user.create")));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("两个一起"),allowed,Map.of()));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("取消刚才的操作:"+original),allowed,Map.of()));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("暂不执行"+original),allowed,Map.of()));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("CG2026100001把报价单价改为实际单价,然后清空报价"),allowed,Map.of()));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("CG2026100001先清空报价,然后复制报价到实际单价"),allowed,Map.of()));
|
||||
}
|
||||
@Test void permissionDenialCannotProduceABusinessDraftAndAbsentCapabilityIsNotInvented() {
|
||||
var denied=AssistantPriceInstructions.propose(messages(original),List.of(Map.of("key","purchase.referencePrice","allowed",false,"deniedReason","请采购负责人协助")),Map.of());
|
||||
assertEquals("answer",denied.get("kind"));assertEquals("请采购负责人协助",denied.get("message"));assertFalse(denied.containsKey("rows"));
|
||||
assertNull(AssistantPriceInstructions.propose(messages(original),List.of(),Map.of()));
|
||||
}
|
||||
@Test void explicitClearOnlyDoesNotReviveOldCopyOperationAndKeepsCurrentDraftScope() {
|
||||
var task=Map.<String,Object>of("action","purchase.referencePrice","rows",List.of(Map.of("purchaseBatchId",316L,"mode","COPY_QUOTE_CLEAR_QUOTE")));
|
||||
var proposal=AssistantPriceInstructions.propose(messages(original,"走更正价格方式清空报价"),allowed,task);
|
||||
var row=AssistantConversationService.maps(proposal.get("rows")).get(0);assertEquals("CLEAR_QUOTE",row.get("mode"));assertEquals(316L,row.get("purchaseBatchId"));assertEquals(false,row.get("acknowledgeArchiveOnly"));
|
||||
proposal=AssistantPriceInstructions.propose(messages("CG2026100001只清空报价"),allowed,Map.of());
|
||||
assertEquals("CLEAR_QUOTE",AssistantConversationService.maps(proposal.get("rows")).get(0).get("mode"));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("不要清空报价"),allowed,task));
|
||||
assertNull(AssistantPriceInstructions.propose(messages("清空报价"),allowed,Map.of("action","user.create")));
|
||||
}
|
||||
@Test void modelEntryUsesGroundedCombinationInsteadOfReenteringClarificationLoop() {
|
||||
var http=mock(HttpClient.class);var client=new AssistantModelClient();
|
||||
ReflectionTestUtils.setField(client,"baseUrl","http://mock-model");ReflectionTestUtils.setField(client,"model","test");ReflectionTestUtils.setField(client,"client",http);
|
||||
assertCombination(client.propose(messages(original,"两个一起","两项都做,先将当前报价复制到实际单价,再清空报价,生成一张确认单"),allowed,Map.of(),Map.of(),List.of()));
|
||||
verifyNoInteractions(http);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AssistantQuotationFollowupTest {
|
||||
Map<String,Object> source(String id,String... names) {
|
||||
return Map.of("id",id,"role","user","content","修改采购价格", "attachments",
|
||||
Arrays.stream(names).map(name->Map.of("id","owned-"+name,"name",name,"type","document")).toList());
|
||||
}
|
||||
final String request="根据pdf来回填CG2026100001批次的采购明细的报价信息";
|
||||
@Test void explicitPdfFollowupReusesOnlyCurrentSessionsOwnedSourceAndKeepsNewBatchInstruction() {
|
||||
var state=Map.<String,Object>of("messages",List.of(source("source-1","重庆报价和营业执照.pdf")));
|
||||
var input=AssistantConversationService.messageInput(state,Map.of("text",request));
|
||||
assertEquals(List.of("owned-重庆报价和营业执照.pdf"),input.get("attachmentIds"));assertEquals("source-1",input.get("contextMessageId"));
|
||||
var conversation=AssistantConversationService.maps(input.get("attachmentConversation"));assertEquals(request,conversation.get(conversation.size()-1).get("content"));
|
||||
}
|
||||
@Test void genericFollowupsDoNotReattachOldFilesOrWalkPastNewerAttachments() {
|
||||
var state=Map.<String,Object>of("messages",List.of(source("old","报价.pdf")));
|
||||
for(String text:List.of("查库存","取消","不要根据pdf来更新报价","如何根据pdf更新报价"))
|
||||
assertEquals(List.of(),AssistantConversationService.messageInput(state,Map.of("text",text)).get("attachmentIds"));
|
||||
state=Map.of("messages",List.of(source("old","报价.pdf"),source("new","其他.docx")));
|
||||
assertEquals(List.of(),AssistantConversationService.messageInput(state,Map.of("text",request)).get("attachmentIds"));
|
||||
assertEquals(List.of("new-upload"),AssistantConversationService.messageInput(state,Map.of("text",request,"attachmentIds",List.of("new-upload"))).get("attachmentIds"));
|
||||
}
|
||||
@Test void multiplePdfFilesRequireSelectionRatherThanGuessing() {
|
||||
var state=Map.<String,Object>of("messages",List.of(source("multiple","甲.pdf","乙.pdf")));
|
||||
assertTrue(assertThrows(ServiceException.class,()->AssistantConversationService.messageInput(state,Map.of("text",request))).getMessage().contains("多个PDF"));
|
||||
}
|
||||
@Test void oldUploadOutsideRecentHistoryCanUseOnlyOneStillOwnedPdfNotAnInventedPath() {
|
||||
var attachments=mock(AssistantAttachmentService.class);
|
||||
var service=new AssistantConversationService(mock(com.ruoyi.common.core.redis.RedisCache.class),mock(com.ruoyi.warehouse.mapper.AiCommandMapper.class),mock(BusinessActionRegistry.class),mock(AssistantModelClient.class),attachments,mock(org.springframework.transaction.PlatformTransactionManager.class));
|
||||
var input=Map.<String,Object>of("text",request,"attachmentIds",List.of());
|
||||
when(attachments.available(null,null)).thenReturn(List.of(Map.of("id","owned-pdf","name","报价.pdf","type","document")));
|
||||
assertEquals(List.of("owned-pdf"),service.quotationFollowupInput(input).get("attachmentIds"));
|
||||
when(attachments.available(null,null)).thenReturn(List.of(Map.of("id","owned-pdf","name","甲.pdf"),Map.of("id","other-owned-pdf","name","乙.pdf")));
|
||||
assertThrows(ServiceException.class,()->service.quotationFollowupInput(input));
|
||||
when(attachments.available(null,null)).thenReturn(List.of());assertThrows(ServiceException.class,()->service.quotationFollowupInput(input));
|
||||
assertEquals(Map.of("text","查库存"),service.quotationFollowupInput(Map.of("text","查库存")));
|
||||
verify(attachments,never()).businessFile(anyString());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.projectdev.ProfileConfiguration;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Opt-in real model/PDF regression. Frozen local fixtures only; no live database/session/execution. */
|
||||
@EnabledIfSystemProperty(named="assistantQuotationModelLive",matches="true")
|
||||
class AssistantQuotationModelLiveTest {
|
||||
@Test void originalMultiItemPdfWithFullCatalogProducesPriceCorrectionInsteadOfExcelImport() throws Exception {
|
||||
Path root=Path.of(System.getProperty("quotationFixtureDirectory"));
|
||||
Path pdf=root.resolve("重庆鸥睿珂报价单和营业执照.pdf");byte[] original=Files.readAllBytes(pdf);
|
||||
var scope=JSON.parseObject(Files.readString(root.resolve("batch-scope.json"))).getJSONObject("cmvr-project-prod");
|
||||
var targets=new ArrayList<Map<String,Object>>();
|
||||
for(var value:scope.getJSONArray("purchase_request")) {
|
||||
var source=JSON.parseObject(JSON.toJSONString(value));var target=new LinkedHashMap<String,Object>();
|
||||
for(var key:Map.of("id","id","name","material_name","spec","material_params","brand","material_brand","quantity","quantity","oldPrice","final_unit_price","projectId","project_id","purchaseBatchId","purchase_batch_id").entrySet())target.put(key.getKey(),source.get(key.getValue()));
|
||||
target.put("batchNo","CG2026100001");targets.add(target);
|
||||
}
|
||||
assertEquals(34,targets.size());
|
||||
var quotationContext=mock(AssistantQuotationContext.class);when(quotationContext.targets(anyList())).thenReturn(targets);
|
||||
var attachments=mock(AssistantAttachmentService.class);when(attachments.quotationInputs(anyList())).thenAnswer(call->AssistantQuotationPdf.read(original,"owned-original-pdf",pdf.getFileName().toString()));
|
||||
var settings=ProfileConfiguration.load("druid");var client=new AssistantModelClient();
|
||||
ReflectionTestUtils.setField(client,"baseUrl",settings.getProperty("agent.model.base-url"));ReflectionTestUtils.setField(client,"apiKey",settings.getProperty("agent.model.api-key",""));
|
||||
ReflectionTestUtils.setField(client,"model",settings.getProperty("agent.model.model"));ReflectionTestUtils.setField(client,"maxOutputTokens",16384);
|
||||
ReflectionTestUtils.setField(client,"timeoutMs",180000L);ReflectionTestUtils.setField(client,"businessTimeZone","Asia/Shanghai");
|
||||
ReflectionTestUtils.setField(client,"attachmentService",attachments);ReflectionTestUtils.setField(client,"quotationContext",quotationContext);
|
||||
var db=mock(org.springframework.jdbc.core.JdbcTemplate.class);var guard=mock(AssistantPermissionGuard.class);when(guard.allows(any())).thenReturn(true);
|
||||
List<Map<String,Object>> catalog;
|
||||
try(var security=mockStatic(com.ruoyi.common.utils.SecurityUtils.class)) {
|
||||
var login=new com.ruoyi.common.core.domain.model.LoginUser();login.setPermissions(Set.of("*:*:*"));
|
||||
security.when(com.ruoyi.common.utils.SecurityUtils::getLoginUser).thenReturn(login);security.when(com.ruoyi.common.utils.SecurityUtils::isAdmin).thenReturn(true);
|
||||
catalog=new BusinessActionRegistry(mock(org.springframework.context.ApplicationContext.class),new com.fasterxml.jackson.databind.ObjectMapper(),db,mock(jakarta.validation.Validator.class),guard).catalog();
|
||||
}
|
||||
var proposal=client.propose(List.of(Map.of("role","user","content","根据pdf来回填CG2026100001批次的采购明细的报价信息")),catalog,Map.of(),Map.of(),
|
||||
List.of(Map.of("id","owned-original-pdf","name",pdf.getFileName().toString(),"type","document")));
|
||||
assertEquals("draft",proposal.get("kind"));assertEquals("purchase.correctPrice",proposal.get("action"));
|
||||
var rows=AssistantConversationService.maps(proposal.get("rows"));assertEquals(35,rows.size());
|
||||
var expected=JSON.parseObject(Files.readString(root.resolve("real-pdf-verification.json"))).getJSONArray("items");
|
||||
for(var row:rows) {
|
||||
int line=((Number)row.get("_sourceRow")).intValue();
|
||||
assertEquals(0,new BigDecimal(expected.getJSONObject(line-1).get("price").toString()).compareTo(new BigDecimal(row.get("finalUnitPrice").toString())),"PDF第"+line+"项价格");
|
||||
assertEquals(false,row.get("acknowledgeArchiveOnly"));assertEquals(316L,((Number)row.get("purchaseBatchId")).longValue());
|
||||
}
|
||||
var ids=targets.stream().map(row->row.get("id").toString()).collect(java.util.stream.Collectors.toSet());
|
||||
long matched=rows.stream().filter(row->ids.contains(Objects.toString(row.get("id"),""))).count();assertEquals(34,matched);
|
||||
assertArrayEquals(original,Files.readAllBytes(pdf));verifyNoInteractions(db);
|
||||
Path output=root.getParent().resolve("quote-clear-pdf-live-result.json");
|
||||
Files.writeString(output,JSON.toJSONString(Map.of("action",proposal.get("action"),"pdfRows",rows.size(),"matched",matched,"allPricesMatchReviewedOriginal",true,"executed",false,"rows",rows)));
|
||||
}
|
||||
}
|
||||
@ -6,10 +6,34 @@ import com.ruoyi.common.exception.ServiceException;
|
||||
class AssistantQuotationRowsTest {
|
||||
private Map<String,Object> proposal(List<Map<String,Object>> rows){return Map.of("kind","draft","action","purchase.correctPrice","rows",rows);}
|
||||
private List<Map<String,Object>> source(){return List.of(Map.of("_sourceRow",1,"sourceName","水泵","sourceSpec","H06A","finalUnitPrice",221.2,"attachmentId","mine"),Map.of("_sourceRow",2,"sourceName","管道","sourceSpec","N8","finalUnitPrice",6.5,"attachmentId","mine"));}
|
||||
@Test void matchingCannotLoseRowsOrReplaceThePriceWithAPlausibleButDifferentValue(){
|
||||
assertThrows(ServiceException.class,()->AssistantQuotationRows.ground(proposal(List.of(Map.of("_sourceRow",1,"id",7))),source()));
|
||||
var value=AssistantQuotationRows.ground(proposal(List.of(Map.of("_sourceRow",1,"id",7,"finalUnitPrice",1),Map.of("_sourceRow",2,"id","管道","attachmentId","someone-else"))),source());
|
||||
@Test void missingMatchRetainsOriginalRowAndMatchingCannotRewritePricesOrAttachment(){
|
||||
var keyed=AssistantQuotationRows.keyed(source());
|
||||
var value=AssistantQuotationRows.ground(proposal(List.of(Map.of("sourceKey",keyed.get(0).get("sourceKey"),"id",7,"finalUnitPrice",1,"attachmentId","someone-else"))),keyed,List.of(Map.of("id",7)));
|
||||
var rows=AssistantConversationService.maps(value.get("rows"));assertEquals(221.2,rows.get(0).get("finalUnitPrice"));assertEquals("mine",rows.get(1).get("attachmentId"));assertTrue(rows.get(0).get("_sourceText").toString().contains("H06A"));
|
||||
assertEquals(2,rows.size());assertEquals(7,rows.get(0).get("id"));assertEquals(Map.of("name","管道","spec","N8"),rows.get(1).get("id"));
|
||||
assertFalse(rows.get(1).containsKey("skipCorrection"));assertFalse(rows.get(0).containsKey("sourceKey"));
|
||||
}
|
||||
@Test void screenshot35Read34MatchedRetainsUnmatchedItem24WithoutShiftingLaterPrices() {
|
||||
var original=new ArrayList<Map<String,Object>>();var targets=new ArrayList<Map<String,Object>>();
|
||||
for(int i=1;i<=35;i++){original.add(Map.of("_sourceRow",i,"sourceName","报价物品"+i,"finalUnitPrice",i*10,"attachmentId","mine"));targets.add(Map.of("id",1000+i));}
|
||||
var keyed=AssistantQuotationRows.keyed(original);var suggestions=new ArrayList<Map<String,Object>>();
|
||||
for(int i=1;i<=35;i++)if(i!=24)suggestions.add(Map.of("sourceKey",keyed.get(i-1).get("sourceKey"),"id",1000+i,"_sourceRow",i>24?i-1:i));
|
||||
var rows=AssistantConversationService.maps(AssistantQuotationRows.ground(proposal(suggestions),keyed,targets).get("rows"));
|
||||
assertEquals(35,rows.size());assertEquals(Map.of("name","报价物品24"),rows.get(23).get("id"));
|
||||
assertEquals(1025,rows.get(24).get("id"));assertEquals(250,rows.get(24).get("finalUnitPrice"));assertEquals(25,rows.get(24).get("_sourceRow"));
|
||||
assertEquals(1035,rows.get(34).get("id"));assertEquals(350,rows.get(34).get("finalUnitPrice"));
|
||||
}
|
||||
@Test void renumberedRowsWithoutSourceKeysNeverAttachTheirIdsToWrongPrices() {
|
||||
var keyed=AssistantQuotationRows.keyed(source());
|
||||
var rows=AssistantConversationService.maps(AssistantQuotationRows.ground(proposal(List.of(Map.of("_sourceRow",1,"id",7),Map.of("_sourceRow",2,"id",8))),keyed,List.of(Map.of("id",7),Map.of("id",8))).get("rows"));
|
||||
assertTrue(rows.stream().allMatch(row->row.get("id") instanceof Map));assertEquals(221.2,rows.get(0).get("finalUnitPrice"));
|
||||
}
|
||||
@Test void duplicateOrUnknownKeysAndForeignIdsLeaveOnlyAffectedRowsForManualMatching() {
|
||||
var keyed=AssistantQuotationRows.keyed(source());var first=keyed.get(0).get("sourceKey");var second=keyed.get(1).get("sourceKey");
|
||||
var suggestions=List.of(Map.<String,Object>of("sourceKey",first,"id",7),Map.<String,Object>of("sourceKey",first,"id",8),Map.<String,Object>of("sourceKey",second,"id",999),Map.<String,Object>of("sourceKey","forged-key","id",8));
|
||||
var rows=AssistantConversationService.maps(AssistantQuotationRows.ground(proposal(suggestions),keyed,List.of(Map.of("id",7),Map.of("id",8))).get("rows"));
|
||||
assertEquals(2,rows.size());assertTrue(rows.stream().allMatch(row->row.get("id") instanceof Map));
|
||||
rows=AssistantConversationService.maps(AssistantQuotationRows.ground(Map.of("rows",List.of()),keyed,List.of()).get("rows"));assertEquals(2,rows.size());
|
||||
}
|
||||
@Test void duplicateOrMissingSourceIndexesCannotBecomeAConfirmableQuotation(){
|
||||
assertThrows(ServiceException.class,()->AssistantQuotationRows.literal(proposal(List.of(source().get(0),source().get(0)))));
|
||||
|
||||
@ -11,6 +11,7 @@ import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseSheetService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchasePriceCorrectionService;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ -20,10 +21,13 @@ class AssistantReferencePriceServiceTest {
|
||||
assertTrue(AssistantConversationService.draftSummary(Map.of("action","purchase.referencePrice","label","修改采购实际单价","rows",rows)).contains("共 34 项"));
|
||||
}
|
||||
AssistantReferencePriceService service;PurchaseSheetService sheets;PurchaseRequestMapper requests;IProjectInfoService projects;PurchaseSheet sheet;MockedStatic<SecurityUtils> security;
|
||||
PurchasePriceCorrectionService corrections;
|
||||
@BeforeEach void setup() {
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
service=new AssistantReferencePriceService();sheets=mock(PurchaseSheetService.class);requests=mock(PurchaseRequestMapper.class);projects=mock(IProjectInfoService.class);
|
||||
ReflectionTestUtils.setField(service,"sheets",sheets);ReflectionTestUtils.setField(service,"requests",requests);ReflectionTestUtils.setField(service,"projects",projects);
|
||||
corrections=mock(PurchasePriceCorrectionService.class);ReflectionTestUtils.setField(service,"corrections",corrections);
|
||||
when(corrections.preview(anyLong(),any())).thenAnswer(call->Map.of("version","cost-"+call.getArgument(0),"archiveOnlyCount",0,"notice","关联成本将变为待补全"));
|
||||
sheet=new PurchaseSheet();var batch=new PurchaseBatch();batch.setId(316L);sheet.setBatch(batch);sheet.setVersion("baseline");
|
||||
sheet.setRows(new ArrayList<>(List.of(row(1L,"12.50",null,4),row(2L,null,"7",2),row(3L,"0","9",3))));
|
||||
when(sheets.load(316L)).thenReturn(sheet);
|
||||
@ -65,4 +69,53 @@ class AssistantReferencePriceServiceTest {
|
||||
sheet.getRows().get(0).setPurchaseStatus(5);assertEquals(false,preview(input("COPY_QUOTE")).get(0).get("changed"));
|
||||
sheet.setRows(Collections.nCopies(101,row(1L,"1",null,1)));assertThrows(ServiceException.class,()->service.preview(input("COPY_QUOTE")));
|
||||
}
|
||||
void makeEditable() {for(var row:sheet.getRows()){row.setHistorical(false);row.setPurchaseStatus(0);row.setPriceLocked(false);}}
|
||||
@Test void combinedPreviewShowsBothPriceChangesWithoutWritingOrMutatingLoadedData() {
|
||||
makeEditable();var before=sheet.getRows().get(0);var values=preview(input("COPY_QUOTE_CLEAR_QUOTE"));
|
||||
assertEquals(new BigDecimal("12.50"),values.get(0).get("newActualPrice"));assertNull(values.get(0).get("newQuotePrice"));
|
||||
assertEquals(new BigDecimal("50.00"),values.get(0).get("newActualAmount"));assertNull(values.get(0).get("newQuoteAmount"));assertEquals(false,values.get(0).get("blocked"));
|
||||
assertEquals(new BigDecimal("7"),values.get(1).get("newActualPrice"));assertEquals(false,values.get(1).get("changed"));
|
||||
assertEquals(BigDecimal.ZERO,values.get(2).get("newActualPrice"));assertNull(values.get(2).get("newQuotePrice"));
|
||||
assertNull(before.getActualUnitPrice());assertEquals(new BigDecimal("12.50"),before.getFinalUnitPrice());verify(sheets,never()).save(any());
|
||||
}
|
||||
@Test void confirmedCombinationDelegatesBothStepsToOneNativeCostCorrectionBatch() {
|
||||
makeEditable();sheet.getRows().get(0).setActualUnitPrice(new BigDecimal("12.50"));
|
||||
var result=service.apply(input("COPY_QUOTE_CLEAR_QUOTE"),"combined-test-save");assertEquals(2,result.get("changed"));
|
||||
verify(sheets,never()).save(any());
|
||||
verify(corrections).correctBatch(argThat(entries->entries.size()==2&&entries.stream().allMatch(entry->Boolean.TRUE.equals(entry.correction().clearQuote())&&Boolean.TRUE.equals(entry.correction().copyQuoteToActual())&&entry.correction().finalUnitPrice()==null)));
|
||||
assertEquals(new BigDecimal("12.50"),sheet.getRows().get(0).getFinalUnitPrice());
|
||||
assertEquals(new BigDecimal("7"),sheet.getRows().get(1).getActualUnitPrice());assertEquals(0,sheet.getRows().get(0).getPurchaseStatus());
|
||||
}
|
||||
@Test void realCostChainErrorStopsBothOperationsForTheEntireBatchBeforeAnyWrite() {
|
||||
makeEditable();when(corrections.preview(eq(3L),any())).thenThrow(new ServiceException("入库成本来源缺失"));
|
||||
assertEquals(true,preview(input("COPY_QUOTE_CLEAR_QUOTE")).get(2).get("blocked"));
|
||||
assertThrows(ServiceException.class,()->service.apply(input("COPY_QUOTE_CLEAR_QUOTE"),"combined-blocked"));
|
||||
assertNull(sheet.getRows().get(0).getActualUnitPrice());assertEquals(new BigDecimal("12.50"),sheet.getRows().get(0).getFinalUnitPrice());verify(sheets,never()).save(any());verify(corrections,never()).correctBatch(any());
|
||||
}
|
||||
@Test void historicalLockedArrivedAndInboundRowsUseExplicitCorrectionInsteadOfBlanketRejection() {
|
||||
var first=sheet.getRows().get(0);first.setPriceLocked(true);first.setAcceptedQuantity(BigDecimal.ONE);
|
||||
when(requests.countConfirmedInbound(1L)).thenReturn(1);
|
||||
var values=preview(input("COPY_QUOTE_CLEAR_QUOTE"));assertEquals(false,values.get(0).get("blocked"));
|
||||
assertTrue(values.get(0).get("notice").toString().contains("成本"));verify(corrections).preview(eq(1L),any());
|
||||
assertEquals(false,preview(input("COPY_QUOTE")).get(0).get("blocked"));
|
||||
}
|
||||
@Test void clearOnlyPreservesActualValuesAndArchiveAcknowledgmentMustBeExplicit() {
|
||||
var values=input("CLEAR_QUOTE");var rows=preview(values);assertNull(rows.get(0).get("newActualPrice"));assertNull(rows.get(0).get("newQuotePrice"));
|
||||
when(corrections.preview(eq(1L),any())).thenReturn(Map.of("version","cost-1","archiveOnlyCount",1,"notice","历史链不完整"));
|
||||
assertEquals(true,preview(values).get(0).get("blocked"));values.put("acknowledgeArchiveOnly",true);
|
||||
assertEquals(false,preview(values).get(0).get("blocked"));service.apply(values,"clear-only");
|
||||
verify(corrections).correctBatch(argThat(entries->entries.stream().allMatch(entry->!Boolean.TRUE.equals(entry.correction().copyQuoteToActual())&&Boolean.TRUE.equals(entry.correction().acknowledgeArchiveOnly()))));
|
||||
}
|
||||
@Test void purchaseEditAloneCannotClearOrReadCostPreviewButStillCanMaintainReferenceAmounts() {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(false);security.when(()->SecurityUtils.hasPermi("warehouse:purchase:edit")).thenReturn(true);
|
||||
assertEquals(403,assertThrows(ServiceException.class,()->service.preview(input("CLEAR_QUOTE"))).getCode());verifyNoInteractions(corrections,sheets);
|
||||
assertEquals(3,preview(input("COPY_QUOTE")).size());
|
||||
}
|
||||
@Test void combinedStaleScopeIsRejectedAndNativeFailurePropagatesInsideTransactionalBoundary() throws Exception {
|
||||
makeEditable();var values=input("COPY_QUOTE_CLEAR_QUOTE");values.put("referenceVersion","stale");
|
||||
assertThrows(ServiceException.class,()->service.apply(values,"combined-stale"));verify(sheets,never()).save(any());
|
||||
doThrow(new ServiceException("模拟并发更新,整单回滚")).when(corrections).correctBatch(any());
|
||||
assertThrows(ServiceException.class,()->service.apply(input("COPY_QUOTE_CLEAR_QUOTE"),"combined-failed"));
|
||||
assertNotNull(AssistantReferencePriceService.class.getMethod("apply",Map.class,String.class).getAnnotation(org.springframework.transaction.annotation.Transactional.class));
|
||||
}
|
||||
}
|
||||
|
||||
@ -27,7 +27,12 @@ public class PurchasePriceCorrectionService {
|
||||
@Autowired private IPurchaseOperationLogService logs;
|
||||
@Autowired private com.ruoyi.production.service.ProductionService production;
|
||||
|
||||
public record Correction(BigDecimal finalUnitPrice,String reason,String version,Boolean acknowledgeArchiveOnly) { }
|
||||
public record Correction(BigDecimal finalUnitPrice,String reason,String version,Boolean acknowledgeArchiveOnly,
|
||||
Boolean clearQuote,Boolean copyQuoteToActual) {
|
||||
public Correction(BigDecimal price,String reason,String version,Boolean acknowledge) {
|
||||
this(price,reason,version,acknowledge,false,false);
|
||||
}
|
||||
}
|
||||
public record Entry(Long id,Correction correction) { }
|
||||
|
||||
/** Validate the entire baseline before any write. Shared cost versions can then advance within this transaction. */
|
||||
@ -48,7 +53,7 @@ public class PurchasePriceCorrectionService {
|
||||
for(var entry:entries) {
|
||||
var input=entry.correction();
|
||||
String currentVersion=previewVersion(snapshot(entry.id()),input);
|
||||
results.add(correct(entry.id(),new Correction(input.finalUnitPrice(),input.reason(),currentVersion,input.acknowledgeArchiveOnly())));
|
||||
results.add(correct(entry.id(),new Correction(input.finalUnitPrice(),input.reason(),currentVersion,input.acknowledgeArchiveOnly(),input.clearQuote(),input.copyQuoteToActual())));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@ -58,7 +63,7 @@ public class PurchasePriceCorrectionService {
|
||||
@Transactional
|
||||
public Map<String,Object> preview(Long id,Correction input) {
|
||||
requirePermission();validate(input);journal.lockInventory();
|
||||
Snapshot snapshot=snapshot(id);var result=view(snapshot,input.finalUnitPrice());result.put("version",previewVersion(snapshot,input));return result;
|
||||
Snapshot snapshot=snapshot(id);var result=view(snapshot,input);result.put("version",previewVersion(snapshot,input));return result;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@ -69,12 +74,12 @@ public class PurchasePriceCorrectionService {
|
||||
throw new ServiceException("采购或关联成本已变化,请重新预览价格更正;如上次响应中断,请先刷新核对结果");
|
||||
if(snapshot.archiveOnly()>0&&!Boolean.TRUE.equals(input.acknowledgeArchiveOnly()))
|
||||
throw new ServiceException("部分历史入库未保留可追溯成本链,请先核对预览并确认仅更正这些历史单据金额");
|
||||
if(old.getFinalUnitPrice()!=null&&old.getFinalUnitPrice().compareTo(input.finalUnitPrice())==0)
|
||||
if(equalPrice(old.getFinalUnitPrice(),input.finalUnitPrice()))
|
||||
throw new ServiceException("报价没有变化,无需更正");
|
||||
String correctionKey="PRICE:"+id+":"+UUID.randomUUID();
|
||||
for(var target:snapshot.events()) {
|
||||
Long eventId=number(target,"id"),projectId=number(target,"project_id"),itemId=number(target,"item_id");
|
||||
journal.reviseReceipt(eventId,PurchasePriceRules.amount((BigDecimal)target.get("quantity"),input.finalUnitPrice()),
|
||||
journal.reviseReceipt(eventId,amount((BigDecimal)target.get("quantity"),input.finalUnitPrice()),
|
||||
correctionKey+":"+eventId,journal.balance(projectId,itemId).getVersion());
|
||||
}
|
||||
// Historical opening receipts have an exact immutable LEGACY-STOCK:<lot id> association.
|
||||
@ -83,16 +88,24 @@ public class PurchasePriceCorrectionService {
|
||||
input.finalUnitPrice(),SecurityUtils.getUsername(),number(lot,"id"));
|
||||
db.update("update in_record set receipt_unit_cost=?,update_time=sysdate() where purchase_request_id=? and in_status in (0,1)",input.finalUnitPrice(),id);
|
||||
if(db.update("update purchase_request set final_unit_price=?,estimated_unit_price=?,estimated_amount=?,update_by=?,update_time=sysdate() where id=? and del_flag='0'",
|
||||
input.finalUnitPrice(),input.finalUnitPrice(),PurchasePriceRules.amount(old.getQuantity(),input.finalUnitPrice()),SecurityUtils.getUsername(),id)!=1)
|
||||
input.finalUnitPrice(),input.finalUnitPrice(),amount(old.getQuantity(),input.finalUnitPrice()),SecurityUtils.getUsername(),id)!=1)
|
||||
throw new ServiceException("采购明细已变化,更正未完成");
|
||||
PurchaseRequest updated=new PurchaseRequest();org.springframework.beans.BeanUtils.copyProperties(old,updated);
|
||||
updated.setFinalUnitPrice(input.finalUnitPrice());
|
||||
prices.refreshLockedAmount(old,updated,"PRICE_CORRECTION");
|
||||
if(Boolean.TRUE.equals(input.copyQuoteToActual())) {
|
||||
// Capture the original quote, not the now-cleared database value. Both writes share this transaction.
|
||||
if(db.update("update purchase_request set actual_unit_price=? where id=? and del_flag='0'",old.getFinalUnitPrice(),id)!=1)
|
||||
throw new ServiceException("采购明细已变化,组合更正未完成");
|
||||
updated.setActualUnitPrice(old.getFinalUnitPrice());
|
||||
}
|
||||
if(Boolean.TRUE.equals(input.clearQuote()))prices.releaseLock(old,updated);
|
||||
else prices.refreshLockedAmount(old,updated,"PRICE_CORRECTION");
|
||||
if(!snapshot.events().isEmpty())production.recalculateSettled();
|
||||
logs.record(id,old.getRequestNo(),"PRICE_CORRECTION","更正采购价格",
|
||||
"报价:"+old.getFinalUnitPrice()+" → "+input.finalUnitPrice()+";采购金额:"+PurchasePriceRules.amount(old.getQuantity(),input.finalUnitPrice())
|
||||
"报价:"+old.getFinalUnitPrice()+" → "+Objects.toString(input.finalUnitPrice(),"未报价")+";采购金额:"+Objects.toString(amount(old.getQuantity(),input.finalUnitPrice()),"待报价")
|
||||
+(Boolean.TRUE.equals(input.copyQuoteToActual())?";原报价已复制到实际单价":"")
|
||||
+";联动成本来源:"+snapshot.events().size()+";仅历史单据:"+snapshot.archiveOnly()+";原因:"+input.reason().trim()+";编号:"+correctionKey);
|
||||
var result=view(snapshot,input.finalUnitPrice());result.put("correctionKey",correctionKey);return result;
|
||||
var result=view(snapshot,input);result.put("correctionKey",correctionKey);return result;
|
||||
}
|
||||
|
||||
private Snapshot snapshot(Long id) {
|
||||
@ -119,28 +132,39 @@ public class PurchasePriceCorrectionService {
|
||||
}
|
||||
int archiveOnly=0;
|
||||
for(var receipt:receipts)if(is(receipt,"in_status",1)&&!is(receipt,"receipt_root",1)&&receipt.get("cost_event_id")==null)archiveOnly++;
|
||||
String signature=List.of(purchase.getId(),Objects.toString(purchase.getFinalUnitPrice(),"NULL"),purchase.getQuantity(),Objects.toString(purchase.getLockRevision(),"NULL"),Objects.toString(purchase.getUpdateTime(),"NULL"),receipts,events,lots).toString();
|
||||
String signature=List.of(purchase.getId(),Objects.toString(purchase.getFinalUnitPrice(),"NULL"),Objects.toString(purchase.getActualUnitPrice(),"NULL"),purchase.getQuantity(),Objects.toString(purchase.getLockRevision(),"NULL"),Objects.toString(purchase.getUpdateTime(),"NULL"),receipts,events,lots).toString();
|
||||
return new Snapshot(purchase,receipts,events,lots,hash(signature),archiveOnly);
|
||||
}
|
||||
|
||||
private Map<String,Object> view(Snapshot snapshot,BigDecimal price) {
|
||||
private Map<String,Object> view(Snapshot snapshot,Correction input) {
|
||||
BigDecimal price=input.finalUnitPrice();
|
||||
var row=snapshot.purchase();var result=new LinkedHashMap<String,Object>();
|
||||
result.put("version",snapshot.version());result.put("materialName",row.getMaterialName());result.put("quantity",row.getQuantity());
|
||||
result.put("oldPrice",row.getFinalUnitPrice());result.put("newPrice",price);
|
||||
result.put("oldAmount",row.getFinalUnitPrice()==null?null:PurchasePriceRules.amount(row.getQuantity(),row.getFinalUnitPrice()));
|
||||
result.put("newAmount",PurchasePriceRules.amount(row.getQuantity(),price));
|
||||
result.put("oldLockedAmount",row.getLockedAmount());result.put("newLockedAmount",Boolean.TRUE.equals(row.getPriceLocked())?PurchasePriceRules.amount(row.getQuantity(),price):row.getLockedAmount());
|
||||
result.put("newAmount",amount(row.getQuantity(),price));
|
||||
result.put("oldLockedAmount",row.getLockedAmount());result.put("newLockedAmount",Boolean.TRUE.equals(row.getPriceLocked())?(Boolean.TRUE.equals(input.clearQuote())?BigDecimal.ZERO:amount(row.getQuantity(),price)):row.getLockedAmount());
|
||||
result.put("receiptCount",snapshot.receipts().size());result.put("costSourceCount",snapshot.events().size());result.put("archiveOnlyCount",snapshot.archiveOnly());
|
||||
result.put("notice",snapshot.archiveOnly()>0?"旧入库未完整保留切换前成本链:将同步采购及历史入库单价、金额,并重算明确关联的期初库存和后续成本;无法追溯的旧出库成本不会推算或改写。":"同步采购金额、已锁定费用、关联入库成本,以及后续领用、库存、借还和已结算生产成本;不改变数量和业务状态。实际单价与实际金额保持不变。");
|
||||
if(Boolean.TRUE.equals(input.clearQuote()))result.put("notice",
|
||||
(Boolean.TRUE.equals(input.copyQuoteToActual())?"先将每条原报价复制到实际单价,自动计算实际金额;":"保留原实际单价与实际金额;")
|
||||
+"再将报价及报价金额清空为未报价(不是0元)。解除对应费用锁定;明确关联的入库、库存、领用、借还及生产成本重算为待报价/成本待补全,不以实际单价代替成本。数量和业务状态不变。"
|
||||
+(snapshot.archiveOnly()>0?"部分历史单据成本链不完整,无法追溯的旧出库成本不推算或改写,需本人核对确认。":""));
|
||||
return result;
|
||||
}
|
||||
static void validate(Correction input) {
|
||||
if(input==null||input.finalUnitPrice()==null||input.finalUnitPrice().signum()<0||input.finalUnitPrice().stripTrailingZeros().scale()>6
|
||||
||input.finalUnitPrice().precision()-input.finalUnitPrice().scale()>14)throw new ServiceException("请填写非负报价,整数最多14位、小数最多6位");
|
||||
if(input==null)throw new ServiceException("请填写价格更正内容");
|
||||
if(Boolean.TRUE.equals(input.clearQuote())) {
|
||||
if(input.finalUnitPrice()!=null)throw new ServiceException("清空报价不能同时指定新报价");
|
||||
} else if(input.finalUnitPrice()==null||input.finalUnitPrice().signum()<0||input.finalUnitPrice().stripTrailingZeros().scale()>6
|
||||
||input.finalUnitPrice().precision()-input.finalUnitPrice().scale()>14)throw new ServiceException("请填写非负报价,整数最多14位、小数最多6位;清空须明确选择清空报价");
|
||||
if(Boolean.TRUE.equals(input.copyQuoteToActual())&&!Boolean.TRUE.equals(input.clearQuote()))throw new ServiceException("复制并清空须作为一个组合操作核对");
|
||||
if(input.reason()==null||input.reason().isBlank()||input.reason().trim().length()>300)throw new ServiceException("请填写价格更正原因,最多300字");
|
||||
}
|
||||
private void requirePermission(){if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("价格更正请由采购管理员协助办理",403);}
|
||||
private String previewVersion(Snapshot snapshot,Correction input){return hash(snapshot.version()+"|"+input.finalUnitPrice().stripTrailingZeros().toPlainString()+"|"+input.reason().trim()+"|"+SecurityUtils.getUserId());}
|
||||
private static BigDecimal amount(BigDecimal quantity,BigDecimal price){return com.ruoyi.warehouse.util.MovingAverageCost.receiptAmount(quantity,price);}
|
||||
private static boolean equalPrice(BigDecimal a,BigDecimal b){return a==null||b==null?a==b:a.compareTo(b)==0;}
|
||||
private String previewVersion(Snapshot snapshot,Correction input){return hash(snapshot.version()+"|"+(input.finalUnitPrice()==null?"NULL":input.finalUnitPrice().stripTrailingZeros().toPlainString())+"|"+input.clearQuote()+"|"+input.copyQuoteToActual()+"|"+input.reason().trim()+"|"+SecurityUtils.getUserId());}
|
||||
private static boolean is(Map<String,Object> row,String key,int expected){Object value=row.get(key);return value instanceof Boolean b?(b?1:0)==expected:value instanceof Number n&&n.intValue()==expected;}
|
||||
private static Long number(Map<String,Object> row,String key){return row.get(key)==null?null:((Number)row.get(key)).longValue();}
|
||||
private static String hash(String text){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));}catch(Exception error){throw new IllegalStateException(error);}}
|
||||
|
||||
@ -110,6 +110,7 @@ public class StockLotServiceImpl implements IStockLotService
|
||||
}
|
||||
|
||||
@Override
|
||||
@org.springframework.transaction.annotation.Transactional
|
||||
public void allocateOutboundLots(OutRecord outRecord)
|
||||
{
|
||||
if (outRecord.getUsageProjectId() == null)
|
||||
@ -132,11 +133,12 @@ public class StockLotServiceImpl implements IStockLotService
|
||||
boolean currentCross = !lot.getSourceProjectId().equals(outRecord.getUsageProjectId())
|
||||
&& !lot.getSourceProjectId().equals(legacyProjectId);
|
||||
crossProject = crossProject || currentCross;
|
||||
if(lot.getUnitCost()==null)throw new ServiceException("该历史库存尚待报价,请先更正采购报价;不会按0元出库");
|
||||
if (stockLotMapper.deductStockLot(lot.getId(), allocated) != 1)
|
||||
{
|
||||
throw new ServiceException("库存批次已变化,请刷新后重试");
|
||||
}
|
||||
BigDecimal unitCost = lot.getUnitCost() == null ? BigDecimal.ZERO : lot.getUnitCost();
|
||||
BigDecimal unitCost = lot.getUnitCost();
|
||||
stockLotMapper.insertOutRecordLot(outRecord.getId(), lot.getId(), lot.getSourceProjectId(),
|
||||
outRecord.getUsageProjectId(), allocated, unitCost,
|
||||
allocated.multiply(unitCost).setScale(2, RoundingMode.HALF_UP));
|
||||
|
||||
@ -1,16 +1,19 @@
|
||||
<template>
|
||||
<section class="assistant-reference-preview" aria-label="实际金额逐项核对">
|
||||
<header><strong>实际金额核对 · {{ rows.length }} 项</strong><span>仅作内部参考,不修改报价及成本。未报价保留原值,零报价可设为 0。</span></header>
|
||||
<header><strong>{{ combined ? '实际金额与报价核对' : '实际金额核对' }} · {{ rows.length }} 项</strong><span>{{ combined ? '按所选方式更正报价(清空不是 0 元);同步核对费用及下游成本,整批确认后提交。' : '仅作内部参考,不修改报价及成本。未报价保留原值,零报价可设为 0。' }}</span></header>
|
||||
<el-table :data="pageRows" border max-height="380">
|
||||
<el-table-column prop="name" label="物品名称" min-width="160"/>
|
||||
<el-table-column prop="spec" label="规格型号" min-width="150"/>
|
||||
<el-table-column prop="quantity" label="采购数量" width="100"/>
|
||||
<el-table-column label="当前报价" width="110"><template #default="{ row }">{{ row.quotePrice ?? '未报价' }}</template></el-table-column>
|
||||
<el-table-column label="原实际单价" width="110"><template #default="{ row }">{{ row.oldActualPrice ?? '未填写' }}</template></el-table-column>
|
||||
<el-table-column label="新实际单价" width="110"><template #default="{ row }"><strong :class="{ changed: row.changed }">{{ row.newActualPrice ?? '未填写' }}</strong></template></el-table-column>
|
||||
<el-table-column label="原实际金额" width="120"><template #default="{ row }">{{ row.oldActualAmount ?? '未填写' }}</template></el-table-column>
|
||||
<el-table-column label="新实际金额" width="120"><template #default="{ row }"><strong :class="{ changed: row.changed }">{{ row.newActualAmount ?? '未填写' }}</strong></template></el-table-column>
|
||||
<el-table-column prop="notice" label="核对说明" min-width="220"/>
|
||||
<el-table-column :label="combined ? '原报价单价' : '当前报价'" width="110"><template #default="{ row }"><span :class="{ removed: row.clearQuote && row.changed }">{{ row.quotePrice ?? '未报价' }}</span></template></el-table-column>
|
||||
<el-table-column v-if="combined" label="新报价单价" width="130"><template #default="{ row }"><strong :class="{ changed: row.clearQuote && row.changed }">{{ row.newQuotePrice ?? (row.clearQuote && row.changed ? '清空(未报价)' : '未报价') }}</strong></template></el-table-column>
|
||||
<el-table-column v-if="combined" label="原报价金额" width="120"><template #default="{ row }">{{ row.oldQuoteAmount ?? '未报价' }}</template></el-table-column>
|
||||
<el-table-column v-if="combined" label="新报价金额" width="130"><template #default="{ row }">{{ row.newQuoteAmount ?? (row.clearQuote && row.changed ? '清空(未报价)' : '未报价') }}</template></el-table-column>
|
||||
<el-table-column label="核对说明" min-width="240"><template #default="{ row }"><span :class="{ blocked: row.blocked }">{{ row.notice }}</span></template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination v-if="rows.length > 20" v-model:current-page="page" :page-size="20" :total="rows.length" layout="total, prev, pager, next" small/>
|
||||
</section>
|
||||
@ -18,6 +21,7 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
const props = defineProps({ rows: { type: Array, default: () => [] } })
|
||||
const combined = computed(() => props.rows.some(row => row.clearQuote))
|
||||
const page = ref(1), pageRows = computed(() => props.rows.slice((page.value - 1) * 20, page.value * 20))
|
||||
watch(() => props.rows, () => { page.value = 1 })
|
||||
</script>
|
||||
@ -25,4 +29,6 @@ watch(() => props.rows, () => { page.value = 1 })
|
||||
.assistant-reference-preview { margin-top:16px; min-width:0; }
|
||||
header { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:10px; font-size:13px; } header span { color:var(--el-text-color-secondary); }
|
||||
.changed { color:var(--el-color-success); } :deep(.cell) { white-space:normal; overflow-wrap:anywhere; } .el-pagination { margin-top:10px; }
|
||||
.removed { color:var(--el-text-color-secondary); text-decoration:line-through; }
|
||||
.blocked { color:var(--el-color-danger); }
|
||||
</style>
|
||||
|
||||
@ -1,180 +1,171 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-popover placement="bottom-end" :width="320" trigger="click" v-model:visible="noticeVisible" popper-class="notice-popover">
|
||||
<!-- 弹出内容 -->
|
||||
<div class="notice-header">
|
||||
<span class="notice-title">通知公告</span>
|
||||
<el-button link type="primary" size="small" :disabled="!unreadCount || noticeLoading" @click="markAllRead">全部已读</el-button>
|
||||
<button type="button" class="right-menu-item hover-effect notice-trigger" aria-label="消息中心" :aria-expanded="visible" @click="openCenter">
|
||||
<svg-icon icon-class="bell" />
|
||||
<span v-if="badge" class="notice-badge" aria-live="polite">{{ badge }}</span>
|
||||
</button>
|
||||
<el-drawer v-model="visible" title="消息中心" direction="rtl" size="min(640px, 100vw)" append-to-body class="message-center" @closed="backToList">
|
||||
<div class="center-toolbar">
|
||||
<el-radio-group v-model="tab" aria-label="消息类型" :disabled="reading" @change="backToList">
|
||||
<el-radio-button value="inbox">站内消息<span v-if="inboxCountLabel" class="tab-count">{{ inboxCountLabel }}</span></el-radio-button>
|
||||
<el-radio-button value="notices">通知公告<span v-if="noticeUnread" class="tab-count">{{ noticeUnread }}</span></el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-button :loading="loading || noticesLoading" :disabled="reading" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
<div v-if="noticeLoading" class="notice-loading">
|
||||
<el-icon class="is-loading"><Loading /></el-icon> 加载中...
|
||||
</div>
|
||||
<div v-else-if="noticeList.length === 0" class="notice-empty">
|
||||
<el-icon style="font-size:24px;display:block;margin-bottom:6px;"><Postcard /></el-icon>
|
||||
暂无公告
|
||||
</div>
|
||||
<div v-else>
|
||||
<div v-for="item in noticeList" :key="item.noticeId" class="notice-item" :class="{ 'is-read': item.isRead }" @click="previewNotice(item)">
|
||||
<el-tag size="small" :type="item.noticeType === '1' ? 'warning' : 'success'" class="notice-tag">
|
||||
{{ item.noticeType === '1' ? '通知' : '公告' }}
|
||||
</el-tag>
|
||||
<span class="notice-item-title">{{ item.noticeTitle }}</span>
|
||||
<span class="notice-item-date">{{ item.createTime }}</span>
|
||||
<el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon class="center-error" />
|
||||
<section v-if="detail" class="message-detail" aria-label="消息详情">
|
||||
<el-button link type="primary" :disabled="reading" @click="backToList">← 返回列表</el-button>
|
||||
<h2>{{ detail.title }}</h2>
|
||||
<div class="detail-meta">{{ detail.time || '—' }} · {{ detail.read ? '已读' : '未读' }}</div>
|
||||
<p class="message-content">{{ detail.content || '暂无正文' }}</p>
|
||||
<el-button v-if="!detail.read" type="primary" :loading="reading" @click="markDetailRead">标为已读</el-button>
|
||||
</section>
|
||||
<div v-else-if="detailLoading" class="center-empty" role="status">正在获取消息详情…</div>
|
||||
<template v-else-if="tab === 'inbox'">
|
||||
<div class="list-tools">
|
||||
<el-checkbox v-model="unreadOnly" :disabled="loading || reading" @change="loadMessages(true)">只看未读</el-checkbox>
|
||||
<el-button link type="primary" :disabled="!messages.some(item => !item.readAt) || reading || loading" :loading="reading" title="每次最多标记 100 条已加载消息" @click="markPageRead">已加载消息标为已读</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="$can(['system:notice:list'])" class="notice-footer">
|
||||
<el-button link type="primary" icon="Setting" @click="openManagement">公告管理</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 触发器 -->
|
||||
<template #reference>
|
||||
<button type="button" class="right-menu-item hover-effect notice-trigger" aria-label="通知公告" :aria-expanded="noticeVisible">
|
||||
<svg-icon icon-class="bell" />
|
||||
<span v-if="unreadCount > 0" class="notice-badge">{{ unreadCount }}</span>
|
||||
</button>
|
||||
<div v-if="loading && !messages.length" class="center-empty" role="status">正在获取你的站内消息…</div>
|
||||
<div v-else-if="!messages.length" class="center-empty">{{ hasMore ? '本页暂无当前可查看的消息,可继续加载较早消息。' : (unreadOnly ? '暂无未读消息' : '暂无站内消息') }}</div>
|
||||
<ul v-if="messages.length" class="center-list">
|
||||
<li v-for="item in messages" :key="item.id">
|
||||
<button type="button" class="message-item" :class="{ 'is-read': item.readAt }" @click="openMessage(item)">
|
||||
<span class="message-title"><span v-if="!item.readAt" class="unread-dot" aria-label="未读" />{{ item.title }}</span>
|
||||
<span class="message-time">{{ item.deliveredAt || '—' }}</span>
|
||||
<span class="message-excerpt">{{ item.content }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="center-footer"><el-button v-if="hasMore" :loading="loading" :disabled="reading" @click="loadMessages(false)">加载更早消息</el-button><span v-else-if="messages.length">已显示当前可查看的消息</span></div>
|
||||
</template>
|
||||
</el-popover>
|
||||
|
||||
<!-- 预览弹窗 -->
|
||||
<notice-detail-view ref="noticeViewRef" />
|
||||
<template v-else>
|
||||
<div class="list-tools"><span>最近 5 条通知公告</span><el-button link type="primary" :disabled="!noticeUnread || reading || noticesLoading" :loading="reading" @click="markNoticesRead">本页标为已读</el-button></div>
|
||||
<div v-if="noticesLoading" class="center-empty" role="status">正在获取通知公告…</div>
|
||||
<div v-else-if="!notices.length" class="center-empty">暂无通知公告</div>
|
||||
<ul v-else class="center-list">
|
||||
<li v-for="item in notices" :key="item.noticeId">
|
||||
<button type="button" class="message-item" :class="{ 'is-read': item.isRead }" @click="openNotice(item)">
|
||||
<span class="message-title"><span v-if="!item.isRead" class="unread-dot" aria-label="未读" />{{ item.noticeTitle }}</span><span class="message-time">{{ item.createTime || '—' }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="proxy?.$can(['system:notice:list'])" class="center-footer"><el-button link type="primary" @click="openManagement">公告管理</el-button></div>
|
||||
</template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import NoticeDetailView from './DetailView'
|
||||
import { listNoticeTop, markNoticeRead, markNoticeReadAll } from '@/api/system/notice'
|
||||
import { ref, computed, watch, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import useUserStore from '@/store/modules/user'
|
||||
import { listNotifications, notificationUnread, getNotification, readNotificationBatch } from '@/api/system/notification'
|
||||
import { listNoticeTop, getNotice, markNoticeReadAll } from '@/api/system/notice'
|
||||
|
||||
const router = useRouter()
|
||||
const noticeList = ref([])
|
||||
const unreadCount = ref(0)
|
||||
const noticeLoading = ref(false)
|
||||
const noticeVisible = ref(false)
|
||||
const { proxy } = getCurrentInstance()
|
||||
|
||||
// 加载顶部公告列表
|
||||
function loadNoticeTop() {
|
||||
noticeLoading.value = true
|
||||
listNoticeTop().then(res => {
|
||||
noticeList.value = res.data || []
|
||||
unreadCount.value = res.unreadCount !== undefined ? res.unreadCount : noticeList.value.filter(n => !n.isRead).length
|
||||
}).catch(() => { noticeList.value = []; unreadCount.value = 0 }).finally(() => {
|
||||
noticeLoading.value = false
|
||||
})
|
||||
const router = useRouter(), user = useUserStore(), { proxy } = getCurrentInstance()
|
||||
const visible = ref(false), tab = ref('inbox'), unreadOnly = ref(false), messages = ref([]), notices = ref([])
|
||||
const loading = ref(false), noticesLoading = ref(false), detailLoading = ref(false), reading = ref(false), error = ref('')
|
||||
const hasMore = ref(false), nextCursor = ref(null), detail = ref(null), count = ref(0), exact = ref(true)
|
||||
let generation = 0, listSerial = 0, noticeSerial = 0, detailSerial = 0, countSerial = 0, timer
|
||||
const noticeUnread = computed(() => notices.value.filter(item => !item.isRead).length)
|
||||
const countLabel = (value, isExact) => value > 99 ? '99+' : (!isExact ? (value ? value + '+' : '…') : (value ? String(value) : ''))
|
||||
const inboxCountLabel = computed(() => countLabel(count.value, exact.value))
|
||||
const badge = computed(() => countLabel(count.value + noticeUnread.value, exact.value))
|
||||
function failure(cause) { error.value = cause?.message || '暂时无法获取消息,请稍后点击刷新重试。' }
|
||||
function backToList() { detailSerial++; detail.value = null; detailLoading.value = false }
|
||||
async function refreshCount() {
|
||||
const epoch = generation, serial = ++countSerial
|
||||
try { const result = await notificationUnread(); if (epoch === generation && serial === countSerial) { count.value = Number(result.data.count) || 0; exact.value = result.data.exact !== false } }
|
||||
catch (cause) { if (epoch === generation && serial === countSerial && visible.value) failure(cause) }
|
||||
}
|
||||
|
||||
onMounted(() => loadNoticeTop())
|
||||
|
||||
function openManagement() {
|
||||
if (!proxy.$can(['system:notice:list'])) return
|
||||
noticeVisible.value = false
|
||||
router.push('/system/notice')
|
||||
async function loadNotices() {
|
||||
const epoch = generation, serial = ++noticeSerial; noticesLoading.value = true
|
||||
try { const result = await listNoticeTop(); if (epoch === generation && serial === noticeSerial) notices.value = result.data || [] }
|
||||
catch (cause) { if (epoch === generation && serial === noticeSerial) failure(cause) }
|
||||
finally { if (epoch === generation && serial === noticeSerial) noticesLoading.value = false }
|
||||
}
|
||||
|
||||
// 预览公告详情
|
||||
async function previewNotice(item) {
|
||||
if (!item.isRead) {
|
||||
try { await markNoticeRead(item.noticeId) } catch { return }
|
||||
const idx = noticeList.value.indexOf(item)
|
||||
if (idx !== -1) noticeList.value[idx] = { ...item, isRead: true }
|
||||
unreadCount.value = Math.max(0, unreadCount.value - 1)
|
||||
}
|
||||
noticeVisible.value = false
|
||||
proxy.$refs["noticeViewRef"].open(item.noticeId)
|
||||
async function loadMessages(reset = true) {
|
||||
if (reading.value || (!reset && (loading.value || !hasMore.value))) return
|
||||
const epoch = generation, serial = ++listSerial, cursor = reset ? null : nextCursor.value
|
||||
loading.value = true; error.value = ''
|
||||
if (reset) { messages.value = []; hasMore.value = false; nextCursor.value = null }
|
||||
try {
|
||||
const result = await listNotifications({ beforeId: cursor, unreadOnly: unreadOnly.value })
|
||||
if (epoch !== generation || serial !== listSerial) return
|
||||
const page = result.data || {}, candidate = page.nextCursor
|
||||
// Empty permission-filtered pages are valid; never auto-loop through them.
|
||||
const advancing = candidate != null && /^\d+$/.test(String(candidate)) && BigInt(candidate) > 0n && (cursor == null || BigInt(candidate) < BigInt(cursor))
|
||||
const seen = new Set(messages.value.map(item => String(item.id)))
|
||||
messages.value = [...messages.value, ...(page.items || []).filter(item => !seen.has(String(item.id)))]
|
||||
hasMore.value = page.hasMore === true && advancing; nextCursor.value = advancing ? candidate : null
|
||||
if (page.hasMore && !advancing) error.value = '分页位置未更新,请刷新消息列表后继续。'
|
||||
} catch (cause) { if (epoch === generation && serial === listSerial) failure(cause) }
|
||||
finally { if (epoch === generation && serial === listSerial) loading.value = false }
|
||||
}
|
||||
|
||||
// 全部已读
|
||||
async function markAllRead() {
|
||||
const ids = noticeList.value.map(n => n.noticeId).join(',')
|
||||
if (!ids) return
|
||||
try { await markNoticeReadAll(ids) } catch { return }
|
||||
noticeList.value = noticeList.value.map(n => ({ ...n, isRead: true }))
|
||||
unreadCount.value = 0
|
||||
async function refresh() { if (reading.value) return; backToList(); error.value = ''; await Promise.all([loadMessages(true), loadNotices(), refreshCount()]) }
|
||||
function openCenter() { visible.value = true; void refresh() }
|
||||
async function openMessage(item) {
|
||||
const epoch = generation, serial = ++detailSerial; detail.value = null; detailLoading.value = true; error.value = ''
|
||||
try { const result = await getNotification(item.id); if (epoch === generation && serial === detailSerial && visible.value) detail.value = { kind: 'inbox', id: item.id, title: result.data.title, content: result.data.content, time: result.data.deliveredAt, read: !!result.data.readAt } }
|
||||
catch (cause) { if (epoch === generation && serial === detailSerial) failure(cause) }
|
||||
finally { if (epoch === generation && serial === detailSerial) detailLoading.value = false }
|
||||
}
|
||||
function plainNotice(html) { const doc = new DOMParser().parseFromString(String(html || ''), 'text/html'); doc.querySelectorAll('script,style,iframe,object').forEach(item => item.remove()); doc.body.querySelectorAll('br,p,div,h1,h2,h3,h4,li,tr').forEach(item => item.append(doc.createTextNode('\n'))); return (doc.body.textContent || '').trim() }
|
||||
async function openNotice(item) {
|
||||
const epoch = generation, serial = ++detailSerial; detail.value = null; detailLoading.value = true; error.value = ''
|
||||
try { const result = await getNotice(item.noticeId); if (epoch === generation && serial === detailSerial && visible.value) detail.value = { kind: 'notices', id: item.noticeId, title: result.data.noticeTitle, content: plainNotice(result.data.noticeContent), time: result.data.createTime, read: !!item.isRead } }
|
||||
catch (cause) { if (epoch === generation && serial === detailSerial) failure(cause) }
|
||||
finally { if (epoch === generation && serial === detailSerial) detailLoading.value = false }
|
||||
}
|
||||
async function mark(ids, kind) {
|
||||
if (reading.value || !ids.length) return false
|
||||
ids = ids.slice(0, 100)
|
||||
const epoch = generation; reading.value = true; countSerial++; error.value = ''
|
||||
if (kind === 'notices') { noticeSerial++; noticesLoading.value = false } else { listSerial++; loading.value = false }
|
||||
try {
|
||||
if (kind === 'notices') await markNoticeReadAll(ids.join(','))
|
||||
else await readNotificationBatch(ids)
|
||||
if (epoch !== generation) return false
|
||||
const selected = new Set(ids.map(String))
|
||||
if (kind === 'notices') notices.value = notices.value.map(item => selected.has(String(item.noticeId)) ? { ...item, isRead: true } : item)
|
||||
else { messages.value = messages.value.map(item => selected.has(String(item.id)) ? { ...item, readAt: new Date().toISOString() } : item); if (unreadOnly.value) messages.value = messages.value.filter(item => !item.readAt); await refreshCount() }
|
||||
if (detail.value && detail.value.kind === kind && selected.has(String(detail.value.id))) detail.value = { ...detail.value, read: true }
|
||||
return true
|
||||
} catch (cause) { if (epoch === generation) failure(cause); return false }
|
||||
finally { if (epoch === generation) reading.value = false }
|
||||
}
|
||||
function markDetailRead() { return mark([detail.value.id], detail.value.kind) }
|
||||
function markPageRead() { return mark(messages.value.filter(item => !item.readAt).map(item => item.id), 'inbox') }
|
||||
function markNoticesRead() { return mark(notices.value.filter(item => !item.isRead).map(item => item.noticeId), 'notices') }
|
||||
function openManagement() { if (!proxy.$can(['system:notice:list'])) return; visible.value = false; router.push('/system/notice') }
|
||||
function reset() { generation++; listSerial++; noticeSerial++; detailSerial++; countSerial++; visible.value = false; messages.value = []; notices.value = []; detail.value = null; count.value = 0; exact.value = true; hasMore.value = false; nextCursor.value = null; loading.value = false; noticesLoading.value = false; detailLoading.value = false; reading.value = false; error.value = '' }
|
||||
watch(() => user.id, () => { reset(); if (user.id) void Promise.all([refreshCount(), loadNotices()]) })
|
||||
onMounted(() => { void Promise.all([refreshCount(), loadNotices()]); timer = setInterval(() => { if (document.visibilityState === 'visible' && !reading.value && !noticesLoading.value) void Promise.all([refreshCount(), loadNotices()]) }, 60000) })
|
||||
onBeforeUnmount(() => { clearInterval(timer); reset() })
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.notice-trigger {
|
||||
position: relative;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
&:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
|
||||
transform: translateX(-6px);
|
||||
.svg-icon { width: 1.2em; height: 1.2em; vertical-align: -0.2em; }
|
||||
.notice-badge {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
right: -3px;
|
||||
background: #f56c6c;
|
||||
color: #fff;
|
||||
border-radius: 10px;
|
||||
font-size: 10px;
|
||||
height: 16px;
|
||||
line-height: 16px;
|
||||
padding: 0 4px;
|
||||
min-width: 16px;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
.notice-popover { padding: 0 !important; }
|
||||
.notice-footer { display: flex; justify-content: flex-end; padding: 10px 14px; border-top: 1px solid var(--el-border-color-light); }
|
||||
.notice-popover .notice-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 14px;
|
||||
background: var(--el-fill-color-light);
|
||||
border-bottom: 1px solid var(--el-border-color-light);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.notice-popover .notice-mark-all {
|
||||
font-size: 12px;
|
||||
color: var(--el-color-primary);
|
||||
font-weight: normal;
|
||||
cursor: pointer;
|
||||
}
|
||||
.notice-popover .notice-mark-all:hover { color: var(--el-color-primary-light-3); }
|
||||
.notice-popover .notice-loading,
|
||||
.notice-popover .notice-empty {
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.notice-popover .notice-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.notice-popover .notice-item:last-child { border-bottom: none; }
|
||||
.notice-popover .notice-item:hover { background: var(--el-fill-color-light); }
|
||||
.notice-popover .notice-item.is-read .notice-tag,
|
||||
.notice-popover .notice-item.is-read .notice-item-title,
|
||||
.notice-popover .notice-item.is-read .notice-item-date { opacity: 0.45; filter: grayscale(1); color: var(--el-text-color-secondary); }
|
||||
.notice-popover .notice-tag { flex-shrink: 0; }
|
||||
.notice-popover .notice-item-title {
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-primary);
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.notice-popover .notice-item-date {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
<style scoped>
|
||||
.notice-trigger { position:relative; border:0; background:transparent; color:inherit; font:inherit; cursor:pointer; }
|
||||
.notice-trigger:focus-visible { outline:2px solid var(--el-color-primary); outline-offset:-2px; }
|
||||
.notice-trigger .svg-icon { width:1.2em; height:1.2em; vertical-align:-.2em; }
|
||||
.notice-badge { position:absolute; top:7px; right:0; padding:0 4px; min-width:16px; height:16px; line-height:16px; border-radius:10px; color:#fff; background:var(--el-color-danger); font-size:10px; white-space:nowrap; pointer-events:none; }
|
||||
.center-toolbar,.list-tools { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px; margin-bottom:16px; }
|
||||
.tab-count { margin-left:6px; font-size:12px; }
|
||||
.list-tools,.detail-meta,.message-time,.center-footer { color:var(--el-text-color-secondary); font-size:12px; }
|
||||
.center-error { margin-bottom:16px; }
|
||||
.center-empty { padding:48px 16px; text-align:center; color:var(--el-text-color-secondary); line-height:1.8; }
|
||||
.center-list { margin:0; padding:0; list-style:none; }
|
||||
.message-item { width:100%; display:grid; grid-template-columns:minmax(0,1fr) auto; gap:10px 12px; padding:18px 4px; text-align:left; border:0; border-bottom:1px solid var(--el-border-color-lighter); color:var(--el-text-color-primary); background:transparent; cursor:pointer; }
|
||||
.message-item:hover { background:var(--el-fill-color-light); }
|
||||
.message-item:focus-visible { outline:2px solid var(--el-color-primary); }
|
||||
.message-title { font-weight:600; overflow-wrap:anywhere; line-height:1.6; }
|
||||
.message-item.is-read .message-title { font-weight:400; color:var(--el-text-color-regular); }
|
||||
.message-time { align-self:center; }
|
||||
.message-excerpt { grid-column:1/-1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:var(--el-text-color-secondary); }
|
||||
.unread-dot { display:inline-block; width:7px; height:7px; border-radius:50%; background:var(--el-color-primary); margin-right:8px; vertical-align:middle; }
|
||||
.center-footer { display:flex; justify-content:center; padding:20px 0; }
|
||||
.message-detail h2 { font-size:20px; line-height:1.7; overflow-wrap:anywhere; margin:22px 0 10px; }
|
||||
.message-content { white-space:pre-wrap; overflow-wrap:anywhere; line-height:1.9; margin:24px 0; color:var(--el-text-color-primary); }
|
||||
@media(max-width:480px) { .message-item { grid-template-columns:minmax(0,1fr); } .message-excerpt { grid-column:auto; } .center-toolbar { gap:10px; } }
|
||||
</style>
|
||||
|
||||
@ -27,7 +27,7 @@
|
||||
|
||||
</template>
|
||||
|
||||
<el-tooltip content="通知公告" effect="dark" placement="bottom">
|
||||
<el-tooltip content="消息中心" effect="dark" placement="bottom">
|
||||
<header-notice id="header-notice" class="right-menu-item hover-effect" />
|
||||
</el-tooltip>
|
||||
|
||||
|
||||
@ -0,0 +1,30 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import Preview from '@/components/BusinessAssistant/AssistantReferencePricePreview.vue'
|
||||
|
||||
it('one combined preview renders actual amounts first, cleared quotes as empty rather than zero, and restrictions', async () => {
|
||||
const wrapper = mount(Preview, { props: { rows: [
|
||||
{ name: '模拟水泵', quantity: 2, quotePrice: 12.5, oldActualPrice: 1, newActualPrice: 12.5, oldActualAmount: 2, newActualAmount: 25, oldQuoteAmount: 25, newQuotePrice: null, newQuoteAmount: null, clearQuote: true, changed: true, blocked: false, notice: '先复制原报价,再清空报价' },
|
||||
{ name: '模拟历史采购', quantity: 1, quotePrice: 0, newActualPrice: 0, newActualAmount: 0, newQuotePrice: null, newQuoteAmount: null, clearQuote: true, changed: true, blocked: true, notice: '已有到货或入库记录,整批不执行' }
|
||||
] }, global: { plugins: [ElementPlus] } })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('实际金额与报价核对')
|
||||
expect(wrapper.text()).toContain('清空(未报价)')
|
||||
expect(wrapper.text()).toContain('不是 0 元')
|
||||
expect(wrapper.find('.blocked').text()).toContain('整批不执行')
|
||||
expect(wrapper.findAll('.removed').map(node => node.text())).toEqual(['12.5', '0'])
|
||||
const headers = wrapper.findAll('thead th').map(node => node.text())
|
||||
expect(headers.indexOf('新实际金额')).toBeLessThan(headers.indexOf('原报价单价'))
|
||||
expect(headers).toContain('新报价金额')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('reference-only mode still promises unchanged quotes and never shows clear-quote columns', async () => {
|
||||
const wrapper = mount(Preview, { props: { rows: [{ name: '模拟物品', newActualPrice: 0, newActualAmount: 0, quotePrice: 0, changed: true }] }, global: { plugins: [ElementPlus] } })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('不修改报价及成本')
|
||||
expect(wrapper.text()).not.toContain('清空(未报价)')
|
||||
expect(wrapper.findAll('thead th').map(node => node.text())).not.toContain('新报价单价')
|
||||
wrapper.unmount()
|
||||
})
|
||||
73
ruoyi-ui-vue3/tests/runtime/message-center.spec.js
Normal file
73
ruoyi-ui-vue3/tests/runtime/message-center.spec.js
Normal file
@ -0,0 +1,73 @@
|
||||
import { beforeEach, afterEach, expect, it, vi } from 'vitest'
|
||||
import { reactive } from 'vue'
|
||||
import { mount, flushPromises, DOMWrapper } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import Center from '@/layout/components/HeaderNotice/index.vue'
|
||||
|
||||
const api = vi.hoisted(() => ({ list: vi.fn(), unread: vi.fn(), detail: vi.fn(), read: vi.fn(), notices: vi.fn(), notice: vi.fn(), readNotices: vi.fn() }))
|
||||
const identity = reactive({ id: 1 })
|
||||
vi.mock('@/store/modules/user', () => ({ default: () => identity }))
|
||||
vi.mock('vue-router', () => ({ useRouter: () => ({ push: vi.fn() }) }))
|
||||
vi.mock('@/api/system/notification', () => ({ listNotifications: api.list, notificationUnread: api.unread, getNotification: api.detail, readNotificationBatch: api.read }))
|
||||
vi.mock('@/api/system/notice', () => ({ listNoticeTop: api.notices, getNotice: api.notice, markNoticeReadAll: api.readNotices }))
|
||||
let wrapper
|
||||
const dom = () => new DOMWrapper(document.body)
|
||||
const message = (id = 7) => ({ id, title: '模拟站内消息', content: '<img src=x onerror="alert(1)">\n纯文本正文', readAt: null, deliveredAt: '2026-10-20 11:00' })
|
||||
const button = label => dom().findAll('button').find(item => item.text() === label)
|
||||
async function open() {
|
||||
wrapper = mount(Center, { attachTo: document.body, global: { plugins: [ElementPlus], stubs: { transition: true, SvgIcon: true }, config: { globalProperties: { $can: () => false } } } })
|
||||
await dom().find('[aria-label="消息中心"]').trigger('click'); await flushPromises()
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks(); identity.id = 1
|
||||
api.unread.mockResolvedValue({ data: { count: 1, exact: true } })
|
||||
api.notices.mockResolvedValue({ data: [] })
|
||||
api.list.mockResolvedValue({ data: { items: [message()], hasMore: false, nextCursor: null } })
|
||||
api.detail.mockImplementation(async id => ({ data: message(id) }))
|
||||
api.read.mockResolvedValue({ code: 200 }); api.readNotices.mockResolvedValue({ code: 200 })
|
||||
})
|
||||
afterEach(() => { wrapper?.unmount(); wrapper = null; document.body.innerHTML = '' })
|
||||
|
||||
it('opens the personal inbox without marking read or displaying message HTML as executable markup', async () => {
|
||||
await open(); expect(dom().text()).toContain('站内消息'); expect(dom().text()).toContain('模拟站内消息')
|
||||
expect(api.list).toHaveBeenCalledExactlyOnceWith({ beforeId: null, unreadOnly: false })
|
||||
expect(api.read).not.toHaveBeenCalled(); expect(api.readNotices).not.toHaveBeenCalled()
|
||||
await dom().find('.message-item').trigger('click'); await flushPromises()
|
||||
expect(dom().find('.message-content').text()).toContain('<img'); expect(dom().find('.message-content img').exists()).toBe(false)
|
||||
expect(api.read).not.toHaveBeenCalled()
|
||||
api.unread.mockResolvedValue({ data: { count: 0, exact: true } })
|
||||
await button('标为已读').trigger('click'); await flushPromises()
|
||||
expect(api.read).toHaveBeenCalledExactlyOnceWith([7]); expect(dom().text()).toContain('已读')
|
||||
await button('← 返回列表').trigger('click'); expect(dom().find('.message-item').classes()).toContain('is-read')
|
||||
})
|
||||
it('empty permission-filtered pages only advance on manual clicks and repeated cursors cannot loop', async () => {
|
||||
api.list.mockResolvedValueOnce({ data: { items: [], hasMore: true, nextCursor: 100 } }).mockResolvedValueOnce({ data: { items: [message(90)], hasMore: true, nextCursor: 100 } })
|
||||
await open(); expect(api.list).toHaveBeenCalledTimes(1); expect(dom().text()).toContain('可继续加载')
|
||||
await button('加载更早消息').trigger('click'); await flushPromises()
|
||||
expect(api.list).toHaveBeenCalledTimes(2); expect(api.list.mock.calls[1][0].beforeId).toBe(100)
|
||||
expect(dom().text()).toContain('分页位置未更新'); expect(button('加载更早消息')).toBeUndefined()
|
||||
})
|
||||
it('a failed read acknowledgement preserves unread state and does not hide the error', async () => {
|
||||
api.read.mockRejectedValueOnce(new Error('暂时断网,请重试'))
|
||||
await open(); await dom().find('.message-item').trigger('click'); await flushPromises()
|
||||
await button('标为已读').trigger('click'); await flushPromises()
|
||||
expect(dom().text()).toContain('暂时断网'); expect(button('标为已读')).toBeDefined()
|
||||
await button('← 返回列表').trigger('click'); expect(dom().find('.message-item').classes()).not.toContain('is-read')
|
||||
})
|
||||
it('switching account clears private content and ignores a late detail response', async () => {
|
||||
let finish; api.detail.mockImplementation(() => new Promise(resolve => { finish = resolve }))
|
||||
await open(); await dom().find('.message-item').trigger('click'); await flushPromises()
|
||||
identity.id = 2; await flushPromises(); finish({ data: { ...message(), content: '上一账号私有正文' } }); await flushPromises()
|
||||
expect(dom().text()).not.toContain('上一账号私有正文'); expect(dom().text()).not.toContain('模拟站内消息')
|
||||
})
|
||||
it('announcement and message read operations stay separate and the badge respects lower-bound counts', async () => {
|
||||
api.unread.mockResolvedValue({ data: { count: 0, exact: false } })
|
||||
api.notices.mockResolvedValue({ data: [{ noticeId: 7, noticeTitle: '模拟公告', isRead: false }] })
|
||||
api.notice.mockResolvedValue({ data: { noticeId: 7, noticeTitle: '模拟公告', noticeContent: '<p>公告正文</p><script>not displayed</script>' } })
|
||||
await open(); expect(dom().find('.notice-badge').text()).toBe('1+')
|
||||
const radio = dom().findAll('input[type="radio"]').find(item => item.element.value === 'notices')
|
||||
await radio.setValue(); await flushPromises(); await dom().find('.message-item').trigger('click'); await flushPromises()
|
||||
expect(dom().text()).toContain('公告正文'); expect(dom().text()).not.toContain('not displayed')
|
||||
await button('标为已读').trigger('click'); await flushPromises()
|
||||
expect(api.readNotices).toHaveBeenCalledExactlyOnceWith('7'); expect(api.read).not.toHaveBeenCalled()
|
||||
})
|
||||
@ -2,11 +2,11 @@ import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
test('notice popover offers a keyboard-accessible, permission-gated management entry even when empty', () => {
|
||||
test('message center offers a keyboard-accessible, permission-gated announcement management entry even when empty', () => {
|
||||
const source = readFileSync(new URL('../../src/layout/components/HeaderNotice/index.vue', import.meta.url), 'utf8')
|
||||
assert.match(source, /trigger="click"/)
|
||||
assert.match(source, /<button[^>]*aria-label="通知公告"/)
|
||||
assert.match(source, /v-if="\$can\(\['system:notice:list'\]\)" class="notice-footer"/)
|
||||
assert.match(source, /@click="openCenter"/)
|
||||
assert.match(source, /<button[^>]*aria-label="消息中心"/)
|
||||
assert.match(source, /v-if="proxy\?\.\$can\(\['system:notice:list'\]\)" class="center-footer"/)
|
||||
assert.match(source, />公告管理<\/el-button>/)
|
||||
assert.match(source, /if \(!proxy\.\$can\(\['system:notice:list'\]\)\) return/)
|
||||
assert.match(source, /router\.push\('\/system\/notice'\)/)
|
||||
|
||||
4
sql/projectdev/20261020_purchase_quote_clear.sql
Normal file
4
sql/projectdev/20261020_purchase_quote_clear.sql
Normal file
@ -0,0 +1,4 @@
|
||||
-- target-database: cmvr-project-dev
|
||||
-- Schema compatibility only: preserve all rows and existing prices.
|
||||
-- A cleared quotation is unknown, not a free item. The authoritative journal already supports NULL cost.
|
||||
ALTER TABLE stock_lot MODIFY COLUMN unit_cost DECIMAL(24,6) NULL DEFAULT NULL COMMENT '单位成本,NULL表示待报价';
|
||||
Loading…
Reference in New Issue
Block a user