feat(purchase): 实现采购PDF解析与验收确认功能
- 新增采购验收确认表及附件系统生成标识字段 - 实现采购PDF多页明细解析合并与数据校验逻辑 - 支持报价与实际金额一致的自动赋值指令处理 - 添加移动端到货照片补充上传及重试机制测试 - 补充后端PDF解析路由分发及事务处理单元测试
This commit is contained in:
parent
99cbd807a2
commit
b39fc01865
20
mobile-app/src/LegacyUpgrade.tsx
Normal file
20
mobile-app/src/LegacyUpgrade.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import React,{useEffect,useState} from 'react';
|
||||
import {ActivityIndicator,Linking,Pressable,ScrollView,Text,View} from 'react-native';
|
||||
import {SafeAreaProvider,SafeAreaView} from 'react-native-safe-area-context';
|
||||
import {getOfficialPackage,officialPackageUrl,type OfficialAppPackage} from './core/official-app-update';
|
||||
|
||||
/** Recovery entry for signed OTA channels whose APK predates the installer bridge. */
|
||||
export default function LegacyUpgrade(){
|
||||
const [release,setRelease]=useState<OfficialAppPackage|null>(null),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[busy,setBusy]=useState(false);
|
||||
useEffect(()=>{let alive=true;const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);setError('');setRelease(null);void getOfficialPackage(controller.signal).then(value=>{if(alive)setRelease(value);}).catch(()=>{if(alive)setError('暂时无法连接下载服务,请联网后重试。');}).finally(()=>clearTimeout(timer));return()=>{alive=false;controller.abort();clearTimeout(timer);};},[attempt]);
|
||||
async function open(){if(!release||busy)return;setBusy(true);setError('');try{await Linking.openURL(officialPackageUrl(release));}catch{setError('未能打开浏览器,请确认手机已安装浏览器后重试。');}finally{setBusy(false);}}
|
||||
return <SafeAreaProvider><SafeAreaView style={{flex:1,backgroundColor:'#f4f7fc'}}><ScrollView contentContainerStyle={{flexGrow:1,justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:420,alignSelf:'center',backgroundColor:'#fff',padding:24,borderRadius:20,gap:18}}>
|
||||
<Text allowFontScaling={false} style={{fontSize:13,color:'#3563d9'}}>设备科综合管理系统</Text><Text allowFontScaling={false} style={{fontSize:21,fontWeight:'700',color:'#182337'}}>升级至正式新版</Text>
|
||||
<Text allowFontScaling={false} style={{fontSize:14,lineHeight:23,color:'#526174'}}>当前旧版本需要通过浏览器下载安装包,再由手机系统完成安装。直接覆盖安装即可,无需卸载原应用。</Text>
|
||||
{release?<><Text allowFontScaling={false} style={{fontSize:14,fontWeight:'600',color:'#182337'}}>版本 {release.versionName} · {(release.size/1024**2).toFixed(1)} MB</Text>{release.notes.map((note,index)=><Text key={index} allowFontScaling={false} style={{fontSize:13,lineHeight:21,color:'#526174'}}>• {note}</Text>)}</>:!error?<ActivityIndicator color="#3563d9"/>:null}
|
||||
{!!error&&<Text accessibilityRole="alert" allowFontScaling={false} style={{fontSize:13,lineHeight:21,color:'#bc3345'}}>{error}</Text>}
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="浏览器下载安装" disabled={!release||busy} onPress={()=>void open()} style={{backgroundColor:!release||busy?'#aac0f3':'#3563d9',paddingVertical:14,borderRadius:10,alignItems:'center'}}><Text allowFontScaling={false} style={{color:'#fff',fontWeight:'600',fontSize:15}}>{busy?'正在打开…':'浏览器下载安装'}</Text></Pressable>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="重新检查" onPress={()=>setAttempt(n=>n+1)} style={{padding:10,alignItems:'center'}}><Text allowFontScaling={false} style={{color:'#3563d9',fontSize:13}}>重新检查</Text></Pressable>
|
||||
<Text allowFontScaling={false} style={{fontSize:12,lineHeight:20,color:'#7a8697'}}>下载后在浏览器中打开安装包;如有提示,允许浏览器安装应用。账号和原有数据无需重新录入。</Text>
|
||||
</View></ScrollView></SafeAreaView></SafeAreaProvider>;
|
||||
}
|
||||
17
mobile-app/src/core/official-app-update.ts
Normal file
17
mobile-app/src/core/official-app-update.ts
Normal file
@ -0,0 +1,17 @@
|
||||
export const officialAppOrigin='https://wms.svc.cmvr-iot.icu';
|
||||
export const productionAppSigner='96ab3e7afc5f60668693feec01140bcf13611f73ed9e76fa806bf9657f3d939b';
|
||||
export type OfficialAppPackage={environment:'prod';packageName:'cn.cmvr.wms';versionCode:number;versionName:string;sha256:string;size:number;signerSha256:string;downloadPath:string;notes:string[]};
|
||||
export function officialPackage(value:unknown,expected?:{versionCode:number;sha256:string;size:number}):OfficialAppPackage{
|
||||
const v=value as OfficialAppPackage;
|
||||
if(!v||v.environment!=='prod'||v.packageName!=='cn.cmvr.wms'||v.signerSha256!==productionAppSigner||!Number.isSafeInteger(v.versionCode)||v.versionCode<1||typeof v.versionName!=='string'||v.versionName.length>32||!/^[a-f0-9]{64}$/.test(v.sha256)||!Number.isSafeInteger(v.size)||v.size<1||v.size>250*1024*1024||v.downloadPath!==`/static/mobile/cmvr-wms-prod-v${v.versionCode}-${v.sha256}.apk`||!Array.isArray(v.notes)||v.notes.length>20||v.notes.some(n=>typeof n!=='string'||n.length>1000))throw Error('官方安装包信息无效,请稍后重试。');
|
||||
if(expected&&(v.versionCode!==expected.versionCode||v.sha256!==expected.sha256||v.size!==expected.size))throw Error('官方安装包版本已变化,请重新检查更新。');
|
||||
return v;
|
||||
}
|
||||
/** A public installer contains no account credentials. Android still verifies the APK. */
|
||||
export async function getOfficialPackage(signal:AbortSignal,expected?:{versionCode:number;sha256:string;size:number},transport:typeof fetch=fetch){
|
||||
const response=await transport(officialAppOrigin+'/static/mobile/app-upgrade.json?check='+Date.now(),{signal,redirect:'error',cache:'no-store'});
|
||||
if(!response.ok)throw Error('暂时无法获取官方安装包,请检查网络后重试。');
|
||||
const body=await response.text();if(body.length>8192)throw Error('官方安装包信息无效,请稍后重试。');
|
||||
return officialPackage(JSON.parse(body),expected);
|
||||
}
|
||||
export function officialPackageUrl(value:OfficialAppPackage){return officialAppOrigin+officialPackage(value).downloadPath;}
|
||||
32
mobile-app/tests/arrival-photo-supplements.test.mjs
Normal file
32
mobile-app/tests/arrival-photo-supplements.test.mjs
Normal file
@ -0,0 +1,32 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {createRequire} from 'node:module';
|
||||
import vm from 'node:vm';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
async function screen({supplemental=true,initial=[],fail=false}={}){
|
||||
const source=await readFile(new URL('../src/screens/ArrivalPhotos.tsx',import.meta.url),'utf8');
|
||||
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
|
||||
let photos=initial,cursor=0,refCursor=0,tree;const states=[],refs=[],calls=[];
|
||||
const react={...React,useState:value=>{const i=cursor++;if(!(i in states))states[i]=value;return[states[i],value=>states[i]=typeof value==='function'?value(states[i]):value];},useRef:value=>refs[refCursor++]??={current:value},useEffect:()=>{}};
|
||||
const picker={launchImageLibraryAsync:async()=>({canceled:false,assets:[{uri:'file:///test.png',mimeType:'image/png',fileSize:100}]}),requestCameraPermissionsAsync:async()=>({granted:true}),launchCameraAsync:async()=>({canceled:false,assets:[{uri:'file:///camera.png',mimeType:'image/png',fileSize:100}]})};
|
||||
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Image:'Image',Pressable:'Pressable',Platform:{OS:'android'}},'expo-image-picker':picker,'expo-crypto':{randomUUID:()=> '11111111-1111-4111-8111-111111111111'},'../ui':{Button:'Button',Note:'Note',Icon:'Icon',s:{}},'../files':{ProtectedImage:'ProtectedImage'}};
|
||||
const mod={exports:{}};vm.runInNewContext(compiled,{module:mod,exports:mod.exports,require:name=>imports[name]||require(name),AbortController,FormData,Blob});
|
||||
const api={request:async(path,options)=>{calls.push({path,...options});if(fail){fail=false;throw Error('temporary failure');}return {data:{id:options.body.get('uploadId'),name:'补录照片.png'}};}};
|
||||
function render(){cursor=0;refCursor=0;tree=mod.exports.ArrivalPhotos({api,requestId:10,arrivalId:100,readonly:true,supplemental,photos,onChange:value=>photos=value});}
|
||||
function find(type,prop,value,node=tree){if(!node||typeof node!=='object')return null;if(node.type===type&&node.props[prop]===value)return node;for(const child of React.Children.toArray(node.props?.children)){const found=find(type,prop,value,child);if(found)return found;}return null;}
|
||||
render();return {calls,get photos(){return photos;},render,button:title=>find('Button','title',title),remove:()=>find('Pressable','accessibilityRole','button')};
|
||||
}
|
||||
const settle=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
test('accepted legacy records can append a camera photo without deleting original evidence',async()=>{
|
||||
const original={id:'old',name:'原照片.png'},s=await screen({initial:[original]});assert.ok(s.button('拍照'));assert.equal(s.remove(),null);
|
||||
s.button('拍照').props.onPress();await settle();s.render();assert.equal(s.calls[0].path,'/warehouse/purchase/arrival/photos/record/100');assert.equal(s.photos.length,2);assert.equal(s.photos[0],original);assert.equal(s.remove(),null);
|
||||
});
|
||||
test('failed supplement retries keep one stable upload ID and do not append a second photo',async()=>{
|
||||
const s=await screen({fail:true});s.button('从相册选择').props.onPress();await settle();s.render();assert.equal(s.photos.length,1);assert.equal(s.photos[0].id,undefined);assert.ok(s.remove());
|
||||
s.button('重试上传').props.onPress();await settle();s.render();assert.equal(s.photos.length,1);assert.ok(s.photos[0].id);assert.equal(s.remove(),null);assert.equal(s.calls[0].body.get('uploadId'),s.calls[1].body.get('uploadId'));
|
||||
});
|
||||
test('read-only viewers have no upload controls; the nine-photo limit disables further supplements',async()=>{
|
||||
const readonly=await screen({supplemental:false});assert.equal(readonly.button('拍照'),null);assert.equal(readonly.button('从相册选择'),null);
|
||||
const full=await screen({initial:Array.from({length:9},(_,i)=>({id:String(i)}))});assert.equal(full.button('拍照').props.disabled,true);assert.equal(full.button('从相册选择').props.disabled,true);assert.equal(full.calls.length,0);
|
||||
});
|
||||
29
mobile-app/tests/official-app-update.test.mjs
Normal file
29
mobile-app/tests/official-app-update.test.mjs
Normal file
@ -0,0 +1,29 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {createRequire} from 'node:module';
|
||||
import vm from 'node:vm';
|
||||
import {getOfficialPackage,officialPackage,officialPackageUrl,productionAppSigner} from '../src/core/official-app-update.ts';
|
||||
import {packageInstallError,verifyInstalledPackage} from '../src/core/package-update.ts';
|
||||
const hash='a'.repeat(64),release={versionCode:7,sha256:hash,size:200};
|
||||
const descriptor={...release,versionName:'1.0.2',environment:'prod',packageName:'cn.cmvr.wms',signerSha256:productionAppSigner,downloadPath:`/static/mobile/cmvr-wms-prod-v7-${hash}.apk`,notes:['更新说明']};
|
||||
test('official recovery only accepts the matching production package, signer, hash and fixed HTTPS origin',async()=>{
|
||||
assert.equal(officialPackage(descriptor,release),descriptor);assert.equal(officialPackageUrl(descriptor),'https://wms.svc.cmvr-iot.icu'+descriptor.downloadPath);
|
||||
for(const patch of [{environment:'dev'},{packageName:'other.app'},{signerSha256:'b'.repeat(64)},{downloadPath:'https://evil.example/file.apk'},{versionCode:0},{size:0},{sha256:'wrong'},{notes:['x'.repeat(1001)]}])assert.throws(()=>officialPackage({...descriptor,...patch}),/无效/);
|
||||
assert.throws(()=>officialPackage(descriptor,{...release,sha256:'c'.repeat(64)}),/版本已变化/);
|
||||
let requested;await getOfficialPackage(new AbortController().signal,release,async(url,options)=>{requested={url,options};return new Response(JSON.stringify(descriptor));});assert.match(requested.url,/^https:\/\/wms\.svc\.cmvr-iot\.icu\//);assert.equal(requested.options.redirect,'error');assert.equal(requested.options.headers,undefined);
|
||||
});
|
||||
test('unavailable verifier is distinguished from a rejection; neither invokes a system install implicitly',async()=>{
|
||||
await assert.rejects(verifyInstalledPackage(undefined,'file:///cache/update.apk',7),/缺少安装检查组件/);
|
||||
await assert.rejects(verifyInstalledPackage({},'file:///cache/update.apk',7),/缺少安装检查组件/);
|
||||
await assert.rejects(verifyInstalledPackage({verify:async()=>false},'file:///cache/update.apk',7),/无法验证/);
|
||||
assert.doesNotMatch(packageInstallError(Error('INVALID_APK')),/签名或版本不匹配/);assert.match(packageInstallError(Error('当前旧版缺少安装检查组件')),/缺少安装检查组件/);
|
||||
});
|
||||
test('very old production runtimes select the recovery screen before loading any newer native module',()=>{
|
||||
const require=createRequire(import.meta.url),ts=require('typescript'),source=readFileSync(new URL('../index.ts',import.meta.url),'utf8'),code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,esModuleInterop:true}}).outputText;
|
||||
for(const [environment,legacyInstallerRecovery,expected] of [['prod',true,'./src/LegacyUpgrade'],['prod',false,'./src/App'],['dev',true,'./src/App']]){
|
||||
const imports=[],exports={};let registered;
|
||||
vm.runInNewContext(code,{exports,require:name=>{imports.push(name);if(name==='expo')return {registerRootComponent:value=>registered=value};if(name==='expo-constants')return {__esModule:true,default:{expoConfig:{extra:{environment,legacyInstallerRecovery}}}};if(name==='react-native')return {Platform:{OS:'android'}};assert.equal(name,expected);return {default:expected};}});
|
||||
assert.equal(registered,expected);assert.equal(imports.includes(expected==='./src/App'?'./src/LegacyUpgrade':'./src/App'),false);
|
||||
}
|
||||
});
|
||||
@ -0,0 +1,20 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.web.service.warehouse.PurchaseAcceptanceConfirmationService;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/warehouse/purchase/batch/{id}/acceptance-confirmation")
|
||||
public class PurchaseAcceptanceConfirmationController {
|
||||
private final PurchaseAcceptanceConfirmationService service;
|
||||
public PurchaseAcceptanceConfirmationController(PurchaseAcceptanceConfirmationService service){this.service=service;}
|
||||
@GetMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
public AjaxResult state(@PathVariable long id){return AjaxResult.success(service.state(id));}
|
||||
@PostMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@Log(title="确认采购验收资料",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult confirm(@PathVariable long id,@RequestBody PurchaseAcceptanceConfirmationService.Input input){return AjaxResult.success(service.confirm(id,input));}
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.web.service.warehouse.PurchaseLiveService;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/warehouse/purchase/sheet/{id}/live")
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
public class PurchaseLiveController {
|
||||
private final PurchaseLiveService live;
|
||||
public PurchaseLiveController(PurchaseLiveService live){this.live=live;}
|
||||
@GetMapping(produces="text/event-stream")
|
||||
public SseEmitter stream(@PathVariable long id,@RequestParam String clientId,HttpServletResponse response){
|
||||
// Authorization remains in the request header; never put bearer tokens into URLs.
|
||||
response.setHeader("Cache-Control","no-store");response.setHeader("X-Accel-Buffering","no");return live.open(id,clientId);
|
||||
}
|
||||
@PostMapping("/state") public AjaxResult state(@PathVariable long id,@RequestBody PurchaseLiveService.State state){return AjaxResult.success(live.state(id,state));}
|
||||
@DeleteMapping public AjaxResult leave(@PathVariable long id,@RequestParam String clientId){live.leave(id,clientId);return AjaxResult.success();}
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.*;
|
||||
|
||||
/** A source ledger is built before business matching; catalog guesses cannot replace PDF cells. */
|
||||
final class AssistantPurchasePdfRows {
|
||||
static final List<String> FIELDS=List.of("sourceName","sourceSpec","sourceBrand","sourceQuantity","sourceUnit","sourceAmount","finalUnitPrice");
|
||||
record PageNumbers(List<Integer> numbers) { PageNumbers { numbers=List.copyOf(numbers); } }
|
||||
record Page(Map<String,Object> file,Map<String,Object> proposal) { }
|
||||
/** Explicit equality on a new purchase copies each source unit price; never synthesizes a total. */
|
||||
static void applyActualPriceInstruction(Map<String,Object> proposal,List<Map<String,Object>> userMessages) {
|
||||
for(int i=userMessages.size()-1;i>=0;i--) {
|
||||
String text=Objects.toString(userMessages.get(i).get("content"),"").replaceAll("[\\s,,。;;::]","");
|
||||
if(!text.contains("报价")||!text.contains("实际"))continue;
|
||||
if(text.matches("(?s).*(?:不要|不用|不需要|不一致|不一样|不同|不相同|不是|取消|暂不|是否|怎么|如何|[??]).*"))return;
|
||||
String quoted="报价(?:单价|金额)?",actual="实际(?:单价|金额)?";
|
||||
boolean equal=text.matches("(?s).*(?:"+quoted+"(?:和|与|、|及)"+actual+"|"+actual+"(?:和|与|、|及)"+quoted+")(?:都|保持|设置为)?(?:一样|相同|一致|相等).*"
|
||||
)||text.matches("(?s).*"+actual+"(?:按|以|等于|取|使用|设为|改为)(?:当前|原|文件中的)?"+quoted+"(?:为准)?.*");
|
||||
if(equal)for(var row:AssistantConversationService.maps(proposal.get("rows")))if(row.get("finalUnitPrice")!=null)row.put("actualUnitPrice",row.get("finalUnitPrice"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
static Map<String,Object> merge(List<Page> pages,boolean quoteAllowed) {
|
||||
var result=new ArrayList<Map<String,Object>>();
|
||||
for(var page:pages){
|
||||
if("answer".equals(page.proposal().get("kind"))&&"本页无采购明细".equals(page.proposal().get("message"))){
|
||||
if(page.file().get("_pdfRowNumbers") instanceof PageNumbers hint&&!hint.numbers().isEmpty())throw incomplete();
|
||||
continue;
|
||||
}
|
||||
if(!"draft".equals(page.proposal().get("kind"))||!"purchase.create".equals(page.proposal().get("action")))throw incomplete();
|
||||
var rows=AssistantConversationService.maps(page.proposal().get("rows"));if(rows.isEmpty()){
|
||||
if(page.file().get("_pdfRowNumbers") instanceof PageNumbers hint&&!hint.numbers().isEmpty())throw incomplete();
|
||||
continue;
|
||||
}
|
||||
var ordered=new TreeMap<Integer,Map<String,Object>>();
|
||||
for(var row:rows){int n=number(row.get("_sourceRow"));if(n<1||n>1_000_000||ordered.put(n,row)!=null)throw incomplete();}
|
||||
if(page.file().get("_pdfRowNumbers") instanceof PageNumbers hint&&!ordered.keySet().equals(new TreeSet<>(hint.numbers())))throw incomplete();
|
||||
for(var entry:ordered.entrySet()){
|
||||
var raw=entry.getValue();var row=new LinkedHashMap<String,Object>();row.put("_sourceRow",result.size()+1);
|
||||
row.put("materialName",raw.get("sourceName"));row.put("materialParams",raw.get("sourceSpec"));row.put("materialBrand",raw.get("sourceBrand"));row.put("unit",raw.get("sourceUnit"));row.put("quantity",raw.get("sourceQuantity"));
|
||||
if(quoteAllowed)row.put("finalUnitPrice",raw.get("finalUnitPrice"));
|
||||
BigDecimal quantity=decimal(raw.get("sourceQuantity")),price=decimal(raw.get("finalUnitPrice")),amount=decimal(raw.get("sourceAmount"));
|
||||
if(quantity!=null&&quantity.signum()<=0||price!=null&&(price.signum()<0||price.stripTrailingZeros().scale()>6))throw incomplete();
|
||||
if(quantity!=null&&price!=null&&amount!=null&&quantity.multiply(price).setScale(2,RoundingMode.HALF_UP).subtract(amount).abs().compareTo(new BigDecimal("0.01"))>0)
|
||||
throw new ServiceException("PDF第"+page.file().get("pdfPage")+"页第"+entry.getKey()+"项的数量、含税单价与小计不一致,请重新识别核对;采购数据未修改");
|
||||
row.put("_sourceText",page.file().get("name")+",原表第"+entry.getKey()+"项:"+Objects.toString(raw.get("sourceName"),"待核对")+";规格:"+Objects.toString(raw.get("sourceSpec"),""));
|
||||
result.add(row);AssistantRowLimits.require("purchase.create",result.size());
|
||||
}
|
||||
}
|
||||
AssistantRowLimits.require("purchase.create",result.size());
|
||||
return Map.of("kind","draft","action","purchase.create","rows",result,"message","已按PDF原页整理采购草稿,尚未创建采购。请补充项目、费用类别并核对物品、数量、单位和含税单价;合计、税额及营业执照不作为采购物品。");
|
||||
}
|
||||
private static int number(Object value){try{return new BigDecimal(Objects.toString(value,"")).intValueExact();}catch(Exception error){throw incomplete();}}
|
||||
private static BigDecimal decimal(Object value){if(value==null||value.toString().isBlank())return null;try{return new BigDecimal(value.toString());}catch(Exception error){throw incomplete();}}
|
||||
private static ServiceException incomplete(){return new ServiceException("PDF原文行号或明细识别不完整,尚未生成确认单。请重新识别,系统不会遗漏或截断采购项");}
|
||||
private AssistantPurchasePdfRows() { }
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
final class AssistantRowLimits {
|
||||
static int maximum(String action) { return java.util.Set.of("purchase.create","purchase.update","purchase.correctPrice").contains(action==null?"":action) ? 200 : 100; }
|
||||
static void require(String action, int size) {
|
||||
int maximum=maximum(action);
|
||||
if(size<1||size>maximum)throw new com.ruoyi.common.exception.ServiceException("一次操作须包含 1 至 "+maximum+" 行,请拆分后处理;不会截断数据");
|
||||
}
|
||||
private AssistantRowLimits() { }
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import com.ruoyi.warehouse.util.PurchaseDataAccess;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.*;
|
||||
|
||||
/** Formal signed-document acceptance is separate from physical arrival inspection.
|
||||
* Append-only confirmations record the actual confirmation instant. Inventory chronology is untouched.
|
||||
*/
|
||||
@Service
|
||||
public class PurchaseAcceptanceConfirmationService {
|
||||
private final JdbcTemplate db;private final PurchaseAcceptanceReportService reports;private final IPurchaseOperationLogService logs;private final ObjectMapper json;
|
||||
public PurchaseAcceptanceConfirmationService(JdbcTemplate db,PurchaseAcceptanceReportService reports,IPurchaseOperationLogService logs,ObjectMapper json){this.db=db;this.reports=reports;this.logs=logs;this.json=json;}
|
||||
public record Input(String attachmentId,String version,String requestKey,boolean acknowledged){}
|
||||
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
|
||||
public Map<String,Object> state(long batch){return stateOnce(batch);}
|
||||
private Map<String,Object> stateOnce(long batch){
|
||||
var owners=db.queryForList("select create_by from purchase_batch where id=?",batch);if(owners.isEmpty())throw new ServiceException("采购批次不存在");
|
||||
var ready=reports.preview(batch);var result=new LinkedHashMap<String,Object>();
|
||||
result.put("ready",ready.get("ready"));result.put("issues",ready.get("issues"));
|
||||
result.put("canConfirm",PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null));
|
||||
String hash=snapshot(batch);result.put("version",hash);
|
||||
var history=db.queryForList("select id,attachment_id attachmentId,snapshot_hash snapshotHash,confirmed_by confirmedBy,confirmed_time confirmedTime from purchase_acceptance_confirmation where batch_id=? order by id desc limit 1",batch);
|
||||
if(history.isEmpty()){result.put("latest",Map.of());result.put("current",false);}
|
||||
else{var latest=new LinkedHashMap<>(history.get(0));result.put("current",hash.equals(latest.remove("snapshotHash")));result.put("latest",latest);}
|
||||
return result;
|
||||
}
|
||||
private static boolean isGenerated(Object value){return Boolean.TRUE.equals(value)||value instanceof Number number&&number.intValue()!=0;}
|
||||
private String snapshot(long batch){
|
||||
// Deliberately exclude display permissions, user nicknames and the confirmation history itself.
|
||||
var source=List.of(
|
||||
db.queryForList("select id,supplier_id,expense_category_id,batch_name from purchase_batch where id=?",batch),
|
||||
db.queryForList("select id,product_id,project_id,material_name,material_brand,material_params,unit,quantity,purchase_status from purchase_request where purchase_batch_id=? and del_flag='0' order by id",batch),
|
||||
db.queryForList("select a.id,a.purchase_request_id,cast(a.acceptance_status as signed) status,a.arrival_quantity,a.defective_quantity,a.returned_quantity,a.accepted_time from purchase_arrival a join purchase_request r on r.id=a.purchase_request_id where r.purchase_batch_id=? and r.del_flag='0' order by a.id",batch),
|
||||
db.queryForList("select g.id,g.document_kind,g.document_no,g.version from purchase_document_group g where g.target_type='batch' and g.target_id=? and g.document_kind in ('REQUEST','QUOTE','CONTRACT','ACCEPTANCE') order by g.id",batch),
|
||||
db.queryForList("select a.id,a.group_id,a.sha256 from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where g.target_type='batch' and g.target_id=? and g.document_kind in ('REQUEST','QUOTE','CONTRACT','ACCEPTANCE') and a.deleted=0 order by a.id",batch));
|
||||
try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsString(source).getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}
|
||||
}
|
||||
@Transactional(isolation=Isolation.READ_COMMITTED)
|
||||
public Map<String,Object> confirm(long batch,Input input){
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:edit")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有采购验收权限",403);
|
||||
if(input==null||!input.acknowledged()||input.requestKey()==null||!input.requestKey().matches("[A-Za-z0-9_-]{16,100}")||input.attachmentId()==null||!input.attachmentId().matches("[0-9a-f-]{36}"))throw new ServiceException("请先核对并选择已签字盖章的验收PDF");
|
||||
var owners=db.queryForList("select create_by from purchase_batch where id=? for update",batch);if(owners.isEmpty())throw new ServiceException("采购批次不存在");
|
||||
if(!PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以确认验收",403);
|
||||
var rows=db.queryForList("select id,request_no from purchase_request where purchase_batch_id=? and del_flag='0' order by id for update",batch);
|
||||
var files=db.queryForList("select a.original_name,a.server_generated from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=? and a.deleted=0 and a.content_type='application/pdf' and g.target_type='batch' and g.target_id=? and g.document_kind='ACCEPTANCE'",input.attachmentId(),batch);
|
||||
if(files.isEmpty()||isGenerated(files.get(0).get("server_generated")))throw new ServiceException("请选择重新上传的签章版PDF,不能使用系统生成的待签章文件");
|
||||
var state=stateOnce(batch);if(!Objects.equals(state.get("version"),input.version()))throw new ServiceException("采购数据或资料已变化,请刷新资料后重新核对");
|
||||
if(!Boolean.TRUE.equals(state.get("ready")))throw new ServiceException("请先补全采购申请、合同并完成整批到货验收,再确认签章资料");
|
||||
var prior=db.queryForList("select batch_id,attachment_id,owner_id,snapshot_hash from purchase_acceptance_confirmation where request_key=?",input.requestKey());
|
||||
if(!prior.isEmpty()){
|
||||
var p=prior.get(0);if(((Number)p.get("batch_id")).longValue()!=batch||((Number)p.get("owner_id")).longValue()!=SecurityUtils.getUserId()||!Objects.equals(p.get("attachment_id"),input.attachmentId())||!Objects.equals(p.get("snapshot_hash"),input.version()))throw new ServiceException("本次确认标识已被使用,请刷新后核对");
|
||||
return state;
|
||||
}
|
||||
var latest=(Map<?,?>)state.get("latest");if(Boolean.TRUE.equals(state.get("current"))&&Objects.equals(latest.get("attachmentId"),input.attachmentId()))return state;
|
||||
db.update("insert into purchase_acceptance_confirmation(batch_id,attachment_id,snapshot_hash,request_key,owner_id,confirmed_by) values(?,?,?,?,?,?)",batch,input.attachmentId(),input.version(),input.requestKey(),SecurityUtils.getUserId(),SecurityUtils.getUsername());
|
||||
for(var row:rows)logs.record(((Number)row.get("id")).longValue(),Objects.toString(row.get("request_no"),""),"DOCUMENT_ACCEPTANCE","确认验收资料","批次:"+batch+";签章附件:"+input.attachmentId()+";入出库业务日期及创建时间保持原记录");
|
||||
return stateOnce(batch);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.listener.*;
|
||||
|
||||
@Configuration
|
||||
public class PurchaseLiveConfiguration {
|
||||
@Bean("purchaseLiveRedis") public StringRedisTemplate redis(RedisConnectionFactory factory){return new StringRedisTemplate(factory);}
|
||||
@Bean public RedisMessageListenerContainer purchaseLiveListener(RedisConnectionFactory factory,PurchaseLiveService service,PurchaseLiveStore store){
|
||||
var container=new RedisMessageListenerContainer();container.setConnectionFactory(factory);container.addMessageListener(service,new ChannelTopic(store.channel()));return container;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,133 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import com.ruoyi.common.constant.CacheConstants;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.PurchasePermissions;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.util.PurchaseDataAccess;
|
||||
import jakarta.annotation.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import org.springframework.data.redis.connection.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.event.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
@Service
|
||||
public class PurchaseLiveService implements MessageListener {
|
||||
private static final org.slf4j.Logger LOG=org.slf4j.LoggerFactory.getLogger(PurchaseLiveService.class);
|
||||
static final Set<String> FIELDS=Set.of("materialName","materialBrand","materialParams","productId","unit","category","quantity","actualUnitPrice","finalUnitPrice","purchaseLink","remark","projectId","productionTaskId","purchasePurpose","loanId","expenseCategoryId");
|
||||
private static final Set<String> IDENTITY=Set.of("materialName","materialBrand","materialParams","productId","unit","category");
|
||||
private final PurchaseLiveStore store;private final RedisCache tokens;private final JdbcTemplate db;private final PurchaseRequestMapper requests;
|
||||
private final ConcurrentMap<String,Connection> connections=new ConcurrentHashMap<>();
|
||||
private final Set<Long> changedBatches=ConcurrentHashMap.newKeySet(),changedRequests=ConcurrentHashMap.newKeySet();
|
||||
private final ScheduledExecutorService clock=Executors.newSingleThreadScheduledExecutor(r->{var t=new Thread(r,"purchase-live-clock");t.setDaemon(true);return t;});
|
||||
private final ExecutorService senders=new ThreadPoolExecutor(2,4,30,TimeUnit.SECONDS,new ArrayBlockingQueue<>(512),r->{var t=new Thread(r,"purchase-live-stream");t.setDaemon(true);return t;},new ThreadPoolExecutor.AbortPolicy());
|
||||
public PurchaseLiveService(PurchaseLiveStore store,RedisCache tokens,JdbcTemplate db,PurchaseRequestMapper requests){this.store=store;this.tokens=tokens;this.db=db;this.requests=requests;}
|
||||
@PostConstruct public void start(){clock.scheduleWithFixedDelay(this::flushChanges,100,150,TimeUnit.MILLISECONDS);clock.scheduleWithFixedDelay(this::heartbeat,10,10,TimeUnit.SECONDS);}
|
||||
@PreDestroy public void stop(){connections.values().forEach(this::close);clock.shutdownNow();senders.shutdownNow();}
|
||||
public record State(String clientId,long sequence,Long rowId,String rowKey,String field,boolean editing,Object value,boolean typing){}
|
||||
private static final class Connection {
|
||||
final long batch,userId;final String client,token;final SseEmitter emitter;volatile boolean quote;final Queue<Outbound> pending=new ArrayDeque<>();boolean draining;
|
||||
Connection(long batch,String client,LoginUser user,boolean quote){this.batch=batch;this.client=client;this.userId=user.getUserId();this.token=user.getToken();this.quote=quote;this.emitter=new SseEmitter(0L);}
|
||||
}
|
||||
private record Outbound(String event,Object data){}
|
||||
static void client(String value){if(value==null||!value.matches("[A-Za-z0-9_-]{16,100}"))throw new ServiceException("协同窗口标识无效");}
|
||||
private void room(long batch){if(batch<=0||db.queryForList("select id from purchase_batch where id=?",batch).isEmpty())throw new ServiceException("请先保存采购批次,再使用实时协同");}
|
||||
private LoginUser user(){var user=SecurityUtils.getLoginUser();if(user==null||user.getToken()==null)throw new ServiceException("请重新登录",401);return user;}
|
||||
private boolean quotes(long id){if(id==1)return true;return Boolean.TRUE.equals(db.queryForObject("select exists(select 1 from sys_user_role ur join sys_role r on r.role_id=ur.role_id where ur.user_id=? and r.role_key='purchase_manager' and r.status='0' and r.del_flag='0')",Boolean.class,id));}
|
||||
public SseEmitter open(long batch,String client){
|
||||
client(client);room(batch);var user=user();if(connections.size()>=300)throw new ServiceException("实时连接较多,请稍后重试");
|
||||
var members=store.members(batch);if(members.size()>=60&&members.stream().noneMatch(m->client.equals(m.get("clientId"))))throw new ServiceException("本批次在线窗口较多,请关闭不用的窗口后重试");
|
||||
var identity=new LinkedHashMap<String,Object>();identity.put("clientId",client);identity.put("userId",user.getUserId());identity.put("name",user.getUser().getNickName());identity.put("token",user.getToken());identity.put("sequence",0);identity.put("rowId",null);identity.put("rowKey",null);identity.put("field",null);identity.put("editing",false);identity.put("lease","");identity.put("draft",null);
|
||||
store.join(batch,identity);var next=new Connection(batch,client,user,quotes(user.getUserId()));var previous=connections.put(client,next);if(previous!=null)previous.emitter.complete();
|
||||
next.emitter.onCompletion(()->close(next));next.emitter.onTimeout(()->close(next));next.emitter.onError(error->close(next));
|
||||
send(next,"hello",Map.of("clientId",client,"peers",visibleMembers(batch,next.quote)));publishMembers(batch);return next.emitter;
|
||||
}
|
||||
public Map<String,Object> state(long batch,State input){
|
||||
client(input.clientId());if(input.sequence()<=0||input.sequence()>9007199254740990L)throw new ServiceException("协同消息序号无效");
|
||||
var user=user();var old=owned(batch,input.clientId(),user);var next=new LinkedHashMap<>(old);next.put("sequence",input.sequence());next.put("editing",input.editing());next.put("lease","");
|
||||
String field=input.field();Long rowId=input.rowId();String rowKey=input.rowKey();
|
||||
if(field!=null&&!FIELDS.contains(field)&&!"batch".equals(field))throw new ServiceException("此字段不支持实时编辑");
|
||||
if(rowKey!=null&&!rowKey.matches("[A-Za-z0-9_-]{1,100}"))throw new ServiceException("新增行标识无效");
|
||||
if(input.editing()){
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:edit")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有采购编辑权限",403);
|
||||
if(field==null)throw new ServiceException("请选择编辑的单元格");
|
||||
if("finalUnitPrice".equals(field)&&!quotes(user.getUserId()))throw new ServiceException("报价金额仅采购管理员可维护",403);
|
||||
if("batch".equals(field)){
|
||||
var owners=db.queryForList("select create_by from purchase_batch where id=?",batch);if(owners.isEmpty()||!PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以维护批次信息",403);
|
||||
rowId=null;rowKey=null;next.put("rowName","批次信息");
|
||||
}else if(rowId!=null){
|
||||
var row=requests.selectPurchaseRequestById(rowId,null);if(row==null||!Objects.equals(row.getPurchaseBatchId(),batch))throw new ServiceException("采购明细已删除或转移,请刷新");PurchaseDataAccess.require(row);
|
||||
if(!"actualUnitPrice".equals(field)&&(Boolean.TRUE.equals(row.getHistorical())||Integer.valueOf(5).equals(row.getPurchaseStatus())))throw new ServiceException("该明细当前只支持实际金额维护");
|
||||
next.put("rowName",row.getMaterialName());
|
||||
}else{
|
||||
if(rowKey==null||!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:add")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有新增采购明细权限",403);
|
||||
next.put("rowName","新增明细");
|
||||
}
|
||||
String target="batch".equals(field)?"header":rowId==null?"new-"+input.clientId()+"-"+rowKey:"row-"+rowId;
|
||||
next.put("lease",store.lease(batch,target,group(field)));
|
||||
}
|
||||
next.put("rowId",rowId);next.put("rowKey",rowKey);next.put("field",field);
|
||||
if(input.typing()){
|
||||
if(!input.editing()||field==null||"batch".equals(field))throw new ServiceException("请先取得单元格的编辑权限");
|
||||
Object value=input.value();if(value!=null&&!(value instanceof String)&&!(value instanceof Number))throw new ServiceException("协同内容只能是文字或数字");
|
||||
if(value!=null&&value.toString().length()>("remark".equals(field)?500:1000))throw new ServiceException("协同内容过长");
|
||||
var draft=new LinkedHashMap<String,Object>();draft.put("field",field);draft.put("value",value);next.put("draft",draft);
|
||||
}else next.put("draft",null);
|
||||
String occupied=store.write(batch,next);
|
||||
if("__stale__".equals(occupied))return Map.of("ok",true,"sequence",input.sequence());
|
||||
if(occupied!=null){var peer=store.get(batch,occupied);throw new ServiceException((peer==null?"其他人":Objects.toString(peer.get("name"),"其他人"))+"正在编辑此单元格的关联内容,请稍后再试",409);}
|
||||
store.publish(Map.of("batch",batch,"type","member","member",publicMember(next,true)));return Map.of("ok",true,"sequence",input.sequence());
|
||||
}
|
||||
@org.springframework.context.event.EventListener
|
||||
public void check(PurchaseSheetEditingCheck check){
|
||||
String client=null;try{client=com.ruoyi.common.utils.ServletUtils.getRequest().getHeader("X-Purchase-Live-Client");}catch(Exception ignored){}
|
||||
if(client!=null){client(client);owned(check.batchId(),client,user());}
|
||||
for(var cell:check.cells()){String target=cell.rowId()==null?"header":"row-"+cell.rowId();String owner=store.holder(check.batchId(),target,group(cell.field()));if(owner!=null&&!owner.equals(client)){var peer=store.get(check.batchId(),owner);throw new ServiceException((peer==null?"其他人":Objects.toString(peer.get("name"),"其他人"))+"正在编辑相关单元格,内容已保留,请稍后再保存",409);}}
|
||||
}
|
||||
static String group(String field){if(IDENTITY.contains(field))return "identity";if(Set.of("projectId","productionTaskId").contains(field))return "project";if(Set.of("purchasePurpose","loanId").contains(field))return "purpose";return field;}
|
||||
private Map<String,Object> owned(long batch,String client,LoginUser user){var old=store.get(batch,client);if(old==null)throw new ServiceException("实时连接已过期,正在重连",409);if(((Number)old.get("userId")).longValue()!=user.getUserId()||!Objects.equals(old.get("token"),user.getToken()))throw new ServiceException("协同窗口不属于当前登录",403);return old;}
|
||||
public void leave(long batch,String client){client(client);var user=user();owned(batch,client,user);var connection=connections.get(client);if(connection!=null)close(connection);else{store.leave(batch,client,user.getToken());publishMembers(batch);}}
|
||||
public void saved(long batch,String client,long sequence){
|
||||
if(client!=null){client(client);var user=user();owned(batch,client,user);store.clearDraft(batch,client,user.getToken(),sequence);publishMembers(batch);}changedBatches.add(batch);
|
||||
}
|
||||
@TransactionalEventListener(phase=TransactionPhase.AFTER_COMMIT,fallbackExecution=true)
|
||||
public void changed(PurchaseSheetChanged event){if(event.batchId()!=null)changedBatches.add(event.batchId());else if(event.requestId()!=null)changedRequests.add(event.requestId());}
|
||||
private void flushChanges(){try{
|
||||
var ids=new ArrayList<Long>();for(Long id:changedRequests)if(changedRequests.remove(id)){ids.add(id);if(ids.size()==1000)break;}
|
||||
if(!ids.isEmpty())for(var row:db.queryForList("select distinct purchase_batch_id batchId from purchase_request where purchase_batch_id is not null and id in ("+String.join(",",Collections.nCopies(ids.size(),"?"))+")",ids.toArray()))changedBatches.add(((Number)row.get("batchId")).longValue());
|
||||
for(Long batch:new HashSet<>(changedBatches))if(changedBatches.remove(batch))store.publish(Map.of("batch",batch,"type","saved"));
|
||||
}catch(Exception error){LOG.warn("Purchase live refresh will retry ({})",error.getClass().getSimpleName());}}
|
||||
static Map<String,Object> publicMember(Map<String,Object> raw,boolean quote){
|
||||
var out=new LinkedHashMap<String,Object>();for(String key:List.of("clientId","userId","name","rowId","rowKey","rowName","field","editing","draft","sequence"))out.put(key,raw.get(key));
|
||||
if(!quote&&"finalUnitPrice".equals(out.get("field"))){out.put("rowId",null);out.put("rowKey",null);out.put("rowName",null);out.put("field",null);out.put("editing",false);out.put("draft",null);}return out;
|
||||
}
|
||||
private List<Map<String,Object>> visibleMembers(long batch,boolean quote){return store.members(batch).stream().map(m->publicMember(m,quote)).toList();}
|
||||
private static boolean canRead(LoginUser login){return login!=null&&(PurchasePermissions.grants(login,"warehouse:purchase:list")||SecurityUtils.hasPermi(login.getPermissions(),"warehouse:purchase:list")||SecurityUtils.hasPermi(login.getPermissions(),"warehouse:purchase:manage"));}
|
||||
private void publishMembers(long batch){store.publish(Map.of("batch",batch,"type","members"));}
|
||||
@Override public void onMessage(Message message,byte[] pattern){
|
||||
try{var event=store.decode(new String(message.getBody(),StandardCharsets.UTF_8));long batch=((Number)event.get("batch")).longValue();String type=Objects.toString(event.get("type"),"");
|
||||
if(!Set.of("saved","members","member").contains(type))return;
|
||||
for(var c:connections.values())if(c.batch==batch){LoginUser active=tokens.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY+c.token);if(!canRead(active)){close(c);continue;}if("members".equals(type)||"member".equals(type)&&"finalUnitPrice".equals(((Map<?,?>)event.get("member")).get("field")))c.quote=quotes(c.userId);Object data="members".equals(type)?Map.of("peers",visibleMembers(batch,c.quote)):"member".equals(type)?publicMember((Map<String,Object>)event.get("member"),c.quote):Map.of("batchId",batch);send(c,type,data);}
|
||||
}catch(Exception error){LOG.warn("Purchase live event rejected ({})",error.getClass().getSimpleName());}
|
||||
}
|
||||
private void heartbeat(){for(var c:connections.values())try{
|
||||
LoginUser login=tokens.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY+c.token);
|
||||
if(!canRead(login)||store.get(c.batch,c.client)==null){close(c);continue;}
|
||||
c.quote=quotes(c.userId);send(c,"members",Map.of("peers",visibleMembers(c.batch,c.quote)));
|
||||
}catch(Exception error){close(c);}}
|
||||
private void send(Connection c,String event,Object data){
|
||||
synchronized(c){if(c.pending.size()>=128){close(c);return;}c.pending.add(new Outbound(event,data));if(c.draining)return;c.draining=true;}
|
||||
try{senders.execute(()->{while(true){Outbound next;synchronized(c){next=c.pending.poll();if(next==null){c.draining=false;return;}}
|
||||
try{c.emitter.send(SseEmitter.event().name(next.event()).data(next.data()));}catch(Exception error){synchronized(c){c.pending.clear();c.draining=false;}close(c);return;}
|
||||
}});}catch(RejectedExecutionException overloaded){synchronized(c){c.pending.clear();c.draining=false;}close(c);}
|
||||
}
|
||||
private void close(Connection c){if(!connections.remove(c.client,c))return;try{store.leave(c.batch,c.client,c.token);publishMembers(c.batch);}catch(Exception ignored){}try{c.emitter.complete();}catch(Exception ignored){}}
|
||||
}
|
||||
@ -0,0 +1,79 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import org.springframework.beans.factory.annotation.*;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Ephemeral, environment-isolated presence and atomic cell leases. No business values are persisted here. */
|
||||
@Component
|
||||
public class PurchaseLiveStore {
|
||||
public static final long MEMBER_MS=75000,LEASE_MS=30000;
|
||||
private final StringRedisTemplate redis;private final ObjectMapper json;private final String prefix;
|
||||
public PurchaseLiveStore(@Qualifier("purchaseLiveRedis") StringRedisTemplate redis,ObjectMapper json,@Value("${ruoyi.cacheNamespace:cmvr-project-dev}") String namespace){
|
||||
if(!namespace.matches("[A-Za-z0-9_-]{1,80}"))throw new IllegalArgumentException("Invalid cache namespace");
|
||||
this.redis=redis;this.json=json;this.prefix=namespace+":purchase-live:";
|
||||
}
|
||||
public String channel(){return prefix+"events";}
|
||||
private String room(long batch){return prefix+"{"+batch+"}:";}
|
||||
private String member(long batch,String client){return room(batch)+"member:"+client;}
|
||||
private String index(long batch){return room(batch)+"members";}
|
||||
public String holder(long batch,String target,String group){return redis.opsForValue().get(lease(batch,target,group));}
|
||||
public String lease(long batch,String target,String group){return room(batch)+"lease:"+target+":"+group;}
|
||||
public Map<String,Object> get(long batch,String client){String value=redis.opsForValue().get(member(batch,client));return value==null?null:decode(value);}
|
||||
public void join(long batch,Map<String,Object> identity){
|
||||
String client=identity.get("clientId").toString(),key=member(batch,client);var old=get(batch,client);
|
||||
if(old!=null&&(((Number)old.get("userId")).longValue()!=((Number)identity.get("userId")).longValue()||!Objects.equals(old.get("token"),identity.get("token"))))throw new ServiceException("协同窗口标识不属于当前登录,请重新打开页面",403);
|
||||
if(old==null){if(!Boolean.TRUE.equals(redis.opsForValue().setIfAbsent(key,encode(identity),Duration.ofMillis(MEMBER_MS)))){join(batch,identity);return;}}
|
||||
else redis.expire(key,Duration.ofMillis(MEMBER_MS));
|
||||
redis.opsForZSet().add(index(batch),client,System.currentTimeMillis());redis.expire(index(batch),Duration.ofHours(1));
|
||||
}
|
||||
private static final DefaultRedisScript<List> WRITE=new DefaultRedisScript<>("""
|
||||
local raw=redis.call('get',KEYS[1]);if not raw then return {-2,''} end
|
||||
local old=cjson.decode(raw);local next=cjson.decode(ARGV[1])
|
||||
if old.userId~=next.userId or old.token~=next.token then return {-3,''} end
|
||||
if next.sequence<=old.sequence then return {2,''} end
|
||||
if next.lease~='' then
|
||||
local owner=redis.call('get',next.lease)
|
||||
if owner and owner~=next.clientId then return {0,owner} end
|
||||
redis.call('psetex',next.lease,ARGV[3],next.clientId)
|
||||
end
|
||||
if old.lease and old.lease~='' and old.lease~=next.lease and redis.call('get',old.lease)==next.clientId then redis.call('del',old.lease) end
|
||||
redis.call('psetex',KEYS[1],ARGV[2],ARGV[1]);redis.call('zadd',KEYS[2],ARGV[4],next.clientId)
|
||||
return {1,''}
|
||||
""",List.class);
|
||||
/** Returns the other client's ID if its lease already owns this related field group. */
|
||||
public String write(long batch,Map<String,Object> state){
|
||||
var out=redis.execute(WRITE,List.of(member(batch,state.get("clientId").toString()),index(batch)),encode(state),String.valueOf(MEMBER_MS),String.valueOf(LEASE_MS),String.valueOf(System.currentTimeMillis()));
|
||||
if(out==null)throw new ServiceException("实时协同暂时不可用,内容仍保留在本机");
|
||||
long status=((Number)out.get(0)).longValue();if(status==-2)throw new ServiceException("协同连接已过期,请等待重连",409);if(status==-3)throw new ServiceException("协同窗口不属于当前登录",403);
|
||||
return status==2?"__stale__":status==0?out.get(1).toString():null;
|
||||
}
|
||||
private static final DefaultRedisScript<Long> REMOVE=new DefaultRedisScript<>("""
|
||||
local raw=redis.call('get',KEYS[1]);if not raw then return 0 end
|
||||
local member=cjson.decode(raw);if member.token~=ARGV[1] then return 0 end
|
||||
if member.lease and member.lease~='' and redis.call('get',member.lease)==member.clientId then redis.call('del',member.lease) end
|
||||
redis.call('del',KEYS[1]);redis.call('zrem',KEYS[2],member.clientId);return 1
|
||||
""",Long.class);
|
||||
public void leave(long batch,String client,String token){redis.execute(REMOVE,List.of(member(batch,client),index(batch)),token);}
|
||||
private static final DefaultRedisScript<Long> CLEAR=new DefaultRedisScript<>("""
|
||||
local raw=redis.call('get',KEYS[1]);if not raw then return 0 end
|
||||
local member=cjson.decode(raw)
|
||||
if member.token~=ARGV[1] or member.sequence>tonumber(ARGV[2]) then return 0 end
|
||||
member.draft=cjson.null;redis.call('psetex',KEYS[1],ARGV[3],cjson.encode(member));return 1
|
||||
""",Long.class);
|
||||
public void clearDraft(long batch,String client,String token,long sequence){redis.execute(CLEAR,List.of(member(batch,client)),token,String.valueOf(sequence),String.valueOf(MEMBER_MS));}
|
||||
public List<Map<String,Object>> members(long batch){
|
||||
redis.opsForZSet().removeRangeByScore(index(batch),0,System.currentTimeMillis()-MEMBER_MS);
|
||||
var ids=redis.opsForZSet().range(index(batch),0,79);if(ids==null)return List.of();var out=new ArrayList<Map<String,Object>>();
|
||||
for(String id:ids){var member=get(batch,id);if(member!=null)out.add(member);}return out;
|
||||
}
|
||||
public void publish(Map<String,Object> event){redis.convertAndSend(channel(),encode(event));}
|
||||
public String encode(Object value){try{return json.writeValueAsString(value);}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
public Map<String,Object> decode(String value){try{return json.readValue(value,new TypeReference<LinkedHashMap<String,Object>>(){});}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import com.ruoyi.common.core.domain.entity.*;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.domain.PurchaseBatch;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseBatchMapper;
|
||||
import com.ruoyi.warehouse.service.impl.*;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.mapping.Environment;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Real mapper SQL against isolated tables: removing an empty batch never deletes detail or audit history. */
|
||||
class PurchaseEmptyBatchDeletionTest {
|
||||
JdbcTemplate db;SqlSession session;PurchaseBatchMapper mapper;PurchaseBatchServiceImpl service;
|
||||
@BeforeEach void setup() throws Exception {
|
||||
var source=new JdbcDataSource();source.setURL("jdbc:h2:mem:empty_batch_"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1");db=new JdbcTemplate(source);
|
||||
db.execute("create table purchase_batch(id bigint primary key,batch_no varchar(64))");
|
||||
db.execute("create table purchase_request(id bigint primary key,purchase_batch_id bigint,purchase_batch_no varchar(64),request_no varchar(64),del_flag char(1))");
|
||||
db.execute("create table purchase_operation_log(id bigint primary key,purchase_request_id bigint,operation_detail varchar(100))");
|
||||
db.execute("create table purchase_document_group(id bigint primary key,target_type varchar(20),target_id bigint,document_no varchar(64))");
|
||||
db.execute("create table purchase_document_attachment(id bigint primary key,group_id bigint,deleted int)");
|
||||
db.update("insert into purchase_batch values(328,'CG2026110002'),(329,'CG2026110003')");
|
||||
for(int i=1;i<=11;i++){db.update("insert into purchase_request values(?,328,'CG2026110002',?,'2')",i,"PR-"+i);db.update("insert into purchase_operation_log values(?,?,?)",i,i,"删除采购明细历史-"+i);}
|
||||
db.update("insert into purchase_request values(20,329,'CG2026110003','PR-20','0')");
|
||||
var configuration=new Configuration();configuration.getTypeAliasRegistry().registerAlias("PurchaseBatch",PurchaseBatch.class);configuration.setEnvironment(new Environment("empty-batch",new JdbcTransactionFactory(),source));
|
||||
String resource="mapper/warehouse/PurchaseBatchMapper.xml";
|
||||
try(var input=getClass().getClassLoader().getResourceAsStream(resource)){new XMLMapperBuilder(input,configuration,resource,configuration.getSqlFragments()).parse();}
|
||||
session=new SqlSessionFactoryBuilder().build(configuration).openSession(true);mapper=session.getMapper(PurchaseBatchMapper.class);
|
||||
var batch=new PurchaseBatch();batch.setId(328L);batch.setBatchNo("CG2026110002");batch.setCreateBy("other-person");
|
||||
var operations=mock(PurchaseBatchMapper.class);when(operations.selectPurchaseBatchForUpdate(328L)).thenReturn(batch);when(operations.selectPurchaseBatchById(328L)).thenReturn(batch);
|
||||
when(operations.countRequestsByBatchId(328L)).thenAnswer(c->mapper.countRequestsByBatchId(328L));when(operations.countBatchDocuments(328L)).thenAnswer(c->mapper.countBatchDocuments(328L));when(operations.deletePurchaseBatchById(328L)).thenAnswer(c->mapper.deletePurchaseBatchById(328L));
|
||||
service=new PurchaseBatchServiceImpl();ReflectionTestUtils.setField(service,"purchaseBatchMapper",operations);ReflectionTestUtils.setField(service,"catalogWriteLock",mock(CatalogWriteLock.class));
|
||||
var role=new SysRole();role.setRoleKey("purchase_manager");role.setStatus("0");role.setDelFlag("0");var user=new SysUser();user.setUserId(22L);user.setUserName("manager");user.setRoles(List.of(role));
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(22L,1L,user,Set.of()),null));
|
||||
}
|
||||
@AfterEach void cleanup(){if(session!=null)session.close();SecurityContextHolder.clearContext();}
|
||||
|
||||
@Test void elevenDeletedDetailsDoNotBlockEmptyBatchDeletionAndTheirHistoryRemainsByteForByte(){
|
||||
var details=db.queryForList("select * from purchase_request order by id");var history=db.queryForList("select * from purchase_operation_log order by id");
|
||||
assertEquals(0,mapper.countRequestsByBatchId(328L));assertEquals(1,mapper.countRequestsByBatchId(329L));
|
||||
assertEquals(1,service.deletePurchaseBatchById(328L));assertEquals(0,db.queryForObject("select count(*) from purchase_batch where id=328",Integer.class));
|
||||
assertEquals(details,db.queryForList("select * from purchase_request order by id"));assertEquals(history,db.queryForList("select * from purchase_operation_log order by id"));assertEquals(1,db.queryForObject("select count(*) from purchase_batch where id=329",Integer.class));
|
||||
}
|
||||
@Test void oneLiveDetailStillPreventsDeletionEvenWhenThereAreElevenDeletedOnes(){
|
||||
db.update("insert into purchase_request values(30,328,'CG2026110002','PR-30','0')");assertEquals(1,mapper.countRequestsByBatchId(328L));
|
||||
assertThrows(ServiceException.class,()->service.deletePurchaseBatchById(328L));assertEquals(1,db.queryForObject("select count(*) from purchase_batch where id=328",Integer.class));
|
||||
}
|
||||
@Test void numberedOrAttachedDocumentsStillProtectAnEmptyBatch(){
|
||||
db.update("insert into purchase_document_group values(1,'batch',328,'HT-1')");assertThrows(ServiceException.class,()->service.deletePurchaseBatchById(328L));
|
||||
db.update("update purchase_document_group set document_no=''");db.update("insert into purchase_document_attachment values(1,1,0)");assertThrows(ServiceException.class,()->service.deletePurchaseBatchById(328L));
|
||||
assertEquals(1,db.queryForObject("select count(*) from purchase_batch where id=328",Integer.class));
|
||||
}
|
||||
@Test void emptyGroupsAndPreviouslyRemovedAttachmentsArePreservedButDoNotBlockDeletion(){
|
||||
db.update("insert into purchase_document_group values(1,'batch',328,'')");db.update("insert into purchase_document_attachment values(1,1,1)");
|
||||
assertEquals(1,service.deletePurchaseBatchById(328L));assertEquals(1,db.queryForObject("select count(*) from purchase_document_group",Integer.class));assertEquals(1,db.queryForObject("select count(*) from purchase_document_attachment",Integer.class));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseSheetCollaboration;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.AopTestUtils;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Real MySQL mappers and native save paths, all enclosed in a rollback-only development fixture. */
|
||||
@EnabledIfSystemProperty(named="projectDbTests",matches="true")
|
||||
class PurchaseOwnershipCollaborationDatabaseTest {
|
||||
@Test void batchOwnerAndDetailOwnerMergeWithoutEditingForeignRowsOrLosingChanges()throws Exception{
|
||||
var f=new PurchaseSheetDatabaseTest.Fixture();var actor=new AtomicReference<>("batch-owner");var user=new AtomicLong(1);var admin=new AtomicBoolean(true);
|
||||
try(var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::getUsername).thenAnswer(c->actor.get());security.when(SecurityUtils::getUserId).thenAnswer(c->user.get());security.when(SecurityUtils::isAdmin).thenAnswer(c->admin.get());security.when(()->SecurityUtils.hasPermi(anyString())).thenReturn(true);
|
||||
var stored=new HashMap<String,String>();var cache=mock(RedisCache.class);
|
||||
doAnswer(c->{stored.put(c.getArgument(0),c.getArgument(1));return null;}).when(cache).setCacheObject(anyString(),anyString(),eq(24),eq(TimeUnit.HOURS));
|
||||
when(cache.getCacheObject(anyString())).thenAnswer(c->stored.get(c.getArgument(0)));
|
||||
f.set(AopTestUtils.getUltimateTargetObject(f.service),"collaboration",new PurchaseSheetCollaboration(cache,new ObjectMapper().findAndRegisterModules()));
|
||||
new TransactionTemplate(f.manager).executeWithoutResult(status->{
|
||||
status.setRollbackOnly();var draft=f.draft();draft.getRows().get(1).setProjectId(draft.getRows().get(0).getProjectId());var saved=f.save(draft);long batch=saved.getBatch().getId(),first=saved.getRows().get(0).getId(),second=saved.getRows().get(1).getId();
|
||||
f.jdbc.update("update purchase_request set create_by='detail-owner' where id=?",first);
|
||||
admin.set(false);actor.set("detail-owner");user.set(2);var own=f.copy(f.service.load(batch));assertTrue(own.getRows().get(0).getEditable());assertFalse(own.getRows().get(1).getEditable());assertFalse(own.getBatch().getEditable());
|
||||
actor.set("batch-owner");user.set(3);var other=f.copy(f.service.load(batch));assertTrue(other.getRows().stream().allMatch(r->r.getEditable()));other.getRows().get(0).setQuantity(new BigDecimal("4"));f.save(other);
|
||||
actor.set("detail-owner");user.set(2);own.getRows().get(0).setRemark("本人修改备注");var merged=f.save(own);assertTrue(merged.isCollaborationMerged());assertEquals(new BigDecimal("4.0000"),merged.getRows().get(0).getQuantity());assertEquals("本人修改备注",merged.getRows().get(0).getRemark());
|
||||
var forbidden=f.copy(merged);forbidden.getRows().get(1).setActualUnitPrice(new BigDecimal("123"));forbidden.getRows().get(1).setCreateBy("detail-owner");forbidden.getRows().get(1).setBatchCreateBy("detail-owner");assertThrows(ServiceException.class,()->f.save(forbidden));assertNull(f.purchaseRows.selectPurchaseRequestById(second,null).getActualUnitPrice());
|
||||
var header=f.copy(f.service.load(batch));header.getBatch().setBatchName("越权修改批次");header.getBatch().setCreateBy("detail-owner");assertThrows(ServiceException.class,()->f.save(header));assertNotEquals("越权修改批次",f.batchMapper.selectPurchaseBatchById(batch).getBatchName());
|
||||
actor.set("outsider");user.set(4);var outsider=f.copy(f.service.load(batch));outsider.getRows().get(0).setRemark("越权");assertThrows(ServiceException.class,()->f.save(outsider));assertEquals("本人修改备注",f.purchaseRows.selectPurchaseRequestById(first,null).getRemark());
|
||||
admin.set(true);var unrestricted=f.copy(f.service.load(batch));unrestricted.getRows().get(1).setRemark("超级管理员可维护历史归属");f.save(unrestricted);assertEquals("超级管理员可维护历史归属",f.purchaseRows.selectPurchaseRequestById(second,null).getRemark());
|
||||
admin.set(false);actor.set("procurement-manager");user.set(22);
|
||||
var role=new com.ruoyi.common.core.domain.entity.SysRole();role.setRoleKey("purchase_manager");role.setStatus("0");role.setDelFlag("0");
|
||||
var account=new com.ruoyi.common.core.domain.entity.SysUser();account.setUserId(22L);account.setUserName("procurement-manager");account.setRoles(List.of(role));
|
||||
security.when(SecurityUtils::getLoginUser).thenReturn(new com.ruoyi.common.core.domain.model.LoginUser(22L,1L,account,Set.of()));
|
||||
security.when(()->SecurityUtils.hasPermi(anyString())).thenCallRealMethod();
|
||||
var managed=f.copy(f.service.load(batch));assertTrue(managed.getBatch().getEditable());assertTrue(managed.getRows().stream().allMatch(r->r.getEditable()));
|
||||
managed.getBatch().setBatchName(f.name+"-管理员维护");managed.getRows().get(0).setRemark("采购管理员可维护所有人数据");managed.getRows().get(1).setQuantity(new BigDecimal("7"));var result=f.save(managed);
|
||||
assertEquals(f.name+"-管理员维护",f.batchMapper.selectPurchaseBatchById(batch).getBatchName());assertEquals("采购管理员可维护所有人数据",f.purchaseRows.selectPurchaseRequestById(first,null).getRemark());assertEquals(new BigDecimal("7.0000"),f.purchaseRows.selectPurchaseRequestById(second,null).getQuantity());
|
||||
assertTrue(f.service.confirm(batch,result.getVersion()).getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked())));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package com.ruoyi.warehouse.service.impl;
|
||||
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.util.PurchaseDataAccess;
|
||||
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 PurchaseDataAccessTest {
|
||||
PurchaseRequest row(){var r=new PurchaseRequest();r.setId(1L);r.setCreateBy("alice");r.setBatchCreateBy("bob");return r;}
|
||||
@Test void creatorAndBatchCreatorCanEditButMenuManagerCannotBypassOwnership(){
|
||||
try(var security=mockStatic(SecurityUtils.class)){
|
||||
var r=row();security.when(SecurityUtils::getUsername).thenReturn("alice");assertTrue(PurchaseDataAccess.canEdit(r));
|
||||
security.when(SecurityUtils::getUsername).thenReturn("bob");assertTrue(PurchaseDataAccess.canEdit(r));
|
||||
security.when(SecurityUtils::getUsername).thenReturn("mallory");security.when(()->SecurityUtils.hasPermi(anyString())).thenReturn(true);assertFalse(r.getEditable());assertThrows(ServiceException.class,()->PurchaseDataAccess.require(r));
|
||||
var batch=new PurchaseBatch();batch.setCreateBy("bob");assertFalse(batch.getEditable());security.when(SecurityUtils::isAdmin).thenReturn(true);assertTrue(batch.getEditable());assertTrue(r.getEditable());
|
||||
}
|
||||
}
|
||||
@Test void nativeDetailAndArrivalEndpointsEnforceOwnershipBeforeWriting(){
|
||||
try(var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::getUsername).thenReturn("mallory");var mapper=mock(PurchaseRequestMapper.class);when(mapper.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(row());
|
||||
var service=new PurchaseRequestServiceImpl();ReflectionTestUtils.setField(service,"purchaseRequestMapper",mapper);ReflectionTestUtils.setField(service,"itemCategories",mock(ItemCategoryService.class));var input=row();input.setCreateBy("mallory");input.setBatchCreateBy("mallory");assertThrows(ServiceException.class,()->service.updatePurchaseRequest(input));verify(mapper,never()).updatePurchaseRequest(any(),any());
|
||||
var arrivalService=new PurchaseArrivalServiceImpl();var arrivals=mock(PurchaseArrivalMapper.class);ReflectionTestUtils.setField(arrivalService,"journal",mock(InventoryCostJournal.class));ReflectionTestUtils.setField(arrivalService,"purchaseRequestMapper",mapper);ReflectionTestUtils.setField(arrivalService,"purchaseArrivalMapper",arrivals);
|
||||
var arrival=new PurchaseArrival();arrival.setId(2L);arrival.setPurchaseRequestId(1L);arrival.setAcceptanceStatus(0);assertThrows(ServiceException.class,()->arrivalService.insertPurchaseArrival(arrival));verify(arrivals,never()).insertPurchaseArrival(any());when(arrivals.selectPurchaseArrivalByIdForUpdate(2L)).thenReturn(arrival);var accept=new PurchaseArrivalAcceptanceRequest();accept.setAcceptanceStatus(1);assertThrows(ServiceException.class,()->arrivalService.acceptPurchaseArrival(2L,accept));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,108 @@
|
||||
package com.ruoyi.warehouse.service.impl;
|
||||
|
||||
import com.ruoyi.common.core.domain.entity.*;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.*;
|
||||
import com.ruoyi.framework.web.service.PermissionService;
|
||||
import com.ruoyi.framework.web.service.SysPermissionService;
|
||||
import com.ruoyi.system.mapper.SysMenuMapper;
|
||||
import com.ruoyi.system.mapper.SysRoleMapper;
|
||||
import com.ruoyi.system.service.ISysMenuService;
|
||||
import com.ruoyi.system.service.impl.SysMenuServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.util.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchaseManagerPermissionTest {
|
||||
@BeforeEach void request() {
|
||||
org.springframework.web.context.request.RequestContextHolder.setRequestAttributes(
|
||||
new org.springframework.web.context.request.ServletRequestAttributes(new org.springframework.mock.web.MockHttpServletRequest()));
|
||||
}
|
||||
static LoginUser login(String key, String status, String deleted, Set<String> permissions) {
|
||||
var role = new SysRole(); role.setRoleId(30L); role.setRoleKey(key); role.setStatus(status); role.setDelFlag(deleted);
|
||||
var user = new SysUser(); user.setUserId(22L); user.setUserName("manager"); user.setRoles(List.of(role));
|
||||
var login = new LoginUser(22L, 1L, user, permissions);
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login, null));
|
||||
return login;
|
||||
}
|
||||
static LoginUser manager() { return login("purchase_manager", "0", "0", Set.of()); }
|
||||
@AfterEach void cleanup() { SecurityContextHolder.clearContext(); org.springframework.web.context.request.RequestContextHolder.resetRequestAttributes(); }
|
||||
|
||||
@Test void activeManagerHasEveryProcurementActionEvenBeforeMenuPermissionsAreRefreshed() {
|
||||
manager(); var expressions = new PermissionService();
|
||||
for (String permission : PurchasePermissions.ACTIONS) {
|
||||
assertTrue(SecurityUtils.hasPermi(permission), permission);
|
||||
assertTrue(expressions.hasPermi(permission), permission);
|
||||
assertTrue(expressions.hasAnyPermi("system:user:remove," + permission), permission);
|
||||
}
|
||||
for (String unrelated : List.of("system:user:edit", "system:role:edit", "system:mobile-release:manage",
|
||||
"warehouse:stock:out", "project:project:edit", "warehouse:product:edit", "warehouse:purchase:unknown", "*:*:*")) {
|
||||
assertFalse(SecurityUtils.hasPermi(unrelated), unrelated);
|
||||
assertFalse(expressions.hasPermi(unrelated), unrelated);
|
||||
}
|
||||
assertFalse(expressions.hasPermi(""));
|
||||
assertFalse(expressions.hasAnyPermi("system:user:edit,warehouse:stock:out"));
|
||||
}
|
||||
|
||||
@Test void allForeignAndLegacyOwnershipFlagsAreEditableForManagerAndQuotationIsVisible() {
|
||||
manager();
|
||||
for (String owner : List.of("someone-else", "", "deleted-account")) {
|
||||
var row = new PurchaseRequest(); row.setCreateBy(owner); row.setBatchCreateBy("old-owner");
|
||||
var batch = new PurchaseBatch(); batch.setCreateBy(owner);
|
||||
assertTrue(row.getEditable()); assertTrue(batch.getEditable());
|
||||
assertDoesNotThrow(() -> PurchaseDataAccess.require(row)); assertDoesNotThrow(() -> PurchaseDataAccess.require(batch));
|
||||
}
|
||||
assertTrue(PurchaseDataAccess.canEdit(null, null));
|
||||
assertFalse(PurchaseDataAccess.canEdit((PurchaseRequest)null));
|
||||
assertFalse(PurchaseDataAccess.canEdit((PurchaseBatch)null));
|
||||
assertTrue(PurchaseQuoteAccess.allowed());
|
||||
}
|
||||
|
||||
@Test void aMenuPermissionOrRoleNameLookalikeDoesNotConferManagerDataOrQuotationRights() {
|
||||
for (String key : List.of("purchase_user", "采购管理员", "purchase_*", "admin")) {
|
||||
login(key, "0", "0", Set.of("warehouse:purchase:manage", "*:*:*"));
|
||||
assertFalse(PurchaseDataAccess.managesAll(), key); assertFalse(PurchaseQuoteAccess.allowed(), key);
|
||||
assertFalse(PurchaseDataAccess.canEdit("someone-else", "old-owner"), key);
|
||||
assertTrue(PurchaseDataAccess.canEdit("manager", "someone-else"), key);
|
||||
}
|
||||
for (String[] state : List.of(new String[]{"1", "0"}, new String[]{"0", "2"})) {
|
||||
login("purchase_manager", state[0], state[1], Set.of());
|
||||
assertFalse(PurchaseDataAccess.managesAll()); assertFalse(PurchaseQuoteAccess.allowed());
|
||||
assertFalse(new PermissionService().hasPermi("warehouse:purchase:manage"));
|
||||
}
|
||||
SecurityContextHolder.clearContext(); assertFalse(PurchaseDataAccess.managesAll());
|
||||
}
|
||||
|
||||
@Test void getInfoPermissionsSupplyWebAppAndAssistantWithExactlyTheSameProcurementActions() {
|
||||
var login = manager(); var menu = mock(ISysMenuService.class);
|
||||
when(menu.selectMenuPermsByRoleId(30L)).thenReturn(Set.of());
|
||||
var permissions = new SysPermissionService(); ReflectionTestUtils.setField(permissions, "menuService", menu);
|
||||
assertEquals(PurchasePermissions.ACTIONS, permissions.getMenuPermission(login.getUser()));
|
||||
assertEquals(PurchasePermissions.ACTIONS, login.getUser().getRoles().get(0).getPermissions());
|
||||
login.getUser().getRoles().get(0).setStatus("1"); assertTrue(permissions.getMenuPermission(login.getUser()).isEmpty());
|
||||
}
|
||||
|
||||
static SysMenu menu(long id, long parent, String type, String permission) {
|
||||
var m = new SysMenu(); m.setMenuId(id); m.setParentId(parent); m.setMenuType(type); m.setPerms(permission); return m;
|
||||
}
|
||||
@Test void procurementMenusIncludeTheirDirectoryButNeverUnassignedSiblingPages() {
|
||||
var login = manager(); var mapper = mock(SysMenuMapper.class); var roles = mock(SysRoleMapper.class);
|
||||
when(roles.selectRolePermissionByUserId(22L)).thenReturn(login.getUser().getRoles());
|
||||
when(mapper.selectMenuTreeByUserId(22L)).thenReturn(List.of());
|
||||
when(mapper.selectMenuTreeAll()).thenReturn(List.of(menu(10,0,"M",""), menu(11,10,"C","warehouse:purchase:list"),
|
||||
menu(12,10,"C","warehouse:stock:list"), menu(13,10,"C","warehouse:purchase:manage"),
|
||||
menu(20,0,"C","system:role:list")));
|
||||
var service = new SysMenuServiceImpl(); ReflectionTestUtils.setField(service,"menuMapper",mapper); ReflectionTestUtils.setField(service,"roleMapper",roles);
|
||||
var tree = service.selectMenuTreeByUserId(22L);
|
||||
assertEquals(1,tree.size()); assertEquals(10L,tree.get(0).getMenuId());
|
||||
assertEquals(List.of(11L,13L),tree.get(0).getChildren().stream().map(SysMenu::getMenuId).toList());
|
||||
login.getUser().getRoles().get(0).setStatus("1"); assertTrue(service.selectMenuTreeByUserId(22L).isEmpty());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
package com.ruoyi.warehouse.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchaseSheetCollaborationTest {
|
||||
ObjectMapper json=new ObjectMapper().findAndRegisterModules();
|
||||
Map<String,String> stored;PurchaseSheetCollaboration merge;MockedStatic<SecurityUtils> security;
|
||||
@BeforeEach void setup(){
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenReturn(10L);security.when(SecurityUtils::getUsername).thenReturn("alice");security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
stored=new HashMap<>();var cache=mock(RedisCache.class);
|
||||
doAnswer(c->{stored.put(c.getArgument(0),c.getArgument(1));return null;}).when(cache).setCacheObject(anyString(),anyString(),eq(24),eq(TimeUnit.HOURS));
|
||||
when(cache.getCacheObject(anyString())).thenAnswer(c->stored.get(c.getArgument(0)));
|
||||
merge=new PurchaseSheetCollaboration(cache,json);
|
||||
}
|
||||
@AfterEach void cleanup(){security.close();}
|
||||
PurchaseRequest row(long id){var r=new PurchaseRequest();r.setId(id);r.setMaterialName("物品"+id);r.setCreateBy("alice");r.setBatchCreateBy("bob");r.setQuantity(BigDecimal.ONE);r.setFinalUnitPrice(BigDecimal.TEN);r.setActualUnitPrice(BigDecimal.ONE);r.setPurchaseStatus(0);r.setPriceLocked(false);return r;}
|
||||
PurchaseSheet base(){var b=new PurchaseBatch();b.setId(5L);b.setCreateBy("bob");b.setBatchName("采购");b.setExpenseCategoryId(1L);var s=new PurchaseSheet();s.setBatch(b);s.setRows(new ArrayList<>(List.of(row(1),row(2))));s.setDeletedIds(List.of());s.setVersion("v1");merge.remember(s);return s;}
|
||||
PurchaseSheet copy(PurchaseSheet s)throws Exception{return json.readValue(json.writeValueAsBytes(s),PurchaseSheet.class);}
|
||||
@Test void differentRowsAndConcurrentNewRowsArePreserved()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");
|
||||
input.getRows().get(0).setRemark("我的备注");latest.getRows().get(1).setQuantity(new BigDecimal("7"));latest.getRows().add(row(3));
|
||||
var result=merge.merge(input,latest);assertEquals(3,result.getRows().size());assertEquals("我的备注",result.getRows().get(0).getRemark());assertEquals(new BigDecimal("7"),result.getRows().get(1).getQuantity());assertTrue(result.isCollaborationMerged());assertEquals("v2",result.getVersion());
|
||||
}
|
||||
@Test void differentFieldsOnSameRowMergeAndIgnoreReadonlySpoofing()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");
|
||||
input.getRows().get(0).setRemark("我的备注");input.getRows().get(0).setCreateBy("mallory");input.getRows().get(0).setPurchaseStatus(4);latest.getRows().get(0).setQuantity(BigDecimal.TEN);
|
||||
var result=merge.merge(input,latest);var r=result.getRows().get(0);assertEquals("我的备注",r.getRemark());assertEquals(BigDecimal.TEN,r.getQuantity());assertEquals("alice",r.getCreateBy());assertEquals(0,r.getPurchaseStatus());
|
||||
}
|
||||
@Test void overlappingEditsReturnSafeProposedDraftAndExplicitConflict()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getRows().get(0).setRemark("我的");latest.getRows().get(0).setRemark("他人");input.getRows().get(1).setQuantity(BigDecimal.TEN);
|
||||
var e=assertThrows(PurchaseSheetCollaboration.ConflictException.class,()->merge.merge(input,latest));assertEquals(1,e.conflicts.size());assertEquals(List.of("remark"),e.conflicts.get(0).fields());assertEquals("我的",e.conflicts.get(0).mine().get("remark"));assertEquals("他人",e.conflicts.get(0).current().get("remark"));assertEquals(BigDecimal.TEN,e.proposed.getRows().get(1).getQuantity());
|
||||
}
|
||||
@Test void relatedIdentityChangesConflictAsOneGroup()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getRows().get(0).setMaterialParams("规格A");latest.getRows().get(0).setMaterialBrand("品牌B");
|
||||
var e=assertThrows(PurchaseSheetCollaboration.ConflictException.class,()->merge.merge(input,latest));assertTrue(e.conflicts.get(0).fields().containsAll(List.of("materialBrand","materialParams","unit")));
|
||||
}
|
||||
@Test void identicalConcurrentEditsAndNumericScaleAreNotConflicts()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getRows().get(0).setQuantity(new BigDecimal("2.0000"));latest.getRows().get(0).setQuantity(new BigDecimal("2"));assertEquals(0,new BigDecimal("2").compareTo(merge.merge(input,latest).getRows().get(0).getQuantity()));
|
||||
}
|
||||
@Test void employeeMergePreservesNewQuoteAndDoesNotRevealConflictValues()throws Exception{
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(false);var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getRows().get(0).setFinalUnitPrice(null);input.getRows().get(0).setRemark("备注");latest.getRows().get(0).setFinalUnitPrice(new BigDecimal("99"));var result=merge.merge(input,latest);assertEquals(new BigDecimal("99"),result.getRows().get(0).getFinalUnitPrice());assertEquals("备注",result.getRows().get(0).getRemark());
|
||||
}
|
||||
@Test void forgedQuoteIsRejectedBeforeItCanEnterConflictResponse()throws Exception{
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(false);var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getRows().get(0).setFinalUnitPrice(new BigDecimal("123"));assertThrows(ServiceException.class,()->merge.merge(input,latest));
|
||||
}
|
||||
@Test void deletionAgainstConcurrentEditsIsRejected()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getRows().remove(0);input.setDeletedIds(List.of(1L));latest.getRows().get(0).setRemark("不能丢失");assertTrue(assertThrows(ServiceException.class,()->merge.merge(input,latest)).getMessage().contains("不能直接删除"));
|
||||
}
|
||||
@Test void concurrentDeletionIsKeptUnlessItWouldLoseAnEdit()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");latest.getRows().remove(0);assertEquals(1,merge.merge(input,latest).getRows().size());input.getRows().get(0).setRemark("我的修改");assertTrue(assertThrows(ServiceException.class,()->merge.merge(input,latest)).getMessage().contains("已被删除"));
|
||||
}
|
||||
@Test void baselineCannotBeBorrowedFromAnotherAccountAndMissingRowsAreRejected()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");security.when(SecurityUtils::getUserId).thenReturn(11L);assertThrows(ServiceException.class,()->merge.merge(input,latest));security.when(SecurityUtils::getUserId).thenReturn(10L);input.getRows().remove(0);assertThrows(ServiceException.class,()->merge.merge(input,latest));
|
||||
}
|
||||
@Test void serverProtectedReadonlyPropertiesCannotBeChangedEvenOnConflictingHeader()throws Exception{
|
||||
var b=base();var input=copy(b);var latest=copy(b);latest.setVersion("v2");input.getBatch().setCreateBy("alice");input.getBatch().setBatchNo("FAKE");input.getBatch().setPurchaseStatus(5);input.getBatch().setProgressRemark("新备注");var result=merge.merge(input,latest);assertEquals("bob",result.getBatch().getCreateBy());assertNull(result.getBatch().getBatchNo());assertNull(result.getBatch().getPurchaseStatus());assertEquals("新备注",result.getBatch().getProgressRemark());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,54 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.projectdev.ProfileConfiguration;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Explicit development regression: only the supplied document and capability catalog, no business writes. */
|
||||
class AssistantPurchasePdfLiveTest {
|
||||
Path fixture(){return Path.of(System.getProperty("purchasePdfFixture"));}
|
||||
@Test @EnabledIfSystemProperty(named="purchasePdfFixture",matches=".+")
|
||||
void nativeNumberColumnFindsAllOneHundredAndOneItemsAcrossBothOriginalPages()throws Exception{
|
||||
var pages=AssistantQuotationPdf.read(Files.readAllBytes(fixture()),"owned-pdf",fixture().getFileName().toString());assertEquals(2,pages.size());
|
||||
var numbers=pages.stream().flatMap(page->((AssistantPurchasePdfRows.PageNumbers)page.get("_pdfRowNumbers")).numbers().stream()).toList();assertEquals(java.util.stream.IntStream.rangeClosed(1,101).boxed().toList(),numbers);
|
||||
var chunks=pages.stream().flatMap(page->((AssistantQuotationPdf.PurchaseChunks)page.get("_pdfPurchaseChunks")).files().stream()).toList();assertEquals(7,chunks.size());
|
||||
String firstSource=chunks.get(0).get("pdfText").toString();assertTrue(firstSource.contains("2500Wh"));assertFalse(firstSource.contains("25004Wh"));
|
||||
String secondPage=chunks.get(4).get("pdfText").toString();assertTrue(secondPage.contains("1000只/包"));assertFalse(secondPage.contains("1000只1/包"));
|
||||
assertEquals(numbers,chunks.stream().flatMap(part->((AssistantPurchasePdfRows.PageNumbers)part.get("_pdfRowNumbers")).numbers().stream()).toList());
|
||||
var dir=Path.of("../.codex-tmp/assistant-pdf-timeout-20261105/crops");Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve("native-source.json"),com.alibaba.fastjson2.JSON.toJSONString(chunks.stream().map(part->Map.of("page",part.get("pdfPage"),"numbers",((AssistantPurchasePdfRows.PageNumbers)part.get("_pdfRowNumbers")).numbers(),"text",part.get("pdfText"))).toList()));
|
||||
try(var source=org.apache.pdfbox.Loader.loadPDF(Files.readAllBytes(fixture()))){
|
||||
var glyphs=new ArrayList<Map<String,Object>>();
|
||||
var originalOrder=new org.apache.pdfbox.text.PDFTextStripper(){
|
||||
@Override protected void processTextPosition(org.apache.pdfbox.text.TextPosition position){glyphs.add(Map.of("page",getCurrentPageNo(),"x",position.getXDirAdj(),"y",position.getYDirAdj(),"width",position.getWidthDirAdj(),"text",position.getUnicode()));super.processTextPosition(position);}
|
||||
};
|
||||
originalOrder.setSortByPosition(false);Files.writeString(dir.resolve("native-drawing-order.txt"),originalOrder.getText(source));Files.writeString(dir.resolve("native-glyphs.json"),com.alibaba.fastjson2.JSON.toJSONString(glyphs));
|
||||
}
|
||||
for(int i=0;i<chunks.size();i++){
|
||||
var part=chunks.get(i);assertTrue(((AssistantPurchasePdfRows.PageNumbers)part.get("_pdfRowNumbers")).numbers().size()<=16);assertFalse(part.containsKey("pdfDetailImages"));
|
||||
byte[] image=Base64.getDecoder().decode(part.get("dataUrl").toString().split(",",2)[1]);Files.write(dir.resolve("chunk-"+(i+1)+".png"),image);
|
||||
var bitmap=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(image));assertTrue(bitmap.getHeight()<600);bitmap.flush();
|
||||
}
|
||||
}
|
||||
@Test @EnabledIfSystemProperty(named="assistantPurchasePdfLive",matches="true")
|
||||
void realConfiguredModelReadsTheProvidedPdfAfterTheCreateFollowupAndPreservesEveryItem()throws Exception{
|
||||
byte[] original=Files.readAllBytes(fixture());var pages=AssistantQuotationPdf.read(original,"owned-pdf",fixture().getFileName().toString());
|
||||
var settings=ProfileConfiguration.load("druid");var client=new AssistantModelClient();for(var field:Map.of("baseUrl","agent.model.base-url","apiKey","agent.model.api-key","model","agent.model.model").entrySet())ReflectionTestUtils.setField(client,field.getKey(),settings.getProperty(field.getValue(),""));
|
||||
ReflectionTestUtils.setField(client,"maxOutputTokens",16384);ReflectionTestUtils.setField(client,"timeoutMs",180000L);ReflectionTestUtils.setField(client,"businessTimeZone","Asia/Shanghai");
|
||||
var attachments=mock(AssistantAttachmentService.class);when(attachments.quotationInputs(anyList())).thenReturn(pages);ReflectionTestUtils.setField(client,"attachmentService",attachments);
|
||||
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(SecurityUtils.class)){var login=new com.ruoyi.common.core.domain.model.LoginUser();login.setPermissions(Set.of("*:*:*"));security.when(SecurityUtils::getLoginUser).thenReturn(login);security.when(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","请识别附件并协助处理"),Map.of("role","assistant","content","用于更新已有批次报价,还是创建新的采购申请?"),Map.of("role","user","content","创建新的采购申请")),catalog,Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","name",fixture().getFileName().toString(),"extension","pdf","type","document")));
|
||||
assertEquals("draft",result.get("kind"));assertEquals("purchase.create",result.get("action"));var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(101,rows.size());
|
||||
BigDecimal total=rows.stream().map(row->new BigDecimal(row.get("quantity").toString()).multiply(new BigDecimal(row.get("finalUnitPrice").toString()))).reduce(BigDecimal.ZERO,BigDecimal::add);assertEquals(0,new BigDecimal("130829.44").compareTo(total));assertEquals(0,new BigDecimal("960.50").compareTo(new BigDecimal(rows.get(0).get("finalUnitPrice").toString())));assertEquals(0,new BigDecimal("2260.00").compareTo(new BigDecimal(rows.get(100).get("finalUnitPrice").toString())));
|
||||
assertArrayEquals(original,Files.readAllBytes(fixture()));verifyNoInteractions(db);verify(attachments).quotationInputs(anyList());
|
||||
var output=Path.of(System.getProperty("purchasePdfOutput"));Files.createDirectories(output.getParent());Files.writeString(output,com.alibaba.fastjson2.JSON.toJSONString(Map.of("complete",true,"executed",false,"count",rows.size(),"total",total,"proposal",result)));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,77 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.http.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AssistantPurchasePdfRoutingTest {
|
||||
static final String PIXEL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j+fsAAAAASUVORK5CYII=";
|
||||
List<Map<String,Object>> definition(boolean allowed){return List.of(Map.of("key","purchase.create","allowed",allowed,"fields",List.of(Map.of("key","materialName"),Map.of("key","materialParams"),Map.of("key","materialBrand"),Map.of("key","unit"),Map.of("key","quantity"),Map.of("key","finalUnitPrice"),Map.of("key","actualUnitPrice"))));}
|
||||
Map<String,Object> file(int page,int first,int last){return Map.of("id","owned-pdf","name","原报价 · 第"+page+"页","type","image","pdfPage",page,"pdfText","本页采购明细","dataUrl",PIXEL,"_pdfRowNumbers",new AssistantPurchasePdfRows.PageNumbers(java.util.stream.IntStream.rangeClosed(first,last).boxed().toList()));}
|
||||
Map<String,Object> transcription(int first,int last){return Map.of("kind","draft","action","purchase.create","message","请核对原文","rows",java.util.stream.IntStream.rangeClosed(first,last).mapToObj(n->Map.of("_sourceRow",n,"sourceName","原物品"+n,"sourceSpec","型号"+n,"sourceQuantity",2,"sourceUnit","件","finalUnitPrice","11.30","sourceAmount","22.60")).toList());}
|
||||
AssistantModelClient client(HttpClient http,AssistantAttachmentService attachments){var client=new AssistantModelClient(http);ReflectionTestUtils.setField(client,"baseUrl","http://127.0.0.1:1/v1");ReflectionTestUtils.setField(client,"model","mock-model");ReflectionTestUtils.setField(client,"timeoutMs",180000L);ReflectionTestUtils.setField(client,"maxOutputTokens",16384);ReflectionTestUtils.setField(client,"businessTimeZone","Asia/Shanghai");ReflectionTestUtils.setField(client,"attachmentService",attachments);return client;}
|
||||
@Test void clarifiedCreateReadsBothPdfPagesAndKeepsAll101RowsWithoutUsingTheQuoteCorrectionAction()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);when(attachments.quotationInputs(anyList())).thenReturn(List.of(file(1,1,64),file(2,65,101)));
|
||||
var route=response(Map.of("kind","draft","action","purchase.create","message","创建采购"));var first=response(transcription(1,64));var second=response(transcription(65,101));
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenAnswer(invocation->{String input=body(invocation.getArgument(0));if(input.contains("originalItemNumbers"))return context(invocation.getArgument(0)).getJSONArray("originalItemNumbers").getInteger(0)==1?first:second;return route;});
|
||||
var proposal=client(http,attachments).propose(List.of(Map.of("role","user","content","请识别附件并协助处理"),Map.of("role","assistant","content","用于更新报价还是创建新的采购申请?"),Map.of("role","user","content","创建新的采购申请")),definition(true),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","extension","pdf","name","报价.pdf")));
|
||||
var rows=AssistantConversationService.maps(proposal.get("rows"));assertEquals(101,rows.size());assertEquals("原物品101",rows.get(100).get("materialName"));assertEquals("11.30",rows.get(100).get("finalUnitPrice"));assertFalse(rows.get(100).containsKey("productId"));
|
||||
var requests=ArgumentCaptor.forClass(HttpRequest.class);verify(http,times(3)).send(requests.capture(),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any());
|
||||
for(var request:requests.getAllValues().subList(1,3)){var body=body(request);assertTrue(body.contains(PIXEL));assertTrue(body.contains("pdfPage")||body.contains("PDF第"));assertFalse(body.contains("quotationTargets"));}
|
||||
verify(attachments).quotationInputs(anyList());
|
||||
}
|
||||
@Test void boundedChunksRunConcurrentlyAndMergeOutOfOrderRepliesWithoutLosingTheActualPriceInstruction()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);var parts=new ArrayList<Map<String,Object>>();
|
||||
var replies=new HashMap<Integer,HttpResponse<String>>();
|
||||
for(int first=1;first<=101;first+=16){int last=Math.min(first+15,101);parts.add(file(first<=64?1:2,first,last));replies.put(first,response(transcription(first,last)));}
|
||||
var page=new LinkedHashMap<>(file(1,1,101));page.put("_pdfPurchaseChunks",new AssistantQuotationPdf.PurchaseChunks(parts));when(attachments.quotationInputs(anyList())).thenReturn(List.of(page));
|
||||
var route=response(Map.of("kind","draft","action","purchase.create","message","创建采购"));var entered=new CountDownLatch(3);var active=new java.util.concurrent.atomic.AtomicInteger();var maximum=new java.util.concurrent.atomic.AtomicInteger();
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenAnswer(invocation->{var input=context(invocation.getArgument(0));if(!input.containsKey("originalItemNumbers"))return route;int current=active.incrementAndGet();maximum.accumulateAndGet(current,Math::max);try{entered.countDown();assertTrue(entered.await(3,TimeUnit.SECONDS));int n=input.getJSONArray("originalItemNumbers").getInteger(0);Thread.sleep(n==1?80:5);return replies.get(n);}finally{active.decrementAndGet();}});
|
||||
var result=client(http,attachments).propose(List.of(Map.of("role","user","content","根据这个报价单生成采购申请,报价和实际金额一样")),definition(true),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","name","报价.pdf")));
|
||||
var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(101,rows.size());assertEquals(3,maximum.get());assertEquals("原物品1",rows.get(0).get("materialName"));assertEquals("原物品101",rows.get(100).get("materialName"));assertTrue(rows.stream().allMatch(row->Objects.equals(row.get("finalUnitPrice"),row.get("actualUnitPrice"))));
|
||||
var requests=ArgumentCaptor.forClass(HttpRequest.class);verify(http,times(8)).send(requests.capture(),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any());
|
||||
for(var request:requests.getAllValues().subList(1,8)){var input=context(request);assertTrue(input.getJSONArray("originalItemNumbers").size()<=16);var json=JSON.parseObject(body(request));assertTrue(json.getJSONArray("messages").getJSONObject(0).getString("content").length()<2000);assertEquals(6144,json.getIntValue("max_tokens"));assertFalse(body(request).contains("pdfDetailImages"));}
|
||||
}
|
||||
@Test void oneTimedOutChunkNeverReturnsOtherSuccessfulRowsAsAPartialDraft()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);var page=new LinkedHashMap<>(file(1,1,32));page.put("_pdfPurchaseChunks",new AssistantQuotationPdf.PurchaseChunks(List.of(file(1,1,16),file(1,17,32))));when(attachments.quotationInputs(anyList())).thenReturn(List.of(page));
|
||||
var route=response(Map.of("kind","draft","action","purchase.create","message","创建采购"));var first=response(transcription(1,16));
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenAnswer(invocation->{var input=context(invocation.getArgument(0));if(!input.containsKey("originalItemNumbers"))return route;if(input.getJSONArray("originalItemNumbers").getInteger(0)==17)throw new HttpTimeoutException("simulated slow model");return first;});
|
||||
var error=assertThrows(AssistantModelClient.ModelFailure.class,()->client(http,attachments).propose(List.of(Map.of("role","user","content","根据报价创建采购申请")),definition(true),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","name","报价.pdf"))));assertEquals("TIMEOUT",error.category());
|
||||
}
|
||||
@Test void moreThanTwoHundredOriginalRowsAreRejectedBeforeAnyTranscriptionCall()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);when(attachments.quotationInputs(anyList())).thenReturn(List.of(file(1,1,201)));var route=response(Map.of("kind","draft","action","purchase.create","message","创建采购"));when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenReturn(route);
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class,()->client(http,attachments).propose(List.of(Map.of("role","user","content","根据PDF创建采购")),definition(true),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","name","报价.pdf"))));verify(http,times(1)).send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any());
|
||||
}
|
||||
@Test void restrictedQuoteFieldCannotBeCopiedBackThroughAnActualPriceInstruction()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);when(attachments.quotationInputs(anyList())).thenReturn(List.of(file(1,1,2)));var selected=new LinkedHashMap<>(definition(true).get(0));selected.put("fields",AssistantConversationService.maps(selected.get("fields")).stream().filter(field->!"finalUnitPrice".equals(field.get("key"))).toList());
|
||||
var route=response(Map.of("kind","draft","action","purchase.create","message","创建采购"));var source=response(transcription(1,2));when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenReturn(route,source);
|
||||
var result=client(http,attachments).propose(List.of(Map.of("role","user","content","报价和实际金额一样,创建采购")),List.of(selected),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","name","报价.pdf")));
|
||||
assertTrue(AssistantConversationService.maps(result.get("rows")).stream().noneMatch(row->row.containsKey("finalUnitPrice")||row.containsKey("actualUnitPrice")));
|
||||
}
|
||||
@Test void forbiddenCreateNeverRendersThePdf()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);
|
||||
var route=response(Map.of("kind","draft","action","purchase.create","message","创建采购"));when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenReturn(route);
|
||||
var result=client(http,attachments).propose(List.of(Map.of("role","user","content","创建采购")),definition(false),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","name","报价.pdf")));assertEquals("answer",result.get("kind"));assertFalse(result.containsKey("rows"));verifyNoInteractions(attachments);
|
||||
}
|
||||
@Test void explicitlyGivenProjectAndNewBatchAreAppliedWithoutReplacingAnySourceCells()throws Exception{
|
||||
var http=mock(HttpClient.class);var attachments=mock(AssistantAttachmentService.class);when(attachments.quotationInputs(anyList())).thenReturn(List.of(file(1,1,2)));
|
||||
var definition=new LinkedHashMap<>(definition(true).get(0));var fields=new ArrayList<>(AssistantConversationService.maps(definition.get("fields")));fields.add(Map.of("key","projectId"));fields.add(Map.of("key","batchName"));definition.put("fields",fields);
|
||||
var route=response(Map.of("kind","draft","action","purchase.create","message","整理采购"));var source=response(transcription(1,2));var common=response(Map.of("kind","draft","action","purchase.create","message","提取公共条件","rows",List.of(Map.of("projectId",Map.of("keyword","模拟项目"),"batchName","电气采购"))));
|
||||
when(http.send(any(HttpRequest.class),org.mockito.ArgumentMatchers.<HttpResponse.BodyHandler<String>>any())).thenReturn(route,source,common);
|
||||
var result=client(http,attachments).propose(List.of(Map.of("role","user","content","按PDF为模拟项目创建采购,新建批次叫电气采购")),List.of(definition),Map.of(),Map.of(),List.of(Map.of("id","owned-pdf","type","document","name","报价.pdf")));
|
||||
var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(2,rows.size());assertEquals("原物品2",rows.get(1).get("materialName"));assertEquals("11.30",rows.get(1).get("finalUnitPrice"));assertEquals("电气采购",rows.get(1).get("batchName"));assertEquals(Map.of("keyword","模拟项目"),rows.get(0).get("projectId"));
|
||||
}
|
||||
static HttpResponse<String> response(Map<String,Object> data){HttpResponse<String> response=mock(HttpResponse.class);when(response.statusCode()).thenReturn(200);when(response.body()).thenReturn(JSON.toJSONString(Map.of("choices",List.of(Map.of("finish_reason","stop","message",Map.of("content",JSON.toJSONString(data)))))));return response;}
|
||||
static JSONObject context(HttpRequest request){return JSON.parseObject(JSON.parseObject(body(request)).getJSONArray("messages").getJSONObject(1).getJSONArray("content").getJSONObject(0).getString("text"));}
|
||||
static String body(HttpRequest request){var completed=new CompletableFuture<String>();var bytes=new ByteArrayOutputStream();request.bodyPublisher().orElseThrow().subscribe(new Flow.Subscriber<ByteBuffer>(){public void onSubscribe(Flow.Subscription subscription){subscription.request(Long.MAX_VALUE);}public void onNext(ByteBuffer buffer){byte[] chunk=new byte[buffer.remaining()];buffer.get(chunk);bytes.writeBytes(chunk);}public void onError(Throwable error){completed.completeExceptionally(error);}public void onComplete(){completed.complete(bytes.toString(StandardCharsets.UTF_8));}});return completed.join();}
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AssistantPurchasePdfRowsTest {
|
||||
Map<String,Object> row(int n){return Map.of("_sourceRow",n,"sourceName","物品"+n,"sourceSpec","M"+n,"sourceQuantity",2,"sourceUnit","件","finalUnitPrice","1.13","sourceAmount","2.26");}
|
||||
AssistantPurchasePdfRows.Page page(int first,int last){return new AssistantPurchasePdfRows.Page(Map.of("name","来源PDF","pdfPage",first==1?1:2,"_pdfRowNumbers",new AssistantPurchasePdfRows.PageNumbers(java.util.stream.IntStream.rangeClosed(first,last).boxed().toList())),Map.of("kind","draft","action","purchase.create","rows",java.util.stream.IntStream.rangeClosed(first,last).mapToObj(this::row).toList()));}
|
||||
@Test void everySourceItemBeyondOneHundredIsKeptAndCrossPageIndexesAreStable(){
|
||||
var result=AssistantPurchasePdfRows.merge(List.of(page(1,64),page(65,101)),true);var rows=AssistantConversationService.maps(result.get("rows"));assertEquals(101,rows.size());assertEquals("物品101",rows.get(100).get("materialName"));assertEquals("M101",rows.get(100).get("materialParams"));assertEquals("1.13",rows.get(100).get("finalUnitPrice"));assertTrue(rows.stream().allMatch(row->!row.containsKey("productId")));assertTrue(rows.get(64).get("_sourceText").toString().contains("原表第65项"));
|
||||
}
|
||||
@Test void exactlyTwoHundredPurchasesAreAllowedButTheTwoHundredFirstIsNotTruncated(){
|
||||
assertEquals(200,AssistantConversationService.maps(AssistantPurchasePdfRows.merge(List.of(page(1,200)),true).get("rows")).size());
|
||||
assertThrows(ServiceException.class,()->AssistantPurchasePdfRows.merge(List.of(page(1,200),page(1,1)),true));assertThrows(ServiceException.class,()->AssistantRowLimits.require("user.create",101));assertDoesNotThrow(()->AssistantRowLimits.require("purchase.create",200));
|
||||
}
|
||||
@Test void missingRepeatedAndMiscalculatedItemsCannotProduceAnExecutablePartialDraft(){
|
||||
var full=page(1,10);var partial=new LinkedHashMap<>(full.proposal());partial.put("rows",List.of(row(1),row(2)));assertThrows(ServiceException.class,()->AssistantPurchasePdfRows.merge(List.of(new AssistantPurchasePdfRows.Page(full.file(),partial)),true));
|
||||
var wrong=new LinkedHashMap<>(row(1));wrong.put("sourceAmount",99);assertThrows(ServiceException.class,()->AssistantPurchasePdfRows.merge(List.of(new AssistantPurchasePdfRows.Page(Map.of("name","PDF","pdfPage",1),Map.of("kind","draft","action","purchase.create","rows",List.of(wrong)))),true));
|
||||
}
|
||||
@Test void pureLicensePageMayBeSkippedButAnItemPageMayNeverBeSkipped(){
|
||||
var empty=Map.<String,Object>of("kind","answer","message","本页无采购明细");assertEquals(10,AssistantConversationService.maps(AssistantPurchasePdfRows.merge(List.of(page(1,10),new AssistantPurchasePdfRows.Page(Map.of("pdfPage",2),empty)),true).get("rows")).size());assertThrows(ServiceException.class,()->AssistantPurchasePdfRows.merge(List.of(new AssistantPurchasePdfRows.Page(page(1,10).file(),empty)),true));
|
||||
assertTrue(AssistantConversationService.maps(AssistantPurchasePdfRows.merge(List.of(page(1,10)),false).get("rows")).stream().noneMatch(row->row.containsKey("finalUnitPrice")));
|
||||
}
|
||||
@Test void explicitActualEqualsQuoteUsesEachRowsUnitPriceAndPreservesUnknownAndZero(){
|
||||
for(String instruction:List.of("报价和实际金额一样","实际单价与报价单价一致","实际单价按报价单价")){
|
||||
var result=AssistantPurchasePdfRows.merge(List.of(page(1,3)),true);var rows=AssistantConversationService.maps(result.get("rows"));rows.get(0).put("finalUnitPrice","12.34");rows.get(1).put("finalUnitPrice",0);rows.get(2).put("finalUnitPrice",null);
|
||||
AssistantPurchasePdfRows.applyActualPriceInstruction(result,List.of(Map.of("content",instruction)));assertEquals("12.34",rows.get(0).get("actualUnitPrice"));assertEquals(0,rows.get(1).get("actualUnitPrice"));assertFalse(rows.get(2).containsKey("actualUnitPrice"));
|
||||
}
|
||||
for(String instruction:List.of("生成采购申请","实际金额不要按报价","实际和报价不同","实际金额与报价一样吗?")){
|
||||
var result=AssistantPurchasePdfRows.merge(List.of(page(1,2)),true);AssistantPurchasePdfRows.applyActualPriceInstruction(result,List.of(Map.of("content",instruction)));assertTrue(AssistantConversationService.maps(result.get("rows")).stream().noneMatch(row->row.containsKey("actualUnitPrice")));
|
||||
}
|
||||
var masked=AssistantPurchasePdfRows.merge(List.of(page(1,2)),false);AssistantPurchasePdfRows.applyActualPriceInstruction(masked,List.of(Map.of("content","实际金额和报价一样")));assertTrue(AssistantConversationService.maps(masked.get("rows")).stream().noneMatch(row->row.containsKey("actualUnitPrice")));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
package com.ruoyi.web.service.assistant;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.ruoyi.common.core.domain.entity.SysDictData;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.AiCommandMapper;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseSheetService;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
|
||||
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Real Spring transaction interception and isolated H2 persistence; no AI or business writes. */
|
||||
class AssistantPurchasePreviewTransactionTest {
|
||||
AssistantPurchaseSheetContractTest fixture;
|
||||
JdbcTemplate db;
|
||||
DataSourceTransactionManager manager;
|
||||
PurchaseSheetService sheets;
|
||||
AssistantConversationService conversations;
|
||||
List<Map<String,Object>> rows;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
fixture=new AssistantPurchaseSheetContractTest();fixture.setup();
|
||||
var source=new JdbcDataSource();source.setURL("jdbc:h2:mem:assistant_preview_"+UUID.randomUUID()+";DB_CLOSE_DELAY=-1");
|
||||
db=new JdbcTemplate(source);manager=new DataSourceTransactionManager(source);
|
||||
db.execute("create table draft(id bigint primary key, body varchar(1000000))");db.execute("create table probe(id int)");
|
||||
var target=new PurchaseSheetService();
|
||||
for(var dependency:Map.of("catalog",fixture.catalog,"products",fixture.products,"dictTypes",fixture.dictionaries,"json",fixture.json,"itemCategories",fixture.itemCategories).entrySet())ReflectionTestUtils.setField(target,dependency.getKey(),dependency.getValue());
|
||||
var proxy=new ProxyFactory(target);proxy.setProxyTargetClass(true);proxy.addAdvice(new TransactionInterceptor(manager,new AnnotationTransactionAttributeSource()));sheets=(PurchaseSheetService)proxy.getProxy();
|
||||
when(fixture.context.getBean(PurchaseSheetService.class)).thenReturn(sheets);
|
||||
var commands=mock(AiCommandMapper.class);
|
||||
when(commands.selectAssistantCommand(1L,7L)).thenAnswer(invocation->command());when(commands.selectAiCommandForUpdate(1L,7L)).thenAnswer(invocation->command());
|
||||
when(commands.updateAssistantCommand(any())).thenAnswer(invocation->{AiCommand command=invocation.getArgument(0);return db.update("update draft set body=? where id=?",command.getPlanJson(),command.getId());});
|
||||
conversations=new AssistantConversationService(mock(RedisCache.class),commands,fixture.registry,null,null,manager);
|
||||
rows=new ArrayList<>();
|
||||
for(int i=1;i<=101;i++){
|
||||
var row=new LinkedHashMap<String,Object>();row.put("_rowId",UUID.randomUUID().toString());row.put("_sourceRow",i);row.put("_sourceText","原PDF第"+i+"项");row.put("materialName","测试物品"+i);row.put("materialParams","型号"+i);row.put("unit","个");row.put("category","零件");row.put("quantity",2);row.put("actualUnitPrice","11.30");row.put("finalUnitPrice","11.30");row.put("projectId",1L);row.put("expenseCategoryId",2L);rows.add(row);
|
||||
}
|
||||
db.update("insert into draft values(1,?)",JSON.toJSONString(Map.of("format","business-assistant-v1","version",1,"action","purchase.create","rows",rows,"status","WAIT_CONFIRM","ready",false,"results",List.of(),"permissionFingerprint",AssistantConversationService.permissionFingerprint(SecurityUtils.getLoginUser()))));
|
||||
}
|
||||
@AfterEach void cleanup(){fixture.cleanup();}
|
||||
AiCommand command(){var command=new AiCommand();command.setId(1L);command.setUserId(7L);command.setAction("purchase.create");command.setCommandStatus("WAIT_CONFIRM");command.setExpiresAt(Date.from(Instant.now().plusSeconds(600)));command.setPlanJson(db.queryForObject("select body from draft where id=1",String.class));return command;}
|
||||
|
||||
@Test void oneHundredAndOneInvalidRowsRemainEditableAndCanBeCorrectedWithoutRollback() {
|
||||
when(fixture.dictionaries.selectDictDataByType("wms_item_unit")).thenReturn(List.of());
|
||||
var preview=assertDoesNotThrow(()->conversations.preview(1L,1,rows));
|
||||
assertEquals(false,preview.get("ready"));assertEquals(2,preview.get("version"));
|
||||
var visible=AssistantConversationService.maps(preview.get("rows"));assertEquals(101,visible.size());
|
||||
assertTrue(visible.stream().allMatch(row->row.get("_errors").toString().contains("单位")));
|
||||
assertEquals("原PDF第101项",visible.get(100).get("_sourceText"));assertEquals(new BigDecimal("11.30"),visible.get(100).get("actualUnitPrice"));
|
||||
assertEquals(2,JSON.parseObject(command().getPlanJson()).getIntValue("version"));
|
||||
var unit=new SysDictData();unit.setDictLabel("个");unit.setStatus("0");when(fixture.dictionaries.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit));
|
||||
var repaired=assertDoesNotThrow(()->conversations.preview(1L,2,visible));assertEquals(true,repaired.get("ready"));assertEquals(3,repaired.get("version"));assertEquals(101,AssistantConversationService.maps(repaired.get("rows")).size());
|
||||
verify(fixture.products,never()).insertProductInfo(any());verifyNoInteractions(fixture.controller);
|
||||
}
|
||||
@Test void duplicateItemValidationDoesNotPoisonItsCallersDraftTransaction() {
|
||||
var first=new ProductInfo();first.setId(1L);first.setProductName("重复物品");first.setSpec("M1");var second=new ProductInfo();second.setId(2L);second.setProductName("重复物品");second.setSpec("M1");fixture.items.add(first);fixture.items.add(second);
|
||||
var identity=new PurchaseRequest();identity.setMaterialName("重复物品");identity.setMaterialParams("M1");
|
||||
assertDoesNotThrow(()->new TransactionTemplate(manager).execute(status->{db.update("insert into probe values(1)");assertThrows(ServiceException.class,()->sheets.findExistingItem(identity));return null;}));
|
||||
assertEquals(1,db.queryForObject("select count(*) from probe",Integer.class));
|
||||
}
|
||||
@Test void unexpectedInfrastructureFailureStillRollsBack() {
|
||||
when(fixture.products.previewImport(anyList())).thenThrow(new IllegalStateException("simulated storage failure"));
|
||||
var input=new PurchaseRequest();input.setMaterialName("测试物品");input.setUnit("个");input.setCategory("零件");
|
||||
assertThrows(IllegalStateException.class,()->new TransactionTemplate(manager).execute(status->{db.update("insert into probe values(1)");sheets.previewItem(input);return null;}));
|
||||
assertEquals(0,db.queryForObject("select count(*) from probe",Integer.class));assertEquals(1,JSON.parseObject(command().getPlanJson()).getIntValue("version"));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchaseAcceptanceConfirmationTest {
|
||||
static final String FILE="11111111-1111-4111-8111-111111111111",KEY="acceptance-test-0001";
|
||||
JdbcTemplate db;PurchaseAcceptanceReportService reports;IPurchaseOperationLogService logs;PurchaseAcceptanceConfirmationService service;MockedStatic<SecurityUtils> security;
|
||||
List<Map<String,Object>> history,receipts;String fileName;boolean fileGenerated;
|
||||
@BeforeEach void setup(){
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUsername).thenReturn("owner");security.when(SecurityUtils::getUserId).thenReturn(7L);security.when(()->SecurityUtils.hasPermi("warehouse:purchase:edit")).thenReturn(true);
|
||||
db=mock(JdbcTemplate.class);reports=mock(PurchaseAcceptanceReportService.class);logs=mock(IPurchaseOperationLogService.class);service=new PurchaseAcceptanceConfirmationService(db,reports,logs,new ObjectMapper());history=new ArrayList<>();receipts=new ArrayList<>();fileName="签字盖章版.pdf";
|
||||
when(reports.preview(1L)).thenReturn(Map.of("ready",true,"issues",List.of()));
|
||||
when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(c->{String sql=c.getArgument(0);if(sql.startsWith("select create_by from purchase_batch"))return List.of(Map.of("create_by","owner"));if(sql.startsWith("select id,request_no"))return List.of(Map.of("id",10L,"request_no","PR10"));if(sql.startsWith("select a.original_name"))return List.of(Map.of("original_name",fileName,"server_generated",fileGenerated));if(sql.startsWith("select id,attachment_id attachmentId"))return history;if(sql.contains("where request_key=?"))return receipts;return List.of();});
|
||||
when(db.update(startsWith("insert into purchase_acceptance_confirmation"),any(Object[].class))).thenAnswer(c->{Object[] args=(Object[])c.getRawArguments()[1];history.add(Map.of("id",1L,"attachmentId",args[1],"snapshotHash",args[2],"confirmedBy","owner","confirmedTime","2026-11-04 18:00:00"));receipts.add(Map.of("batch_id",1L,"attachment_id",args[1],"owner_id",7L,"snapshot_hash",args[2]));return 1;});
|
||||
}
|
||||
@AfterEach void cleanup(){security.close();}
|
||||
PurchaseAcceptanceConfirmationService.Input input(){return new PurchaseAcceptanceConfirmationService.Input(FILE,service.state(1).get("version").toString(),KEY,true);}
|
||||
@Test void signedConfirmationIsAppendOnlyIdempotentAndNeverRewritesInventoryDates(){
|
||||
fileName="材料_待签章.pdf";var command=input();var saved=service.confirm(1,command);assertEquals(true,saved.get("current"));assertEquals(true,service.confirm(1,command).get("current"));verify(db,times(1)).update(startsWith("insert into purchase_acceptance_confirmation"),any(Object[].class));verify(db,never()).update(startsWith("update"),any(Object[].class));verify(logs,times(1)).record(eq(10L),eq("PR10"),eq("DOCUMENT_ACCEPTANCE"),anyString(),contains("保持原记录"));
|
||||
}
|
||||
@Test void foreignBatchCannotBeConfirmedEvenWithEditMenu(){security.when(SecurityUtils::getUsername).thenReturn("other");assertThrows(ServiceException.class,()->service.confirm(1,input()));verify(db,never()).update(anyString(),any(Object[].class));}
|
||||
@Test void procurementManagerCanConfirmAnotherPersonsBatch(){
|
||||
security.when(SecurityUtils::getUsername).thenReturn("manager");
|
||||
var role=new com.ruoyi.common.core.domain.entity.SysRole();role.setRoleKey("purchase_manager");role.setStatus("0");role.setDelFlag("0");
|
||||
var user=new com.ruoyi.common.core.domain.entity.SysUser();user.setUserId(7L);user.setUserName("manager");user.setRoles(List.of(role));
|
||||
security.when(SecurityUtils::getLoginUser).thenReturn(new com.ruoyi.common.core.domain.model.LoginUser(7L,1L,user,Set.of()));
|
||||
security.when(()->SecurityUtils.hasPermi(anyString())).thenCallRealMethod();
|
||||
assertEquals(true,service.state(1).get("canConfirm"));assertEquals(true,service.confirm(1,input()).get("current"));
|
||||
}
|
||||
@Test void draftFilesStaleSnapshotsAndIncompletePhysicalAcceptanceAreRejected(){
|
||||
var command=input();fileGenerated=true;fileName="验收资料_待签章.pdf";assertThrows(ServiceException.class,()->service.confirm(1,command));fileGenerated=false;fileName="签字盖章版.pdf";
|
||||
assertThrows(ServiceException.class,()->service.confirm(1,new PurchaseAcceptanceConfirmationService.Input(FILE,"stale",KEY,true)));
|
||||
when(reports.preview(1L)).thenReturn(Map.of("ready",false,"issues",List.of("待验收")));assertThrows(ServiceException.class,()->service.confirm(1,command));verify(db,never()).update(anyString(),any(Object[].class));
|
||||
}
|
||||
@Test void superAdministratorCanConfirmLegacyBatchesButHumanAcknowledgementIsRequired(){security.when(SecurityUtils::getUsername).thenReturn("admin");security.when(SecurityUtils::isAdmin).thenReturn(true);var command=input();assertThrows(ServiceException.class,()->service.confirm(1,new PurchaseAcceptanceConfirmationService.Input(FILE,command.version(),KEY,false)));assertEquals(true,service.confirm(1,command).get("current"));}
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.data.redis.connection.*;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Uses a unique, disposable namespace on Redis development database 11; never scans application keys. */
|
||||
@EnabledIfSystemProperty(named="projectDbTests",matches="true")
|
||||
class PurchaseLiveRedisTest {
|
||||
@Test void atomicLeasesSequencesAndDeparturesAreSharedAcrossApplicationInstances(){
|
||||
var yaml=new YamlPropertiesFactoryBean();yaml.setResources(new ClassPathResource("application-druid.yml"));var p=yaml.getObject();assertEquals("11",p.getProperty("spring.data.redis.database"));
|
||||
String namespace="live-test-"+UUID.randomUUID();var cfg=new RedisStandaloneConfiguration(p.getProperty("spring.data.redis.host"),Integer.parseInt(p.getProperty("spring.data.redis.port")));cfg.setDatabase(11);cfg.setPassword(RedisPassword.of(p.getProperty("spring.data.redis.password")));
|
||||
var factory=new LettuceConnectionFactory(cfg);factory.afterPropertiesSet();factory.start();var redis=new StringRedisTemplate(factory);
|
||||
try{
|
||||
var a=new PurchaseLiveStore(redis,new ObjectMapper(),namespace);var b=new PurchaseLiveStore(redis,new ObjectMapper(),namespace);String first="window-aaaaaaaaaaaaaaaa",second="window-bbbbbbbbbbbbbbbb";
|
||||
var one=member(first,7L);var two=member(second,8L);a.join(10,one);b.join(10,two);a.join(10,one);assertEquals(2,b.members(10).size());
|
||||
String lease=a.lease(10,"row-1","identity");one.put("lease",lease);one.put("sequence",1L);assertNull(a.write(10,one));two.put("lease",lease);two.put("sequence",1L);assertEquals(first,b.write(10,two));
|
||||
var stale=new LinkedHashMap<>(one);stale.put("sequence",0L);assertEquals("__stale__",b.write(10,stale));assertEquals(1,((Number)b.get(10,first).get("sequence")).intValue());
|
||||
one.put("draft",Map.of("field","materialName","value","新名字"));one.put("sequence",2L);a.write(10,one);b.clearDraft(10,first,"token-7",1);assertNotNull(a.get(10,first).get("draft"));b.clearDraft(10,first,"token-7",2);assertNull(a.get(10,first).get("draft"));
|
||||
a.leave(10,first,"wrong-token");assertNotNull(b.holder(10,"row-1","identity"));a.leave(10,first,"token-7");assertNull(b.holder(10,"row-1","identity"));assertNull(b.write(10,two));
|
||||
}finally{
|
||||
// Exact test namespace only; no production or development business cache is inspected.
|
||||
var keys=redis.keys(namespace+":purchase-live:*");if(keys!=null&&!keys.isEmpty())redis.delete(keys);factory.destroy();
|
||||
}
|
||||
}
|
||||
private Map<String,Object> member(String id,long user){var m=new LinkedHashMap<String,Object>();m.put("clientId",id);m.put("userId",user);m.put("token","token-"+user);m.put("name","fixture");m.put("sequence",0L);m.put("lease","");m.put("draft",null);return m;}
|
||||
}
|
||||
@ -0,0 +1,89 @@
|
||||
package com.ruoyi.web.service.warehouse;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.constant.CacheConstants;
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.data.redis.connection.Message;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import com.ruoyi.web.controller.warehouse.PurchaseLiveController;
|
||||
import org.springframework.web.context.request.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
|
||||
class PurchaseLiveServiceTest {
|
||||
static final String A="client-aaaaaaaaaaaaaaa",B="client-bbbbbbbbbbbbbbb";
|
||||
PurchaseLiveStore store;PurchaseLiveService service;JdbcTemplate db;RedisCache tokens;PurchaseRequestMapper requests;MockedStatic<SecurityUtils> security;LoginUser current;
|
||||
Map<String,Map<String,Object>> members;Map<String,String> leases;ObjectMapper json=new ObjectMapper();
|
||||
LoginUser login(long id,String name){var user=new SysUser();user.setUserId(id);user.setUserName(name);user.setNickName(name);var login=new LoginUser(id,1L,user,Set.of("warehouse:purchase:list","warehouse:purchase:edit","warehouse:purchase:add"));login.setToken("session-"+id);return login;}
|
||||
@BeforeEach void setup()throws Exception{
|
||||
store=mock(PurchaseLiveStore.class);db=mock(JdbcTemplate.class);tokens=mock(RedisCache.class);requests=mock(PurchaseRequestMapper.class);members=new HashMap<>();leases=new HashMap<>();current=login(7,"alice");
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getLoginUser).thenAnswer(c->current);security.when(SecurityUtils::getUserId).thenAnswer(c->current.getUserId());security.when(SecurityUtils::getUsername).thenAnswer(c->current.getUsername());security.when(()->SecurityUtils.hasPermi(anyString())).thenReturn(true);security.when(()->SecurityUtils.hasPermi(any(Collection.class),anyString())).thenReturn(true);
|
||||
when(db.queryForList("select id from purchase_batch where id=?",10L)).thenReturn(List.of(Map.of("id",10L)));
|
||||
when(db.queryForObject(startsWith("select exists"),eq(Boolean.class),anyLong())).thenAnswer(c->c.getArgument(2,Long.class)==7L);
|
||||
var row=new PurchaseRequest();row.setId(1L);row.setPurchaseBatchId(10L);row.setCreateBy("alice");row.setBatchCreateBy("bob");row.setMaterialName("测试物品");row.setPurchaseStatus(0);when(requests.selectPurchaseRequestById(1L,null)).thenReturn(row);
|
||||
when(store.members(10L)).thenAnswer(c->new ArrayList<>(members.values()));when(store.get(eq(10L),anyString())).thenAnswer(c->members.get(c.getArgument(1)));
|
||||
doAnswer(c->{var m=new LinkedHashMap<>((Map<String,Object>)c.getArgument(1));members.put(m.get("clientId").toString(),m);return null;}).when(store).join(eq(10L),anyMap());
|
||||
when(store.lease(anyLong(),anyString(),anyString())).thenAnswer(c->c.getArgument(1)+":"+c.getArgument(2));
|
||||
when(store.holder(anyLong(),anyString(),anyString())).thenAnswer(c->leases.get(c.getArgument(1)+":"+c.getArgument(2)));
|
||||
when(store.write(eq(10L),anyMap())).thenAnswer(c->{var next=(Map<String,Object>)c.getArgument(1);String key=next.get("lease").toString(),client=next.get("clientId").toString();if(!key.isEmpty()&&leases.containsKey(key)&&!client.equals(leases.get(key)))return leases.get(key);var old=members.get(client);if(old!=null)leases.remove(old.get("lease"),client);if(!key.isEmpty())leases.put(key,client);members.put(client,new LinkedHashMap<>(next));return null;});
|
||||
doAnswer(c->{members.remove(c.getArgument(1));return null;}).when(store).leave(anyLong(),anyString(),anyString());
|
||||
when(tokens.getCacheObject(startsWith(CacheConstants.LOGIN_TOKEN_KEY))).thenAnswer(c->login(c.getArgument(0,String.class).endsWith("7")?7:8,"connected"));
|
||||
when(store.decode(anyString())).thenAnswer(c->json.readValue(c.getArgument(0,String.class),Map.class));
|
||||
service=new PurchaseLiveService(store,tokens,db,requests);
|
||||
doAnswer(c->{var message=mock(Message.class);when(message.getBody()).thenReturn(json.writeValueAsString(c.getArgument(0)).getBytes(StandardCharsets.UTF_8));service.onMessage(message,null);return null;}).when(store).publish(anyMap());
|
||||
}
|
||||
@AfterEach void cleanup(){service.stop();security.close();RequestContextHolder.resetRequestAttributes();}
|
||||
PurchaseLiveService.State state(String client,long seq,String field,Object value){return new PurchaseLiveService.State(client,seq,1L,null,field,true,value,true);}
|
||||
@Test void relatedCellLeasePreventsOverlappingEditsAndSpoofedClientsCannotPublish(){
|
||||
service.open(10,A);service.state(10,state(A,1,"materialName","新增名字"));current=login(8,"bob");service.open(10,B);
|
||||
assertThrows(ServiceException.class,()->service.state(10,state(B,1,"materialParams","不能同时改规格")));
|
||||
assertDoesNotThrow(()->service.state(10,state(B,2,"remark","可以同时改备注")));
|
||||
assertThrows(ServiceException.class,()->service.state(10,state(A,3,"remark","冒用别人的窗口")));
|
||||
}
|
||||
@Test void backendOwnershipAndQuotationGateApplyBeforeLiveDraftBroadcast(){
|
||||
service.open(10,A);current=login(9,"outsider");service.open(10,B);
|
||||
assertThrows(ServiceException.class,()->service.state(10,state(B,1,"quantity",100)));
|
||||
current=login(8,"bob");members.get(B).put("userId",8L);members.get(B).put("token",current.getToken());
|
||||
assertThrows(ServiceException.class,()->service.state(10,state(B,2,"finalUnitPrice",100)));
|
||||
assertThrows(ServiceException.class,()->service.state(10,new PurchaseLiveService.State(B,3,999L,null,"remark",true,"跨批次",true)));
|
||||
}
|
||||
@Test void publicPresenceNeverContainsSessionTokensAndEmployeesNeverReceiveDraftQuotation(){
|
||||
var raw=new LinkedHashMap<String,Object>();raw.put("clientId",A);raw.put("userId",7L);raw.put("token","secret-session");raw.put("lease","private-key");raw.put("field","finalUnitPrice");raw.put("rowId",1L);raw.put("editing",true);raw.put("draft",Map.of("field","finalUnitPrice","value",12345));
|
||||
var employee=PurchaseLiveService.publicMember(raw,false);assertNull(employee.get("draft"));assertNull(employee.get("field"));assertFalse(employee.containsKey("token"));assertFalse(employee.containsKey("lease"));assertNotNull(PurchaseLiveService.publicMember(raw,true).get("draft"));
|
||||
}
|
||||
@Test void procurementManagerCanEditForeignRowsAndBatchHeaderButStillHonorsLiveLeases(){
|
||||
current=login(20,"manager");
|
||||
var role=new com.ruoyi.common.core.domain.entity.SysRole();role.setRoleKey("purchase_manager");role.setStatus("0");role.setDelFlag("0");current.getUser().setRoles(List.of(role));current.setPermissions(Set.of());
|
||||
security.when(()->SecurityUtils.hasPermi(anyString())).thenCallRealMethod();
|
||||
when(db.queryForList("select create_by from purchase_batch where id=?",10L)).thenReturn(List.of(Map.of("create_by","old-owner")));
|
||||
when(db.queryForObject(startsWith("select exists"),eq(Boolean.class),eq(20L))).thenReturn(true);
|
||||
service.open(10,A);
|
||||
assertDoesNotThrow(()->service.state(10,state(A,1,"quantity",4)));
|
||||
assertDoesNotThrow(()->service.state(10,new PurchaseLiveService.State(A,2,null,null,"batch",true,null,false)));
|
||||
assertDoesNotThrow(()->service.state(10,state(A,3,"finalUnitPrice",123)));
|
||||
leases.put("row-1:quantity",B);
|
||||
assertThrows(ServiceException.class,()->service.state(10,state(A,4,"quantity",5)));
|
||||
}
|
||||
@Test void nativeSheetSaveGuardRejectsAnyOtherWindowsLeaseIncludingOfflineEdits(){
|
||||
service.open(10,A);service.state(10,state(A,1,"quantity",2));var check=new PurchaseSheetEditingCheck(10L,List.of(new PurchaseSheetEditingCheck.Cell(1L,"quantity")));
|
||||
assertThrows(ServiceException.class,()->service.check(check));var request=new MockHttpServletRequest();request.addHeader("X-Purchase-Live-Client",A);RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));assertDoesNotThrow(()->service.check(check));current=login(8,"bob");assertThrows(ServiceException.class,()->service.check(check));
|
||||
}
|
||||
@Test void sseProducesImmediateUtf8PresenceAndDisablesProxyBuffering()throws Exception{
|
||||
MockMvc mvc=MockMvcBuilders.standaloneSetup(new PurchaseLiveController(service)).build();var result=mvc.perform(get("/warehouse/purchase/sheet/10/live").param("clientId",A)).andReturn();assertTrue(result.getRequest().isAsyncStarted());assertEquals("no",result.getResponse().getHeader("X-Accel-Buffering"));assertEquals("no-store",result.getResponse().getHeader("Cache-Control"));
|
||||
long end=System.currentTimeMillis()+1500;while(result.getResponse().getContentAsString().isEmpty()&&System.currentTimeMillis()<end)Thread.sleep(10);assertTrue(result.getResponse().getContentAsString().contains("event:hello"));assertFalse(result.getResponse().getContentAsString().contains("session-7"));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
package com.ruoyi.common.utils;
|
||||
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import java.util.Set;
|
||||
|
||||
/** The active procurement manager role grants procurement actions, never system-wide privileges. */
|
||||
public final class PurchasePermissions {
|
||||
public static final String ROLE_KEY = "purchase_manager";
|
||||
public static final Set<String> ACTIONS = Set.of(
|
||||
"warehouse:purchase:list", "warehouse:purchase:query", "warehouse:purchase:add",
|
||||
"warehouse:purchase:edit", "warehouse:purchase:remove", "warehouse:purchase:import",
|
||||
"warehouse:purchase:export", "warehouse:purchase:manage");
|
||||
|
||||
private PurchasePermissions() { }
|
||||
|
||||
public static boolean isManager(SysUser user) {
|
||||
return user != null && user.getRoles() != null && user.getRoles().stream().anyMatch(role ->
|
||||
role != null && ROLE_KEY.equals(role.getRoleKey())
|
||||
&& "0".equals(role.getStatus()) && "0".equals(role.getDelFlag()));
|
||||
}
|
||||
|
||||
public static boolean isManager(LoginUser login) {
|
||||
return login != null && isManager(login.getUser());
|
||||
}
|
||||
|
||||
public static boolean grants(LoginUser login, String permission) {
|
||||
return permission != null && ACTIONS.contains(permission.trim()) && isManager(login);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
/** Payload contains identifiers only; subscribers reload with their own permissions after commit. */
|
||||
public record PurchaseSheetChanged(Long batchId,Long requestId) { }
|
||||
@ -0,0 +1,7 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
import java.util.List;
|
||||
/** Synchronous, pre-write cell lease validation; listeners may reject the transaction. */
|
||||
public record PurchaseSheetEditingCheck(Long batchId,List<Cell> cells) {
|
||||
public record Cell(Long rowId,String field){}
|
||||
}
|
||||
@ -0,0 +1,113 @@
|
||||
package com.ruoyi.warehouse.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.util.PurchaseQuoteAccess;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.BeanWrapperImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Three-way merge against a server-held, account-bound baseline, under the sheet's DB locks.
|
||||
* No client-supplied baseline or read-only properties are trusted as persisted state.
|
||||
*/
|
||||
@Service
|
||||
public class PurchaseSheetCollaboration {
|
||||
private final RedisCache cache;
|
||||
private final ObjectMapper json;
|
||||
public PurchaseSheetCollaboration(RedisCache cache,ObjectMapper json){this.cache=cache;this.json=json;}
|
||||
private static final List<List<String>> HEADER=List.of(List.of("batchName"),List.of("supplierId"),List.of("businessDate"),List.of("progressRemark"),List.of("expenseCategoryId"));
|
||||
private static final List<List<String>> DETAIL=List.of(
|
||||
List.of("productId","productCode","materialName","materialBrand","materialParams","unit","category"),
|
||||
List.of("projectId","projectCode","productionTaskId"),List.of("expenseCategoryId","expenseCategoryCode"),
|
||||
List.of("purchasePurpose","loanId"),List.of("quantity"),List.of("finalUnitPrice"),List.of("actualUnitPrice"),List.of("purchaseLink"),List.of("remark"));
|
||||
private static final Map<String,String> LABELS=Map.ofEntries(
|
||||
Map.entry("batchName","批次名称"),Map.entry("supplierId","供应商"),Map.entry("businessDate","日期"),Map.entry("progressRemark","批次备注"),
|
||||
Map.entry("expenseCategoryId","费用类别"),Map.entry("productId","物品、品牌、规格、单位和类别"),Map.entry("projectId","所属项目和生产计划"),
|
||||
Map.entry("purchasePurpose","采购用途"),Map.entry("quantity","数量"),Map.entry("finalUnitPrice","报价单价"),
|
||||
Map.entry("actualUnitPrice","实际单价"),Map.entry("purchaseLink","链接"),Map.entry("remark","备注"));
|
||||
public void remember(PurchaseSheet sheet){
|
||||
if(sheet==null||sheet.getVersion()==null)return;
|
||||
try{cache.setCacheObject(key(sheet),json.writeValueAsString(sheet),24,TimeUnit.HOURS);}
|
||||
catch(com.fasterxml.jackson.core.JsonProcessingException e){throw new IllegalStateException(e);}
|
||||
}
|
||||
private String key(PurchaseSheet sheet){return "purchase:sheet:baseline:"+SecurityUtils.getUserId()+":"+(sheet.getBatch()==null?null:sheet.getBatch().getId())+":"+sheet.getVersion();}
|
||||
public PurchaseSheet merge(PurchaseSheet input,PurchaseSheet latest){
|
||||
String encoded=cache.getCacheObject(key(input));
|
||||
if(encoded==null)throw new ServiceException("编辑快照已过期,请保留本机草稿后重新打开批次,再核对修改;当前内容未丢失",409);
|
||||
PurchaseSheet base;
|
||||
try{base=json.readValue(encoded,PurchaseSheet.class);}catch(Exception e){throw new IllegalStateException("Cannot read collaboration baseline",e);}
|
||||
if(!Objects.equals(base.getVersion(),input.getVersion())||!Objects.equals(base.getBatch().getId(),latest.getBatch().getId()))throw new ServiceException("编辑快照不匹配,请重新打开批次");
|
||||
remember(latest);
|
||||
var conflicts=new ArrayList<Conflict>();
|
||||
var result=new PurchaseSheet();result.setVersion(latest.getVersion());result.setSubmissionKey(input.getSubmissionKey());result.setUnbatched(input.isUnbatched());result.setCollaborationMerged(true);
|
||||
var header=new PurchaseBatch();BeanUtils.copyProperties(latest.getBatch(),header);
|
||||
if(!input.isUnbatched())mergeFields(base.getBatch(),input.getBatch(),latest.getBatch(),header,HEADER,null,"批次信息",conflicts);
|
||||
result.setBatch(header);
|
||||
var originals=index(base.getRows());var current=index(latest.getRows());var submitted=index(input.getRows());
|
||||
var deletes=new LinkedHashSet<>(input.getDeletedIds()==null?List.<Long>of():input.getDeletedIds());
|
||||
if(deletes.size()!=(input.getDeletedIds()==null?0:input.getDeletedIds().size())||deletes.contains(null))throw new ServiceException("删除明细重复或无效");
|
||||
var covered=new HashSet<>(submitted.keySet());
|
||||
for(Long id:deletes)if(!covered.add(id))throw new ServiceException("明细不能同时修改和删除");
|
||||
if(!covered.equals(originals.keySet()))throw new ServiceException("原清单明细不完整或混入其他批次,当前内容未保存");
|
||||
var rows=new ArrayList<PurchaseRequest>();var removed=new ArrayList<Long>();
|
||||
for(var server:latest.getRows()){
|
||||
Long id=server.getId();var original=originals.get(id);var mine=submitted.get(id);
|
||||
if(original==null){rows.add(server);continue;} // Keep another editor's newly created rows.
|
||||
if(deletes.contains(id)){
|
||||
if(!sameRow(original,server))throw new ServiceException("“"+server.getMaterialName()+"”已被他人修改,不能直接删除;请保留草稿并核对该行",409);
|
||||
removed.add(id);continue;
|
||||
}
|
||||
PurchaseQuoteAccess.preserveQuotation(mine,original);
|
||||
if(!mine.isActualUnitPriceProvided())mine.setActualUnitPrice(original.getActualUnitPrice());
|
||||
var merged=new PurchaseRequest();BeanUtils.copyProperties(server,merged);
|
||||
mergeFields(original,mine,server,merged,DETAIL,id,server.getMaterialName(),conflicts);
|
||||
rows.add(merged);
|
||||
}
|
||||
for(var original:base.getRows())if(!current.containsKey(original.getId())&&!deletes.contains(original.getId())){
|
||||
var mine=submitted.get(original.getId());PurchaseQuoteAccess.preserveQuotation(mine,original);
|
||||
if(!sameRow(original,mine))throw new ServiceException("“"+original.getMaterialName()+"”已被删除或转批次;你的修改仍在草稿中,请核对后另存该行",409);
|
||||
}
|
||||
input.getRows().stream().filter(row->row.getId()==null).forEach(rows::add);
|
||||
result.setRows(rows);result.setDeletedIds(removed);
|
||||
if(!conflicts.isEmpty())throw new ConflictException(latest,result,conflicts);
|
||||
return result;
|
||||
}
|
||||
private Map<Long,PurchaseRequest> index(List<PurchaseRequest> rows){
|
||||
var result=new LinkedHashMap<Long,PurchaseRequest>();
|
||||
if(rows==null)throw new ServiceException("采购明细不能为空");
|
||||
for(var row:rows){if(row==null)throw new ServiceException("采购明细不能为空");if(row.getId()!=null&&result.put(row.getId(),row)!=null)throw new ServiceException("采购明细重复");}
|
||||
return result;
|
||||
}
|
||||
private boolean sameRow(PurchaseRequest a,PurchaseRequest b){
|
||||
return DETAIL.stream().flatMap(List::stream).allMatch(field->same(value(a,field),value(b,field)))
|
||||
&&Objects.equals(a.getPriceLocked(),b.getPriceLocked())&&Objects.equals(a.getPurchaseStatus(),b.getPurchaseStatus())
|
||||
&&same(a.getAcceptedQuantity(),b.getAcceptedQuantity())&&same(a.getPendingArrivalQuantity(),b.getPendingArrivalQuantity());
|
||||
}
|
||||
private void mergeFields(Object base,Object mine,Object current,Object target,List<List<String>> groups,Long rowId,String rowName,List<Conflict> conflicts){
|
||||
for(var group:groups){
|
||||
boolean changed=group.stream().anyMatch(field->!same(value(base,field),value(mine,field)));
|
||||
if(!changed)continue;
|
||||
boolean concurrent=group.stream().anyMatch(field->!same(value(base,field),value(current,field)));
|
||||
boolean equal=group.stream().allMatch(field->same(value(mine,field),value(current,field)));
|
||||
if(concurrent&&!equal){conflicts.add(new Conflict(rowId,rowName,LABELS.get(group.get(0)),group,values(mine,group),values(current,group)));continue;}
|
||||
var writable=new BeanWrapperImpl(target);for(String field:group)writable.setPropertyValue(field,value(mine,field));
|
||||
}
|
||||
}
|
||||
private Map<String,Object> values(Object bean,List<String> fields){var result=new LinkedHashMap<String,Object>();fields.forEach(field->result.put(field,value(bean,field)));return result;}
|
||||
private Object value(Object bean,String field){return new BeanWrapperImpl(bean).getPropertyValue(field);}
|
||||
private boolean same(Object a,Object b){
|
||||
if(a==null||"".equals(a))return b==null||"".equals(b);
|
||||
if(a instanceof Number&&b instanceof Number)return new java.math.BigDecimal(a.toString()).compareTo(new java.math.BigDecimal(b.toString()))==0;
|
||||
return Objects.equals(a,b);
|
||||
}
|
||||
public record Conflict(Long rowId,String rowName,String label,List<String> fields,Map<String,Object> mine,Map<String,Object> current){}
|
||||
public static class ConflictException extends RuntimeException {
|
||||
public final PurchaseSheet latest,proposed;public final List<Conflict> conflicts;
|
||||
ConflictException(PurchaseSheet latest,PurchaseSheet proposed,List<Conflict> conflicts){super("有 "+conflicts.size()+" 处内容被同时修改,请选择保留哪一份;其余修改已合并");this.latest=latest;this.proposed=proposed;this.conflicts=List.copyOf(conflicts);}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package com.ruoyi.warehouse.util;
|
||||
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.PurchasePermissions;
|
||||
import com.ruoyi.warehouse.domain.PurchaseBatch;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
|
||||
/** Ownership is an additional restriction; it never grants menu or quotation permissions. */
|
||||
public final class PurchaseDataAccess {
|
||||
private PurchaseDataAccess() {}
|
||||
public static boolean managesAll() {
|
||||
try{return SecurityUtils.isAdmin() || PurchasePermissions.isManager(SecurityUtils.getLoginUser());}
|
||||
catch(ServiceException unauthenticated){return false;}
|
||||
}
|
||||
public static boolean canEdit(String creator, String batchCreator) {
|
||||
return managesAll() || owns(creator) || owns(batchCreator);
|
||||
}
|
||||
public static boolean owns(String creator) {
|
||||
try{return creator != null && !creator.isBlank() && creator.equals(SecurityUtils.getUsername());}
|
||||
catch(ServiceException unauthenticated){return false;}
|
||||
}
|
||||
public static boolean canEdit(PurchaseRequest row) {
|
||||
try{return row != null && canEdit(row.getCreateBy(), row.getBatchCreateBy());}
|
||||
catch(ServiceException unauthenticated){return false;}
|
||||
}
|
||||
public static boolean canEdit(PurchaseBatch batch) {
|
||||
try{return batch != null && canEdit(batch.getCreateBy(), null);}
|
||||
catch(ServiceException unauthenticated){return false;}
|
||||
}
|
||||
public static void require(PurchaseRequest row) {
|
||||
if (!canEdit(row)) throw new ServiceException("仅明细创建人、批次创建人、采购管理员或超级管理员可以维护", 403);
|
||||
}
|
||||
public static void require(PurchaseBatch batch) {
|
||||
if (!canEdit(batch)) throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以维护批次信息", 403);
|
||||
}
|
||||
}
|
||||
34
ruoyi-ui-vue3/src/components/PurchaseSheet/Presence.vue
Normal file
34
ruoyi-ui-vue3/src/components/PurchaseSheet/Presence.vue
Normal file
@ -0,0 +1,34 @@
|
||||
<template>
|
||||
<el-popover v-if="state.enabled" v-model:visible="open" placement="bottom-end" trigger="click" :width="340" popper-class="purchase-presence-panel">
|
||||
<template #reference>
|
||||
<button type="button" class="sheet-presence" :class="{warning:!!state.issue}" :title="state.issue||state.saveStatus||state.status" aria-haspopup="dialog" :aria-expanded="open" aria-label="查看在线人员和同步状态">
|
||||
<span class="presence-dot" :class="{online:state.connected}"/>
|
||||
<span>{{state.connected?state.peers.length+' 人在线':state.status}}</span>
|
||||
<span v-if="state.connected" class="presence-avatars" aria-hidden="true"><span v-for="peer in preview" :key="peer.clientId" class="presence-avatar" :style="{background:livePresenceColor(peer)}" :title="peer.name">{{(peer.name||'?').slice(0,1)}}</span></span>
|
||||
<span v-if="editing" class="presence-save" role="status">{{saveLabel}}</span><span class="presence-arrow" aria-hidden="true"/>
|
||||
</button>
|
||||
</template>
|
||||
<div v-if="open" class="presence-panel" role="dialog" aria-label="在线人员和同步状态">
|
||||
<div class="presence-panel-heading"><strong>实时协同</strong><span>{{state.connected?state.peers.length+' 人在线':state.status}}</span></div>
|
||||
<div class="presence-members"><div v-for="peer in state.peers" :key="peer.clientId" class="presence-member"><span class="presence-avatar" :style="{background:livePresenceColor(peer)}">{{(peer.name||'?').slice(0,1)}}</span><div><strong>{{peer.name}}{{peer.clientId===state.clientId?'(我)':''}}</strong><span>{{position(peer)}}</span></div></div><div v-if="!state.peers.length" class="presence-empty">连接恢复后显示在线人员</div></div>
|
||||
<div class="presence-panel-status" :class="{warning:!!state.issue}" role="status">{{state.issue||state.saveStatus||(editing?'有效修改将自动保存':state.status)}}</div>
|
||||
<el-button v-if="state.issue" link type="primary" size="small" @click="$emit('retry')">重试连接 / 保存</el-button>
|
||||
</div>
|
||||
</el-popover>
|
||||
</template>
|
||||
<script setup>
|
||||
import {computed,ref} from 'vue'
|
||||
import {livePresenceColor} from '@/utils/purchase-live-presence'
|
||||
const props=defineProps({state:{type:Object,required:true},editing:Boolean,rows:{type:Array,default:()=>[]},columns:{type:Array,default:()=>[]}})
|
||||
defineEmits(['retry'])
|
||||
const open=ref(false),preview=computed(()=>props.state.peers.slice(0,3))
|
||||
const positions=computed(()=>new Map(props.rows.map((row,index)=>[String(row.id),index+1])))
|
||||
const fields=computed(()=>new Map(props.columns.map(column=>[column.field,column.label])))
|
||||
const saveLabel=computed(()=>{const state=props.state;if(state.issue)return state.connected?'待处理':'草稿已保留';if(state.saving)return '保存中';if(!props.editing)return '';if(state.saveStatus==='已自动保存')return '已保存';if(state.saveStatus?.includes('待完善'))return '待完善';return '自动保存'})
|
||||
function position(peer){if(!peer.editing)return '正在查看';if(peer.field==='batch')return '正在维护批次信息';if(peer.rowKey)return '正在新增明细';return '正在编辑第 '+(positions.value.get(String(peer.rowId))||'—')+' 行 '+(fields.value.get(peer.field)||peer.field)}
|
||||
</script>
|
||||
<style scoped>
|
||||
.sheet-presence{display:inline-flex;align-items:center;gap:6px;flex:none;max-width:235px;height:27px;white-space:nowrap;border:1px solid var(--el-border-color-lighter);border-radius:15px;background:var(--el-fill-color-extra-light);color:var(--el-text-color-regular);padding:0 9px;font:inherit;font-size:12px;cursor:pointer}.sheet-presence:hover{border-color:var(--el-color-primary-light-5);background:var(--el-color-primary-light-9)}.sheet-presence:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:2px}.presence-dot{width:6px;height:6px;flex:none;border-radius:50%;background:var(--el-color-warning)}.presence-dot.online{background:var(--el-color-success)}.presence-avatars{display:flex;padding-left:3px}.presence-avatar{display:inline-flex;align-items:center;justify-content:center;flex:none;width:21px;height:21px;border-radius:50%;color:#fff;font-size:11px}.presence-avatars .presence-avatar{width:18px;height:18px;border:1px solid var(--el-bg-color);margin-left:-3px}.presence-save{max-width:75px;overflow:hidden;text-overflow:ellipsis;color:var(--el-text-color-secondary);border-left:1px solid var(--el-border-color);padding-left:7px}.presence-arrow{width:5px;height:5px;border-right:1px solid currentColor;border-bottom:1px solid currentColor;transform:rotate(45deg);margin:0 1px 3px 0;opacity:.6}.warning,.warning .presence-save{color:var(--el-color-warning-dark-2)}
|
||||
.presence-panel{font-size:12px}.presence-panel-heading{display:flex;align-items:center;justify-content:space-between;padding-bottom:10px;border-bottom:1px solid var(--el-border-color-lighter)}.presence-panel-heading>span{color:var(--el-text-color-secondary)}.presence-members{max-height:260px;overflow:auto;padding:5px 0}.presence-member{display:flex;gap:9px;padding:8px 0;align-items:center}.presence-member>div{min-width:0;display:flex;flex-direction:column;gap:3px}.presence-member strong{font-weight:500;color:var(--el-text-color-primary)}.presence-member div>span{color:var(--el-text-color-secondary);overflow-wrap:anywhere}.presence-empty{padding:12px 0;color:var(--el-text-color-secondary)}.presence-panel-status{padding-top:10px;border-top:1px solid var(--el-border-color-lighter);line-height:1.6;overflow-wrap:anywhere}
|
||||
@media(max-width:1100px){.presence-avatars{display:none}.sheet-presence{gap:5px;padding:0 7px}}
|
||||
</style>
|
||||
59
ruoyi-ui-vue3/src/utils/purchase-live-data.js
Normal file
59
ruoyi-ui-vue3/src/utils/purchase-live-data.js
Normal file
@ -0,0 +1,59 @@
|
||||
export const liveRowFields=['id','requestNo','projectId','projectCode','expenseCategoryId','expenseCategoryCode','productionTaskId','productId','productCode','materialName','materialBrand','materialParams','category','unit','purchasePurpose','loanId','purchaseLink','remark','requestRemark','quantity','finalUnitPrice','actualUnitPrice']
|
||||
const headerFields=['id','supplierId','batchName','businessDate','progressRemark','expenseCategoryId']
|
||||
export const liveGroups=[['productId','productCode','materialName','materialBrand','materialParams','unit','category'],['projectId','projectCode','productionTaskId'],['expenseCategoryId','expenseCategoryCode'],['purchasePurpose','loanId'],['quantity'],['finalUnitPrice'],['actualUnitPrice'],['purchaseLink'],['remark']]
|
||||
const headerGroups=headerFields.filter(f=>f!=='id').map(f=>[f])
|
||||
const labels={productId:'物品、品牌、规格、单位和类别',projectId:'项目和生产计划',expenseCategoryId:'费用类别',purchasePurpose:'采购用途',quantity:'数量',finalUnitPrice:'报价单价',actualUnitPrice:'实际单价',purchaseLink:'链接',remark:'备注',batchName:'批次名称',businessDate:'日期',supplierId:'供应商',progressRemark:'批次备注'}
|
||||
export const cloneLive=value=>JSON.parse(JSON.stringify(value))
|
||||
export function sameLive(a,b){if(a==null||a==='')return b==null||b==='';return Object.is(a,b)||((typeof a==='number'||typeof b==='number')&&String(a).trim()!==''&&String(b??'').trim()!==''&&Number.isFinite(Number(a))&&Number(a)===Number(b))}
|
||||
export const liveGroup=field=>liveGroups.find(g=>g.includes(field))?.[0]||field
|
||||
const pick=(object,fields)=>Object.fromEntries(fields.map(f=>[f,object?.[f]??null]))
|
||||
const delta=(a,b,fields)=>Object.fromEntries(fields.filter(f=>!sameLive(a?.[f],b?.[f])).map(f=>[f,b?.[f]??null]))
|
||||
|
||||
/** Compact immutable attempt: reconstruct retries from the unchanged local baseline, never current keystrokes. */
|
||||
export function createLiveAttempt(base,current,key){
|
||||
const old=new Map(base.rows.map(r=>[r._key,r]))
|
||||
return {key,version:base.version,order:current.rows.map(r=>r._key),rows:current.rows.map(r=>({key:r._key,changes:old.has(r._key)?delta(old.get(r._key),r,liveRowFields):pick(r,liveRowFields)})).filter(r=>Object.keys(r.changes).length),batch:delta(base.batch,current.batch,headerFields),deletedIds:[...(current.deletedIds||[])]}
|
||||
}
|
||||
export function liveAttemptSheet(base,attempt){
|
||||
if(base.version!==attempt.version)throw Error('自动保存快照不匹配,请保留草稿并核对上次保存结果')
|
||||
const old=new Map(base.rows.map(r=>[r._key,r])),changes=new Map(attempt.rows.map(r=>[r.key,r.changes]))
|
||||
return {batch:{...base.batch,...attempt.batch},rows:attempt.order.map(key=>({...old.get(key),...changes.get(key),_key:key,clientRowKey:key})),version:attempt.version,deletedIds:attempt.deletedIds,submissionKey:attempt.key}
|
||||
}
|
||||
|
||||
/** Preserve unsent local keystrokes while adopting committed remote data and newly assigned row IDs. */
|
||||
export function rebaseLiveSheet(base,local,server,accepted=null){
|
||||
const mapping=new Map(Object.entries(server.clientRowIds||{}).map(([key,id])=>[String(id),key]))
|
||||
const oldById=new Map(base.rows.filter(r=>r.id).map(r=>[String(r.id),r])),oldByKey=new Map(base.rows.map(r=>[r._key,r]))
|
||||
const localByKey=new Map(local.rows.map(r=>[r._key,r])),localById=new Map(local.rows.filter(r=>r.id).map(r=>[String(r.id),r]))
|
||||
const latest=cloneLive(server);latest.deletedIds=[];delete latest.livePending;latest.submissionKey=null
|
||||
latest.rows=latest.rows.map(r=>({...r,_key:localById.get(String(r.id))?._key||mapping.get(String(r.id))||'saved-'+r.id}))
|
||||
const proposed=cloneLive(latest),conflicts=[],changed=new Map((accepted?.rows||[]).map(r=>[r.key,r.changes]))
|
||||
function merge(old,mine,theirs,target,groups,rowId,rowName,key){
|
||||
for(const fields of groups){if(!fields.some(f=>!sameLive(old?.[f],mine?.[f])))continue
|
||||
const other=fields.some(f=>!sameLive(old?.[f],theirs?.[f])),equal=fields.every(f=>sameLive(mine?.[f],theirs?.[f]))
|
||||
const ownAccepted=accepted&&(rowId==null?fields.some(f=>Object.hasOwn(accepted.batch||{},f)):!old?.id||fields.some(f=>Object.hasOwn(changed.get(key)||{},f)))
|
||||
if(other&&!equal&&!ownAccepted){conflicts.push({rowId,rowName,label:labels[fields[0]]||fields[0],fields,mine:pick(mine,fields),current:pick(theirs,fields)});continue}
|
||||
for(const f of fields)target[f]=mine[f]??null
|
||||
}
|
||||
}
|
||||
merge(base.batch,local.batch,latest.batch,proposed.batch,headerGroups,null,'批次信息',null)
|
||||
const serverIds=new Set(latest.rows.map(r=>String(r.id))),deleted=new Set((local.deletedIds||[]).map(String));proposed.deletedIds=[]
|
||||
proposed.rows=proposed.rows.filter(row=>{
|
||||
const mine=localByKey.get(row._key)||localById.get(String(row.id)),old=oldById.get(String(row.id))||oldByKey.get(row._key)
|
||||
if(accepted&&mapping.has(String(row.id))&&old&&!old.id&&!mine){proposed.deletedIds.push(row.id);return false}
|
||||
if(deleted.has(String(row.id))){if(old&&liveRowFields.some(f=>f!=='id'&&!sameLive(old[f],row[f]))){conflicts.push({kind:'deleted',rowName:row.materialName,rowId:row.id});return true}proposed.deletedIds.push(row.id);return false}
|
||||
if(mine&&old)merge(old,mine,latest.rows.find(r=>r.id===row.id),row,liveGroups,row.id,row.materialName,row._key)
|
||||
return true
|
||||
})
|
||||
for(const row of local.rows){
|
||||
if(!row.id&&!proposed.rows.some(r=>r._key===row._key)){proposed.rows.push(cloneLive(row));continue}
|
||||
const old=oldById.get(String(row.id));if(row.id&&!serverIds.has(String(row.id))&&old&&liveRowFields.some(f=>f!=='id'&&!sameLive(old[f],row[f])))conflicts.push({kind:'removed',rowId:row.id,rowName:row.materialName})
|
||||
}
|
||||
return {latest,proposed,conflicts}
|
||||
}
|
||||
|
||||
/** Fetch chunks can split UTF-8 characters and SSE frames; only complete data events are delivered. */
|
||||
export function createLiveEventParser(deliver){
|
||||
let buffered=''
|
||||
return text=>{buffered+=text;let match;while((match=/\r?\n\r?\n/.exec(buffered))){const frame=buffered.slice(0,match.index);buffered=buffered.slice(match.index+match[0].length);let event='message';const data=[];for(const line of frame.split(/\r?\n/)){if(line.startsWith('event:'))event=line.slice(6).trim();if(line.startsWith('data:'))data.push(line.slice(5).trimStart())}if(data.length)deliver(event,JSON.parse(data.join('\n')))}if(buffered.length>512*1024)throw Error('协同消息过长,连接将重新建立')}
|
||||
}
|
||||
35
ruoyi-ui-vue3/src/utils/purchase-live-presence.js
Normal file
35
ruoyi-ui-vue3/src/utils/purchase-live-presence.js
Normal file
@ -0,0 +1,35 @@
|
||||
import {shallowReactive} from 'vue'
|
||||
import {liveGroup,sameLive} from './purchase-live-data.js'
|
||||
|
||||
const fields=['clientId','userId','name','rowId','rowKey','rowName','field','editing']
|
||||
const unchanged=(a,b)=>a&&fields.every(field=>a[field]===b[field])&&a.draft?.field===b.draft?.field&&sameLive(a.draft?.value,b.draft?.value)
|
||||
const key=(row,field)=>String(row)+'|'+field
|
||||
|
||||
/** Keyed reactive lookups invalidate only the cells affected by a peer's cursor or draft. */
|
||||
export function createLivePresence(state){
|
||||
let members=new Map()
|
||||
const sequences=new Map(),exact=shallowReactive(new Map()),related=shallowReactive(new Map())
|
||||
function sync(target,next){for(const cell of target.keys())if(!next.has(cell))target.delete(cell);for(const [cell,peer] of next)if(target.get(cell)!==peer)target.set(cell,peer)}
|
||||
function update(list,replace=false){
|
||||
const next=replace?new Map():new Map(members)
|
||||
for(const peer of list){
|
||||
const prior=members.get(peer.clientId),sequence=Number(peer.sequence)||0,seen=sequences.get(peer.clientId)||0
|
||||
if(prior&&sequence<seen){next.set(peer.clientId,prior);continue}
|
||||
sequences.set(peer.clientId,sequence);next.set(peer.clientId,unchanged(prior,peer)?prior:peer)
|
||||
}
|
||||
if(replace)for(const client of sequences.keys())if(!next.has(client))sequences.delete(client)
|
||||
const changed=next.size!==members.size||[...next].some(([client,peer])=>members.get(client)!==peer)
|
||||
if(!changed)return
|
||||
members=next
|
||||
const cells=new Map(),groups=new Map()
|
||||
for(const peer of members.values())if(peer.clientId!==state.clientId&&peer.editing&&peer.rowId){cells.set(key(peer.rowId,peer.field),peer);groups.set(key(peer.rowId,liveGroup(peer.field)),peer)}
|
||||
sync(exact,cells);sync(related,groups)
|
||||
state.headerBusy=[...members.values()].some(peer=>peer.clientId!==state.clientId&&peer.editing&&peer.field==='batch')
|
||||
state.peers=[...members.values()]
|
||||
}
|
||||
function clear(){members=new Map();sequences.clear();exact.clear();related.clear();state.headerBusy=false;if(state.peers.length)state.peers=[]}
|
||||
return {update,clear,peer(row,field,group=false){return row.id?(group?related:exact).get(key(row.id,group?liveGroup(field):field)):undefined},
|
||||
ghost(row,field){const peer=row.id?exact.get(key(row.id,field)):null;return peer?.draft?.field===field?{...peer.draft,name:peer.name}:null}}
|
||||
}
|
||||
|
||||
export function livePresenceColor(peer){let hash=0;for(const char of String(peer?.userId||peer?.clientId||''))hash=(hash*31+char.charCodeAt(0))>>>0;return ['#168078','#9c4bb0','#3f66c9','#c87720','#b74861','#367b9f'][hash%6]}
|
||||
14
ruoyi-ui-vue3/src/utils/purchase-sheet-conflicts.js
Normal file
14
ruoyi-ui-vue3/src/utils/purchase-sheet-conflicts.js
Normal file
@ -0,0 +1,14 @@
|
||||
/** Resolving a conflict only prepares an editable draft; saving still runs every server rule. */
|
||||
export function resolvePurchaseSheetConflicts(data, choices) {
|
||||
const result = JSON.parse(JSON.stringify(data.proposed))
|
||||
if (choices.length !== data.conflicts.length || choices.some(choice => !['mine', 'current'].includes(choice))) {
|
||||
throw new Error('请逐项选择保留我的内容或最新内容')
|
||||
}
|
||||
data.conflicts.forEach((conflict, index) => {
|
||||
const target = conflict.rowId == null ? result.batch : result.rows.find(row => String(row.id) === String(conflict.rowId))
|
||||
if (!target) throw new Error('冲突明细已变化,请重新校验')
|
||||
for (const field of conflict.fields) target[field] = conflict[choices[index]][field]
|
||||
})
|
||||
result.submissionKey = null
|
||||
return result
|
||||
}
|
||||
135
ruoyi-ui-vue3/src/utils/purchase-sheet-live.js
Normal file
135
ruoyi-ui-vue3/src/utils/purchase-sheet-live.js
Normal file
@ -0,0 +1,135 @@
|
||||
import {createLivePresence} from './purchase-live-presence'
|
||||
import {getToken} from '@/utils/auth'
|
||||
import {getPurchaseSheet,savePurchaseSheet,getPurchaseSheetSubmission} from '@/api/warehouse/purchase'
|
||||
import {collectRowErrors,validateRows,same} from '@/utils/purchase-sheet'
|
||||
import {cloneLive,createLiveAttempt,liveAttemptSheet,rebaseLiveSheet,createLiveEventParser,sameLive} from './purchase-live-data'
|
||||
|
||||
const id=()=>globalThis.crypto?.randomUUID?.()||'live-'+Date.now()+'-'+Math.random().toString(36).slice(2)
|
||||
const baseUrl=import.meta.env.VITE_APP_BASE_API||'/dev-api'
|
||||
export function createPurchaseLive(vm){
|
||||
let stopped=false,room=null,clientId=id(),sequence=0,stream,heartbeat,retryTimer,saveTimer,pushTimer,refreshTimer,running=null,applying=false,failures=0,lastState={rowId:null,rowKey:null,field:null,editing:false,value:null,typing:false},uncommitted=false,pushChain=Promise.resolve(),needsRefresh=false,pendingText=new Set()
|
||||
const state=vm.live,presence=createLivePresence(state)
|
||||
const endpoint=()=>`${baseUrl}/warehouse/purchase/sheet/${room}/live`
|
||||
const auth=()=>({Authorization:'Bearer '+getToken(),'Content-Type':'application/json'})
|
||||
async function send(method,url,data,options={}){
|
||||
const response=await fetch(url,{method,headers:auth(),body:data?JSON.stringify(data):undefined,cache:'no-store',...options})
|
||||
const result=await response.json();if(!response.ok||result.code&&result.code!==200){const error=new Error(result.msg||'实时协同连接失败');error.code=result.code||response.status;throw error}return result.data
|
||||
}
|
||||
function onEvent(event,data){
|
||||
if(event==='hello'){state.connected=true;state.status='实时协同';state.issue='';failures=0;presence.update(data.peers||[],true);void push();void refresh();scheduleSave()}
|
||||
else if(event==='members')presence.update(data.peers||[],true)
|
||||
else if(event==='member')presence.update([data])
|
||||
else if(event==='saved'){clearTimeout(refreshTimer);refreshTimer=setTimeout(()=>refresh(),120)}
|
||||
}
|
||||
async function connect(){
|
||||
if(stopped||!room)return
|
||||
stream?.abort();stream=new AbortController();state.connected=false;state.status='连接中'
|
||||
try{
|
||||
const response=await fetch(endpoint()+'?clientId='+encodeURIComponent(clientId),{headers:{...auth(),Accept:'text/event-stream, application/json'},signal:stream.signal,cache:'no-store'})
|
||||
if(!response.ok||!response.headers.get('content-type')?.includes('text/event-stream')){const result=await response.json();const error=new Error(result.msg||'实时连接暂不可用');error.code=result.code||response.status;throw error}
|
||||
const parser=createLiveEventParser(onEvent),reader=response.body.getReader(),decoder=new TextDecoder()
|
||||
while(!stopped){const {done,value}=await reader.read();if(done)break;parser(decoder.decode(value,{stream:true}))}
|
||||
if(!stopped)throw Error('实时连接中断')
|
||||
}catch(error){if(stopped||error.name==='AbortError')return;state.connected=false;presence.clear();state.status='离线草稿';state.issue=error.message;vm.persistDraft();if([401,403].includes(error.code))return;retryTimer=setTimeout(connect,Math.min(5000,500*2**Math.min(failures++,4)))}
|
||||
}
|
||||
async function push(next=null){
|
||||
if(next)lastState={...lastState,...next}
|
||||
if(stopped||!room||!state.connected)return false
|
||||
const payload={...lastState,clientId,sequence:++sequence},url=endpoint()+'/state'
|
||||
const task=pushChain.catch(()=>{}).then(()=>send('POST',url,payload))
|
||||
pushChain=task
|
||||
try{await task;return true}catch(error){
|
||||
if(error.code===409){state.issue=error.message;if(lastState.editing){lastState={...lastState,editing:false,typing:false};vm.persistDraft();vm.editCell=null;state.blocked=true}if(error.message.includes('过期')||error.message.includes('重连')){stream?.abort();clearTimeout(retryTimer);retryTimer=setTimeout(connect,250)}}
|
||||
else if([401,403].includes(error.code)){state.issue=error.message;state.blocked=true;vm.persistDraft()}
|
||||
else{state.connected=false;state.status='离线草稿';state.issue='连接中断,本机草稿已保留';stream?.abort();retryTimer=setTimeout(connect,1000)}
|
||||
return false
|
||||
}
|
||||
}
|
||||
function normalize(sheet){const out=cloneLive(sheet);delete out.livePending;out.rows=out.rows.map(row=>({...row,finalUnitPrice:vm.canViewQuotes&&row.finalUnitPrice!=null&&row.finalUnitPrice!==''?Number(row.finalUnitPrice):null,actualUnitPrice:row.actualUnitPrice===''||row.actualUnitPrice===undefined?null:row.actualUnitPrice}));return out}
|
||||
function valid(){
|
||||
if(lastState.typing&&['finalUnitPrice','actualUnitPrice'].includes(lastState.field)&&typeof lastState.value==='string'&&lastState.value!==''&&!/^\d+(?:\.\d+)?$/.test(lastState.value)){state.saveStatus='输入中,草稿实时同步';return false}
|
||||
if(!vm.isEditing||!vm.dirty||vm.saving||vm.conflictOpen||uncommitted||Object.keys(vm.sheet?.liveText||{}).length||state.blocked||vm.sheet?.submissionKey||!vm.sheet?.batch?.expenseCategoryId)return false
|
||||
const rows=vm.activeRows(),changed=rows.filter(r=>(!r.id||vm.changedKeys.has(r._key))&&!vm.referenceOnly(r))
|
||||
if(collectRowErrors(changed,vm.items,changed.map(r=>vm.originalIndex(r)+1),vm.units,vm.activeCategoryLabels).length){state.saveStatus='有待完善内容,本机草稿已保留';vm.validationEnabled=true;return false}
|
||||
try{validateRows(changed,vm.items);if(rows.some(row=>!vm.referenceOnly(row)&&!row.productId&&!vm.units.some(unit=>same(unit,row.unit))))return false}catch{state.saveStatus='有待完善内容,本机草稿已保留';return false}
|
||||
return true
|
||||
}
|
||||
function withText(sheet){const out=cloneLive(sheet);for(const raw of Object.values(sheet.liveText||{})){const row=out.rows.find(r=>r._key===raw.key);if(row)row[raw.field]=raw.value}return out}
|
||||
function mergeRemote(base,local,server,accepted){const probe=rebaseLiveSheet(base,withText(local),server,accepted);return probe.conflicts.length?probe:rebaseLiveSheet(base,local,server,accepted)}
|
||||
function apply(result){
|
||||
if(result.conflicts.length){state.blocked=true;state.saveStatus='有并发内容待核对';vm.persistDraft();
|
||||
if(result.conflicts.some(c=>c.kind)){state.issue='有明细被删除或转移,当前草稿已保留,请核对后另存相关内容';return false}
|
||||
vm.conflictData={latest:result.latest,proposed:result.proposed,conflicts:result.conflicts};vm.conflictChoices=result.conflicts.map(()=>null);vm.conflictOpen=true;return false
|
||||
}
|
||||
applying=true;vm._liveRebasing=true
|
||||
try{
|
||||
vm._editor?.flush();const active=vm.editCell,editing=vm.editing,current=new Map(vm.sheet.rows.map(r=>[r._key,r])),baseIds=new Set((JSON.parse(vm.baseline).rows||[]).map(r=>String(r.id)))
|
||||
const activeSplit=active?.lastIndexOf('|'),activeKey=active?.slice(0,activeSplit),activeField=active?.slice(activeSplit+1),activeRow=current.get(activeKey),oldActive=JSON.parse(vm.baseline).rows.find(r=>r._key===activeKey),preserveRaw=activeRow&&oldActive&&JSON.stringify(activeRow[activeField])!==JSON.stringify(oldActive[activeField]),rawValue=activeRow?.[activeField]
|
||||
const ownKeys=new Set(Object.keys(result.latest.clientRowIds||{})),remoteKeys=result.latest.rows.filter(row=>!baseIds.has(String(row.id))&&!ownKeys.has(row._key)).map(row=>row._key)
|
||||
vm._editor?.acceptRemoteRows?.(remoteKeys)
|
||||
vm.sheet.rows=result.proposed.rows.map(row=>{const existing=current.get(row._key);if(existing){Object.assign(existing,row);if(preserveRaw&&row._key===activeKey)existing[activeField]=rawValue;return existing}return row})
|
||||
Object.assign(vm.sheet.batch,result.proposed.batch);vm.sheet.version=result.latest.version;vm.sheet.deletedIds=result.proposed.deletedIds||[];delete vm.sheet.livePending
|
||||
vm.baseline=vm.serialize(result.latest);vm.editing=editing;vm.editCell=active&&vm.sheet.rows.some(r=>active.startsWith(r._key+'|'))?active:null
|
||||
if(vm.editCell){const split=vm.editCell.lastIndexOf('|'),row=vm.sheet.rows.find(r=>r._key===vm.editCell.slice(0,split));if(row)vm._editor?.beginCell(row,vm.editCell.slice(split+1))}
|
||||
vm.mergeItems(result.latest.rows.filter(r=>r.productId).map(r=>({id:r.productId,productCode:r.productCode,productName:r.materialName,brand:r.materialBrand,spec:r.materialParams,unit:r.unit,category:r.category})))
|
||||
}finally{vm._liveRebasing=false;applying=false}
|
||||
if(vm.dirty)vm.persistDraft();else vm.clearDraft(vm.draftId());return true
|
||||
}
|
||||
async function acceptSaved(response,attempt,sent){
|
||||
if(stopped||Number(vm.sheet?.batch?.id)!==room)return response;const current=cloneLive(vm.sheet);vm._editor?.flush();vm._editor?.acknowledge?.(sent,response)
|
||||
const sentRow=sent.rows.find(r=>r.id&&r.id===lastState.rowId||r._key===lastState.rowKey);if(!uncommitted&&sentRow&&sameLive(lastState.value,sentRow[lastState.field])){lastState={...lastState,typing:false};void push()}
|
||||
delete vm.sheet.livePending;state.saving=false;state.blocked=false;state.saveStatus='已自动保存';state.issue=''
|
||||
const result=mergeRemote(sent,current,response,attempt);apply(result);if(lastState.rowKey){const assigned=response.clientRowIds?.[lastState.rowKey];if(assigned){lastState={...lastState,rowId:assigned,rowKey:null};void push()}}if(vm.dirty)scheduleSave();return response
|
||||
}
|
||||
async function saveOnce(){
|
||||
if(running)return running;if(stopped||!state.connected||!room||!vm.isEditing||vm.saving)return
|
||||
if(!vm.sheet.livePending&&!valid())return
|
||||
running=(async()=>{
|
||||
state.saving=true;state.saveStatus='正在自动保存'
|
||||
let attempt=vm.sheet.livePending,sent
|
||||
try{
|
||||
const base=normalize(JSON.parse(vm.baseline))
|
||||
if(!attempt){vm._editor?.flush();attempt=createLiveAttempt(base,normalize(vm.sheet),'live-'+id());vm.sheet.livePending=attempt;if(!vm.persistDraft())throw Error('请先恢复本机草稿保存功能')}
|
||||
sent=liveAttemptSheet(base,attempt)
|
||||
if(vm.sheet.livePending===attempt&&attempt.recover){const receipt=await getPurchaseSheetSubmission(attempt.key);if(receipt.data)return await acceptSaved(receipt.data,attempt,sent)}
|
||||
attempt.recover=true;vm.persistDraft()
|
||||
await pushChain.catch(()=>{});const result=await savePurchaseSheet({...sent,liveClientId:clientId,liveSequence:sequence})
|
||||
return await acceptSaved(result.data,attempt,sent)
|
||||
}catch(error){
|
||||
state.saving=false;state.saveStatus='未保存,本机草稿已保留';state.issue=error.message||'自动保存失败,请检查连接';state.blocked=true
|
||||
if(error.code===409&&error.data?.conflicts){delete vm.sheet.livePending;vm.conflictData=error.data;vm.conflictChoices=error.data.conflicts.map(()=>null);vm.conflictOpen=true}
|
||||
// Business failures are confirmed rollbacks. Unknown network outcomes keep the frozen attempt.
|
||||
else if(attempt&&sent){try{const receipt=await getPurchaseSheetSubmission(attempt.key);if(receipt.data)return await acceptSaved(receipt.data,attempt,sent);if(typeof error.code==='number'&&![401,403].includes(error.code))delete vm.sheet.livePending}catch{/* The frozen attempt is retained until its outcome can be recovered. */}}
|
||||
vm.persistDraft()
|
||||
}finally{state.saving=false;queueMicrotask(()=>{running=null;if(needsRefresh){needsRefresh=false;clearTimeout(refreshTimer);refreshTimer=setTimeout(refresh,150)}})}
|
||||
})();return running
|
||||
}
|
||||
function scheduleSave(){if(stopped||applying)return;clearTimeout(saveTimer);saveTimer=setTimeout(saveOnce,900)}
|
||||
async function refresh(){
|
||||
if(stopped||!room)return;if(vm.saving||vm.sheet?.livePending||running){needsRefresh=true;return}
|
||||
try{const response=await getPurchaseSheet(room);if(stopped||Number(vm.sheet?.batch?.id)!==room)return
|
||||
if(!vm.sheet||response.data.version===vm.sheet.version)return
|
||||
if(!vm.isEditing){vm.install(response.data);return}
|
||||
apply(mergeRemote(JSON.parse(vm.baseline),cloneLive(vm.sheet),response.data));scheduleSave()
|
||||
}catch(error){state.issue=error.message||'暂未取得最新内容,本机草稿已保留'}
|
||||
}
|
||||
function start(batch){
|
||||
if(Number(batch)===room&&!stopped)return
|
||||
stop();room=Number(batch)||null;stopped=false;clientId=id();sequence=0;lastState={rowId:null,rowKey:null,field:null,editing:false,value:null,typing:false};state.clientId=clientId;state.enabled=!!room;presence.clear();state.blocked=false;state.status=room?'连接中':'保存批次后启用实时协同'
|
||||
if(room){void connect();heartbeat=setInterval(()=>{if(state.connected)void push()},12000)}
|
||||
}
|
||||
function stop(){
|
||||
stopped=true;clearTimeout(retryTimer);clearTimeout(saveTimer);clearTimeout(pushTimer);clearTimeout(refreshTimer);clearInterval(heartbeat);stream?.abort()
|
||||
if(room&&state.connected)void send('DELETE',endpoint()+'?clientId='+encodeURIComponent(clientId),null,{keepalive:true}).catch(()=>{})
|
||||
state.connected=false;presence.clear();room=null
|
||||
}
|
||||
return {start,stop,peer:presence.peer,ghost:presence.ghost,scheduleSave,refresh,get sequence(){return sequence},get busy(){return !!running},async settle(){if(pendingText.size)await Promise.allSettled([...pendingText]);if(running)await running;if(vm.sheet?.livePending){state.blocked=false;await saveOnce()}return !vm.sheet?.livePending},
|
||||
async claim(row,field){if(!room)return true;if(!state.connected){state.saveStatus='离线修改,本机草稿已保留';return true}uncommitted=false;const ok=await push({rowId:row?.id||null,rowKey:row&&!row.id?row._key:null,field,editing:true,typing:false,value:null});if(ok){state.blocked=false;state.issue=''}return ok||(!state.connected&&!state.blocked)},
|
||||
typing(row,field,value,raw=false){if(applying||!room)return;uncommitted=raw;if(raw){vm.sheet.liveText||={};const key=row._key+'|'+field;if(value===String(row[field]||''))delete vm.sheet.liveText[key];else vm.sheet.liveText[key]={key:row._key,field,value};vm.persistDraft()}lastState={rowId:row.id||null,rowKey:row.id?null:row._key,field,editing:true,typing:true,value};clearTimeout(pushTimer);pushTimer=setTimeout(()=>push(),120);state.blocked=false;state.saveStatus=raw?'输入中,草稿实时同步':'待自动保存';if(!raw)scheduleSave()},
|
||||
commit(row,field,value,task){const pending=Promise.resolve(task).then(()=>{const key=row._key+'|'+field;if(vm.sheet?.liveText?.[key]?.value===value)delete vm.sheet.liveText[key]},error=>{state.issue=error.message||'输入校验尚未完成,草稿已保留'}).finally(()=>{pendingText.delete(pending);uncommitted=Object.keys(vm.sheet?.liveText||{}).length>0;vm.persistDraft();scheduleSave()});pendingText.add(pending);return pending},
|
||||
committed(){uncommitted=Object.keys(vm.sheet?.liveText||{}).length>0;scheduleSave()},
|
||||
rowChanged(row){if(applying||!room)return;state.blocked=false;const field=vm.editCell?.startsWith(row._key+'|')?vm.editCell.slice(row._key.length+1):null;if(field&&!['materialName','materialBrand','materialParams'].includes(field))this.typing(row,field,row[field]);scheduleSave()},
|
||||
release(){uncommitted=false;clearTimeout(pushTimer);if(room&&state.connected)void push({editing:false,typing:false});scheduleSave()},
|
||||
retry(){state.blocked=false;if(!state.connected){clientId=id();sequence=0;state.clientId=clientId}if(state.connected){void refresh();void saveOnce()}else{clearTimeout(retryTimer);void connect()}},
|
||||
}
|
||||
}
|
||||
47
ruoyi-ui-vue3/tests/runtime/purchase-live-editor.spec.js
Normal file
47
ruoyi-ui-vue3/tests/runtime/purchase-live-editor.spec.js
Normal file
@ -0,0 +1,47 @@
|
||||
import {it,expect,vi} from 'vitest'
|
||||
import {reactive} from 'vue'
|
||||
import {createSheetEditor,readSheetDraft} from '../../src/utils/purchase-sheet-editor'
|
||||
|
||||
function fixture(){
|
||||
const vm=reactive({live:{enabled:true},sheet:null,baseline:'',editing:true,isEditing:true,history:[],redoHistory:[],changedKeys:new Set(),selected:[],persistDraft:vi.fn(),draftPrefix:()=> 'live-test:',draftId:()=> 'one',refreshDrafts:vi.fn(),$modal:{msgWarning:vi.fn()}})
|
||||
const editor=createSheetEditor(vm)
|
||||
vm.sheet={batch:{id:1,batchName:'原名称',progressRemark:'原批次备注'},deletedIds:[],rows:[{id:1,_key:'saved-1',quantity:2,remark:'原备注'}]}
|
||||
vm.baseline=JSON.stringify(vm.sheet)
|
||||
return {vm,editor}
|
||||
}
|
||||
it('collaborative undo changes only the local field while retaining a different field from a peer',()=>{
|
||||
const {vm,editor}=fixture();try{
|
||||
editor.beginCell(vm.sheet.rows[0],'remark');vm.sheet.rows[0].remark='我的';editor.flush()
|
||||
vm._liveRebasing=true;vm.sheet.rows[0].quantity=9;vm.baseline=JSON.stringify(vm.sheet);vm._liveRebasing=false
|
||||
editor.undo();expect(vm.sheet.rows[0].remark).toBe('原备注');expect(vm.sheet.rows[0].quantity).toBe(9)
|
||||
editor.redo();expect(vm.sheet.rows[0].remark).toBe('我的');expect(vm.sheet.rows[0].quantity).toBe(9)
|
||||
}finally{editor.stop()}
|
||||
})
|
||||
it('undo cannot replace a later peer edit to the same field',()=>{
|
||||
const {vm,editor}=fixture();try{
|
||||
editor.beginCell(vm.sheet.rows[0],'remark');vm.sheet.rows[0].remark='我的';editor.flush()
|
||||
vm._liveRebasing=true;vm.sheet.rows[0].remark='他人后改';vm.baseline=JSON.stringify(vm.sheet);vm._liveRebasing=false
|
||||
editor.undo();expect(vm.sheet.rows[0].remark).toBe('他人后改');expect(vm.$modal.msgWarning).toHaveBeenCalledOnce()
|
||||
}finally{editor.stop()}
|
||||
})
|
||||
it('a header undo retains another user’s changed header fields',()=>{
|
||||
const {vm,editor}=fixture();try{
|
||||
editor.beginHeader('batchName');vm.sheet.batch.batchName='我改的名称';editor.flush()
|
||||
vm._liveRebasing=true;vm.sheet.batch.progressRemark='别人更新的备注';vm.baseline=JSON.stringify(vm.sheet);vm._liveRebasing=false
|
||||
editor.undo();expect(vm.sheet.batch.batchName).toBe('原名称');expect(vm.sheet.batch.progressRemark).toBe('别人更新的备注')
|
||||
}finally{editor.stop()}
|
||||
})
|
||||
it('undoing a local insertion preserves rows added by another user',()=>{
|
||||
const {vm,editor}=fixture();try{
|
||||
editor.remember([]);vm.sheet.rows.push({_key:'mine-new',id:2,quantity:1});editor.flush()
|
||||
vm._liveRebasing=true;editor.acceptRemoteRows(['saved-3']);vm.sheet.rows.push({_key:'saved-3',id:3,quantity:8});vm.baseline=JSON.stringify(vm.sheet);vm._liveRebasing=false
|
||||
editor.undo();expect(vm.sheet.rows.map(r=>r.id)).toEqual([1,3]);expect(vm.sheet.deletedIds).toContain(2)
|
||||
}finally{editor.stop()}
|
||||
})
|
||||
it('unfinished identity text and pending save receipts survive a local draft reload',()=>{
|
||||
const {vm,editor}=fixture();try{
|
||||
vm.dirty=true;vm.sheet.liveText={'saved-1|materialParams':{key:'saved-1',field:'materialParams',value:'第一段 第二段'}};vm.sheet.livePending={key:'same-retry-key',version:'v1',recover:true}
|
||||
expect(editor.persist()).toBe(true);const draft=readSheetDraft('live-test:one')
|
||||
expect(draft.sheet.liveText['saved-1|materialParams'].value).toBe('第一段 第二段');expect(draft.sheet.livePending.key).toBe('same-retry-key');expect(draft.sheet.rows[0].quantity).toBe(2)
|
||||
}finally{editor.stop();localStorage.clear()}
|
||||
})
|
||||
35
ruoyi-ui-vue3/tests/runtime/purchase-live-presence.spec.js
Normal file
35
ruoyi-ui-vue3/tests/runtime/purchase-live-presence.spec.js
Normal file
@ -0,0 +1,35 @@
|
||||
import {it,expect} from 'vitest'
|
||||
import {reactive,watchEffect,nextTick} from 'vue'
|
||||
import {createLivePresence} from '../../src/utils/purchase-live-presence'
|
||||
|
||||
const peer=(patch={})=>({clientId:'other',userId:8,name:'同事',sequence:1,rowId:1,field:'remark',editing:true,draft:{field:'remark',value:'草稿'},...patch})
|
||||
const fixture=()=>{const state=reactive({clientId:'mine',peers:[],headerBusy:false});return {state,presence:createLivePresence(state)}}
|
||||
|
||||
it('typing invalidates only the targeted cell rather than all 2000 rows',async()=>{
|
||||
const {presence}=fixture(),counts=Array(2000).fill(0),stops=counts.map((_,index)=>watchEffect(()=>{presence.ghost({id:index+1},'remark');counts[index]++}))
|
||||
try{presence.update([peer()]);await nextTick();presence.update([peer({sequence:2,draft:{field:'remark',value:'继续输入'}})]);await nextTick()
|
||||
expect(counts[0]).toBe(3);expect(counts.slice(1).every(count=>count===1)).toBe(true)
|
||||
}finally{stops.forEach(stop=>stop())}
|
||||
})
|
||||
it('unchanged heartbeat snapshots keep the public array and cell objects stable',()=>{
|
||||
const {state,presence}=fixture();presence.update([peer()],true);const list=state.peers,cell=presence.peer({id:1},'remark')
|
||||
for(let sequence=2;sequence<10;sequence++)presence.update([peer({sequence})],true)
|
||||
expect(state.peers).toBe(list);expect(presence.peer({id:1},'remark')).toBe(cell)
|
||||
// Filtering stale data uses the latest transport sequence, even when no UI change was needed.
|
||||
presence.update([peer({sequence:8,draft:{field:'remark',value:'过时输入'}})])
|
||||
expect(presence.ghost({id:1},'remark').value).toBe('草稿')
|
||||
})
|
||||
it('moving a cursor releases the old field and marks its related identity fields',()=>{
|
||||
const {presence}=fixture();presence.update([peer()]);presence.update([peer({sequence:2,rowId:2,field:'materialName',draft:null})])
|
||||
expect(presence.peer({id:1},'remark')).toBeUndefined();expect(presence.peer({id:2},'materialParams',true)?.name).toBe('同事');expect(presence.peer({id:2},'quantity',true)).toBeUndefined()
|
||||
})
|
||||
it('saving can clear a draft at the same sequence while retaining cursor occupancy',()=>{
|
||||
const {presence}=fixture();presence.update([peer()]);presence.update([peer({draft:null})],true)
|
||||
expect(presence.ghost({id:1},'remark')).toBeNull();expect(presence.peer({id:1},'remark')).toBeTruthy()
|
||||
})
|
||||
it('leaving, header occupancy and own cursors update without leaking stale locks',()=>{
|
||||
const {state,presence}=fixture();presence.update([peer({clientId:'mine'}),peer({clientId:'header',rowId:null,field:'batch',draft:null}),peer()],true)
|
||||
expect(state.headerBusy).toBe(true);expect(presence.peer({id:1},'remark')?.clientId).toBe('other')
|
||||
presence.update([peer({clientId:'mine'})],true);expect(state.headerBusy).toBe(false);expect(presence.peer({id:1},'remark')).toBeUndefined()
|
||||
presence.clear();expect(state.peers).toHaveLength(0)
|
||||
})
|
||||
31
ruoyi-ui-vue3/tests/unit/purchase-live-data.test.mjs
Normal file
31
ruoyi-ui-vue3/tests/unit/purchase-live-data.test.mjs
Normal file
@ -0,0 +1,31 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {createLiveAttempt,liveAttemptSheet,rebaseLiveSheet,createLiveEventParser,cloneLive} from '../../src/utils/purchase-live-data.js'
|
||||
const fixture=()=>({version:'v1',batch:{id:1,batchName:'测试'},deletedIds:[],rows:[{id:1,_key:'saved-1',materialName:'物品一',quantity:1,remark:'原备注'},{id:2,_key:'saved-2',materialName:'物品二',quantity:2,remark:''}]})
|
||||
test('an immutable attempt retries original cells even after subsequent typing',()=>{
|
||||
const base=fixture(),local=cloneLive(base);local.rows[0].remark='本次';const attempt=createLiveAttempt(base,local,'test-key');local.rows[0].remark='后续输入';const sent=liveAttemptSheet(base,attempt)
|
||||
assert.equal(sent.rows[0].remark,'本次');assert.equal(sent.rows[0].clientRowKey,'saved-1');assert.equal(sent.submissionKey,'test-key');assert.equal(attempt.rows.length,1);assert.throws(()=>liveAttemptSheet({...base,version:'new'},attempt),/快照不匹配/)
|
||||
})
|
||||
test('remote rows and fields become visible without overwriting current local edits',()=>{
|
||||
const base=fixture(),local=cloneLive(base),server=cloneLive(base);local.rows[0].remark='我的';server.version='v2';server.rows[1].quantity=7;server.rows.push({id:3,materialName:'新增',quantity:9})
|
||||
const result=rebaseLiveSheet(base,local,server);assert.equal(result.conflicts.length,0);assert.equal(result.proposed.rows[0].remark,'我的');assert.equal(result.latest.rows[0].remark,'原备注');assert.equal(result.proposed.rows[1].quantity,7);assert.equal(result.proposed.rows[2]._key,'saved-3')
|
||||
})
|
||||
test('the same field and related identity fields produce an explicit conflict',()=>{
|
||||
const base=fixture(),local=cloneLive(base),server=cloneLive(base);local.rows[0].remark='我的';server.rows[0].remark='他人';assert.equal(rebaseLiveSheet(base,local,server).conflicts[0].label,'备注')
|
||||
local.rows[0].remark='原备注';local.rows[0].materialParams='规格A';server.rows[0].remark='原备注';server.rows[0].materialName='其他物品';assert.equal(rebaseLiveSheet(base,local,server).conflicts[0].fields.includes('materialParams'),true)
|
||||
})
|
||||
test('self acknowledgements retain subsequent typing and stable keys for assigned new row IDs',()=>{
|
||||
const base=fixture(),sent=cloneLive(base);sent.rows.push({id:null,_key:'new-local',materialName:'新增',productId:null,quantity:1});const attempt=createLiveAttempt(base,sent,'test-key'),local=cloneLive(sent),server=cloneLive(sent)
|
||||
local.rows[2].materialName='继续输入';server.rows[2]={id:3,materialName:'新增',productId:8,quantity:1};server.clientRowIds={'new-local':3};server.version='v2'
|
||||
const result=rebaseLiveSheet(sent,local,server,attempt);assert.equal(result.conflicts.length,0);assert.equal(result.proposed.rows[2]._key,'new-local');assert.equal(result.proposed.rows[2].id,3);assert.equal(result.proposed.rows[2].materialName,'继续输入')
|
||||
})
|
||||
test('deleting a new row while its creation is in flight schedules deletion of its assigned ID',()=>{
|
||||
const base=fixture(),sent=cloneLive(base);sent.rows.push({id:null,_key:'new-local',materialName:'新增',quantity:1});const local=cloneLive(base),server=cloneLive(base);server.rows.push({id:3,materialName:'新增',quantity:1});server.clientRowIds={'new-local':3}
|
||||
const result=rebaseLiveSheet(sent,local,server,createLiveAttempt(base,sent,'key'));assert.deepEqual(result.proposed.deletedIds,[3]);assert.equal(result.proposed.rows.length,2)
|
||||
})
|
||||
test('a concurrent deletion cannot silently discard local changes',()=>{
|
||||
const base=fixture(),local=cloneLive(base),server=cloneLive(base);local.rows[0].remark='不能丢失';server.rows.shift();assert.equal(rebaseLiveSheet(base,local,server).conflicts[0].kind,'removed')
|
||||
})
|
||||
test('SSE framing supports fragmented input, CRLF and comments without processing incomplete data',()=>{
|
||||
const events=[],feed=createLiveEventParser((type,data)=>events.push([type,data]));feed(':ping\r\nevent: member\r\ndata: {"name":"张');assert.equal(events.length,0);feed('三"}\r\n\r\nevent: saved\ndata: {"batchId":1}\n\n');assert.deepEqual(events,[['member',{name:'张三'}],['saved',{batchId:1}]])
|
||||
})
|
||||
10
ruoyi-ui-vue3/tests/unit/purchase-sheet-conflicts.test.mjs
Normal file
10
ruoyi-ui-vue3/tests/unit/purchase-sheet-conflicts.test.mjs
Normal file
@ -0,0 +1,10 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {resolvePurchaseSheetConflicts} from '../../src/utils/purchase-sheet-conflicts.js'
|
||||
|
||||
test('resolve each conflict into a draft without mutating either server snapshot',()=>{
|
||||
const data={latest:{},proposed:{version:'v2',submissionKey:'old',batch:{batchName:'最新'},rows:[{id:1,remark:'最新',quantity:5}]},conflicts:[{rowId:1,fields:['remark'],mine:{remark:'我的'},current:{remark:'最新'}},{rowId:null,fields:['batchName'],mine:{batchName:'我的批次'},current:{batchName:'最新'}}]}
|
||||
const result=resolvePurchaseSheetConflicts(data,['mine','current'])
|
||||
assert.equal(result.rows[0].remark,'我的');assert.equal(result.rows[0].quantity,5);assert.equal(result.batch.batchName,'最新');assert.equal(result.submissionKey,null);assert.equal(data.proposed.rows[0].remark,'最新')
|
||||
assert.throws(()=>resolvePurchaseSheetConflicts(data,['mine',null]),/逐项选择/)
|
||||
})
|
||||
15
sql/projectdev/20261104_purchase_acceptance_confirmation.sql
Normal file
15
sql/projectdev/20261104_purchase_acceptance_confirmation.sql
Normal file
@ -0,0 +1,15 @@
|
||||
-- Additive structure only. Does not rewrite any inventory dates or historical business rows.
|
||||
CREATE TABLE IF NOT EXISTS purchase_acceptance_confirmation (
|
||||
id bigint NOT NULL AUTO_INCREMENT,
|
||||
batch_id bigint NOT NULL,
|
||||
attachment_id varchar(36) NOT NULL,
|
||||
snapshot_hash char(64) NOT NULL,
|
||||
request_key varchar(100) NOT NULL,
|
||||
owner_id bigint NOT NULL,
|
||||
confirmed_by varchar(64) NOT NULL,
|
||||
confirmed_time datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||
PRIMARY KEY(id),
|
||||
UNIQUE KEY uk_purchase_acceptance_request(request_key),
|
||||
KEY idx_purchase_acceptance_batch(batch_id,id),
|
||||
KEY idx_purchase_acceptance_file(attachment_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
2
sql/projectdev/20261104_purchase_attachment_source.sql
Normal file
2
sql/projectdev/20261104_purchase_attachment_source.sql
Normal file
@ -0,0 +1,2 @@
|
||||
-- Apply only if this column is absent. Existing attachments remain available for manual verification.
|
||||
ALTER TABLE purchase_document_attachment ADD COLUMN server_generated tinyint(1) NOT NULL DEFAULT 0 COMMENT 'System-generated unsigned document; not a human-uploaded signed copy';
|
||||
Loading…
Reference in New Issue
Block a user