feat: add optional arrival photos and harden purchase quote access
This commit is contained in:
parent
f3e181a158
commit
da8246c202
@ -1,3 +1,4 @@
|
||||
import {ArrivalHistory} from './screens/ArrivalHistory';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ActivityIndicator, AppState, BackHandler, FlatList, Image, KeyboardAvoidingView, Modal, Platform,
|
||||
Keyboard, Pressable, ScrollView, Text, View } from 'react-native';
|
||||
@ -137,6 +138,7 @@ function Login({api,onLogin,server,connection}:{api:ApiClient;onLogin:(token:str
|
||||
function BusinessList({api,module,permissions}:{api:ApiClient;module:Module;permissions:string[]}){
|
||||
const t=useTheme();const [query,setQuery]=useState(''),[rows,setRows]=useState<Row[]>([]),[total,setTotal]=useState(0),[page,setPage]=useState(1);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[operation,setOperation]=useState<{row:Row;kind:string}|null>(null);
|
||||
const [historyRow,setHistoryRow]=useState<Row|null>(null);
|
||||
const [arrivalQueue,setArrivalQueue]=useState<'arrival'|'accept'>('arrival');
|
||||
const [compactAmounts,setCompactAmounts]=useState(true);
|
||||
const serial=useRef(0),controller=useRef<AbortController|null>(null),busyRef=useRef(false),appliedQuery=useRef('');
|
||||
@ -159,11 +161,13 @@ function BusinessList({api,module,permissions}:{api:ApiClient;module:Module;perm
|
||||
{['move','use'].includes(module.key)&&stockWrite&&<Button title={module.key==='move'?'移库':'领用出库'} secondary disabled={Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:module.key})}/>}
|
||||
{module.key==='count'&&allows(permissions,['warehouse:check:add'])&&<Button title="登记盘点" secondary onPress={()=>setOperation({row:item,kind:'check'})}/>}
|
||||
{module.key==='check'&&Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm'])&&<Button title="确认盘点生效" secondary disabled={busy} onPress={()=>confirmCheck(item)}/>}
|
||||
{['arrival','purchase'].includes(module.key)&&<Button title="到货记录 / 照片" secondary onPress={()=>setHistoryRow(item)}/>}
|
||||
{module.key==='arrival'&&<ArrivalActions row={item} permissions={permissions} queue={arrivalQueue}
|
||||
onOpen={kind=>setOperation({row:item,kind})}/>}
|
||||
{module.key==='pending'&&allows(permissions,['warehouse:in:confirm'])&&(item.receiptRoot||allows(permissions,['warehouse:in:edit']))&&<Button title="办理入库" secondary onPress={()=>setOperation({row:item,kind:'receive'})}/>}
|
||||
</ListCard>}/>
|
||||
<View style={[s.row,{padding:12,justifyContent:'space-between'}]}><Button title="上一页" secondary disabled={busy||page<=1} onPress={()=>void load(page-1,appliedQuery.current)}/><Button title="下一页" secondary disabled={busy||page*20>=total} onPress={()=>void load(page+1,appliedQuery.current)}/></View>
|
||||
{!!historyRow&&<ArrivalHistory api={api} row={historyRow} close={()=>setHistoryRow(null)}/>}
|
||||
{!!operation&&(operation.kind==='arrival'||operation.kind==='accept'?<ArrivalOperation api={api} row={operation.row} mode={operation.kind} close={()=>setOperation(null)} done={()=>{setOperation(null);void load(page,query);}}/>:<StockOperation api={api} row={operation.row} kind={operation.kind} close={()=>setOperation(null)} done={()=>{setOperation(null);void load(page,query);}}/>)}
|
||||
</View>;
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import {displayTimestamp} from './date-display.ts';
|
||||
import type {Row} from './modules';
|
||||
|
||||
export function draftStatus(value:unknown) {
|
||||
@ -42,7 +43,7 @@ export function queryColumnGroups(columns:Row[],rows:Row[]) {
|
||||
export function referenceText(value:unknown):string {
|
||||
if(value==null||value==='')return '—';
|
||||
if(Array.isArray(value))return value.map(referenceText).join(';');
|
||||
if(typeof value!=='object')return String(value);
|
||||
if(typeof value!=='object')return String(displayTimestamp(value));
|
||||
const row=value as Row;
|
||||
const summary=['label','name','keyword','code','spec','brand','supplierName','projectName'].map(key=>row[key]).filter(v=>v!=null&&v!=='');
|
||||
return [...new Set(summary.map(String))].join(' / ')||'尚未匹配,请补充名称或在电脑端选择';
|
||||
|
||||
22
mobile-app/src/core/date-display.ts
Normal file
22
mobile-app/src/core/date-display.ts
Normal file
@ -0,0 +1,22 @@
|
||||
const timestamp=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/i;
|
||||
|
||||
export function formatDateTime(value:unknown):string {
|
||||
if(value==null||value===''||typeof value==='boolean')return '—';
|
||||
if(!(value instanceof Date)&&typeof value!=='string'&&typeof value!=='number')return '—';
|
||||
const source=typeof value==='string'?value.trim():value;
|
||||
const dateOnly=typeof source==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(source);
|
||||
const numeric=typeof source==='string'&&/^\d+$/.test(source)?Number(source):source;
|
||||
const input=typeof numeric==='number'&&String(numeric).length===10?numeric*1000:numeric;
|
||||
// Plain calendar dates remain local; ISO offsets are interpreted as instants.
|
||||
const normalized=typeof input==='string'?input.replace(/^(\d{4}-\d{2}-\d{2}) /,'$1T').replace(/(\.\d{3})\d+/,'$1')+(dateOnly?'T00:00:00':''):input;
|
||||
const date=normalized instanceof Date?normalized:new Date(normalized);
|
||||
if(Number.isNaN(date.getTime()))return '—';
|
||||
const pad=(n:number)=>String(n).padStart(2,'0');
|
||||
const day=`${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}`;
|
||||
if(dateOnly)return day===source?day:'—';
|
||||
return `${day} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
export function displayTimestamp(value:unknown):unknown {
|
||||
return value instanceof Date||typeof value==='string'&×tamp.test(value.trim())?formatDateTime(value):value;
|
||||
}
|
||||
@ -1,3 +1,4 @@
|
||||
import {displayTimestamp} from './date-display.ts';
|
||||
export type Row = Record<string, any>;
|
||||
export type Module = { key: string; title: string; path: string; permissions: string[][];
|
||||
search: string; titleKey: string; fields: [string, string][]; query?: Row; pages?: string[]; guide?: string };
|
||||
@ -34,7 +35,7 @@ export function routeComponents(routes: Row[]): string[] {
|
||||
return routes.flatMap(r => [String(r.component || ''), ...routeComponents(r.children || [])]);
|
||||
}
|
||||
export function localDate() { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }
|
||||
export function display(value: unknown) { return value == null || value === '' ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(value); }
|
||||
export function display(value: unknown) { return value == null || value === '' ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(displayTimestamp(value)); }
|
||||
export function validDate(value: string) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||
const parsed = new Date(`${value}T00:00:00Z`);
|
||||
|
||||
18
mobile-app/src/screens/ArrivalHistory.tsx
Normal file
18
mobile-app/src/screens/ArrivalHistory.tsx
Normal file
@ -0,0 +1,18 @@
|
||||
import React,{useEffect,useState} from 'react';
|
||||
import {Modal,ScrollView,View} from 'react-native';
|
||||
import {SafeAreaView} from 'react-native-safe-area-context';
|
||||
import type {ApiClient} from '../core/network';
|
||||
import type {Row} from '../core/modules';
|
||||
import {formatDateTime} from '../core/date-display';
|
||||
import {Button,Card,Heading,Note,s,useTheme} from '../ui';
|
||||
import {ArrivalPhotos} from './ArrivalPhotos';
|
||||
|
||||
export function ArrivalHistory({api,row,close}:{api:ApiClient;row:Row;close:()=>void}){
|
||||
const t=useTheme(),[records,setRecords]=useState<Row[]>([]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[expanded,setExpanded]=useState<number|null>(null);
|
||||
useEffect(()=>{const ctl=new AbortController();setLoading(true);setError('');void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:ctl.signal}).then(r=>{if(!ctl.signal.aborted)setRecords(r.data||[]);}).catch(e=>{if(!ctl.signal.aborted)setError(e.message);}).finally(()=>{if(!ctl.signal.aborted)setLoading(false);});return()=>ctl.abort();},[api,row.id,attempt]);
|
||||
return <Modal visible animationType="slide" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:16,justifyContent:'space-between'}]}><Heading>到货记录</Heading><Button title="关闭" secondary onPress={close}/></View><ScrollView contentContainerStyle={s.page}><Note>{row.materialName} · {row.materialParams} · {row.unit}</Note>
|
||||
{loading&&<Note>正在读取到货记录…</Note>}{!!error&&<><Note>{error}</Note><Button title="重新加载" secondary onPress={()=>setAttempt(n=>n+1)}/></>}{!loading&&!error&&!records.length&&<Note>暂无到货记录</Note>}
|
||||
{records.map(record=><Card key={record.id}><Heading>{record.arrivalNo}</Heading><Note>{formatDateTime(record.arrivalDate)} · 到货 {record.arrivalQuantity} {row.unit} · {['待验收','验收通过','拒收','已撤销'][record.acceptanceStatus]||'已撤销'}</Note>{!!record.remark&&<Note>{record.remark}</Note>}{!!record.acceptanceRemark&&<Note>验收说明:{record.acceptanceRemark}</Note>}
|
||||
{(record.photos||[]).length?<><Button title={expanded===record.id?'收起照片':`查看到货照片(${record.photos.length})`} secondary onPress={()=>setExpanded(expanded===record.id?null:record.id)}/>{expanded===record.id&&<ArrivalPhotos api={api} requestId={row.id} photos={record.photos} readonly/>}</>:<Note>未上传到货照片</Note>}</Card>)}
|
||||
</ScrollView></SafeAreaView></Modal>;
|
||||
}
|
||||
@ -1,3 +1,5 @@
|
||||
import {ArrivalPhotos} from './ArrivalPhotos';
|
||||
import {formatDateTime} from '../core/date-display';
|
||||
import React,{useEffect,useRef,useState} from 'react';
|
||||
import {KeyboardAvoidingView,Modal,Platform,ScrollView,View} from 'react-native';
|
||||
import {SafeAreaView} from 'react-native-safe-area-context';
|
||||
@ -12,23 +14,25 @@ export function ArrivalOperation({api,row,mode,close,done}:{api:ApiClient;row:Ro
|
||||
const [quantity,setQuantity]=useState(''),[date,setDate]=useState(localDate()),[remark,setRemark]=useState('');
|
||||
const [records,setRecords]=useState<Row[]>([]),[record,setRecord]=useState<Row|null>(null),[loading,setLoading]=useState(accept);
|
||||
const [preview,setPreview]=useState<Row|null>(null),[busy,setBusy]=useState(false),[attempted,setAttempted]=useState(false),[error,setError]=useState('');
|
||||
const [photos,setPhotos]=useState<Row[]>([]),[photosPending,setPhotosPending]=useState(false);
|
||||
useEffect(()=>{alive.current=true;const controller=new AbortController();
|
||||
if(accept)void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:controller.signal}).then(result=>{if(alive.current){const pending=(result.data||[]).filter((r:Row)=>Number(r.acceptanceStatus)===0).map((r:Row)=>({...r,label:`${r.arrivalNo} · ${r.arrivalQuantity} ${row.unit||''} · ${r.arrivalDate||''}`}));setRecords(pending);if(pending.length===1)setRecord(pending[0]);}}).catch(e=>{if(alive.current&&!controller.signal.aborted)setError((e as Error).message);}).finally(()=>{if(alive.current)setLoading(false);});
|
||||
if(accept)void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:controller.signal}).then(result=>{if(alive.current){const pending=(result.data||[]).filter((r:Row)=>Number(r.acceptanceStatus)===0).map((r:Row)=>({...r,label:`${r.arrivalNo} · ${r.arrivalQuantity} ${row.unit||''} · ${formatDateTime(r.arrivalDate)}`}));setRecords(pending);if(pending.length===1)setRecord(pending[0]);}}).catch(e=>{if(alive.current&&!controller.signal.aborted)setError((e as Error).message);}).finally(()=>{if(alive.current)setLoading(false);});
|
||||
return()=>{alive.current=false;controller.abort();};},[api,row.id,accept]);
|
||||
function prepare(){
|
||||
if(!accept&&photosPending)return setError('有照片尚未上传完成,请重试或移除后继续。');
|
||||
const amount=Number(quantity||'0');
|
||||
if(!/^\d+(\.\d{1,4})?$/.test(quantity||'0')||!Number.isFinite(amount)||(accept?amount<0:amount<=0))return setError(accept?'请填写不合格数量,允许为 0,最多 4 位小数。':'请填写大于 0 的到货数量,最多 4 位小数。');
|
||||
if(accept&&!record)return setError('请选择本次验收的到货记录。');
|
||||
if(amount>Number(accept?record?.arrivalQuantity:row.remainingQuantity))return setError(accept?'不合格数量不能超过本次到货数量。':'数量超过当前剩余可登记到货数量。');
|
||||
if(!accept&&!validDate(date))return setError('请填写有效到货日期。');
|
||||
setError('');setPreview(accept?{id:record!.id,body:{acceptanceStatus:1,defectiveQuantity:amount,acceptanceRemark:remark}}:{body:{purchaseRequestId:row.id,arrivalQuantity:amount,arrivalDate:date,remark,requestKey:requestKey.current}});
|
||||
setError('');setPreview(accept?{id:record!.id,body:{acceptanceStatus:1,defectiveQuantity:amount,acceptanceRemark:remark}}:{body:{purchaseRequestId:row.id,arrivalQuantity:amount,arrivalDate:date,remark,requestKey:requestKey.current,photoIds:photos.map(p=>p.id)}});
|
||||
}
|
||||
async function submit(){if(lock.current||!preview||accept&&attempted)return;lock.current=true;setBusy(true);setAttempted(true);setError('');
|
||||
try{await api.request(accept?`/warehouse/purchase/arrival/${preview.id}/accept`:'/warehouse/purchase/arrival',{method:accept?'PUT':'POST',body:preview.body});if(alive.current)done();}
|
||||
catch(e){if(alive.current)setError((e as Error).message+(accept?' 请返回列表刷新到货记录,核对是否已经验收;不会自动重发。':' 请先核对到货记录。重试仅发送相同内容与请求标识,不会新建另一请求。'));}
|
||||
finally{lock.current=false;if(alive.current)setBusy(false);}
|
||||
}
|
||||
function requestClose(){if(busy)return;if(preview||quantity||remark)Alert.alert('结束本次填写?',attempted?'请先到到货记录核对处理结果。':'未提交内容不会写入业务。',[{text:'继续核对',style:'cancel'},{text:'关闭',onPress:close}]);else close();}
|
||||
function requestClose(){if(busy)return;if(preview||quantity||remark||photos.length)Alert.alert('结束本次填写?',attempted?'请先到到货记录核对处理结果。':'未提交内容不会写入业务。',[{text:'继续核对',style:'cancel'},{text:'关闭',onPress:close}]);else close();}
|
||||
const title=accept?'验收到货':'登记到货';
|
||||
return <Modal visible animationType="slide" onRequestClose={requestClose}><SafeAreaView style={[s.fill,{backgroundColor:t.bg,width:'100%',maxWidth:Platform.OS==='web'?480:undefined,alignSelf:'center'}]}><KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}>
|
||||
<View style={{paddingHorizontal:18,paddingVertical:10,flexDirection:'row',alignItems:'center',justifyContent:'space-between',borderBottomWidth:1,borderColor:t.line}}><Heading>{title}</Heading><Button title="关闭" secondary disabled={busy} onPress={requestClose}/></View>
|
||||
@ -38,11 +42,12 @@ export function ArrivalOperation({api,row,mode,close,done}:{api:ApiClient;row:Ro
|
||||
{!preview?<>
|
||||
{accept?<><Choice label="到货记录" items={records} value={record} onChange={setRecord} nameKey="label"/>{!loading&&!records.length&&<Note>暂无待验收记录。尚未登记的货物,请先返回选择“登记到货”。</Note>}<Note>本次到货:{display(record?.arrivalQuantity)} {display(row.unit)};合格数量将按到货数量减去不合格数量计算。</Note></>:<><Note>剩余可登记:{display(row.remainingQuantity)} {display(row.unit)}</Note><Button title="本次全部到齐" secondary onPress={()=>setQuantity(String(row.remainingQuantity))}/><Field label="到货日期(YYYY-MM-DD)" value={date} onChange={setDate}/></>}
|
||||
<Field label={accept?'不合格数量(0 表示全部合格)':'本次到货数量'} value={quantity} onChange={setQuantity} keyboard="decimal-pad"/><Field label={accept?'验收说明':'到货备注'} value={remark} onChange={setRemark} multiline/>
|
||||
</>:<Card><Heading>请核对本次{title}</Heading>{accept?<><Note>到货单:{display(record?.arrivalNo)}</Note><Note>到货数量:{display(record?.arrivalQuantity)} {display(row.unit)}</Note><Note>合格数量:{Number(record?.arrivalQuantity)-Number(preview.body.defectiveQuantity)} {display(row.unit)}</Note><Note>不合格数量:{preview.body.defectiveQuantity} {display(row.unit)}</Note><Note>验收合格后进入待入库,尚不会增加库存。</Note></>:<><Note>到货数量:{preview.body.arrivalQuantity} {display(row.unit)}</Note><Note>到货日期:{preview.body.arrivalDate}</Note><Note>本次仅登记到货,之后再办理验收。</Note></>}
|
||||
</>:<Card><Heading>请核对本次{title}</Heading>{accept?<><Note>到货单:{display(record?.arrivalNo)}</Note><Note>到货数量:{display(record?.arrivalQuantity)} {display(row.unit)}</Note><Note>合格数量:{Number(record?.arrivalQuantity)-Number(preview.body.defectiveQuantity)} {display(row.unit)}</Note><Note>不合格数量:{preview.body.defectiveQuantity} {display(row.unit)}</Note><Note>验收合格后进入待入库,尚不会增加库存。</Note></>:<><Note>到货数量:{preview.body.arrivalQuantity} {display(row.unit)}</Note><Note>到货日期:{formatDateTime(preview.body.arrivalDate)}</Note><Note>本次仅登记到货,之后再办理验收。</Note></>}
|
||||
<Note>说明:{remark||'无'}</Note>
|
||||
</Card>}
|
||||
<ArrivalPhotos api={api} requestId={row.id} photos={accept?(record?.photos||[]):photos} onChange={setPhotos} onPending={setPhotosPending} readonly={accept||!!preview} disabled={busy||attempted}/>
|
||||
{!!error&&<Note>{error}</Note>}
|
||||
</ScrollView><View style={{padding:14,borderTopWidth:1,borderColor:t.line,backgroundColor:t.card}}>
|
||||
{!preview?<Button title="核对预览" disabled={loading||accept&&!record} onPress={prepare}/>:<View style={{flexDirection:'row',gap:10}}><View style={{flex:1}}><Button title="返回修改" secondary disabled={busy||attempted} onPress={()=>setPreview(null)}/></View><View style={{flex:1}}><Button title={attempted?'核对后重试原请求':'确认提交'} busy={busy} disabled={accept&&attempted} onPress={()=>void submit()}/></View></View>}
|
||||
{!preview?<Button title="核对预览" disabled={loading||photosPending||accept&&!record} onPress={prepare}/>:<View style={{flexDirection:'row',gap:10}}><View style={{flex:1}}><Button title="返回修改" secondary disabled={busy||attempted} onPress={()=>setPreview(null)}/></View><View style={{flex:1}}><Button title={attempted?'核对后重试原请求':'确认提交'} busy={busy} disabled={accept&&attempted} onPress={()=>void submit()}/></View></View>}
|
||||
</View></KeyboardAvoidingView></SafeAreaView></Modal>;
|
||||
}
|
||||
|
||||
56
mobile-app/src/screens/ArrivalPhotos.tsx
Normal file
56
mobile-app/src/screens/ArrivalPhotos.tsx
Normal file
@ -0,0 +1,56 @@
|
||||
import React,{useEffect,useRef,useState} from 'react';
|
||||
import {Image,Platform,View} from 'react-native';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import * as Crypto from 'expo-crypto';
|
||||
import type {ApiClient} from '../core/network';
|
||||
import type {Row} from '../core/modules';
|
||||
import {Button,Note,s} from '../ui';
|
||||
import {ProtectedImage} from '../files';
|
||||
|
||||
export function ArrivalPhotos({api,requestId,photos,onChange,onPending,readonly=false,disabled=false}:{api:ApiClient;requestId:number;photos:Row[];onChange?:(photos:Row[])=>void;onPending?:(pending:boolean)=>void;readonly?:boolean;disabled?:boolean}){
|
||||
const [working,setWorking]=useState(false),[error,setError]=useState('');
|
||||
const current=useRef(photos),alive=useRef(true),locked=useRef(false),controller=useRef<AbortController|null>(null);
|
||||
current.current=photos;
|
||||
useEffect(()=>{alive.current=true;return()=>{alive.current=false;controller.current?.abort();};},[]);
|
||||
useEffect(()=>{onPending?.(!readonly&&(working||photos.some(p=>!p.id||p.error)));},[working,photos,readonly,onPending]);
|
||||
const update=(values:Row[])=>{current.current=values;if(alive.current)onChange?.(values);};
|
||||
async function upload(photo:Row){
|
||||
if(disabled||locked.current||!photo.uri)return;locked.current=true;setWorking(true);setError('');const ctl=new AbortController();controller.current=ctl;
|
||||
try{
|
||||
const body=new FormData();body.append('uploadId',photo.clientKey);
|
||||
if(Platform.OS==='web')body.append('file',await(await fetch(photo.uri)).blob(),photo.name);
|
||||
else body.append('file',{uri:photo.uri,type:photo.contentType,name:photo.name} as unknown as Blob);
|
||||
const result=await api.request<Row>(`/warehouse/purchase/arrival/photos/${requestId}`,{method:'POST',body,signal:ctl.signal,timeout:120000});
|
||||
if(alive.current)update(current.current.map(p=>p.clientKey===photo.clientKey?{...p,...result.data,error:''}:p));
|
||||
}catch(e){if(alive.current&&!ctl.signal.aborted)update(current.current.map(p=>p.clientKey===photo.clientKey?{...p,error:(e as Error).message||'上传失败'}:p));}
|
||||
finally{locked.current=false;if(alive.current)setWorking(false);}
|
||||
}
|
||||
async function choose(camera:boolean){
|
||||
if(disabled||locked.current||photos.length>=9)return;locked.current=true;setWorking(true);setError('');let photo:Row|undefined;
|
||||
try{
|
||||
if(camera){const permission=await ImagePicker.requestCameraPermissionsAsync();if(!permission.granted){setError('未获得相机权限。可在系统设置中允许拍照,或从相册选择照片。');return;}}
|
||||
const result=camera?await ImagePicker.launchCameraAsync({mediaTypes:['images'],quality:.7,exif:false}):await ImagePicker.launchImageLibraryAsync({mediaTypes:['images'],quality:.7,allowsMultipleSelection:false,exif:false});
|
||||
if(result.canceled||!alive.current)return;
|
||||
const asset=result.assets[0],type=asset.mimeType||'image/jpeg';
|
||||
if(!['image/jpeg','image/png','image/webp'].includes(type)){setError('请选择 JPG、PNG 或 WebP 照片。');return;}
|
||||
if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>5*1024*1024)){setError('每张照片不能超过5MB,请降低照片大小或重新拍摄。');return;}
|
||||
const extension=type==='image/png'?'png':type==='image/webp'?'webp':'jpg';
|
||||
photo={clientKey:Crypto.randomUUID(),name:`arrival-${Date.now()}.${extension}`,contentType:type,uri:asset.uri};update([...current.current,photo]);
|
||||
}catch(e){if(alive.current)setError((e as Error).message||'无法获取照片,请重试。');}
|
||||
finally{locked.current=false;if(alive.current)setWorking(false);}
|
||||
if(photo&&alive.current)await upload(photo);
|
||||
}
|
||||
async function remove(photo:Row){
|
||||
if(disabled||locked.current)return;locked.current=true;setWorking(true);setError('');
|
||||
try{if(photo.id)await api.request(`/warehouse/purchase/arrival/photos/${photo.id}`,{method:'DELETE'});if(alive.current)update(current.current.filter(p=>(p.clientKey||p.id)!==(photo.clientKey||photo.id)));}
|
||||
catch(e){if(alive.current)setError((e as Error).message);}
|
||||
finally{locked.current=false;if(alive.current)setWorking(false);}
|
||||
}
|
||||
return <View style={{gap:10}}><Note>到货照片{readonly?` · ${photos.length} 张`:`(选传)· ${photos.length}/9 · 每张不超过5MB`}</Note>
|
||||
{!readonly&&<View style={s.row}>{Platform.OS!=='web'&&<Button title="拍照" disabled={disabled||working||photos.length>=9} onPress={()=>void choose(true)}/>}<Button title={Platform.OS==='web'?'上传图片':'从相册选择'} secondary disabled={disabled||working||photos.length>=9} onPress={()=>void choose(false)}/></View>}
|
||||
<View style={[s.row,{alignItems:'flex-start'}]}>{photos.map((photo,index)=><View key={photo.clientKey||photo.id} style={{width:120,gap:5}}>{photo.id?<ProtectedImage api={api} path={`/warehouse/purchase/arrival/photos/${photo.id}/content`} label={`到货照片 ${index+1}`}/>:photo.uri?<Image source={{uri:photo.uri}} style={{width:118,height:100,borderRadius:10}}/>:null}
|
||||
{!!photo.error&&<><Note>{photo.error}</Note><Button title="重试上传" secondary disabled={disabled||working} onPress={()=>void upload(photo)}/></>}
|
||||
{!readonly&&<Button title={`移除第${index+1}张`} secondary disabled={disabled||working} onPress={()=>void remove(photo)}/>}</View>)}</View>
|
||||
{working&&<Note>正在处理照片,请稍候…</Note>}{!!error&&<Note>{error}</Note>}{readonly&&!photos.length&&<Note>本次到货未上传照片</Note>}
|
||||
</View>;
|
||||
}
|
||||
@ -1,3 +1,4 @@
|
||||
import {formatDateTime} from '../core/date-display';
|
||||
import React,{useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {Image,KeyboardAvoidingView,Platform,Pressable,ScrollView,Text,View} from 'react-native';
|
||||
import {Dialog as Alert} from '../dialogs';
|
||||
@ -40,9 +41,9 @@ export function Feedback({api,mode,bindLeave,open}:{api:ApiClient;mode:'create'|
|
||||
{images.length<5&&<Pressable accessibilityRole="button" accessibilityLabel="添加反馈图片" disabled={busy||uncertain} onPress={()=>void choose()} style={{width:100,height:100,borderRadius:12,borderWidth:1,borderColor:t.line,borderStyle:'dashed',alignItems:'center',justifyContent:'center',gap:8}}><Icon name="add"/><Note>添加图片</Note></Pressable>}</View>
|
||||
<Note>提交后会按后台通知配置交由负责人处理。你只能查看自己的反馈。</Note><Button title="提交反馈" busy={busy} disabled={uncertain||!title.trim()||!description.trim()} onPress={()=>Alert.alert('提交反馈','确认将以上描述和图片发送给系统负责人?',[{text:'再检查一下',style:'cancel'},{text:'确认提交',onPress:()=>void submit()}])}/>
|
||||
<Button title="我的反馈" secondary disabled={busy} onPress={()=>open('feedback-list')}/>
|
||||
</>):detail?<><Button title="返回反馈列表" secondary onPress={()=>setDetail(null)}/><Card><Note>{detail.type==='BUG'?'问题反馈':'功能建议'} · {feedbackStatuses[detail.status]||detail.status}</Note><Heading>{detail.title}</Heading><Note>{detail.createTime}</Note><Text selectable style={{color:t.text,lineHeight:24}}>{detail.description}</Text><View style={s.row}>{(detail.images||[]).map((image:Row)=><ProtectedImage key={image.id} api={api} path={`/system/feedback/images/${image.id}/content`} label={image.name}/>)}</View></Card><Card><Heading>处理进展</Heading><Note>{detail.reply||'负责人尚未回复,请稍后再来查看。'}</Note>{!!detail.handledTime&&<Note>更新于 {detail.handledTime}</Note>}</Card></>:<><View style={[s.row,{justifyContent:'space-between'}]}><Heading>我的反馈</Heading><Button title="刷新" secondary busy={busy} onPress={()=>void load(page)}/></View><Note>共 {total} 条 · 仅展示当前账号提交的反馈。</Note>
|
||||
</>):detail?<><Button title="返回反馈列表" secondary onPress={()=>setDetail(null)}/><Card><Note>{detail.type==='BUG'?'问题反馈':'功能建议'} · {feedbackStatuses[detail.status]||detail.status}</Note><Heading>{detail.title}</Heading><Note>{formatDateTime(detail.createTime)}</Note><Text selectable style={{color:t.text,lineHeight:24}}>{detail.description}</Text><View style={s.row}>{(detail.images||[]).map((image:Row)=><ProtectedImage key={image.id} api={api} path={`/system/feedback/images/${image.id}/content`} label={image.name}/>)}</View></Card><Card><Heading>处理进展</Heading><Note>{detail.reply||'负责人尚未回复,请稍后再来查看。'}</Note>{!!detail.handledTime&&<Note>更新于 {formatDateTime(detail.handledTime)}</Note>}</Card></>:<><View style={[s.row,{justifyContent:'space-between'}]}><Heading>我的反馈</Heading><Button title="刷新" secondary busy={busy} onPress={()=>void load(page)}/></View><Note>共 {total} 条 · 仅展示当前账号提交的反馈。</Note>
|
||||
{!busy&&!rows.length&&<Card><Icon name="chatbubbles-outline" size={40}/><Heading>还没有反馈</Heading><Note>遇到问题时,欢迎随时告诉我们。</Note><Button title="提交反馈" onPress={()=>open('feedback')}/></Card>}
|
||||
{rows.map(row=><Pressable accessibilityRole="button" accessibilityLabel={`查看反馈:${row.title}`} disabled={busy} key={row.id} onPress={()=>void inspect(row.id)}><Card><View style={[s.row,{justifyContent:'space-between'}]}><Text style={{color:t.accent,fontSize:12}}>{row.type==='BUG'?'问题反馈':'功能建议'}</Text><Note>{feedbackStatuses[row.status]||row.status}</Note></View><Text style={{color:t.text,fontSize:17,fontWeight:'600'}}>{row.title}</Text><Note>{row.createTime}</Note><Icon name="arrow-forward" size={18}/></Card></Pressable>)}
|
||||
{rows.map(row=><Pressable accessibilityRole="button" accessibilityLabel={`查看反馈:${row.title}`} disabled={busy} key={row.id} onPress={()=>void inspect(row.id)}><Card><View style={[s.row,{justifyContent:'space-between'}]}><Text style={{color:t.accent,fontSize:12}}>{row.type==='BUG'?'问题反馈':'功能建议'}</Text><Note>{feedbackStatuses[row.status]||row.status}</Note></View><Text style={{color:t.text,fontSize:17,fontWeight:'600'}}>{row.title}</Text><Note>{formatDateTime(row.createTime)}</Note><Icon name="arrow-forward" size={18}/></Card></Pressable>)}
|
||||
<View style={[s.row,{justifyContent:'space-between'}]}><Button title="上一页" secondary disabled={busy||page<=1} onPress={()=>void load(page-1)}/><Button title="下一页" secondary disabled={busy||page*10>=total} onPress={()=>void load(page+1)}/></View>
|
||||
</>}{!!error&&<Note>{error}</Note>}
|
||||
</ScrollView></KeyboardAvoidingView>;
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import {formatDateTime} from '../core/date-display';
|
||||
import React,{useEffect,useMemo,useState} from 'react';
|
||||
import {Pressable,ScrollView,Text,View} from 'react-native';
|
||||
import {Button,Card,Heading,Icon,Note,s,useTheme} from '../ui';
|
||||
@ -15,12 +16,12 @@ export function MessageCenter({api,onRead}:{api:ApiClient;onRead:()=>void}){
|
||||
{!!state.error&&<Note>{state.error}</Note>}
|
||||
{detail?<>
|
||||
<Button title="返回消息列表" secondary disabled={state.reading} onPress={center.back}/>
|
||||
<Card><Heading>{detail.title}</Heading><Note>{detail.time||'—'} · {detail.read?'已读':'未读'}</Note><Text selectable style={{color:t.text,lineHeight:27,fontSize:16}}>{detail.content||'暂无正文'}</Text>{!detail.read&&<Button title="标为已读" busy={state.reading} onPress={()=>void center.mark(true)}/>}</Card>
|
||||
<Card><Heading>{detail.title}</Heading><Note>{formatDateTime(detail.time)} · {detail.read?'已读':'未读'}</Note><Text selectable style={{color:t.text,lineHeight:27,fontSize:16}}>{detail.content||'暂无正文'}</Text>{!detail.read&&<Button title="标为已读" busy={state.reading} onPress={()=>void center.mark(true)}/>}</Card>
|
||||
</>:<>
|
||||
<View style={s.row}>{state.tab==='inbox'?<Button title={state.unreadOnly?'✓ 只看未读':'只看未读'} secondary disabled={busy} onPress={()=>void center.filter(!state.unreadOnly)}/>:<Note>最近 5 条通知公告</Note>}<Button title="刷新" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load()}/></View>
|
||||
{unread&&<Button title="已加载消息标为已读" secondary busy={state.reading} disabled={state.busy} onPress={()=>void center.mark()}/>}
|
||||
{!items.length&&<Note>{state.busy?'正在获取消息…':state.hasMore?'本页暂无可查看的消息,可继续加载较早消息。':state.tab==='notices'?'暂无通知公告':state.unreadOnly?'暂无未读消息':'暂无站内消息'}</Note>}
|
||||
{items.map(item=>{const read=state.tab==='inbox'?!!item.readAt:!!item.isRead;return <Pressable key={item.id??item.noticeId} accessibilityRole="button" accessibilityLabel={(read?'已读:':'未读:')+(item.title||item.noticeTitle)} disabled={busy} onPress={()=>void center.detail(item)}><Card><View style={[s.row,{flexWrap:'nowrap'}]}>{!read&&<View style={{width:7,height:7,borderRadius:4,backgroundColor:t.accent}}/>}<Text style={{flex:1,color:t.text,fontSize:16,fontWeight:read?'400':'700',lineHeight:24}}>{item.title||item.noticeTitle}</Text><Icon name="chevron-forward" size={18}/></View><Note>{item.deliveredAt||item.createTime||'—'}</Note>{state.tab==='inbox'&&<Text numberOfLines={2} style={{color:t.muted,lineHeight:21}}>{item.content}</Text>}</Card></Pressable>;})}
|
||||
{items.map(item=>{const read=state.tab==='inbox'?!!item.readAt:!!item.isRead;return <Pressable key={item.id??item.noticeId} accessibilityRole="button" accessibilityLabel={(read?'已读:':'未读:')+(item.title||item.noticeTitle)} disabled={busy} onPress={()=>void center.detail(item)}><Card><View style={[s.row,{flexWrap:'nowrap'}]}>{!read&&<View style={{width:7,height:7,borderRadius:4,backgroundColor:t.accent}}/>}<Text style={{flex:1,color:t.text,fontSize:16,fontWeight:read?'400':'700',lineHeight:24}}>{item.title||item.noticeTitle}</Text><Icon name="chevron-forward" size={18}/></View><Note>{formatDateTime(item.deliveredAt||item.createTime)}</Note>{state.tab==='inbox'&&<Text numberOfLines={2} style={{color:t.muted,lineHeight:21}}>{item.content}</Text>}</Card></Pressable>;})}
|
||||
{state.tab==='inbox'&&state.hasMore&&<Button title="加载更早消息" secondary busy={state.busy} disabled={state.reading} onPress={()=>void center.load(true)}/>}
|
||||
</>}
|
||||
</ScrollView>;
|
||||
|
||||
28
mobile-app/tests/arrival-photos.test.mjs
Normal file
28
mobile-app/tests/arrival-photos.test.mjs
Normal file
@ -0,0 +1,28 @@
|
||||
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({permission=true,cancel=false,failOnce=false}={}){
|
||||
const source=await readFile(new URL('../src/screens/ArrivalPhotos.tsx',import.meta.url),'utf8'),compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
|
||||
const values=[],refs=[],calls=[],camera=[],cleanup=[];let state=0,ref=0,photos=[],fail=failOnce;
|
||||
const react={...React,useState:v=>{const i=state++;if(!(i in values))values[i]=v;return[values[i],v=>{values[i]=typeof v==='function'?v(values[i]):v;}];},useRef:v=>{const i=ref++;return refs[i]??={current:v};},useEffect:fn=>{const value=fn();if(value)cleanup.push(value);}};
|
||||
const picker={async requestCameraPermissionsAsync(){return {granted:permission};},async launchCameraAsync(options){camera.push(options);return {canceled:cancel,assets:[{uri:'file:///camera.jpg',mimeType:'image/jpeg',fileSize:1000}]};},async launchImageLibraryAsync(){return {canceled:cancel,assets:[{uri:'file:///album.jpg',mimeType:'image/jpeg',fileSize:1000}]};}};
|
||||
class Form {values=new Map();append(k,v){this.values.set(k,v);}get(k){return this.values.get(k);}}
|
||||
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Image:'Image',Platform:{OS:'android'}},'expo-image-picker':picker,'expo-crypto':{randomUUID:()=> '11111111-1111-4111-8111-111111111111'},'../ui':{Button:'Button',Note:'Note',s:{}},'../files':{ProtectedImage:'ProtectedImage'}};
|
||||
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:n=>imports[n]||require(n),FormData:Form,AbortController});
|
||||
const api={async request(path,options){calls.push({path,options});if(fail){fail=false;throw Error('模拟上传失败');}return {data:{id:options.body?.get('uploadId'),name:'到货.jpg'}};}};
|
||||
let tree;const render=()=>{state=0;ref=0;tree=module.exports.ArrivalPhotos({api,requestId:10,photos,onChange:v=>{photos=v;}});};render();
|
||||
function find(title,node=tree){if(!node||typeof node!=='object')return null;if(node.type==='Button'&&node.props.title===title)return node;for(const child of React.Children.toArray(node.props?.children)){const value=find(title,child);if(value)return value;}return null;}
|
||||
return {calls,camera,render,button:find,get photos(){return photos;},cleanup:()=>cleanup.forEach(fn=>fn())};
|
||||
}
|
||||
test('camera permission denial and camera cancellation do not upload or block a photo-free arrival',async()=>{
|
||||
for(const options of [{permission:false},{cancel:true}]){const page=await screen(options);await page.button('拍照').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls.length,0);assert.equal(page.photos.length,0);page.cleanup();}
|
||||
});
|
||||
test('taking a photo sends an image-only camera request and private multipart upload',async()=>{
|
||||
const page=await screen();await page.button('拍照').props.onPress();await new Promise(r=>setImmediate(r));assert.deepEqual(Array.from(page.camera[0].mediaTypes),['images']);assert.equal(page.calls[0].path,'/warehouse/purchase/arrival/photos/10');assert.equal(page.calls[0].options.body.get('file').uri,'file:///camera.jpg');assert.equal(page.photos[0].id,'11111111-1111-4111-8111-111111111111');page.cleanup();
|
||||
});
|
||||
test('album uploads can retry the same photo identifier after failure',async()=>{
|
||||
const page=await screen({failOnce:true});await page.button('从相册选择').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.photos[0].error,'模拟上传失败');page.render();await page.button('重试上传').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls[0].options.body.get('uploadId'),page.calls[1].options.body.get('uploadId'));assert.ok(page.photos[0].id);page.cleanup();
|
||||
});
|
||||
23
mobile-app/tests/date-display.test.mjs
Normal file
23
mobile-app/tests/date-display.test.mjs
Normal file
@ -0,0 +1,23 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {formatDateTime,displayTimestamp} from '../src/core/date-display.ts';
|
||||
import {display} from '../src/core/modules.ts';
|
||||
import {referenceText} from '../src/core/assistant-display.ts';
|
||||
|
||||
test('native messages, feedback and generic lists display readable timestamps',()=>{
|
||||
for(const value of ['2026-10-26T12:01:54','2026-10-26T12:01:54.123456','2026-10-26 12:01:54'])assert.equal(formatDateTime(value),'2026-10-26 12:01:54');
|
||||
assert.equal(display('2026-10-26T12:01:54'),'2026-10-26 12:01:54');
|
||||
assert.equal(referenceText('2026-10-26T12:01:54'),'2026-10-26 12:01:54');
|
||||
assert.equal(formatDateTime('2026-10-26'),'2026-10-26');
|
||||
});
|
||||
test('native timestamp offsets and numeric epoch values refer to the same instant',()=>{
|
||||
const instant=Date.UTC(2026,9,26,4,1,54),expected=formatDateTime(new Date(instant));
|
||||
assert.equal(formatDateTime('2026-10-26T12:01:54+08:00'),expected);
|
||||
assert.equal(formatDateTime('2026-10-26T04:01:54Z'),expected);
|
||||
assert.equal(formatDateTime(instant/1000),expected);
|
||||
assert.equal(formatDateTime(String(instant)),expected);
|
||||
});
|
||||
test('native invalid dates are safe and ordinary values are preserved',()=>{
|
||||
for(const value of [null,'','invalid',new Date(NaN),{},true,'2026-02-30'])assert.equal(formatDateTime(value),'—');
|
||||
for(const value of [1000,'物品T1','2026-10-26T12:01:54.pdf'])assert.equal(displayTimestamp(value),value);
|
||||
});
|
||||
@ -5,6 +5,7 @@ import {createRequire} from 'node:module';
|
||||
import vm from 'node:vm';
|
||||
import {modules} from '../src/core/modules.ts';
|
||||
import {allows} from '../src/core/network.ts';
|
||||
import * as dateDisplay from '../src/core/date-display.ts';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
|
||||
async function screen({mode='arrival',failure=false}={}){
|
||||
@ -15,7 +16,7 @@ async function screen({mode='arrival',failure=false}={}){
|
||||
const react={...React,useState:initial=>{const i=cursor++;if(!(i in values))values[i]=initial;return[values[i],v=>values[i]=typeof v==='function'?v(values[i]):v];},useRef:initial=>{const i=refCursor++;return refs[i]??= {current:initial};},useEffect:()=>{}};
|
||||
const native={Modal:'Modal',ScrollView:'ScrollView',View:'View',KeyboardAvoidingView:'KeyboardAvoidingView',Platform:{OS:'android'}};
|
||||
const ui={useTheme:()=>({bg:'#fff'}),s:{},Button:'Button',Card:'Card',Choice:'Choice',Field:'Field',Heading:'Heading',Note:'Note'};
|
||||
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}}};
|
||||
const imports={'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}}};
|
||||
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>imports[name]||require(name),AbortController});
|
||||
const api={async request(path,options){calls.push({path,...options});if(failure)throw Error('timeout');return {data:{}};}};
|
||||
const render=()=>{cursor=0;refCursor=0;return module.exports.ArrivalOperation({api,row:{id:10,materialName:'电机',remainingQuantity:2,unit:'个'},mode,close(){},done(){done++;}});};
|
||||
|
||||
@ -0,0 +1,33 @@
|
||||
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.warehouse.service.impl.PurchaseArrivalPhotoService;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/warehouse/purchase/arrival/photos")
|
||||
public class PurchaseArrivalPhotoController {
|
||||
private final PurchaseArrivalPhotoService photos;
|
||||
public PurchaseArrivalPhotoController(PurchaseArrivalPhotoService photos){this.photos=photos;}
|
||||
@PostMapping("/{requestId}")
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@Log(title="上传到货照片",businessType=BusinessType.INSERT)
|
||||
public AjaxResult upload(@PathVariable Long requestId,@RequestParam String uploadId,@RequestParam MultipartFile file){return AjaxResult.success(photos.upload(requestId,uploadId,file));}
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
public AjaxResult remove(@PathVariable String id){photos.removeDraft(id);return AjaxResult.success();}
|
||||
@GetMapping("/{id}/content")
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
public ResponseEntity<byte[]> read(@PathVariable String id){
|
||||
var photo=photos.content(id);
|
||||
return ResponseEntity.ok().contentType(MediaType.parseMediaType(photo.type())).contentLength(photo.bytes().length).cacheControl(CacheControl.noStore())
|
||||
.header("X-Content-Type-Options","nosniff").header("Content-Security-Policy","sandbox; default-src 'none'; frame-ancestors 'self'")
|
||||
.header("Content-Disposition",ContentDisposition.inline().filename(photo.name(),StandardCharsets.UTF_8).build().toString()).body(photo.bytes());
|
||||
}
|
||||
}
|
||||
@ -22,6 +22,7 @@ public class PurchasePriceController
|
||||
@PostMapping("/price-lock")
|
||||
public AjaxResult lock(@RequestBody Long[] ids)
|
||||
{
|
||||
com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
|
||||
if (ids == null || ids.length == 0 || ids.length > 1000)
|
||||
throw new ServiceException("请选择1至1000条采购明细");
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
|
||||
@ -37,6 +37,7 @@ import com.ruoyi.warehouse.service.IProductInfoService;
|
||||
import com.ruoyi.warehouse.service.IPurchaseRequestService;
|
||||
import com.ruoyi.warehouse.service.IPurchaseSmartImportService;
|
||||
import com.ruoyi.warehouse.util.WarehouseFileUtils;
|
||||
import com.ruoyi.warehouse.util.PurchaseQuoteAccess;
|
||||
import com.ruoyi.project.domain.ExpenseCategory;
|
||||
import com.ruoyi.project.service.IProjectBudgetService;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
@ -85,13 +86,13 @@ public class PurchaseRequestController extends BaseController
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
@GetMapping("/sheet/{id}")
|
||||
public AjaxResult sheet(@PathVariable Long id) { return success(sheetService.load(id)); }
|
||||
public AjaxResult sheet(@PathVariable Long id) { return success(PurchaseQuoteAccess.view(sheetService.load(id))); }
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:manage') && @ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @PostMapping("/sheet/prepare")
|
||||
@Log(title="采购组批",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult prepareSheet(@RequestBody Long[] ids,@org.springframework.web.bind.annotation.RequestParam(required=false) Long batchId){return success(sheetService.prepare(ids,batchId));}
|
||||
public AjaxResult prepareSheet(@RequestBody Long[] ids,@org.springframework.web.bind.annotation.RequestParam(required=false) Long batchId){return success(PurchaseQuoteAccess.view(sheetService.prepare(ids,batchId)));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
@GetMapping("/sheet/unbatched")
|
||||
public AjaxResult unbatchedSheet(@org.springframework.web.bind.annotation.RequestParam Long[] ids){return success(sheetService.loadUnbatched(ids));}
|
||||
public AjaxResult unbatchedSheet(@org.springframework.web.bind.annotation.RequestParam Long[] ids){return success(PurchaseQuoteAccess.view(sheetService.loadUnbatched(ids)));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/sheet/plans")
|
||||
public AjaxResult sheetPlans(Long projectId,String keyword){
|
||||
var args=new java.util.ArrayList<Object>();var where=new StringBuilder(" where t.status='OPEN'");if(projectId!=null){where.append(" and t.project_id=?");args.add(projectId);}if(keyword!=null&&!keyword.isBlank()){where.append(" and convert(concat_ws(' ',t.task_no,p.product_name) using utf8mb4) collate utf8mb4_general_ci like ?");args.add("%"+keyword+"%");}
|
||||
@ -101,20 +102,22 @@ public class PurchaseRequestController extends BaseController
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:remove,warehouse:purchase:manage')")
|
||||
@Log(title = "采购批次表格", businessType = BusinessType.UPDATE)
|
||||
@PostMapping("/sheet")
|
||||
public AjaxResult saveSheet(@RequestBody com.ruoyi.warehouse.domain.PurchaseSheet sheet) { return success(sheetService.save(sheet)); }
|
||||
public AjaxResult saveSheet(@RequestBody com.ruoyi.warehouse.domain.PurchaseSheet sheet) { return success(PurchaseQuoteAccess.view(sheetService.save(sheet))); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:remove,warehouse:purchase:manage')")
|
||||
@GetMapping("/sheet/submission/{key}")
|
||||
public AjaxResult savedSheetSubmission(@PathVariable String key) { return success(sheetService.savedSubmission(key)); }
|
||||
public AjaxResult savedSheetSubmission(@PathVariable String key) { return success(PurchaseQuoteAccess.view(sheetService.savedSubmission(key))); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@Log(title = "确认采购报价", businessType = BusinessType.UPDATE)
|
||||
@PostMapping("/sheet/{id}/confirm")
|
||||
public AjaxResult confirmSheet(@PathVariable Long id, @Validated @RequestBody com.ruoyi.warehouse.domain.PurchaseSheetConfirmRequest data) {
|
||||
PurchaseQuoteAccess.require();
|
||||
return success(data.getRowIds()==null?sheetService.confirm(id,data.getVersion()):sheetService.confirm(id,data.getVersion(),data.getRowIds()));
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @PostMapping("/sheet/{id}/quote-preview")
|
||||
public AjaxResult quotePreview(@PathVariable Long id,MultipartFile file,@org.springframework.web.bind.annotation.RequestParam(required=false) String version)throws Exception {
|
||||
PurchaseQuoteAccess.require();
|
||||
WarehouseFileUtils.validateUpload(file,10L*1024*1024,Set.of("xls","xlsx"));
|
||||
var sheet=sheetService.load(id);
|
||||
if(version!=null&&!java.util.Objects.equals(version,sheet.getVersion()))throw new com.ruoyi.common.exception.ServiceException("采购清单已变化,请刷新后重新上传报价");
|
||||
@ -125,8 +128,9 @@ public class PurchaseRequestController extends BaseController
|
||||
public void inquiryExport(@PathVariable Long id,@org.springframework.web.bind.annotation.RequestParam String version,HttpServletResponse response)throws Exception {
|
||||
var sheet=sheetService.load(id);
|
||||
if(!java.util.Objects.equals(version,sheet.getVersion()))throw new com.ruoyi.common.exception.ServiceException("采购清单已变化,请刷新后重新导出询价单");
|
||||
boolean compactAmounts=amountDisplaySettings.enabled();
|
||||
boolean compactAmounts=PurchaseQuoteAccess.allowed()&&amountDisplaySettings.enabled();
|
||||
if(compactAmounts)sheet.setRows(sheet.getRows().stream().filter(row->row.getFinalUnitPrice()==null||row.getFinalUnitPrice().signum()!=0).toList());
|
||||
sheet=PurchaseQuoteAccess.view(sheet);
|
||||
try(var workbook=SupplierInquiryExport.workbook(sheet,!compactAmounts)) {
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
com.ruoyi.common.utils.file.FileUtils.setAttachmentResponseHeader(response,"供应商询价单_"+sheet.getBatch().getBatchNo()+".xlsx");
|
||||
@ -168,9 +172,12 @@ public class PurchaseRequestController extends BaseController
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(PurchaseRequest purchaseRequest)
|
||||
{
|
||||
com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(purchaseRequest);
|
||||
purchaseDisplay(purchaseRequest);
|
||||
startPage();
|
||||
return getDataTable(purchaseRequestService.selectPurchaseRequestList(purchaseRequest));
|
||||
var rows=purchaseRequestService.selectPurchaseRequestList(purchaseRequest);
|
||||
var result=getDataTable(rows);
|
||||
result.setRows(PurchaseQuoteAccess.rows(rows));
|
||||
return result;
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
@ -180,13 +187,13 @@ public class PurchaseRequestController extends BaseController
|
||||
return success(purchaseRequestService.selectPurchaseTaskSummary());
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/filtered")
|
||||
public AjaxResult filtered(PurchaseRequest query){return success(purchaseRequestService.selectPurchaseRequestList(com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(query)));}
|
||||
public AjaxResult filtered(PurchaseRequest query){return success(PurchaseQuoteAccess.rows(purchaseRequestService.selectPurchaseRequestList(purchaseDisplay(query))));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/filtered-totals")
|
||||
public AjaxResult totals(PurchaseRequest query){
|
||||
var rows=purchaseRequestService.selectPurchaseRequestList(com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(query));java.math.BigDecimal locked=java.math.BigDecimal.ZERO,amount=java.math.BigDecimal.ZERO,actual=java.math.BigDecimal.ZERO;int missing=0,actualCount=0;
|
||||
var rows=purchaseRequestService.selectPurchaseRequestList(purchaseDisplay(query));java.math.BigDecimal locked=java.math.BigDecimal.ZERO,amount=java.math.BigDecimal.ZERO,actual=java.math.BigDecimal.ZERO;int missing=0,actualCount=0;
|
||||
for(var row:rows){if(row.getFinalUnitPrice()==null)missing++;else amount=amount.add(row.getFinalUnitPrice().multiply(row.getQuantity()));if(row.getLockedAmount()!=null&&!Integer.valueOf(5).equals(row.getPurchaseStatus()))locked=locked.add(row.getLockedAmount());}
|
||||
for(var row:rows)if(!Integer.valueOf(5).equals(row.getPurchaseStatus())&&row.getActualAmount()!=null){actual=actual.add(row.getActualAmount());actualCount++;}
|
||||
var result=new java.util.LinkedHashMap<String,Object>();result.put("count",rows.size());result.put("amount",amount);result.put("lockedAmount",locked);result.put("unpriced",missing);result.put("actualAmount",actualCount==0?null:actual);return success(result);
|
||||
var result=new java.util.LinkedHashMap<String,Object>();result.put("count",rows.size());if(PurchaseQuoteAccess.allowed()){result.put("amount",amount);result.put("lockedAmount",locked);}result.put("unpriced",missing);result.put("actualAmount",actualCount==0?null:actual);return success(result);
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:export,warehouse:purchase:manage')")
|
||||
@ -194,14 +201,15 @@ public class PurchaseRequestController extends BaseController
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, PurchaseRequest purchaseRequest, @org.springframework.web.bind.annotation.RequestParam(required=false) Long[] ids) throws Exception
|
||||
{
|
||||
com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(purchaseRequest);
|
||||
purchaseDisplay(purchaseRequest);
|
||||
List<PurchaseRequest> list = purchaseRequestService.selectPurchaseRequestList(purchaseRequest);
|
||||
if(ids!=null && ids.length>0){var selected=new java.util.HashSet<>(java.util.Arrays.asList(ids));list=list.stream().filter(row->selected.contains(row.getId())).toList();}
|
||||
PurchaseTemplateExcelUtil.writeExport(response, list, productInfoService.selectProductInfoAll());
|
||||
PurchaseTemplateExcelUtil.writeExport(response, list, productInfoService.selectProductInfoAll(),PurchaseQuoteAccess.allowed());
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:export,warehouse:purchase:manage')")
|
||||
@PostMapping("/supplier-export") @Log(title="供应商采购汇总导出",businessType=BusinessType.EXPORT)
|
||||
public void supplierExport(HttpServletResponse response,PurchaseRequest query,@org.springframework.web.bind.annotation.RequestParam(required=false) Long[] ids)throws Exception{
|
||||
PurchaseQuoteAccess.require();
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
com.ruoyi.common.utils.file.FileUtils.setAttachmentResponseHeader(response,"供应商采购汇总.xlsx");
|
||||
var rows=purchaseRequestService.selectPurchaseRequestList(com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(query));
|
||||
@ -255,14 +263,14 @@ public class PurchaseRequestController extends BaseController
|
||||
@GetMapping("/{id}")
|
||||
public AjaxResult getInfo(@PathVariable Long id)
|
||||
{
|
||||
return success(purchaseRequestService.selectPurchaseRequestById(id));
|
||||
return success(PurchaseQuoteAccess.view(purchaseRequestService.selectPurchaseRequestById(id)));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:query,warehouse:purchase:manage')")
|
||||
@GetMapping("/{id}/operations")
|
||||
public AjaxResult operationList(@PathVariable Long id)
|
||||
{
|
||||
return success(purchaseOperationLogService.selectByPurchaseRequestId(id));
|
||||
return success(purchaseOperationLogService.selectByPurchaseRequestId(id).stream().map(PurchaseQuoteAccess::view).toList());
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:manage')")
|
||||
@ -302,7 +310,7 @@ public class PurchaseRequestController extends BaseController
|
||||
@GetMapping("/arrival/{requestId}")
|
||||
public AjaxResult arrivalList(@PathVariable Long requestId)
|
||||
{
|
||||
return success(purchaseArrivalService.selectPurchaseArrivalList(requestId));
|
||||
return success(purchaseArrivalService.selectPurchaseArrivalList(requestId).stream().map(PurchaseQuoteAccess::view).toList());
|
||||
}
|
||||
public record CancelRemaining(java.math.BigDecimal expectedQuantity,String reason){}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@ -344,13 +352,15 @@ public class PurchaseRequestController extends BaseController
|
||||
return toAjax(purchaseArrivalService.deletePurchaseArrival(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
@GetMapping("/batch/list")
|
||||
public TableDataInfo batchList(PurchaseBatch batch)
|
||||
{
|
||||
com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(batch);
|
||||
if(PurchaseQuoteAccess.allowed())com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(batch);
|
||||
else batch.getParams().remove("amountDisplay");
|
||||
startPage();
|
||||
return getDataTable(purchaseBatchService.selectPurchaseBatchList(batch));
|
||||
var rows=purchaseBatchService.selectPurchaseBatchList(batch);
|
||||
var result=getDataTable(rows);result.setRows(rows.stream().map(PurchaseQuoteAccess::view).toList());return result;
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
@ -364,7 +374,7 @@ public class PurchaseRequestController extends BaseController
|
||||
@GetMapping("/batch/filter-options")
|
||||
public AjaxResult batchFilterOptions(String keyword)
|
||||
{
|
||||
return success(purchaseBatchService.selectPurchaseBatchFilterOptions(keyword));
|
||||
return success(purchaseBatchService.selectPurchaseBatchFilterOptions(keyword).stream().map(PurchaseQuoteAccess::view).toList());
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
@ -407,4 +417,10 @@ public class PurchaseRequestController extends BaseController
|
||||
{
|
||||
return toAjax(purchaseRequestService.deletePurchaseRequestByIds(ids));
|
||||
}
|
||||
|
||||
private PurchaseRequest purchaseDisplay(PurchaseRequest query) {
|
||||
if(PurchaseQuoteAccess.allowed())com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(query);
|
||||
else query.getParams().remove("amountDisplay");
|
||||
return query;
|
||||
}
|
||||
}
|
||||
|
||||
@ -276,6 +276,12 @@ public final class PurchaseTemplateExcelUtil
|
||||
|
||||
public static void writeExport(HttpServletResponse response, List<PurchaseRequest> requests,
|
||||
List<ProductInfo> products) throws IOException
|
||||
{
|
||||
writeExport(response,requests,products,true);
|
||||
}
|
||||
|
||||
public static void writeExport(HttpServletResponse response, List<PurchaseRequest> requests,
|
||||
List<ProductInfo> products, boolean includeQuotes) throws IOException
|
||||
{
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
response.setCharacterEncoding("utf-8");
|
||||
@ -287,12 +293,19 @@ public final class PurchaseTemplateExcelUtil
|
||||
Sheet options = workbook.createSheet("系统下拉数据");
|
||||
CellStyle headerStyle = createHeaderStyle(workbook);
|
||||
Row header = sheet.createRow(0);
|
||||
for (int index = 0; index < EXPORT_HEADERS.length; index++)
|
||||
// Build only authorized cells; never hide confidential values in Excel columns.
|
||||
var columns = new ArrayList<Integer>();
|
||||
for(int index=0;index<EXPORT_HEADERS.length;index++) {
|
||||
if(index==11){columns.add(-1);columns.add(-2);}
|
||||
if(includeQuotes || !Set.of(11,12,15).contains(index))columns.add(index);
|
||||
}
|
||||
for (int index = 0; index < columns.size(); index++)
|
||||
{
|
||||
int source=columns.get(index);
|
||||
Cell cell = header.createCell(index);
|
||||
cell.setCellValue(EXPORT_HEADERS[index]);
|
||||
cell.setCellValue(source==-1?"实际单价(内部参考)":source==-2?"实际金额(内部参考)":EXPORT_HEADERS[source]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
sheet.setColumnWidth(index, exportColumnWidth(index));
|
||||
sheet.setColumnWidth(index, source<0?20*256:exportColumnWidth(source));
|
||||
}
|
||||
sheet.createFreezePane(0, 1);
|
||||
|
||||
@ -311,9 +324,10 @@ public final class PurchaseTemplateExcelUtil
|
||||
request.getRequestRemark(), request.getAcceptedQuantity(), request.getPendingArrivalQuantity(),
|
||||
"REPAY".equals(request.getPurchasePurpose()) ? "采购归还" : "本项目使用", request.getLoanId(), request.getProductionTaskId(), request.getSupplierName()
|
||||
};
|
||||
for (int column = 0; column < values.length; column++)
|
||||
for (int column = 0; column < columns.size(); column++)
|
||||
{
|
||||
setCellValue(row.createCell(column), values[column]);
|
||||
int source=columns.get(column);
|
||||
setCellValue(row.createCell(column), source==-1?request.getActualUnitPrice():source==-2?request.getActualAmount():values[source]);
|
||||
}
|
||||
}
|
||||
|
||||
@ -322,7 +336,7 @@ public final class PurchaseTemplateExcelUtil
|
||||
addOptionColumn(workbook, sheet, options, 6, "品牌", values(products, "brand"));
|
||||
addOptionColumn(workbook, sheet, options, 7, "类别", values(products, "category"));
|
||||
addOptionColumn(workbook, sheet, options, 8, "参数规格", values(products, "spec"));
|
||||
addOptionColumn(workbook, sheet, options, 13, "单位", values(products, "unit"));
|
||||
addOptionColumn(workbook, sheet, options, columns.indexOf(13), "单位", values(products, "unit"));
|
||||
workbook.setSheetVisibility(workbook.getSheetIndex(options), SheetVisibility.HIDDEN);
|
||||
workbook.write(response.getOutputStream());
|
||||
}
|
||||
|
||||
@ -59,6 +59,7 @@ public class AssistantReferencePriceService {
|
||||
private BigDecimal amount(BigDecimal price,BigDecimal quantity) { return price==null?null:price.multiply(quantity).setScale(2,RoundingMode.HALF_UP); }
|
||||
private boolean clearsQuote(Map<String,Object> input) { return Set.of("COPY_QUOTE_CLEAR_QUOTE","CLEAR_QUOTE").contains(Objects.toString(input.get("mode"),"")); }
|
||||
private void correctionPermission(Map<String,Object> input) {
|
||||
if("COPY_QUOTE".equals(input.get("mode")))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
|
||||
if(clearsQuote(input)&&!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))
|
||||
throw new ServiceException("清空报价涉及金额及成本更正,请采购管理员协助办理",403);
|
||||
}
|
||||
@ -91,7 +92,7 @@ public class AssistantReferencePriceService {
|
||||
row.put("blocked",!restriction.isEmpty());row.put("correctionImpact",impact);
|
||||
if(!impact.isEmpty())row.put("notice",(restriction.isEmpty()?"":restriction+";")+impact.get("notice"));
|
||||
}
|
||||
return rows;
|
||||
return rows.stream().map(com.ruoyi.warehouse.util.PurchaseQuoteAccess::viewMap).toList();
|
||||
}
|
||||
public Map<String,Object> preview(Map<String,Object> input) {
|
||||
correctionPermission(input);var scope=scope(input);var rows=previewRows(input,scope);var result=new LinkedHashMap<String,Object>();
|
||||
@ -120,6 +121,6 @@ public class AssistantReferencePriceService {
|
||||
for(var value:scope.selected())if(ids.contains(value.getId()))value.setActualUnitPrice(target(input,value));
|
||||
scope.sheet().setDeletedIds(List.of());scope.sheet().setSubmissionKey(executionKey);sheets.save(scope.sheet());
|
||||
return Map.of("message","已更新"+ids.size()+"项实际单价及实际金额;报价和成本未改变","changed",ids.size(),"rows",changes,
|
||||
"columns",List.of(Map.of("key","name","label","物品"),Map.of("key","spec","label","规格"),Map.of("key","oldActualPrice","label","原实际单价"),Map.of("key","newActualPrice","label","新实际单价"),Map.of("key","newActualAmount","label","新实际金额"),Map.of("key","quotePrice","label","原报价"),Map.of("key","newQuotePrice","label","新报价"),Map.of("key","newQuoteAmount","label","新报价金额"),Map.of("key","notice","label","核对说明")));
|
||||
"columns",List.of(Map.of("key","name","label","物品"),Map.of("key","spec","label","规格"),Map.of("key","oldActualPrice","label","原实际单价"),Map.of("key","newActualPrice","label","新实际单价"),Map.of("key","newActualAmount","label","新实际金额"),Map.of("key","quotePrice","label","原报价"),Map.of("key","newQuotePrice","label","新报价"),Map.of("key","newQuoteAmount","label","新报价金额"),Map.of("key","notice","label","核对说明")).stream().filter(column->com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed()||!Set.of("quotePrice","newQuotePrice","newQuoteAmount").contains(column.get("key"))).toList());
|
||||
}
|
||||
}
|
||||
|
||||
@ -89,7 +89,7 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
|
||||
private List<Map<String,Object>> describeFields(Action action) {
|
||||
return action.fields().stream().sorted(Comparator.comparingInt(field->businessFieldOrder(action,field.key(),true))).map(field -> {
|
||||
return action.fields().stream().filter(field->!action.key().startsWith("purchase.") || !"finalUnitPrice".equals(field.key()) || com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed()).sorted(Comparator.comparingInt(field->businessFieldOrder(action,field.key(),true))).map(field -> {
|
||||
Map<String,Object> result=field.describe();
|
||||
if(SYSTEM_DERIVED_FIELDS.contains(field.key()))result.put("readonly",true);
|
||||
if(Set.of("quoteSummary","recipientVersion").contains(field.key()))result.put("hidden",true);
|
||||
@ -117,7 +117,10 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
if(AssistantMessages.administratorOnly(action) && !supplementalAllowed(definition))
|
||||
throw new ServiceException(AssistantMessages.forAction(action),403);
|
||||
if(!supplementalAllowed(definition))throw new ServiceException("当前账号暂无项目物资使用权限",403);
|
||||
if(!supplementalAllowed(definition)) {
|
||||
if(Set.of("purchase.lock","purchase.supplierExport").contains(action))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
|
||||
throw new ServiceException("当前账号暂无项目物资使用权限",403);
|
||||
}
|
||||
}
|
||||
|
||||
/** Read/write classification is owned by the registered server capability, never model input. */
|
||||
@ -138,6 +141,7 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
|
||||
private boolean supplementalAllowed(Action action) {
|
||||
if(Set.of("purchase.lock","purchase.confirm","purchase.supplierExport","batch.confirm").contains(action.key()))return com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed();
|
||||
if("role.dataScope".equals(action.key()))return com.ruoyi.common.utils.SecurityUtils.isAdmin();
|
||||
if(!Set.of("material.issue","material.return","material.revoke","material.revokeReturn").contains(action.key()))return true;
|
||||
Set<String> current=com.ruoyi.common.utils.SecurityUtils.getLoginUser().getPermissions();
|
||||
@ -282,6 +286,8 @@ public class BusinessActionRegistry {
|
||||
errors.add("当前查询不支持筛选字段:"+key+",请调整查询条件");
|
||||
}
|
||||
}
|
||||
if(PURCHASE_ACTIONS.contains(action.key())&&!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed()
|
||||
&&(input.get("finalUnitPrice")!=null||input.get("estimatedUnitPrice")!=null))errors.add("报价金额仅采购管理员可查看和维护");
|
||||
if("notification.send".equals(action.key()))input=AssistantNotificationService.selectionInput(input);
|
||||
input=withExistingValues(action,input,snapshots);
|
||||
if("purchase.correctPrice".equals(action.key())) input=new LinkedHashMap<>(input);
|
||||
@ -391,8 +397,11 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
if(!errors.isEmpty())for(var quote:AssistantConversationService.maps(row.get("_quotePreview")))quote.put("error",String.join(";",errors));
|
||||
}
|
||||
if(!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())for(Field field:action.fields())
|
||||
if(Set.of("purchase","batch").contains(Objects.toString(field.ref(),""))&&snapshots.get(field.key()) instanceof Map<?,?>)
|
||||
snapshots.put(field.key(),com.ruoyi.warehouse.util.PurchaseQuoteAccess.viewMap(asMap(snapshots.get(field.key()))));
|
||||
row.put("_labels",labels); row.put("_snapshot",snapshots); row.put("_candidates",choices); row.put("_errors",errors);
|
||||
return row;
|
||||
return action.key().startsWith("purchase.")?com.ruoyi.warehouse.util.PurchaseQuoteAccess.viewMap(row):row;
|
||||
}
|
||||
|
||||
private static void queryPage(Map<String,Object> row,String key,int fallback,int maximum,List<String> errors) {
|
||||
@ -852,6 +861,7 @@ public class BusinessActionRegistry {
|
||||
long skip=serverPaged?0:(long)(pageNum-1)*pageSize;
|
||||
int index=0;
|
||||
for(Object item:(Collection<?>)data) { if(index++<skip)continue;if(rows.size()>=pageSize)break; rows.add(asMap(item)); }
|
||||
if(action.key().startsWith("purchase.")||action.key().startsWith("batch."))rows=rows.stream().map(com.ruoyi.warehouse.util.PurchaseQuoteAccess::viewMap).toList();
|
||||
Map<String,String> names=displayColumns();
|
||||
if(action.key().startsWith("product."))names.remove("version"); // Internal concurrency number is not a product edition.
|
||||
// Result semantics belong to this business, not the last registered action using a key.
|
||||
@ -859,6 +869,7 @@ public class BusinessActionRegistry {
|
||||
// A DTO property can also be a search input. Its record column is not a search hint.
|
||||
for(String key:List.of("productName","materialName","itemName"))names.put(key,"物品名称");
|
||||
names.put("businessDate","业务日期");names.put("reason","原因");names.put("versionTag","BOM版本");
|
||||
if(action.key().startsWith("purchase.")||action.key().startsWith("batch."))names.putAll(Map.of("actualUnitPrice","实际单价","actualAmount","实际金额","actualTotalAmount","实际总金额","finalUnitPrice","报价单价","estimatedUnitPrice","报价单价","estimatedAmount","报价金额","totalAmount","报价合计"));
|
||||
names.put("inNum","入库数量");names.put("spentAmount","已锁定采购费用");
|
||||
if(action.key().startsWith("batch.")){names.put("businessDate","采购日期");names.put("amount","报价合计");}
|
||||
if(action.key().startsWith("loan."))names.put("businessDate","借用日期");
|
||||
@ -906,8 +917,8 @@ public class BusinessActionRegistry {
|
||||
case "area"->List.of("areaName","status");
|
||||
case "supplier"->List.of("name","contact","phone","email","active");
|
||||
case "stock","stockCheck","material","receipt","arrival"->List.of("productName","itemName","materialName","itemId","productId","spec","materialParams","brand","stockNum","inNum","quantity","realNum","outNum","arrivalQuantity","acceptedQuantity","remainingQuantity","unit","areaName","area_name","areaId","fromAreaId","toAreaId","projectName","projectId","sourceProjectName","sourceProjectId","usageProjectName","usageProjectId","inStatus","checkStatus","acceptanceStatus","status","averageUnitCost","stockAmount","categoryGroupName","category");
|
||||
case "purchase"->List.of("materialName","productName","productId","quantity","unit","finalUnitPrice","estimatedUnitPrice","amount","materialParams","spec","materialBrand","brand","category","projectName","projectId","expenseCategoryId","purchaseBatchNo","purchaseBatchId","batchName","supplierName","supplierId","purchaseStatus","purchasePurpose");
|
||||
case "batch"->List.of("batchName","purchaseBatchNo","batchNo","supplierName","supplierId","purchaseStatus","quantity","amount","lockedAmount","unpriced");
|
||||
case "purchase"->List.of("materialName","productName","productId","quantity","unit","actualUnitPrice","actualAmount","finalUnitPrice","estimatedUnitPrice","estimatedAmount","amount","materialParams","spec","materialBrand","brand","category","projectName","projectId","expenseCategoryId","purchaseBatchNo","purchaseBatchId","batchName","supplierName","supplierId","purchaseStatus","purchasePurpose");
|
||||
case "batch"->List.of("batchName","purchaseBatchNo","batchNo","supplierName","supplierId","purchaseStatus","quantity","actualTotalAmount","totalAmount","amount","lockedAmount","unpriced");
|
||||
case "item","product","projectProduct","bom","cost","production"->List.of("seriesName","editionTag","itemName","item_name","productName","itemId","productId","projectName","project_name","projectId","spec","brand","category","unit","versionTag","version_tag","bomId","taskNo","task_no","taskId","status","quantity","planned_quantity","good_quantity","required","available","shortage","purchaseSuggestion","unitQuantity","unitCost","unit_cost","amount","material_cost","current_material_cost");
|
||||
case "loan"->List.of("itemName","productName","itemId","spec","brand","unit","lenderProjectName","lenderProjectId","borrowerProjectName","borrowerProjectId","areaName","fromAreaId","toAreaId","loanNo","quantity","returnedQuantity","outstandingQuantity","returnType","active","amount");
|
||||
case "budget","expenseCategory"->List.of("projectName","projectId","categoryName","expenseCategoryId","categoryCode","budgetAmount","spentAmount","committedAmount","availableAmount","alertPercent","status");
|
||||
@ -1348,7 +1359,7 @@ public class BusinessActionRegistry {
|
||||
reference("assistantFile","","name","");
|
||||
reference("dictionaryTypeRecord","select dict_id id,dict_type code,dict_name name,status,update_time updateTime from sys_dict_type","name","system:dict:list,system:dict:query,system:dict:edit,system:dict:remove");
|
||||
reference("readableNotice","select notice_id id,notice_title name,update_time updateTime from sys_notice where status='0'","name","");
|
||||
reference("purchaseAttachment","select a.id,a.original_name name,a.sha256,g.target_type targetType,g.target_id targetId,coalesce(b.batch_no,p.request_no) code from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id left join purchase_batch b on g.target_type='batch' and b.id=g.target_id left join purchase_request p on g.target_type='detail' and p.id=g.target_id where a.deleted=0","name","warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:manage");
|
||||
reference("purchaseAttachment","select a.id,a.original_name name,a.sha256,g.target_type targetType,g.target_id targetId,g.document_kind documentKind,coalesce(b.batch_no,p.request_no) code from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id left join purchase_batch b on g.target_type='batch' and b.id=g.target_id left join purchase_request p on g.target_type='detail' and p.id=g.target_id where a.deleted=0","name","warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:manage");
|
||||
for(String ref:List.of("sysUser","sysRole","sysDepartment","sysPost","sysMenu"))reference(ref,"","name","");
|
||||
reference("project","select id,project_code code,project_name name,project_type projectType,project_status projectStatus,version from project_info where del_flag='0'","name","project:project:list,project:project:query,project:project:manage,project:project:edit,project:project:add,project:budget:edit,project:inventory:use,warehouse:purchase:list,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:manage,warehouse:in:list,warehouse:in:add,warehouse:in:edit,warehouse:out:list,warehouse:out:add,warehouse:stock:out,warehouse:stock:list,warehouse:check:list,warehouse:check:add,warehouse:check:edit");
|
||||
reference("item","select id,product_code code,product_name name,brand,spec,unit,category from product_info","name","warehouse:product:list,warehouse:product:query,warehouse:product:add,warehouse:product:edit,warehouse:product:remove,warehouse:purchase:list,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:manage,warehouse:in:list,warehouse:in:confirm,warehouse:stock:list,warehouse:stock:out,warehouse:out:add,warehouse:check:add,warehouse:check:edit,production:bom:edit,production:product:edit,project:inventory:use");
|
||||
@ -1433,6 +1444,7 @@ public class BusinessActionRegistry {
|
||||
String sql="select * from ("+definition.sql()+") assistant_ref";
|
||||
List<Object> args=new ArrayList<>();
|
||||
List<String> filters=new ArrayList<>();
|
||||
if("purchaseAttachment".equals(ref)&&!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())filters.add("documentKind <> 'QUOTE'");
|
||||
if(id!=null){filters.add("id=?");args.add(id);}
|
||||
else {
|
||||
if(query!=null&&!query.isBlank()) {
|
||||
|
||||
@ -0,0 +1,37 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
class GlobalRequestFailureTest {
|
||||
@RestController static class Requests {
|
||||
record Input(String name) { }
|
||||
@GetMapping("/audit-error/number") public Object number(@RequestParam Long id){return id;}
|
||||
@PostMapping("/audit-error/body") public Object body(@RequestBody Input value){return value;}
|
||||
@GetMapping("/audit-error/runtime") public Object runtime(){throw new IllegalStateException("internal.jdbc.url=private; com.example.InternalService.run()");}
|
||||
@GetMapping("/audit-error/checked") public Object checked() throws Exception {throw new Exception("private file path and implementation details");}
|
||||
@GetMapping("/audit-error/business") public Object business(){throw new ServiceException("请先选择所属项目",403);}
|
||||
}
|
||||
private final org.springframework.test.web.servlet.MockMvc mvc=MockMvcBuilders.standaloneSetup(new Requests()).setControllerAdvice(new GlobalExceptionHandler()).build();
|
||||
@Test void missingParametersAreActionableAndContainNoJavaSignature() throws Exception {
|
||||
mvc.perform(get("/audit-error/number")).andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.msg").value("请求信息不完整,请补充必填信息后重试"));
|
||||
}
|
||||
@Test void malformedNumbersDoNotEchoInputOrJavaTypes() throws Exception {
|
||||
mvc.perform(get("/audit-error/number").param("id","private-sensitive-input")).andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.msg").value("参数格式不正确,请检查后重试"));
|
||||
}
|
||||
@Test void emptyAndMalformedJsonFailBeforeTheBusinessHandler() throws Exception {
|
||||
for(String body:new String[]{"","{","{\"name\": [1,2]}"})mvc.perform(post("/audit-error/body").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.msg").value("提交内容格式不正确,请检查后重试"));
|
||||
}
|
||||
@Test void unexpectedFailuresKeepInternalDetailsOutOfResponses() throws Exception {
|
||||
for(String path:new String[]{"runtime","checked"})mvc.perform(get("/audit-error/"+path)).andExpect(jsonPath("$.code").value(500)).andExpect(jsonPath("$.msg").value("系统暂时无法完成操作,请稍后重试;如仍有问题请联系管理员。"));
|
||||
}
|
||||
@Test void businessPermissionsRetainTheirSpecificStatusAndGuidance() throws Exception {
|
||||
mvc.perform(get("/audit-error/business")).andExpect(jsonPath("$.code").value(403)).andExpect(jsonPath("$.msg").value("请先选择所属项目"));
|
||||
}
|
||||
}
|
||||
@ -40,6 +40,9 @@ class PurchaseNamedImportTest
|
||||
@BeforeEach
|
||||
void setup()
|
||||
{
|
||||
var user=new com.ruoyi.common.core.domain.entity.SysUser();user.setUserId(7L);user.setUserName("import-manager");
|
||||
var login=new com.ruoyi.common.core.domain.model.LoginUser(7L,1L,user,java.util.Set.of("warehouse:purchase:manage"));
|
||||
org.springframework.security.core.context.SecurityContextHolder.getContext().setAuthentication(new org.springframework.security.authentication.UsernamePasswordAuthenticationToken(login,null));
|
||||
projectRows.add(project(1L, "P001", "机器人项目"));
|
||||
expenseRows.add(expense(2L, "MATERIAL", "材料费", 0));
|
||||
productRows.add(product(3L, "WP001", "A", "M4", "机械件"));
|
||||
@ -62,6 +65,8 @@ class PurchaseNamedImportTest
|
||||
when(categories.options()).thenAnswer(call -> new ArrayList<>(categoryRows));
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.AfterEach void clearSecurity(){org.springframework.security.core.context.SecurityContextHolder.clearContext();}
|
||||
|
||||
private ProjectInfo project(Long id, String code, String name)
|
||||
{
|
||||
var value = new ProjectInfo(); value.setId(id); value.setProjectCode(code); value.setProjectName(name); value.setProjectStatus(2); return value;
|
||||
|
||||
@ -0,0 +1,80 @@
|
||||
package com.ruoyi.warehouse.service.impl;
|
||||
|
||||
import com.ruoyi.common.config.RuoYiConfig;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.storage.BusinessFileStorage;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.PurchaseArrival;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchaseArrivalPhotosTest {
|
||||
static final String A="11111111-1111-4111-8111-111111111111",B="22222222-2222-4222-8222-222222222222";
|
||||
@TempDir Path temp;
|
||||
JdbcTemplate db;PurchaseArrivalPhotoService service;TransactionTemplate tx;MockedStatic<SecurityUtils> security;BusinessFileStorage storage;Map<String,byte[]> files;
|
||||
@BeforeEach void setup() throws Exception {
|
||||
var source=new JdbcDataSource();source.setURL("jdbc:h2:mem:arrival_photos_"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1");db=new JdbcTemplate(source);tx=new TransactionTemplate(new DataSourceTransactionManager(source));
|
||||
db.execute("create table purchase_request(id bigint primary key,price_locked boolean,purchase_status int,historical boolean)");
|
||||
db.execute("create table purchase_arrival(id bigint primary key)");
|
||||
db.execute("create table purchase_arrival_photo(id varchar(36) primary key,purchase_request_id bigint,arrival_id bigint references purchase_arrival(id) on delete set null,owner_id bigint,original_name varchar(180),content_type varchar(50),byte_size int,sha256 varchar(64),sort_no int default 0,create_by varchar(64),create_time timestamp default current_timestamp)");
|
||||
db.update("insert into purchase_request values(10,true,2,false),(20,true,2,false),(30,false,0,false)");
|
||||
files=new HashMap<>();storage=mock(BusinessFileStorage.class);
|
||||
doAnswer(c->{files.put(c.getArgument(0),c.getArgument(1));return null;}).when(storage).save(anyString(),any(byte[].class),anyString(),any(Path.class));
|
||||
when(storage.read(anyString(),any(Path.class),anyInt())).thenAnswer(c->files.get(c.getArgument(0)));
|
||||
doAnswer(c->{files.remove(c.getArgument(0));return null;}).when(storage).discardFailedUpload(anyString(),any(Path.class));
|
||||
new RuoYiConfig().setProfile(temp.resolve("public").toString());service=new PurchaseArrivalPhotoService(db,storage);
|
||||
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(7L);security.when(SecurityUtils::getUsername).thenReturn("uploader");
|
||||
}
|
||||
@AfterEach void cleanup(){security.close();}
|
||||
MockMultipartFile image()throws Exception{var output=new ByteArrayOutputStream();ImageIO.write(new BufferedImage(2,2,BufferedImage.TYPE_INT_RGB),"png",output);return new MockMultipartFile("file","到货.png","image/png",output.toByteArray());}
|
||||
PurchaseArrival arrival(long id,long request,String... ids){var a=new PurchaseArrival();a.setId(id);a.setPurchaseRequestId(request);a.setPhotoIds(List.of(ids));return a;}
|
||||
|
||||
@Test void optionalPhotosAndLegacyRecordsRemainEmptyWithoutImageWrites(){
|
||||
db.update("insert into purchase_arrival values(100)");var old=arrival(100,10);service.bind(old);service.attach(List.of(old));assertTrue(old.getPhotos().isEmpty());service.verifyRetry(old,100L);verifyNoInteractions(storage);
|
||||
}
|
||||
@Test void uploadBindReadAndRetryKeepOnePhotoAndImmutableEvidence()throws Exception{
|
||||
var first=tx.execute(s-> {try{return service.upload(10L,A,image());}catch(Exception e){throw new RuntimeException(e);}});
|
||||
assertEquals("image/png",first.contentType());assertEquals(first.id(),service.upload(10L,A,image()).id());assertEquals(1,db.queryForObject("select count(*) from purchase_arrival_photo",Integer.class));
|
||||
db.update("insert into purchase_arrival values(100)");var arrival=arrival(100,10,A);tx.executeWithoutResult(s->service.bind(arrival));service.attach(List.of(arrival));assertEquals(A,arrival.getPhotos().get(0).id());service.verifyRetry(arrival,100L);
|
||||
security.when(SecurityUtils::getUserId).thenReturn(8L);assertTrue(service.content(A).bytes().length>0);assertThrows(ServiceException.class,()->service.removeDraft(A));assertThrows(ServiceException.class,()->service.verifyRetry(arrival(100,10),100L));
|
||||
verify(storage,times(1)).save(anyString(),any(byte[].class),anyString(),any(Path.class));
|
||||
}
|
||||
@Test void otherOwnersAndOtherPurchasesCannotStealStagedPhotos()throws Exception{
|
||||
service.upload(10L,A,image());db.update("insert into purchase_arrival values(100)");
|
||||
security.when(SecurityUtils::getUserId).thenReturn(8L);assertThrows(ServiceException.class,()->service.content(A));assertThrows(ServiceException.class,()->service.bind(arrival(100,10,A)));assertThrows(ServiceException.class,()->service.removeDraft(A));
|
||||
security.when(SecurityUtils::getUserId).thenReturn(7L);assertThrows(ServiceException.class,()->service.bind(arrival(100,20,A)));assertNull(db.queryForObject("select arrival_id from purchase_arrival_photo where id=?",Long.class,A));
|
||||
}
|
||||
@Test void partialBindingRollsBackWithArrivalAndLeavesOriginalUploadReusable()throws Exception{
|
||||
service.upload(10L,A,image());assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->{db.update("insert into purchase_arrival values(100)");service.bind(arrival(100,10,A,B));}));
|
||||
assertEquals(0,db.queryForObject("select count(*) from purchase_arrival",Integer.class));assertNull(db.queryForObject("select arrival_id from purchase_arrival_photo where id=?",Long.class,A));assertTrue(service.content(A).bytes().length>0);
|
||||
}
|
||||
@Test void rejectsBadFilesLimitsAndUnconfirmedPurchasesBeforeStoring()throws Exception{
|
||||
assertThrows(ServiceException.class,()->service.upload(30L,A,image()));
|
||||
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","fake.png","image/png","not an image".getBytes())));
|
||||
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","large.png","image/png",new byte[5*1024*1024+1])));
|
||||
assertThrows(ServiceException.class,()->PurchaseArrivalPhotoService.ids(List.of(A,A)));assertThrows(ServiceException.class,()->PurchaseArrivalPhotoService.ids(Collections.nCopies(10,A)));
|
||||
assertThrows(ServiceException.class,()->service.content("../private"));verifyNoInteractions(storage);
|
||||
}
|
||||
@Test void removingDraftAndExpiryNeverDeleteSavedArrivalPhotos()throws Exception{
|
||||
service.upload(10L,A,image());service.upload(10L,B,image());db.update("insert into purchase_arrival values(100)");service.bind(arrival(100,10,A));
|
||||
db.update("update purchase_arrival_photo set create_time=?",java.sql.Timestamp.valueOf(java.time.LocalDateTime.now().minusDays(8)));
|
||||
tx.executeWithoutResult(s->service.expireDrafts());assertEquals(1,db.queryForObject("select count(*) from purchase_arrival_photo",Integer.class));assertTrue(files.containsKey("purchase/arrival-"+A+".bin"));assertFalse(files.containsKey("purchase/arrival-"+B+".bin"));
|
||||
}
|
||||
@Test void cancellingAnUnacceptedArrivalIsNotBlockedByItsPhotos()throws Exception{
|
||||
service.upload(10L,A,image());db.update("insert into purchase_arrival values(100)");service.bind(arrival(100,10,A));db.update("delete from purchase_arrival where id=100");
|
||||
assertNull(db.queryForObject("select arrival_id from purchase_arrival_photo where id=?",Long.class,A));tx.executeWithoutResult(s->service.removeDraft(A));assertFalse(files.containsKey("purchase/arrival-"+A+".bin"));
|
||||
}
|
||||
}
|
||||
@ -25,7 +25,7 @@ class PurchaseDocumentsTest {
|
||||
JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db);
|
||||
when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->call.getArgument(0,String.class).startsWith("select id from ")?List.of(Map.of("id",1)):List.of());
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:list")).thenReturn(true);
|
||||
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
|
||||
var groups=service.list("batch",1L);assertEquals(6,groups.size());assertTrue(groups.stream().allMatch(g->g.number().isEmpty()&&g.files().isEmpty()));
|
||||
assertEquals(List.of("REQUEST","QUOTE","CONTRACT","ACCEPTANCE","PAYMENT","OTHER"),groups.stream().map(PurchaseDocumentService.Group::kind).toList());
|
||||
assertEquals("OTHER",service.list("detail",1L).get(0).kind());
|
||||
@ -33,6 +33,26 @@ class PurchaseDocumentsTest {
|
||||
verify(db,never()).update(anyString(),any(Object[].class));
|
||||
}
|
||||
|
||||
@Test void ordinaryReadersCannotListOrDownloadQuotationFilesEvenWithKnownAttachmentIds() {
|
||||
JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db);
|
||||
when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->{
|
||||
String sql=call.getArgument(0,String.class);
|
||||
if(sql.startsWith("select id from "))return List.of(Map.of("id",1));
|
||||
if(sql.startsWith("select g.document_kind"))return List.of(Map.of("document_kind","QUOTE"));
|
||||
return List.of();
|
||||
});
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:list")).thenReturn(true);
|
||||
assertEquals(5,service.list("batch",1L).size());
|
||||
assertTrue(service.list("batch",1L).stream().noneMatch(group->group.kind().equals("QUOTE")));
|
||||
assertThrows(ServiceException.class,()->service.content("batch",1L,ID));
|
||||
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:edit")).thenReturn(true);
|
||||
assertThrows(ServiceException.class,()->service.saveNumber("batch",1L,"QUOTE","Q1",0));
|
||||
assertThrows(ServiceException.class,()->service.remove("batch",1L,ID));
|
||||
}
|
||||
verify(db,never()).update(anyString(),any(Object[].class));
|
||||
}
|
||||
|
||||
@Test void deniedRequestsNeverReadMetadataAndReadersCannotUploadChangeOrRemove() {
|
||||
JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db);
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
|
||||
@ -0,0 +1,94 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.service.*;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseSheetService;
|
||||
import com.ruoyi.warehouse.util.PurchaseQuoteAccess;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
class PurchaseQuoteAccessTest {
|
||||
private PurchaseRequest source;
|
||||
@BeforeEach void employee() {
|
||||
login(10L,Set.of("warehouse:purchase:list","warehouse:purchase:edit","warehouse:purchase:export"));
|
||||
source=new PurchaseRequest();source.setId(1L);source.setQuantity(new BigDecimal("2"));
|
||||
source.setFinalUnitPrice(new BigDecimal("891.25"));source.setEstimatedUnitPrice(new BigDecimal("891.25"));
|
||||
source.setEstimatedAmount(new BigDecimal("1782.5"));source.setLockedAmount(new BigDecimal("1782.5"));
|
||||
source.setActualUnitPrice(new BigDecimal("100"));source.setMaterialName("权限测试物品");
|
||||
}
|
||||
@AfterEach void cleanup(){SecurityContextHolder.clearContext();}
|
||||
private void login(Long id,Set<String> permissions){var user=new SysUser();user.setUserId(id);user.setUserName("test");SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(id,1L,user,permissions),null));}
|
||||
|
||||
@Test void employeeViewsMaskAllQuoteAliasesWithoutMutatingCostingObjects(){
|
||||
var result=PurchaseQuoteAccess.view(source);
|
||||
assertNull(result.getFinalUnitPrice());assertNull(result.getEstimatedUnitPrice());assertNull(result.getEstimatedAmount());assertNull(result.getLockedAmount());
|
||||
assertEquals(new BigDecimal("100"),result.getActualUnitPrice());assertEquals(new BigDecimal("200.00"),result.getActualAmount());assertTrue(result.getQuoteAvailable());
|
||||
assertEquals(new BigDecimal("891.25"),source.getFinalUnitPrice());
|
||||
source.setFinalUnitPrice(BigDecimal.ZERO);assertTrue(PurchaseQuoteAccess.view(source).getQuoteAvailable());
|
||||
source.setFinalUnitPrice(null);assertFalse(PurchaseQuoteAccess.view(source).getQuoteAvailable());
|
||||
}
|
||||
@Test void onlyManagementPermissionOrSuperAdministratorRevealsQuotes(){
|
||||
assertFalse(PurchaseQuoteAccess.allowed());
|
||||
login(10L,Set.of("warehouse:purchase:manage"));assertSame(source,PurchaseQuoteAccess.view(source));
|
||||
login(1L,Set.of());assertTrue(PurchaseQuoteAccess.allowed());
|
||||
login(10L,Set.of("*:*:*"));assertTrue(PurchaseQuoteAccess.allowed());
|
||||
}
|
||||
@Test void employeeEditPreservesHiddenQuoteAndRejectsPriceTampering(){
|
||||
var edit=new PurchaseRequest();edit.setId(1L);edit.setActualUnitPrice(new BigDecimal("7"));
|
||||
PurchaseQuoteAccess.preserveQuotation(edit,source);assertEquals(source.getFinalUnitPrice(),edit.getFinalUnitPrice());
|
||||
assertEquals(new BigDecimal("7"),edit.getActualUnitPrice());
|
||||
edit.setFinalUnitPrice(BigDecimal.ZERO);assertThrows(ServiceException.class,()->PurchaseQuoteAccess.preserveQuotation(edit,source));
|
||||
var create=new PurchaseRequest();create.setEstimatedUnitPrice(BigDecimal.ONE);assertThrows(ServiceException.class,()->PurchaseQuoteAccess.preserveQuotation(create,null));
|
||||
}
|
||||
@Test void batchArrivalHistoryAndAssistantSnapshotsCannotRevealQuoteCosts(){
|
||||
var batch=new PurchaseBatch();batch.setTotalAmount(new BigDecimal("1782.5"));batch.setLockedTotal(new BigDecimal("1782.5"));batch.setActualTotalAmount(new BigDecimal("200"));
|
||||
var sheet=new PurchaseSheet();sheet.setBatch(batch);sheet.setRows(List.of(source));sheet.setVersion("original-concurrency-token");
|
||||
var result=PurchaseQuoteAccess.view(sheet);assertEquals(sheet.getVersion(),result.getVersion());assertNull(result.getBatch().getTotalAmount());assertNull(result.getBatch().getLockedTotal());assertEquals(batch.getActualTotalAmount(),result.getBatch().getActualTotalAmount());
|
||||
var arrival=new PurchaseArrival();arrival.setActualUnitPrice(source.getFinalUnitPrice());arrival.setActualAmount(source.getEstimatedAmount());assertNull(PurchaseQuoteAccess.view(arrival).getActualUnitPrice());assertNull(PurchaseQuoteAccess.view(arrival).getActualAmount());
|
||||
var log=new PurchaseOperationLog();log.setOperationDetail("单价891.25");assertFalse(PurchaseQuoteAccess.view(log).getOperationDetail().contains("891.25"));
|
||||
var snapshot=Map.<String,Object>of("finalUnitPrice",891.25,"actualUnitPrice",100,"_snapshot",Map.of("currentRecord",Map.of("estimatedAmount",1782.5,"id",1)));
|
||||
var masked=PurchaseQuoteAccess.viewMap(snapshot);assertFalse(masked.containsKey("finalUnitPrice"));assertEquals(100,masked.get("actualUnitPrice"));assertFalse(masked.toString().contains("1782.5"));
|
||||
}
|
||||
@Test void httpDetailSheetListTotalsAndBatchResponsesApplyTheSamePolicy() throws Exception {
|
||||
var controller=new PurchaseRequestController();var purchases=mock(IPurchaseRequestService.class);var sheets=mock(PurchaseSheetService.class);var batches=mock(IPurchaseBatchService.class);
|
||||
ReflectionTestUtils.setField(controller,"purchaseRequestService",purchases);ReflectionTestUtils.setField(controller,"sheetService",sheets);ReflectionTestUtils.setField(controller,"purchaseBatchService",batches);
|
||||
when(purchases.selectPurchaseRequestById(1L)).thenReturn(source);when(purchases.selectPurchaseRequestList(any())).thenReturn(List.of(source));
|
||||
var batch=new PurchaseBatch();batch.setId(2L);batch.setTotalAmount(source.getEstimatedAmount());batch.setActualTotalAmount(source.getActualAmount());
|
||||
when(batches.selectPurchaseBatchList(any())).thenReturn(List.of(batch));
|
||||
var sheet=new PurchaseSheet();sheet.setBatch(batch);sheet.setRows(List.of(source));sheet.setVersion("v1");when(sheets.load(2L)).thenReturn(sheet);
|
||||
MockMvc mvc=MockMvcBuilders.standaloneSetup(controller).build();
|
||||
mvc.perform(get("/warehouse/purchase/1")).andExpect(jsonPath("$.data.finalUnitPrice").doesNotExist()).andExpect(jsonPath("$.data.actualAmount").value(200));
|
||||
mvc.perform(get("/warehouse/purchase/list")).andExpect(jsonPath("$.rows[0].estimatedAmount").doesNotExist()).andExpect(jsonPath("$.rows[0].actualAmount").value(200)).andExpect(jsonPath("$.total").value(1));
|
||||
mvc.perform(get("/warehouse/purchase/sheet/2")).andExpect(jsonPath("$.data.batch.totalAmount").doesNotExist()).andExpect(jsonPath("$.data.rows[0].lockedAmount").doesNotExist());
|
||||
mvc.perform(get("/warehouse/purchase/filtered-totals")).andExpect(jsonPath("$.data.amount").doesNotExist()).andExpect(jsonPath("$.data.lockedAmount").doesNotExist()).andExpect(jsonPath("$.data.actualAmount").value(200));
|
||||
mvc.perform(get("/warehouse/purchase/batch/list")).andExpect(jsonPath("$.rows[0].totalAmount").doesNotExist()).andExpect(jsonPath("$.rows[0].actualTotalAmount").value(200));
|
||||
assertThrows(ServiceException.class,()->controller.confirmSheet(2L,new PurchaseSheetConfirmRequest()));
|
||||
verify(sheets,never()).confirm(any(),anyString());
|
||||
}
|
||||
@Test void employeeExportContainsActualsButNoQuotationCellsOrHiddenQuoteColumns() throws Exception {
|
||||
for(boolean manager:new boolean[]{false,true}){
|
||||
var response=new MockHttpServletResponse();PurchaseTemplateExcelUtil.writeExport(response,List.of(source),List.of(),manager);
|
||||
try(var workbook=new org.apache.poi.xssf.usermodel.XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){
|
||||
var sheet=workbook.getSheetAt(0);var headers=new HashMap<String,Integer>();for(var cell:sheet.getRow(0))headers.put(cell.getStringCellValue(),cell.getColumnIndex());
|
||||
assertEquals(manager,headers.containsKey("最终含税单价"));assertEquals(manager,headers.containsKey("采购总金额"));assertEquals(manager,headers.containsKey("已计项目费用"));
|
||||
assertEquals(200d,sheet.getRow(1).getCell(headers.get("实际金额(内部参考)")).getNumericCellValue());
|
||||
if(!manager)for(var tab:workbook)for(var row:tab)for(var cell:row)assertFalse(cell.toString().contains("891.25")||cell.toString().contains("1782.5"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -108,7 +108,11 @@ class SupplierInquiryRoundTripTest {
|
||||
var purchase=purchase();purchase.getRows().forEach(row->row.setActualUnitPrice(new BigDecimal("123.456789")));
|
||||
var controller=new PurchaseRequestController();var sheets=org.mockito.Mockito.mock(com.ruoyi.warehouse.service.impl.PurchaseSheetService.class);var settings=org.mockito.Mockito.mock(com.ruoyi.warehouse.service.impl.AmountDisplaySettings.class);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(controller,"sheetService",sheets);org.springframework.test.util.ReflectionTestUtils.setField(controller,"amountDisplaySettings",settings);org.mockito.Mockito.when(sheets.load(1L)).thenReturn(purchase);org.mockito.Mockito.when(settings.enabled()).thenReturn(true);
|
||||
var response=new org.springframework.mock.web.MockHttpServletResponse();controller.inquiryExport(1L,"snapshot-1",response);
|
||||
var response=new org.springframework.mock.web.MockHttpServletResponse();
|
||||
try(var security=org.mockito.Mockito.mockStatic(com.ruoyi.common.utils.SecurityUtils.class)){
|
||||
security.when(()->com.ruoyi.common.utils.SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
|
||||
controller.inquiryExport(1L,"snapshot-1",response);
|
||||
}
|
||||
try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){var tab=book.getSheetAt(0);assertEquals("采购链接",tab.getRow(5).getCell(8).getStringCellValue());assertTrue(tab.isColumnHidden(9));for(var cell:tab.getRow(5))assertFalse(cell.getStringCellValue().contains("实际"));}
|
||||
}
|
||||
}
|
||||
|
||||
@ -279,4 +279,32 @@ class AssistantPurchaseSheetContractTest {
|
||||
for(String key:List.of("materialName","materialParams","materialBrand","unit","category","finalUnitPrice","batchName","supplierId","businessDate"))assertTrue(fields.stream().anyMatch(field->key.equals(field.get("key"))),key);
|
||||
assertEquals(true,fields.stream().filter(field->"batchName".equals(field.get("key"))).findFirst().orElseThrow().get("batch"));
|
||||
}
|
||||
|
||||
private void employeeIdentity(){
|
||||
var user=new SysUser();user.setUserId(7L);user.setUserName("employee");
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(7L,1L,user,Set.of("warehouse:purchase:list","warehouse:purchase:add","warehouse:purchase:edit")),null));
|
||||
}
|
||||
@Test void employeeAiQueriesAndCatalogNeverExposeQuotedAmounts() {
|
||||
employeeIdentity();
|
||||
var record=persisted(81);record.setFinalUnitPrice(new BigDecimal("9876.54"));record.setActualUnitPrice(new BigDecimal("11"));
|
||||
var table=new com.ruoyi.common.core.page.TableDataInfo();table.setRows(List.of(record));table.setTotal(1);
|
||||
when(controller.list(any())).thenReturn(table);
|
||||
var result=registry.executeReadOnly("purchase.query",Map.of());
|
||||
assertFalse(json.valueToTree(result).toString().contains("9876.54"));
|
||||
var rows=(List<Map<String,Object>>)result.get("rows");assertFalse(rows.get(0).containsKey("finalUnitPrice"));
|
||||
assertEquals("11",rows.get(0).get("actualUnitPrice").toString());assertNotNull(rows.get(0).get("actualAmount"));
|
||||
var action=registry.catalog().stream().filter(item->"purchase.create".equals(item.get("key"))).findFirst().orElseThrow();
|
||||
assertFalse(((List<Map<String,Object>>)action.get("fields")).stream().anyMatch(field->field.get("key").equals("finalUnitPrice")));
|
||||
}
|
||||
@Test void employeeAiEditPreviewsHideCurrentQuoteSnapshotsAndRejectExplicitQuoteEdits() {
|
||||
employeeIdentity();items.add(item(4L,"M4"));
|
||||
var current=raw("unused");current.remove("_rowId");current.put("productId",4L);current.put("finalUnitPrice",new BigDecimal("9876.54"));purchases.put(81L,current);
|
||||
var original=sheet(9,List.of(persisted(81)));original.setUnbatched(true);original.getBatch().setId(null);
|
||||
doReturn(original).when(sheets).loadUnbatched(any(Long[].class));
|
||||
var rows=ready("purchase.update",List.of(Map.of("_rowId","r1","id",81L,"quantity",3)));
|
||||
assertFalse(json.valueToTree(rows).toString().contains("9876.54"));assertFalse(rows.get(0).containsKey("finalUnitPrice"));
|
||||
var denied=registry.prepare("purchase.update",List.of(Map.of("_rowId","r2","id",81L,"finalUnitPrice",1)));
|
||||
assertEquals(false,denied.get("ready"));assertTrue(denied.get("errors").toString().contains("采购管理员"));
|
||||
verifyNoInteractions(controller);
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,7 +109,10 @@ class AssistantReferencePriceServiceTest {
|
||||
@Test void purchaseEditAloneCannotClearOrReadCostPreviewButStillCanMaintainReferenceAmounts() {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(false);security.when(()->SecurityUtils.hasPermi("warehouse:purchase:edit")).thenReturn(true);
|
||||
assertEquals(403,assertThrows(ServiceException.class,()->service.preview(input("CLEAR_QUOTE"))).getCode());verifyNoInteractions(corrections,sheets);
|
||||
assertEquals(3,preview(input("COPY_QUOTE")).size());
|
||||
assertEquals(403,assertThrows(ServiceException.class,()->service.preview(input("COPY_QUOTE"))).getCode());
|
||||
var values=input("SET");values.put("actualUnitPrice",8);var rows=preview(values);assertEquals(3,rows.size());
|
||||
assertEquals(new BigDecimal("8"),rows.get(0).get("newActualPrice"));
|
||||
for(var row:rows)for(String field:List.of("quotePrice","newQuotePrice","oldQuoteAmount","newQuoteAmount"))assertFalse(row.containsKey(field));
|
||||
}
|
||||
@Test void combinedStaleScopeIsRejectedAndNativeFailurePropagatesInsideTransactionalBoundary() throws Exception {
|
||||
makeEditable();var values=input("COPY_QUOTE_CLEAR_QUOTE");values.put("referenceVersion","stale");
|
||||
|
||||
@ -8,16 +8,16 @@ import org.springframework.validation.BindException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingPathVariableException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import com.ruoyi.common.constant.HttpStatus;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.core.text.Convert;
|
||||
import com.ruoyi.common.exception.DemoModeException;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.common.utils.html.EscapeUtil;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
@ -49,7 +49,7 @@ public class GlobalExceptionHandler
|
||||
{
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
|
||||
return AjaxResult.error(e.getMessage());
|
||||
return AjaxResult.error(HttpStatus.BAD_METHOD, "当前操作不支持这种请求方式,请刷新页面后重试");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -81,13 +81,22 @@ public class GlobalExceptionHandler
|
||||
public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request)
|
||||
{
|
||||
String requestURI = request.getRequestURI();
|
||||
String value = Convert.toStr(e.getValue());
|
||||
if (StringUtils.isNotEmpty(value))
|
||||
{
|
||||
value = EscapeUtil.clean(value);
|
||||
}
|
||||
log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
|
||||
return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), value));
|
||||
return AjaxResult.error(HttpStatus.BAD_REQUEST, "参数格式不正确,请检查后重试");
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public AjaxResult handleMissingRequestParameter(MissingServletRequestParameterException e, HttpServletRequest request)
|
||||
{
|
||||
log.warn("请求地址'{}',缺少必填参数'{}'", request.getRequestURI(), e.getParameterName());
|
||||
return AjaxResult.error(HttpStatus.BAD_REQUEST, "请求信息不完整,请补充必填信息后重试");
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public AjaxResult handleUnreadableBody(HttpMessageNotReadableException e, HttpServletRequest request)
|
||||
{
|
||||
log.warn("请求地址'{}',提交内容无法解析", request.getRequestURI(), e);
|
||||
return AjaxResult.error(HttpStatus.BAD_REQUEST, "提交内容格式不正确,请检查后重试");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -105,7 +114,7 @@ public class GlobalExceptionHandler
|
||||
{
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',发生未知异常.", requestURI, e);
|
||||
return AjaxResult.error(e.getMessage());
|
||||
return AjaxResult.error("系统暂时无法完成操作,请稍后重试;如仍有问题请联系管理员。");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -116,7 +125,7 @@ public class GlobalExceptionHandler
|
||||
{
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',发生系统异常.", requestURI, e);
|
||||
return AjaxResult.error(e.getMessage());
|
||||
return AjaxResult.error("系统暂时无法完成操作,请稍后重试;如仍有问题请联系管理员。");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -126,7 +135,7 @@ public class GlobalExceptionHandler
|
||||
public AjaxResult handleBindException(BindException e)
|
||||
{
|
||||
log.error(e.getMessage(), e);
|
||||
String message = e.getAllErrors().get(0).getDefaultMessage();
|
||||
String message = e.getAllErrors().stream().map(error -> error.getDefaultMessage()).filter(StringUtils::isNotBlank).findFirst().orElse("请检查填写的信息后重试");
|
||||
return AjaxResult.error(message);
|
||||
}
|
||||
|
||||
@ -137,7 +146,7 @@ public class GlobalExceptionHandler
|
||||
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
|
||||
{
|
||||
log.error(e.getMessage(), e);
|
||||
String message = e.getBindingResult().getFieldError().getDefaultMessage();
|
||||
String message = e.getBindingResult().getAllErrors().stream().map(error -> error.getDefaultMessage()).filter(StringUtils::isNotBlank).findFirst().orElse("请检查填写的信息后重试");
|
||||
return AjaxResult.error(message);
|
||||
}
|
||||
|
||||
|
||||
@ -146,7 +146,7 @@ public class FeedbackImageStorage
|
||||
return realRoot.resolve(id + ".bin");
|
||||
}
|
||||
|
||||
static String validateContent(byte[] bytes, String extension)
|
||||
public static String validateContent(byte[] bytes, String extension)
|
||||
{
|
||||
if ("png".equals(extension))
|
||||
{
|
||||
|
||||
@ -10,6 +10,14 @@ import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class PurchaseArrival extends BaseEntity
|
||||
{
|
||||
private java.util.List<String> photoIds;
|
||||
private java.util.List<PurchaseArrivalPhoto> photos = java.util.List.of();
|
||||
@com.fasterxml.jackson.annotation.JsonProperty(access=com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY)
|
||||
public java.util.List<String> getPhotoIds(){return photoIds;}
|
||||
public void setPhotoIds(java.util.List<String> value){photoIds=value;}
|
||||
@com.fasterxml.jackson.annotation.JsonProperty(access=com.fasterxml.jackson.annotation.JsonProperty.Access.READ_ONLY)
|
||||
public java.util.List<PurchaseArrivalPhoto> getPhotos(){return photos;}
|
||||
public void setPhotos(java.util.List<PurchaseArrivalPhoto> value){photos=value;}
|
||||
private java.math.BigDecimal defectiveQuantity;
|
||||
public java.math.BigDecimal getDefectiveQuantity(){return defectiveQuantity;}
|
||||
public void setDefectiveQuantity(java.math.BigDecimal v){defectiveQuantity=v;}
|
||||
|
||||
@ -0,0 +1,3 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
public record PurchaseArrivalPhoto(String id,String name,String contentType,int size,String uploadedBy,String uploadedAt) { }
|
||||
@ -102,6 +102,10 @@ public class PurchaseRequest extends BaseEntity
|
||||
private BigDecimal estimatedAmount;
|
||||
@Excel(name = "最终含税单价")
|
||||
private BigDecimal finalUnitPrice;
|
||||
private Boolean quoteAvailable;
|
||||
@com.fasterxml.jackson.annotation.JsonProperty(access=com.fasterxml.jackson.annotation.JsonProperty.Access.READ_ONLY)
|
||||
public Boolean getQuoteAvailable() { return quoteAvailable; }
|
||||
public void setQuoteAvailable(Boolean value) { quoteAvailable=value; }
|
||||
/** Internal reference only. Never use these values in price locking or costing. */
|
||||
@Excel(name = "实际单价(内部参考)", type = Excel.Type.EXPORT)
|
||||
private BigDecimal actualUnitPrice;
|
||||
|
||||
@ -0,0 +1,133 @@
|
||||
package com.ruoyi.warehouse.service.impl;
|
||||
|
||||
import com.ruoyi.common.config.RuoYiConfig;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.storage.BusinessFileStorage;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.system.service.impl.FeedbackImageStorage;
|
||||
import com.ruoyi.warehouse.domain.PurchaseArrival;
|
||||
import com.ruoyi.warehouse.domain.PurchaseArrivalPhoto;
|
||||
import com.ruoyi.warehouse.util.WarehouseFileUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
/** Private, owner-bound draft photos become immutable evidence when an arrival is saved. */
|
||||
@Service
|
||||
public class PurchaseArrivalPhotoService {
|
||||
public static final int MAX_BYTES=5*1024*1024,MAX_PHOTOS=9;
|
||||
private final JdbcTemplate db;
|
||||
private final BusinessFileStorage storage;
|
||||
public PurchaseArrivalPhotoService(JdbcTemplate db,BusinessFileStorage storage){this.db=db;this.storage=storage;}
|
||||
public record Content(byte[] bytes,String type,String name) { }
|
||||
|
||||
@Transactional(rollbackFor=Exception.class)
|
||||
public PurchaseArrivalPhoto upload(Long requestId,String id,MultipartFile file){
|
||||
permission(true);validId(id);requireRequest(requestId,true);
|
||||
String extension=WarehouseFileUtils.validateUpload(file,MAX_BYTES,Set.of("jpg","jpeg","png","webp"));
|
||||
byte[] bytes;
|
||||
try(var input=file.getInputStream()){bytes=input.readNBytes(MAX_BYTES+1);}catch(IOException e){throw new ServiceException("照片读取失败,请重新选择");}
|
||||
if(bytes.length==0||bytes.length>MAX_BYTES)throw new ServiceException("每张照片不能超过5MB");
|
||||
String type=FeedbackImageStorage.validateContent(bytes,extension),name=PurchaseDocumentService.safeName(file.getOriginalFilename()),sha=digest(bytes);
|
||||
var existing=db.queryForList("select * from purchase_arrival_photo where id=?",id);
|
||||
if(!existing.isEmpty()){
|
||||
var old=existing.get(0);
|
||||
if(number(old,"owner_id")!=SecurityUtils.getUserId()||number(old,"purchase_request_id")!=requestId||!sha.equals(old.get("sha256")))throw new ServiceException("照片上传标识已被使用,请重新选择照片");
|
||||
return photo(old);
|
||||
}
|
||||
if(db.queryForObject("select count(*) from purchase_arrival_photo where purchase_request_id=? and owner_id=? and arrival_id is null",Integer.class,requestId,SecurityUtils.getUserId())>=90)throw new ServiceException("未提交照片较多,请先完成或取消之前的到货登记");
|
||||
Path path=path(id);
|
||||
try{storage.save(key(id),bytes,type,path);}catch(IOException e){throw new ServiceException("照片保存失败,请稍后重试");}
|
||||
if(TransactionSynchronizationManager.isSynchronizationActive())TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){@Override public void afterCompletion(int status){if(status!=STATUS_COMMITTED)storage.discardFailedUpload(key(id),path);}});
|
||||
try{db.update("insert into purchase_arrival_photo(id,purchase_request_id,owner_id,original_name,content_type,byte_size,sha256,create_by) values(?,?,?,?,?,?,?,?)",id,requestId,SecurityUtils.getUserId(),name,type,bytes.length,sha,SecurityUtils.getUsername());}
|
||||
catch(RuntimeException e){storage.discardFailedUpload(key(id),path);throw e;}
|
||||
return new PurchaseArrivalPhoto(id,name,type,bytes.length,SecurityUtils.getUsername(),null);
|
||||
}
|
||||
|
||||
@Transactional(readOnly=true)
|
||||
public Content content(String id){
|
||||
permission(false);validId(id);
|
||||
var rows=db.queryForList("select p.* from purchase_arrival_photo p join purchase_request r on r.id=p.purchase_request_id where p.id=?",id);
|
||||
if(rows.isEmpty())throw new ServiceException("照片不存在或已失效",404);
|
||||
var row=rows.get(0);
|
||||
if(row.get("arrival_id")==null&&number(row,"owner_id")!=SecurityUtils.getUserId())throw new ServiceException("照片尚未提交,不能查看其他人的草稿",403);
|
||||
try{var bytes=storage.read(key(id),path(id),MAX_BYTES);if(bytes.length!=number(row,"byte_size")||!digest(bytes).equals(row.get("sha256")))throw new IOException();return new Content(bytes,row.get("content_type").toString(),row.get("original_name").toString());}
|
||||
catch(IOException e){throw new ServiceException("照片读取失败,请稍后重试");}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeDraft(String id){
|
||||
permission(true);validId(id);
|
||||
var rows=db.queryForList("select * from purchase_arrival_photo where id=? for update",id);
|
||||
if(rows.isEmpty())return;
|
||||
var row=rows.get(0);
|
||||
if(number(row,"owner_id")!=SecurityUtils.getUserId()||row.get("arrival_id")!=null)throw new ServiceException("仅可移除自己尚未提交的到货照片",403);
|
||||
if(db.update("delete from purchase_arrival_photo where id=? and owner_id=? and arrival_id is null",id,SecurityUtils.getUserId())==1)discardAfterCommit(id);
|
||||
}
|
||||
|
||||
public void bind(PurchaseArrival arrival){
|
||||
var ids=ids(arrival.getPhotoIds());
|
||||
for(int i=0;i<ids.size();i++)if(db.update("update purchase_arrival_photo set arrival_id=?,sort_no=? where id=? and purchase_request_id=? and owner_id=? and arrival_id is null",arrival.getId(),i,ids.get(i),arrival.getPurchaseRequestId(),SecurityUtils.getUserId())!=1)throw new ServiceException("照片不存在、已被使用或不属于本次到货,请重新上传");
|
||||
}
|
||||
public void verifyRetry(PurchaseArrival arrival,Long savedId){
|
||||
var previous=db.queryForList("select id from purchase_arrival_photo where arrival_id=? order by sort_no,id",String.class,savedId);
|
||||
if(!previous.equals(ids(arrival.getPhotoIds())))throw new ServiceException("重复到货的照片与已保存记录不一致,请刷新到货记录核对");
|
||||
}
|
||||
public void attach(List<PurchaseArrival> arrivals){
|
||||
if(arrivals.isEmpty())return;
|
||||
var byId=new HashMap<Long,PurchaseArrival>();arrivals.forEach(a->{a.setPhotos(new ArrayList<>());byId.put(a.getId(),a);});
|
||||
var placeholders=String.join(",",Collections.nCopies(byId.size(),"?"));
|
||||
for(var row:db.queryForList("select * from purchase_arrival_photo where arrival_id in ("+placeholders+") order by sort_no,id",byId.keySet().toArray()))byId.get(number(row,"arrival_id")).getPhotos().add(photo(row));
|
||||
}
|
||||
public static List<String> ids(List<String> input){
|
||||
if(input==null)return List.of();
|
||||
if(input.size()>MAX_PHOTOS||new HashSet<>(input).size()!=input.size())throw new ServiceException("每次到货最多9张照片,不能重复选择");
|
||||
input.forEach(PurchaseArrivalPhotoService::validId);return List.copyOf(input);
|
||||
}
|
||||
/** Only abandoned drafts expire. Saved arrival evidence is never removed here. */
|
||||
@Scheduled(fixedDelay=3600000,initialDelay=3600000)
|
||||
@Transactional
|
||||
public void expireDrafts(){
|
||||
var cutoff=java.sql.Timestamp.valueOf(LocalDateTime.now().minusDays(7));
|
||||
for(var row:db.queryForList("select id from purchase_arrival_photo where arrival_id is null and create_time<? limit 100",cutoff)){
|
||||
String id=row.get("id").toString();
|
||||
if(db.update("delete from purchase_arrival_photo where id=? and arrival_id is null and create_time<?",id,cutoff)==1)discardAfterCommit(id);
|
||||
}
|
||||
}
|
||||
private void discardAfterCommit(String id){
|
||||
Path path=path(id);
|
||||
if(TransactionSynchronizationManager.isSynchronizationActive())TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){@Override public void afterCommit(){storage.discardFailedUpload(key(id),path);}});
|
||||
else storage.discardFailedUpload(key(id),path);
|
||||
}
|
||||
private void requireRequest(Long id,boolean lock){
|
||||
if(id==null||id<=0)throw new ServiceException("请先选择采购明细");
|
||||
// MySQL tinyint(1) is otherwise exposed as Boolean and loses status values such as 2/5.
|
||||
var rows=db.queryForList("select id,price_locked,cast(purchase_status as signed) as purchase_status,historical from purchase_request where id=?"+(lock?" for update":""),id);
|
||||
if(rows.isEmpty())throw new ServiceException("采购明细不存在",404);
|
||||
var r=rows.get(0);
|
||||
if(!truth(r.get("price_locked"))||truth(r.get("historical"))||number(r,"purchase_status")==5)throw new ServiceException("请先确认采购,历史或已取消采购不能登记到货照片");
|
||||
}
|
||||
private static boolean truth(Object value){return Boolean.TRUE.equals(value)||value instanceof Number n&&n.intValue()!=0;}
|
||||
private static void validId(String id){if(id==null||!id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))throw new ServiceException("照片标识无效");}
|
||||
private static long number(Map<String,Object> row,String key){return ((Number)row.get(key)).longValue();}
|
||||
private static PurchaseArrivalPhoto photo(Map<String,Object> r){return new PurchaseArrivalPhoto(r.get("id").toString(),r.get("original_name").toString(),r.get("content_type").toString(),((Number)r.get("byte_size")).intValue(),r.get("create_by").toString(),Objects.toString(r.get("create_time"),null));}
|
||||
private static String digest(byte[] bytes){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
private static String key(String id){return "purchase/arrival-"+id+".bin";}
|
||||
private static Path path(String id){
|
||||
validId(id);
|
||||
var profile=Path.of(RuoYiConfig.getProfile()).toAbsolutePath().normalize();
|
||||
var root=profile.resolveSibling(".purchase-arrival-photos-private");
|
||||
try{Files.createDirectories(root);if(Files.isSymbolicLink(root)||root.toRealPath().startsWith(Files.exists(profile)?profile.toRealPath():profile))throw new IOException();return root.resolve(id+".bin");}
|
||||
catch(IOException e){throw new ServiceException("到货照片存储暂时不可用");}
|
||||
}
|
||||
private static void permission(boolean write){if(SecurityUtils.isAdmin()||SecurityUtils.hasPermi("warehouse:purchase:manage")||SecurityUtils.hasPermi("warehouse:purchase:edit")||!write&&SecurityUtils.hasPermi("warehouse:purchase:list"))return;throw new ServiceException("当前账号未开通到货照片"+(write?"维护":"查看")+"权限",403);}
|
||||
}
|
||||
@ -29,6 +29,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers;
|
||||
@Autowired private InventoryCostJournal journal;
|
||||
@Autowired private org.springframework.jdbc.core.JdbcTemplate database;
|
||||
@Autowired private PurchaseArrivalPhotoService arrivalPhotos;
|
||||
|
||||
@Autowired
|
||||
private PurchaseArrivalMapper purchaseArrivalMapper;
|
||||
@ -53,7 +54,9 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
{
|
||||
throw new ServiceException("采购申请不存在");
|
||||
}
|
||||
return purchaseArrivalMapper.selectPurchaseArrivalList(purchaseRequestId);
|
||||
var rows=purchaseArrivalMapper.selectPurchaseArrivalList(purchaseRequestId);
|
||||
if(arrivalPhotos!=null)arrivalPhotos.attach(rows);
|
||||
return rows;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -72,6 +75,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
{
|
||||
throw new ServiceException("采购申请不能为空");
|
||||
}
|
||||
PurchaseArrivalPhotoService.ids(arrival.getPhotoIds());
|
||||
PurchaseRequest request = purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId());
|
||||
if (request == null)
|
||||
{
|
||||
@ -92,7 +96,9 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
if(!java.util.Objects.equals(((Number)previous.get("purchase_request_id")).longValue(),arrival.getPurchaseRequestId())||arrival.getArrivalQuantity()==null||new BigDecimal(previous.get("arrival_quantity").toString()).compareTo(arrival.getArrivalQuantity())!=0
|
||||
||!java.util.Objects.equals(date,previousDate)||!java.util.Objects.equals(trimToNull(arrival.getRemark()),trimToNull((String)previous.get("remark"))))
|
||||
throw new ServiceException("重复到货内容不一致,请刷新后核对已登记的数量、日期和备注");
|
||||
arrival.setId(((Number)previous.get("id")).longValue());arrival.setArrivalNo(stableNo);return 1;
|
||||
arrival.setId(((Number)previous.get("id")).longValue());arrival.setArrivalNo(stableNo);
|
||||
if(arrivalPhotos!=null)arrivalPhotos.verifyRetry(arrival,arrival.getId());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (Integer.valueOf(5).equals(request.getPurchaseStatus()))
|
||||
@ -124,6 +130,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
arrival.setCreateBy(SecurityUtils.getUsername());
|
||||
arrival.setRemark(trimToNull(arrival.getRemark()));
|
||||
int rows = purchaseArrivalMapper.insertPurchaseArrival(arrival);
|
||||
if(arrival.getPhotoIds()!=null&&!arrival.getPhotoIds().isEmpty())arrivalPhotos.bind(arrival);
|
||||
purchaseOperationLogService.record(request.getId(), request.getRequestNo(), "ARRIVAL_REGISTER",
|
||||
"登记到货", "到货单:" + arrival.getArrivalNo()
|
||||
+ ";数量:" + decimalText(arrival.getArrivalQuantity()) + unitText(request.getUnit())
|
||||
|
||||
@ -45,6 +45,7 @@ public class PurchaseDocumentService {
|
||||
requirePermission(false); requireTarget(type, targetId, false);
|
||||
List<Group> result = new ArrayList<>();
|
||||
for (var kind : kinds(type).entrySet()) {
|
||||
if("QUOTE".equals(kind.getKey())&&!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())continue;
|
||||
var groups = db.queryForList("select id,document_no,version from purchase_document_group where target_type=? and target_id=? and document_kind=?", type, targetId, kind.getKey());
|
||||
if (groups.isEmpty()) result.add(new Group(kind.getKey(), kind.getValue(), "", 0, List.of()));
|
||||
else {
|
||||
@ -114,6 +115,7 @@ public class PurchaseDocumentService {
|
||||
@Transactional
|
||||
public void remove(String type, Long targetId, String id) {
|
||||
requirePermission(true); requireId(id); requireTarget(type, targetId, true);
|
||||
requireFileAccess(type,targetId,id);
|
||||
if (db.update("update purchase_document_attachment a join purchase_document_group g on g.id=a.group_id set a.deleted=1,a.deleted_by=?,a.deleted_time=current_timestamp where a.id=? and a.deleted=0 and g.target_type=? and g.target_id=?", SecurityUtils.getUsername(), id, type, targetId) != 1)
|
||||
throw new ServiceException("附件不存在或已移除,请刷新资料");
|
||||
// Keep private bytes and removal metadata for audit. Never delete another business record.
|
||||
@ -122,6 +124,7 @@ public class PurchaseDocumentService {
|
||||
@Transactional(readOnly = true)
|
||||
public Content content(String type, Long targetId, String id) {
|
||||
requirePermission(false); requireId(id); requireTarget(type, targetId, false);
|
||||
requireFileAccess(type,targetId,id);
|
||||
var files = db.queryForList("select a.original_name,a.content_type,a.byte_size,a.sha256 from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=? and a.deleted=0 and g.target_type=? and g.target_id=?", id, type, targetId);
|
||||
if (files.isEmpty()) throw new ServiceException("附件不存在或已移除");
|
||||
var meta = files.get(0);
|
||||
@ -160,6 +163,12 @@ public class PurchaseDocumentService {
|
||||
}
|
||||
static void requireKind(String type, String kind) {
|
||||
if (!kinds(type).containsKey(kind)) throw new ServiceException("附件资料类型不正确");
|
||||
if("QUOTE".equals(kind))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
|
||||
}
|
||||
private void requireFileAccess(String type,Long targetId,String id) {
|
||||
if(com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())return;
|
||||
var kinds=db.queryForList("select g.document_kind from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=? and g.target_type=? and g.target_id=?",id,type,targetId);
|
||||
if(kinds.stream().anyMatch(row->"QUOTE".equals(row.get("document_kind"))))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
|
||||
}
|
||||
static void requireId(String id) {
|
||||
if (id == null || !id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) throw new ServiceException("附件编号无效");
|
||||
|
||||
@ -90,6 +90,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
|
||||
@Transactional
|
||||
public int insertPurchaseRequest(PurchaseRequest purchaseRequest)
|
||||
{
|
||||
com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(purchaseRequest, null);
|
||||
normalize(purchaseRequest);
|
||||
resolveFunding(purchaseRequest);
|
||||
resolveProduct(purchaseRequest);
|
||||
@ -124,6 +125,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
|
||||
throw new ServiceException("采购申请ID不能为空");
|
||||
}
|
||||
PurchaseRequest existing = requireRequestForUpdate(purchaseRequest.getId());
|
||||
com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(purchaseRequest, existing);
|
||||
if(!purchaseRequest.isActualUnitPriceProvided())purchaseRequest.setActualUnitPrice(existing.getActualUnitPrice());
|
||||
if(existing.getProductionTaskId()!=null)purchaseRequest.setProductionTaskId(existing.getProductionTaskId());
|
||||
if (purchaseRequest.getPurchasePurpose()==null) { purchaseRequest.setPurchasePurpose(existing.getPurchasePurpose()); purchaseRequest.setLoanId(existing.getLoanId()); }
|
||||
@ -342,6 +344,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
|
||||
try
|
||||
{
|
||||
if (row == null) throw new ServiceException("采购明细不能为空");
|
||||
com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(row, null);
|
||||
normalize(row);
|
||||
resolveImportFunding(row, references);
|
||||
resolveFunding(row);
|
||||
|
||||
@ -212,6 +212,7 @@ public class PurchaseSheetService
|
||||
for (PurchaseRequest row : sheet.getRows()) {
|
||||
line++;
|
||||
PurchaseRequest existing = old.get(row.getId());
|
||||
com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(row, existing);
|
||||
if(existing!=null&&!row.isActualUnitPriceProvided())row.setActualUnitPrice(existing.getActualUnitPrice());
|
||||
com.ruoyi.warehouse.util.PurchaseReferenceAmounts.validate(row.getActualUnitPrice());
|
||||
if(existing!=null&&sameCoreEditable(existing,row)&&!decimal(existing.getActualUnitPrice()).equals(decimal(row.getActualUnitPrice()))){
|
||||
@ -311,6 +312,7 @@ public class PurchaseSheetService
|
||||
var items=new ArrayList<>(catalog.selectProductInfoAll());var saved=new ArrayList<PurchaseRequest>();int line=0;
|
||||
for(var row:sheet.getRows()){
|
||||
line++;
|
||||
com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(row, old.get(row.getId()));
|
||||
try{if(row.getId()==null||!sameEditable(old.get(row.getId()),row)){
|
||||
resolveItem(row,items,old.get(row.getId()));row.setPurchaseBatchId(null);row.setPurchaseBatchNo(null);row.setEstimatedUnitPrice(row.getFinalUnitPrice());
|
||||
if(row.getId()==null){row.setRequestNo(null);row.setHistorical(false);purchases.insertPurchaseRequest(row);}else purchases.updatePurchaseRequest(row);
|
||||
|
||||
@ -0,0 +1,87 @@
|
||||
package com.ruoyi.warehouse.util;
|
||||
|
||||
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 org.springframework.beans.BeanUtils;
|
||||
|
||||
/** Purchase quotations are confidential; internal actual amounts remain employee-visible.
|
||||
* Apply at read boundaries, never to mapper objects used for costing or concurrency checks.
|
||||
*/
|
||||
public final class PurchaseQuoteAccess {
|
||||
private PurchaseQuoteAccess() { }
|
||||
|
||||
public static boolean allowed() {
|
||||
try { return SecurityUtils.isAdmin() || SecurityUtils.hasPermi("warehouse:purchase:manage"); }
|
||||
catch(ServiceException unauthenticated) { return false; }
|
||||
}
|
||||
public static void require() {
|
||||
if (!allowed()) throw new ServiceException("报价金额仅采购管理员可查看和维护", 403);
|
||||
}
|
||||
public static PurchaseRequest view(PurchaseRequest source) {
|
||||
if (source == null || allowed()) return source;
|
||||
var copy = new PurchaseRequest(); BeanUtils.copyProperties(source, copy);
|
||||
copy.setQuoteAvailable(source.getFinalUnitPrice() != null);
|
||||
copy.setFinalUnitPrice(null); copy.setEstimatedUnitPrice(null);
|
||||
copy.setEstimatedAmount(null); copy.setLockedAmount(null);
|
||||
return copy;
|
||||
}
|
||||
public static List<PurchaseRequest> rows(List<PurchaseRequest> source) {
|
||||
return source.stream().map(PurchaseQuoteAccess::view).toList();
|
||||
}
|
||||
public static PurchaseBatch view(PurchaseBatch source) {
|
||||
if (source == null || allowed()) return source;
|
||||
var copy = new PurchaseBatch(); BeanUtils.copyProperties(source, copy);
|
||||
copy.setTotalAmount(null); copy.setLockedTotal(null);
|
||||
return copy;
|
||||
}
|
||||
public static PurchaseSheet view(PurchaseSheet source) {
|
||||
if (source == null || allowed()) return source;
|
||||
var copy = new PurchaseSheet(); BeanUtils.copyProperties(source, copy);
|
||||
copy.setBatch(view(source.getBatch())); copy.setRows(rows(source.getRows()));
|
||||
return copy;
|
||||
}
|
||||
public static PurchaseArrival view(PurchaseArrival source) {
|
||||
if (source == null || allowed()) return source;
|
||||
var copy = new PurchaseArrival(); BeanUtils.copyProperties(source, copy);
|
||||
// Arrival actual_* are locked quotation costs, not purchase_request.actual_*.
|
||||
copy.setActualUnitPrice(null); copy.setActualAmount(null); copy.setEstimatedUnitPrice(null);
|
||||
return copy;
|
||||
}
|
||||
public static PurchaseOperationLog view(PurchaseOperationLog source) {
|
||||
if (source == null || allowed()) return source;
|
||||
var copy = new PurchaseOperationLog(); BeanUtils.copyProperties(source, copy);
|
||||
copy.setOperationDetail("报价相关操作明细仅采购管理员可查看");
|
||||
return copy;
|
||||
}
|
||||
/** Hidden quote fields omitted by employees must never erase an existing quotation. */
|
||||
public static void preserveQuotation(PurchaseRequest input, PurchaseRequest existing) {
|
||||
if (allowed()) return;
|
||||
BigDecimal old = existing == null ? null : existing.getFinalUnitPrice();
|
||||
if (differentSupplied(input.getFinalUnitPrice(), old) || differentSupplied(input.getEstimatedUnitPrice(), old)) require();
|
||||
input.setFinalUnitPrice(old); input.setEstimatedUnitPrice(old);
|
||||
}
|
||||
private static boolean differentSupplied(BigDecimal supplied, BigDecimal old) {
|
||||
return supplied != null && (old == null || supplied.compareTo(old) != 0);
|
||||
}
|
||||
|
||||
/** Assistant purchase snapshots use maps, including nested existing-record metadata. */
|
||||
public static Map<String,Object> viewMap(Map<String,Object> source) {
|
||||
if(allowed())return source;
|
||||
var result=new LinkedHashMap<String,Object>();
|
||||
var confidential=Set.of("finalUnitPrice","estimatedUnitPrice","estimatedAmount","lockedAmount","lockedTotal","totalAmount","amount",
|
||||
"quotePrice","newQuotePrice","oldQuoteAmount","newQuoteAmount");
|
||||
source.forEach((key,value)->{
|
||||
if(confidential.contains(key))return;
|
||||
result.put(key,viewValue(value));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
private static Object viewValue(Object value) {
|
||||
if(value instanceof Map<?,?> map){var copy=new LinkedHashMap<String,Object>();map.forEach((key,item)->copy.put(key.toString(),item));return viewMap(copy);}
|
||||
if(value instanceof List<?> list)return list.stream().map(PurchaseQuoteAccess::viewValue).toList();
|
||||
return value;
|
||||
}
|
||||
}
|
||||
10
ruoyi-ui-vue3/src/api/warehouse/arrival-photos.js
Normal file
10
ruoyi-ui-vue3/src/api/warehouse/arrival-photos.js
Normal file
@ -0,0 +1,10 @@
|
||||
import request from '@/utils/request'
|
||||
export const ARRIVAL_PHOTO_LIMIT=9,ARRIVAL_PHOTO_BYTES=5*1024*1024
|
||||
export function arrivalPhotoError(file){
|
||||
if(!['image/jpeg','image/png','image/webp'].includes(file.type)||! /\.(jpe?g|png|webp)$/i.test(file.name||''))return '请选择 JPG、PNG 或 WebP 图片'
|
||||
if(!file.size||file.size>ARRIVAL_PHOTO_BYTES)return '每张照片不能超过5MB'
|
||||
return ''
|
||||
}
|
||||
export function uploadArrivalPhoto(requestId,uploadId,file,signal){const data=new FormData();data.append('file',file);data.append('uploadId',uploadId);return request({url:'/warehouse/purchase/arrival/photos/'+requestId,method:'post',headers:{'Content-Type':'multipart/form-data',repeatSubmit:false},data,signal,timeout:120000})}
|
||||
export const removeArrivalPhoto=id=>request({url:'/warehouse/purchase/arrival/photos/'+id,method:'delete'})
|
||||
export const readArrivalPhoto=(id,signal)=>request({url:'/warehouse/purchase/arrival/photos/'+id+'/content',responseType:'blob',signal})
|
||||
49
ruoyi-ui-vue3/src/components/ArrivalPhotos/index.vue
Normal file
49
ruoyi-ui-vue3/src/components/ArrivalPhotos/index.vue
Normal file
@ -0,0 +1,49 @@
|
||||
<template>
|
||||
<span v-if="compact" class="arrival-photos-trigger"><el-button v-if="!readonly||modelValue.length" link type="primary" :disabled="disabled&&!readonly" @click="open=true">{{ readonly?'查看照片':'到货照片' }}<span v-if="modelValue.length">({{ modelValue.length }})</span><span v-else>(选传)</span></el-button><span v-else>—</span></span>
|
||||
<component :is="compact?'el-dialog':'div'" v-if="!compact||open" v-model="open" :title="title||'到货照片'" width="min(720px,94vw)" append-to-body class="arrival-photos-dialog" :close-on-click-modal="!busy" :show-close="!busy" :close-on-press-escape="!busy">
|
||||
<section class="arrival-photos" :aria-busy="busy">
|
||||
<div v-if="!readonly" class="arrival-photos-toolbar"><input ref="input" type="file" accept="image/jpeg,image/png,image/webp" multiple hidden :disabled="disabled||busy" @change="choose"/><el-button :disabled="disabled||busy||modelValue.length>=9" :loading="busy" @click="input.click()"><el-icon><Upload/></el-icon>上传照片</el-button><span>选传 · {{ modelValue.length }}/9 张 · 每张不超过5MB</span></div>
|
||||
<div v-if="modelValue.length" class="arrival-photos-grid">
|
||||
<article v-for="photo in modelValue" :key="photo.clientKey||photo.id" class="arrival-photo" :class="{'is-failed':photo.error}">
|
||||
<el-image v-if="url(photo)" :src="url(photo)" fit="cover" :preview-src-list="previewUrls" :initial-index="Math.max(0,previewUrls.indexOf(url(photo)))" preview-teleported :alt="photo.name||'到货照片'"/>
|
||||
<button v-else type="button" class="arrival-photo-placeholder" :disabled="loading[photo.id]" @click="load(photo)">{{ loading[photo.id]?'正在加载…':loadErrors[photo.id]?'加载失败,点击重试':'加载照片' }}</button>
|
||||
<span class="arrival-photo-name" :title="photo.name">{{ photo.name }}</span>
|
||||
<div v-if="photo.uploading" class="arrival-photo-status" role="status">正在上传…</div>
|
||||
<div v-if="photo.error" class="arrival-photo-status is-error" role="alert">{{ photo.error }}<el-button v-if="photo.raw" link type="danger" :disabled="disabled||busy" @click="upload(photo)">重试</el-button></div>
|
||||
<div v-if="loadErrors[photo.id]" class="arrival-photo-status is-error" role="alert">{{ loadErrors[photo.id] }}</div>
|
||||
<el-button v-if="!readonly" class="arrival-photo-remove" size="small" :disabled="disabled||photo.uploading" @click="remove(photo)">移除</el-button>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else-if="readonly" class="arrival-photos-empty">本次到货未上传照片</p>
|
||||
</section>
|
||||
<template v-if="compact" #footer><el-button :disabled="busy" @click="open=false">完成</el-button></template>
|
||||
</component>
|
||||
</template>
|
||||
<script setup>
|
||||
import {computed,nextTick,onBeforeUnmount,ref,watch} from 'vue'
|
||||
import {Upload} from '@element-plus/icons-vue'
|
||||
import {ElMessage} from 'element-plus'
|
||||
import {arrivalPhotoError,uploadArrivalPhoto,removeArrivalPhoto,readArrivalPhoto} from '@/api/warehouse/arrival-photos'
|
||||
import {purchaseUploadId} from '@/utils/purchase-documents'
|
||||
const props=defineProps({modelValue:{type:Array,default:()=>[]},requestId:[Number,String],readonly:Boolean,disabled:Boolean,compact:Boolean,title:String})
|
||||
const emit=defineEmits(['update:modelValue','pending'])
|
||||
const input=ref(),open=ref(false),resources=ref({}),loading=ref({}),loadErrors=ref({}),active=new Set(),ownedUrls=new Set()
|
||||
let disposed=false
|
||||
const busy=computed(()=>props.modelValue.some(p=>p.uploading)),pending=computed(()=>!props.readonly&&props.modelValue.some(p=>!p.id||p.uploading||p.error&&p.raw))
|
||||
watch(pending,v=>emit('pending',v),{immediate:true})
|
||||
function update(photo,patch){if(!disposed)emit('update:modelValue',props.modelValue.map(p=>(p.clientKey||p.id)===(photo.clientKey||photo.id)?{...p,...patch}:p))}
|
||||
function url(photo){return photo.localUrl&&ownedUrls.has(photo.localUrl)?photo.localUrl:resources.value[photo.id||photo.clientKey]||''}
|
||||
const previewUrls=computed(()=>props.modelValue.map(url).filter(Boolean))
|
||||
function own(blob){const value=URL.createObjectURL(blob);ownedUrls.add(value);return value}
|
||||
async function choose(event){const files=[...event.target.files];event.target.value='';if(props.disabled||busy.value)return;const values=[...props.modelValue];for(const raw of files){if(values.length>=9){ElMessage.warning('每次到货最多9张照片');break}const error=arrivalPhotoError(raw);if(error){ElMessage.warning(error);continue}try{values.push({clientKey:purchaseUploadId(),name:raw.name,raw,localUrl:own(raw),uploading:false})}catch(e){ElMessage.error(e.message);break}}emit('update:modelValue',values);await nextTick();for(const p of values.filter(p=>p.raw&&!p.id&&!p.error))await upload(p)}
|
||||
async function upload(photo){if(props.disabled||disposed)return;const ctl=new AbortController();active.add(ctl);update(photo,{uploading:true,error:''});try{const result=await uploadArrivalPhoto(props.requestId,photo.clientKey,photo.raw,ctl.signal);update(photo,{...result.data,uploading:false,error:''})}catch(e){if(!ctl.signal.aborted)update(photo,{uploading:false,error:e.message||'上传失败,请重试或移除'})}finally{active.delete(ctl)}}
|
||||
async function remove(photo){if(props.disabled||photo.uploading)return;try{if(photo.id)await removeArrivalPhoto(photo.id);if(disposed)return;emit('update:modelValue',props.modelValue.filter(p=>(p.clientKey||p.id)!==(photo.clientKey||photo.id)));if(photo.localUrl){URL.revokeObjectURL(photo.localUrl);ownedUrls.delete(photo.localUrl)}}catch(e){ElMessage.error(e.message||'移除失败,请重试')}}
|
||||
async function load(photo){if(!photo.id||url(photo)||disposed||loading.value[photo.id])return;const ctl=new AbortController();active.add(ctl);loading.value={...loading.value,[photo.id]:true};loadErrors.value={...loadErrors.value,[photo.id]:''};try{const blob=await readArrivalPhoto(photo.id,ctl.signal);if(!/^image\/(jpeg|png|webp)$/.test(blob.type))throw Error('照片加载失败');if(!disposed&&!ctl.signal.aborted)resources.value={...resources.value,[photo.id]:own(blob)}}catch(e){if(!disposed&&!ctl.signal.aborted)loadErrors.value={...loadErrors.value,[photo.id]:e.message||'照片加载失败'}}finally{active.delete(ctl);if(!disposed)loading.value={...loading.value,[photo.id]:false}}}
|
||||
watch(()=>[props.modelValue.map(p=>p.id||p.clientKey).join(','),open.value],()=>{if(!props.compact||open.value){props.modelValue.filter(p=>p.raw&&!p.id&&!url(p)).forEach(p=>{resources.value={...resources.value,[p.clientKey]:own(p.raw)}});props.modelValue.filter(p=>p.id&&!url(p)).forEach(load)}},{immediate:true})
|
||||
watch(()=>props.modelValue,rows=>{const ids=new Set(rows.map(p=>p.id||p.clientKey));resources.value=Object.fromEntries(Object.entries(resources.value).filter(([id])=>ids.has(id)));const keep=new Set([...rows.map(p=>p.localUrl),...Object.values(resources.value)]);for(const value of ownedUrls)if(!keep.has(value)){URL.revokeObjectURL(value);ownedUrls.delete(value)}})
|
||||
onBeforeUnmount(()=>{disposed=true;active.forEach(c=>c.abort());ownedUrls.forEach(u=>URL.revokeObjectURL(u))})
|
||||
defineExpose({pending,busy})
|
||||
</script>
|
||||
<style scoped>
|
||||
.arrival-photos{width:100%;min-width:0}.arrival-photos-toolbar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin:4px 0 12px}.arrival-photos-toolbar>span,.arrival-photos-empty{font-size:12px;color:var(--el-text-color-secondary)}.arrival-photos-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:12px}.arrival-photo{position:relative;min-width:0;padding:8px;border:1px solid var(--el-border-color-lighter);border-radius:8px;background:var(--el-bg-color)}.arrival-photo :deep(.el-image){display:block;width:100%;height:100px;border-radius:5px}.arrival-photo-name{display:block;font-size:12px;line-height:1.6;margin-top:6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.arrival-photo-status{font-size:12px;line-height:1.6;color:var(--el-color-primary);overflow-wrap:anywhere}.arrival-photo-status .el-button{margin-left:6px}.is-error{color:var(--el-color-danger)}.is-failed{border-color:var(--el-color-danger-light-5)}.arrival-photo-remove{margin-top:6px;width:100%}.arrival-photo-placeholder{width:100%;height:100px;border:0;border-radius:5px;color:var(--el-text-color-secondary);background:var(--el-fill-color-light);cursor:pointer}.arrival-photos-trigger :deep(.el-button){white-space:normal;height:auto;line-height:1.5}
|
||||
</style>
|
||||
@ -3,7 +3,7 @@
|
||||
<el-option v-for="option in options" :key="optionKey(option)" :value="optionKey(option)" :label="(selectedLabel||label)(option)"><span :title="label(option)">{{ label(option) }}</span></el-option>
|
||||
<template #empty><div class="picker-footer">{{ loading ? '正在加载' : failed ? '加载失败' : '没有匹配结果' }}</div></template>
|
||||
<template #footer>
|
||||
<div v-if="failed || hasMore || total || !createLabel" class="picker-footer" @mousedown.prevent>
|
||||
<div v-if="failed || hasMore || total || !createLabel || keyword && selected && !rows.length" class="picker-footer" @mousedown.prevent>
|
||||
<el-button v-if="failed" link type="danger" @click="loadPage(page+1)">加载失败,重试</el-button>
|
||||
<el-button v-else-if="hasMore" link type="primary" :loading="loading" @click="loadPage(page+1)">加载更多({{ loaded }} / {{ total }})</el-button>
|
||||
<span v-else>{{ total ? '共 '+total+' 项' : '没有匹配结果' }}</span>
|
||||
|
||||
@ -13,6 +13,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { computed } from 'vue'
|
||||
import AssistantResults from './AssistantResults.vue'
|
||||
import { assistantQueryConditions, assistantQueryTitle, assistantActionNotice } from '@/utils/business-assistant'
|
||||
@ -26,7 +27,7 @@ const errors = computed(() => {
|
||||
const errors = props.query.errors
|
||||
return [...new Set((Array.isArray(errors) ? errors : errors && typeof errors === 'object' ? Object.values(errors).flat() : errors ? [errors] : []).map(String))]
|
||||
})
|
||||
function formatTime(value) { const time = new Date(value); return Number.isNaN(time.valueOf()) ? '' : `查询于 ${time.toLocaleString('zh-CN', { hour12: false })}` }
|
||||
function formatTime(value) { const time = formatDateTime(value); return time === '—' ? '' : `查询于 ${time}` }
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@ -39,7 +39,7 @@
|
||||
<el-table-column label="参与人员" min-width="230"><template #default="{row}"><div class="kpi-person"><span class="kpi-avatar">{{ Array.from(row.employeeName||row.account||'?')[0] }}</span><div><strong>{{ row.employeeName }}</strong><small>{{ row.account }}</small></div></div></template></el-table-column>
|
||||
<el-table-column prop="deptName" label="所属部门" min-width="160"><template #default="{row}">{{ row.deptName||'—' }}</template></el-table-column>
|
||||
<el-table-column label="本阶段进度" min-width="180" class-name="business-status-cell"><template #default="{row}"><span class="kpi-person-status" :class="{confirmed:row.status!=='DRAFT'}"><i/>{{ kpiWorkflow(current)==='CREATED'?'待开始':kpiProgressLabel(row) }}</span><small class="kpi-progress-detail">{{ current.phase==='REVIEW'?'已补充 '+(row.completeCount||0)+' / '+(row.itemCount||0)+' 项评价':'已填 '+(row.filledCount||0)+' 项目标' }}</small></template></el-table-column>
|
||||
<el-table-column prop="updateTime" label="最后更新" min-width="180"/>
|
||||
<el-table-column :formatter="(row,column,value)=>formatDateTime(value)" prop="updateTime" label="最后更新" min-width="180"/>
|
||||
<el-table-column label="操作" width="155" fixed="right" class-name="business-operation-cell"><template #default="{row}"><el-button link type="primary" @click="openAssessment(row.id)">{{ kpiWorkflow(current)==='ENDED'?'查看详情':'查看 / 维护' }}<el-icon class="kpi-link-icon"><ArrowRight/></el-icon></el-button></template></el-table-column>
|
||||
<template #empty><KpiEmpty title="没有找到匹配的人员" description="试试其他关键词,或查看全部参与人员。" action-label="清除筛选" @action="personFilter='';progressFilter='ALL'"/></template>
|
||||
</el-table>
|
||||
@ -67,6 +67,7 @@
|
||||
</div>
|
||||
</template>
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { computed,nextTick,onActivated,onBeforeUnmount,onMounted,ref } from 'vue'
|
||||
import { useRoute,useRouter } from 'vue-router'
|
||||
import { ElMessage,ElMessageBox } from 'element-plus'
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
<div :class="['file-symbol',fileTone(file(doc))]" aria-hidden="true"><el-icon :size="20"><Document/></el-icon></div>
|
||||
<div class="file-description">
|
||||
<div class="file-name-line"><el-button v-if="file(doc)" link type="primary" class="file-name" :disabled="busy" :title="doc.title===file(doc).name?doc.title:`材料:${doc.title}\n文件:${file(doc).name}`" @click="emitAction(previewable(file(doc))?'preview':'download',doc)">{{ file(doc).name }}</el-button><strong v-else class="file-name" :title="doc.title">{{ doc.title }}</strong></div>
|
||||
<div class="file-meta"><span v-if="!category" class="file-category">{{ categoryName(doc.category) }}</span><span v-if="file(doc)">{{ formatSize(file(doc).size) }}</span><span>{{ file(doc)?.createBy||doc.createBy||'—' }}</span><time :title="file(doc)?.createTime||doc.createTime">{{ formatTime(file(doc)?.createTime||doc.createTime) }}</time></div>
|
||||
<div class="file-meta"><span v-if="!category" class="file-category">{{ categoryName(doc.category) }}</span><span v-if="file(doc)">{{ formatSize(file(doc).size) }}</span><span>{{ file(doc)?.createBy||doc.createBy||'—' }}</span><time :title="formatDateTime(file(doc)?.createTime||doc.createTime)">{{ formatTime(file(doc)?.createTime||doc.createTime) }}</time></div>
|
||||
<div v-if="normalize(keyword)&&normalize(doc.title).includes(normalize(keyword))&&!normalize(file(doc)?.name).includes(normalize(keyword))" class="material-title" :title="doc.title">匹配材料名:{{ doc.title }}</div>
|
||||
<div v-if="historicalMatch(doc)" class="history-match" :title="historicalMatch(doc)">匹配历史版本:{{ historicalMatch(doc) }}</div>
|
||||
</div>
|
||||
@ -52,6 +52,7 @@
|
||||
</section>
|
||||
</template>
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import {computed,ref,watch} from 'vue'
|
||||
import {Document,Search,MoreFilled} from '@element-plus/icons-vue'
|
||||
const props=defineProps({documents:{type:Array,default:()=>[]},categories:{type:Array,default:()=>[]},selected:{type:Object,default:()=>({})},busy:Boolean,canWrite:Boolean,readOnly:Boolean,emptyDescription:{type:String,default:'暂无文件'}})
|
||||
@ -75,7 +76,7 @@ function historicalMatch(doc){const q=normalize(keyword.value);if(!q||normalize(
|
||||
function versionLabel(doc,item){return `第 ${item.revision} 版${item.id===doc.currentFileId?' · 最新':''}${item.id===doc.finalFileId?' · 最终版':''}`}
|
||||
function previewable(item){return ['application/pdf','image/png','image/jpeg'].includes(item?.contentType)}
|
||||
function fileTone(item){if(item?.contentType==='application/pdf')return 'pdf';if(item?.contentType?.startsWith('image/'))return 'image';return 'other'}
|
||||
function formatTime(value){return value?String(value).replace('T',' ').slice(0,16):'—'}
|
||||
function formatTime(value){return formatDateTime(value).slice(0,16)}
|
||||
function formatSize(value){const size=Number(value)||0;return size<1024*1024?`${Math.max(1,Math.round(size/1024))} KB`:`${(size/1024/1024).toFixed(2)} MB`}
|
||||
function writable(doc){return props.canWrite&&!props.readOnly&&doc.canWrite}
|
||||
function manageable(doc){return props.canWrite&&!props.readOnly&&doc.canManage}
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
<section class="project-governance">
|
||||
<div class="team-heading"><div><h3>项目团队</h3><p>项目经理或超级管理员可维护团队,设置经理不改变原有业务归属。</p></div><div v-if="summary.canManage&&canEdit" class="actions"><el-button :disabled="busy" @click="openPeople('ADD')">添加成员</el-button><el-button :disabled="busy" @click="openPeople('TRANSFER')">{{ hasManager?'转交经理':'设置项目经理' }}</el-button><el-dropdown v-if="[0,1].includes(Number(project.projectStatus))" :disabled="busy" @command="openState"><el-button :disabled="busy">更多操作</el-button><template #dropdown><el-dropdown-menu><el-dropdown-item v-if="Number(project.projectStatus)===0" command="START">内部项目启动</el-dropdown-item><el-dropdown-item v-if="Number(project.projectStatus)===1" command="FINISH">项目结题</el-dropdown-item><el-dropdown-item command="TERMINATE">终止项目</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div></div>
|
||||
<div class="team-grid"><article v-for="person in summary.members||[]" :key="person.userId" class="person"><div class="avatar">{{ (person.name||person.userName||'?').slice(0,1) }}</div><div class="person-name"><strong>{{ person.name||person.userName }}</strong><small>{{ person.userName }}</small></div><el-tag size="small" :type="person.role==='MANAGER'?'primary':'info'">{{ person.role==='MANAGER'?'项目经理':'成员' }}</el-tag><el-button v-if="summary.canManage&&canEdit&&person.role!=='MANAGER'" link type="danger" :disabled="busy" @click="remove(person)">移除</el-button></article></div>
|
||||
<el-collapse class="history"><el-collapse-item title="状态和操作记录" name="history"><el-empty v-if="!summary.history?.length" description="暂无操作记录" :image-size="60"/><el-timeline v-else><el-timeline-item v-for="item in summary.history" :key="item.id" :timestamp="`${item.createTime} · ${item.createBy}`">{{ item.description }}</el-timeline-item></el-timeline></el-collapse-item></el-collapse>
|
||||
<el-collapse class="history"><el-collapse-item title="状态和操作记录" name="history"><el-empty v-if="!summary.history?.length" description="暂无操作记录" :image-size="60"/><el-timeline v-else><el-timeline-item v-for="item in summary.history" :key="item.id" :timestamp="`${formatDateTime(item.createTime)} · ${item.createBy}`">{{ item.description }}</el-timeline-item></el-timeline></el-collapse-item></el-collapse>
|
||||
<el-dialog v-model="peopleOpen" :title="peopleAction==='ADD'?'添加项目成员':hasManager?'转交项目经理':'设置项目经理'" :width="peopleAction==='ADD'?'min(820px,96vw)':'min(480px,94vw)'" append-to-body :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy">
|
||||
<template v-if="peopleAction==='ADD'">
|
||||
<el-input v-model="memberKeyword" class="member-search" clearable :disabled="busy" placeholder="搜索姓名或账号" aria-label="搜索可选项目成员" @input="scheduleMemberSearch"/>
|
||||
@ -16,6 +16,7 @@
|
||||
</section>
|
||||
</template>
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import {computed,onBeforeUnmount,ref,watch} from 'vue'
|
||||
import {ElMessageBox,ElMessage} from 'element-plus'
|
||||
import {addProjectMembers,changeProjectMember,projectUserCandidates,transferProjectManager,changeProjectState} from '@/api/project/workspace'
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
<el-alert v-if="error" :title="error" type="error" show-icon :closable="false"><el-button link @click="load">重新加载</el-button></el-alert>
|
||||
<template v-if="!error">
|
||||
<div v-if="type==='batch'" class="purchase-documents__kinds" role="tablist" aria-label="采购资料分类">
|
||||
<el-button v-for="item in purchaseDocumentKinds" :key="item.kind" :type="activeKind===item.kind?'primary':''" :plain="activeKind!==item.kind" :disabled="busy" role="tab" :aria-selected="activeKind===item.kind" @click="switchKind(item.kind)">{{ item.label }} <span class="purchase-documents__count">{{ groups.find(g=>g.kind===item.kind)?.files.length || 0 }}</span></el-button>
|
||||
<el-button v-for="item in visibleKinds" :key="item.kind" :type="activeKind===item.kind?'primary':''" :plain="activeKind!==item.kind" :disabled="busy" role="tab" :aria-selected="activeKind===item.kind" @click="switchKind(item.kind)">{{ item.label }} <span class="purchase-documents__count">{{ groups.find(g=>g.kind===item.kind)?.files.length || 0 }}</span></el-button>
|
||||
</div>
|
||||
<template v-if="current">
|
||||
<div class="purchase-documents__heading"><h3>{{ current.label }}</h3><span>{{ current.files.length }} / 10 个附件</span></div>
|
||||
@ -24,7 +24,7 @@
|
||||
<el-empty v-if="!current.files.length && !loading" :description="editable?'暂无附件,可按需上传':'暂无附件'" :image-size="72"/>
|
||||
<ul v-else class="purchase-documents__files">
|
||||
<li v-for="file in current.files" :key="file.id" :class="{'is-previewing':previewFile?.id===file.id}">
|
||||
<div class="purchase-documents__file-info"><strong :title="file.name">{{ file.name }}</strong><span>{{ purchaseDocumentSize(file.size) }} · {{ file.uploadedBy }} · {{ file.uploadedAt }}</span></div>
|
||||
<div class="purchase-documents__file-info"><strong :title="file.name">{{ file.name }}</strong><span>{{ purchaseDocumentSize(file.size) }} · {{ file.uploadedBy }} · {{ formatDateTime(file.uploadedAt) }}</span></div>
|
||||
<div class="purchase-documents__file-actions"><el-button v-if="canPreview(file)" link type="primary" :disabled="busy" @click="preview(file)">预览</el-button><el-button link type="primary" :disabled="busy" @click="download(file)">下载</el-button><el-popconfirm v-if="editable" title="确认移除此附件?" confirm-button-text="移除" @confirm="remove(file)"><template #reference><el-button link type="danger" :disabled="busy">移除</el-button></template></el-popconfirm></div>
|
||||
</li>
|
||||
</ul>
|
||||
@ -41,6 +41,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { computed, defineAsyncComponent, onBeforeUnmount, ref, shallowRef } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { saveAs } from 'file-saver'
|
||||
@ -50,6 +51,7 @@ import { purchaseDocumentKinds, purchaseAttachmentAccept, purchaseAttachmentErro
|
||||
|
||||
const DocumentPdfPreview = defineAsyncComponent(()=>import('@/components/SupplierLicenseAttachment/PdfPreview.vue'))
|
||||
const user = useUserStore()
|
||||
const visibleKinds = computed(()=>purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||user.permissions.includes('*:*:*')||user.permissions.includes('warehouse:purchase:manage')))
|
||||
const visible = ref(false), type = ref('batch'), targetId = ref(), context = ref(''), activeKind = ref('REQUEST'), groups = ref([])
|
||||
const loading = ref(false), busy = ref(false), uploading = ref(false), error = ref(''), closeWarning = ref(false)
|
||||
const previewFile = ref(null), previewBlob = shallowRef(null), previewUrl = ref('')
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
<el-table-column v-if="!unbatched" prop="purchaseBatchNo" label="批次" min-width="140" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!unbatched" prop="supplierName" label="供应商" min-width="120" show-overflow-tooltip/>
|
||||
<el-table-column label="数量" width="95" show-overflow-tooltip><template #default="s">{{ s.row.quantity }} {{ s.row.unit }}</template></el-table-column>
|
||||
<el-table-column label="单价" width="100" align="right" show-overflow-tooltip><template #default="s">{{ s.row.finalUnitPrice==null?'待报价':s.row.finalUnitPrice }}</template></el-table-column>
|
||||
<el-table-column v-if="canViewQuotes" label="报价单价" width="100" align="right" show-overflow-tooltip><template #default="s">{{ s.row.finalUnitPrice==null?'待报价':s.row.finalUnitPrice }}</template></el-table-column>
|
||||
<el-table-column v-if="!compactAmounts" prop="actualUnitPrice" label="实际单价" width="115" align="right" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!compactAmounts" prop="actualAmount" label="实际金额" width="115" align="right" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!unbatched" label="进度" width="150" align="center" show-overflow-tooltip><template #default="s">已验收 {{ s.row.acceptedQuantity||0 }} / 未到 {{ s.row.remainingQuantity||0 }}</template></el-table-column>
|
||||
@ -39,7 +39,7 @@ import {projectOptions} from '@/api/project/project'
|
||||
import {amountDisplay,loadAmountDisplay} from '@/utils/amount-display'
|
||||
export default {
|
||||
props:{projectId:Number,unbatched:Boolean,embedded:Boolean},
|
||||
computed:{compactAmounts(){return amountDisplay.enabled}},
|
||||
computed:{canViewQuotes(){return this.$auth.hasPermiOr(['warehouse:purchase:manage'])},compactAmounts(){return this.canViewQuotes&&amountDisplay.enabled}},
|
||||
components:{GroupDialog,SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker'))},
|
||||
data(){return {query:{pageNum:1,pageSize:20,materialName:'',purchaseBatchNo:'',projectId:this.projectId,supplierId:null,productionTaskId:Number(this.$route.query.productionTaskId)||undefined},rows:[],projects:[],total:0,selected:[],loading:false,saving:false}},
|
||||
watch:{unbatched(){this.clearSelection();this.search()},projectId(id){this.query.projectId=id;this.clearSelection();this.search()},'$route.fullPath'(){if(!this.embedded){this.applyRoute();this.clearSelection();this.search()}}},
|
||||
|
||||
@ -34,7 +34,7 @@
|
||||
<el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="businessDate" label="日期" width="115" show-overflow-tooltip/>
|
||||
<el-table-column prop="requestCount" label="明细数" width="90" align="center" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!compactAmounts" label="实际总金额" width="140" align="right" show-overflow-tooltip><template #default="s">{{ s.row.actualTotalAmount==null?'—':money(s.row.actualTotalAmount) }}</template></el-table-column>
|
||||
<el-table-column label="报价合计" width="140" align="right" show-overflow-tooltip><template #default="s">{{ money(s.row.totalAmount) }}<span v-if="s.row.unpricedCount" class="secondary">{{ s.row.unpricedCount }}项未报价</span></template></el-table-column>
|
||||
<el-table-column v-if="canViewQuotes" label="报价合计" width="140" align="right" show-overflow-tooltip><template #default="s">{{ money(s.row.totalAmount) }}<span v-if="s.row.unpricedCount" class="secondary">{{ s.row.unpricedCount }}项未报价</span></template></el-table-column>
|
||||
<el-table-column label="进度" width="110" align="center" class-name="business-status-cell"><template #default="s"><el-tag size="small" :type="(batchProgress(s.row).type) || 'primary'">{{ batchProgress(s.row).label }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="操作" width="125" align="center" fixed="right" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" size="small" @click="openBatch(s.row)">打开</el-button><el-dropdown v-if="(s.row.arrivableCount>0 && s.row.supplierId) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" trigger="click" @command="batchArrival(s.row)" ><el-button link type="primary" size="small">更多<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu ><el-dropdown-item command="arrival">登记到货</el-dropdown-item></el-dropdown-menu></template></el-dropdown></template></el-table-column>
|
||||
</el-table>
|
||||
@ -48,7 +48,7 @@
|
||||
<el-form-item v-if="!sheet.unbatched" label="批次"><el-input :model-value="sheet.batch.batchNo || '保存后自动生成'" disabled /></el-form-item>
|
||||
<el-form-item v-if="!sheet.unbatched" label="供应商"><supplier-picker v-if="isEditing && !supplierLocked" v-model="sheet.batch.supplierId" /><table-text v-else :value="supplierName" /></el-form-item>
|
||||
<el-form-item v-if="!sheet.unbatched" label="所属项目" required><el-select v-if="isEditing && !batchProject.mixed" ref="batchProjectSelect" :model-value="batchProject.value" filterable placeholder="选择一次,整批明细沿用" aria-label="批次所属项目" :disabled="!!projectId" @change="setBatchProject"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName"/></el-select><span v-else>{{ batchProject.mixed?'历史多项目批次(按明细保留)':batchProject.value?projectName(batchProject.value):'待选择' }}</span></el-form-item>
|
||||
<el-form-item v-if="!sheet.unbatched" label="日期"><el-date-picker v-if="isEditing" v-model="sheet.batch.businessDate" type="date" value-format="YYYY-MM-DD" :clearable="false" /><span v-else>{{ sheet.batch.businessDate || '—' }}</span></el-form-item>
|
||||
<el-form-item v-if="!sheet.unbatched" label="日期"><el-date-picker v-if="isEditing" v-model="sheet.batch.businessDate" type="date" value-format="YYYY-MM-DD" :clearable="false" /><span v-else>{{ formatDateTime(sheet.batch.businessDate) }}</span></el-form-item>
|
||||
<el-form-item v-if="isEditing" label="默认分类"><el-select v-model="commonCategory" filterable><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
|
||||
<el-form-item v-if="!sheet.unbatched" label="名称"><el-input v-if="isEditing" v-model="sheet.batch.batchName" maxlength="100" placeholder="选填" /><table-text v-else :value="sheet.batch.batchName" /></el-form-item>
|
||||
</el-form>
|
||||
@ -78,7 +78,7 @@
|
||||
<el-popover trigger="click" width="320" placement="bottom"><template #reference><el-button size="small" :disabled="saving||!selected.length">批量设置<business-icon name="arrow-down"/></el-button></template><el-form label-width="80px" size="small"><el-form-item v-if="sheet.unbatched || batchProject.mixed" label="项目"><el-select v-model="commonProject" filterable clearable placeholder="选择项目" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'projectId')||r.id&&r.productionTaskId)" @change="setProjects"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName" /></el-select></el-form-item><el-form-item label="费用分类"><el-select v-model="commonCategory" filterable clearable placeholder="选择费用分类" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'expenseCategoryId'))" @change="setCategories"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName" /></el-select></el-form-item></el-form></el-popover>
|
||||
</template>
|
||||
<el-button v-if="!isEditing&&canExportInquiry && !sheet.unbatched" size="small" icon="el-icon-download" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryRows.length" @click="$refs.quotation.exportInquiry()">导出询价单</el-button>
|
||||
<el-button v-if="!isEditing&&canEdit && !sheet.unbatched" size="small" icon="el-icon-upload" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryRows.length" @click="quoteImportOpen=true">回填供应商报价</el-button>
|
||||
<el-button v-if="!isEditing&&canEdit && canViewQuotes && !sheet.unbatched" size="small" icon="el-icon-upload" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryRows.length" @click="quoteImportOpen=true">回填供应商报价</el-button>
|
||||
<el-button size="small" :disabled="saving||!cellRange" @mousedown.prevent @click="copySelection">复制选区</el-button>
|
||||
<el-dropdown v-if="isEditing" trigger="click" :disabled="saving||!cellRange" @command="command=>command==='clear'?clearGridSelection():fillGrid(command)"><el-button size="small" :disabled="saving||!cellRange">选区操作<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item command="clear">清空内容(Delete)</el-dropdown-item><el-dropdown-item command="down" :disabled="!cellRange||cellRange.top===cellRange.bottom">向下填充(Ctrl/⌘+D)</el-dropdown-item><el-dropdown-item command="right" :disabled="!cellRange||cellRange.left===cellRange.right">向右填充(Ctrl/⌘+R)</el-dropdown-item></el-dropdown-menu></template></el-dropdown>
|
||||
<div class="sheet-toolbar__view"><el-checkbox v-model="extras">更多列</el-checkbox></div>
|
||||
@ -119,10 +119,10 @@
|
||||
<el-button v-if="rowErrors.length" link type="primary" @click="focusError(rowErrors[0])">定位错误</el-button>
|
||||
</div>
|
||||
<div class="sheet-footer">
|
||||
<div>显示 {{ visibleRows.length }} / {{ sheet.rows.length }} 行<span v-if="!compactAmounts" class="secondary-inline">实际总金额 {{ actualTotal==null?'—':'¥ '+money(actualTotal) }}</span><span class="secondary-inline">报价总金额 ¥ {{ money(amount) }} <span v-if="unpriced">({{ unpriced }} 行未报价)</span></span><el-tooltip content="选中后直接输入,Delete/Backspace 清空内容;拖动或 Shift 扩选。Ctrl/⌘+C/V 复制粘贴,Ctrl/⌘+D/R 向下/右填充,Z 撤销,Y 或 Shift+Z 重做。Tab 横移、输入后 Enter 换行、F2/双击编辑、Esc 取消本格修改。" placement="top"><business-icon name="question" /></el-tooltip></div>
|
||||
<div><el-button size="small" :disabled="saving || dirty || !selected.length || !selected.every(canArrive)" v-if="!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="arrival(selected)" >批量到货</el-button><el-button v-if="isEditing" size="small" type="primary" :loading="saving" :disabled="!dirty" @click="save">{{ sheet.unbatched?'保存未组批明细':'保存清单' }}</el-button><el-button size="small" type="success" plain icon="el-icon-lock" :disabled="saving || !canConfirm" v-if="!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="confirm" >确认采购</el-button></div>
|
||||
<div>显示 {{ visibleRows.length }} / {{ sheet.rows.length }} 行<span v-if="!compactAmounts" class="secondary-inline">实际总金额 {{ actualTotal==null?'—':'¥ '+money(actualTotal) }}</span><span v-if="canViewQuotes" class="secondary-inline">报价总金额 ¥ {{ money(amount) }} <span v-if="unpriced">({{ unpriced }} 行未报价)</span></span><el-tooltip content="选中后直接输入,Delete/Backspace 清空内容;拖动或 Shift 扩选。Ctrl/⌘+C/V 复制粘贴,Ctrl/⌘+D/R 向下/右填充,Z 撤销,Y 或 Shift+Z 重做。Tab 横移、输入后 Enter 换行、F2/双击编辑、Esc 取消本格修改。" placement="top"><business-icon name="question" /></el-tooltip></div>
|
||||
<div><el-button size="small" :disabled="saving || dirty || !selected.length || !selected.every(canArrive)" v-if="!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="arrival(selected)" >批量到货</el-button><el-button v-if="isEditing" size="small" type="primary" :loading="saving" :disabled="!dirty" @click="save">{{ sheet.unbatched?'保存未组批明细':'保存清单' }}</el-button><el-button size="small" type="success" plain icon="el-icon-lock" :disabled="saving || !canConfirm" v-if="canViewQuotes&&!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="confirm" >确认采购</el-button></div>
|
||||
</div>
|
||||
<div v-if="selectionStats" class="sheet-selection-stats" role="status" aria-live="polite"><span>选区 {{ selectionStats.rowCount }} 行 · {{ selectionStats.cellCount }} 格</span><span v-if="selectionStats.numeric">{{ selectionStats.numeric.label }}:计数 {{ selectionStats.numeric.count }} · 合计 {{ selectionStats.numeric.sum }} · 平均 {{ selectionStats.numeric.average }}</span><span v-else-if="selectionStats.numericCount">数值 {{ selectionStats.numericCount }} 格(不同字段/单位不混合计)</span><span v-if="selectionStats.quantities.length">数量:{{ selectionStats.quantities.map(group=>group.total+' '+(group.unit||'未填单位')).join(' / ') }}</span><span v-if="!compactAmounts">选中行实际金额 {{ selectionStats.actual?.amount===null?'—':'¥ '+selectionStats.actual?.amount }}<small v-if="selectionStats.actual?.unpricedCount">({{ selectionStats.actual.unpricedCount }} 行未填)</small></span><span>选中行报价金额 {{ selectionStats.quote.amount===null?'—':'¥ '+selectionStats.quote.amount }}<small v-if="selectionStats.quote.unpricedCount">({{ selectionStats.quote.unpricedCount }} 行未报价)</small></span></div>
|
||||
<div v-if="selectionStats" class="sheet-selection-stats" role="status" aria-live="polite"><span>选区 {{ selectionStats.rowCount }} 行 · {{ selectionStats.cellCount }} 格</span><span v-if="selectionStats.numeric">{{ selectionStats.numeric.label }}:计数 {{ selectionStats.numeric.count }} · 合计 {{ selectionStats.numeric.sum }} · 平均 {{ selectionStats.numeric.average }}</span><span v-else-if="selectionStats.numericCount">数值 {{ selectionStats.numericCount }} 格(不同字段/单位不混合计)</span><span v-if="selectionStats.quantities.length">数量:{{ selectionStats.quantities.map(group=>group.total+' '+(group.unit||'未填单位')).join(' / ') }}</span><span v-if="!compactAmounts">选中行实际金额 {{ selectionStats.actual?.amount===null?'—':'¥ '+selectionStats.actual?.amount }}<small v-if="selectionStats.actual?.unpricedCount">({{ selectionStats.actual.unpricedCount }} 行未填)</small></span><span v-if="canViewQuotes">选中行报价金额 {{ selectionStats.quote.amount===null?'—':'¥ '+selectionStats.quote.amount }}<small v-if="selectionStats.quote.unpricedCount">({{ selectionStats.quote.unpricedCount }} 行未报价)</small></span></div>
|
||||
</template>
|
||||
<teleport to="body"><div v-if="rowMenu&&isEditing" class="sheet-row-context" role="menu" aria-label="采购明细行操作" :style="{left:rowMenu.x+'px',top:rowMenu.y+'px'}" @contextmenu.prevent @keydown="rowMenuKeydown"><div class="sheet-row-context__heading">第 {{ contextRow?originalIndex(contextRow)+1:'—' }} 行 · 已选 {{ selected.length }} 行</div><button role="menuitem" type="button" :disabled="!canAdd||saving||sheet.rows.length>=2000" @click="rowCommand('before')">在上方插入一行</button><button role="menuitem" type="button" :disabled="!canAdd||saving||sheet.rows.length>=2000" @click="rowCommand('after')">在下方插入一行</button><button role="menuitem" type="button" :disabled="!canAdd||saving||sheet.rows.length>=2000" @click="rowCommand('many')">连续插入多行…</button><button role="menuitem" type="button" :disabled="!canAdd||saving||!selected.length||sheet.rows.length+selected.length>2000" @click="rowCommand('duplicate')">复制选中行到下方</button><div class="sheet-row-context__separator"/><button role="menuitem" type="button" class="is-danger" :disabled="saving||!canRemoveSelection" @click="rowCommand('remove')">删除选中行</button></div></teleport>
|
||||
<el-dialog v-model="insertRowsOpen" title="连续插入多行" width="min(400px,94vw)" append-to-body :close-on-click-modal="false"><el-form label-position="top"><el-form-item label="插入位置"><span>第 {{ insertRowsLine }} 行下方,仅新增编辑草稿</span></el-form-item><el-form-item label="新增行数"><el-input-number v-model="insertRowsCount" :min="1" :max="Math.min(100,2000-(sheet?.rows.length||0))" :precision="0" :controls="false" aria-label="新增行数"/></el-form-item></el-form><template #footer><el-button @click="insertRowsOpen=false">取消</el-button><el-button type="primary" :disabled="saving||!isEditing||!canAdd" @click="insertManyRows">插入</el-button></template></el-dialog>
|
||||
@ -139,7 +139,7 @@
|
||||
</el-alert>
|
||||
</template>
|
||||
</excel-import-dialog>
|
||||
<supplier-quotation ref="quotation" v-model="quoteImportOpen" :sheet="sheet" :supplier-name="supplierName" :disabled="saving || dirty" :can-edit="!!canEdit" :can-export="canExportInquiry" @apply="applyQuotes" @busy="quoteLoading=$event"/>
|
||||
<supplier-quotation ref="quotation" v-model="quoteImportOpen" :sheet="sheet" :supplier-name="supplierName" :disabled="saving || dirty" :can-edit="!!canEdit&&canViewQuotes" :can-export="canExportInquiry" @apply="applyQuotes" @busy="quoteLoading=$event"/>
|
||||
<el-dialog :close-on-press-escape="!saving" :close-on-click-modal="!saving" :show-close="!saving" title="转采购批次" v-model="moveOpen" width="min(580px,96vw)" append-to-body>
|
||||
<p>已选 {{ selected.length }} 项 · 只调整批次归组,不改变数量、报价、确认状态及到货/入库记录。</p>
|
||||
<el-radio-group v-model="moveMode" :disabled="saving||moveAttempted"><el-radio-button value="existing">转入已有批次</el-radio-button><el-radio-button value="new">新建批次并转入</el-radio-button></el-radio-group>
|
||||
@ -151,13 +151,14 @@
|
||||
</el-dialog>
|
||||
<batch-arrival ref="arrival" @changed="arrivalChanged" />
|
||||
<el-dialog title="到货记录" v-model="recordsOpen" width="900px" append-to-body>
|
||||
<p>{{ recordsItem }}</p><el-table :data="arrivalRecords" size="small"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="arrivalDate" label="日期" show-overflow-tooltip min-width="100"/><el-table-column prop="arrivalQuantity" label="数量" show-overflow-tooltip min-width="100"/><el-table-column label="验收" show-overflow-tooltip min-width="100"><template #default="s">{{ ['待验收','合格','不合格'][s.row.acceptanceStatus] || '已撤销' }}</template></el-table-column><el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="160"/></el-table>
|
||||
<p>{{ recordsItem }}</p><el-table :data="arrivalRecords" size="small"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="arrivalDate" label="日期" show-overflow-tooltip min-width="100"/><el-table-column prop="arrivalQuantity" label="数量" show-overflow-tooltip min-width="100"/><el-table-column label="验收" show-overflow-tooltip min-width="100"><template #default="s">{{ ['待验收','合格','不合格'][s.row.acceptanceStatus] || '已撤销' }}</template></el-table-column><el-table-column label="到货照片" width="130" class-name="business-control-cell"><template #default="s"><arrival-photos :model-value="s.row.photos||[]" readonly compact/></template></el-table-column><el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="160"/></el-table>
|
||||
<template #footer><div ><el-button @click="recordsOpen=false">关闭</el-button><el-button type="primary" @click="goArrival">去到货验收</el-button></div></template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { registerPageGuard } from '@/utils/page-guards'
|
||||
import { purchaseProjectState, purchaseBatchProjectChanges } from '@/utils/purchase-project'
|
||||
import { runLatest } from '@/utils/query-session'
|
||||
@ -194,11 +195,12 @@ function purchaseRouteStamp(route) {
|
||||
export default {
|
||||
setup(){const tableStage=ref(null),{height:gridHeight}=useContentHeight(tableStage),app=useAppStore();return {tableStage,gridHeight,pasteIssues:ref([]),cellSelection:ref(null),density:computed(()=>app.size),changedKeys:ref(new Set()),headerDirty:ref(false),structureDirty:ref(false),virtualStart:ref(0),virtualRowHeight:ref(40)}},
|
||||
name:'PurchaseBatchSheet', props:{projectId:Number,embedded:Boolean}, dicts:['wms_item_category'],
|
||||
components:{PurchaseCell,PriceCorrection,HistoryCorrection,PurchaseDocuments,SupplierQuotation,PastePreview,PurchaseLookup:defineAsyncComponent(()=>import('./Lookup')),SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),BatchArrival:defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')),CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')),ExcelImportDialog:defineAsyncComponent(()=>import('@/components/ExcelImportDialog'))},
|
||||
components:{ArrivalPhotos:defineAsyncComponent(()=>import('@/components/ArrivalPhotos')),PurchaseCell,PriceCorrection,HistoryCorrection,PurchaseDocuments,SupplierQuotation,PastePreview,PurchaseLookup:defineAsyncComponent(()=>import('./Lookup')),SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),BatchArrival:defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')),CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')),ExcelImportDialog:defineAsyncComponent(()=>import('@/components/ExcelImportDialog'))},
|
||||
data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,viewMode:'batches',loading:true,creating:false,saving:false,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,batches:[],total:0,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
|
||||
computed:{
|
||||
documentKinds(){return purchaseDocumentKinds},
|
||||
compactAmounts(){return amountDisplay.enabled},
|
||||
documentKinds(){return purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||this.canViewQuotes)},
|
||||
canViewQuotes(){return this.$auth.hasPermiOr(['warehouse:purchase:manage'])},
|
||||
compactAmounts(){return this.canViewQuotes&&amountDisplay.enabled},
|
||||
actualTotal(){return purchaseActualTotal(this.sheet?.rows||[])},
|
||||
baselineRowMap(){return new Map((this.baseline?JSON.parse(this.baseline).rows||[]:[]).map(row=>[row._key,row]))},
|
||||
inquiryRows(){return supplierInquiryRows(this.sheet?.rows?.filter(row=>visibleAmountRow(row,this.compactAmounts)))},
|
||||
@ -222,9 +224,9 @@ data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLin
|
||||
canUndo(){this.editCell;return this.history.length>0||!!this._editor?.hasPending()},
|
||||
canRedo(){return this.redoHistory.length>0&&!this._editor?.hasPending()},
|
||||
queueOptions(){return sheetQueues.map(q=>({...q,count:(this.sheet?.rows||[]).filter(r=>this.amountRowVisible(r)&&queueMatches(this.viewReference(r),q.value)).length}))},
|
||||
sortOptions(){return sheetSorts},
|
||||
sortOptions(){return this.canViewQuotes?sheetSorts:sheetSorts.filter(sort=>!['priceAsc','priceDesc','amountDesc'].includes(sort.value))},
|
||||
quoteCandidates(){return (this.sheet?.rows||[]).filter(r=>!r.historical&&Number(r.purchaseStatus)!==5&&!r.priceLocked&&!this.hasPrice(r))},
|
||||
visibleRows(){const q=clean(this.rowFilter).toLowerCase();const rows=this.sheet.rows.filter(r=>this.amountRowVisible(r)&&queueMatches(this.viewReference(r),this.rowQueue)&&(!q||[r.materialName,r.materialBrand,r.materialParams,r.requestNo,this.projectName(r.projectId)].join(' ').toLowerCase().includes(q))&&(!this.onlyInvalid||this.errorKeys.has(r._key)));return sortSheetRows(rows,this.rowSort,this.viewReference)},
|
||||
visibleRows(){const q=clean(this.rowFilter).toLowerCase();const rows=(this.sheet?.rows||[]).filter(r=>this.amountRowVisible(r)&&queueMatches(this.viewReference(r),this.rowQueue)&&(!q||[r.materialName,r.materialBrand,r.materialParams,r.requestNo,this.projectName(r.projectId)].join(' ').toLowerCase().includes(q))&&(!this.onlyInvalid||this.errorKeys.has(r._key)));return sortSheetRows(rows,this.rowSort,this.viewReference)},
|
||||
rowErrors(){if(!this.validationEnabled||!this.sheet||!this.isEditing)return [];const changed=this.activeRows().filter(r=>!r.id||this.changedKeys.has(r._key)),core=changed.filter(row=>!this.referenceOnly(row));return [...collectRowErrors(core,this.items,core.map(r=>this.originalIndex(r)+1),this.units,(this.dict.type.wms_item_category||[]).map(d=>d.label)),...changed.filter(row=>referencePriceError(row)).map(row=>({rowKey:row._key,line:this.originalIndex(row)+1,field:'actualUnitPrice',message:referencePriceError(row)}))]},
|
||||
errorKeys(){return new Set(this.rowErrors.map(e=>e.rowKey))},
|
||||
errorFields(){const result={};this.rowErrors.forEach(e=>{result[e.rowKey+'|'+e.field]=e.message});return result},
|
||||
@ -238,20 +240,20 @@ rowErrors(){if(!this.validationEnabled||!this.sheet||!this.isEditing)return [];c
|
||||
supplierLocked(){return !!this.sheet.batch.supplierId && this.sheet.rows.some(r=>r.priceLocked || r.historical || Number(r.acceptedQuantity)>0 || Number(r.pendingArrivalQuantity)>0)},
|
||||
supplierName(){return this.sheet?.batch?.supplierName || this.sheet?.rows?.find(r=>r.supplierName)?.supplierName || '待定'},
|
||||
nameItems(){return this.nameOptions || this.items},
|
||||
columns(){const columns=[{field:'materialName',label:'物品名称',width:180,required:true},{field:'materialParams',label:'规格型号',width:170},{field:'quantity',label:'数量',width:100,required:true},{field:'unit',label:'单位',width:75,required:true},{field:'finalUnitPrice',label:'报价单价',width:115},{field:'projectId',label:'项目',width:210,required:true},{field:'expenseCategoryId',label:'费用分类',width:150,required:true},{field:'materialBrand',label:'品牌',width:120},{field:'category',label:'物品类别',width:140,required:true},{field:'purchaseLink',label:'链接',width:190}];if(!this.compactAmounts)columns.splice(4,0,{field:'actualUnitPrice',label:'实际单价',width:115});if(this.extras)columns.push({field:'productionTaskId',label:'生产计划',width:200},{field:'purchasePurpose',label:'用途',width:130},{field:'loanId',label:'归还借用',width:200},{field:'remark',label:'备注',width:180});return columns.filter(column=>column.field!=='projectId'||this.sheet?.unbatched||this.batchProject.mixed)},
|
||||
columns(){const columns=[{field:'materialName',label:'物品名称',width:180,required:true},{field:'materialParams',label:'规格型号',width:170},{field:'quantity',label:'数量',width:100,required:true},{field:'unit',label:'单位',width:75,required:true},{field:'finalUnitPrice',label:'报价单价',width:115},{field:'projectId',label:'项目',width:210,required:true},{field:'expenseCategoryId',label:'费用分类',width:150,required:true},{field:'materialBrand',label:'品牌',width:120},{field:'category',label:'物品类别',width:140,required:true},{field:'purchaseLink',label:'链接',width:190}];if(!this.compactAmounts)columns.splice(4,0,{field:'actualUnitPrice',label:'实际单价',width:115});if(this.extras)columns.push({field:'productionTaskId',label:'生产计划',width:200},{field:'purchasePurpose',label:'用途',width:130},{field:'loanId',label:'归还借用',width:200},{field:'remark',label:'备注',width:180});return columns.filter(column=>(column.field!=='finalUnitPrice'||this.canViewQuotes)&&(column.field!=='projectId'||this.sheet?.unbatched||this.batchProject.mixed))},
|
||||
amount(){return this.sheet.rows.reduce((sum,r)=>sum+(Number(r.purchaseStatus)!==5?Number(r.quantity||0)*Number(r.finalUnitPrice||0):0),0)},
|
||||
unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Number(r.purchaseStatus)!==5).length},
|
||||
confirmationRows(){return (this.selected.length?this.selected:this.visibleRows).filter(r=>!r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5)},
|
||||
canConfirm(){return this.sheet.batch.id && !this.dirty && this.confirmationRows.length>0 && this.confirmationRows.every(this.hasPrice)},
|
||||
canConfirm(){return this.canViewQuotes && this.sheet.batch.id && !this.dirty && this.confirmationRows.length>0 && this.confirmationRows.every(this.hasPrice)},
|
||||
},
|
||||
watch:{sheet(){this.cellSelection=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pasteContext=null;this._insertContext=null},density(){this.resetGridScroll();this.layout()},editing(value){if(value)this.snapshotView();else{this.viewSnapshot=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false}this.layout()},extras(){this.cellSelection=null;this.layout()},rowFilter(){this.rowViewChanged()},rowQueue(){this.rowViewChanged()},rowSort(){this.rowViewChanged()},onlyInvalid(){this.cellSelection=null;this.resetGridScroll()},'sheet.rows.length'(){this.virtualStart=0;this.layout()},'$route.fullPath'(){if(this._routeStamp!==undefined&&!this._pageInactive)this.applyRoute()}},
|
||||
watch:{sheet(){this.cellSelection=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pasteContext=null;this._insertContext=null},density(){this.resetGridScroll();this.layout()},virtualCount(count,previous){if(!this.sheet||!this.virtualized)return;const end=Math.max(0,this.visibleRows.length-count),previousEnd=Math.max(0,this.visibleRows.length-previous);if(this.virtualStart>=previousEnd||this.virtualStart>end)this.virtualStart=end},editing(value){if(value)this.snapshotView();else{this.viewSnapshot=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false}this.layout()},extras(){this.cellSelection=null;this.layout()},rowFilter(){this.rowViewChanged()},rowQueue(){this.rowViewChanged()},rowSort(){this.rowViewChanged()},onlyInvalid(){this.cellSelection=null;this.resetGridScroll()},'sheet.rows.length'(){this.virtualStart=0;this.layout()},'$route.fullPath'(){if(this._routeStamp!==undefined&&!this._pageInactive)this.applyRoute()}},
|
||||
async created(){this.changedKeys=new Set();this.headerDirty=false;this.structureDirty=false;this._editor=createSheetEditor(this);this.loading=true;try{this.refreshDrafts();await this.references();if(this.embedded||this.$route.path!=='/procurement/details')await this.loadBatches();else await this.applyRoute()}finally{this.loading=false}},
|
||||
async activated(){this._pageInactive=false;if(this._routeStamp===undefined||this.loading||this.creating)return;const identity=this._routeIdentity;await this.applyRoute();if(!this._refreshOnActivate)return;this._refreshOnActivate=false;if(identity!==this._routeIdentity||this.saving||this.editing||this.dirty)return;if(this.sheet){const filter=this.rowFilter;if(this.sheet.unbatched){if(this.sheet.rows.length)await this.openUnbatched(this.sheet.rows,false)}else await this.openBatch(this.sheet.batch);this.rowFilter=filter}else if(this.viewMode==='batches')await this.loadBatches();else await this.$refs.lookup?.load()},
|
||||
unmounted(){this.endCellSelection()},
|
||||
deactivated(){this.persistDraft();this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pageInactive=true;this._creationEpoch=(this._creationEpoch||0)+1;this._refreshOnActivate=true;this.endCellSelection()},
|
||||
mounted(){this._guardPath=this.$route.path;this._unregisterPageGuard=registerPageGuard(this._guardPath,navigation=>this.checkNavigation(navigation));window.addEventListener('pointerdown',this.dismissRowMenu,true);window.addEventListener('keydown',this.dismissRowMenu);window.addEventListener('resize',this.resize);window.addEventListener('beforeunload',this.beforeUnload);window.addEventListener('pagehide',this.persistDraft);window.addEventListener('offline',this.persistDraft);document.addEventListener('visibilitychange',this.persistDraft)},
|
||||
beforeUnmount(){this._purchaseDisposed=true;this._creationEpoch=(this._creationEpoch||0)+1;this._unregisterPageGuard?.();this.persistDraft();this._editor?.stop();window.removeEventListener('pointerdown',this.dismissRowMenu,true);window.removeEventListener('keydown',this.dismissRowMenu);window.removeEventListener('resize',this.resize);window.removeEventListener('beforeunload',this.beforeUnload);window.removeEventListener('pagehide',this.persistDraft);window.removeEventListener('offline',this.persistDraft);document.removeEventListener('visibilitychange',this.persistDraft)},
|
||||
methods:{
|
||||
methods:{formatDateTime,
|
||||
exportTemplate(){this.download('warehouse/purchase/importTemplate',{},`采购申请导入模板_${Date.now()}.xlsx`)},
|
||||
async importedPurchases(){this.viewMode='unbatched';await this.references();await this.$nextTick();await this.$refs.lookup?.load()},
|
||||
canReopen:canReopenPurchase,
|
||||
@ -358,7 +360,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
|
||||
money(v){return Number(v||0).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})},
|
||||
actualAmount:purchaseActualAmount,
|
||||
referenceOnly(row){return referenceOnlyChange(row,this.baselineRowMap.get(row._key))},
|
||||
serialize(value){return JSON.stringify(value)},hasPrice(r){return r.finalUnitPrice!==null && r.finalUnitPrice!==undefined && r.finalUnitPrice!==''},
|
||||
serialize(value){return JSON.stringify(value)},hasPrice(r){return r.quoteAvailable===true || r.finalUnitPrice!==null && r.finalUnitPrice!==undefined && r.finalUnitPrice!==''},
|
||||
readonly(r){return !this.isEditing || !!r.historical || Number(r.purchaseStatus)===5},
|
||||
linkUrl(value){try{const url=new URL(clean(value));return ['http:','https:'].includes(url.protocol)?url.href:''}catch(e){return ''}},
|
||||
canArrive(r){return this.sheet && this.sheet.batch.supplierId && r.id && r.priceLocked && !r.historical && Number(r.purchaseStatus)!==5 && Number(r.remainingQuantity)>0},
|
||||
@ -375,14 +377,14 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
|
||||
selectColumn(field,event){if(this.saving||!this.visibleRows.length)return;document.activeElement?.blur?.();this.editCell=null;const anchor=event.shiftKey&&this.cellSelection?this.cellSelection.anchor.field:field;this.cellSelection={anchor:{key:this.visibleRows[0]._key,field:anchor},focus:{key:this.visibleRows.at(-1)._key,field}};this.$nextTick(()=>this.focusSelectedCell())},
|
||||
async focusSelectedCell(){const point=this.cellSelection?.focus,row=this.visibleRows.find(row=>row._key===point?.key);if(!row)return;await this.revealRow(row);await this.$nextTick();const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+point.field+'"]');(cell?.querySelector('.sheet-keyboard-input')||cell)?.focus({preventScroll:true});cell?.scrollIntoView({block:'nearest',inline:'nearest'})},
|
||||
isGridTypingCell(row,field){const range=this.cellRange;return !this.editCell&&this.editableCell(row,field)&&range&&range.top===range.bottom&&range.left===range.right&&this.cellSelection?.focus.key===row._key&&this.cellSelection?.focus.field===field},
|
||||
async typeGridCell(row,field,text){if(!this.editableCell(row,field)||this._typingGrid)return;this._typingGrid=true;try{await this.activateCell(row,field);const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]'),input=cell?.querySelector('input:not([disabled]),textarea:not([disabled])');if(input){input.value=text;input.dispatchEvent(new Event('input',{bubbles:true}));input.setSelectionRange?.(text.length,text.length)}}finally{this._typingGrid=false}},
|
||||
async typeGridCell(row,field,text){if(!this.editableCell(row,field)||this._typingGrid)return;this._typingGrid=true;try{await this.activateCell(row,field);const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]'),input=cell?.querySelector('input:not([disabled]),textarea:not([disabled])');if(input){input.value=text;input.dispatchEvent(new Event('input',{bubbles:true}));if(input.tagName==='TEXTAREA'||['text','search','tel','url','password'].includes(input.type))input.setSelectionRange?.(text.length,text.length)}}finally{this._typingGrid=false}},
|
||||
async clearGridSelection(){if(!this.isEditing||this.saving||!this.cellRange)return;try{await this.finishCellEdit();const changes=clearPurchaseGrid(this.visibleRows,this.columns,this.cellRange,this.editableCell);if(!changes.length)return;const byKey=new Map(changes.map(row=>[row._key,row]));this._identityEditor?.invalidate(this.sheet.rows);this.remember(this.sheet.rows.filter(row=>byKey.has(row._key)));for(const row of this.sheet.rows)if(byKey.has(row._key))Object.assign(row,byKey.get(row._key));await this.focusSelectedCell()}catch(error){this.$modal.msgWarning(error.message)}},
|
||||
selectionText(){return selectedGridText(this.cellRange,this.visibleRows,this.columns,(row,field)=>this.displayCell(row,field)==='—'?'':this.displayCell(row,field))},
|
||||
copyGridEvent(event){if(!this.cellRange)return;const target=event.target,one=this.cellRange.top===this.cellRange.bottom&&this.cellRange.left===this.cellRange.right;if(one&&target.matches('input,textarea')&&target.selectionStart!==target.selectionEnd)return;event.preventDefault();event.clipboardData?.setData('text/plain',this.selectionText())},
|
||||
async copySelection(){if(!this.cellRange||this.saving)return;await this.finishCellEdit();try{await writeClipboardText(this.selectionText());this.$modal.msgSuccess('选区已复制,可粘贴到 Excel')}catch(error){this.$modal.msgWarning(error.message)}},
|
||||
async activateCell(row,field,openDropdown=false,event){if(!this.editableCell(row,field))return;await this.revealRow(row);const key=row._key+'|'+field,wasActive=this.editCell===key;this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}};this.rememberCell(this.originalIndex(row),field);this.editCell=key;await this.$nextTick();const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]');if(!cell)return;cell.scrollIntoView({block:'nearest',inline:'nearest'});const input=cell.querySelector('input:not([disabled]),textarea:not([disabled])');if(input&&!cell.contains(document.activeElement)){input.focus({preventScroll:true});input.select()}if(openDropdown&&!wasActive&&input?.getAttribute('aria-expanded')!=='true')cell.querySelector('.el-select__wrapper')?.click()},
|
||||
originalIndex(row){return this.rowIndexMap.get(row._key)??-1},
|
||||
fieldLocked(row,field){const received=Number(row.receivedQuantity||0)>0,arrived=received||Number(row.acceptedQuantity||0)>0||Number(row.pendingArrivalQuantity||0)>0;return (received&&['projectId','expenseCategoryId','purchasePurpose','loanId'].includes(field))||(arrived&&['materialName','materialBrand','materialParams','unit','category','finalUnitPrice'].includes(field))},
|
||||
fieldLocked(row,field){if(field==='finalUnitPrice'&&!this.canViewQuotes)return true;const received=Number(row.receivedQuantity||0)>0,arrived=received||Number(row.acceptedQuantity||0)>0||Number(row.pendingArrivalQuantity||0)>0;return (received&&['projectId','expenseCategoryId','purchasePurpose','loanId'].includes(field))||(arrived&&['materialName','materialBrand','materialParams','unit','category','finalUnitPrice'].includes(field))},
|
||||
mergeItems(items){const map=new Map(this.items.map(r=>[String(r.id),r]));items.forEach(r=>{const old=map.get(String(r.id))||{};map.set(String(r.id),{...old,...r,unit:r.unit||old.unit,category:r.category||old.category})});this.items=[...map.values()]},
|
||||
async searchNames(keyword){const seq=this._nameSequence=(this._nameSequence||0)+1;this.nameLoading=true;try{const r=await purchaseSheetOptions({keyword});if(seq===this._nameSequence){this.mergeItems(r.data.items||[]);this.nameOptions=r.data.items||[]}}finally{if(seq===this._nameSequence)this.nameLoading=false}},
|
||||
async loadName(name){const r=await purchaseSheetOptions({name});this.mergeItems(r.data.items||[])},
|
||||
@ -523,7 +525,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
|
||||
validateRows(changed,this.items,changed.map(r=>this.sheet.rows.findIndex(o=>o._key===r._key)+1))
|
||||
for(const row of rows){
|
||||
if(!this.referenceOnly(row)&&!row.productId&&!this.units.some(u=>same(u,row.unit)))throw new Error('新物品请使用字典中的单位')
|
||||
row.finalUnitPrice=this.hasPrice(row)?Number(row.finalUnitPrice):null
|
||||
row.finalUnitPrice=this.canViewQuotes&&this.hasPrice(row)?Number(row.finalUnitPrice):null
|
||||
row.actualUnitPrice=row.actualUnitPrice===''||row.actualUnitPrice===undefined?null:row.actualUnitPrice
|
||||
}
|
||||
this.saving=true
|
||||
|
||||
@ -26,6 +26,7 @@
|
||||
<el-form-item label="本次数量"><el-input-number v-model="row.quantity" :precision="4" :min="0" :max="row.maximum" :disabled="mode==='acceptance'||row.done||saving||!!row.arrivalIdCreated" :controls="false"/><span class="batch-quantity-hint">{{ remainingLabel }} {{ remainingQuantity(row) }} {{ row.unit }}</span></el-form-item>
|
||||
<el-form-item v-if="mode==='receipt'" label="库区"><el-select v-model="row.areaId" filterable :class="{'area-required':row.validationError==='area'&&!row.areaId}" :disabled="row.done||saving" @change="clearAreaError(row)"><el-option v-for="a in areas" :key="a.id" :label="a.areaName" :value="a.id"/></el-select></el-form-item>
|
||||
</el-form>
|
||||
<arrival-photos v-if="mode!=='receipt'" v-model="row.photos" :request-id="row.id" :readonly="mode==='acceptance'||!!row.arrivalIdCreated" :disabled="saving" compact :title="(row.materialName||row.productName)+' · 到货照片'" @pending="row.photosPending=$event"/>
|
||||
<div v-if="row.result" class="batch-row-result" :class="{failed:row.failed}" role="status">{{ row.result }}</div>
|
||||
</div>
|
||||
<el-empty v-if="!filteredRows.length&&!opening" description="没有符合条件的记录" :image-size="60"/>
|
||||
@ -38,6 +39,7 @@
|
||||
<el-table-column v-if="mode==='acceptance'" label="不合格数量" width="145" align="right" class-name="business-control-cell"><template #default="s"><el-input-number v-model="s.row.defectiveQuantity" :precision="4" :min="0" :max="s.row.quantity" :disabled="saving||s.row.done" :controls="false" style="width:120px"/></template></el-table-column>
|
||||
<el-table-column label="本次数量" width="145" align="right" class-name="business-control-cell"><template #default="s"><el-input-number v-model="s.row.quantity" :precision="4" :min="0" :max="s.row.maximum" :disabled="mode==='acceptance'||s.row.done||saving||!!s.row.arrivalIdCreated" :controls="false" style="width:120px"/></template></el-table-column>
|
||||
<el-table-column v-if="mode==='receipt'" label="库区" width="180" class-name="business-control-cell"><template #default="s"><el-select v-model="s.row.areaId" filterable :class="{'area-required':s.row.validationError==='area'&&!s.row.areaId}" :disabled="s.row.done||saving" @change="clearAreaError(s.row)"><el-option v-for="a in areas" :key="a.id" :label="a.areaName" :value="a.id"/></el-select></template></el-table-column>
|
||||
<el-table-column v-if="mode!=='receipt'" label="到货照片" width="145" class-name="business-control-cell"><template #default="s"><arrival-photos v-model="s.row.photos" :request-id="s.row.id" :readonly="mode==='acceptance'||!!s.row.arrivalIdCreated" :disabled="saving" compact :title="(s.row.materialName||s.row.productName)+' · 到货照片'" @pending="s.row.photosPending=$event"/></template></el-table-column>
|
||||
<el-table-column label="处理状态" min-width="150" class-name="business-status-cell"><template #default="s"><span class="batch-dialog-status" :class="{'is-failed':s.row.failed,'is-done':s.row.done}">{{ s.row.result||'待提交' }}</span></template></el-table-column>
|
||||
</el-table>
|
||||
</template>
|
||||
@ -49,13 +51,14 @@
|
||||
import { optionselectArea } from '@/api/warehouse/area'
|
||||
import { getInRecord, receiveInRecord, updateInRecord, confirmInRecord } from '@/api/warehouse/inRecord'
|
||||
import { addPurchaseArrival, acceptPurchaseArrival, listPurchaseArrival } from '@/api/warehouse/purchase'
|
||||
import ArrivalPhotos from '@/components/ArrivalPhotos'
|
||||
import BatchProgress from '@/components/BatchProgress'
|
||||
import DialogWorkspace from '@/components/DialogWorkspace'
|
||||
import ItemSummary from '@/components/ItemSummary'
|
||||
import TableText from '@/components/TableText'
|
||||
import { useCompactLayout } from '@/utils/use-compact-layout'
|
||||
export default {
|
||||
components:{BatchProgress,DialogWorkspace,ItemSummary,TableText},setup:useCompactLayout,
|
||||
components:{ArrivalPhotos,BatchProgress,DialogWorkspace,ItemSummary,TableText},setup:useCompactLayout,
|
||||
data:()=>({visible:false,saving:false,opening:false,mode:'receipt',rows:[],runRows:[],onlyFailed:false,areas:[],commonArea:undefined,date:'',remark:'',acceptAll:true,keyword:'',pageNum:1,pageSize:20}),
|
||||
watch:{keyword(){this.pageNum=1;const visible=new Set(this.filteredRows);this.rows.forEach(r=>{if(!visible.has(r)&&!r.done)r.chosen=false})},onlyFailed(){this.pageNum=1},'filteredRows.length'(count){this.pageNum=Math.min(this.pageNum,Math.max(1,Math.ceil(count/this.pageSize)))}},
|
||||
computed:{
|
||||
@ -82,9 +85,9 @@ export default {
|
||||
if(mode==='acceptance') {
|
||||
const requests=[...new Map(input.filter(r=>!r.historical&&Number(r.purchaseStatus)!==5).map(r=>[r.id,r])).values()]
|
||||
const arrivals=await Promise.all(requests.map(request=>listPurchaseArrival(request.id)))
|
||||
this.rows=requests.flatMap((request,index)=>(arrivals[index].data||[]).filter(a=>Number(a.acceptanceStatus)===0).map(a=>({...request,arrivalIdCreated:a.id,arrivalNo:a.arrivalNo,quantity:Number(a.arrivalQuantity),maximum:Number(a.arrivalQuantity),defectiveQuantity:0,chosen:true,done:false,failed:false,result:''})))
|
||||
this.rows=requests.flatMap((request,index)=>(arrivals[index].data||[]).filter(a=>Number(a.acceptanceStatus)===0).map(a=>({...request,arrivalIdCreated:a.id,arrivalNo:a.arrivalNo,photos:a.photos||[],quantity:Number(a.arrivalQuantity),maximum:Number(a.arrivalQuantity),defectiveQuantity:0,chosen:true,done:false,failed:false,result:''})))
|
||||
} else {
|
||||
this.rows=input.filter(r=>mode==='receipt'?Number(r.inStatus)===0:Number(r.remainingQuantity)>0&&Number(r.purchaseStatus)!==5&&r.priceLocked&&!r.historical).map(r=>({...r,quantity:mode==='receipt'?Number(r.inNum):0,maximum:Number(mode==='receipt'?r.inNum:r.remainingQuantity),chosen:true,done:false,failed:false,result:'',key:'batch-'+r.id+'-'+Date.now()+'-'+Math.random().toString(36).slice(2),arrivalIdCreated:null}))
|
||||
this.rows=input.filter(r=>mode==='receipt'?Number(r.inStatus)===0:Number(r.remainingQuantity)>0&&Number(r.purchaseStatus)!==5&&r.priceLocked&&!r.historical).map(r=>({...r,quantity:mode==='receipt'?Number(r.inNum):0,maximum:Number(mode==='receipt'?r.inNum:r.remainingQuantity),chosen:true,done:false,failed:false,result:'',key:'batch-'+r.id+'-'+Date.now()+'-'+Math.random().toString(36).slice(2),arrivalIdCreated:null,photos:[],photosPending:false}))
|
||||
}
|
||||
if(!this.rows.length){this.visible=false;this.$modal.msgWarning('没有可办理的记录')}
|
||||
} catch {this.visible=false} finally {this.opening=false}
|
||||
@ -97,6 +100,7 @@ export default {
|
||||
if(!this.date)return this.$modal.msgWarning('请选择日期')
|
||||
const pending=(retryOnly===true?this.rows.filter(r=>r.failed&&!r.done):this.selectedRows).filter(r=>Number(r.quantity)>0)
|
||||
if(!pending.length)return this.$modal.msgWarning('请填写本次实际数量')
|
||||
if(pending.some(r=>r.photosPending))return this.$modal.msgWarning('有照片尚未上传完成,请重试或移除后继续')
|
||||
if(this.mode==='receipt'){
|
||||
const missing=pending.filter(row=>!row.areaId)
|
||||
if(missing.length){missing.forEach(row=>{row.failed=true;row.validationError='area';row.result='请选择库区'});return this.$modal.msgWarning('请先为 '+missing.length+' 项选择库区,可使用统一库区')}
|
||||
@ -118,7 +122,7 @@ export default {
|
||||
}
|
||||
} else {
|
||||
if(!row.arrivalIdCreated){
|
||||
const result=await addPurchaseArrival({purchaseRequestId:row.id,arrivalQuantity:row.quantity,arrivalDate:this.date,requestKey:row.key,remark:this.remark})
|
||||
const result=await addPurchaseArrival({purchaseRequestId:row.id,arrivalQuantity:row.quantity,arrivalDate:this.date,requestKey:row.key,remark:this.remark,photoIds:(row.photos||[]).map(p=>p.id)})
|
||||
row.arrivalIdCreated=result.data&&result.data.id
|
||||
if(!row.arrivalIdCreated)throw new Error('请刷新到货记录核对')
|
||||
changed=true
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<business-list-page :loading="loading" :error="loadError" :filtered="!!keyword" @retry="load"><template #header>
|
||||
<el-form inline><query-toolbar><el-form-item label="关键词" class="query-field-wide"><el-input v-model="keyword" placeholder="供应商、联系人、电话或邮箱" clearable @keyup.enter="filterSuppliers"/></el-form-item><template #actions><el-button type="primary" icon="Search" @click="filterSuppliers">搜索</el-button><el-button icon="Refresh" @click="keyword='';filterSuppliers()">重置</el-button><el-button icon="Refresh" :loading="loading" @click="load">刷新</el-button></template><template #business><el-button type="primary" plain icon="Plus" @click="edit()" v-if="$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">新增</el-button></template></query-toolbar></el-form>
|
||||
</template><template #default="{tableHeight}">
|
||||
<business-table :data="filteredRows" v-loading="loading" :height="tableHeight" border><el-table-column prop="name" label="名称" show-overflow-tooltip min-width="160"/><el-table-column prop="contact" label="联系人" show-overflow-tooltip min-width="100"/><el-table-column prop="phone" label="联系电话" show-overflow-tooltip min-width="100"/><el-table-column prop="email" label="邮箱" show-overflow-tooltip min-width="180"/><el-table-column label="营业执照" min-width="160"><template #default="s"><supplier-license-attachment :model-value="s.row.businessLicenseId" :file-name="s.row.businessLicenseName" readonly/></template></el-table-column><el-table-column label="操作" align="center" width="120" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" @click="edit(s.row)" v-if="$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">修改</el-button><el-button link type="primary" @click="remove(s.row)" v-if="$can(['warehouse:purchase:manage'])">删除</el-button></template></el-table-column></business-table>
|
||||
<business-table :data="filteredRows" v-loading="loading" :height="tableHeight" border><el-table-column prop="name" label="名称" show-overflow-tooltip min-width="160"/><el-table-column prop="contact" label="联系人" show-overflow-tooltip min-width="100"/><el-table-column prop="phone" label="联系电话" show-overflow-tooltip min-width="100"/><el-table-column prop="email" label="邮箱" show-overflow-tooltip min-width="180"/><el-table-column label="营业执照" min-width="160" class-name="business-control-cell"><template #default="s"><supplier-license-attachment :model-value="s.row.businessLicenseId" :file-name="s.row.businessLicenseName" readonly/></template></el-table-column><el-table-column label="操作" align="center" width="120" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" @click="edit(s.row)" v-if="$can(['warehouse:purchase:edit','warehouse:purchase:manage'])">修改</el-button><el-button link type="primary" @click="remove(s.row)" v-if="$can(['warehouse:purchase:manage'])">删除</el-button></template></el-table-column></business-table>
|
||||
</template><template #footer><span class="supplier-count">共 {{ filteredRows.length }} 条</span></template></business-list-page>
|
||||
</component>
|
||||
<el-dialog title="供应商资料" v-model="editOpen" width="min(560px,96vw)" append-to-body :close-on-click-modal="false" :close-on-press-escape="!saving && !licenseUploading" :show-close="!saving && !licenseUploading">
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
<div class="status-line"><el-tag>{{ moduleLabel(state.module) }}</el-tag><el-tag :type="state.mailState === 'SENT' ? 'success' : 'info'">{{ mailLabel(state.mailState) }}</el-tag><span>{{ analysisLabel(state.analysisState) }}</span></div>
|
||||
<p>{{ state.reason }}</p>
|
||||
<el-alert v-if="state.lastError" :title="state.lastError" type="warning" :closable="false" />
|
||||
<p v-if="state.sentAt">已提交邮件服务器:{{ state.sentAt }}(不代表收件人已阅读)</p>
|
||||
<p v-if="state.sentAt">已提交邮件服务器:{{ formatDateTime(state.sentAt) }}(不代表收件人已阅读)</p>
|
||||
<p v-if="state.attemptRecipients?.length">本次通知邮箱:{{ state.attemptRecipients.join('、') }}</p>
|
||||
<template v-if="!locked">
|
||||
<div class="controls"><el-select v-model="selectedModule" aria-label="反馈归属" placeholder="人工选择归属" :disabled="busy || analyzing" style="width:180px"><el-option label="项目协作" value="COLLABORATION" /><el-option label="其他业务" value="OTHER" /></el-select><el-button :disabled="busy || analyzing || !selectedModule" @click="changeModule">确认归属</el-button><el-button :disabled="busy || analyzing" @click="analyze">{{ state.analysisState === 'NOT_STARTED' ? 'AI 分析归属' : '重新分析' }}</el-button></div>
|
||||
@ -28,6 +28,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { feedbackNotification, analyzeFeedback, changeFeedbackModule, previewFeedbackMail, sendFeedbackMail } from '@/api/system/feedback-notification'
|
||||
|
||||
@ -53,10 +53,10 @@
|
||||
<template v-if="detail">
|
||||
<div class="feedback-detail-tags"><el-tag :type="typeLabel(detail.type).tag">{{ typeLabel(detail.type).label }}</el-tag><el-tag :type="statusLabel(detail.status).tag">{{ statusLabel(detail.status).label }}</el-tag></div>
|
||||
<h3>{{ detail.title }}</h3>
|
||||
<dl class="feedback-detail-meta"><div><dt>提交人</dt><dd>{{ detail.submitterName || detail.userName || detail.createBy || '—' }}</dd></div><div><dt>提交时间</dt><dd>{{ detail.createTime || '—' }}</dd></div><div v-if="detail.pagePath"><dt>来源页面</dt><dd>{{ detail.pageTitle }} {{ detail.pagePath }}</dd></div></dl>
|
||||
<dl class="feedback-detail-meta"><div><dt>提交人</dt><dd>{{ detail.submitterName || detail.userName || detail.createBy || '—' }}</dd></div><div><dt>提交时间</dt><dd>{{ formatDateTime(detail.createTime) }}</dd></div><div v-if="detail.pagePath"><dt>来源页面</dt><dd>{{ detail.pageTitle }} {{ detail.pagePath }}</dd></div></dl>
|
||||
<div class="feedback-description">{{ detail.description }}</div>
|
||||
<div v-if="detailImages.length" class="feedback-detail-images"><figure v-for="image in detailImages" :key="image.key" class="feedback-image-card"><button type="button" class="feedback-thumbnail" :aria-label="`预览${image.name}`" :disabled="!image.url" @click="previewImages(detailImages, image.key)"><img v-if="image.url" :src="image.url" :alt="image.name" /><span v-else>{{ image.error || '加载中…' }}</span></button><figcaption :title="image.name">{{ image.name }}</figcaption></figure></div>
|
||||
<section v-if="detail.reply" class="feedback-existing-reply"><h4>处理回复</h4><div>{{ detail.reply }}</div><small v-if="detail.handledTime || detail.updateTime">{{ detail.handledTime || detail.updateTime }}</small></section>
|
||||
<section v-if="detail.reply" class="feedback-existing-reply"><h4>处理回复</h4><div>{{ detail.reply }}</div><small v-if="detail.handledTime || detail.updateTime">{{ formatDateTime(detail.handledTime || detail.updateTime) }}</small></section>
|
||||
<NotificationDetail v-if="canManage" :key="detail.id" :feedback-id="detail.id" />
|
||||
<el-form v-if="canManage" class="feedback-handle-form" label-position="top" @submit.prevent="saveHandling">
|
||||
<h4>处理反馈</h4><el-form-item label="处理状态"><el-select v-model="handling.status" aria-label="处理状态" :disabled="savingHandling"><el-option v-for="item in FEEDBACK_STATUSES" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
|
||||
@ -75,7 +75,7 @@
|
||||
<el-table-column label="类型" width="115" class-name="business-status-cell"><template #default="{ row }"><el-tag :type="typeLabel(row.type).tag" size="small">{{ typeLabel(row.type).label }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="状态" width="100" class-name="business-status-cell feedback-state-cell"><template #default="{ row }"><el-tag :type="statusLabel(row.status).tag" size="small">{{ statusLabel(row.status).label }}</el-tag></template></el-table-column>
|
||||
<el-table-column v-if="tab === 'all'" prop="submitterName" label="提交人" width="120" show-overflow-tooltip />
|
||||
<el-table-column prop="createTime" label="提交时间" width="166" />
|
||||
<el-table-column :formatter="(row,column,value)=>formatDateTime(value)" prop="createTime" label="提交时间" width="166" />
|
||||
<el-table-column label="操作" width="78" fixed="right" class-name="business-operation-cell feedback-actions-cell"><template #default="{ row }"><el-button link type="primary" @click="showDetail(row)">详情</el-button></template></el-table-column>
|
||||
</el-table></div>
|
||||
<el-pagination v-if="total > 0" v-model:current-page="page" :page-size="10" :total="total" layout="total, prev, pager, next" @current-change="loadList" />
|
||||
@ -87,6 +87,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
@ -27,7 +27,7 @@
|
||||
</span>
|
||||
<span class="meta-item">
|
||||
<el-icon><Clock /></el-icon>
|
||||
<span>{{ detail.createTime || '—' }}</span>
|
||||
<span>{{ formatDateTime(detail.createTime) }}</span>
|
||||
</span>
|
||||
<span class="meta-item">
|
||||
<span :class="['status-dot', isStatusNormal ? 'status-ok' : 'status-off']"></span>
|
||||
@ -53,6 +53,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { getNotice } from '@/api/system/notice'
|
||||
|
||||
const visible = ref(false)
|
||||
|
||||
@ -16,7 +16,7 @@
|
||||
<section v-if="detail" class="message-detail" aria-label="消息详情">
|
||||
<el-button link type="primary" :disabled="reading" @click="backToList">← 返回列表</el-button>
|
||||
<h2>{{ detail.title }}</h2>
|
||||
<div class="detail-meta">{{ detail.time || '—' }} · {{ detail.read ? '已读' : '未读' }}</div>
|
||||
<div class="detail-meta">{{ formatDateTime(detail.time) }} · {{ detail.read ? '已读' : '未读' }}</div>
|
||||
<p class="message-content">{{ detail.content || '暂无正文' }}</p>
|
||||
<el-button v-if="kpiTarget" type="primary" plain @click="openKpi">查看KPI</el-button>
|
||||
<el-button v-if="!detail.read" type="primary" :loading="reading" @click="markDetailRead">标为已读</el-button>
|
||||
@ -33,7 +33,7 @@
|
||||
<li v-for="item in messages" :key="item.id">
|
||||
<button type="button" class="message-item" :class="{ 'is-read': item.readAt }" @click="openMessage(item)">
|
||||
<span class="message-title"><span v-if="!item.readAt" class="unread-dot" aria-label="未读" />{{ item.title }}</span>
|
||||
<span class="message-time">{{ item.deliveredAt || '—' }}</span>
|
||||
<span class="message-time">{{ formatDateTime(item.deliveredAt) }}</span>
|
||||
<span class="message-excerpt">{{ item.content }}</span>
|
||||
</button>
|
||||
</li>
|
||||
@ -47,7 +47,7 @@
|
||||
<ul v-else class="center-list">
|
||||
<li v-for="item in notices" :key="item.noticeId">
|
||||
<button type="button" class="message-item" :class="{ 'is-read': item.isRead }" @click="openNotice(item)">
|
||||
<span class="message-title"><span v-if="!item.isRead" class="unread-dot" aria-label="未读" />{{ item.noticeTitle }}</span><span class="message-time">{{ item.createTime || '—' }}</span>
|
||||
<span class="message-title"><span v-if="!item.isRead" class="unread-dot" aria-label="未读" />{{ item.noticeTitle }}</span><span class="message-time">{{ formatDateTime(item.createTime) }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
@ -58,6 +58,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { ref, computed, watch, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import useUserStore from '@/store/modules/user'
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { displayTimestamp } from './display-format.js'
|
||||
export const ASSISTANT_FILE_TYPES = ['png', 'jpg', 'jpeg', 'xls', 'xlsx', 'pdf', 'doc', 'docx', 'txt', 'zip']
|
||||
export const ASSISTANT_FILE_LIMIT = 10 * 1024 * 1024
|
||||
export const ASSISTANT_PRODUCT_FILE_LIMIT = 50 * 1024 * 1024
|
||||
@ -228,7 +229,7 @@ export function assistantDisplayValue(value) {
|
||||
if (typeof value === 'boolean') return value ? '是' : '否'
|
||||
if (Array.isArray(value)) return value.map(assistantDisplayValue).join('、')
|
||||
if (typeof value === 'object') return Object.entries(value).filter(([key]) => !key.startsWith('_')).map(([key, item]) => `${key}:${assistantDisplayValue(item)}`).join(';')
|
||||
return String(value)
|
||||
return String(displayTimestamp(value))
|
||||
}
|
||||
|
||||
export function assistantResultTable(data) {
|
||||
|
||||
@ -1,6 +1,13 @@
|
||||
import { parseTime } from '@/utils/ruoyi'
|
||||
import { parseTime } from './ruoyi.js'
|
||||
export function formatDateTime(value) {
|
||||
if(value===null||value===undefined||value==='')return '—'
|
||||
if(typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value))return value
|
||||
if(typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value))return parseTime(value,'{y}-{m}-{d}')||'—'
|
||||
return parseTime(value,'{y}-{m}-{d} {h}:{i}:{s}')||'—'
|
||||
}
|
||||
|
||||
// Only format complete timestamp values; never rewrite a title, remark or item code.
|
||||
export function displayTimestamp(value) {
|
||||
if (value instanceof Date) return formatDateTime(value)
|
||||
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/i.test(value.trim())) return formatDateTime(value)
|
||||
return value
|
||||
}
|
||||
|
||||
5
ruoyi-ui-vue3/src/utils/project-access.js
Normal file
5
ruoyi-ui-vue3/src/utils/project-access.js
Normal file
@ -0,0 +1,5 @@
|
||||
// The root administrator can maintain historical projects without an assigned manager.
|
||||
export function canManageProject(project,userId){
|
||||
const actor=Number(userId)
|
||||
return !!project&&Number.isSafeInteger(actor)&&actor>0&&(actor===1||Number(project.managerId)===actor)
|
||||
}
|
||||
@ -13,7 +13,7 @@ export function batchProgress(row){
|
||||
if(Number(row.unlockedCount)>0)return {label:'待确认',type:'warning'}
|
||||
return {label:'采购中',type:''}
|
||||
}
|
||||
export function quoted(row){return row.finalUnitPrice!==null&&row.finalUnitPrice!==undefined&&row.finalUnitPrice!==''&&Number.isFinite(Number(row.finalUnitPrice))&&Number(row.finalUnitPrice)>=0}
|
||||
export function quoted(row){return row.quoteAvailable===true||row.finalUnitPrice!==null&&row.finalUnitPrice!==undefined&&row.finalUnitPrice!==''&&Number.isFinite(Number(row.finalUnitPrice))&&Number(row.finalUnitPrice)>=0}
|
||||
export function canReopenPurchase(row){return !!(row?.id&&!row.historical&&row.priceLocked&&Number(row.purchaseStatus)!==5&&!Number(row.acceptedQuantity)&&!Number(row.pendingArrivalQuantity)&&!Number(row.receivedQuantity))}
|
||||
export function queueMatches(row,queue){
|
||||
if(queue==='all')return true
|
||||
|
||||
@ -5,24 +5,39 @@
|
||||
|
||||
// 日期格式化
|
||||
export function parseTime(time, pattern) {
|
||||
if (arguments.length === 0 || !time) {
|
||||
if (time === null || time === undefined || time === '' || typeof time === 'boolean') {
|
||||
return null
|
||||
}
|
||||
if (!(time instanceof Date) && typeof time !== 'string' && typeof time !== 'number') return null
|
||||
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
|
||||
let date
|
||||
if (typeof time === 'object') {
|
||||
if (time instanceof Date) {
|
||||
date = time
|
||||
} else {
|
||||
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
|
||||
time = parseInt(time)
|
||||
} else if (typeof time === 'string') {
|
||||
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '')
|
||||
time = time.trim()
|
||||
// Calendar values have no timezone. Construct them locally on every browser;
|
||||
// keep ISO offsets intact so UTC/offset timestamps represent the correct instant.
|
||||
const local = time.match(/^(\d{4})[-/](\d{2})[-/](\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?$/)
|
||||
if (local) {
|
||||
const [, y, m, d, h = '0', i = '0', s = '0', fraction = ''] = local
|
||||
date = new Date(0)
|
||||
date.setFullYear(Number(y), Number(m) - 1, Number(d))
|
||||
date.setHours(Number(h), Number(i), Number(s), Number(fraction.padEnd(3, '0').slice(0, 3)))
|
||||
if (date.getFullYear() !== Number(y) || date.getMonth() !== Number(m) - 1 || date.getDate() !== Number(d)
|
||||
|| date.getHours() !== Number(h) || date.getMinutes() !== Number(i) || date.getSeconds() !== Number(s)) return null
|
||||
} else {
|
||||
time = time.replace(/^(\d{4}-\d{2}-\d{2}) /, '$1T').replace(/(\.\d{3})\d+/, '$1')
|
||||
}
|
||||
}
|
||||
if ((typeof time === 'number') && (time.toString().length === 10)) {
|
||||
time = time * 1000
|
||||
}
|
||||
date = new Date(time)
|
||||
if (!date) date = new Date(time)
|
||||
}
|
||||
if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null
|
||||
const formatObj = {
|
||||
y: date.getFullYear(),
|
||||
m: date.getMonth() + 1,
|
||||
|
||||
@ -60,6 +60,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import {ref,onBeforeUnmount} from 'vue'
|
||||
import {ElMessage,ElMessageBox,useZIndex} from 'element-plus'
|
||||
import {Upload,MoreFilled,ArrowDown} from '@element-plus/icons-vue'
|
||||
@ -79,7 +80,7 @@ function textFile(f){return f&&f.byte_size<=1024*1024&&/\.(txt|csv)$/i.test(f.na
|
||||
function previewable(f){return f&&(textFile(f)||f.byte_size<=30*1024*1024&&['application/pdf','image/png','image/jpeg','image/webp'].includes(f.content_type))}
|
||||
function kind(name){const ext=String(name||'').split('.').pop().toLowerCase();return ({pdf:'pdf',doc:'doc',docx:'doc',xls:'xls',xlsx:'xls',csv:'xls',ppt:'ppt',pptx:'ppt',png:'img',jpg:'img',jpeg:'img',webp:'img',zip:'zip','7z':'zip',rar:'zip'})[ext]||'file'}
|
||||
function size(n){return n>=1024*1024*1024?(n/(1024*1024*1024)).toFixed(2)+' GB':n>=1024*1024?(n/(1024*1024)).toFixed(1)+' MB':Math.max(1,Math.ceil(n/1024))+' KB'}
|
||||
function time(value){return value?String(value).replace('T',' ').slice(0,16):''}
|
||||
function time(value){return value?formatDateTime(value).slice(0,16):''}
|
||||
function pause(){controller?.abort()}
|
||||
function openNew(){if(props.blocked||working.value||!props.editable)return;versionDocument=null;picker.value.multiple=true;picker.value.click()}
|
||||
function dropFiles(event){dragging.value=false;if(props.blocked||working.value||!props.editable)return;versionDocument=null;selectFiles({target:{files:event.dataTransfer?.files||[],value:''}})}
|
||||
|
||||
@ -21,6 +21,7 @@
|
||||
</section>
|
||||
</template>
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import {computed,ref,watch} from 'vue'
|
||||
import {countDocuments,itemNames} from './archive-model'
|
||||
const props=defineProps({review:{type:Object,default:()=>({})},items:{type:Array,default:()=>[]},history:{type:Array,default:()=>[]},state:String,canReturn:Boolean}),emit=defineEmits(['open','return'])
|
||||
@ -35,7 +36,7 @@ const filteredDocuments=computed(()=>documents.value.filter(row=>matches([row.it
|
||||
const filteredItems=computed(()=>props.items.filter(item=>matches([item.title,...(item.documents||[]).map(doc=>doc.title)])))
|
||||
const filteredCosts=computed(()=>costs.value.filter(row=>matches([row.label,row.before,row.after])))
|
||||
const fileRows=computed(()=>filteredDocuments.value.slice((filePage.value-1)*50,filePage.value*50)),costRows=computed(()=>filteredCosts.value.slice((costPage.value-1)*50,costPage.value*50))
|
||||
const value=v=>v==null||v===''?'—':String(v),time=v=>v?String(v).replace('T',' ').slice(0,16):'—'
|
||||
const value=v=>v==null||v===''?'—':String(v),time=v=>formatDateTime(v).slice(0,16)
|
||||
const itemValue=(field,v)=>field==='state'?(itemNames[v]||value(v)):field==='applicable'?(Number(v)?'适用':'不适用'):value(v)
|
||||
function costValue(row,side){const v=row[side];if(v==null||v==='')return '未填写';if(row.path?.endsWith('.userId'))return side==='before'?'原关联人员':'已更换人员,请查看明细';if(typeof v==='number'){const n=v.toLocaleString('zh-CN',{maximumFractionDigits:4});if(row.path?.endsWith('.days'))return n+' 天';if(/(?:income|rate|gross|tax|amount)$/.test(row.path||'')||/(收入|金额|费用标准|采购成本|差旅费用|费用)$/.test(row.label||''))return v.toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})+(row.path?.endsWith('.rate')?' 元/人日':' 元');return n}return String(v)}
|
||||
function costChange(row){if(row.path?.endsWith('.userId'))return '已更换关联人员';if(row.before==null||row.before==='')return '新增填写';if(row.after==null||row.after==='')return '已清空';if(typeof row.before==='number'&&typeof row.after==='number')return (row.after>row.before?'增加 ':'减少 ')+costValue({...row,after:Math.abs(row.after-row.before)},'after');return '已修改'}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
<template>
|
||||
<main class="cost-dashboard" v-loading="booting">
|
||||
<header class="analysis-heading"><div><div class="analysis-eyebrow">项目资料 / 经营分析</div><h2>项目成本汇总 <span>管理员专享</span></h2></div><el-button @click="$router.push('/project-archive')">返回项目资料</el-button></header>
|
||||
<main class="cost-dashboard" aria-label="项目成本汇总" v-loading="booting">
|
||||
<el-result v-if="denied" icon="warning" title="仅项目资料管理员可查看成本汇总" sub-title="请联系管理员确认角色和成本汇总权限。"/>
|
||||
<template v-else-if="!booting">
|
||||
<section class="analysis-filters">
|
||||
@ -13,7 +12,6 @@
|
||||
<el-form-item label="成本范围"><el-select v-model="query.mode"><el-option label="仅完整成本" value="COMPLETE"/><el-option label="包含已保存草稿" value="SAVED"/></el-select></el-form-item>
|
||||
<div class="filter-buttons"><el-button type="primary" :loading="loading" native-type="submit">汇总</el-button><el-button :disabled="loading" @click="reset">重置</el-button></div>
|
||||
</el-form>
|
||||
<div class="analysis-scope"><span>按项目经理负责的项目全额汇总,含已归档项目。<span v-if="query.basis==='END'"> 按结束时间仅统计已记录结束时间的项目。</span></span><el-tooltip content="选择项目经理后,仅汇总当前由他负责的项目。收入为项目收入(不含税),各项成本使用保存时的金额;每个项目只统计一次。"><el-button link>统计口径 ⓘ</el-button></el-tooltip></div>
|
||||
</section>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon class="analysis-notice"/>
|
||||
<template v-if="report&&!error">
|
||||
@ -22,9 +20,9 @@
|
||||
<section class="metric-grid"><article v-for="m in metrics" :key="m.key" class="metric-card" :class="m.key"><span>{{ m.label }}</span><strong :class="{'is-negative':Number(report.summary[m.key])<0}">{{ report.included?m.key==='margin'?percent(report.summary[m.key]):money(report.summary[m.key]):'—' }}<small v-if="report.included&&m.key!=='margin'">元</small></strong><footer>{{ m.caption }}</footer></article></section>
|
||||
<section class="chart-grid"><article class="analysis-panel"><div class="panel-heading"><h3>{{ report.yearly?'年度':'月度' }}收入与成本</h3><span>单位:元</span></div><div v-if="report.included" ref="trendEl" class="trend-chart" role="img" aria-label="项目收入、成本与毛利润趋势"/><el-empty v-else description="暂无可汇总的成本金额" :image-size="65"/></article><article class="analysis-panel"><div class="panel-heading"><h3>成本构成</h3><span>按金额排序</span></div><div v-if="costCategories.length" class="cost-bars"><div v-for="c in costCategories" :key="c.name" class="cost-bar"><div><span>{{ c.name }}</span><strong>{{ money(c.amount) }}</strong></div><el-progress :percentage="categoryPercent(c.amount)" :show-text="false" :stroke-width="7" color="#4c78de"/></div></div><el-empty v-else :description="report.included?'已计入项目的成本为零':'暂无可汇总的成本金额'" :image-size="65"/></article></section>
|
||||
<section class="analysis-panel details-panel" v-loading="loading">
|
||||
<div class="detail-toolbar"><el-radio-group v-model="view"><el-radio-button value="projects">项目明细</el-radio-button><el-radio-button value="managers">经理汇总</el-radio-button><el-radio-button value="categories">费用分类</el-radio-button></el-radio-group><span>{{ view==='projects'?'金额汇总覆盖所有筛选结果,不受翻页影响':'仅包含已计入金额的项目' }}</span></div>
|
||||
<el-table v-if="view==='projects'" :data="report.rows" stripe class="analysis-table" @row-dblclick="openCost">
|
||||
<el-table-column label="项目" min-width="220" fixed><template #default="{row}"><el-button link type="primary" @click="openCost(row)">{{ row.name }}</el-button><div class="project-code">{{ row.code }}</div></template></el-table-column>
|
||||
<div class="detail-toolbar"><el-radio-group v-model="view"><el-radio-button value="projects">项目明细</el-radio-button><el-radio-button value="managers">经理汇总</el-radio-button><el-radio-button value="categories">费用分类</el-radio-button></el-radio-group><span>{{ view==='projects'?'汇总涵盖全部结果;左右滚动查看明细全部列':'仅包含已计入金额的项目' }}</span></div>
|
||||
<el-table v-if="view==='projects'" :data="report.rows" stripe scrollbar-always-on class="analysis-table" @row-dblclick="openCost">
|
||||
<el-table-column label="项目" min-width="220" fixed class-name="business-operation-cell"><template #default="{row}"><el-button link type="primary" @click="openCost(row)">{{ row.name }}</el-button><div class="project-code">{{ row.code }}</div></template></el-table-column>
|
||||
<el-table-column prop="manager_name" label="项目经理" width="120"/>
|
||||
<el-table-column label="开始时间" width="125"><template #default="{row}">{{ day(row.effective_start) }}<el-tooltip v-if="row.legacyStart" content="未填开始时间,暂按创建时间"><span> *</span></el-tooltip></template></el-table-column>
|
||||
<el-table-column label="预计结束" width="120"><template #default="{row}">{{ day(row.expected_end_time) }}</template></el-table-column>
|
||||
@ -33,8 +31,8 @@
|
||||
<el-table-column label="成本(元)" min-width="140" align="right"><template #default="{row}">{{ money(row.cost) }}</template></el-table-column>
|
||||
<el-table-column label="毛利润(元)" min-width="140" align="right"><template #default="{row}"><span :class="{'is-negative':Number(row.profit)<0}">{{ money(row.profit) }}</span></template></el-table-column>
|
||||
<el-table-column label="利润率" width="110" align="right"><template #default="{row}">{{ percent(row.margin) }}</template></el-table-column>
|
||||
<el-table-column label="计入汇总" min-width="160"><template #default="{row}"><el-tag :type="row.included?'success':'info'" effect="plain">{{ row.included?(row.complete?'已计入':'草稿 · 已计入'):row.reason }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="归档状态" width="130"><template #default="{row}">{{ archiveNames[row.archive_state] }}</template></el-table-column>
|
||||
<el-table-column label="计入汇总" min-width="160" class-name="business-status-cell"><template #default="{row}"><el-tag :type="row.included?'success':'info'" effect="plain">{{ row.included?(row.complete?'已计入':'草稿 · 已计入'):row.reason }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="归档状态" width="130" class-name="business-status-cell"><template #default="{row}">{{ archiveNames[row.archive_state] }}</template></el-table-column>
|
||||
<template #empty><el-empty description="此范围没有项目,试试调整时间或人员" :image-size="70"/></template>
|
||||
</el-table>
|
||||
<el-table v-else-if="view==='managers'" :data="report.managers" stripe><el-table-column prop="name" label="项目经理" min-width="160"/><el-table-column prop="count" label="项目数" width="100"/><el-table-column v-for="m in metrics" :key="m.key" :label="m.label+(m.key==='margin'?'':'(元)')" min-width="160" align="right"><template #default="{row}">{{ m.key==='margin'?percent(row[m.key]):money(row[m.key]) }}</template></el-table-column></el-table>
|
||||
@ -81,10 +79,14 @@ onMounted(init)
|
||||
onBeforeUnmount(()=>{disposed=true;controller?.abort();detailController?.abort();Object.values(personControls).forEach(c=>c.abort());Object.values(personTimers).forEach(clearTimeout);chart?.dispose();observer?.disconnect()})
|
||||
</script>
|
||||
<style scoped>
|
||||
.cost-dashboard{padding:24px;background:#f4f6fa;min-height:calc(100vh - 90px);color:#23324b}.analysis-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;gap:16px}.analysis-eyebrow{font-size:12px;color:#8794a8;margin-bottom:7px}.analysis-heading h2{margin:0;font-size:24px;font-weight:650;letter-spacing:.3px}.analysis-heading h2 span{display:inline-block;font-size:11px;font-weight:400;background:#e8eefb;color:#5274ae;padding:4px 8px;border-radius:5px;vertical-align:middle;margin-left:10px}.analysis-filters,.analysis-panel,.metric-card{background:white;border:1px solid #e5eaf2;border-radius:12px}.analysis-filters{padding:18px 20px 12px}.analysis-filters form{display:flex;align-items:flex-end;gap:12px 16px;flex-wrap:wrap}.analysis-filters :deep(.el-form-item){width:158px;margin:0}.analysis-filters :deep(.el-form-item__label){padding-bottom:7px;font-size:12px;color:#708097;line-height:18px}.analysis-filters :deep(.date-filter){width:290px}.analysis-filters :deep(.el-date-editor),.analysis-filters :deep(.el-select){width:100%}.filter-buttons{display:flex;gap:8px;align-self:flex-end}.filter-buttons .el-button+.el-button{margin:0}.analysis-scope{display:flex;align-items:center;justify-content:space-between;color:#8794a7;font-size:12px;border-top:1px solid #f0f3f8;padding-top:10px;margin-top:14px;gap:12px}.analysis-scope .el-button{font-size:12px;color:#657fa5}.report-caption{display:flex;gap:16px;align-items:center;flex-wrap:wrap;font-size:12px;color:#7b879b;margin:20px 2px 12px}.report-caption strong{color:#445570;font-weight:500}.analysis-notice{margin:12px 0}.metric-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-bottom:18px}.metric-card{padding:20px 22px}.metric-card>span{font-size:13px;color:#7b889c}.metric-card>strong{display:block;font-size:clamp(20px,1.9vw,32px);margin:12px 0 14px;font-variant-numeric:tabular-nums;letter-spacing:-.5px;font-weight:650;overflow-wrap:anywhere}.metric-card strong small{font-size:12px;font-weight:400;color:#8794aa;margin-left:7px}.metric-card footer{font-size:11px;color:#94a0b3}.metric-card.profit{border-top:3px solid #429b88;padding-top:18px}.metric-card.income{border-top:3px solid #4779db;padding-top:18px}.is-negative{color:#d6535f!important}.chart-grid{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(300px,1fr);gap:18px;margin-bottom:18px}.analysis-panel{padding:20px}.panel-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.panel-heading h3{font-size:15px;font-weight:600;margin:0}.panel-heading>span{font-size:11px;color:#95a0b0}.trend-chart{height:290px}.cost-bars{height:270px;overflow:auto;margin-top:18px;padding-right:8px}.cost-bar{margin-bottom:17px}.cost-bar>div{display:flex;justify-content:space-between;font-size:12px;margin-bottom:7px;gap:12px}.cost-bar strong{font-weight:500;font-variant-numeric:tabular-nums}.detail-toolbar{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:18px}.detail-toolbar>span{font-size:12px;color:#93a0b2}.analysis-table :deep(.el-button){white-space:normal;text-align:left;height:auto;line-height:1.5;max-width:100%}.project-code{font-size:11px;color:#99a4b4;margin-top:2px}.details-panel :deep(.el-pagination){margin-top:18px;justify-content:flex-end;flex-wrap:wrap}.details-panel :deep(.el-table__header th){background:#f6f8fc;font-size:12px;font-weight:500;color:#75839a}.details-panel :deep(.el-table .cell){font-variant-numeric:tabular-nums}.analysis-cost-scroll{max-height:70dvh;overflow:auto}.details-panel{min-height:200px}@media(max-width:1100px){.chart-grid{grid-template-columns:1fr}.metric-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.cost-bars{height:220px}}@media(max-width:600px){.cost-dashboard{padding:12px}.analysis-heading h2{font-size:20px}.analysis-heading h2 span{display:none}.analysis-filters{padding:14px}.analysis-filters :deep(.el-form-item){width:calc(50% - 8px)}.analysis-filters :deep(.date-filter){width:100%}.analysis-scope{align-items:flex-start}.metric-grid{gap:10px}.metric-card{padding:15px}.analysis-panel{padding:14px}.detail-toolbar{align-items:flex-start;flex-direction:column}}
|
||||
.cost-dashboard{flex:1;min-height:0;min-width:0;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;box-sizing:border-box;padding:24px;background:#f4f6fa;color:#23324b}.analysis-filters,.analysis-panel,.metric-card{background:white;border:1px solid #e5eaf2;border-radius:12px}.analysis-filters{padding:18px 20px 12px}.analysis-filters form{display:flex;align-items:flex-end;gap:12px 16px;flex-wrap:wrap}.analysis-filters :deep(.el-form-item){width:158px;margin:0}.analysis-filters :deep(.el-form-item__label){padding-bottom:7px;font-size:12px;color:#708097;line-height:18px}.analysis-filters :deep(.date-filter){width:290px}.analysis-filters :deep(.el-date-editor),.analysis-filters :deep(.el-select){width:100%}.filter-buttons{display:flex;gap:8px;align-self:flex-end}.filter-buttons .el-button+.el-button{margin:0}.report-caption{display:flex;gap:16px;align-items:center;flex-wrap:wrap;font-size:12px;color:#7b879b;margin:20px 2px 12px}.report-caption strong{color:#445570;font-weight:500}.analysis-notice{margin:12px 0}.metric-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-bottom:18px}.metric-card{padding:20px 22px}.metric-card>span{font-size:13px;color:#7b889c}.metric-card>strong{display:block;font-size:clamp(20px,1.9vw,32px);margin:12px 0 14px;font-variant-numeric:tabular-nums;letter-spacing:-.5px;font-weight:650;overflow-wrap:anywhere}.metric-card strong small{font-size:12px;font-weight:400;color:#8794aa;margin-left:7px}.metric-card footer{font-size:11px;color:#94a0b3}.metric-card.profit{border-top:3px solid #429b88;padding-top:18px}.metric-card.income{border-top:3px solid #4779db;padding-top:18px}.is-negative{color:#d6535f!important}.chart-grid{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(300px,1fr);gap:18px;margin-bottom:18px}.analysis-panel{padding:20px}.panel-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.panel-heading h3{font-size:15px;font-weight:600;margin:0}.panel-heading>span{font-size:11px;color:#95a0b0}.trend-chart{height:290px}.cost-bars{height:270px;overflow:auto;margin-top:18px;padding-right:8px}.cost-bar{margin-bottom:17px}.cost-bar>div{display:flex;justify-content:space-between;font-size:12px;margin-bottom:7px;gap:12px}.cost-bar strong{font-weight:500;font-variant-numeric:tabular-nums}.detail-toolbar{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:18px}.detail-toolbar>span{font-size:12px;color:#93a0b2}.analysis-table :deep(.el-button){white-space:normal;text-align:left;height:auto;line-height:1.5;max-width:100%}.project-code{font-size:11px;color:#99a4b4;margin-top:2px}.details-panel :deep(.el-pagination){margin-top:18px;justify-content:flex-end;flex-wrap:wrap}.details-panel :deep(.el-table__header th){background:#f6f8fc;font-size:12px;font-weight:500;color:#75839a}.details-panel :deep(.el-table .cell){font-variant-numeric:tabular-nums}.analysis-cost-scroll{flex:1 1 auto;min-height:0;max-height:none;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}.details-panel{min-height:200px}@media(max-width:1100px){.chart-grid{grid-template-columns:1fr}.metric-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.cost-bars{height:220px}}@media(max-width:600px){.cost-dashboard{padding:12px}.analysis-filters{padding:14px}.analysis-filters :deep(.el-form-item){width:calc(50% - 8px)}.analysis-filters :deep(.date-filter){width:100%}.metric-grid{gap:10px}.metric-card{padding:15px}.analysis-panel{padding:14px}.detail-toolbar{align-items:flex-start;flex-direction:column}}
|
||||
</style>
|
||||
<style>
|
||||
.el-dialog.analysis-cost-detail{max-height:92dvh;display:flex;flex-direction:column;border-radius:12px}
|
||||
.analysis-cost-detail>.el-dialog__body{min-height:0;overflow:auto}
|
||||
.el-dialog.analysis-cost-detail.is-align-center{align-self:center;height:auto;max-height:min(1100px,calc(100dvh - 48px));margin:0 auto;display:flex;flex-direction:column;overflow:hidden;border-radius:12px}
|
||||
.analysis-cost-detail>.el-dialog__header,.analysis-cost-detail>.el-dialog__footer{flex:none;background:var(--el-bg-color)}
|
||||
.analysis-cost-detail>.el-dialog__header{border-bottom:1px solid var(--el-border-color-lighter)}
|
||||
.analysis-cost-detail>.el-dialog__body{display:flex;flex-direction:column;flex:1 1 auto;min-height:0;overflow:hidden}
|
||||
.analysis-cost-detail>.el-dialog__footer{padding:12px 20px;border-top:1px solid var(--el-border-color-lighter)}
|
||||
.analysis-cost-detail .el-dialog__title{display:block;overflow-wrap:anywhere}
|
||||
.analysis-cost-scroll .el-input.is-disabled .el-input__inner,.analysis-cost-scroll .el-textarea.is-disabled .el-textarea__inner{-webkit-text-fill-color:#536078;color:#536078}
|
||||
</style>
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
<template>
|
||||
<div class="app-container archive-page" :class="{'is-comparison':view==='matrix'}" v-loading="booting">
|
||||
<template v-if="metadata">
|
||||
<header class="page-heading"><div><div class="heading-title"><h2>项目资料</h2><span class="scope-badge">{{ metadata.all?'全部项目 · 管理视图':'我负责的项目' }}</span></div><p v-if="view==='list'">{{ metadata.all?'资料完整性、归档进度与项目成本,一处查阅。':'维护自己负责的资料项目。这里的项目与采购、库存及项目协作独立。' }}</p></div><div class="heading-actions"><el-button v-if="metadata.canAnalyzeCosts" @click="$router.push('/project-archive/cost-analysis')">成本汇总</el-button><el-button v-if="metadata.canMaintainCosts" :disabled="loading" @click="ratesDialog=true">人员费用标准</el-button><el-button v-if="metadata.canConfigure" :disabled="loading" @click="showCatalog">模板与字典</el-button><el-button v-if="metadata.canCreate" type="primary" :icon="Plus" @click="editProject()">新建资料项目</el-button></div></header>
|
||||
<section v-show="view==='list'" class="overview-cards" aria-label="项目归档概览" :aria-busy="loading">
|
||||
<button v-for="card in overviewCards" :key="card.key" class="overview-card" :class="[card.key,{active:activeOverview===card.key}]" :aria-pressed="activeOverview===card.key" :disabled="loading" @click="filterOverview(card.key)"><span>{{ card.label }}</span><strong>{{ overview?overview[card.key]:'—' }}<small>个项目</small></strong><span class="overview-caption">{{ card.caption }}</span></button>
|
||||
</section>
|
||||
@ -19,7 +18,12 @@
|
||||
<el-checkbox v-model="query.includeArchived" class="include-archived" @change="changeArchivedVisibility">显示归档项目</el-checkbox>
|
||||
<span class="muted project-total">{{ total }} 个项目<span v-if="total>rows.length"> · 本页 {{ rows.length }} 个</span><span v-if="selected.length"> · 已选 {{ selected.length }} 个</span></span>
|
||||
<div v-if="view==='matrix'" class="matrix-legend" aria-label="清单状态图例" title="确认齐全指维护人员确认,不等于整个项目已归档;点击图标查看资料"><span class="legend-MISSING"><b aria-hidden="true">✘</b> {{ itemNames.MISSING }}</span><span class="legend-PARTIAL"><b aria-hidden="true">◐</b> {{ itemNames.PARTIAL }}</span><span class="legend-DONE"><b aria-hidden="true">✔</b> {{ itemNames.DONE }}</span><span v-if="matrixHasNa" class="muted"><b>—</b> 不适用</span><span v-if="matrixHasAbsent" class="muted"><b>∅</b> 未包含</span><span class="muted matrix-guide">{{ comparisonItems.length }} 项 · <span class="required">✳</span> 必须项</span></div>
|
||||
<div class="export-actions"><el-button :disabled="!selected.length||exporting" :loading="exporting" @click="download(false)">导出核对表</el-button><el-dropdown trigger="click" :disabled="!selected.length||exporting" @command="v=>download(true,v==='history')"><el-button :disabled="!selected.length||exporting">下载归档包<el-icon class="el-icon--right"><ArrowDown/></el-icon></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item command="final">归档版(未定稿材料使用当前版本)</el-dropdown-item><el-dropdown-item command="history">包含全部历史版本</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div>
|
||||
<div class="toolbar-actions">
|
||||
<el-button v-if="metadata.canCreate" type="primary" :icon="Plus" :disabled="loading||busy" @click="editProject()">新建资料项目</el-button>
|
||||
<el-button v-if="metadata.canAnalyzeCosts" :disabled="loading||busy" @click="$router.push('/project-archive/cost-analysis')">成本汇总</el-button>
|
||||
<el-dropdown v-if="metadata.canMaintainCosts||metadata.canConfigure" trigger="click" :disabled="loading||busy" @command="manageProjectData"><el-button :disabled="loading||busy">管理设置<el-icon class="el-icon--right"><ArrowDown/></el-icon></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item v-if="metadata.canMaintainCosts" command="rates">人员费用标准</el-dropdown-item><el-dropdown-item v-if="metadata.canConfigure" command="catalog">模板与字典</el-dropdown-item></el-dropdown-menu></template></el-dropdown>
|
||||
<div class="export-actions"><el-button :disabled="!selected.length||exporting" :loading="exporting" @click="download(false)">导出核对表</el-button><el-dropdown trigger="click" :disabled="!selected.length||exporting" @command="v=>download(true,v==='history')"><el-button :disabled="!selected.length||exporting">下载归档包<el-icon class="el-icon--right"><ArrowDown/></el-icon></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item command="final">归档版(未定稿材料使用当前版本)</el-dropdown-item><el-dropdown-item command="history">包含全部历史版本</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="view==='list'" class="overview-scope">概览随项目、经理、类别及归档显示范围统计;点击卡片筛选列表。勾选项目可批量导出;最新维护的项目排在前面。</p>
|
||||
<el-table v-show="view==='list'" ref="listTable" :data="rows" v-loading="loading" row-key="id" scrollbar-always-on @selection-change="v=>selected=v.map(p=>p.id)" class="project-table">
|
||||
@ -162,6 +166,7 @@
|
||||
</div>
|
||||
</template>
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import {ref,computed,watch,onBeforeUnmount,nextTick} from 'vue'
|
||||
import {ElMessage,ElMessageBox} from 'element-plus'
|
||||
import {Plus,Search,ArrowDown,ArrowLeft,ArrowRight,MoreFilled,Upload} from '@element-plus/icons-vue'
|
||||
@ -230,7 +235,7 @@ function setMaterialBusy(id,value){if(value){activeMaterial.value=id;materialBus
|
||||
function canConfirm(item){return archiveItemEligibility(item,detail.value?.cost,costDirty.value).allowed}
|
||||
function canSetComplete(item){return item.item_key==='costAnalysis'?!!detail.value?.cost?.complete&&!costDirty.value:item.state==='DONE'||canConfirm(item)}
|
||||
async function setItemState(item,state){if(!detail.value?.canEdit||materialBusy.value||busy.value||detailLoading.value||!Number(item.applicable)||!Object.hasOwn(itemNames,state)||state===item.state||item.item_key==='costAnalysis'&&costDirty.value)return;if(state==='DONE'&&!canSetComplete(item)){ElMessage.warning('请先补齐附件份数或完成成本填报');return}busy.value=true;try{await api.archiveItem(detail.value.id,item.id,{version:detail.value.version,state,applicable:true,exceptionReason:item.exception_reason||'',expectedCount:item.expected_count,note:item.note||''});ElMessage.success('已标记为'+itemNames[state]);await reloadDetail()}catch{}finally{busy.value=false}}
|
||||
function time(s){return s?String(s).replace('T',' ').slice(0,16):'—'}
|
||||
function time(s){return formatDateTime(s).slice(0,16)}
|
||||
async function initialize(){booting.value=true;error.value='';try{metadata.value=(await api.archiveMetadata()).data;await load()}catch(e){error.value=e.message||'请确认模块已初始化及当前账号已获授权'}finally{booting.value=false}}
|
||||
async function load(){const g=++listGeneration;listController?.abort();listController=new AbortController();loading.value=true;selected.value=[];listTable.value?.clearSelection()
|
||||
try{const r=await api.archiveProjects({...query.value,comparison:view.value==='matrix'},listController.signal);if(disposed||g!==listGeneration)return;rows.value=r.data.rows;total.value=r.data.total;overview.value=r.data.overview||null;matrix.value=r.data.matrix||{};if(r.data.size)query.value.size=r.data.size;if(r.data.page)query.value.page=r.data.page;selected.value=[];listTable.value?.clearSelection()}catch{}finally{if(g===listGeneration)loading.value=false}}
|
||||
@ -270,6 +275,7 @@ async function changeState(action){if(busy.value||materialBusy.value||costDirty.
|
||||
busy.value=true;await api.archiveState(detail.value.id,{version:detail.value.version,action,reason});await reloadDetail()}catch{}finally{busy.value=false}}
|
||||
function transferManager(){assignment.value={managerId:null,reason:''};people.value=[];assignDialog.value=true;searchPeople()}
|
||||
async function saveAssignment(){if(busy.value||!assignment.value.managerId||!assignment.value.reason?.trim()){ElMessage.warning('请选择经理并填写交接说明');return}busy.value=true;try{await api.archiveAssign(detail.value.id,{version:detail.value.version,...assignment.value});assignDialog.value=false;await reloadDetail()}catch{}finally{busy.value=false}}
|
||||
function manageProjectData(command){if(loading.value||busy.value)return;if(command==='rates'&&metadata.value?.canMaintainCosts)ratesDialog.value=true;else if(command==='catalog'&&metadata.value?.canConfigure)showCatalog()}
|
||||
function showCatalog(){if(!metadata.value?.canConfigure||busy.value)return;catalogForm.value=JSON.parse(JSON.stringify(metadata.value.catalog));catalogForm.value.items=comparisonRows(catalogForm.value.items,catalogForm.value.formatVersion>=2);catalogCustomers.value=catalogForm.value.customerTypes.join('\n');catalogBusinesses.value=catalogForm.value.businessCategories.join('\n');catalogDialog.value=true;nextTick(()=>catalogTable.value?.setScrollTop?.(0))}
|
||||
function addCatalogItem(){if(!metadata.value?.canConfigure||busy.value||!catalogDialog.value||catalogForm.value.items.length>=100)return;catalogForm.value.items.push({key:'custom_'+uuid().replaceAll('-',''),category:catalogForm.value.items.at(-1)?.category||'',title:'',required:false});nextTick(()=>catalogTable.value?.setScrollTop?.(Number.MAX_SAFE_INTEGER))}
|
||||
function moveCatalogItem(index,delta){if(!metadata.value?.canConfigure||busy.value||!catalogDialog.value)return;const items=catalogForm.value.items,target=index+delta;if(!Number.isInteger(index)||!Number.isInteger(target)||index<0||index>=items.length||target<0||target>=items.length||index===target)return;items.splice(target,0,...items.splice(index,1))}
|
||||
@ -285,15 +291,10 @@ onBeforeUnmount(()=>{disposed=true;listGeneration++;detailGeneration++;peopleGen
|
||||
.include-archived{margin:0;flex-shrink:0;height:28px}
|
||||
.archive-page>.pagination{box-sizing:border-box;padding-right:56px}
|
||||
.archive-page.is-comparison{display:flex;flex-direction:column;min-height:0;overflow:hidden!important}
|
||||
.archive-page.is-comparison>.page-heading,.archive-page.is-comparison>.project-filters,.archive-page.is-comparison>.list-toolbar,.archive-page.is-comparison>.pagination{flex-shrink:0}
|
||||
.archive-page.is-comparison>.project-filters,.archive-page.is-comparison>.list-toolbar,.archive-page.is-comparison>.pagination{flex-shrink:0}
|
||||
.is-comparison>.matrix-view{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden}
|
||||
.is-comparison .matrix-legend{flex-shrink:0}
|
||||
.is-comparison .comparison-table{flex:1;min-height:0}
|
||||
.page-heading{display:flex;justify-content:space-between;gap:16px;align-items:center;margin:0 0 12px}
|
||||
.page-heading h2{margin:0;font-size:21px;font-weight:600;color:var(--el-text-color-primary)}
|
||||
.page-heading p{margin:8px 0 0;font-size:13px;line-height:1.7;color:var(--el-text-color-secondary)}
|
||||
.heading-title{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.scope-badge{padding:3px 9px;border-radius:5px;font-size:12px;color:var(--el-color-primary);background:var(--el-color-primary-light-9)}
|
||||
.overview-cards{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin-bottom:20px}
|
||||
.overview-card{display:flex;flex-direction:column;align-items:flex-start;gap:6px;min-width:0;padding:16px 18px;border:1px solid var(--el-border-color-lighter);border-radius:8px;background:var(--el-bg-color);font:inherit;text-align:left;color:var(--el-text-color-regular);cursor:pointer;transition:border-color .15s,background-color .15s}
|
||||
.overview-card>span:first-child{font-size:13px;font-weight:500}
|
||||
@ -306,8 +307,10 @@ onBeforeUnmount(()=>{disposed=true;listGeneration++;detailGeneration++;peopleGen
|
||||
.overview-card:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:2px}
|
||||
.overview-card:disabled{cursor:wait}
|
||||
.overview-scope{margin:0 0 12px;color:var(--el-text-color-secondary);font-size:12px;line-height:1.6}
|
||||
.heading-actions,.export-actions{display:flex;align-items:center;gap:10px;flex-shrink:0}
|
||||
.heading-actions .el-button,.export-actions .el-button{margin:0}
|
||||
.toolbar-actions,.export-actions{display:flex;align-items:center;gap:8px;flex-shrink:0}
|
||||
.toolbar-actions{margin-left:auto;flex-wrap:wrap;max-width:100%}
|
||||
.export-actions{border-left:1px solid var(--el-border-color-lighter);padding-left:12px;margin-left:4px}
|
||||
.toolbar-actions .el-button,.export-actions .el-button{margin:0}
|
||||
.project-filters{display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;padding:10px 12px;background:var(--el-fill-color-light);border-radius:8px;margin-bottom:10px}
|
||||
.project-filters .el-form-item{margin:0;align-items:center}
|
||||
.project-filters :deep(.el-form-item__label){white-space:nowrap}
|
||||
@ -315,7 +318,7 @@ onBeforeUnmount(()=>{disposed=true;listGeneration++;detailGeneration++;peopleGen
|
||||
.project-filters :deep(.el-form-item__content>.el-select){width:150px!important}
|
||||
.project-filters .manager-filter :deep(.el-form-item__content>.el-select){width:200px!important}
|
||||
.filter-actions :deep(.el-form-item__content){flex-wrap:nowrap}
|
||||
.list-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;margin-bottom:8px}.export-actions{margin-left:auto}.project-total{white-space:nowrap}
|
||||
.list-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin-bottom:8px}.project-total{white-space:nowrap}
|
||||
.muted{color:var(--el-text-color-secondary);font-size:12px;line-height:1.7}
|
||||
.project-name{font-size:14px;height:auto;white-space:normal;text-align:left;line-height:1.6}
|
||||
.project-table :deep(th .cell){white-space:nowrap}
|
||||
@ -437,8 +440,7 @@ onBeforeUnmount(()=>{disposed=true;listGeneration++;detailGeneration++;peopleGen
|
||||
@media(max-width:760px){
|
||||
.overview-cards{grid-template-columns:repeat(3,minmax(0,1fr))}.overview-card{gap:4px;padding:12px}.overview-card strong{font-size:23px}.overview-card small{display:none}
|
||||
.project-navigation{display:none}
|
||||
.page-heading{align-items:flex-start;flex-direction:column;gap:14px}
|
||||
.list-toolbar{flex-wrap:wrap;gap:12px}.export-actions{margin-left:0}
|
||||
.list-toolbar{flex-wrap:wrap;gap:12px}.toolbar-actions{width:100%;margin-left:0}.export-actions{margin-left:0;padding-left:0;border-left:0}
|
||||
.project-filters{padding:12px;gap:12px}.project-filters .el-input{width:190px}
|
||||
.workbench-heading{gap:12px}.workbench-title h3{font-size:16px}
|
||||
.attachment-workspace{grid-template-columns:1fr}.attachment-nav{display:none}
|
||||
|
||||
@ -30,7 +30,7 @@
|
||||
<div v-if="!loading && list.length === 0" class="empty-tip">暂无采购申请</div>
|
||||
<article v-for="item in list" :key="'purchase-' + item.id" class="mobile-card purchase-card">
|
||||
<el-checkbox v-if="canSelectArrival(item)" :model-value="selectedIds.includes(item.id)" :disabled="loading" @change="value=>selectedIds=value?[...new Set([...selectedIds,item.id])]:selectedIds.filter(id=>id!==item.id)">选择本条采购</el-checkbox>
|
||||
<el-tag v-if="item.historical" size="small">历史已完成 · {{ item.originalDate }}</el-tag>
|
||||
<el-tag v-if="item.historical" size="small">历史已完成 · {{ formatDateTime(item.originalDate) }}</el-tag>
|
||||
<div class="card-head">
|
||||
<div>
|
||||
<div class="card-title">{{ item.materialName || '-' }}</div>
|
||||
@ -48,9 +48,9 @@
|
||||
<span v-if="Number(item.pendingArrivalQuantity || 0) > 0" class="pending">待验收 {{ item.pendingArrivalQuantity }}</span>
|
||||
</div>
|
||||
<div class="record-line">
|
||||
<span>采购金额:¥{{ money(item.estimatedAmount) }}</span>
|
||||
<span>实际金额:{{ item.actualAmount==null?'—':'¥'+money(item.actualAmount) }}</span><span v-if="canManage">报价金额:¥{{ money(item.estimatedAmount) }}</span>
|
||||
<span v-if="item.purchaseBatchNo">批次:{{ [item.purchaseBatchNo, item.purchaseBatchName].filter(Boolean).join(' / ') }}</span>
|
||||
<span>价格{{ item.priceLocked ? '已锁定' : '未锁定' }} · 计费 ¥{{ money(item.lockedAmount) }}</span>
|
||||
<span v-if="canManage">价格{{ item.priceLocked ? '已锁定' : '未锁定' }} · 计费 ¥{{ money(item.lockedAmount) }}</span>
|
||||
</div>
|
||||
<div class="card-actions purchase-actions">
|
||||
<el-button v-if="(canOperate(item) && Number(item.remainingQuantity)>0) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" size="small" @click="$refs.cancelPurchase.open(item)" >取消未到货</el-button>
|
||||
@ -108,7 +108,7 @@
|
||||
<el-form-item label="物品类别" prop="category"><el-input v-model="form.category" readonly placeholder="由物品档案带出,缺少时请补全档案" /></el-form-item>
|
||||
<el-form-item label="数量" prop="quantity"><el-input-number v-model="form.quantity" :min="0.0001" :precision="4" :controls="false" /></el-form-item>
|
||||
<el-form-item label="单位"><el-input v-model="form.unit" readonly placeholder="由物品档案带出" /></el-form-item>
|
||||
<el-form-item label="最终单价" prop="finalUnitPrice"><el-input-number v-model="form.finalUnitPrice" :min="0" :precision="6" placeholder="可暂不填写" :controls="false" :disabled="Number(form.receivedQuantity||0)>0" /><div v-if="Number(form.receivedQuantity||0)>0" class="meta-line">已有确认入库,先撤销到待入库后才能修改价格。</div></el-form-item>
|
||||
<el-form-item v-if="canManage" label="报价单价" prop="finalUnitPrice"><el-input-number v-model="form.finalUnitPrice" :min="0" :precision="6" placeholder="可暂不填写" :controls="false" :disabled="Number(form.receivedQuantity||0)>0" /><div v-if="Number(form.receivedQuantity||0)>0" class="meta-line">已有确认入库,先撤销到待入库后才能修改价格。</div></el-form-item>
|
||||
<div class="purchase-total-preview"><span>采购总额</span><strong>¥ {{ money(plannedAmount) }}</strong></div>
|
||||
|
||||
<el-collapse v-model="formPanels" class="purchase-extra-fields">
|
||||
@ -147,14 +147,16 @@
|
||||
<el-form-item label="本次到货" prop="arrivalQuantity"><el-input-number v-model="arrivalForm.arrivalQuantity" :min="0.0001" :max="Number(arrivalRequest.remainingQuantity || 0)" :precision="4" :controls="false" /></el-form-item>
|
||||
<el-form-item label="到货日期" prop="arrivalDate"><el-date-picker v-model="arrivalForm.arrivalDate" type="date" value-format="YYYY-MM-DD" /></el-form-item>
|
||||
<el-form-item label="备注"><el-input v-model="arrivalForm.remark" /></el-form-item>
|
||||
<el-form-item label="到货照片"><arrival-photos v-model="arrivalPhotos" :request-id="arrivalRequest.id" :disabled="arrivalBusy" @pending="arrivalPhotosPending=$event"/></el-form-item>
|
||||
<el-button class="full-button" type="primary" icon="el-icon-plus" :loading="arrivalSubmitting" :disabled="!!arrivalActionKey" @click="submitArrival">登记到货</el-button>
|
||||
</el-form>
|
||||
<div v-loading="arrivalLoading" class="mobile-arrival-list">
|
||||
<div v-if="!arrivalLoading && arrivalList.length === 0" class="empty-tip">暂无到货记录</div>
|
||||
<article v-for="item in arrivalList" :key="'arrival-' + item.id" class="arrival-card">
|
||||
<div class="card-head"><div><div class="card-title">{{ item.arrivalNo }}</div><div class="card-subtitle">{{ item.arrivalDate }} · {{ item.arrivalQuantity }} {{ arrivalRequest && arrivalRequest.unit || '' }}</div></div><el-tag size="small" :type="acceptanceType(item.acceptanceStatus)">{{ acceptanceLabel(item.acceptanceStatus) }}</el-tag></div>
|
||||
<div class="record-line"><span>单价:¥{{ money(item.actualUnitPrice) }}</span><span>金额:¥{{ money(item.actualAmount) }}</span></div>
|
||||
<div class="card-head"><div><div class="card-title">{{ item.arrivalNo }}</div><div class="card-subtitle">{{ formatDateTime(item.arrivalDate) }} · {{ item.arrivalQuantity }} {{ arrivalRequest && arrivalRequest.unit || '' }}</div></div><el-tag size="small" :type="acceptanceType(item.acceptanceStatus)">{{ acceptanceLabel(item.acceptanceStatus) }}</el-tag></div>
|
||||
<div v-if="canManage" class="record-line"><span>单价:¥{{ money(item.actualUnitPrice) }}</span><span>金额:¥{{ money(item.actualAmount) }}</span></div>
|
||||
<div v-if="item.remark || item.acceptanceRemark || item.revokeRemark" class="meta-line">{{ item.acceptanceRemark || item.revokeRemark || item.remark }}</div>
|
||||
<arrival-photos :model-value="item.photos||[]" readonly compact/>
|
||||
<div v-if="arrivalRequest && canOperate(arrivalRequest)" class="card-actions purchase-actions">
|
||||
<template v-if="Number(item.acceptanceStatus) === 0">
|
||||
<el-button type="success" size="small" icon="el-icon-check" :loading="arrivalActionKey === 'accept:' + item.id" :disabled="arrivalBusy" @click="acceptArrival(item, 1)" v-if="$can(['warehouse:purchase:edit', 'warehouse:purchase:manage'])">验收通过</el-button>
|
||||
@ -186,6 +188,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import { listPurchase, getPurchase, listPurchaseOperations, addPurchase, updatePurchase, updatePurchaseStatus, delPurchase, lockPurchasePrices, listPurchaseArrival, addPurchaseArrival, acceptPurchaseArrival, revokePurchaseArrival, delPurchaseArrival } from '@/api/warehouse/purchase'
|
||||
import { optionselectProduct } from '@/api/warehouse/product'
|
||||
@ -197,7 +200,7 @@ const DRAFT_MAX_AGE = 7 * 24 * 60 * 60 * 1000
|
||||
|
||||
export default {
|
||||
name: 'MobilePurchase',
|
||||
components: { PurchasePurpose, SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')), CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')), BatchArrival: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')), AcceptanceException: defineAsyncComponent(()=>import('@/components/ReceiptDialog/AcceptanceException')), PurchaseReturn: defineAsyncComponent(()=>import('@/components/ReceiptDialog/PurchaseReturn')) },
|
||||
components: { ArrivalPhotos:defineAsyncComponent(()=>import('@/components/ArrivalPhotos')), PurchasePurpose, SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')), CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')), BatchArrival: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')), AcceptanceException: defineAsyncComponent(()=>import('@/components/ReceiptDialog/AcceptanceException')), PurchaseReturn: defineAsyncComponent(()=>import('@/components/ReceiptDialog/PurchaseReturn')) },
|
||||
props: {
|
||||
userId: [String, Number],
|
||||
userName: { type: String, default: '' },
|
||||
@ -232,7 +235,7 @@ export default {
|
||||
draftRestored: false, draftSavedAt: '',
|
||||
statusOpen: false, statusSubmitting: false, statusForm: {},
|
||||
statusRules: { purchaseStatus: [{ required: true, message: '请选择采购状态', trigger: 'change' }] },
|
||||
arrivalOpen: false, arrivalLoading: false, arrivalRequestId: 0, arrivalSubmitting: false, arrivalActionKey: '', arrivalRequest: null, arrivalList: [], operationList: [], arrivalForm: {},
|
||||
arrivalOpen: false, arrivalLoading: false, arrivalRequestId: 0, arrivalSubmitting: false, arrivalActionKey: '', arrivalRequest: null, arrivalList: [], operationList: [], arrivalForm: {}, arrivalPhotos: [], arrivalPhotosPending: false,
|
||||
arrivalRules: {
|
||||
arrivalQuantity: [{ required: true, message: '请输入到货数量', trigger: 'change' }],
|
||||
arrivalDate: [{ required: true, message: '请选择到货日期', trigger: 'change' }]
|
||||
@ -260,7 +263,7 @@ export default {
|
||||
categoryOptions().then(res => { this.allExpenseCategories = res.data || [] })
|
||||
if (!this.entryCommand || !this.entryCommand.serial) this.load(true)
|
||||
},
|
||||
methods: {
|
||||
methods: {formatDateTime,
|
||||
handleEntry(command) {
|
||||
if (!command || !command.serial || command.serial === this.handledCommand) return
|
||||
this.handledCommand = command.serial
|
||||
@ -305,7 +308,7 @@ export default {
|
||||
canOperate(row) { return this.hasPurchaseWrite() && (!row || (!row.historical && Number(row.purchaseStatus) !== 5)) },
|
||||
canRegisterArrival(row) { return this.canOperate(row) && !!row.priceLocked && Number(row.remainingQuantity || 0) > 0 },
|
||||
canSelectArrival(row) { return this.canRegisterArrival(row) || (this.canOperate(row) && Number(row.pendingArrivalQuantity || 0) > 0) },
|
||||
canLockPurchase(row) { return this.canOperate(row) && !row.priceLocked && row.finalUnitPrice !== null && row.finalUnitPrice !== undefined && row.finalUnitPrice !== '' },
|
||||
canLockPurchase(row) { return this.canManage && this.canOperate(row) && !row.priceLocked && row.finalUnitPrice !== null && row.finalUnitPrice !== undefined && row.finalUnitPrice !== '' },
|
||||
canDeletePurchase(row) { return this.canOperate(row) && Number(row.acceptedQuantity || 0) <= 0 && Number(row.pendingArrivalQuantity || 0) <= 0 },
|
||||
primaryAction(row) { if (!this.canOperate(row)) return '查看到货明细'; if (Number(row.pendingArrivalQuantity || 0) > 0) return '验收到货'; if (Number(row.remainingQuantity || 0) > 0) return '登记到货'; return '查看到货明细' },
|
||||
projectLabel(project) { return project.projectName + '(' + project.projectCode + ')' },
|
||||
@ -366,8 +369,8 @@ export default {
|
||||
openArrival(row) { if(this.arrivalBusy)return; this.arrivalOpen = true; this.arrivalRequest = { ...row }; this.resetArrivalForm(); return this.refreshArrival(row.id) },
|
||||
handleArrivalClosed() { this.arrivalRequestId += 1; this.arrivalLoading = false; this.arrivalRequest = null; this.arrivalList = []; this.operationList = [] },
|
||||
refreshArrival(requestId) { const refreshId = ++this.arrivalRequestId; this.arrivalLoading = true; return Promise.all([getPurchase(requestId), listPurchaseArrival(requestId), listPurchaseOperations(requestId)]).then(([requestRes, arrivalRes, operationRes]) => { if (refreshId !== this.arrivalRequestId) return; this.arrivalRequest = requestRes.data; this.arrivalList = arrivalRes.data || []; this.operationList = operationRes.data || [] }).catch(() => { /* Shared request handler reports the failure; keep the arrival draft for retry. */ }).finally(() => { if (refreshId === this.arrivalRequestId) this.arrivalLoading = false }) },
|
||||
resetArrivalForm() { this.arrivalForm = { purchaseRequestId: this.arrivalRequest && this.arrivalRequest.id, requestKey: `mobile-arrival-${this.arrivalRequest && this.arrivalRequest.id}-${Date.now()}-${Math.random().toString(36).slice(2)}`, arrivalQuantity: undefined, actualUnitPrice: this.arrivalRequest && this.arrivalRequest.finalUnitPrice, arrivalDate: this.parseTime(new Date(), '{y}-{m}-{d}'), remark: undefined }; this.$nextTick(() => this.$refs.arrivalForm && this.$refs.arrivalForm.clearValidate()) },
|
||||
submitArrival() { if (this.arrivalBusy || this.arrivalLoading || !this.arrivalRequest || !this.$refs.arrivalForm) return; this.arrivalForm.purchaseRequestId = this.arrivalRequest.id; this.$refs.arrivalForm.validate(valid => { if (!valid || this.arrivalBusy) return; const data={...this.arrivalForm}; this.arrivalSubmitting = true; addPurchaseArrival(data).then(() => { this.$modal.msgSuccess('到货已登记,等待验收'); this.resetArrivalForm(); this.refreshArrival(data.purchaseRequestId); this.refresh() }).catch(() => { /* Keep this logical arrival's request key, quantity, date and remark on failure. */ }).finally(() => { this.arrivalSubmitting = false }) }) },
|
||||
resetArrivalForm() { this.arrivalPhotos=[];this.arrivalPhotosPending=false;this.arrivalForm = { purchaseRequestId: this.arrivalRequest && this.arrivalRequest.id, requestKey: `mobile-arrival-${this.arrivalRequest && this.arrivalRequest.id}-${Date.now()}-${Math.random().toString(36).slice(2)}`, arrivalQuantity: undefined, actualUnitPrice: this.arrivalRequest && this.arrivalRequest.finalUnitPrice, arrivalDate: this.parseTime(new Date(), '{y}-{m}-{d}'), remark: undefined }; this.$nextTick(() => this.$refs.arrivalForm && this.$refs.arrivalForm.clearValidate()) },
|
||||
submitArrival() { if (this.arrivalBusy || this.arrivalLoading || !this.arrivalRequest || !this.$refs.arrivalForm) return; this.arrivalForm.purchaseRequestId = this.arrivalRequest.id; this.$refs.arrivalForm.validate(valid => { if (!valid || this.arrivalBusy) return; if(this.arrivalPhotosPending)return this.$modal.msgWarning('有照片尚未上传完成,请重试或移除后继续'); const data={...this.arrivalForm,photoIds:this.arrivalPhotos.map(p=>p.id)}; this.arrivalSubmitting = true; addPurchaseArrival(data).then(() => { this.$modal.msgSuccess('到货已登记,等待验收'); this.resetArrivalForm(); this.refreshArrival(data.purchaseRequestId); this.refresh() }).catch(() => { /* Keep this logical arrival's request key, quantity, date and remark on failure. */ }).finally(() => { this.arrivalSubmitting = false }) }) },
|
||||
acceptArrival(row, status) { if (this.arrivalBusy) return; const actionKey = (status === 1 ? 'accept:' : 'reject:') + row.id; this.arrivalActionKey = actionKey; const request = status === 1 ? this.$modal.confirm('确认数量、单价和物料无误并通过验收?').then(() => acceptPurchaseArrival(row.id, { acceptanceStatus: 1 })) : this.$prompt('请输入拒收原因', '拒收到货', { inputValidator: value => !!(value && value.trim()) || '拒收原因不能为空' }).then(({ value }) => acceptPurchaseArrival(row.id, { acceptanceStatus: 2, acceptanceRemark: value })); request.then(() => { this.$modal.msgSuccess(status === 1 ? '验收通过,已生成待入库记录' : '已拒收,本次数量可以重新登记'); this.refreshArrival(this.arrivalRequest.id); this.refresh() }).catch(() => {}).finally(() => { if (this.arrivalActionKey === actionKey) this.arrivalActionKey = '' }) },
|
||||
deleteArrival(row) { if (this.arrivalBusy) return; const actionKey = 'delete:' + row.id; this.arrivalActionKey = actionKey; this.$modal.confirm('确认删除待验收到货记录“' + row.arrivalNo + '”?').then(() => delPurchaseArrival(row.id)).then(() => { this.$modal.msgSuccess('到货记录已删除'); this.refreshArrival(this.arrivalRequest.id); this.refresh() }).catch(() => {}).finally(() => { if (this.arrivalActionKey === actionKey) this.arrivalActionKey = '' }) },
|
||||
revokeArrival(row) { if (this.arrivalBusy) return; const actionKey = 'revoke:' + row.id; this.arrivalActionKey = actionKey; const action = Number(row.acceptanceStatus) === 1 ? '验收通过' : '拒收'; this.$prompt('请输入撤销原因', '撤销' + action, { inputValidator: value => !!(value && value.trim()) || '撤销原因不能为空' }).then(({ value }) => revokePurchaseArrival(row.id, { revokeRemark: value })).then(() => { this.$modal.msgSuccess('验收已撤销'); this.refreshArrival(this.arrivalRequest.id); this.refresh() }).catch(() => {}).finally(() => { if (this.arrivalActionKey === actionKey) this.arrivalActionKey = '' }) },
|
||||
|
||||
@ -21,15 +21,15 @@
|
||||
</el-row>
|
||||
<el-row class="detail-row">
|
||||
<el-col :span="12">
|
||||
<div class="detail-item"><span class="detail-label">开始时间</span><span class="detail-value">{{ form.startTime }}</span></div>
|
||||
<div class="detail-item"><span class="detail-label">开始时间</span><span class="detail-value">{{ formatDateTime(form.startTime) }}</span></div>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<div class="detail-item"><span class="detail-label">结束时间</span><span class="detail-value">{{ form.endTime }}</span></div>
|
||||
<div class="detail-item"><span class="detail-label">结束时间</span><span class="detail-value">{{ formatDateTime(form.endTime) }}</span></div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row class="detail-row">
|
||||
<el-col :span="12">
|
||||
<div class="detail-item"><span class="detail-label">记录时间</span><span class="detail-value">{{ form.createTime }}</span></div>
|
||||
<div class="detail-item"><span class="detail-label">记录时间</span><span class="detail-value">{{ formatDateTime(form.createTime) }}</span></div>
|
||||
</el-col>
|
||||
<el-col :span="12" v-if="form.status == 0 && form.startTime && form.endTime">
|
||||
<div class="detail-item"><span class="detail-label">执行耗时</span><span class="detail-value">{{ costTime }} 毫秒</span></div>
|
||||
@ -157,7 +157,7 @@
|
||||
<div class="detail-item"><span class="detail-label">创建人</span><span class="detail-value">{{ form.createBy || '-' }}</span></div>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<div class="detail-item"><span class="detail-label">创建时间</span><span class="detail-value">{{ form.createTime }}</span></div>
|
||||
<div class="detail-item"><span class="detail-label">创建时间</span><span class="detail-value">{{ formatDateTime(form.createTime) }}</span></div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row class="detail-row">
|
||||
@ -165,7 +165,7 @@
|
||||
<div class="detail-item"><span class="detail-label">更新人</span><span class="detail-value">{{ form.updateBy || '-' }}</span></div>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<div class="detail-item"><span class="detail-label">更新时间</span><span class="detail-value">{{ form.updateTime || '-' }}</span></div>
|
||||
<div class="detail-item"><span class="detail-label">更新时间</span><span class="detail-value">{{ formatDateTime(form.updateTime) }}</span></div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row class="detail-row" v-if="form.remark">
|
||||
@ -185,6 +185,7 @@
|
||||
</template>
|
||||
|
||||
<script setup name="JobDetail">
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
const props = defineProps({
|
||||
visible: { type: Boolean, default: false },
|
||||
row: { type: Object, default: () => ({}) },
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
</el-row>
|
||||
<el-row class="detail-row">
|
||||
<el-col :span="12">
|
||||
<div class="detail-item"><span class="detail-label">操作时间</span><span class="detail-value">{{ form.operTime }}</span></div>
|
||||
<div class="detail-item"><span class="detail-label">操作时间</span><span class="detail-value">{{ formatDateTime(form.operTime) }}</span></div>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<div class="detail-item">
|
||||
@ -112,6 +112,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
const props = defineProps({
|
||||
visible: { type: Boolean, default: false },
|
||||
row: { type: Object, default: () => ({}) }
|
||||
|
||||
@ -113,7 +113,7 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="el-table__cell is-leaf"><div class="cell">启动时间</div></td>
|
||||
<td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.startTime }}</div></td>
|
||||
<td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ formatDateTime(server.jvm.startTime) }}</div></td>
|
||||
<td class="el-table__cell is-leaf"><div class="cell">运行时长</div></td>
|
||||
<td class="el-table__cell is-leaf"><div class="cell" v-if="server.jvm">{{ server.jvm.runTime }}</div></td>
|
||||
</tr>
|
||||
@ -171,6 +171,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { getServer } from '@/api/monitor/server'
|
||||
import { runLatest, invalidateQuery, queryError } from '@/utils/query-session'
|
||||
|
||||
|
||||
@ -32,6 +32,7 @@
|
||||
</div>
|
||||
</template>
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import {computed,ref} from 'vue'
|
||||
import {useElementSize} from '@vueuse/core'
|
||||
import {Download,Plus,Search,Paperclip,Document,ArrowDown} from '@element-plus/icons-vue'
|
||||
@ -43,7 +44,7 @@ const emit=defineEmits(['search','reset','load','create','export','open','projec
|
||||
const container=ref(null),{width}=useElementSize(container)
|
||||
const hasFilters=computed(()=>!!query.value.kind||!!query.value.keyword?.trim()||(!props.projectId&&!!query.value.projectId))
|
||||
function chooseKind(kind){if(query.value.kind===kind)return;query.value.kind=kind;emit('search')}
|
||||
function displayTime(value){return value?String(value).replace('T',' ').slice(0,16):'—'}
|
||||
function displayTime(value){return formatDateTime(value).slice(0,16)}
|
||||
</script>
|
||||
<style scoped>
|
||||
.achievement-ledger{min-width:0;container:achievement-ledger / inline-size}.ledger-heading,.ledger-title,.ledger-actions{display:flex;align-items:center;gap:12px}.ledger-heading{justify-content:space-between;flex-wrap:wrap;margin-bottom:18px}.ledger-title h2{margin:0;font-size:20px;font-weight:600;color:var(--el-text-color-primary)}.result-count{font-size:13px;color:var(--el-text-color-secondary);white-space:nowrap}.ledger-actions{flex-wrap:wrap;gap:10px}.ledger-actions .el-button{margin:0}.ledger-actions :deep(.business-page-header){margin:0;padding:0;position:static;min-height:0;flex:0 0 auto}.ledger-panel{border:1px solid var(--el-border-color-lighter);border-radius:10px;background:var(--el-bg-color);overflow:hidden}.kind-tabs{display:flex;gap:24px;align-items:center;padding:0 20px;border-bottom:1px solid var(--el-border-color-lighter);overflow-x:auto}.kind-tabs button{position:relative;border:0;background:transparent;color:var(--el-text-color-secondary);padding:16px 2px;white-space:nowrap;font:inherit;font-size:14px;cursor:pointer}.kind-tabs button.active{color:var(--el-color-primary);font-weight:600}.kind-tabs button.active:after{content:'';position:absolute;bottom:0;left:0;right:0;height:3px;border-radius:3px 3px 0 0;background:var(--el-color-primary)}.kind-tabs button:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:-3px}.ledger-filters{display:flex;align-items:center;flex-wrap:wrap;gap:12px 18px;padding:18px 20px}.ledger-filters .el-form-item{margin:0}.ledger-filters :deep(.el-form-item__label){white-space:nowrap}.ledger-filters .el-select{width:220px}.keyword-filter{flex:1 1 240px;max-width:420px}.keyword-filter :deep(.el-form-item__content){min-width:140px}.filter-actions{display:flex;gap:8px}.filter-actions .el-button{margin:0}.achievement-table{width:100%}.achievement-table :deep(th.el-table__cell){background:var(--el-fill-color-light);font-weight:500}.achievement-table :deep(td.el-table__cell){padding-top:15px;padding-bottom:15px}.achievement-identity{display:flex;flex-direction:column;align-items:flex-start;gap:5px}.achievement-name{font-weight:600;font-size:14px;text-align:left;line-height:1.6;white-space:normal;overflow-wrap:anywhere}.secondary-line{display:block;font-size:12px;line-height:1.6;color:var(--el-text-color-secondary);margin-top:5px}.reference-number{color:var(--el-text-color-secondary);font-size:12px;overflow-wrap:anywhere}.team-owner{display:flex;align-items:baseline;gap:8px;color:var(--el-text-color-primary)}.team-owner>span{color:var(--el-text-color-secondary);font-size:12px}.update-time{color:var(--el-text-color-secondary);font-size:12px;white-space:nowrap}.ledger-empty{padding:44px 16px 48px;text-align:center;line-height:1.6}.empty-symbol{display:grid;place-items:center;width:64px;height:64px;border-radius:18px;margin:0 auto 16px;background:var(--el-color-primary-light-9);color:var(--el-color-primary)}.ledger-empty h3{font-size:15px;font-weight:500;color:var(--el-text-color-primary);margin:0 0 7px}.ledger-empty p{font-size:13px;color:var(--el-text-color-secondary);margin:0 0 18px}.ledger-pagination{padding:0 20px 16px}.ledger-pagination :deep(.pagination-container){margin-top:14px}.ledger-panel>.el-alert{margin:0 20px 14px;width:auto}
|
||||
|
||||
@ -127,6 +127,7 @@
|
||||
<script>
|
||||
import { runLatest, queryError } from '@/utils/query-session'
|
||||
import { projectCodeError } from '@/utils/project-code'
|
||||
import { canManageProject } from '@/utils/project-access'
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import { listProject, getProject, addProject, updateProject, delProject, listProjectBudget, saveProjectBudget, listFundLedger, listCategory, categoryOptions, addCategory, updateCategory, delCategory } from '@/api/project/project'
|
||||
import { projectOverview } from '@/api/production/tasks'
|
||||
@ -154,7 +155,7 @@ export default {
|
||||
},
|
||||
created() { this.getList() },
|
||||
methods: {
|
||||
isManager(row){return row&&String(row.managerId)===String(this.currentUser.id)},
|
||||
isManager(row){return canManageProject(row,this.currentUser.id)},
|
||||
canSelectProject(row) { return row && row.projectCode !== 'LEGACY' && this.isManager(row) },
|
||||
getList() {
|
||||
const query={...this.queryParams}
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
<el-alert title="从左侧节点库拖入阶段并手工连线确定执行顺序;前置阶段全部工作项完成或关闭后,下游工作项才可开始。含工作项的阶段须先调整归属再删除。" type="info" :closable="false" />
|
||||
<el-button v-if="iterationId && view" size="small" class="structure-button" @click="structureOpen = true">调整阶段层级与连线</el-button>
|
||||
<el-table :data="stages" size="small" table-layout="fixed" max-height="min(55vh, 520px)" class="stage-table">
|
||||
<el-table-column label="阶段" min-width="245"><template #default="{ row }"><div class="stage-name"><el-tag size="small" type="info">{{ stageNodeTypeLabel(row) }}</el-tag><span :title="row.stagePath || row.name">{{ row.stagePath || row.name }}</span></div></template></el-table-column>
|
||||
<el-table-column label="阶段" min-width="245" class-name="business-status-cell"><template #default="{ row }"><div class="stage-name"><el-tag size="small" type="info">{{ stageNodeTypeLabel(row) }}</el-tag><span :title="row.stagePath || row.name">{{ row.stagePath || row.name }}</span></div></template></el-table-column>
|
||||
<el-table-column label="负责人" width="100" show-overflow-tooltip><template #default="{ row }">{{ row.ownerName || '未分配' }}</template></el-table-column>
|
||||
<el-table-column label="工作项" width="70"><template #default="{ row }">{{ row.counts.total }}</template></el-table-column><el-table-column label="完成" width="80"><template #default="{ row }">{{ row.complete ? '已完成' : '未完成' }}</template></el-table-column>
|
||||
<el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<el-dialog :close-on-click-modal="false" :model-value="visible" title="调整未执行阶段结构" width="min(900px, 96%)" append-to-body @close="emit('close')">
|
||||
<el-alert title="先指定父级,再明确编辑最终保留的全部连线。不会自动猜测跨层连线;已执行阶段、执行过的阶段组结构受保护。预览成功后才能确认。" type="info" :closable="false" />
|
||||
<el-table :data="view.stages" size="small" max-height="280"><el-table-column label="阶段" min-width="200"><template #default="{ row }">{{ row.stagePath || row.name }}</template></el-table-column><el-table-column label="类型" width="90"><template #default="{ row }">{{ row.stageKind === 'GROUP' ? '阶段组' : '工作阶段' }}</template></el-table-column><el-table-column label="父阶段组" min-width="220"><template #default="{ row }"><el-select v-model="parents[row.id]" size="small" clearable placeholder="根画布" :disabled="busy || row.stageKind === 'GROUP' || !row.canEditStructure"><el-option v-for="group in groups" :key="group.id" :value="group.id" :label="group.name" /></el-select></template></el-table-column></el-table>
|
||||
<el-table :data="view.stages" size="small" max-height="280"><el-table-column label="阶段" min-width="200"><template #default="{ row }">{{ row.stagePath || row.name }}</template></el-table-column><el-table-column label="类型" width="90"><template #default="{ row }">{{ row.stageKind === 'GROUP' ? '阶段组' : '工作阶段' }}</template></el-table-column><el-table-column label="父阶段组" min-width="220" class-name="business-control-cell"><template #default="{ row }"><el-select v-model="parents[row.id]" size="small" clearable placeholder="根画布" :disabled="busy || row.stageKind === 'GROUP' || !row.canEditStructure"><el-option v-for="group in groups" :key="group.id" :value="group.id" :label="group.name" /></el-select></template></el-table-column></el-table>
|
||||
<h4>最终执行连线</h4>
|
||||
<div v-for="(edge, index) in links" :key="index" class="edge-row"><el-select v-model="edge.predecessorStageId" :disabled="busy" size="small" filterable><el-option v-for="stage in view.stages" :key="stage.id" :value="stage.id" :label="stage.name" /></el-select><span>→</span><el-select v-model="edge.successorStageId" :disabled="busy" size="small" filterable><el-option v-for="stage in view.stages" :key="stage.id" :value="stage.id" :label="stage.name" /></el-select><span v-if="scope(edge.predecessorStageId) !== scope(edge.successorStageId)" class="invalid">跨画布,请调整</span><el-button size="small" link type="danger" :disabled="busy" @click="links.splice(index, 1)">移除</el-button></div>
|
||||
<el-button size="small" :disabled="busy || view.stages.length < 2" @click="addEdge">增加连线</el-button>
|
||||
|
||||
@ -26,7 +26,7 @@
|
||||
<el-alert v-if="failure" :title="failure" type="error" :closable="false" class="history-message" />
|
||||
<el-table v-loading="loading" :data="revisions" size="small" class="history-table"><el-table-column label="版本" width="70"><template #default="{ row }">v{{ row.revision_no }}</template></el-table-column><el-table-column label="阶段名称" prop="stage_name_snapshot" /><el-table-column label="开始" width="155"><template #default="{ row }">{{ readable(row.startedAt) }}</template></el-table-column><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ row.supersededAt ? '已被取代' : '当前版本' }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openRevision(row)">查看</el-button></template></el-table-column></el-table>
|
||||
<el-pagination v-if="revisionTotal > 20" v-model:current-page="revisionPage" :page-size="20" :total="revisionTotal" layout="prev, pager, next, total" @current-change="reloadRevisions" />
|
||||
<template v-if="selected"><h3 v-if="selected.childStages?.length">本版本子阶段组合</h3><el-table v-if="selected.childStages?.length" :data="selected.childStages" size="small"><el-table-column label="子阶段" prop="name" /><el-table-column label="版本" width="80"><template #default="{ row }">v{{ row.revisionNo }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }">{{ stageStatusNames[row.executionStatus as keyof typeof stageStatusNames] }}</template></el-table-column><el-table-column label="工作项" prop="itemCount" width="80" /><el-table-column label="当时预计结束" width="140"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column></el-table><StageSchedulePanel :project-id="projectId" :iteration-id="iterationId" :stage-id="stageId!" :schedule="selected.revision" :historical="true" :superseded-at="selected.revision.supersededAt" /><h3>v{{ selected.revision.revision_no }} 工作项 · {{ selected.total ?? selected.items.length }} 个</h3><el-table :data="selected.items" size="small" max-height="330" empty-text="此版本没有工作项"><el-table-column label="工作项" min-width="190"><template #default="{ row }"><el-link @click="openHistorical(row.id)">{{ row.parent_task_id ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column><el-table-column label="状态" width="105" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column><el-table-column label="原预计结束" width="155"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openHistorical(row.id)">详情</el-button></template></el-table-column></el-table><el-pagination v-if="(selected.total || 0) > 50" v-model:current-page="detailPage" :page-size="50" :total="selected.total" layout="prev, pager, next, total" @current-change="reloadDetail" /><h3>当时的阶段连线</h3><p v-if="!selected.flowDefinition" class="history-muted">该轮次尚未开始,或迁移前未留存流程定义快照。</p><p v-else-if="!selected.flowDefinition.edges.length" class="history-muted">定义 v{{ selected.flowDefinition.revisionNo }} 没有连线。</p><div v-else class="history-edges"><el-tag v-for="edge in selected.flowDefinition.edges" :key="`${edge.predecessorStageId}-${edge.successorStageId}`" size="small">{{ edge.predecessorName }} → {{ edge.successorName }}</el-tag></div></template>
|
||||
<template v-if="selected"><h3 v-if="selected.childStages?.length">本版本子阶段组合</h3><el-table v-if="selected.childStages?.length" :data="selected.childStages" size="small"><el-table-column label="子阶段" prop="name" /><el-table-column label="版本" width="80"><template #default="{ row }">v{{ row.revisionNo }}</template></el-table-column><el-table-column label="状态" width="100" class-name="business-status-cell"><template #default="{ row }">{{ stageStatusNames[row.executionStatus as keyof typeof stageStatusNames] }}</template></el-table-column><el-table-column label="工作项" prop="itemCount" width="80" /><el-table-column label="当时预计结束" width="140"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column></el-table><StageSchedulePanel :project-id="projectId" :iteration-id="iterationId" :stage-id="stageId!" :schedule="selected.revision" :historical="true" :superseded-at="selected.revision.supersededAt" /><h3>v{{ selected.revision.revision_no }} 工作项 · {{ selected.total ?? selected.items.length }} 个</h3><el-table :data="selected.items" size="small" max-height="330" empty-text="此版本没有工作项"><el-table-column label="工作项" min-width="190"><template #default="{ row }"><el-link @click="openHistorical(row.id)">{{ row.parent_task_id ? '↳ ' : '' }}{{ row.title }}</el-link></template></el-table-column><el-table-column label="状态" width="105" class-name="business-status-cell"><template #default="{ row }">{{ statusNames[row.status as Lifecycle] || row.status }}</template></el-table-column><el-table-column label="原预计结束" width="155"><template #default="{ row }">{{ plannedDate(row.plannedEndAt) }}</template></el-table-column><el-table-column label="操作" width="70" class-name="business-operation-cell"><template #default="{ row }"><el-button size="small" link type="primary" @click="openHistorical(row.id)">详情</el-button></template></el-table-column></el-table><el-pagination v-if="(selected.total || 0) > 50" v-model:current-page="detailPage" :page-size="50" :total="selected.total" layout="prev, pager, next, total" @current-change="reloadDetail" /><h3>当时的阶段连线</h3><p v-if="!selected.flowDefinition" class="history-muted">该轮次尚未开始,或迁移前未留存流程定义快照。</p><p v-else-if="!selected.flowDefinition.edges.length" class="history-muted">定义 v{{ selected.flowDefinition.revisionNo }} 没有连线。</p><div v-else class="history-edges"><el-tag v-for="edge in selected.flowDefinition.edges" :key="`${edge.predecessorStageId}-${edge.successorStageId}`" size="small">{{ edge.predecessorName }} → {{ edge.successorName }}</el-tag></div></template>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</el-drawer>
|
||||
|
||||
@ -25,7 +25,7 @@
|
||||
<el-table v-loading="loading" :data="rows" row-key="sourceProjectId" size="small" :height="'100%'" empty-text="暂无你创建或参与的项目">
|
||||
<el-table-column label="项目编号" prop="code" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column label="项目名称" prop="name" min-width="260" show-overflow-tooltip>
|
||||
<template #default="{ row }"><el-link type="primary" :underline="false" :href="projectLink(row.sourceProjectId)" @click="enterProject($event, row.sourceProjectId)">{{ row.name }}</el-link></template>
|
||||
<template #default="{ row }"><el-link type="primary" underline="never" :href="projectLink(row.sourceProjectId)" @click="enterProject($event, row.sourceProjectId)">{{ row.name }}</el-link></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="类型" width="100"><template #default="{ row }">{{ row.projectType === 'PRODUCT' ? '产品项目' : '研发项目' }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="90" class-name="business-status-cell"><template #default="{ row }"><el-tag size="small" :type="statusType(row.projectStatus)">{{ statusNames[row.projectStatus] || '未知' }}</el-tag></template></el-table-column>
|
||||
|
||||
@ -35,7 +35,7 @@
|
||||
</li>
|
||||
<li class="list-group-item">
|
||||
<svg-icon icon-class="date" />创建日期
|
||||
<div class="pull-right">{{ state.user.createTime }}</div>
|
||||
<div class="pull-right">{{ formatDateTime(state.user.createTime) }}</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -63,6 +63,7 @@
|
||||
</template>
|
||||
|
||||
<script setup name="Profile">
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import userAvatar from "./userAvatar"
|
||||
import userInfo from "./userInfo"
|
||||
import resetPwd from "./resetPwd"
|
||||
|
||||
@ -81,7 +81,7 @@
|
||||
<el-col :span="12">
|
||||
<div class="info-item">
|
||||
<label class="info-label">创建时间:</label>
|
||||
<span class="info-value plaintext">{{ info.createTime }}</span>
|
||||
<span class="info-value plaintext">{{ formatDateTime(info.createTime) }}</span>
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@ -95,7 +95,7 @@
|
||||
<el-col :span="12">
|
||||
<div class="info-item">
|
||||
<label class="info-label">更新时间:</label>
|
||||
<span class="info-value plaintext">{{ info.updateTime }}</span>
|
||||
<span class="info-value plaintext">{{ formatDateTime(info.updateTime) }}</span>
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@ -109,7 +109,7 @@
|
||||
<el-col :span="12">
|
||||
<div class="info-item">
|
||||
<label class="info-label">最后登录时间:</label>
|
||||
<span class="info-value plaintext">{{ info.loginDate }}</span>
|
||||
<span class="info-value plaintext">{{ formatDateTime(info.loginDate) }}</span>
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@ -126,6 +126,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { getUser } from '@/api/system/user'
|
||||
|
||||
const visible = ref(false)
|
||||
|
||||
@ -69,7 +69,7 @@
|
||||
<el-table-column label="项目" prop="projectName" :min-width="arrivalMode?120:150" show-overflow-tooltip />
|
||||
<el-table-column v-if="!arrivalMode" label="费用分类" prop="expenseCategoryName" width="110" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!arrivalMode" label="用途" width="110" show-overflow-tooltip><template #default="s">{{ s.row.purchasePurpose==='REPAY'?'归还借用':'本项目使用' }}</template></el-table-column>
|
||||
<el-table-column v-if="!arrivalMode" label="采购金额" width="126" align="right" class-name="business-status-cell">
|
||||
<el-table-column v-if="!arrivalMode&&canManageAll" label="报价金额" width="126" align="right" class-name="business-status-cell">
|
||||
<template #default="scope">
|
||||
<div class="primary-text">{{ scope.row.finalUnitPrice === null ? '待定价' : '¥ ' + money(scope.row.estimatedAmount) }}</div>
|
||||
<el-tag size="small" :type="(scope.row.priceLocked ? 'success' : 'info') || 'primary'">{{ scope.row.priceLocked ? '价格已锁定' : '价格未锁定' }}</el-tag>
|
||||
@ -78,7 +78,7 @@
|
||||
</el-table-column>
|
||||
<el-table-column :label="arrivalMode ? '采购数量' : '数量'" :width="arrivalMode?95:135" class-name="business-control-cell"><template #default="s"><el-input-number v-if="!arrivalMode && inlineEdit && canOperate(s.row)" v-model="s.row.quantity" :precision="4" :min="0.0001" :controls="false" :disabled="s.row._saving" style="width:110px"/><span v-else>{{ s.row.quantity }}{{ arrivalMode?' '+(s.row.unit || ''):'' }}</span></template></el-table-column>
|
||||
<el-table-column v-if="!arrivalMode" label="单位" prop="unit" width="70" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!arrivalMode" label="最终单价" width="145" class-name="business-control-cell"><template #default="s"><el-input-number v-if="inlineEdit && canOperate(s.row)" v-model="s.row.finalUnitPrice" :precision="6" :min="0" :controls="false" :disabled="s.row._saving || !canEditPrice(s.row)" style="width:120px"/><span v-else>{{ s.row.finalUnitPrice==null?'未定价':s.row.finalUnitPrice }}</span><div v-if="Number(s.row.receivedQuantity)>0" class="secondary-text">已入库,价格锁定</div></template></el-table-column>
|
||||
<el-table-column v-if="!arrivalMode&&canManageAll" label="报价单价" width="145" class-name="business-control-cell"><template #default="s"><el-input-number v-if="inlineEdit && canOperate(s.row)" v-model="s.row.finalUnitPrice" :precision="6" :min="0" :controls="false" :disabled="s.row._saving || !canEditPrice(s.row)" style="width:120px"/><span v-else>{{ s.row.finalUnitPrice==null?'未定价':s.row.finalUnitPrice }}</span><div v-if="Number(s.row.receivedQuantity)>0" class="secondary-text">已入库,价格锁定</div></template></el-table-column>
|
||||
<el-table-column v-if="!arrivalMode && inlineEdit" label="保存修改" width="100" class-name="business-operation-cell"><template #default="s"><el-button v-if="canOperate(s.row)" link type="primary" :loading="s.row._saving" @click="saveInline(s.row)">保存本行</el-button><span v-else>-</span></template></el-table-column>
|
||||
<el-table-column v-if="!arrivalMode" label="供应商" prop="supplierName" min-width="120" show-overflow-tooltip/>
|
||||
<el-table-column v-if="!arrivalMode" label="采购批次" min-width="165">
|
||||
@ -156,8 +156,8 @@
|
||||
<div class="detail-grid">
|
||||
<div><span>采购项目</span><strong>{{ detailRequest.projectName || '-' }}</strong></div>
|
||||
<div><span>经费科目</span><strong>{{ detailRequest.expenseCategoryName || '-' }}</strong></div>
|
||||
<div><span>采购金额</span><strong>{{ detailRequest.finalUnitPrice === null ? '待定价' : '¥ ' + money(detailRequest.estimatedAmount) }}</strong></div>
|
||||
<div><span>计入项目费用</span><strong>¥ {{ money(detailRequest.lockedAmount) }}({{ detailRequest.priceLocked ? '已锁价' : '未锁价' }})</strong></div>
|
||||
<div v-if="canManageAll"><span>报价金额</span><strong>{{ detailRequest.finalUnitPrice === null ? '待定价' : '¥ ' + money(detailRequest.estimatedAmount) }}</strong></div>
|
||||
<div v-if="canManageAll"><span>计入项目费用</span><strong>¥ {{ money(detailRequest.lockedAmount) }}({{ detailRequest.priceLocked ? '已锁价' : '未锁价' }})</strong></div>
|
||||
<div><span>采购批次</span><strong>{{ detailRequest.purchaseBatchNo ? [detailRequest.purchaseBatchNo, detailRequest.purchaseBatchName].filter(Boolean).join(' / ') : '未分配' }}</strong></div>
|
||||
<div><span>创建时间</span><strong>{{ parseTime(detailRequest.createTime) || '-' }}</strong></div>
|
||||
</div>
|
||||
@ -173,7 +173,7 @@
|
||||
<div class="arrival-dot" :class="'status-' + Number(item.acceptanceStatus)" />
|
||||
<div>
|
||||
<div class="detail-arrival-head"><strong>{{ item.arrivalNo }}</strong><el-tag size="small" :type="(acceptanceType(item.acceptanceStatus)) || 'primary'">{{ acceptanceLabel(item.acceptanceStatus) }}</el-tag></div>
|
||||
<p>{{ item.arrivalDate }} · {{ item.arrivalQuantity }} {{ detailRequest.unit || '' }} · ¥{{ money(item.actualAmount) }}</p>
|
||||
<p>{{ formatDateTime(item.arrivalDate) }} · {{ item.arrivalQuantity }} {{ detailRequest.unit || '' }}<span v-if="canManageAll"> · ¥{{ money(item.actualAmount) }}</span></p>
|
||||
<small v-if="item.remark || item.acceptanceRemark">{{ item.acceptanceRemark || item.remark }}</small>
|
||||
</div>
|
||||
</div>
|
||||
@ -271,8 +271,8 @@
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="12"><el-form-item label="需求数量" prop="quantity"><el-input-number v-model="form.quantity" :min="0.0001" :precision="4" :controls="false" /></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="最终含税单价" prop="finalUnitPrice"><el-input-number v-model="form.finalUnitPrice" :min="0" :precision="6" :controls="false" :disabled="Number(form.receivedQuantity||0)>0" placeholder="可暂不填写" /><div v-if="Number(form.receivedQuantity||0)>0" class="product-meta">已有确认入库,需先逐步撤销到待入库后才能修改价格。</div></el-form-item></el-col>
|
||||
<el-col :span="12"><el-form-item label="采购总金额"><el-input :model-value="money(Number(form.quantity || 0) * Number(form.finalUnitPrice || 0))" disabled /></el-form-item></el-col>
|
||||
<el-col v-if="canManageAll" :span="12"><el-form-item label="最终含税单价" prop="finalUnitPrice"><el-input-number v-model="form.finalUnitPrice" :min="0" :precision="6" :controls="false" :disabled="Number(form.receivedQuantity||0)>0" placeholder="可暂不填写" /><div v-if="Number(form.receivedQuantity||0)>0" class="product-meta">已有确认入库,需先逐步撤销到待入库后才能修改价格。</div></el-form-item></el-col>
|
||||
<el-col v-if="canManageAll" :span="12"><el-form-item label="采购总金额"><el-input :model-value="money(Number(form.quantity || 0) * Number(form.finalUnitPrice || 0))" disabled /></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="采购链接" prop="purchaseLink"><el-input v-model="form.purchaseLink" placeholder="请输入商品或供应商链接" /></el-form-item></el-col>
|
||||
<el-col :span="24"><el-form-item label="申请备注" prop="remark"><el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入用途、预算等补充信息" /></el-form-item></el-col>
|
||||
</el-row>
|
||||
@ -387,7 +387,7 @@
|
||||
<el-table-column label="需求数量" min-width="110" class-name="business-control-cell">
|
||||
<template #default="scope"><el-input v-model="scope.row.quantity" @paste="handleGridPaste($event, scope.$index, 8)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最终含税单价" min-width="130" class-name="business-control-cell">
|
||||
<el-table-column v-if="canManageAll" label="最终含税单价" min-width="130" class-name="business-control-cell">
|
||||
<template #default="scope"><el-input v-model="scope.row.finalUnitPrice" @paste="handleGridPaste($event, scope.$index, 9)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="采购链接" min-width="210" class-name="business-control-cell">
|
||||
@ -430,16 +430,18 @@
|
||||
<el-form-item label="本次到货" prop="arrivalQuantity"><el-input-number v-model="arrivalForm.arrivalQuantity" :min="0" :max="Number(arrivalRequest.remainingQuantity || 0)" :precision="4" :controls="false" :disabled="arrivalBusy" /></el-form-item>
|
||||
<el-form-item><el-button :disabled="arrivalBusy" @click="arrivalForm.arrivalQuantity=Number(arrivalRequest.remainingQuantity)">全部剩余数量</el-button></el-form-item><el-form-item label="到货日期" prop="arrivalDate"><el-date-picker v-model="arrivalForm.arrivalDate" type="date" value-format="YYYY-MM-DD" :disabled="arrivalBusy" /></el-form-item>
|
||||
<el-form-item label="备注" prop="remark"><el-input v-model="arrivalForm.remark" :disabled="arrivalBusy" /></el-form-item>
|
||||
<el-form-item label="到货照片" class="arrival-photos-field"><arrival-photos v-model="arrivalPhotos" :request-id="arrivalRequest.id" :disabled="arrivalBusy" @pending="arrivalPhotosPending=$event"/></el-form-item>
|
||||
<el-form-item><el-button type="primary" :loading="arrivalSubmitting" :disabled="arrivalBusy || Number(arrivalRequest.remainingQuantity) <= 0" @click="submitArrival">登记到货</el-button></el-form-item>
|
||||
</el-form>
|
||||
<h4 class="arrival-records-heading">到货记录 <span>{{ arrivalList.length }} 条</span></h4>
|
||||
<el-table v-loading="arrivalLoading" :data="arrivalList" border class="arrival-table" :height="'min(340px,40vh)'" empty-text="暂无到货记录">
|
||||
<el-table-column type="expand" width="40"><template #default="s"><el-descriptions :column="2" border class="arrival-record-details"><el-descriptions-item label="采购单价">{{ s.row.actualUnitPrice }}</el-descriptions-item><el-descriptions-item label="到货金额">{{ s.row.actualAmount }}</el-descriptions-item><el-descriptions-item label="到货备注">{{ s.row.remark||'—' }}</el-descriptions-item><el-descriptions-item label="验收说明">{{ s.row.acceptanceRemark||'—' }}</el-descriptions-item><el-descriptions-item label="撤销说明">{{ s.row.revokeRemark||'—' }}</el-descriptions-item></el-descriptions></template></el-table-column>
|
||||
<el-table-column type="expand" width="40"><template #default="s"><el-descriptions :column="2" border class="arrival-record-details"><el-descriptions-item v-if="canManageAll" label="采购单价">{{ s.row.actualUnitPrice }}</el-descriptions-item><el-descriptions-item v-if="canManageAll" label="到货金额">{{ s.row.actualAmount }}</el-descriptions-item><el-descriptions-item label="到货备注">{{ s.row.remark||'—' }}</el-descriptions-item><el-descriptions-item label="验收说明">{{ s.row.acceptanceRemark||'—' }}</el-descriptions-item><el-descriptions-item label="撤销说明">{{ s.row.revokeRemark||'—' }}</el-descriptions-item></el-descriptions></template></el-table-column>
|
||||
<el-table-column label="到货单号" prop="arrivalNo" min-width="160" show-overflow-tooltip/>
|
||||
<el-table-column :formatter="(row,column,value)=>$dateTime(value)" label="到货日期" prop="arrivalDate" width="110" show-overflow-tooltip/>
|
||||
<el-table-column label="数量" prop="arrivalQuantity" width="100" align="right" show-overflow-tooltip/>
|
||||
<el-table-column label="到货金额" prop="actualAmount" width="110" align="right" show-overflow-tooltip/>
|
||||
<el-table-column v-if="canManageAll" label="到货金额" prop="actualAmount" width="110" align="right" show-overflow-tooltip/>
|
||||
<el-table-column label="验收状态" width="100" align="center" class-name="business-status-cell"><template #default="scope"><el-tag :type="(acceptanceType(scope.row.acceptanceStatus)) || 'primary'" size="small">{{ acceptanceLabel(scope.row.acceptanceStatus) }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="到货照片" width="130" class-name="business-control-cell"><template #default="s"><arrival-photos :model-value="s.row.photos||[]" readonly compact/></template></el-table-column>
|
||||
<el-table-column label="验收人" prop="acceptedBy" width="100" show-overflow-tooltip/>
|
||||
<el-table-column label="操作" width="190" align="center" fixed="right" class-name="business-operation-cell">
|
||||
<template #default="scope">
|
||||
@ -459,6 +461,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { formatDateTime } from '@/utils/display-format'
|
||||
import { runLatest, invalidateQuery } from '@/utils/query-session'
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import { filteredPurchases, filteredPurchaseTotals } from '@/api/warehouse/purchase'
|
||||
@ -472,7 +475,7 @@ import CancelPurchase from '@/components/ReceiptDialog/CancelPurchase'
|
||||
export default {
|
||||
name: 'PurchaseRequest',
|
||||
props:{projectId:Number,initialView:{type:String,default:'all'}},
|
||||
components: { PurchaseSheet:defineAsyncComponent(()=>import('@/components/PurchaseSheet')), ExcelImportDialog, PurchasePurpose, CancelPurchase, PurchaseBulkEdit:defineAsyncComponent(()=>import('@/components/ReceiptDialog/PurchaseBulkEdit')), BatchArrival: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')), SupplierPicker: defineAsyncComponent(()=>import('@/components/SupplierPicker')), AcceptanceException: defineAsyncComponent(()=>import('@/components/ReceiptDialog/AcceptanceException')), PurchaseReturn: defineAsyncComponent(()=>import('@/components/ReceiptDialog/PurchaseReturn')) },
|
||||
components: { ArrivalPhotos:defineAsyncComponent(()=>import('@/components/ArrivalPhotos')), PurchaseSheet:defineAsyncComponent(()=>import('@/components/PurchaseSheet')), ExcelImportDialog, PurchasePurpose, CancelPurchase, PurchaseBulkEdit:defineAsyncComponent(()=>import('@/components/ReceiptDialog/PurchaseBulkEdit')), BatchArrival: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')), SupplierPicker: defineAsyncComponent(()=>import('@/components/SupplierPicker')), AcceptanceException: defineAsyncComponent(()=>import('@/components/ReceiptDialog/AcceptanceException')), PurchaseReturn: defineAsyncComponent(()=>import('@/components/ReceiptDialog/PurchaseReturn')) },
|
||||
data() {
|
||||
return {
|
||||
legacyMode:false,
|
||||
@ -545,7 +548,7 @@ export default {
|
||||
arrivalActionKey: '',
|
||||
arrivalRequest: null,
|
||||
arrivalList: [],
|
||||
arrivalForm: {},
|
||||
arrivalForm: {}, arrivalPhotos: [], arrivalPhotosPending: false,
|
||||
title: '',
|
||||
batchTitle: '',
|
||||
batchList: [],
|
||||
@ -683,7 +686,7 @@ export default {
|
||||
},
|
||||
activated(){if(this._homeRoute!==this.$route.fullPath)this.applyHomeNavigation()},
|
||||
watch:{'$route.fullPath'(){if(!this._pageInactive)this.applyHomeNavigation()}},
|
||||
methods: {
|
||||
methods: {formatDateTime,
|
||||
applyHomeFilters(){this._homeRoute=this.$route.fullPath;const q=this.$route.query;this.queryParams.projectId=this.projectId||Number(q.projectId)||undefined;this.queryParams.requestNo=q.requestNo||undefined;if(q.queue==='pending'){this.arrivalQueue='pendingAcceptance';this.queryParams.pendingAcceptance=true;this.queryParams.notArrived=false}},
|
||||
applyHomeNavigation(){if(this._homeRoute===this.$route.fullPath)return;if(this.arrivalMode && this.$route.path==='/procurement/arrival'){this.applyHomeFilters();this.queryParams.purchaseBatchNo=this.$route.query.purchaseBatchNo||undefined;if(this.$route.query.queue!=='pending'){this.queryParams.pendingAcceptance=false;this.queryParams.notArrived=!this.queryParams.purchaseBatchNo;this.arrivalQueue=this.queryParams.purchaseBatchNo?'all':'open'}this.queryParams.pageNum=1;this.getList()}},
|
||||
openLegacy(view='details'){this.purchaseView=view;this.legacyMode=true;this.queryParams.unbatched=view==='unbatched';if(this.queryParams.unbatched)this.queryParams.purchaseBatchNo=undefined;this.queryParams.pageNum=1;this.queryParams.projectId=this.projectId||Number(this.$route.query.projectId)||undefined;this.getList();this.getTaskStats();this.getProductFilterOptions();this.getFundingOptions();this.searchBatchFilterOptions('');if(this.canManageAll)this.getBatchOptions()},
|
||||
@ -1034,6 +1037,7 @@ export default {
|
||||
})
|
||||
},
|
||||
resetArrivalForm() {
|
||||
this.arrivalPhotos=[];this.arrivalPhotosPending=false
|
||||
this.arrivalForm = { purchaseRequestId: this.arrivalRequest && this.arrivalRequest.id, arrivalQuantity: 0, actualUnitPrice: this.arrivalRequest && this.arrivalRequest.finalUnitPrice, arrivalDate: this.parseTime(new Date(), '{y}-{m}-{d}'), remark: undefined, requestKey: `arrival-${this.arrivalRequest?.id}-${Date.now()}-${Math.random().toString(36).slice(2)}` }
|
||||
this.$nextTick(() => this.$refs.arrivalForm && this.$refs.arrivalForm.clearValidate())
|
||||
},
|
||||
@ -1046,7 +1050,7 @@ export default {
|
||||
if (this.arrivalBusy) return
|
||||
const requestId = this.arrivalRequest.id
|
||||
this.arrivalSubmitting = true
|
||||
addPurchaseArrival({ ...this.arrivalForm }).then(() => {
|
||||
addPurchaseArrival({ ...this.arrivalForm,photoIds:this.arrivalPhotos.map(p=>p.id) }).then(() => {
|
||||
this.$modal.msgSuccess('到货已登记,等待验收')
|
||||
this.resetArrivalForm()
|
||||
this.refreshPurchaseData(requestId)
|
||||
@ -1439,7 +1443,7 @@ export default {
|
||||
},
|
||||
canEditPrice(row) { return this.canOperate(row) && Number(row.receivedQuantity || 0) <= 0 },
|
||||
canBulkEditPurchase(row) { return this.canOperate(row) && Number(row.receivedQuantity || 0) <= 0 },
|
||||
canLockPurchase(row) { return this.canOperate(row) && !row.priceLocked && row.finalUnitPrice !== null && row.finalUnitPrice !== undefined && row.finalUnitPrice !== '' },
|
||||
canLockPurchase(row) { return this.canManageAll && this.canOperate(row) && !row.priceLocked && row.finalUnitPrice !== null && row.finalUnitPrice !== undefined && row.finalUnitPrice !== '' },
|
||||
canDeletePurchase(row) { return this.canOperate(row) && Number(row.acceptedQuantity || 0) <= 0 && Number(row.pendingArrivalQuantity || 0) <= 0 },
|
||||
canSelectArrival(row) {
|
||||
if (!this.canOperate(row) || !row || row.historical || Number(row.purchaseStatus) === 5) return false
|
||||
@ -2038,3 +2042,5 @@ export default {
|
||||
.purchase-detail-drawer { width: 100% !important; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<style scoped>.arrival-photos-field{display:flex!important;width:100%;margin-right:0}.arrival-photos-field :deep(.el-form-item__content){flex:1;min-width:0}</style>
|
||||
|
||||
@ -55,7 +55,7 @@ test('comparison column order is sequence, merged category, original material na
|
||||
expect(api.archiveSave).not.toHaveBeenCalled();expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
|
||||
})
|
||||
test('independent page loads without importing business projects or collaboration membership',async()=>{
|
||||
const w=mount(Archive);await flushPromises();expect(api.archiveProjects).toHaveBeenCalledOnce();expect(w.text()).toContain('项目资料');expect(w.text()).toContain('与采购、库存及项目协作独立');w.unmount()
|
||||
const w=mount(Archive);await flushPromises();expect(api.archiveProjects).toHaveBeenCalledOnce();expect(w.find('.page-heading').exists()).toBe(false);expect(w.find('.list-toolbar .toolbar-actions').text()).toContain('新建资料项目');expect(api.archiveDetail).not.toHaveBeenCalled();w.unmount()
|
||||
})
|
||||
|
||||
test('archived visibility is opt-in, shared by both views, and disabling it resets the archive-only filter and page',async()=>{
|
||||
@ -199,7 +199,7 @@ test('cost save uses the archive API and never turns saving into completion conf
|
||||
expect(api.archiveCost).toHaveBeenCalledWith(21,expect.objectContaining({version:3,data:expect.objectContaining({income:100,formatVersion:3})}));expect(api.archiveItem).not.toHaveBeenCalled();w.unmount()
|
||||
})
|
||||
test('new projects default external and the rates entry is restricted by administrator metadata',async()=>{
|
||||
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.editProject();expect(state.projectForm.scopeType).toBe('EXTERNAL');expect(w.text()).not.toContain('人员费用标准');state.metadata.canMaintainCosts=true;await flushPromises();expect(w.text()).toContain('人员费用标准');w.unmount()
|
||||
const w=mount(Archive);await flushPromises();const state=w.vm.$.setupState;state.editProject();expect(state.projectForm.scopeType).toBe('EXTERNAL');expect(w.text()).not.toContain('管理设置');state.manageProjectData('rates');expect(state.ratesDialog).toBe(false);state.metadata.canMaintainCosts=true;await flushPromises();expect(w.text()).toContain('管理设置');state.manageProjectData('rates');expect(state.ratesDialog).toBe(true);state.manageProjectData('catalog');expect(state.catalogDialog).toBe(false);w.unmount()
|
||||
})
|
||||
test('person selectors keep selected users during search and use their current centrally managed rates',async()=>{
|
||||
api.archiveCostPeople.mockResolvedValue({data:[{id:5,name:'普通成员',account:'member',rate:1200}]});const source={data:{formatVersion:3,income:10000,labor:[{userId:5,name:'旧姓名',duty:'研发',days:2,rate:900}]}}
|
||||
|
||||
33
ruoyi-ui-vue3/tests/runtime/arrival-photos.spec.js
Normal file
33
ruoyi-ui-vue3/tests/runtime/arrival-photos.spec.js
Normal file
@ -0,0 +1,33 @@
|
||||
import {beforeEach,afterEach,expect,it,vi} from 'vitest'
|
||||
import {mount,flushPromises} from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import Photos from '@/components/ArrivalPhotos/index.vue'
|
||||
const request=vi.hoisted(()=>vi.fn())
|
||||
vi.mock('@/utils/request',()=>({default:request}))
|
||||
let wrapper,created,revoke
|
||||
beforeEach(()=>{request.mockReset();created=URL.createObjectURL;revoke=URL.revokeObjectURL;URL.createObjectURL=vi.fn(()=>`blob:photo-${Math.random()}`);URL.revokeObjectURL=vi.fn()})
|
||||
afterEach(()=>{wrapper?.unmount();document.body.innerHTML='';URL.createObjectURL=created;URL.revokeObjectURL=revoke})
|
||||
function page(props={}){wrapper=mount(Photos,{attachTo:document.body,props:{requestId:10,modelValue:[],...props,'onUpdate:modelValue':value=>wrapper.setProps({modelValue:value})},global:{plugins:[ElementPlus]}});return wrapper}
|
||||
async function choose(files){const input=wrapper.find('input[type=file]');Object.defineProperty(input.element,'files',{value:files,configurable:true});await input.trigger('change');await flushPromises()}
|
||||
const picture=()=>new File(['image'],'到货.png',{type:'image/png'})
|
||||
it('photos are optional and successful uploads are included in the model before submission',async()=>{
|
||||
request.mockImplementation(async c=>c.method==='post'?{data:{id:c.data.get('uploadId'),name:'到货.png'}}:{});page();expect(wrapper.vm.pending).toBe(false)
|
||||
await choose([picture()]);expect(wrapper.props('modelValue')).toHaveLength(1);expect(wrapper.props('modelValue')[0].id).toMatch(/^[0-9a-f-]{36}$/);expect(wrapper.vm.pending).toBe(false)
|
||||
await wrapper.findAll('button').find(b=>b.text()==='移除').trigger('click');await flushPromises();expect(wrapper.props('modelValue')).toEqual([]);expect(request.mock.calls[1][0].method).toBe('delete')
|
||||
})
|
||||
it('failed photos can be retried using the same upload identifier or removed without blocking optional registration',async()=>{
|
||||
request.mockRejectedValueOnce(Error('模拟上传失败')).mockImplementation(async c=>({data:{id:c.data.get('uploadId'),name:'到货.png'}}));page();await choose([picture()]);expect(wrapper.vm.pending).toBe(true);expect(wrapper.text()).toContain('模拟上传失败')
|
||||
await wrapper.findAll('button').find(b=>b.text()==='重试').trigger('click');await flushPromises();expect(wrapper.vm.pending).toBe(false);expect(request.mock.calls[0][0].data.get('uploadId')).toBe(request.mock.calls[1][0].data.get('uploadId'))
|
||||
})
|
||||
it('read-only saved photos load privately on demand and never expose upload or remove controls',async()=>{
|
||||
request.mockResolvedValue(new Blob(['private'],{type:'image/png'}));page({compact:true,readonly:true,disabled:true,modelValue:[{id:'11111111-1111-4111-8111-111111111111',name:'到货.png'}]});expect(request).not.toHaveBeenCalled()
|
||||
await wrapper.find('button').trigger('click');await flushPromises();expect(request).toHaveBeenCalledOnce();expect(request.mock.calls[0][0].url).toContain('/content');expect(document.body.textContent).not.toContain('上传照片');expect(document.body.textContent).not.toContain('移除')
|
||||
})
|
||||
it('non-images and oversized files do not upload; each arrival is limited to nine photos',async()=>{
|
||||
request.mockImplementation(async c=>({data:{id:c.data.get('uploadId'),name:'到货.png'}}));page();await choose([new File(['not image'],'file.txt',{type:'text/plain'}),new File([new Uint8Array(5*1024*1024+1)],'large.png',{type:'image/png'})]);expect(request).not.toHaveBeenCalled()
|
||||
await choose(Array.from({length:10},picture));expect(wrapper.props('modelValue')).toHaveLength(9);expect(request).toHaveBeenCalledTimes(9)
|
||||
})
|
||||
it('saved photo loading errors can retry without editing the arrival or its photo metadata',async()=>{
|
||||
request.mockRejectedValueOnce(Error('模拟读取失败')).mockResolvedValue(new Blob(['private'],{type:'image/png'}));page({readonly:true,modelValue:[{id:'11111111-1111-4111-8111-111111111111',name:'到货.png'}]});await flushPromises();expect(wrapper.text()).toContain('加载失败,点击重试');expect(wrapper.props('modelValue')[0].error).toBeUndefined()
|
||||
await wrapper.find('.arrival-photo-placeholder').trigger('click');await flushPromises();expect(request).toHaveBeenCalledTimes(2);expect(wrapper.text()).not.toContain('模拟读取失败')
|
||||
})
|
||||
6
ruoyi-ui-vue3/tests/runtime/project-list-access.spec.js
Normal file
6
ruoyi-ui-vue3/tests/runtime/project-list-access.spec.js
Normal file
@ -0,0 +1,6 @@
|
||||
import {expect,test} from 'vitest'
|
||||
import {canManageProject} from '@/utils/project-access'
|
||||
const canManage=(id,row)=>canManageProject(row,id)
|
||||
test('the root administrator can maintain historical projects without a manager',()=>{expect(canManage(1,{id:27,managerId:null})).toBe(true);expect(canManage(1,{id:28,managerId:9})).toBe(true);expect(canManage(1,null)).toBe(false)})
|
||||
test('ordinary users only maintain projects that they manage',()=>{expect(canManage(8,{id:27,managerId:null})).toBe(false);expect(canManage(8,{id:28,managerId:9})).toBe(false);expect(canManage(8,{id:29,managerId:8})).toBe(true)})
|
||||
test('an unavailable login never matches an unassigned manager',()=>{expect(canManage(undefined,{})).toBe(false);expect(canManage(null,{managerId:null})).toBe(false)})
|
||||
@ -6,6 +6,8 @@ import {defineComponent,nextTick} from 'vue'
|
||||
import {mount,flushPromises} from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import Sheet from '../../src/components/PurchaseSheet/index.vue'
|
||||
import {amountDisplay} from '../../src/utils/amount-display'
|
||||
import {queueMatches} from '../../src/utils/purchase-sheet-view'
|
||||
vi.mock('@/utils/request',()=>({default:vi.fn()}))
|
||||
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
|
||||
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
|
||||
@ -22,7 +24,7 @@ it('real purchase columns, batch totals and footer keep actual amounts before qu
|
||||
visit(baseParse(template));expect(grid).toBeTruthy();expect(footer).toBeTruthy();expect(totals).toHaveLength(2)
|
||||
const extract=node=>template.slice(node.loc.start.offset,node.loc.end.offset)
|
||||
const host=defineComponent({template:`<div><el-table class="detail" :data="sheet.rows">${extract(grid)}</el-table><el-table class="batches" :data="sheet.rows">${totals.map(extract).join('')}</el-table><section class="summary">${extract(footer)}</section></div>`,
|
||||
data:()=>({compactAmounts:false,extras:false,batchProject:{mixed:false},sheet:{rows:[{_key:'r',quantity:2,unit:'个',actualUnitPrice:3,finalUnitPrice:5,actualTotalAmount:6,totalAmount:10}]},cellOwner:{},editCell:null}),
|
||||
data:()=>({canViewQuotes:true,compactAmounts:false,extras:false,batchProject:{mixed:false},sheet:{rows:[{_key:'r',quantity:2,unit:'个',actualUnitPrice:3,finalUnitPrice:5,actualTotalAmount:6,totalAmount:10}]},cellOwner:{},editCell:null}),
|
||||
computed:{columns(){return Sheet.computed.columns.call(this)},visibleRows(){return this.sheet.rows},actualTotal:()=>6,amount:()=>10,unpriced:()=>0},
|
||||
methods:{selectColumn(){},originalIndex:()=>0,actualAmount:row=>row.quantity*row.actualUnitPrice,hasPrice:()=>true,money:value=>Number(value).toFixed(2)}})
|
||||
const wrapper=mount(host,{global:{plugins:[ElementPlus],stubs:{PurchaseCell:true,BusinessIcon:true}}})
|
||||
@ -41,5 +43,25 @@ it('real purchase columns, batch totals and footer keep actual amounts before qu
|
||||
expect(wrapper.get('.summary').text()).not.toContain('实际总金额')
|
||||
await wrapper.setData({compactAmounts:false});await flushPromises();await nextTick()
|
||||
expect(headers().filter(h=>expected.includes(h))).toEqual(expected)
|
||||
await wrapper.setData({canViewQuotes:false});await flushPromises();await nextTick()
|
||||
expect(headers().filter(h=>expected.includes(h))).toEqual(['实际单价','实际金额'])
|
||||
expect(wrapper.findAll('.batches thead th').map(h=>h.text())).toEqual(['实际总金额'])
|
||||
expect(wrapper.get('.summary').text()).not.toContain('报价总金额')
|
||||
expect(wrapper.get('.summary').text()).toContain('实际总金额 ¥ 6.00')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('employee purchase views keep actual amounts, omit quote sorts and preserve quotation workflow states',()=>{
|
||||
const vm={canViewQuotes:false,extras:false,sheet:{unbatched:true},batchProject:{mixed:false}}
|
||||
expect(Sheet.computed.columns.call(vm).map(c=>c.field)).toContain('actualUnitPrice')
|
||||
expect(Sheet.computed.columns.call(vm).map(c=>c.field)).not.toContain('finalUnitPrice')
|
||||
expect(Sheet.computed.sortOptions.call(vm).map(c=>c.value)).not.toEqual(expect.arrayContaining(['priceAsc','priceDesc','amountDesc']))
|
||||
expect(Sheet.methods.fieldLocked.call(vm,{},'finalUnitPrice')).toBe(true)
|
||||
const original=amountDisplay.enabled;amountDisplay.enabled=true
|
||||
try{expect(Sheet.computed.compactAmounts.call(vm)).toBe(false)}finally{amountDisplay.enabled=original}
|
||||
const row={id:1,quoteAvailable:true,finalUnitPrice:null,priceLocked:false,purchaseStatus:0}
|
||||
expect(Sheet.methods.hasPrice.call(vm,row)).toBe(true)
|
||||
expect(queueMatches(row,'confirm')).toBe(true);expect(queueMatches(row,'quote')).toBe(false)
|
||||
expect(Sheet.computed.canViewQuotes.call({$auth:{hasPermiOr:()=>false}})).toBe(false)
|
||||
expect(Sheet.computed.canViewQuotes.call({$auth:{hasPermiOr:()=>true}})).toBe(true)
|
||||
})
|
||||
|
||||
@ -7,6 +7,15 @@ import {writeClipboardText} from '../../src/utils/purchase-grid-clipboard'
|
||||
vi.mock('@/utils/request',()=>({default:vi.fn()}))
|
||||
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
|
||||
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
|
||||
it.each(['number','text'])('typing into a %s grid input does not invoke unsupported native text selection',async type=>{
|
||||
const root=document.createElement('div'),cell=document.createElement('div'),input=document.createElement('input')
|
||||
cell.className='sheet-cell';cell.dataset.row='0';cell.dataset.field='quantity';input.type=type;cell.append(input);root.append(cell)
|
||||
const entered=vi.fn();input.addEventListener('input',entered)
|
||||
const vm={$el:root,editableCell:()=>true,activateCell:vi.fn(),originalIndex:()=>0}
|
||||
await expect(Sheet.methods.typeGridCell.call(vm,{},'quantity','12')).resolves.toBeUndefined()
|
||||
expect(input.value).toBe('12');expect(entered).toHaveBeenCalledOnce();expect(vm._typingGrid).toBe(false)
|
||||
if(type==='text')expect(input.selectionStart).toBe(2)
|
||||
})
|
||||
it('compact display filters rows without removing them from complete purchase saves',()=>{
|
||||
const rows=[{_key:'zero',id:1,finalUnitPrice:0,purchaseStatus:0},{_key:'priced',id:2,finalUnitPrice:3,purchaseStatus:0}]
|
||||
const vm={sheet:{rows},rowFilter:'',rowQueue:'all',rowSort:'original',onlyInvalid:false,compactAmounts:true,isEditing:false,viewReference:r=>r,projectName:()=>''}
|
||||
@ -65,3 +74,13 @@ it('search input retains native shortcuts while grid shortcuts are intercepted e
|
||||
event.target=root;Sheet.methods.editorShortcut.call(vm,event);expect(undo).toHaveBeenCalledOnce()
|
||||
event.shiftKey=true;Sheet.methods.editorShortcut.call(vm,event);expect(redo).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('a virtual window at the end retains the last row when density changes its capacity',()=>{
|
||||
const vm={sheet:{},virtualized:true,visibleRows:Array.from({length:500}),virtualStart:476}
|
||||
Sheet.watch.virtualCount.call(vm,23,24)
|
||||
expect(vm.virtualStart).toBe(477);expect(vm.virtualStart+23).toBe(500)
|
||||
vm.virtualStart=200;Sheet.watch.virtualCount.call(vm,25,23);expect(vm.virtualStart).toBe(200)
|
||||
vm.virtualStart=477;Sheet.watch.virtualCount.call(vm,28,23);expect(vm.virtualStart).toBe(472)
|
||||
})
|
||||
|
||||
it('closing a sheet leaves an empty virtual view without dereferencing its old rows',()=>{expect(Sheet.computed.visibleRows.call({sheet:null,rowFilter:'',rowSort:'original'})).toEqual([]);expect(()=>Sheet.watch.virtualCount.call({sheet:null},24,23)).not.toThrow()})
|
||||
|
||||
17
ruoyi-ui-vue3/tests/runtime/remote-picker.spec.js
Normal file
17
ruoyi-ui-vue3/tests/runtime/remote-picker.spec.js
Normal file
@ -0,0 +1,17 @@
|
||||
import {expect,it,vi} from 'vitest'
|
||||
import {mount,flushPromises} from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import RemotePicker from '../../src/components/BomEditor/RemotePicker.vue'
|
||||
|
||||
it('an empty remote search explains the result while keeping the existing selection',async()=>{
|
||||
const fetchPage=vi.fn(async()=>({rows:[],total:0}))
|
||||
const wrapper=mount(RemotePicker,{attachTo:document.body,props:{modelValue:7,item:{id:7,name:'原产品'},fetchPage,optionKey:p=>p.id,label:p=>p.name,createLabel:'产品',createHref:'/businessBasics/products?create=1'},global:{plugins:[ElementPlus]}})
|
||||
try{
|
||||
await wrapper.find('.el-select__wrapper').trigger('click');await flushPromises()
|
||||
await wrapper.vm.search('不存在的产品');await flushPromises()
|
||||
expect(wrapper.vm.options).toEqual([{id:7,name:'原产品'}])
|
||||
expect(document.querySelector('.el-select-dropdown').textContent).toContain('没有匹配结果')
|
||||
expect(wrapper.props('modelValue')).toBe(7)
|
||||
expect(wrapper.emitted('update:modelValue')).toBeUndefined()
|
||||
}finally{wrapper.unmount()}
|
||||
})
|
||||
@ -25,7 +25,7 @@ it('successful inventory operations keep a completed summary instead of reportin
|
||||
expect(Operations.computed.resultSummary.call(vm)).toBe('成功 1 项 · 待处理 1 项')
|
||||
})
|
||||
it('confirmed but not arrived purchases allow both prices; arrival locks quote while reference remains editable',()=>{
|
||||
const vm={isEditing:true,saving:false,compactAmounts:false,readonly:Sheet.methods.readonly,fieldLocked:Sheet.methods.fieldLocked,canEditCategory:()=>true}
|
||||
const vm={canViewQuotes:true,isEditing:true,saving:false,compactAmounts:false,readonly:Sheet.methods.readonly,fieldLocked:Sheet.methods.fieldLocked,canEditCategory:()=>true}
|
||||
const row={id:1,purchaseStatus:1,priceLocked:true,acceptedQuantity:0,pendingArrivalQuantity:0,receivedQuantity:0}
|
||||
expect(Sheet.methods.editableCell.call(vm,row,'finalUnitPrice')).toBe(true)
|
||||
expect(Sheet.methods.editableCell.call(vm,row,'actualUnitPrice')).toBe(true)
|
||||
|
||||
@ -0,0 +1,8 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>成本汇总 · 正式布局隔离验证</title><div id="app"></div>
|
||||
<script type="module">
|
||||
if(location.port!=='8091'){document.querySelector('#app').textContent='只在8091隔离服务中验证';}else{
|
||||
const [{createApp,h},{default:ElementPlus},{default:Analysis}]=await Promise.all([import('vue'),import('element-plus'),new URL(location.href).searchParams.has('list')?import('@/views/archive/index.vue'):import('@/views/archive/cost-analysis.vue')]);
|
||||
await import('element-plus/dist/index.css');await import('@/assets/styles/index.scss');await import('@/assets/styles/app.scss');await import('@/assets/styles/business-ui.scss');await import('@/assets/styles/viewport.scss');
|
||||
createApp({render:()=>h('div',{class:'hasTagsView'},[h('aside',{class:'fixture-aside'},'项目资料'),h('div',{class:'main-container'},[h('header',{class:'fixed-header'},'隔离验证 · 使用实际页面样式和滚动容器 · 全部为虚构数据'),h('section',{class:'app-main'},[h('div',{class:'desktop-viewport'},[h(Analysis)])])])])}).use(ElementPlus).mount('#app');
|
||||
}
|
||||
</script><style>html,body,#app{height:100%;margin:0;overflow:hidden}.fixture-aside{position:fixed;inset:0 auto 0 0;width:200px;background:#1c2637;color:#fff;padding:26px;font-size:16px}.main-container{height:100dvh;margin-left:200px}.fixed-header{height:84px;padding:22px 24px;background:#fff4d4;color:#805c16;font-size:13px;border-bottom:1px solid #e7eaf0}.app-main{margin:0!important}.desktop-viewport{width:100%}@media(max-width:700px){.fixture-aside{display:none}.main-container{margin-left:0}}</style></html>
|
||||
29
ruoyi-ui-vue3/tests/unit/date-display.test.mjs
Normal file
29
ruoyi-ui-vue3/tests/unit/date-display.test.mjs
Normal file
@ -0,0 +1,29 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {parseTime} from '../../src/utils/ruoyi.js'
|
||||
import {formatDateTime,displayTimestamp} from '../../src/utils/display-format.js'
|
||||
import {assistantDisplayValue} from '../../src/utils/business-assistant.js'
|
||||
|
||||
test('local API timestamps display without T, milliseconds or timezone suffixes',()=>{
|
||||
for(const value of ['2026-10-26T12:01:54','2026-10-26T12:01:54.123456789','2026-10-26 12:01:54','2026/10/26 12:01:54'])assert.equal(formatDateTime(value),'2026-10-26 12:01:54')
|
||||
assert.equal(formatDateTime('2026-10-26'),'2026-10-26')
|
||||
assert.equal(parseTime('2026-10-26T12:01:54','{y}-{m}-{d}'),'2026-10-26')
|
||||
})
|
||||
test('ISO offsets retain their actual instant while plain dates stay local',()=>{
|
||||
const instant=Date.UTC(2026,9,26,4,1,54)
|
||||
const expected=parseTime(new Date(instant))
|
||||
assert.equal(formatDateTime('2026-10-26T12:01:54.123456+08:00'),expected)
|
||||
assert.equal(formatDateTime('2026-10-26T04:01:54Z'),expected)
|
||||
assert.equal(formatDateTime(instant),expected)
|
||||
assert.equal(formatDateTime(String(instant/1000)),expected)
|
||||
assert.equal(formatDateTime(0),parseTime(new Date(0)))
|
||||
assert.equal(formatDateTime('2024-02-29'),'2024-02-29')
|
||||
})
|
||||
test('missing and invalid values produce a placeholder instead of NaN or a thrown error',()=>{
|
||||
for(const value of [null,undefined,'',' ','not a date','2026-02-30','2026-10-26T25:01:54',new Date(NaN),{},[],true,Symbol('invalid')])assert.equal(formatDateTime(value),'—')
|
||||
})
|
||||
test('generic query values format complete timestamps without changing business text or numbers',()=>{
|
||||
assert.equal(assistantDisplayValue({time:'2026-10-26T12:01:54',quantity:12}),'time:2026-10-26 12:01:54;quantity:12')
|
||||
assert.equal(assistantDisplayValue(['2026-10-26T12:01:54']),'2026-10-26 12:01:54')
|
||||
for(const value of ['版本T1','文件-2026-10-26T12:01:54.txt','2026-10-26',1000])assert.equal(displayTimestamp(value),value)
|
||||
})
|
||||
@ -37,18 +37,18 @@ const {checkForms}=require('./vue3-form-display-check.cjs')
|
||||
const checks=[]
|
||||
for(const viewport of [{width:1366,height:768},{width:1024,height:600}]){
|
||||
await page.setViewportSize(viewport);await page.waitForTimeout(180)
|
||||
checks.push(await page.evaluate(()=>{const stage=document.querySelector('.desktop-viewport'),visible=e=>e.getClientRects().length&&getComputedStyle(e).visibility!=='hidden',box=e=>{const r=e.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right}};return {viewport:[innerWidth,innerHeight],document:[document.documentElement.scrollWidth,document.documentElement.scrollHeight],root:stage?.firstElementChild?.className,rootScroll:stage?.firstElementChild?{height:stage.firstElementChild.clientHeight,scroll:stage.firstElementChild.scrollHeight}:null,tables:[...(stage?.querySelectorAll('div.el-table')||[])].filter(e=>visible(e)&&e.querySelector('.el-table__body-wrapper')).map(e=>({...box(e),columns:[...e.querySelectorAll('.el-table__header th')].map(c=>({text:c.innerText,width:c.getBoundingClientRect().width}))})),headers:[...(stage?.querySelectorAll('.query-toolbar,.business-list-page__header')||[])].filter(visible).map(e=>({...box(e),overflow:e.scrollWidth-e.clientWidth})),loading:[...document.querySelectorAll('.el-loading-mask')].filter(e=>visible(e)&&Number(getComputedStyle(e).opacity)>.1).length}}))
|
||||
checks.push(await page.evaluate(()=>{const stage=document.querySelector('.desktop-viewport'),visible=e=>e.getClientRects().length&&getComputedStyle(e).visibility!=='hidden',box=e=>{const r=e.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right}};return {viewport:[innerWidth,innerHeight],document:[document.documentElement.scrollWidth,document.documentElement.scrollHeight],root:stage?.firstElementChild?.className,rootScroll:stage?.firstElementChild?{height:stage.firstElementChild.clientHeight,scroll:stage.firstElementChild.scrollHeight}:null,tables:[...(stage?.querySelectorAll('div.el-table')||[])].filter(e=>visible(e)&&e.querySelector('.el-table__body-wrapper')).map(e=>{const b=box(e);let lastRowReachable=b.bottom<=innerHeight+1;if(!lastRowReachable){let parent=e.parentElement;while(parent&&!(parent.scrollHeight>parent.clientHeight+1&&/auto|scroll/.test(getComputedStyle(parent).overflowY)))parent=parent.parentElement;if(parent&&box(parent).bottom<=innerHeight+1){const before=parent.scrollTop;parent.scrollTop=parent.scrollHeight;const last=e.querySelector('.el-table__body tbody tr:last-child')||e;lastRowReachable=box(last).bottom<=Math.min(innerHeight,box(parent).bottom)+1;parent.scrollTop=before}}return {...b,lastRowReachable,columns:[...e.querySelectorAll('.el-table__header th')].map(c=>({text:c.innerText,width:c.getBoundingClientRect().width}))}}),headers:[...(stage?.querySelectorAll('.query-toolbar,.business-list-page__header')||[])].filter(visible).map(e=>({...box(e),overflow:e.scrollWidth-e.clientWidth})),loading:[...document.querySelectorAll('.el-loading-mask')].filter(e=>visible(e)&&Number(getComputedStyle(e).opacity)>.1).length}}))
|
||||
await checkControlCells(page,route.title+' '+viewport.width)
|
||||
await checkForms(page,route.title+' '+viewport.width,'.desktop-viewport')
|
||||
if(viewport.width===1366)await page.screenshot({path:path.join(out,route.url.replace(/[^a-zA-Z0-9]/g,'_')+'.png'),animations:'disabled'})
|
||||
}
|
||||
results.push({...route,checks});const issues=checks.flatMap(v=>[...v.tables.filter(t=>t.bottom>v.viewport[1]+1||t.height<80).map(t=>'table '+Math.round(t.height)+'px bottom '+Math.round(t.bottom)),...v.headers.filter(h=>h.overflow>2).map(()=> 'header overflow'),...(v.loading?['loading remains']:[])]);console.log('CHECK',route.title,JSON.stringify(issues))
|
||||
results.push({...route,checks});const issues=checks.flatMap(v=>[...v.tables.filter(t=>!t.lastRowReachable||t.height<80).map(t=>'table '+Math.round(t.height)+'px bottom '+Math.round(t.bottom)),...v.headers.filter(h=>h.overflow>2).map(()=> 'header overflow'),...(v.loading?['loading remains']:[])]);console.log('CHECK',route.title,JSON.stringify(issues))
|
||||
}catch(e){results.push({...route,error:e.message});console.log('FAIL',route.title,e.message.slice(0,120))}
|
||||
}
|
||||
fs.writeFileSync(path.join(out,'result.json'),JSON.stringify({results,errors,warnings},null,2))
|
||||
fs.writeFileSync(path.join(out,'index.html'),'<!doctype html><meta charset="utf-8"><title>全页面复核</title><style>body{font:14px system-ui;background:#f3f5f7;margin:24px;color:#303133}section{padding:16px;margin:20px 0;background:white}h2{font-size:16px}img{width:100%}</style><h1>全页面复核</h1><p>业务写入已拦截;缓存内容和生成配置使用模拟数据。包含菜单页面及隐藏的维护页面。</p>'+results.map(r=>'<section><h2>'+r.title+' · '+r.url+'</h2>'+(r.error?'<p>检查异常</p>':'<img loading="lazy" src="'+r.url.replace(/[^a-zA-Z0-9]/g,'_')+'.png">')+'</section>').join(''))
|
||||
console.log('DONE',JSON.stringify({pages:results.length,failures:results.filter(r=>r.error).length,errors,warnings}))
|
||||
assert.equal(results.filter(r=>r.error).length,0);assert.deepEqual(errors,[]);assert.deepEqual(warnings,[])
|
||||
for(const r of results)for(const check of r.checks){if(!['/monitor/druid','/tool/swagger'].includes(r.url))assert.ok(check.root,r.url+' must mount a visible page');assert.ok(!check.loading,r.url+' leaves a loading mask');check.tables.forEach(t=>assert.ok(t.height>=80&&t.bottom<=check.viewport[1]+1,r.url+' table does not fit'));check.headers.forEach(h=>assert.ok(h.overflow<=2,r.url+' header overflows'))}
|
||||
for(const r of results)for(const check of r.checks){if(!['/monitor/druid','/tool/swagger'].includes(r.url))assert.ok(check.root,r.url+' must mount a visible page');assert.ok(!check.loading,r.url+' leaves a loading mask');check.tables.forEach(t=>assert.ok(t.height>=80&&t.lastRowReachable,r.url+' table does not fit'));check.headers.forEach(h=>assert.ok(h.overflow<=2,r.url+' header overflows'))}
|
||||
}finally{await browser.close()}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1})
|
||||
|
||||
@ -35,9 +35,9 @@ const output=path.resolve(__dirname,'../../.codex-tmp/batch-borrow-regression');
|
||||
await page.getByRole('button',{name:'批量借用',exact:true}).click();const dialog=page.getByRole('dialog',{name:'批量借用',exact:true});await dialog.waitFor();assert.equal(await page.locator('.el-dialog:visible').count(),1)
|
||||
const project=dialog.locator('.el-form-item').filter({has:page.locator('label').filter({hasText:'借入项目'})}).locator('.el-select');await project.click();await page.getByRole('option',{name:'借入项目C',exact:true}).click()
|
||||
assert.equal(await dialog.locator('.borrow-review-table .el-table__body tr').count(),2)
|
||||
const uniform=dialog.locator('.batch-borrow-actions>.el-select');await uniform.click();await page.getByRole('option',{name:'接收库区C',exact:true}).click();await dialog.getByRole('button',{name:'应用',exact:true}).click()
|
||||
const uniform=dialog.locator('.batch-dialog-fieldgroup .el-select');await uniform.click();await page.getByRole('option',{name:'接收库区C',exact:true}).click();await dialog.getByRole('button',{name:'应用库区',exact:true}).click()
|
||||
await dialog.locator('.borrow-review-table .el-input-number input').first().fill('2');await dialog.locator('.el-dialog__header').click()
|
||||
await dialog.locator('.batch-borrow-footer').click();await checkControlCells(page,'批量借用清单')
|
||||
await dialog.locator('.batch-dialog-footer').click();await checkControlCells(page,'批量借用清单')
|
||||
// Full-list validation occurs before any request, not halfway through the batch.
|
||||
// Locate the owning Vue component explicitly; dialog element belongs to ElDialog.
|
||||
await dialog.evaluate(el=>{let instance=el.__vueParentComponent;while(instance&&instance.type.name!=='BatchBorrow')instance=instance.parent;window.batchBorrowVm=instance.proxy;instance.proxy.rows[1].quantity=null})
|
||||
@ -54,7 +54,7 @@ const output=path.resolve(__dirname,'../../.codex-tmp/batch-borrow-regression');
|
||||
await project.click();await page.getByRole('option',{name:'借入项目C',exact:true}).click()
|
||||
await dialog.locator('.el-table__body tr').first().waitFor();await page.waitForTimeout(300)
|
||||
await dialog.locator('.el-table__body tr').first().locator('.el-checkbox').click();await dialog.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForTimeout(300);await dialog.locator('.el-table__body tr').first().locator('.el-checkbox').click()
|
||||
assert.ok((await dialog.locator('.batch-borrow-footer').innerText()).includes('已选 2 项'))
|
||||
assert.ok((await dialog.locator('.batch-dialog-footer').innerText()).includes('已选 2 项'))
|
||||
await dialog.getByRole('button',{name:'上一页',exact:true}).click();await page.waitForTimeout(300);assert.equal(await dialog.locator('.el-table__body .el-checkbox.is-checked').count(),1)
|
||||
await dialog.getByRole('button',{name:'下一步',exact:true}).click();assert.equal(await dialog.locator('.borrow-review-table .el-table__body tr').count(),2)
|
||||
await dialog.getByText('选择库存',{exact:true}).click();await page.waitForTimeout(300);assert.equal(await dialog.locator('.el-table__body .el-checkbox.is-checked').count(),1)
|
||||
|
||||
@ -17,6 +17,7 @@ const { chromium, frontend, backend, username, password } = require('./vue3-test
|
||||
return route.fulfill({ json: failSave ? { code: 500, msg: '模拟保存失败,保留输入' } : { code: 200 } })
|
||||
}
|
||||
if (!['GET', 'HEAD'].includes(req.method())) return route.abort('blockedbyclient')
|
||||
if (path === '/dev-api/project/workspace/capabilities') return route.fulfill({json:{code:200,data:{supported:false}}});
|
||||
if (path === '/dev-api/project/info/990900') return route.fulfill({ json: { code: 200, data: { id: 990900, projectName: '预算回归项目', projectType: 'PRODUCT', totalAmount: 10000, projectStatus: 1 } } })
|
||||
if (path.includes('/overview/990900')) return route.fulfill({ json: { code: 200, data: {} } })
|
||||
if (path === '/dev-api/project/info/990900/budgets') return route.fulfill({ json: failList ? { code: 500, msg: '模拟列表失败' } : { code: 200, data: [] } })
|
||||
|
||||
@ -7,7 +7,7 @@ const files=dir=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirecto
|
||||
const attr=(n,key)=>n.props?.find(p=>p.type===6&&p.name===key)?.value?.content
|
||||
const bound=(n,key)=>n.props?.find(p=>p.type===7&&p.arg?.content===key)?.exp?.content
|
||||
const buttons=new Set(['el-button','el-dropdown'])
|
||||
const interactive=new Set(['el-switch','el-checkbox','el-radio','el-input-number','el-input','el-select','el-date-picker','el-cascader','purchase-cell','item-picker','product-picker','purchase-purpose','item-category-select','remote-picker','supplier-picker'])
|
||||
const interactive=new Set(['el-switch','el-checkbox','el-radio','el-input-number','el-input','el-select','el-date-picker','el-cascader','purchase-cell','item-picker','product-picker','purchase-purpose','item-category-select','remote-picker','supplier-picker','supplier-license-attachment'])
|
||||
const status=new Set(['el-tag','dict-tag','el-progress'])
|
||||
function tags(n,out=new Set()){if(n.type===1)out.add(n.tag);for(const c of n.children||[])tags(c,out);return out}
|
||||
const report={files:0,columns:0,guarded:0,candidates:[],textColumns:0}
|
||||
|
||||
@ -109,11 +109,11 @@ async function setting(page, patch) {
|
||||
await page.locator('.theme-switch-wrapper').click()
|
||||
await page.waitForFunction(() => document.documentElement.classList.contains('dark'))
|
||||
await page.waitForTimeout(750)
|
||||
await page.locator('#header-notice').hover()
|
||||
await page.getByRole('button',{name:'消息中心',exact:true}).click();await page.locator('.message-center').waitFor()
|
||||
await page.waitForTimeout(200)
|
||||
report.dark = await page.evaluate(() => ({
|
||||
tool: getComputedStyle(document.querySelector('.right-menu-item')).color,
|
||||
header: getComputedStyle(document.querySelector('.notice-header')).backgroundColor,
|
||||
header: getComputedStyle(document.querySelector('.message-center')).backgroundColor,
|
||||
light9: getComputedStyle(document.documentElement).getPropertyValue('--el-color-primary-light-9')
|
||||
}))
|
||||
assert.notEqual(report.dark.tool, 'rgb(90, 94, 102)')
|
||||
@ -121,8 +121,8 @@ async function setting(page, patch) {
|
||||
// Historical notice contents were copied deliberately. Check they come from
|
||||
// the current API, rather than treating words in real data as UI branding.
|
||||
const noticeRows=await page.evaluate(async()=>{const {default:request}=await import('/src/utils/request.js');return (await request.get('/system/notice/listTop')).data||[]})
|
||||
assert.deepEqual(await page.locator('.notice-popover .notice-item-title').allTextContents(),noticeRows.map(row=>row.noticeTitle))
|
||||
await page.mouse.move(600, 400)
|
||||
await page.locator('.message-center').locator('.el-radio-button').filter({hasText:'通知公告'}).click();await page.waitForTimeout(200);assert.deepEqual(await page.locator('.message-center .message-title').allTextContents(),noticeRows.map(row=>row.noticeTitle))
|
||||
await page.locator('.message-center .el-drawer__close-btn').click()
|
||||
await page.evaluate(async () => {
|
||||
const { handleThemeStyle } = await import('/src/utils/theme.js')
|
||||
handleThemeStyle(null)
|
||||
@ -191,14 +191,14 @@ async function setting(page, patch) {
|
||||
await ready(page, '/procurement/details')
|
||||
await page.getByRole('button', { name: '新增采购批次', exact: true }).click()
|
||||
const quantityCell = page.locator('.sheet-cell[data-field="quantity"]').first()
|
||||
const quantity = page.locator('.sheet-cell[data-field="quantity"] input').first()
|
||||
await quantityCell.click()
|
||||
const quantity = page.locator('.sheet-cell[data-field="quantity"] input:not(.sheet-keyboard-input)').first()
|
||||
await quantityCell.dblclick()
|
||||
await quantity.fill('9'); await quantity.blur()
|
||||
for (const [name, height, font] of [['紧凑', 24, '12px'], ['宽松', 32, '14px'], ['标准', 28, '13px']]) {
|
||||
await density(page, name)
|
||||
await quantityCell.click()
|
||||
await quantityCell.dblclick()
|
||||
assert.equal(Number(await quantity.inputValue()), 9)
|
||||
await page.locator('.sheet-cell[data-field="unit"]').first().click()
|
||||
await page.locator('.sheet-cell[data-field="unit"]').first().dblclick()
|
||||
const grid = await page.locator('.sheet-grid .el-select__wrapper').first().evaluate(e => ({ height: e.getBoundingClientRect().height, font: getComputedStyle(e).fontSize }))
|
||||
assert.equal(grid.height, height); assert.equal(grid.font, font)
|
||||
}
|
||||
@ -209,7 +209,7 @@ async function setting(page, patch) {
|
||||
assert.equal(await tab.count(), 1)
|
||||
await page.locator('.tags-refresh-btn').click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click()
|
||||
await quantityCell.click()
|
||||
await quantityCell.dblclick()
|
||||
assert.equal(Number(await quantity.inputValue()), 9)
|
||||
await page.locator('.tags-action-dropdown').click()
|
||||
await page.getByRole('menuitem', { name: '全部关闭', exact: true }).click()
|
||||
|
||||
@ -24,10 +24,10 @@ const {chromium,frontend,backend,username,password}=require('./vue3-test-runtime
|
||||
const lists=[['system/config/index.vue','/system/config/list'],['system/dept/index.vue','/system/dept/list'],['system/menu/index.vue','/system/menu/list'],['system/post/index.vue','/system/post/list'],['system/role/index.vue','/system/role/list'],['system/user/index.vue','/system/user/list'],['system/dict/index.vue','/system/dict/type/list'],['system/dict/data.vue','/system/dict/data/list'],['monitor/logininfor/index.vue','/monitor/logininfor/list'],['monitor/online/index.vue','/monitor/online/list'],['monitor/operlog/index.vue','/monitor/operlog/list'],['monitor/job/index.vue','/monitor/job/list'],['monitor/job/log.vue','/monitor/jobLog/list'],['tool/gen/index.vue','/tool/gen/list']]
|
||||
async function navigate(url){await page.evaluate(async url=>{await document.querySelector('#app').__vue_app__.config.globalProperties.$router.push(url)},url);await page.waitForLoadState('networkidle')}
|
||||
await navigate('/project/collaboration')
|
||||
await page.locator('.collaboration-entry').getByText('项目协作功能待接入',{exact:true}).waitFor()
|
||||
assert.equal(await page.locator('.collaboration-entry .project-workspace').count(),0,'independent entry must not restore the removed replacement business UI')
|
||||
await page.reload();await page.locator('.collaboration-entry').getByText('项目协作功能待接入',{exact:true}).waitFor()
|
||||
console.log('PASS independent collaboration menu entry resolves and refreshes without restoring removed business functions')
|
||||
await page.locator('.project-catalog').getByRole('heading',{name:'项目协作',exact:true}).waitFor()
|
||||
assert.equal(await page.locator('.project-catalog .project-workspace').count(),0,'independent entry must not restore the removed replacement business UI')
|
||||
await page.reload();await page.locator('.project-catalog').getByRole('heading',{name:'项目协作',exact:true}).waitFor()
|
||||
console.log('PASS current collaboration catalog resolves and refreshes independently')
|
||||
await page.evaluate(async lists=>{const router=document.querySelector('#app').__vue_app__.config.globalProperties.$router,{default:Layout}=await import('/src/layout/index.vue');for(let i=0;i<lists.length;i++){const component=(await import('/src/views/'+lists[i][0])).default;router.addRoute({path:'/_legacy/'+i,component:Layout,children:[{path:lists[i][0]==='system/dict/data.vue'?':dictId':'',component,meta:{noCache:true}}]})}},lists)
|
||||
for(let i=0;i<lists.length;i++){
|
||||
console.log('CHECK retry',lists[i][0])
|
||||
|
||||
@ -5,9 +5,9 @@ const {chromium,frontend,backend,username,password}=require('./vue3-test-runtime
|
||||
const browser=await chromium.launch()
|
||||
try{
|
||||
const context=await browser.newContext({viewport:{width:1366,height:768}});await context.addCookies([{name:'Admin-Token',value:login.token,url:frontend}])
|
||||
const page=await context.newPage(),errors=[],warnings=[];page.setDefaultTimeout(12000);page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='warning')warnings.push(m.text())})
|
||||
const page=await context.newPage(),errors=[],warnings=[];page.setDefaultTimeout(12000);page.on('pageerror',e=>{errors.push(e.message);console.log('PAGEERROR',e.stack)});page.on('console',m=>{if(m.type()==='warning')warnings.push(m.text())})
|
||||
await page.route('**/dev-api/**',r=>['GET','HEAD'].includes(r.request().method())?r.continue():r.abort('blockedbyclient'))
|
||||
await page.goto(frontend+'/procurement/details');await page.getByRole('button',{name:'新增未组批',exact:true}).click()
|
||||
await page.goto(frontend+'/procurement/details');await page.getByRole('button',{name:'新增未组批',exact:true}).click();await page.locator('.sheet-grid').waitFor()
|
||||
await page.locator('.purchase-sheet').evaluate(async el=>{const vm=el.__vueParentComponent.proxy,item=vm.items.find(i=>i.unit&&i.category),project=vm.projects[0];vm.sheet.rows=Array.from({length:500},(_,i)=>({...vm.emptyRow(),_key:'regression-'+i,productId:item.id,materialName:item.productName,materialBrand:item.brand,materialParams:item.spec,unit:item.unit,category:item.category,projectId:project.id,quantity:i+1,finalUnitPrice:2}));await vm.$nextTick()})
|
||||
await page.waitForTimeout(150)
|
||||
assert.ok(await page.locator('.sheet-grid .el-table__body tbody tr').count()<60)
|
||||
@ -24,18 +24,19 @@ const {chromium,frontend,backend,username,password}=require('./vue3-test-runtime
|
||||
assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.selected.length),2,'selection survives window scroll')
|
||||
await page.locator('.sheet-grid .el-table__header-wrapper .el-checkbox').click();assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.selected.length),500)
|
||||
await page.locator('.sheet-grid .el-table__header-wrapper .el-checkbox').click();assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.selected.length),0)
|
||||
await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy,u=vm.sheet.rows[480].unit;vm.paste({clipboardData:{getData:()=>`9\t${u}\t12\n10\t${u}\t13`},preventDefault(){}},480,'quantity')})
|
||||
await vmEvaluate(async el=>{const vm=el.__vueParentComponent.proxy,u=vm.sheet.rows[480].unit;await vm.activateCell(vm.sheet.rows[480],'quantity');await vm.paste({clipboardData:{getData:()=>`数量\t单位\t报价单价\n9\t${u}\t12\n10\t${u}\t13`},preventDefault(){}},480,'quantity')})
|
||||
await page.getByRole('dialog',{name:'Excel 粘贴预览',exact:true}).getByRole('button',{name:'应用到表格',exact:true}).click();await page.getByRole('dialog',{name:'Excel 粘贴预览',exact:true}).waitFor({state:'hidden'})
|
||||
assert.deepEqual(await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy;return vm.sheet.rows.slice(480,482).map(r=>[r.quantity,r.finalUnitPrice])}),[[9,12],[10,13]])
|
||||
await page.getByRole('button',{name:'撤销',exact:true}).click();assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.sheet.rows[480].quantity),481)
|
||||
await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy;vm.selected=[vm.sheet.rows[10],vm.sheet.rows[11]];vm.remove()});assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.sheet.rows.length),498)
|
||||
await page.getByRole('button',{name:'撤销',exact:true}).click();assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.sheet.rows.length),500)
|
||||
await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy;vm.sheet.rows[420].quantity=42;vm.persistDraft()})
|
||||
const key=await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy;return vm.draftPrefix()+vm.draftId()})
|
||||
assert.equal(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)).format,key),2)
|
||||
assert.equal(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)).format,key),3)
|
||||
await page.locator('.purchase-sheet').evaluate(async(el,key)=>{const vm=el.__vueParentComponent.proxy;vm.sheet=null;vm.editing=false;await vm.restoreDraft(key)},key)
|
||||
assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.sheet.rows[420].quantity),42)
|
||||
assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.sheet.rows.length),500)
|
||||
for(const density of ['紧凑','标准','宽松']){await page.locator('#size-select').click();await page.getByRole('menuitem',{name:density,exact:true}).click();await page.waitForTimeout(100);await vmEvaluate(async el=>{const vm=el.__vueParentComponent.proxy;await vm.activateCell(vm.sheet.rows[499],'quantity')});assert.ok(await page.locator('.sheet-cell[data-row="499"] input').count())}
|
||||
for(const density of ['紧凑','标准','宽松']){await page.locator('#size-select').click();await page.getByRole('menuitem',{name:density,exact:true}).click();await page.waitForTimeout(100);await vmEvaluate(async el=>{const vm=el.__vueParentComponent.proxy;await vm.activateCell(vm.sheet.rows[499],'quantity')});await page.locator('.sheet-cell[data-row="499"] input:not(.sheet-keyboard-input)').waitFor()}
|
||||
console.log('PASS virtual scrolling, last-row editing, cross-window selection/select-all, paste/undo/delete/restore and three densities')
|
||||
const lookupSheet=await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy;return {batch:{id:989001,batchNo:'PC26100001'},rows:vm.sheet.rows.map((r,i)=>({...r,id:989000+i,materialName:'同名规格物品'})),version:'lookup-test'}})
|
||||
await page.route('**/dev-api/warehouse/purchase/sheet/989001',r=>r.fulfill({json:{code:200,data:lookupSheet}}))
|
||||
@ -50,26 +51,14 @@ const {chromium,frontend,backend,username,password}=require('./vue3-test-runtime
|
||||
const gridLayout=()=>vmEvaluate(el=>{const table=el.querySelector('.sheet-table').getBoundingClientRect(),footer=el.querySelector('.sheet-footer').getBoundingClientRect();return {tableHeight:table.height,footerBottom:footer.bottom,height:innerHeight}})
|
||||
for(const [name,density]of [['紧凑','small'],['标准','default'],['宽松','large']]){
|
||||
await page.locator('#size-select').click();await page.getByRole('menuitem',{name,exact:true}).click();await page.waitForTimeout(200)
|
||||
const before=await gridLayout()
|
||||
await page.getByRole('button',{name:'各项目金额',exact:true}).click()
|
||||
const drawer=page.locator('.project-totals-drawer:visible');await drawer.waitFor();await page.waitForTimeout(350)
|
||||
const after=await gridLayout()
|
||||
assert.ok(after.tableHeight>=120&&after.footerBottom<after.height,'main table and save controls fit short viewport: '+JSON.stringify(after))
|
||||
assert.ok(Math.abs(after.tableHeight-before.tableHeight)<2,'opening totals must not shrink the purchase grid')
|
||||
const box=await drawer.boundingBox();assert.ok(box.x>=0&&box.y>=0&&box.x+box.width<=1281&&box.y+box.height<=601,'totals drawer fits viewport')
|
||||
const totalsScroll=drawer.locator('.el-table__body-wrapper .el-scrollbar__wrap')
|
||||
assert.ok(await totalsScroll.evaluate(e=>e.scrollHeight>e.clientHeight),'project totals scroll internally')
|
||||
await totalsScroll.evaluate(e=>{e.scrollTop=e.scrollHeight})
|
||||
const last=await drawer.locator('.el-table__body tbody tr').last().evaluate(e=>{const r=e.getBoundingClientRect(),b=e.closest('.el-table__body-wrapper').getBoundingClientRect();return {top:r.top,bottom:r.bottom,bodyTop:b.top,bodyBottom:b.bottom}})
|
||||
assert.ok(last.top>=last.bodyTop&&last.bottom<=last.bodyBottom+1,'last project total is reachable')
|
||||
const layout=await gridLayout();assert.ok(layout.tableHeight>=120&&layout.footerBottom<layout.height,'table and save controls fit a short viewport: '+JSON.stringify(layout))
|
||||
await vmEvaluate(async el=>{const vm=el.__vueParentComponent.proxy;vm.cellSelection={anchor:{key:vm.sheet.rows[0]._key,field:'quantity'},focus:{key:vm.sheet.rows[24]._key,field:'quantity'}};await vm.$nextTick()});assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.selectionStats.rowCount),25)
|
||||
const stats=await page.locator('.sheet-selection-stats').boundingBox();assert.ok(stats.y+stats.height<=601,'selection totals remain visible at '+density)
|
||||
const scroll=page.locator('.sheet-grid .el-table__body-wrapper .el-scrollbar__wrap');await scroll.evaluate(e=>{e.scrollTop=e.scrollHeight});await page.locator('.sheet-cell[data-row="24"]').first().waitFor();await vmEvaluate(el=>{const vm=el.__vueParentComponent.proxy;vm.selected=[];vm.cellSelection=null})
|
||||
await page.screenshot({path:'.codex-tmp/function-recheck/multi-project-fixed-'+density+'.png'})
|
||||
await drawer.getByRole('button',{name:'关闭',exact:true}).click();await drawer.waitFor({state:'hidden'})
|
||||
}
|
||||
await page.getByRole('button',{name:'各项目金额',exact:true}).click();await page.setViewportSize({width:600,height:800});await page.waitForTimeout(350)
|
||||
const narrowDrawer=page.locator('.project-totals-drawer:visible'),narrowBox=await narrowDrawer.boundingBox();assert.ok(narrowBox.x>=0&&narrowBox.x+narrowBox.width<=601,'totals drawer fits a narrow viewport')
|
||||
await page.screenshot({path:'.codex-tmp/function-recheck/multi-project-fixed-narrow.png'})
|
||||
await narrowDrawer.getByRole('button',{name:'关闭',exact:true}).click();await narrowDrawer.waitFor({state:'hidden'});await page.setViewportSize({width:1366,height:768})
|
||||
console.log('PASS 25 project totals scroll in a responsive drawer without shrinking the purchase table or hiding save controls at any density')
|
||||
await page.setViewportSize({width:1366,height:768})
|
||||
console.log('PASS 25-project table, selection totals and save controls remain reachable in short viewports at all three densities')
|
||||
// Saved-sheet change tracking returns clean after undo, without scanning the whole sheet.
|
||||
await vmEvaluate(async el=>{const vm=el.__vueParentComponent.proxy,rows=vm.sheet.rows.slice(0,2).map((r,i)=>({...r,id:988000+i}));vm.install({unbatched:true,batch:{},rows,deletedIds:[],version:'readonly-test'});vm.startEditing();await vm.activateCell(vm.sheet.rows[0],'quantity')});assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.dirty),false)
|
||||
await page.locator('.sheet-cell[data-row="0"][data-field="quantity"] input').fill('777');await page.locator('.sheet-cell[data-row="0"][data-field="quantity"] input').blur();assert.equal(await vmEvaluate(el=>el.__vueParentComponent.proxy.dirty),true)
|
||||
|
||||
@ -74,7 +74,7 @@ const gate = () => { let release; const promise = new Promise(resolve => { relea
|
||||
const { default: business } = await import('/src/plugins/business.js'), { default: Editor } = await import('/src/components/BomEditor/index.vue')
|
||||
useUser(store).permissions = ['*:*:*']; document.querySelector('#app')?.remove()
|
||||
const el = document.createElement('div'); document.body.append(el)
|
||||
const app = createApp({ render: () => h(Editor, { ref: 'editor' }) }); app.use(store); app.use(ElementPlus); business(app)
|
||||
const app = createApp({ render: () => h(Editor, { ref: 'editor' }) }); app.use(store); app.use(ElementPlus); business(app); app.config.globalProperties.$router=(await import('/src/router/index.js')).default; (await import('/src/store/modules/user.js')).default(store).permissions=['*:*:*']
|
||||
Object.assign(app.config.globalProperties, { $route: { path: '/audit-bom' }, $modal: { msgSuccess() {}, msgWarning() {}, msgError() {} }, download() {} })
|
||||
window.auditBomApp = app; window.auditBomRoot = app.mount(el); await nextTick(); window.editor = window.auditBomRoot.$refs.editor
|
||||
await window.editor.open({ id: 301 })
|
||||
|
||||
@ -69,8 +69,8 @@ const base = process.env.VUE3_URL || 'http://127.0.0.1:8088'
|
||||
}
|
||||
async function editQuantity(value) {
|
||||
await page.getByRole('button', { name: '编辑', exact: true }).click()
|
||||
await page.locator('.sheet-cell[data-field="quantity"]').first().click()
|
||||
const input = page.locator('.sheet-cell[data-field="quantity"] input').first()
|
||||
await page.locator('.sheet-cell[data-field="quantity"]').first().dblclick()
|
||||
const input = page.locator('.sheet-cell[data-field="quantity"] .el-input-number input').first()
|
||||
await input.fill(String(value)); await input.blur()
|
||||
}
|
||||
const batchA = '/procurement/details?purchaseBatchId=991001'
|
||||
@ -86,7 +86,7 @@ const base = process.env.VUE3_URL || 'http://127.0.0.1:8088'
|
||||
await page.evaluate(() => window.__purchaseNavigation)
|
||||
await confirmation.waitFor({ state: 'hidden' })
|
||||
assert.equal(new URL(page.url()).searchParams.get('purchaseBatchId'), '991001')
|
||||
assert.equal(Number(await page.locator('.sheet-cell[data-field="quantity"] input').first().inputValue()), 11)
|
||||
assert.equal(Number(await page.locator('.sheet-cell[data-field="quantity"] .el-input-number input').first().inputValue()), 11)
|
||||
console.log('PASS cancelled query navigation keeps URL, sheet and dirty values together')
|
||||
|
||||
await navigate(batchB)
|
||||
@ -108,7 +108,7 @@ const base = process.env.VUE3_URL || 'http://127.0.0.1:8088'
|
||||
await page.evaluate(() => window.__purchaseNavigation)
|
||||
assert.equal(await confirmation.count(), 0)
|
||||
assert.equal(sheetReads.length, readsBeforeHash)
|
||||
assert.equal(Number(await page.locator('.sheet-cell[data-field="quantity"] input').first().inputValue()), 12)
|
||||
assert.equal(Number(await page.locator('.sheet-cell[data-field="quantity"] .el-input-number input').first().inputValue()), 12)
|
||||
console.log('PASS unrelated query/hash updates preserve editing without reloading')
|
||||
|
||||
await page.getByRole('button', { name: '保存清单', exact: true }).click()
|
||||
@ -160,7 +160,7 @@ const base = process.env.VUE3_URL || 'http://127.0.0.1:8088'
|
||||
await navigate(batchA); await settled(991001)
|
||||
assert.equal(await confirmation.count(), 0)
|
||||
assert.equal(sheetReads.length, readsBeforeDirtyReturn)
|
||||
assert.equal(Number(await page.locator('.sheet-cell[data-field="quantity"] input').first().inputValue()), 13)
|
||||
assert.equal(Number(await page.locator('.sheet-cell[data-field="quantity"] .el-input-number input').first().inputValue()), 13)
|
||||
console.log('PASS returning to a clean sheet refreshes with its filter; an edited sheet is preserved')
|
||||
|
||||
await page.evaluate(() => {
|
||||
@ -178,7 +178,7 @@ const base = process.env.VUE3_URL || 'http://127.0.0.1:8088'
|
||||
})
|
||||
const batchReadsBeforeReturn = batchQueries.length
|
||||
await navigate('/index'); await page.locator('.business-home').waitFor()
|
||||
await navigate('/procurement/details'); await page.locator('.purchase-sheet').waitFor()
|
||||
await Promise.all([page.waitForResponse(r=>r.url().includes('/warehouse/purchase/batch/list')&&new URL(r.url()).searchParams.get('keyword')==='批次筛选'),navigate('/procurement/details')]); await page.locator('.purchase-sheet').waitFor()
|
||||
await page.waitForFunction(() => !document.querySelector('.purchase-sheet').__vueParentComponent.proxy.loading)
|
||||
assert.equal(batchQueries.length, batchReadsBeforeReturn + 1)
|
||||
assert.equal(batchQueries.at(-1).keyword, '批次筛选')
|
||||
|
||||
@ -112,7 +112,7 @@ const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||
await page.goto(frontend + '/procurement/details')
|
||||
await page.getByRole('button', { name: '新增采购批次', exact: true }).waitFor()
|
||||
// Supplier is deliberately absent while preparing the initial list.
|
||||
await page.getByRole('button', { name: '新增采购批次', exact: true }).click()
|
||||
await page.getByRole('button', { name: '新增采购批次', exact: true }).click();await page.locator('.sheet-grid').waitFor()
|
||||
await page.locator('.purchase-sheet').evaluate(el => {
|
||||
const v = el.__vueParentComponent.proxy, item = v.items.find(i => i.unit && i.category)
|
||||
if (!item || !v.projects.length || !v.categories.length) throw Error('Missing reference fixtures')
|
||||
|
||||
@ -46,34 +46,37 @@ const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||
await page.goto(base+'/procurement/details')
|
||||
await page.getByRole('button',{name:'新增采购批次',exact:true}).waitFor()
|
||||
const sheet=code=>page.locator('.purchase-sheet').evaluate((el,code)=>Function('v','return ('+code+')(v)')(el.__vueParentComponent.proxy),code)
|
||||
await page.waitForFunction(()=>!document.querySelector('.purchase-sheet').__vueParentComponent.proxy.loading)
|
||||
const batches=await sheet(`async v=>{v.query.keyword='AUDIT-A';const first=v.loadBatches();v.query.keyword='AUDIT-B';const last=v.loadBatches();await Promise.all([first,last]);return {query:v.query.keyword,batch:v.batches[0].batchName,loading:v.loading}}`)
|
||||
assert.deepEqual(batches,{query:'AUDIT-B',batch:'AUDIT-B',loading:false})
|
||||
await page.getByRole('button',{name:'新增采购批次',exact:true}).click()
|
||||
await page.getByRole('button',{name:'新增采购批次',exact:true}).click();await page.locator('.sheet-grid').waitFor()
|
||||
const validation=await sheet(`async v=>{const good={projectId:v.projects[0].id,expenseCategoryId:v.categories[0].id,materialName:'回归新物品',unit:v.units[0],category:v.dict.type.wms_item_category[0].label,quantity:1};v.sheet.rows=[{...v.emptyRow(),...good,projectId:null},{...v.emptyRow(),...good,materialName:'正常行'},{...v.emptyRow(),...good,materialName:'错误行',finalUnitPrice:-1,category:''}];await v.save();v.onlyInvalid=true;await v.$nextTick();const originalLines=v.visibleRows.map(row=>v.originalIndex(row)+1);await v.focusError(v.rowErrors.find(e=>e.field==='finalUnitPrice'));return {errors:v.rowErrors.length,rows:v.errorKeys.size,originalLines,focused:document.activeElement.closest('.sheet-cell')?.dataset.row}}`)
|
||||
assert.deepEqual(validation,{errors:3,rows:2,originalLines:[1,3],focused:'2'})
|
||||
assert.equal(await page.locator('.cell-invalid').count(),3)
|
||||
assert.equal(await page.locator('.cell-invalid').count(),2)
|
||||
const timings=await sheet(`async v=>{const times=[];v.onlyInvalid=false;v.validationEnabled=false;for(const count of [50,100,200]){const begin=performance.now();v.sheet.rows=Array.from({length:count},(_,i)=>({...v.emptyRow(),projectId:v.projects[0].id,expenseCategoryId:v.categories[0].id,materialName:'性能样例'+i,unit:v.units[0],category:v.dict.type.wms_item_category[0].label,quantity:1}));await v.$nextTick();times.push({rows:count,renderMs:Math.round(performance.now()-begin)});}v.sheet.rows[0].quantity=2;await v.$nextTick();v.baseline=v.serialize(v.sheet);return times}`)
|
||||
console.log('PASS batch latest request; sheet collects all errors, preserves original row numbers and focuses field. Render baseline:',JSON.stringify(timings))
|
||||
|
||||
const cell=field=>page.locator('.sheet-cell[data-row="0"][data-field="'+field+'"]')
|
||||
await cell('quantity').click();await cell('quantity').locator('input').fill('3');await cell('quantity').locator('input').press('Enter')
|
||||
assert.equal(await sheet('v=>document.activeElement.closest(".sheet-cell")?.dataset.field'),'unit')
|
||||
await cell('unit').locator('input').press('Tab')
|
||||
await cell('finalUnitPrice').locator('input').fill('9');await cell('finalUnitPrice').locator('input').press('Tab')
|
||||
assert.equal(await sheet('v=>document.activeElement.closest(".sheet-cell")?.dataset.field'),'projectId')
|
||||
await cell('projectId').locator('input').press('Shift+Tab')
|
||||
assert.equal(await sheet('v=>document.activeElement.closest(".sheet-cell")?.dataset.field'),'finalUnitPrice')
|
||||
await cell('quantity').dblclick();await cell('quantity').locator('input:not(.sheet-keyboard-input)').fill('3');await cell('quantity').locator('input:not(.sheet-keyboard-input)').press('Enter')
|
||||
await page.waitForFunction(()=>document.activeElement.closest('.sheet-cell')?.dataset.row==='1')
|
||||
assert.equal(await sheet('v=>document.activeElement.closest(".sheet-cell")?.dataset.field'),'quantity')
|
||||
await cell('finalUnitPrice').dblclick();await cell('finalUnitPrice').locator('input:not(.sheet-keyboard-input)').fill('9');await cell('finalUnitPrice').locator('input:not(.sheet-keyboard-input)').press('Shift+Tab')
|
||||
await page.waitForFunction(()=>document.activeElement.closest('.sheet-cell')?.dataset.field==='actualUnitPrice')
|
||||
await page.keyboard.press('Tab');await page.waitForFunction(()=>document.activeElement.closest('.sheet-cell')?.dataset.field==='finalUnitPrice')
|
||||
await cell('quantity').click()
|
||||
const pastedUnit=await sheet('v=>v.sheet.rows[0].unit')
|
||||
await cell('quantity').evaluate((el,unit)=>{const data=new DataTransfer();data.setData('text/plain',`2\t${unit}\t3.50\n4\t${unit}\t5.00`);el.dispatchEvent(new ClipboardEvent('paste',{bubbles:true,clipboardData:data}))},pastedUnit)
|
||||
await cell('quantity').evaluate((el,unit)=>{const data=new DataTransfer();data.setData('text/plain',`数量\t单位\t报价单价\n2\t${unit}\t3.50\n4\t${unit}\t5.00`);el.dispatchEvent(new ClipboardEvent('paste',{bubbles:true,clipboardData:data}))},pastedUnit)
|
||||
await page.getByRole('dialog',{name:'Excel 粘贴预览',exact:true}).getByRole('button',{name:'应用到表格',exact:true}).click();await page.getByRole('dialog',{name:'Excel 粘贴预览',exact:true}).waitFor({state:'hidden'})
|
||||
assert.deepEqual(await sheet('v=>v.sheet.rows.slice(0,2).map(r=>[r.quantity,r.finalUnitPrice])'),[[2,3.5],[4,5]])
|
||||
await page.getByRole('button',{name:'撤销',exact:true}).click()
|
||||
assert.deepEqual(await sheet('v=>[v.sheet.rows[0].quantity,v.sheet.rows[0].finalUnitPrice]'),[3,'9'])
|
||||
await cell('materialName').click();await cell('materialName').locator('input').fill('回归目录物品')
|
||||
await cell('materialName').dblclick();await cell('materialName').locator('input').fill('回归目录物品')
|
||||
await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({hasText:/回归目录物品.*甲牌/}).click()
|
||||
await page.waitForFunction(()=>document.querySelector('.purchase-sheet').__vueParentComponent.proxy.items.some(i=>i.id===996002))
|
||||
await cell('materialBrand').click()
|
||||
await cell('materialBrand').dblclick()
|
||||
await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({hasText:/^乙牌$/}).click()
|
||||
assert.deepEqual(await sheet('v=>{const r=v.sheet.rows[0];return [r.productId,r.materialBrand,r.materialParams,r.unit]}'),[null,'乙牌','10型','件'],'changing brand alone must preserve an explicit specification')
|
||||
await cell('materialParams').dblclick();await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({hasText:'20型'}).click()
|
||||
assert.deepEqual(await sheet('v=>{const r=v.sheet.rows[0];return [r.productId,r.materialBrand,r.materialParams,r.unit]}'),[996002,'乙牌','20型','件'])
|
||||
await sheet('v=>{v.baseline=v.serialize(v.sheet)}')
|
||||
console.log('PASS lazy editor keeps Enter/Tab/Shift-Tab, rectangular paste, undo and item/brand/spec auto-fill')
|
||||
|
||||
@ -103,7 +103,7 @@ const { chromium, frontend } = require('./vue3-test-runtime.cjs')
|
||||
const el = document.createElement('div'); el.id = 'flow'; el.style.height = '100vh'; document.body.append(el)
|
||||
const Component = (await import(path)).default
|
||||
const app = createApp({ render: () => h(Component, { ...props, ref: 'child' }) })
|
||||
app.use(store); app.use(ElementPlus); business(app); app.component('Pagination', Pagination)
|
||||
app.use(store); app.use(ElementPlus); business(app); app.config.globalProperties.$router=(await import('/src/router/index.js')).default; (await import('/src/store/modules/user.js')).default(store).permissions=['*:*:*']; app.component('Pagination', Pagination)
|
||||
Object.assign(app.config.globalProperties, { $route: { path: '/flow', fullPath: '/flow', query: {} }, parseTime: () => '2026-10-14', $auth: { hasPermi: () => true }, $modal: { msgSuccess: text => window.messages.push(text), msgWarning: text => window.messages.push(text), msgError: text => window.messages.push(text), confirm: (...args) => app.config.globalProperties.$confirm(...args) }, download() {} })
|
||||
window.flowApp = app; window.flowRoot = app.mount(el); await nextTick(); window.vm = window.flowRoot.$refs.child
|
||||
}
|
||||
@ -114,7 +114,7 @@ const { chromium, frontend } = require('./vue3-test-runtime.cjs')
|
||||
await page.getByRole('button', { name: '新增', exact: true }).click()
|
||||
await page.locator('.el-dialog:visible .el-select').click()
|
||||
await page.locator('.el-select-dropdown:visible .el-select-dropdown__item').filter({ hasText: item.productName }).click()
|
||||
await page.evaluate(() => { window.vm.save(); window.vm.save() })
|
||||
await page.locator('.el-dialog:visible .el-form-item').filter({hasText:'产品版本'}).locator('input').fill('回归验证版');await page.evaluate(() => { window.vm.save(); window.vm.save() })
|
||||
await page.waitForFunction(()=>!window.vm.saving)
|
||||
assert.equal(await page.evaluate(()=>window.vm.open&&window.vm.form.itemId===900),true)
|
||||
await page.evaluate(() => { window.vm.save(); window.vm.save() })
|
||||
|
||||
@ -53,7 +53,7 @@ const checkControlCells=require('./vue3-cell-overflow-check.cjs')
|
||||
const el=document.createElement('div');el.id='audit';document.body.append(el)
|
||||
const Component=(await import(path)).default
|
||||
const app=createApp({data:()=>({value:null}),render(){return h(Component,{...props,ref:'child',...(Component.props?.modelValue?{modelValue:this.value,'onUpdate:modelValue':value=>this.value=value}:{})})}})
|
||||
app.use(store);app.use(ElementPlus);business(app);app.component('Pagination',Pagination)
|
||||
app.use(store);app.use(ElementPlus);business(app);app.config.globalProperties.$router=(await import('/src/router/index.js')).default;app.component('Pagination',Pagination)
|
||||
Object.assign(app.config.globalProperties,{$route:{path:'/production/bom',fullPath:'/production/bom',query:{}},parseTime:()=> '2026-10-13',$modal:{msgSuccess(){},msgWarning(){},msgError(){}},download(){}})
|
||||
window.auditApp=app;window.auditRoot=app.mount(el);await nextTick();window.auditVm=window.auditRoot.$refs.child;return true
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ const {chromium,frontend,backend,username,password}=require('./vue3-test-runtime
|
||||
const context=await browser.newContext({viewport:{width:1366,height:768}});await context.addCookies([{name:'Admin-Token',value:login.token,url:frontend}]);const page=await context.newPage();page.setDefaultTimeout(12000);page.on('pageerror',e=>errors.push(e.message))
|
||||
await page.route('**/dev-api/**',async route=>{
|
||||
const r=route.request(),p=new URL(r.url()).pathname.replace('/dev-api',''),m=r.method(),ok=data=>route.fulfill({json:{code:200,data}})
|
||||
if(p==='/project/workspace/capabilities')return ok({supported:false});
|
||||
if(p==='/project/info/list')return route.fulfill({json:{code:200,rows:project?[project]:[],total:project?1:0}})
|
||||
if(p==='/project/info'&&['POST','PUT'].includes(m)){writes.push({path:p,method:m,data:r.postDataJSON()});saveAttempts++;await new Promise(r=>setTimeout(r,120));if(saveAttempts===1)return route.fulfill({json:{code:500,msg:'模拟保存失败,请重试'}});project={...r.postDataJSON(),id:910001,projectCode:'XM26100001',version:saveAttempts,spentAmount:0,availableAmount:r.postDataJSON().totalAmount};return ok(1)}
|
||||
if(p==='/project/info/910001')return detailFailed?route.fulfill({json:{code:500,msg:'模拟项目加载失败'}}):ok(project)
|
||||
@ -19,18 +20,19 @@ const {chromium,frontend,backend,username,password}=require('./vue3-test-runtime
|
||||
})
|
||||
await page.goto(frontend+'/project/info');await page.getByRole('button',{name:'新增项目',exact:true}).click()
|
||||
let dialog=page.locator('.el-dialog:visible').last()
|
||||
await dialog.getByRole('button',{name:'确定',exact:true}).click();await dialog.locator('.el-form-item__error').waitFor();assert.equal(writes.length,0)
|
||||
await dialog.locator('.el-form-item').filter({hasText:'项目名称'}).locator('input').fill('完整流程模拟项目')
|
||||
await dialog.getByRole('button',{name:'确定',exact:true}).click();await dialog.locator('.el-form-item__error').first().waitFor();assert.equal(writes.length,0)
|
||||
await dialog.locator('.el-form-item').filter({hasText:'项目编号'}).locator('input').fill('AUDIT-PROJECT-20261027');await dialog.locator('.el-form-item').filter({hasText:'项目名称'}).locator('input').fill('完整流程模拟项目')
|
||||
await dialog.locator('.el-form-item').filter({hasText:'总金额'}).locator('input').fill('12000')
|
||||
await dialog.getByRole('button',{name:'确定',exact:true}).click();await page.getByText('模拟保存失败,请重试',{exact:true}).waitFor();assert.equal(await dialog.locator('.el-form-item').filter({hasText:'项目名称'}).locator('input').inputValue(),'完整流程模拟项目')
|
||||
await dialog.getByRole('button',{name:'确定',exact:true}).click();await dialog.waitFor({state:'hidden'});assert.equal(saveAttempts,2);assert.equal(project.totalAmount,12000)
|
||||
console.log('PASS project required fields, failed-save retention, immediate retry and generated code')
|
||||
console.log('PASS project required fields, failed-save retention, immediate retry and explicit project code')
|
||||
await page.getByText('完整流程模拟项目',{exact:true}).click();await page.getByText('模拟项目加载失败',{exact:true}).last().waitFor();detailFailed=false;await page.getByRole('button',{name:'重试',exact:true}).click();await page.getByText('未到齐采购 2 条',{exact:true}).waitFor()
|
||||
await page.locator('.el-message').last().waitFor({state:'hidden'});await page.screenshot({path:path.join(out,'project-overview.png')});assert.equal(await page.getByRole('tab',{name:'分类预算',exact:true}).count(),1)
|
||||
await page.getByRole('button',{name:'返回列表',exact:true}).click();await page.locator('.el-table__body .el-button').filter({hasText:'更多'}).click();await page.getByRole('menuitem',{name:'修改',exact:true}).click()
|
||||
dialog=page.locator('.el-dialog:visible').last();await dialog.locator('.el-form-item').filter({hasText:'项目状态'}).locator('.el-select').click();await page.locator('.el-select-dropdown:visible').getByText('结题',{exact:true}).click();await dialog.getByRole('button',{name:'确定',exact:true}).click();await page.getByText('结题前核对',{exact:true}).waitFor();assert.ok((await page.locator('.el-message-box').innerText()).includes('后续仍可继续处理'));await page.getByRole('button',{name:'返回检查',exact:true}).click();assert.equal(saveAttempts,2)
|
||||
await dialog.getByRole('button',{name:'确定',exact:true}).click();await page.getByRole('button',{name:'确认保存',exact:true}).click();await dialog.waitFor({state:'hidden'});assert.equal(project.projectStatus,2)
|
||||
console.log('PASS project closing enumerates unfinished work; cancel has no mutation; confirmed closing only changes project state')
|
||||
dialog=page.locator('.el-dialog:visible').last();assert.equal(await dialog.locator('.el-form-item').filter({hasText:'项目状态'}).locator('input').isDisabled(),true)
|
||||
await dialog.locator('.el-form-item').filter({hasText:'备注'}).locator('textarea').fill('超级管理员维护无经理历史项目')
|
||||
await dialog.getByRole('button',{name:'确定',exact:true}).click();await dialog.waitFor({state:'hidden'});assert.equal(saveAttempts,3);assert.equal(project.projectStatus,0);assert.equal(project.remark,'超级管理员维护无经理历史项目')
|
||||
console.log('PASS root administrator edits a managerless project; ordinary edit keeps lifecycle status read-only')
|
||||
await page.evaluate(async()=>{const r=document.querySelector('#app').__vue_app__.config.globalProperties.$router,{default:Layout}=await import('/src/layout/index.vue'),{default:Edit}=await import('/src/views/tool/gen/editTable.vue');r.addRoute({path:'/_project-flow',component:Layout,children:[{path:'gen/:tableId',component:Edit}]});await r.push('/_project-flow/gen/990003')})
|
||||
await page.locator('.gen-edit-page .el-alert').waitFor();assert.equal(await page.getByRole('button',{name:'提交',exact:true}).isDisabled(),true);genFailed=false;await page.getByRole('button',{name:'重试',exact:true}).click();await page.locator('.gen-edit-page .el-alert').waitFor({state:'hidden'});await page.locator('.gen-edit-footer button:not([disabled])').filter({hasText:'提交'}).waitFor();assert.equal(await page.getByRole('button',{name:'提交',exact:true}).isEnabled(),true)
|
||||
console.log('PASS missing generation config shows retry and blocks empty submission')
|
||||
|
||||
@ -38,7 +38,7 @@ const output=path.resolve(__dirname,'../../.codex-tmp/purchase-queues-regression
|
||||
const rows=()=>page.locator('.sheet-grid .el-table__body tr'),queue=label=>page.locator('.sheet-queues .el-radio-button').filter({hasText:new RegExp('^'+label+'\\s')})
|
||||
await rows().first().waitFor();assert.equal(await rows().count(),9)
|
||||
await queue('待报价').click();assert.equal(await rows().count(),2)
|
||||
await page.getByRole('button',{name:'录入报价',exact:true}).click();await page.locator('.sheet-cell[data-field="finalUnitPrice"] input:visible').fill('5')
|
||||
await page.getByRole('button',{name:'编辑',exact:true}).click();await page.locator('.sheet-cell[data-field="finalUnitPrice"]').first().dblclick();await page.locator('.sheet-cell[data-field="finalUnitPrice"] input:visible').fill('5')
|
||||
assert.equal(await rows().count(),2,'quoting must not remove the actively edited row')
|
||||
await page.getByRole('button',{name:'保存清单',exact:true}).click();await until(()=>assert.equal(writes.length,1));await until(async()=>assert.equal(await rows().count(),1))
|
||||
assert.equal(writes[0].data.rows.find(r=>r.id===998001).finalUnitPrice,5)
|
||||
@ -50,9 +50,9 @@ const output=path.resolve(__dirname,'../../.codex-tmp/purchase-queues-regression
|
||||
await page.getByRole('button',{name:'重置',exact:true}).click()
|
||||
await page.getByRole('button',{name:'回填供应商报价',exact:true}).click();const importer=page.getByRole('dialog',{name:'供应商询价与报价回填',exact:true});await importer.waitFor();assert.ok((await importer.textContent()).includes('供应商填写黄色报价栏'))
|
||||
await importer.locator('input[type=file]').setInputFiles({name:'mock.xlsx',mimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',buffer:Buffer.from('mock preview intercepted')})
|
||||
const preview=importer;await preview.getByText('当前批次找不到该物品',{exact:true}).waitFor();await preview.getByRole('checkbox',{name:'仅回填校验通过项,异常项保留原报价',exact:true}).check();await preview.getByRole('button',{name:'回填有效报价(1 项)',exact:true}).click()
|
||||
const price=page.locator('.sheet-cell[data-row="1"][data-field="finalUnitPrice"]');await price.click();assert.equal(await price.locator('input').inputValue(),'9.5');assert.equal(writes.filter(w=>w.endpoint==='/warehouse/purchase/sheet').length,1,'import preview does not auto-save')
|
||||
await page.getByRole('button',{name:'取消编辑',exact:true}).click();await page.locator('.el-message-box').getByRole('button',{name:'确定',exact:true}).click()
|
||||
const preview=importer;await preview.getByText('当前批次找不到该物品',{exact:true}).waitFor();await preview.locator('.el-checkbox').filter({hasText:'仅回填校验通过项,异常项保留原报价'}).click();await preview.getByRole('button',{name:'回填有效报价(1 项)',exact:true}).click()
|
||||
const price=page.locator('.sheet-cell[data-row="1"][data-field="finalUnitPrice"]');await price.dblclick();assert.equal(await price.locator('input:not(.sheet-keyboard-input)').inputValue(),'9.5');assert.equal(writes.filter(w=>w.endpoint==='/warehouse/purchase/sheet').length,1,'import preview does not auto-save')
|
||||
await page.getByRole('button',{name:'取消编辑',exact:true}).click();await page.locator('.el-message-box').getByRole('button',{name:'放弃修改',exact:true}).click()
|
||||
await page.screenshot({path:path.join(output,'queues.png'),animations:'disabled'})
|
||||
await page.goto(frontend+'/procurement/arrival',{waitUntil:'domcontentloaded'});await page.locator('.business-list-page .el-table__body tr').first().waitFor()
|
||||
await page.getByRole('button',{name:'选择待到货项',exact:true}).click();await page.getByText('已选 13 项 · 全部筛选页',{exact:true}).waitFor();assert.equal(await page.locator('.el-table__body .el-checkbox.is-checked').count(),10,'visible checkboxes must reflect cross-page selection')
|
||||
|
||||
@ -31,7 +31,7 @@ fs.mkdirSync(output,{recursive:true})
|
||||
assert.ok(routes.includes('/warehouse/pending')&&routes.includes('/procurement/details'))
|
||||
for(const route of routes) {
|
||||
console.log('CHECK '+route);await ready(page,route)
|
||||
assert.equal(await page.locator('.desktop-viewport .el-button:visible').filter({hasText:/^导出/}).count(),0,route+' export entry')
|
||||
assert.equal(await page.locator('.desktop-viewport .el-button:visible').filter({hasText:/^导出/}).count(),route==='/procurement/details'?1:0,route+' export entry')
|
||||
assert.equal(await page.locator('.top-right-btn .el-button.is-circle:visible').filter({has:page.locator('[data-icon="Search"]')}).count(),0)
|
||||
const toolbars=page.locator('.desktop-viewport .top-right-btn:visible')
|
||||
for(let n=0;n<await toolbars.count();n++)assert.ok(await toolbars.nth(n).evaluate(el=>!!el.closest('.el-form--inline')),route+' refresh belongs to filters')
|
||||
@ -65,7 +65,7 @@ fs.mkdirSync(output,{recursive:true})
|
||||
await page.locator('.business-list-page__table .el-table__body tr').filter({has:page.locator('.el-checkbox:not(.is-disabled)')}).first().locator('.el-checkbox').click()
|
||||
await page.getByRole('button',{name:'批量操作',exact:true}).click()
|
||||
const dialog=page.locator('.stock-batch-dialog:visible');await dialog.waitFor()
|
||||
assert.equal(await dialog.locator('.el-dialog__title').textContent(),'批量操作')
|
||||
assert.equal(await dialog.locator('.el-dialog__title').textContent(),'批量库存操作')
|
||||
const operation=dialog.locator('.el-form-item').filter({hasText:'操作'}).first().locator('.el-select')
|
||||
assert.ok((await operation.boundingBox()).width>=200,'operation label must fit')
|
||||
assert.ok((await operation.innerText()).includes('项目领用'))
|
||||
@ -75,7 +75,7 @@ fs.mkdirSync(output,{recursive:true})
|
||||
await dialog.getByRole('button',{name:'关闭',exact:true}).click();await page.locator('.stock-batch-dialog').waitFor({state:'hidden'})
|
||||
// New procurement draft: native editing controls only; no persistence or server writes.
|
||||
await ready(page,'/procurement/details');await page.getByRole('button',{name:'新增采购批次',exact:true}).click()
|
||||
const cell=page.locator('.sheet-cell[data-field="projectId"]').first();await cell.click();const select=cell.locator('.el-select');await select.waitFor()
|
||||
await page.locator('.sheet-grid').waitFor();const cell=page.locator('.batch-form .el-form-item').filter({hasText:'所属项目'});const select=cell.locator('.el-select');await select.waitFor();await select.click()
|
||||
assert.ok((await select.boundingBox()).width>=185,'project selection width')
|
||||
assert.equal(await cell.evaluate(el=>getComputedStyle(el).outlineStyle),'none','active cell must not add another blue outline')
|
||||
await select.locator('input').focus();assert.equal(await select.locator('input').evaluate(el=>getComputedStyle(el).outlineStyle),'none')
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user