feat(mobile): 优化移动端界面和功能
- 添加移动工作空间对话框全屏样式支持 - 更新应用主视图以支持桌面视口布局 - 重构Excel导入对话框增加预览和校验功能 - 在移动端主页增加生产与交付模块和项目借还功能 - 移动端库存列表显示项目名称和成品标识 - 增加入库记录批量操作和撤销功能 - 优化分页组件在桌面视口中的滚动行为 - 更新路由配置和数据库连接配置 - 调整仓库领域模型移除预期日期字段 - 优化智能代理服务的正则匹配和出库类型处理
This commit is contained in:
parent
4bf9d95a73
commit
ca1f5a27f9
8
.gitignore
vendored
8
.gitignore
vendored
@ -73,6 +73,14 @@ ruoyi-ui/yarn-error.log*
|
||||
# Local environment overrides may contain database credentials.
|
||||
/ruoyi-admin/src/main/resources/application-test.yml
|
||||
|
||||
# Local inspection output and development logs are not source files.
|
||||
/.codex-tmp/
|
||||
/android-app/.gradle/
|
||||
/android-app/app/build/
|
||||
/android-app/build/
|
||||
/android-app/app/src/main/assets/web.zip
|
||||
/android-app/local.properties
|
||||
|
||||
!*/build/*.java
|
||||
!*/build/*.html
|
||||
!*/build/*.xml
|
||||
|
||||
9
android-app/app/build.gradle
Normal file
9
android-app/app/build.gradle
Normal file
@ -0,0 +1,9 @@
|
||||
plugins { id 'com.android.application' }
|
||||
android {
|
||||
namespace 'cn.cmvr.projectwarehouse'
|
||||
compileSdk 35
|
||||
defaultConfig { applicationId 'cn.cmvr.projectwarehouse'; minSdk 26; targetSdk 35; versionCode 3; versionName '1.2.0' }
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
buildTypes { release { minifyEnabled false } }
|
||||
}
|
||||
dependencies { testImplementation 'junit:junit:4.13.2' }
|
||||
9
android-app/app/src/main/AndroidManifest.xml
Normal file
9
android-app/app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,9 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<application android:label="项目物资管理" android:theme="@android:style/Theme.Material.Light.NoActionBar" android:usesCleartextTraffic="true" android:allowBackup="false" android:supportsRtl="true" android:enableOnBackInvokedCallback="true">
|
||||
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize|keyboardHidden" android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@ -0,0 +1,56 @@
|
||||
package cn.cmvr.projectwarehouse;
|
||||
|
||||
import android.content.Context;
|
||||
import org.json.JSONObject;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
/** A downloaded bundle only becomes active on the next launch; the packaged version is always retained. */
|
||||
final class BundleStore {
|
||||
private final Context context;
|
||||
private final File root;
|
||||
BundleStore(Context context){this.context=context;root=new File(context.getFilesDir(),"web-bundles");root.mkdirs();}
|
||||
File activate()throws Exception{
|
||||
byte[] packagedBytes;try(var input=context.getAssets().open("web.zip")){packagedBytes=read(input,100*1024*1024);}
|
||||
String packagedVersion="packaged-"+digest(packagedBytes).substring(0,24);File packaged=folder(packagedVersion);
|
||||
if(!new File(packaged,"index.html").isFile())extract(new ByteArrayInputStream(packagedBytes),packaged);
|
||||
var prefs=context.getSharedPreferences("application",0);
|
||||
String origin=prefs.getString("server","");
|
||||
if(!origin.equals(prefs.getString("bundleOrigin","")))prefs.edit().putString("bundleOrigin",origin).putString("activeBundle",packagedVersion).remove("pendingBundle").remove("trialBundle").remove("previousBundle").commit();
|
||||
// A native reinstall carries its own current web bundle, not an obsolete cached packaged-1 folder.
|
||||
if(!packagedVersion.equals(prefs.getString("packagedVersion","")))prefs.edit().putString("packagedVersion",packagedVersion).putString("activeBundle",packagedVersion).remove("pendingBundle").remove("trialBundle").remove("previousBundle").commit();
|
||||
if(prefs.contains("trialBundle"))rollback();
|
||||
String pending=prefs.getString("pendingBundle",null);
|
||||
if(pending!=null){File candidate=folder(pending);if(new File(candidate,"index.html").isFile())prefs.edit().putString("previousBundle",prefs.getString("activeBundle",packagedVersion)).putString("trialBundle",pending).putString("activeBundle",pending).remove("pendingBundle").commit();}
|
||||
String active=prefs.getString("activeBundle",packagedVersion);File result=folder(active);return new File(result,"index.html").isFile()?result:packaged;
|
||||
}
|
||||
boolean trial(){return context.getSharedPreferences("application",0).contains("trialBundle");}
|
||||
void healthy(){context.getSharedPreferences("application",0).edit().remove("trialBundle").remove("previousBundle").apply();}
|
||||
void rollback(){var prefs=context.getSharedPreferences("application",0);prefs.edit().putString("activeBundle",prefs.getString("previousBundle",prefs.getString("packagedVersion","packaged-1"))).remove("trialBundle").remove("previousBundle").remove("pendingBundle").commit();}
|
||||
static String digest(byte[] bytes)throws Exception{byte[] hash=MessageDigest.getInstance("SHA-256").digest(bytes);StringBuilder actual=new StringBuilder();for(byte b:hash)actual.append(String.format(Locale.ROOT,"%02x",b));return actual.toString();}
|
||||
void check(String origin){new Thread(()->{try{
|
||||
HttpURLConnection manifest=connection(new URL(origin+"/mobile-update.json"));String json;try(InputStream input=manifest.getInputStream()){json=new String(read(input,1024*32),StandardCharsets.UTF_8);}finally{manifest.disconnect();}
|
||||
JSONObject info=new JSONObject(json);String version=info.getString("version"),expected=info.getString("sha256").toLowerCase(Locale.ROOT);
|
||||
int nativeVersion=context.getPackageManager().getPackageInfo(context.getPackageName(),0).versionCode;
|
||||
if(!version.matches("[A-Za-z0-9_-]{1,80}")||version.startsWith("packaged-")||!expected.matches("[a-f0-9]{64}")||info.optInt("minimumNativeVersion",1)>nativeVersion)return;
|
||||
var prefs=context.getSharedPreferences("application",0);if(version.equals(prefs.getString("activeBundle",""))||version.equals(prefs.getString("pendingBundle","")))return;
|
||||
URL zipUrl=new URL(new URL(origin+"/"),info.getString("url"));if(!sameOrigin(new URL(origin),zipUrl))return;
|
||||
HttpURLConnection download=connection(zipUrl);byte[] bytes;try(InputStream input=download.getInputStream()){bytes=read(input,100*1024*1024);}finally{download.disconnect();}
|
||||
if(!expected.equals(digest(bytes)))return;
|
||||
File candidate=folder(version);extract(new ByteArrayInputStream(bytes),candidate);if(new File(candidate,"index.html").isFile()&&origin.equals(prefs.getString("server","")))prefs.edit().putString("pendingBundle",version).apply();
|
||||
}catch(Exception ignored){/* Current version remains usable; the next launch retries. */}},"page-update").start();}
|
||||
private File folder(String name)throws IOException{if(!name.matches("[A-Za-z0-9_-]{1,80}"))throw new IOException("Invalid bundle version");return new File(root,name);}
|
||||
static HttpURLConnection connection(URL url)throws IOException{var connection=(HttpURLConnection)url.openConnection();connection.setConnectTimeout(10000);connection.setReadTimeout(30000);connection.setInstanceFollowRedirects(false);return connection;}
|
||||
static boolean sameOrigin(URL a,URL b){return a.getProtocol().equals(b.getProtocol())&&a.getHost().equals(b.getHost())&&port(a)==port(b);}
|
||||
private static int port(URL u){return u.getPort()<0?u.getDefaultPort():u.getPort();}
|
||||
static byte[] read(InputStream input,int limit)throws IOException{var output=new ByteArrayOutputStream();byte[] buffer=new byte[8192];int count;while((count=input.read(buffer))!=-1){if(output.size()+count>limit)throw new IOException("Content too large");output.write(buffer,0,count);}return output.toByteArray();}
|
||||
static void extract(InputStream input,File directory)throws IOException{
|
||||
directory.mkdirs();String prefix=directory.getCanonicalPath()+File.separator;long total=0;int entries=0;
|
||||
try(var zip=new ZipInputStream(input)){ZipEntry entry;byte[] buffer=new byte[8192];while((entry=zip.getNextEntry())!=null){if(++entries>10000)throw new IOException("Too many files");File file=new File(directory,entry.getName());if(!file.getCanonicalPath().startsWith(prefix))throw new IOException("Invalid bundle path");if(entry.isDirectory()){file.mkdirs();continue;}file.getParentFile().mkdirs();try(var output=new FileOutputStream(file)){int n;while((n=zip.read(buffer))!=-1){total+=n;if(total>200L*1024*1024)throw new IOException("Bundle too large");output.write(buffer,0,n);}}}}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
package cn.cmvr.projectwarehouse;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Color;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
|
||||
/** Edge-swipe fallback for devices that do not provide predictive-back progress. */
|
||||
final class EdgeBackLayout extends FrameLayout {
|
||||
interface Listener { void onBack(); }
|
||||
private final Listener listener;
|
||||
private final TextView indicator;
|
||||
private final int edgeWidth;
|
||||
private final int touchSlop;
|
||||
private View content;
|
||||
private float downX, downY;
|
||||
private boolean eligible, dragging;
|
||||
|
||||
EdgeBackLayout(Context context, Listener listener) {
|
||||
super(context);
|
||||
this.listener = listener;
|
||||
edgeWidth = dp(28);
|
||||
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
|
||||
setClipChildren(false);
|
||||
indicator = new TextView(context);
|
||||
indicator.setText("‹");
|
||||
indicator.setTextSize(34);
|
||||
indicator.setTextColor(Color.WHITE);
|
||||
indicator.setGravity(Gravity.CENTER);
|
||||
indicator.setBackgroundColor(0xcc185bb4);
|
||||
indicator.setAlpha(0f);
|
||||
indicator.setVisibility(INVISIBLE);
|
||||
LayoutParams marker = new LayoutParams(dp(44), dp(56), Gravity.START | Gravity.CENTER_VERTICAL);
|
||||
marker.leftMargin = dp(8);
|
||||
addView(indicator, marker);
|
||||
}
|
||||
|
||||
void setContent(View view) {
|
||||
if (content != null) removeView(content);
|
||||
content = view;
|
||||
addView(content, 0, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
|
||||
}
|
||||
|
||||
@Override public boolean onInterceptTouchEvent(android.view.MotionEvent event) {
|
||||
switch (event.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
downX = event.getX(); downY = event.getY();
|
||||
eligible = downX <= edgeWidth; dragging = false;
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (eligible) {
|
||||
float dx = event.getX() - downX, dy = Math.abs(event.getY() - downY);
|
||||
if (dx > touchSlop && dx > dy * 1.25f) { dragging = true; return true; }
|
||||
if (dy > touchSlop && dy > Math.abs(dx)) eligible = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override public boolean onTouchEvent(MotionEvent event) {
|
||||
if (!dragging) return false;
|
||||
float distance = Math.max(0, event.getX() - downX);
|
||||
if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
|
||||
float progress = Math.min(1f, distance / Math.max(dp(120), getWidth() * .28f));
|
||||
content.setTranslationX(dp(52) * progress);
|
||||
content.setScaleX(1f - .025f * progress);
|
||||
content.setScaleY(1f - .025f * progress);
|
||||
indicator.setVisibility(VISIBLE);
|
||||
indicator.setAlpha(.25f + .75f * progress);
|
||||
indicator.setTranslationX(dp(10) * progress);
|
||||
return true;
|
||||
}
|
||||
if (event.getActionMasked() == MotionEvent.ACTION_UP || event.getActionMasked() == MotionEvent.ACTION_CANCEL) {
|
||||
boolean commit = event.getActionMasked() == MotionEvent.ACTION_UP && distance >= Math.max(dp(72), getWidth() * .20f);
|
||||
reset(commit);
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void reset(boolean commit) {
|
||||
long duration = commit ? 90 : 160;
|
||||
content.animate().translationX(0).scaleX(1).scaleY(1).setDuration(duration).start();
|
||||
indicator.animate().alpha(0).translationX(0).setDuration(duration).withEndAction(() -> indicator.setVisibility(INVISIBLE)).start();
|
||||
if (commit) { performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); postDelayed(listener::onBack, duration); }
|
||||
eligible = false; dragging = false;
|
||||
}
|
||||
|
||||
private int dp(int value) { return Math.round(value * getResources().getDisplayMetrics().density); }
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
package cn.cmvr.projectwarehouse;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** Loopback-only transport for packaged pages and the configured application's API. */
|
||||
final class LocalWebServer implements Closeable {
|
||||
private final File bundle;
|
||||
private final String origin;
|
||||
private final ServerSocket server;
|
||||
private final ExecutorService workers=Executors.newFixedThreadPool(8);
|
||||
private volatile boolean stopped;
|
||||
LocalWebServer(File bundle,String origin)throws IOException{this.bundle=bundle;this.origin=origin;server=new ServerSocket();server.setReuseAddress(true);server.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"),49180));}
|
||||
void start(){new Thread(()->{while(!stopped)try{Socket socket=server.accept();workers.execute(()->handle(socket));}catch(IOException ignored){}},"app-loopback").start();}
|
||||
private void handle(Socket socket){try(socket){try{serve(socket);}catch(Exception failure){respond(socket.getOutputStream(),503,"application/json","{\"code\":503,\"msg\":\"连接失败,本次操作未确认成功,请检查网络后刷新\"}".getBytes(StandardCharsets.UTF_8));}}catch(IOException ignored){}}
|
||||
private void serve(Socket socket)throws IOException{socket.setSoTimeout(30000);var input=new BufferedInputStream(socket.getInputStream());String first=line(input);if(first==null)return;String[] parts=first.split(" ",3);if(parts.length!=3)return;String method=parts[0],target=parts[1];if(!target.startsWith("/"))throw new IOException("Invalid target");Map<String,String> headers=new LinkedHashMap<>();String header;while((header=line(input))!=null&&!header.isEmpty()){int colon=header.indexOf(':');if(colon>0)headers.put(header.substring(0,colon).trim().toLowerCase(Locale.ROOT),header.substring(colon+1).trim());if(headers.size()>100)throw new IOException("Too many headers");}
|
||||
if(!"127.0.0.1:49180".equals(headers.get("host")))throw new IOException("Unexpected host");
|
||||
if(target.startsWith("/prod-api/")){proxy(method,target.substring(9),headers,input,socket.getOutputStream());return;}
|
||||
if(!"GET".equals(method)&&!"HEAD".equals(method)){respond(socket.getOutputStream(),405,"text/plain",new byte[0]);return;}
|
||||
String path=URLDecoder.decode(target.split("\\?",2)[0],"UTF-8");File file=new File(bundle,path.equals("/")?"index.html":path.substring(1));if(!file.getCanonicalPath().startsWith(bundle.getCanonicalPath()+File.separator))throw new IOException("Invalid path");
|
||||
if(!file.isFile())file=new File(bundle,"index.html");byte[] bytes=Files.readAllBytes(file.toPath());respond(socket.getOutputStream(),200,mime(file.getName()),"HEAD".equals(method)?new byte[0]:bytes);
|
||||
}
|
||||
private void proxy(String method,String path,Map<String,String> headers,InputStream input,OutputStream output)throws IOException{
|
||||
String requestOrigin=headers.get("origin");if(requestOrigin!=null&&!requestOrigin.equals("http://127.0.0.1:49180")){respond(output,403,"text/plain",new byte[0]);return;}
|
||||
URL url=new URL(origin+"/prod-api"+path);HttpURLConnection connection=BundleStore.connection(url);connection.setRequestMethod(method);
|
||||
for(String allowed:Arrays.asList("authorization","content-type","accept","accept-language"))if(headers.containsKey(allowed))connection.setRequestProperty(allowed,headers.get(allowed));
|
||||
if(headers.containsKey("transfer-encoding"))throw new IOException("Unsupported request encoding");int length=Integer.parseInt(headers.getOrDefault("content-length","0"));if(length<0||length>50*1024*1024)throw new IOException("Request too large");
|
||||
try{if(length>0){connection.setDoOutput(true);connection.setFixedLengthStreamingMode(length);try(var body=connection.getOutputStream()){byte[] buffer=new byte[8192];int remaining=length;while(remaining>0){int n=input.read(buffer,0,Math.min(buffer.length,remaining));if(n<0)throw new EOFException();body.write(buffer,0,n);remaining-=n;}}}
|
||||
int status=connection.getResponseCode();InputStream response=status>=400?connection.getErrorStream():connection.getInputStream();byte[] bytes=response==null?new byte[0]:BundleStore.read(response,80*1024*1024);if(response!=null)response.close();respond(output,status,Optional.ofNullable(connection.getContentType()).orElse("application/json"),bytes);
|
||||
}finally{connection.disconnect();}
|
||||
}
|
||||
private static String line(InputStream in)throws IOException{var out=new ByteArrayOutputStream();int b;while((b=in.read())!=-1){if(b=='\n')break;if(b!='\r')out.write(b);if(out.size()>16384)throw new IOException("Header too long");}return b==-1&&out.size()==0?null:new String(out.toByteArray(),StandardCharsets.ISO_8859_1);}
|
||||
private static void respond(OutputStream output,int status,String type,byte[] bytes)throws IOException{String headers="HTTP/1.1 "+status+" OK\r\nContent-Type: "+type.replace("\r","").replace("\n","")+"\r\nContent-Length: "+bytes.length+"\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n";output.write(headers.getBytes(StandardCharsets.ISO_8859_1));output.write(bytes);output.flush();}
|
||||
private static String mime(String path){if(path.endsWith(".js"))return "application/javascript";if(path.endsWith(".css"))return "text/css";if(path.endsWith(".svg"))return "image/svg+xml";if(path.endsWith(".png"))return "image/png";if(path.endsWith(".jpg"))return "image/jpeg";if(path.endsWith(".woff2"))return "font/woff2";if(path.endsWith(".woff"))return "font/woff";if(path.endsWith(".ttf"))return "font/ttf";return "text/html; charset=utf-8";}
|
||||
public void close()throws IOException{stopped=true;server.close();workers.shutdownNow();}
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
package cn.cmvr.projectwarehouse;
|
||||
|
||||
import android.app.*;
|
||||
import android.os.Bundle;
|
||||
import android.view.*;
|
||||
import android.webkit.*;
|
||||
import android.widget.*;
|
||||
import android.net.Uri;
|
||||
import android.content.Intent;
|
||||
import java.net.URI;
|
||||
|
||||
public final class MainActivity extends Activity {
|
||||
private WebView web;
|
||||
private LocalWebServer server;
|
||||
private int launchSequence;
|
||||
private View appLayout;
|
||||
private boolean showingSettings;
|
||||
private boolean navigating;
|
||||
private AlertDialog exitDialog;
|
||||
private ProgressBar progress;
|
||||
private final android.os.Handler handler=new android.os.Handler(android.os.Looper.getMainLooper());
|
||||
@Override public void onCreate(Bundle state){super.onCreate(state);registerNativeBack();String origin=getSharedPreferences("application",0).getString("server","");if(origin.isEmpty())settings();else launch(origin);}
|
||||
private void registerNativeBack(){
|
||||
if(android.os.Build.VERSION.SDK_INT>=34){
|
||||
getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,new android.window.OnBackAnimationCallback(){
|
||||
@Override public void onBackProgressed(android.window.BackEvent event){updateBackProgress(event.getProgress(),event.getSwipeEdge());}
|
||||
@Override public void onBackCancelled(){resetBackProgress(true);}
|
||||
@Override public void onBackInvoked(){resetBackProgress(false);navigateBack();}
|
||||
});
|
||||
}else if(android.os.Build.VERSION.SDK_INT>=33)getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,this::navigateBack);
|
||||
}
|
||||
private void settings(){
|
||||
showingSettings=true;
|
||||
LinearLayout panel=new LinearLayout(this);panel.setOrientation(LinearLayout.VERTICAL);panel.setPadding(dp(20),dp(24),dp(20),dp(20));panel.setFitsSystemWindows(true);
|
||||
if(appLayout!=null){Button back=new Button(this);back.setText("‹ 返回应用");back.setOnClickListener(v->navigateBack());panel.addView(back);}
|
||||
TextView title=new TextView(this);title.setText("项目物资管理");title.setTextSize(26);panel.addView(title);
|
||||
TextView hint=new TextView(this);hint.setText("填写电脑端网页地址,手机需能连接该服务器。");panel.addView(hint);
|
||||
EditText address=new EditText(this);address.setSingleLine();address.setInputType(android.text.InputType.TYPE_CLASS_TEXT|android.text.InputType.TYPE_TEXT_VARIATION_URI);address.setHint("http://服务器地址:8088");address.setText(getSharedPreferences("application",0).getString("server",""));panel.addView(address);
|
||||
Button connect=new Button(this);connect.setText("连接系统");panel.addView(connect);connect.setOnClickListener(v->{try{URI uri=URI.create(address.getText().toString().trim());if(!("http".equals(uri.getScheme())||"https".equals(uri.getScheme()))||uri.getHost()==null||uri.getUserInfo()!=null||uri.getQuery()!=null||uri.getFragment()!=null||!(uri.getPath().isEmpty()||uri.getPath().equals("/")))throw new IllegalArgumentException();String origin=uri.getScheme()+"://"+uri.getRawAuthority();String old=getSharedPreferences("application",0).getString("server","");if(!origin.equals(old)){CookieManager.getInstance().removeAllCookies(null);WebStorage.getInstance().deleteAllData();getSharedPreferences("application",0).edit().remove("pendingBundle").remove("activeBundle").apply();}getSharedPreferences("application",0).edit().putString("server",origin).apply();launch(origin);}catch(Exception e){address.setError("请输入有效的网页地址,不包含账号、密码或页面路径");}});setContentView(panel);
|
||||
}
|
||||
@SuppressWarnings("SetJavaScriptEnabled") private void launch(String origin){
|
||||
final int sequence=++launchSequence;showingSettings=false;navigating=false;appLayout=null;
|
||||
try{if(web!=null){web.destroy();web=null;}if(server!=null)server.close();BundleStore store=new BundleStore(this);server=new LocalWebServer(store.activate(),origin);server.start();
|
||||
LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);layout.setFitsSystemWindows(true);
|
||||
LinearLayout bar=new LinearLayout(this);bar.setGravity(Gravity.CENTER_VERTICAL);bar.setBackgroundColor(0xff185bb4);bar.setPadding(dp(4),0,dp(4),0);
|
||||
Button back=toolbarButton("‹ 返回");Button home=toolbarButton("首页");Button menu=toolbarButton("⋮");menu.setContentDescription("更多操作");
|
||||
TextView title=new TextView(this);title.setText("项目物资管理");title.setTextColor(0xffffffff);title.setTextSize(18);title.setSingleLine(true);title.setEllipsize(android.text.TextUtils.TruncateAt.END);
|
||||
bar.addView(back,new LinearLayout.LayoutParams(dp(72),dp(52)));bar.addView(title,new LinearLayout.LayoutParams(0,dp(52),1));title.setGravity(Gravity.CENTER_VERTICAL);bar.addView(home,new LinearLayout.LayoutParams(dp(56),dp(52)));bar.addView(menu,new LinearLayout.LayoutParams(dp(44),dp(52)));layout.addView(bar);
|
||||
progress=new ProgressBar(this,null,android.R.attr.progressBarStyleHorizontal);progress.setMax(100);layout.addView(progress,new LinearLayout.LayoutParams(-1,dp(2)));
|
||||
web=new WebView(this);web.getSettings().setJavaScriptEnabled(true);web.getSettings().setDomStorageEnabled(true);web.getSettings().setAllowFileAccess(false);web.getSettings().setAllowContentAccess(false);web.getSettings().setTextZoom(100);web.getSettings().setUserAgentString(web.getSettings().getUserAgentString()+" CMVRAndroid/1.1");web.setWebChromeClient(new WebChromeClient(){@Override public void onProgressChanged(WebView view,int value){progress.setProgress(value);progress.setVisibility(value==100?View.GONE:View.VISIBLE);}});
|
||||
web.setWebViewClient(new WebViewClient(){@Override public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){Uri uri=request.getUrl();if("http".equals(uri.getScheme())&&"127.0.0.1".equals(uri.getHost())&&uri.getPort()==49180)return false;if("http".equals(uri.getScheme())||"https".equals(uri.getScheme()))startActivity(new Intent(Intent.ACTION_VIEW,uri));return true;}@Override public void onReceivedError(WebView view,WebResourceRequest request,WebResourceError error){if(request.isForMainFrame())Toast.makeText(MainActivity.this,"页面加载失败,请重新打开或检查连接设置",Toast.LENGTH_LONG).show();}});
|
||||
layout.addView(web,new LinearLayout.LayoutParams(-1,0,1));EdgeBackLayout gestureRoot=new EdgeBackLayout(this,this::navigateBack);gestureRoot.setContent(layout);appLayout=gestureRoot;setContentView(gestureRoot);back.setOnClickListener(v->navigateBack());home.setOnClickListener(v->navigate("home"));menu.setOnClickListener(v->{PopupMenu popup=new PopupMenu(this,menu);popup.getMenu().add("刷新页面").setOnMenuItemClickListener(item->{new AlertDialog.Builder(this).setMessage("刷新会丢弃尚未保存的填写内容,是否继续?").setNegativeButton("取消",null).setPositiveButton("刷新",(d,w)->web.reload()).show();return true;});popup.getMenu().add("连接设置").setOnMenuItemClickListener(item->{settings();return true;});popup.show();});web.loadUrl("http://127.0.0.1:49180/mobile");
|
||||
if(store.trial())verifyBundle(store,origin,sequence,0);else store.check(origin);
|
||||
}catch(Exception failure){new AlertDialog.Builder(this).setMessage("启动失败:"+failure.getMessage()).setPositiveButton("连接设置",(dialog,which)->settings()).show();}
|
||||
}
|
||||
private void verifyBundle(BundleStore store,String origin,int sequence,int attempt){handler.postDelayed(()->{if(sequence!=launchSequence||web==null||isFinishing())return;web.evaluateJavascript("Boolean(document.querySelector('#app') && document.querySelector('#app').children.length)",result->{if(sequence!=launchSequence)return;if("true".equals(result)){store.healthy();store.check(origin);}else if(attempt<14)verifyBundle(store,origin,sequence,attempt+1);else{store.rollback();Toast.makeText(this,"新页面未能正常启动,已恢复原版本",Toast.LENGTH_LONG).show();launch(origin);}});},1000);}
|
||||
private int dp(int value){return Math.round(value*getResources().getDisplayMetrics().density);}
|
||||
private void updateBackProgress(float progress,int edge){if(appLayout==null||showingSettings)return;float direction=edge==android.window.BackEvent.EDGE_RIGHT?-1f:1f;appLayout.setTranslationX(direction*dp(42)*progress);appLayout.setScaleX(1f-.035f*progress);appLayout.setScaleY(1f-.035f*progress);appLayout.setAlpha(1f-.08f*progress);}
|
||||
private void resetBackProgress(boolean animated){if(appLayout==null)return;if(animated)appLayout.animate().translationX(0).scaleX(1).scaleY(1).alpha(1).setDuration(160).start();else{appLayout.animate().cancel();appLayout.setTranslationX(0);appLayout.setScaleX(1);appLayout.setScaleY(1);appLayout.setAlpha(1);}}
|
||||
private Button toolbarButton(String text){Button button=new Button(this);button.setText(text);button.setTextSize(15);button.setTextColor(0xffffffff);button.setBackgroundColor(android.graphics.Color.TRANSPARENT);button.setPadding(0,0,0,0);button.setMinWidth(0);button.setMinimumWidth(0);return button;}
|
||||
private void navigateBack(){
|
||||
if(showingSettings){if(appLayout!=null){showingSettings=false;setContentView(appLayout);}else confirmExit();return;}
|
||||
navigate("back");
|
||||
}
|
||||
private void navigate(String action){
|
||||
if(web==null){confirmExit();return;}
|
||||
if(navigating)return;
|
||||
navigating=true;final WebView current=web;
|
||||
// Do not expose a native JavascriptInterface to network content.
|
||||
web.evaluateJavascript("window.cmvrAppNavigate ? window.cmvrAppNavigate('"+action+"') : 'history'",result->{
|
||||
navigating=false;if(web!=current||showingSettings||isFinishing())return;
|
||||
if("\"handled\"".equals(result))return;
|
||||
if("\"root\"".equals(result)){if("back".equals(action))confirmExit();return;}
|
||||
Uri location=Uri.parse(web.getUrl()==null?"":web.getUrl());String path=location.getPath();
|
||||
if("home".equals(action))web.loadUrl("http://127.0.0.1:49180/mobile");
|
||||
else if(!"/login".equals(path)&&!"/mobile".equals(path)&&web.canGoBack())web.goBack();
|
||||
else confirmExit();
|
||||
});
|
||||
}
|
||||
private void confirmExit(){if(exitDialog!=null&&exitDialog.isShowing())return;exitDialog=new AlertDialog.Builder(this).setTitle("退出应用?").setMessage("未保存的填写内容将丢失,已提交的业务不受影响。").setNegativeButton("继续使用",null).setPositiveButton("退出",(dialog,which)->finish()).create();exitDialog.show();}
|
||||
@Override public void onBackPressed(){navigateBack();}
|
||||
@Override protected void onDestroy(){launchSequence++;handler.removeCallbacksAndMessages(null);try{if(server!=null)server.close();}catch(Exception ignored){}if(web!=null)web.destroy();super.onDestroy();}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package cn.cmvr.projectwarehouse;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
public class LocalTransportTest {
|
||||
@Test public void packagedVersionChangesOnlyWithContent()throws Exception{assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",BundleStore.digest(new byte[0]));assertEquals(BundleStore.digest(new byte[]{1,2}),BundleStore.digest(new byte[]{1,2}));assertNotEquals(BundleStore.digest(new byte[]{1}),BundleStore.digest(new byte[]{2}));}
|
||||
@Test public void pagesWorkAndInvalidPathsReturnVisibleFailure()throws Exception{
|
||||
Path root=Files.createTempDirectory("cmvr-pages-");Files.write(root.resolve("index.html"),"<html>mobile-test</html>".getBytes(StandardCharsets.UTF_8));
|
||||
try(var server=new LocalWebServer(root.toFile(),"http://127.0.0.1:1")){server.start();
|
||||
assertTrue(request("/","127.0.0.1:49180","").contains("mobile-test"));assertTrue(request("/mobile","127.0.0.1:49180","").contains("200 OK"));
|
||||
assertTrue(request("/../private","127.0.0.1:49180","").contains("503 OK"));assertTrue(request("/","attacker.invalid","").contains("503 OK"));
|
||||
assertTrue(request("/prod-api/test","127.0.0.1:49180","Origin: https://attacker.invalid\r\n").contains("403 OK"));
|
||||
assertTrue(request("/prod-api/test","127.0.0.1:49180","").contains("本次操作未确认成功"));
|
||||
}finally{Files.deleteIfExists(root.resolve("index.html"));Files.deleteIfExists(root);}
|
||||
}
|
||||
@Test public void bundleExtractionRejectsTraversalAndOversizedResponses()throws Exception{
|
||||
Path root=Files.createTempDirectory("cmvr-bundle-");var bytes=new ByteArrayOutputStream();try(var zip=new ZipOutputStream(bytes)){zip.putNextEntry(new ZipEntry("../outside.txt"));zip.write(1);zip.closeEntry();}
|
||||
try{assertThrows(IOException.class,()->BundleStore.extract(new ByteArrayInputStream(bytes.toByteArray()),root.toFile()));assertThrows(IOException.class,()->BundleStore.read(new ByteArrayInputStream(new byte[11]),10));assertTrue(BundleStore.sameOrigin(new URL("https://example.com"),new URL("https://example.com:443/update.zip")));assertFalse(BundleStore.sameOrigin(new URL("https://example.com"),new URL("http://example.com/update.zip")));}finally{Files.deleteIfExists(root);}
|
||||
}
|
||||
private String request(String target,String host,String extra)throws Exception{try(var socket=new Socket("127.0.0.1",49180)){socket.setSoTimeout(5000);socket.getOutputStream().write(("GET "+target+" HTTP/1.1\r\nHost: "+host+"\r\n"+extra+"Connection: close\r\n\r\n").getBytes(StandardCharsets.UTF_8));return new String(socket.getInputStream().readAllBytes(),StandardCharsets.UTF_8);}}
|
||||
}
|
||||
1
android-app/build.gradle
Normal file
1
android-app/build.gradle
Normal file
@ -0,0 +1 @@
|
||||
plugins { id 'com.android.application' version '8.9.2' apply false }
|
||||
3
android-app/gradle.properties
Normal file
3
android-app/gradle.properties
Normal file
@ -0,0 +1,3 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
org.gradle.daemon=false
|
||||
4
android-app/settings.gradle
Normal file
4
android-app/settings.gradle
Normal file
@ -0,0 +1,4 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
|
||||
rootProject.name = 'ProjectWarehouse'
|
||||
include ':app'
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
> 版本:V0.2
|
||||
> 日期:2026-10-09
|
||||
> 状态:本轮字段、页面和操作规则及两项旧稿遗漏已确认;整体数据设计方案供集中审阅,技术实现及完整验收仍待推进。项目类型细分仍暂定。
|
||||
> 状态:字段、页面和操作规则已确认并完成实现及自动回归;项目类型细分仍暂定,真实人员浏览器与安卓实体设备终验待项目组执行。
|
||||
|
||||
系统管理项目、采购、库存、借还、BOM、组装生产、交付及材料成本。网页端、安卓App和适配手机的网页端纳入完整系统,一次性交付。开发过程逐模块验证,最终统一验收上线。
|
||||
|
||||
@ -357,8 +357,8 @@ App启动检查页面和业务逻辑热更新,下载后下次启动生效,
|
||||
## 15 暂定内容与后续确认
|
||||
|
||||
1. 研发项目与产品项目的具体区分仍暂定,项目类型字段先按两类设计,不设强制限制。
|
||||
2. 第4步确定整体数据关系、库存和费用关联、成本调整算法、接口、现有数据兼容及开发安排。
|
||||
3. 第5步确定真实业务完整验收、网页与安卓测试、部署、初始化及一次性交付材料。
|
||||
2. 整体数据关系、库存和费用关联、成本调整算法、接口及现有数据兼容已经实现并完成自动回归。
|
||||
3. Web、后端和安卓安装包已一次性交付;仍需项目组在真实浏览器和安卓实体设备完成最终业务验收。
|
||||
|
||||
旧稿所列未做内容继续保留:询比价和招标、采购合同付款发票及应付、供应商门户、公共库存、预留冻结、仓库批次先进先出、序列号、单位换算、多币种、复杂工序工时排程、异常照片、iOS、离线库存和系统内安装包下载。成品拆解回收及人工费、其他费用录入已明确删除。
|
||||
|
||||
|
||||
79
docs/项目采购库存生产成本系统开发交付说明.md
Normal file
79
docs/项目采购库存生产成本系统开发交付说明.md
Normal file
@ -0,0 +1,79 @@
|
||||
# 项目采购库存生产成本系统开发交付说明
|
||||
|
||||
> 交付日期:2026-10-10
|
||||
> 业务依据:《项目采购库存生产成本管理系统设计确认稿》V0.2
|
||||
> 数据库:仅 `cmvr-project-dev`
|
||||
|
||||
## 1. Web 菜单
|
||||
|
||||
1. 项目管理
|
||||
- 项目列表
|
||||
- 项目详情(从项目列表进入):总览、分类预算、产品与BOM、采购、库存、借用与归还、生产、成本与损耗
|
||||
2. 采购管理
|
||||
- 采购明细
|
||||
- 到货验收
|
||||
3. 库存管理
|
||||
- 待入库
|
||||
- 库存查询
|
||||
- 借用与归还
|
||||
- 入库记录
|
||||
- 领用与退回记录
|
||||
- 库存盘点
|
||||
4. 生产管理
|
||||
- 生产任务
|
||||
- 报废与交付记录
|
||||
5. 材料成本
|
||||
- 产品材料成本
|
||||
6. 基础资料
|
||||
- 物品档案
|
||||
- 产品档案
|
||||
- BOM管理
|
||||
- 供应商档案
|
||||
- 库区管理
|
||||
7. 系统管理
|
||||
- 用户管理
|
||||
- 角色管理
|
||||
- 菜单权限
|
||||
- 业务字典
|
||||
- 历史数据补录
|
||||
- 操作日志
|
||||
|
||||
监控和开发工具菜单仅从侧栏隐藏,原权限及数据未删除。旧的 `/purchase` 和 `/materialCost` 地址保留自动跳转。
|
||||
|
||||
## 2. 已实现的关键业务规则
|
||||
|
||||
- 项目仅维护编号、名称、暂定类型、总金额、状态和备注;状态为立项、进行中、结题、终止。
|
||||
- 结题或终止前显示未到齐采购、待入库、未结算任务、未归还借用和剩余库存,只提示不阻断,后续业务仍可办理。
|
||||
- 默认费用分类为材料费、设备费、加工费;无人工费、工时工资、服务类采购和其他费用手工录入入口。
|
||||
- 采购必须关联物品档案;采购明细平铺维护,批次按供应商归组,支持直接采购、任务缺料采购、分批到货、批量验收和供应商Excel。
|
||||
- 锁价后才计入项目费用。未入库时可修改并按差额调整;存在有效入库时必须逐步撤回到待入库后才能改价。
|
||||
- 到货验收与确认入库分开;待入库时选择项目、库区、数量和日期,支持分次、分库区和批量操作。
|
||||
- 库存按项目、物品、库区管理,支持直接出库、归还、移库、盘点、其他入库、撤销和只读流水。
|
||||
- 借用记录显示借用、已还和待还数量;支持库存归还和采购归还,采购归还以实际入库为准。
|
||||
- 产品、公共BOM、项目BOM和任务BOM快照均已实现,支持多层BOM、下级自制任务并阻止循环。
|
||||
- 生产支持领补料、退料、完工验收、同步增加超计划数量、四类报废、成品交付与退回、撤销和成本重算。
|
||||
- 库存采用项目加物品维度的移动加权平均成本;产品成本同时保留参考成本和任务实际结算成本,并可联动校正下游。
|
||||
- 期初库存、历史采购和历史借用余额可选补录,支持模板、预览、校验、手工行和分行导入结果。
|
||||
- Web、手机网页和安卓 App 共用接口、账号、权限和数据;安卓支持系统返回、原生左边缘滑动返回和页面热更新。
|
||||
- Web 已统一为若依通用列表页风格:不单设页面大标题和说明区,筛选、操作按钮、表格在同一白色内容区连续排列,不再拆成多个卡片;表头、按钮、分页、弹窗和系统管理页面沿用若依/Element 的统一视觉与间距。
|
||||
|
||||
## 3. 运行与产物
|
||||
|
||||
- Web:`http://localhost:8088`
|
||||
- 后端:`http://localhost:8080`
|
||||
- 安卓调试安装包:`android-app/app/build/outputs/apk/debug/app-debug.apk`
|
||||
- 页面热更新清单:`ruoyi-ui/dist/mobile-update.json`
|
||||
|
||||
菜单由登录时加载。已登录用户更新后刷新页面;若浏览器保留旧路由,退出后重新登录一次。
|
||||
|
||||
## 4. 验证结果
|
||||
|
||||
- 后端及真实数据库回归:19 个测试套件,58 项测试,0 失败,0 错误;数据库测试限定为 `cmvr-project-dev` 并回滚测试数据。
|
||||
- Web 生产构建:通过;仅有包体积提示,无编译错误。
|
||||
- Web 设计契约:32 个页面/组件和菜单结构检查通过;使用登录后的真实浏览器尺寸完成项目、采购、到货、库存、生产、借还、物品档案和用户管理 8 个代表页面渲染验收。
|
||||
- Android:单元测试和 Debug APK 构建通过。
|
||||
- 运行健康检查:8080、8088 均返回成功,后端启动日志无错误。
|
||||
- 登录后运行验收:7 个一级菜单顺序正确,25 个页面接口及产品成本历史接口全部返回成功。
|
||||
- 字段验收:项目接口无负责人、成员、部门和起止日期;采购接口无申请人和预计到货日期;费用分类仅返回材料费、设备费、加工费。
|
||||
|
||||
自动化验证不能替代真实人员在浏览器和安卓设备上的最终业务验收。当前电脑的界面控制辅助进程异常退出,未能完成自动点击截图;安卓也尚未在实体设备安装操作。正式使用前仍应由项目组用一组真实项目数据,在浏览器和安卓设备完整走一次采购、到货、入库、生产、交付及撤销链路。
|
||||
@ -17,6 +17,12 @@
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- spring-boot-devtools -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
@ -58,6 +64,11 @@
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.3</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
|
||||
@ -0,0 +1,84 @@
|
||||
package com.ruoyi.web.controller.production;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.core.page.TableDataInfo;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.service.BomService;
|
||||
import com.ruoyi.warehouse.domain.ProductInfo;
|
||||
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/production/bom")
|
||||
public class BomController extends BaseController {
|
||||
@Autowired private BomService service;
|
||||
@Autowired private ProductInfoMapper items;
|
||||
@PostMapping("/import-template") @PreAuthorize("@ss.hasPermi('production:bom:edit')")
|
||||
public void template(jakarta.servlet.http.HttpServletResponse response){new com.ruoyi.common.utils.poi.ExcelUtil<>(BomLine.class).importTemplateExcel(response,"BOM用料模板");}
|
||||
@PostMapping("/{id}/export") @PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,project:project:list')")
|
||||
public void export(@PathVariable Long id,jakarta.servlet.http.HttpServletResponse response){new com.ruoyi.common.utils.poi.ExcelUtil<>(BomLine.class).exportExcel(response,service.get(id).getLines(),"BOM用料");}
|
||||
@PostMapping("/import-preview") @PreAuthorize("@ss.hasPermi('production:bom:edit')")
|
||||
public AjaxResult preview(org.springframework.web.multipart.MultipartFile file,Long rootItemId)throws Exception{
|
||||
com.ruoyi.warehouse.util.WarehouseFileUtils.validateUpload(file,10L*1024*1024,java.util.Set.of("xls","xlsx"));
|
||||
java.util.List<BomLine> rows;try(var input=file.getInputStream()){rows=new com.ruoyi.common.utils.poi.ExcelUtil<>(BomLine.class).importExcel(input);}
|
||||
if(rows.isEmpty()||rows.size()>2000)throw new com.ruoyi.common.exception.ServiceException("请上传1至2000行用料");
|
||||
var result=new java.util.ArrayList<java.util.Map<String,Object>>();var seen=new java.util.HashSet<Long>();int index=1;
|
||||
for(var row:rows){String error=null;try{
|
||||
if(row.getItemCode()==null||row.getItemCode().isBlank())throw new IllegalArgumentException("物品编码必填");var item=items.checkProductCodeUnique(row.getItemCode().trim());if(item==null)throw new IllegalArgumentException("物品编码不存在");if(java.util.Objects.equals(item.getId(),rootItemId))throw new IllegalArgumentException("不能使用产出物品自身作为用料");if(!seen.add(item.getId()))throw new IllegalArgumentException("文件内物品重复");
|
||||
var quantity=row.getUnitQuantity();if(quantity==null||quantity.signum()<=0||quantity.stripTrailingZeros().scale()>4)throw new IllegalArgumentException("单台用量必须大于0,最多4位小数");
|
||||
row.setItemId(item.getId());row.setItemName(item.getProductName());row.setBrand(item.getBrand());row.setSpec(item.getSpec());row.setUnit(item.getUnit());
|
||||
if(row.getChildVersionTag()!=null&&!row.getChildVersionTag().isBlank()){var matches=service.list(item.getId(),null).stream().filter(b->row.getChildVersionTag().trim().equals(b.getVersionTag())).toList();if(matches.size()!=1)throw new IllegalArgumentException("未找到唯一的下级公共BOM版本");row.setChildBomId(matches.get(0).getId());}
|
||||
}catch(Exception e){error=e.getMessage();}var value=new java.util.LinkedHashMap<String,Object>();value.put("line",++index);value.put("row",row);value.put("error",error);result.add(value);}return success(result);
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit')")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(Long itemId, String keyword) {
|
||||
startPage(); return getDataTable(service.list(itemId, keyword));
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,production:product:list,production:product:edit,project:project:list,project:project:edit,project:project:manage')")
|
||||
@GetMapping("/options")
|
||||
public AjaxResult options(@RequestParam Long itemId) { return success(service.list(itemId, null)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,production:product:list,production:product:edit,project:project:list,project:project:edit,project:project:manage')")
|
||||
@GetMapping("/items")
|
||||
public AjaxResult items(ProductInfo query) {
|
||||
startPage(); return success(items.selectProductInfoList(query));
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,project:project:list,project:project:edit,project:project:manage')")
|
||||
@GetMapping("/{id}")
|
||||
public AjaxResult get(@PathVariable Long id) { return success(service.get(id)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,production:bom:edit,project:project:list,project:project:edit,project:project:manage')")
|
||||
@GetMapping("/{id}/logs")
|
||||
public AjaxResult logs(@PathVariable Long id) { return success(service.logs(id)); }
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('production:bom:edit')")
|
||||
@Log(title="BOM用料", businessType=BusinessType.UPDATE)
|
||||
@PostMapping
|
||||
public AjaxResult save(@RequestBody BomVersion bom) { return success(service.save(bom)); }
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('production:bom:edit')")
|
||||
@Log(title="复制BOM版本", businessType=BusinessType.INSERT)
|
||||
@PostMapping("/{id}/copy")
|
||||
public AjaxResult copy(@PathVariable Long id, @RequestBody BomVersion request) {
|
||||
return success(service.copy(id, request.getVersionTag(), request.getDescription(), request.getIsDefault()));
|
||||
}
|
||||
|
||||
public record DefaultVersion(Integer version) {}
|
||||
@PreAuthorize("@ss.hasPermi('production:bom:edit')")
|
||||
@Log(title="BOM默认版本", businessType=BusinessType.UPDATE)
|
||||
@PostMapping("/{id}/default")
|
||||
public AjaxResult setDefault(@PathVariable Long id, @RequestBody DefaultVersion request) {
|
||||
return success(service.setDefault(id, request.version()));
|
||||
}
|
||||
@PreAuthorize("@ss.hasPermi('production:bom:edit')")
|
||||
@Log(title="BOM版本", businessType=BusinessType.DELETE)
|
||||
@DeleteMapping("/{id}")
|
||||
public AjaxResult delete(@PathVariable Long id) { service.delete(id); return success(); }
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package com.ruoyi.web.controller.production;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.IOException;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
final class ProductionExcel {
|
||||
private ProductionExcel(){}
|
||||
static void write(HttpServletResponse response,List<Map<String,Object>> rows,String[][] columns)throws IOException{
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
response.setHeader("Content-Disposition","attachment; filename=production.xlsx");
|
||||
try(var workbook=new XSSFWorkbook()){
|
||||
var sheet=workbook.createSheet("业务数据");var header=sheet.createRow(0);
|
||||
for(int i=0;i<columns.length;i++){header.createCell(i).setCellValue(columns[i][1]);sheet.setColumnWidth(i,22*256);}
|
||||
int index=1;for(var data:rows){var row=sheet.createRow(index++);for(int i=0;i<columns.length;i++){Object value=data.get(columns[i][0]);var cell=row.createCell(i);if(value instanceof Number number)cell.setCellValue(number.doubleValue());else cell.setCellValue(value==null?"":String.valueOf(value));}}
|
||||
sheet.createFreezePane(0,1);workbook.write(response.getOutputStream());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package com.ruoyi.web.controller.production;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.core.page.TableDataInfo;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.service.BomService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/production/product")
|
||||
public class ProductionProductController extends BaseController {
|
||||
@Autowired private BomService service;
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:product:list,production:product:edit')")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(String keyword) { startPage(); return getDataTable(service.products(keyword)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:product:list,production:product:edit,production:bom:list,production:bom:edit,project:project:list,project:project:edit,project:project:manage')")
|
||||
@GetMapping("/options")
|
||||
public AjaxResult options(String keyword) { startPage(); return success(service.products(keyword)); }
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('production:product:edit')")
|
||||
@Log(title="产品档案", businessType=BusinessType.UPDATE)
|
||||
@PostMapping
|
||||
public AjaxResult save(@RequestBody ProductionProduct product) { return success(service.saveProduct(product)); }
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('production:product:edit')")
|
||||
@Log(title="产品档案", businessType=BusinessType.DELETE)
|
||||
@DeleteMapping("/{id}")
|
||||
public AjaxResult delete(@PathVariable Long id) { service.deleteProduct(id); return success(); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:project:list,project:project:edit,project:project:manage')")
|
||||
@GetMapping("/project/{projectId}")
|
||||
public AjaxResult projectProducts(@PathVariable Long projectId) { return success(service.projectProducts(projectId)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:project:edit,project:project:manage')")
|
||||
@Log(title="项目产品用料", businessType=BusinessType.UPDATE)
|
||||
@PostMapping("/project")
|
||||
public AjaxResult link(@RequestBody ProjectProduct product) { return success(service.link(product)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:project:edit,project:project:manage')")
|
||||
@Log(title="项目产品关联", businessType=BusinessType.DELETE)
|
||||
@DeleteMapping("/project/{id}")
|
||||
public AjaxResult unlink(@PathVariable Long id) { service.unlink(id); return success(); }
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package com.ruoyi.web.controller.production;
|
||||
|
||||
import java.util.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.production.domain.ProductionCommand;
|
||||
import com.ruoyi.production.service.ProductionService;
|
||||
|
||||
@RestController @RequestMapping("/production/tasks")
|
||||
public class ProductionTaskController extends BaseController {
|
||||
@Autowired private ProductionService service;
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping
|
||||
public AjaxResult list(Long projectId,Long itemId){return success(service.tasks(projectId,itemId));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/{id}")
|
||||
public AjaxResult get(@PathVariable Long id){return success(service.detail(id));}
|
||||
@PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasAnyPermi('project:project:edit,project:project:manage')") @PostMapping @Log(title="生产任务",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult save(@RequestBody ProductionCommand command){return success(service.save(command));}
|
||||
@PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasPermi('warehouse:stock:out')") @PostMapping("/actions") @Log(title="生产报废与交付",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult perform(@RequestBody ProductionCommand command){return success(service.perform(command));}
|
||||
@PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasPermi('warehouse:stock:out')") @PostMapping("/actions/{id}/revoke") @Log(title="撤销生产报废交付",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult revoke(@PathVariable Long id,@RequestBody Map<String,String> request){service.revoke(id,request.get("reason"));return success();}
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')") @GetMapping("/actions")
|
||||
public AjaxResult actions(Long projectId,Long taskId){return success(service.actions(projectId,taskId));}
|
||||
@PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasAnyPermi('project:project:edit,project:project:manage')") @PostMapping("/{id}/settle") @Log(title="生产成本结算",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult settle(@PathVariable Long id,@RequestBody TaskVersion request){if(request.version()==null)throw new com.ruoyi.common.exception.ServiceException("请刷新任务后重试");return success(service.settle(id,request.version()));}
|
||||
@PreAuthorize("@ss.hasPermi('project:inventory:use') && @ss.hasAnyPermi('project:project:edit,project:project:manage')") @PostMapping("/{id}/reopen") @Log(title="继续生产",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult reopen(@PathVariable Long id,@RequestBody TaskVersion request){if(request.version()==null)throw new com.ruoyi.common.exception.ServiceException("请刷新任务后重试");return success(service.reopen(id,request.version()));}
|
||||
public record TaskVersion(Integer version){}
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,project:project:list')") @GetMapping("/reference")
|
||||
public AjaxResult reference(@RequestParam Long bomId,Long projectId,Long taskId){return success(service.reference(bomId,projectId,taskId));}
|
||||
@PreAuthorize("@ss.hasPermi('project:project:list')") @GetMapping("/overview/{projectId}")
|
||||
public AjaxResult overview(@PathVariable Long projectId){return success(service.overview(projectId));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,project:project:list')") @GetMapping("/cost-history")
|
||||
public AjaxResult costHistory(@RequestParam Long itemId,Long bomId,Long projectId){return success(service.costHistory(itemId,bomId,projectId));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('production:bom:list,project:project:list')") @PostMapping("/cost-history/export")
|
||||
public void costHistoryExport(jakarta.servlet.http.HttpServletResponse response,@RequestParam Long itemId,Long bomId,Long projectId)throws java.io.IOException{
|
||||
ProductionExcel.write(response,service.costHistory(itemId,bomId,projectId),new String[][]{{"project_name","项目"},{"task_no","任务"},{"version_tag","BOM版本"},{"project_adjusted","项目独立用料"},{"planned_quantity","计划"},{"good_quantity","合格"},{"scrap_quantity","组装报废"},{"material_cost","材料总成本"},{"unit_cost","单位成本"},{"status","结算状态"},{"settled_time","结算时间"}});
|
||||
}
|
||||
@PreAuthorize("@ss.hasPermi('project:project:list')") @PostMapping("/export")
|
||||
public void export(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long itemId)throws java.io.IOException{
|
||||
ProductionExcel.write(response,service.tasks(projectId,itemId),new String[][]{{"task_no","任务编号"},{"project_name","项目"},{"item_name","产品"},{"version_tag","BOM版本"},{"planned_quantity","计划数量"},{"good_quantity","合格数量"},{"scrap_quantity","组装报废数量"},{"material_cost","实际材料成本"},{"unit_cost","单位材料成本"},{"status","状态"},{"settled_time","结算时间"}});
|
||||
}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:stock:export')") @PostMapping("/actions/export")
|
||||
public void exportActions(jakarta.servlet.http.HttpServletResponse response,Long projectId,Long taskId)throws java.io.IOException{
|
||||
ProductionExcel.write(response,service.actions(projectId,taskId),new String[][]{{"project_name","项目"},{"task_no","任务"},{"item_name","物品"},{"kind","类型"},{"quantity","数量"},{"handled_quantity","已退回或报废"},{"area_name","库区"},{"original_cost","原始成本"},{"effective_cost","当前成本"},{"business_date","日期"},{"recipient","接收方"},{"reason","原因"},{"remark","备注"},{"active","有效"}});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package com.ruoyi.web.controller.project;
|
||||
import java.math.BigDecimal;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.core.page.TableDataInfo;
|
||||
import com.ruoyi.project.service.ProjectLoanService;
|
||||
import com.ruoyi.project.domain.ProjectLoan;
|
||||
import com.ruoyi.common.utils.poi.ExcelUtil;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@RestController @RequestMapping("/project/loans") public class ProjectLoanController extends BaseController {
|
||||
@Autowired private ProjectLoanService service;
|
||||
public record Borrow(Long lenderProjectId,Long borrowerProjectId,Long itemId,Long fromAreaId,Long toAreaId,BigDecimal quantity,String key,String remark,java.time.LocalDate date){}
|
||||
public record Return(Long fromAreaId,Long toAreaId,BigDecimal quantity,String key,java.time.LocalDate date,String remark){}
|
||||
public record Revoke(String reason,String key){}
|
||||
@GetMapping @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list,warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
public TableDataInfo list(Long projectId,Long itemId,boolean outstandingOnly){startPage();return getDataTable(service.list(projectId,itemId,outstandingOnly));}
|
||||
@GetMapping("/options") @PreAuthorize("@ss.hasAnyPermi('project:inventory:use,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
public AjaxResult options(Long projectId,Long itemId){return success(service.list(projectId,itemId,true));}
|
||||
@GetMapping("/{id}/returns") @PreAuthorize("@ss.hasAnyPermi('project:project:list,warehouse:stock:list')")
|
||||
public AjaxResult returns(@PathVariable Long id){return success(service.returns(id));}
|
||||
@PostMapping @PreAuthorize("@ss.hasPermi('project:inventory:use') and @ss.hasPermi('warehouse:stock:out')") @Log(title="跨项目借用",businessType=BusinessType.INSERT)
|
||||
public AjaxResult borrow(@RequestBody Borrow r){return success(service.borrow(r.lenderProjectId(),r.borrowerProjectId(),r.itemId(),r.fromAreaId(),r.toAreaId(),r.quantity(),r.key(),r.remark(),r.date()));}
|
||||
@PostMapping("/{id}/return") @PreAuthorize("@ss.hasPermi('project:inventory:use') and @ss.hasPermi('warehouse:stock:out')") @Log(title="库存归还",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult returnStock(@PathVariable Long id,@RequestBody Return r){return success(service.returnStock(id,r.fromAreaId(),r.toAreaId(),r.quantity(),r.key(),r.date(),r.remark()));}
|
||||
@PostMapping("/{id}/revoke") @PreAuthorize("@ss.hasPermi('project:inventory:use') and @ss.hasPermi('warehouse:stock:out')") @Log(title="撤销借用",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult revoke(@PathVariable Long id,@RequestBody Revoke r){service.revokeLoan(id,r.reason());return success();}
|
||||
@PostMapping("/{id}/returns/revoke") @PreAuthorize("@ss.hasPermi('project:inventory:use') and @ss.hasPermi('warehouse:stock:out')") @Log(title="撤销归还",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult revokeReturn(@PathVariable Long id,@RequestBody Revoke r){service.revokeStockReturn(id,r.key(),r.reason());return success();}
|
||||
@PostMapping("/export") @PreAuthorize("@ss.hasPermi('warehouse:stock:export')") @Log(title="借还记录",businessType=BusinessType.EXPORT)
|
||||
public void export(HttpServletResponse response,Long projectId,Long itemId){new ExcelUtil<>(ProjectLoan.class).exportExcel(response,service.list(projectId,itemId,false),"项目借还");}
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.warehouse.service.impl.BusinessWithdrawalService;
|
||||
@RestController @RequestMapping("/warehouse/withdrawals") public class BusinessWithdrawalController extends BaseController {
|
||||
@Autowired private BusinessWithdrawalService service;
|
||||
@PostMapping @PreAuthorize("@ss.hasPermi('project:inventory:use') and @ss.hasAnyPermi('warehouse:stock:out,warehouse:out:add')") @Log(title="按原记录撤销",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult withdraw(@RequestBody BusinessWithdrawalService.Request request){return success(service.withdraw(request));}
|
||||
}
|
||||
@ -29,6 +29,9 @@ public class InRecordController extends BaseController
|
||||
{
|
||||
@Autowired
|
||||
private IInRecordService inRecordService;
|
||||
public record ReceiptRequest(Long areaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark){}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:in:confirm')") @PostMapping("/receive/{id}") @Log(title="分次入库",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult receive(@PathVariable Long id,@RequestBody ReceiptRequest request){return toAjax(inRecordService.receive(id,request.areaId(),request.quantity(),request.key(),getUsername(),request.date(),request.remark()));}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:in:list')")
|
||||
@GetMapping("/list")
|
||||
@ -96,4 +99,13 @@ public class InRecordController extends BaseController
|
||||
{
|
||||
return toAjax(inRecordService.deleteInRecordByIds(ids));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:in:confirm')")
|
||||
@Log(title = "撤销入库", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/revoke/{id}")
|
||||
public AjaxResult revoke(@PathVariable Long id, @RequestBody java.util.Map<String, String> request)
|
||||
{
|
||||
if(request.get("quantity")!=null)return toAjax(inRecordService.withdraw(id,new java.math.BigDecimal(request.get("quantity")),request.get("reason"),request.get("key"),getUsername()));
|
||||
return toAjax(inRecordService.revokeInRecord(id, request.get("reason"), getUsername()));
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,41 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
|
||||
import java.util.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.service.impl.InitializationService;
|
||||
|
||||
@RestController @RequestMapping("/warehouse/initialization")
|
||||
@PreAuthorize("@ss.hasAnyPermi('project:inventory:use,warehouse:purchase:import,warehouse:purchase:manage')")
|
||||
public class InitializationController extends BaseController {
|
||||
@Autowired private InitializationService service;
|
||||
private static final String[][] COMMON={{"sourceKey","来源编号"},{"projectCode","项目编码"},{"itemCode","物品编码"},{"quantity","数量"}};
|
||||
public static List<String[]> columns(String kind){var result=new ArrayList<String[]>(Arrays.asList(COMMON));switch(kind){case "STOCK"->result.addAll(List.of(new String[]{"areaName","库区名称"},new String[]{"unitPrice","成本单价"}));case "LOAN"->result.addAll(List.of(new String[]{"lenderCode","借出项目编码"},new String[]{"returnedQuantity","历史已还数量"}));case "PURCHASE"->result.addAll(List.of(new String[]{"supplierName","供应商名称"},new String[]{"categoryCode","费用分类编码"},new String[]{"unitPrice","最终单价"},new String[]{"receivedQuantity","历史已入库数量"},new String[]{"acceptedQuantity","已验收待入库数量"}));default->throw new ServiceException("初始化类型无效");}result.add(new String[]{"date","原日期"});result.add(new String[]{"remark","备注"});return result;}
|
||||
@GetMapping("/{kind}/columns") public AjaxResult columnsApi(@PathVariable String kind){return success(columns(kind));}
|
||||
@PostMapping("/{kind}/template") public void template(@PathVariable String kind,HttpServletResponse response)throws Exception{
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setHeader("Content-Disposition","attachment; filename=initialization.xlsx");try(var book=new XSSFWorkbook()){var sheet=book.createSheet("初始化");var header=sheet.createRow(0);var cols=columns(kind);for(int i=0;i<cols.size();i++){header.createCell(i).setCellValue(cols.get(i)[1]);sheet.setColumnWidth(i,24*256);}book.write(response.getOutputStream());}
|
||||
}
|
||||
@PostMapping("/{kind}/read") public AjaxResult read(@PathVariable String kind,@RequestParam MultipartFile file)throws Exception{
|
||||
if(file.isEmpty()||file.getSize()>10*1024*1024)throw new ServiceException("请选择10MB以内Excel");var cols=columns(kind);var rows=new ArrayList<InitializationService.Row>();
|
||||
try(var input=file.getInputStream();var book=WorkbookFactory.create(input)){var sheet=book.getSheetAt(0);if(sheet.getLastRowNum()>2000)throw new ServiceException("每次最多2000行");var format=new DataFormatter(Locale.ROOT);var header=sheet.getRow(0);for(int c=0;c<cols.size();c++)if(header==null||!cols.get(c)[1].equals(format.formatCellValue(header.getCell(c)).trim()))throw new ServiceException("表头不匹配,请使用对应模板");
|
||||
for(int n=1;n<=sheet.getLastRowNum();n++){var line=sheet.getRow(n);if(line==null)continue;var row=new InitializationService.Row();boolean content=false;for(int c=0;c<cols.size();c++){var cell=line.getCell(c);String text=format.formatCellValue(cell).trim();if(text.isEmpty())continue;content=true;if(cell.getCellType()==CellType.FORMULA)throw new ServiceException("第"+(n+1)+"行包含公式,请粘贴为数值后导入");try{var field=InitializationService.Row.class.getField(cols.get(c)[0]);Object value=text;if(field.getType()==BigDecimal.class)value=cell.getCellType()==CellType.NUMERIC?BigDecimal.valueOf(cell.getNumericCellValue()):new BigDecimal(text.replace(",",""));else if(field.getType()==LocalDate.class)value=cell.getCellType()==CellType.NUMERIC&&DateUtil.isCellDateFormatted(cell)?cell.getLocalDateTimeCellValue().toLocalDate():LocalDate.parse(text.replace('/','-'));field.set(row,value);}catch(Exception e){throw new ServiceException("第"+(n+1)+"行“"+cols.get(c)[1]+"”格式错误,日期请用YYYY-MM-DD,数量请用数字");}}if(content)rows.add(row);}
|
||||
}return success(service.preview(kind,rows));
|
||||
}
|
||||
@PostMapping("/{kind}/preview") public AjaxResult preview(@PathVariable String kind,@RequestBody List<InitializationService.Row> rows){return success(service.preview(kind,rows));}
|
||||
@PostMapping("/{kind}/apply") @Log(title="可选历史初始化",businessType=BusinessType.IMPORT)
|
||||
public AjaxResult apply(@PathVariable String kind,@RequestBody List<InitializationService.Row> rows){
|
||||
if(rows==null||rows.size()>2000)throw new ServiceException("每次最多2000行");var results=new ArrayList<Map<String,Object>>();for(var row:rows){var result=new LinkedHashMap<String,Object>();result.put("sourceKey",row.sourceKey);try{result.put("data",service.apply(kind,row));result.put("success",true);}catch(Exception e){result.put("success",false);result.put("message",e.getMessage());}results.add(result);}return success(results);
|
||||
}
|
||||
}
|
||||
@ -27,6 +27,23 @@ public class OutRecordController extends BaseController
|
||||
{
|
||||
@Autowired
|
||||
private IOutRecordService outRecordService;
|
||||
public record ReturnRequest(Long areaId, java.math.BigDecimal quantity,String key) {}
|
||||
public record RevokeRequest(String reason) {}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:out:list')") @GetMapping("/{id}/returns")
|
||||
public AjaxResult returns(@PathVariable Long id){return success(outRecordService.returns(id));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:stock:out,warehouse:out:add')")
|
||||
@PostMapping("/{id}/returns/{eventId}/revoke") @Log(title="撤销退料",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult revokeReturn(@PathVariable Long id,@PathVariable Long eventId,@RequestBody RevokeRequest request){outRecordService.revokeReturn(id,eventId,request.reason());return success();}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:stock:out,warehouse:out:add')")
|
||||
@PostMapping("/{id}/return") @Log(title="退料",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult returnMaterial(@PathVariable Long id,@RequestBody ReturnRequest request) {
|
||||
return success(outRecordService.returnMaterial(id,request.areaId(),request.quantity(),request.key()));
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:stock:out,warehouse:out:add')")
|
||||
@PostMapping("/{id}/revoke") @Log(title="撤销出库",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult revoke(@PathVariable Long id,@RequestBody RevokeRequest request) {
|
||||
return toAjax(outRecordService.revoke(id,request.reason()));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:out:list')")
|
||||
@GetMapping("/list")
|
||||
|
||||
@ -29,6 +29,17 @@ public class ProductInfoController extends BaseController
|
||||
{
|
||||
@Autowired
|
||||
private IProductInfoService productInfoService;
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.WarehouseImportReceiptService importReceipts;
|
||||
private List<ProductInfo> importRows(org.springframework.web.multipart.MultipartFile file)throws Exception{
|
||||
com.ruoyi.warehouse.util.WarehouseFileUtils.validateUpload(file,10L*1024*1024,java.util.Set.of("xls","xlsx"));
|
||||
try(var input=file.getInputStream()){return new ExcelUtil<>(ProductInfo.class).importExcel(input);}
|
||||
}
|
||||
@PostMapping("/importTemplate") @PreAuthorize("@ss.hasPermi('warehouse:product:add')")
|
||||
public void importTemplate(HttpServletResponse response){new ExcelUtil<>(ProductInfo.class).importTemplateExcel(response,"物品档案模板");}
|
||||
@PostMapping("/importPreview") @PreAuthorize("@ss.hasPermi('warehouse:product:add')")
|
||||
public AjaxResult importPreview(org.springframework.web.multipart.MultipartFile file)throws Exception{return success(productInfoService.previewImport(importRows(file)));}
|
||||
@PostMapping("/importData") @PreAuthorize("@ss.hasPermi('warehouse:product:add')") @Log(title="物品档案导入",businessType=BusinessType.IMPORT)
|
||||
public AjaxResult importData(org.springframework.web.multipart.MultipartFile file)throws Exception{var rows=importRows(file);return success(importReceipts.apply("PRODUCT",file.getBytes(),()->productInfoService.importNew(rows)));}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:product:list')")
|
||||
@GetMapping("/list")
|
||||
|
||||
@ -0,0 +1,41 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
|
||||
import java.util.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.service.impl.PurchasePriceService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/warehouse/purchase")
|
||||
public class PurchasePriceController
|
||||
{
|
||||
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(PurchasePriceController.class);
|
||||
@Autowired private PurchasePriceService priceService;
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@Log(title = "采购价格锁定", businessType = BusinessType.UPDATE)
|
||||
@PostMapping("/price-lock")
|
||||
public AjaxResult lock(@RequestBody Long[] ids)
|
||||
{
|
||||
if (ids == null || ids.length == 0 || ids.length > 1000)
|
||||
throw new ServiceException("请选择1至1000条采购明细");
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
for (Long id : new LinkedHashSet<>(Arrays.asList(ids)))
|
||||
{
|
||||
Map<String, Object> row = new LinkedHashMap<>(); row.put("id", id);
|
||||
try { row.put("message", priceService.lockPrice(id)); row.put("success", true); }
|
||||
catch (ServiceException e) { row.put("message", e.getMessage()); row.put("success", false); }
|
||||
catch (RuntimeException e) {
|
||||
LOG.error("Purchase price lock failed for request {}", id, e);
|
||||
row.put("message", "本条锁价失败,事务已回滚,请刷新后重试"); row.put("success", false);
|
||||
}
|
||||
result.add(row);
|
||||
}
|
||||
return AjaxResult.success(result);
|
||||
}
|
||||
}
|
||||
@ -45,6 +45,41 @@ import com.ruoyi.project.service.IProjectInfoService;
|
||||
@RequestMapping("/warehouse/purchase")
|
||||
public class PurchaseRequestController extends BaseController
|
||||
{
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.PurchaseSheetService sheetService;
|
||||
@Autowired private com.ruoyi.system.service.ISysDictTypeService dictTypes;
|
||||
@Autowired private org.springframework.jdbc.core.JdbcTemplate sheetDatabase;
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
@GetMapping("/sheet/options")
|
||||
public AjaxResult sheetOptions()
|
||||
{
|
||||
var result = new java.util.LinkedHashMap<String, Object>();
|
||||
result.put("items", productInfoService.selectProductInfoAll());
|
||||
result.put("units", dictTypes.selectDictDataByType("wms_item_unit"));
|
||||
result.put("plans", sheetDatabase.queryForList("select t.id,t.project_id projectId,t.task_no taskNo,p.product_name productName from production_task t left join product_info p on p.id=t.item_id order by t.id desc"));
|
||||
return success(result);
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
@GetMapping("/sheet/{id}")
|
||||
public AjaxResult sheet(@PathVariable Long id) { return success(sheetService.load(id)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:edit,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)); }
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@Log(title = "确认整批采购", businessType = BusinessType.UPDATE)
|
||||
@PostMapping("/sheet/{id}/confirm")
|
||||
public AjaxResult confirmSheet(@PathVariable Long id, @RequestBody java.util.Map<String, String> data) { return success(sheetService.confirm(id, data.get("version"))); }
|
||||
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.WarehouseImportReceiptService importReceipts;
|
||||
@PostMapping("/importPreview") @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:import,warehouse:purchase:manage')")
|
||||
public AjaxResult importPreview(MultipartFile file)throws Exception{
|
||||
WarehouseFileUtils.validateUpload(file,10L*1024*1024,Set.of("xls","xlsx"));
|
||||
try(var input=file.getInputStream()){return success(purchaseRequestService.previewImport(new ExcelUtil<>(PurchaseRequest.class).importExcel(input)));}
|
||||
}
|
||||
@Autowired
|
||||
private IPurchaseRequestService purchaseRequestService;
|
||||
|
||||
@ -83,15 +118,33 @@ 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(query));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping("/filtered-totals")
|
||||
public AjaxResult totals(PurchaseRequest query){
|
||||
var rows=purchaseRequestService.selectPurchaseRequestList(query);java.math.BigDecimal locked=java.math.BigDecimal.ZERO,amount=java.math.BigDecimal.ZERO;int missing=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());}
|
||||
return success(java.util.Map.of("count",rows.size(),"amount",amount,"lockedAmount",locked,"unpriced",missing));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:export,warehouse:purchase:manage')")
|
||||
@Log(title = "采购申请", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/export")
|
||||
public void export(HttpServletResponse response, PurchaseRequest purchaseRequest) throws Exception
|
||||
public void export(HttpServletResponse response, PurchaseRequest purchaseRequest, @org.springframework.web.bind.annotation.RequestParam(required=false) Long[] ids) throws Exception
|
||||
{
|
||||
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());
|
||||
}
|
||||
@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{
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
com.ruoyi.common.utils.file.FileUtils.setAttachmentResponseHeader(response,"供应商采购汇总.xlsx");
|
||||
var rows=purchaseRequestService.selectPurchaseRequestList(query);
|
||||
if(ids!=null && ids.length>0){var selected=new java.util.HashSet<>(java.util.Arrays.asList(ids));rows=rows.stream().filter(row->selected.contains(row.getId())).toList();}
|
||||
try(var workbook=SupplierPurchaseExport.workbook(rows)){workbook.write(response.getOutputStream());}
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:import,warehouse:purchase:manage')")
|
||||
@Log(title = "采购申请", businessType = BusinessType.IMPORT)
|
||||
@ -101,7 +154,7 @@ public class PurchaseRequestController extends BaseController
|
||||
WarehouseFileUtils.validateUpload(file, 10L * 1024 * 1024, Set.of("xls", "xlsx"));
|
||||
ExcelUtil<PurchaseRequest> util = new ExcelUtil<PurchaseRequest>(PurchaseRequest.class);
|
||||
List<PurchaseRequest> requestList = util.importExcel(file.getInputStream());
|
||||
return success(purchaseRequestService.importPurchaseRequest(requestList, getUsername()));
|
||||
return success(importReceipts.apply("PURCHASE",file.getBytes(),()->purchaseRequestService.importPurchaseRequest(requestList,getUsername())));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:add,warehouse:purchase:manage')")
|
||||
@ -177,13 +230,18 @@ public class PurchaseRequestController extends BaseController
|
||||
{
|
||||
return success(purchaseArrivalService.selectPurchaseArrivalList(requestId));
|
||||
}
|
||||
public record CancelRemaining(java.math.BigDecimal expectedQuantity,String reason){}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@PostMapping("/{id}/cancel-remaining") @Log(title="取消未到货采购",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult cancelRemaining(@PathVariable Long id,@RequestBody CancelRemaining body){return toAjax(purchaseRequestService.cancelRemaining(id,body.expectedQuantity(),body.reason()));}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
@Log(title = "采购到货", businessType = BusinessType.INSERT)
|
||||
@PostMapping("/arrival")
|
||||
public AjaxResult addArrival(@Validated @RequestBody PurchaseArrival arrival)
|
||||
{
|
||||
return toAjax(purchaseArrivalService.insertPurchaseArrival(arrival));
|
||||
purchaseArrivalService.insertPurchaseArrival(arrival);
|
||||
return success(java.util.Map.of("id",arrival.getId(),"arrivalNo",arrival.getArrivalNo()));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
|
||||
|
||||
@ -0,0 +1,17 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseReturnService;
|
||||
@RestController @RequestMapping("/warehouse/purchase/returns")
|
||||
public class PurchaseReturnController extends BaseController {
|
||||
@Autowired private PurchaseReturnService service;
|
||||
@PostMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @Log(title="采购退货",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult returnGoods(@RequestBody PurchaseReturnService.Request request){service.returnGoods(request);return success();}
|
||||
@GetMapping @PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
|
||||
public AjaxResult history(Long arrivalId){return success(service.history(arrivalId));}
|
||||
}
|
||||
@ -33,13 +33,13 @@ public final class PurchaseTemplateExcelUtil
|
||||
{
|
||||
private static final String[] HEADERS = {
|
||||
"项目编码", "经费科目编码", "关联物料编码", "物料名称", "品牌", "类别", "参数规格", "采购链接",
|
||||
"需求数量", "预计含税单价", "单位", "期望到货日期", "产品备注", "申请备注"
|
||||
"需求数量", "最终含税单价", "单位", "产品备注", "申请备注"
|
||||
};
|
||||
|
||||
private static final String[] EXPORT_HEADERS = {
|
||||
"项目编码", "项目名称", "经费科目编码", "经费科目", "关联物料编码", "物料名称", "品牌", "类别", "参数规格", "采购链接",
|
||||
"需求数量", "预计含税单价", "预计总金额", "单位", "期望到货日期", "申请人", "采购状态", "采购批次", "进度说明",
|
||||
"产品备注", "申请备注", "已验收数量", "待验收数量"
|
||||
"需求数量", "最终含税单价", "采购总金额", "单位", "价格锁定", "已计项目费用", "采购状态", "采购批次", "进度说明",
|
||||
"产品备注", "申请备注", "已验收数量", "待验收数量", "采购用途", "归还借用记录", "关联生产任务", "供应商"
|
||||
};
|
||||
|
||||
private PurchaseTemplateExcelUtil()
|
||||
@ -110,7 +110,6 @@ public final class PurchaseTemplateExcelUtil
|
||||
}
|
||||
sheet.createFreezePane(0, 1);
|
||||
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
|
||||
for (int rowIndex = 0; rowIndex < requests.size(); rowIndex++)
|
||||
{
|
||||
PurchaseRequest request = requests.get(rowIndex);
|
||||
@ -119,11 +118,12 @@ public final class PurchaseTemplateExcelUtil
|
||||
request.getProjectCode(), request.getProjectName(), request.getExpenseCategoryCode(),
|
||||
request.getExpenseCategoryName(), request.getProductCode(), request.getMaterialName(), request.getMaterialBrand(),
|
||||
request.getCategory(), request.getMaterialParams(),
|
||||
request.getPurchaseLink(), request.getQuantity(), request.getEstimatedUnitPrice(), request.getEstimatedAmount(), request.getUnit(),
|
||||
request.getExpectedDate() == null ? null : dateFormat.format(request.getExpectedDate()),
|
||||
request.getApplicantName(), purchaseStatusLabel(request.getPurchaseStatus()),
|
||||
request.getPurchaseLink(), request.getQuantity(), request.getFinalUnitPrice(), request.getEstimatedAmount(), request.getUnit(),
|
||||
Boolean.TRUE.equals(request.getPriceLocked()) ? "已锁定" : "未锁定", request.getLockedAmount(),
|
||||
purchaseStatusLabel(request.getPurchaseStatus()),
|
||||
request.getPurchaseBatchNo(), request.getProgressRemark(), request.getProductRemark(),
|
||||
request.getRequestRemark(), request.getAcceptedQuantity(), request.getPendingArrivalQuantity()
|
||||
request.getRequestRemark(), request.getAcceptedQuantity(), request.getPendingArrivalQuantity(),
|
||||
"REPAY".equals(request.getPurchasePurpose()) ? "采购归还" : "本项目使用", request.getLoanId(), request.getProductionTaskId(), request.getSupplierName()
|
||||
};
|
||||
for (int column = 0; column < values.length; column++)
|
||||
{
|
||||
@ -182,7 +182,7 @@ public final class PurchaseTemplateExcelUtil
|
||||
validation.setSuppressDropDownArrow(true);
|
||||
validation.setErrorStyle(ErrorStyle.WARNING);
|
||||
validation.setShowErrorBox(true);
|
||||
validation.createErrorBox("不在系统数据中", "可以继续输入新值,确认后系统会新增或复用该属性");
|
||||
validation.createErrorBox("不在系统数据中", "请使用已有项目、费用分类及物品档案;新物品请先建立档案");
|
||||
validation.setShowPromptBox(false);
|
||||
sheet.addValidationData(validation);
|
||||
}
|
||||
|
||||
@ -84,6 +84,11 @@ public class StockCheckRecordController extends BaseController
|
||||
return toAjax(stockCheckRecordService.confirmStockCheckRecord(id, getUsername()));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:check:confirm')")
|
||||
@Log(title="撤销盘库",businessType=BusinessType.UPDATE)
|
||||
@PostMapping("/{id}/revoke")
|
||||
public AjaxResult revoke(@PathVariable Long id,@RequestBody java.util.Map<String,String> body){return toAjax(stockCheckRecordService.revoke(id,body.get("reason")));}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:check:remove')")
|
||||
@Log(title = "盘库记录", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ids}")
|
||||
|
||||
@ -36,6 +36,20 @@ public class StockInfoController extends BaseController
|
||||
|
||||
@Autowired
|
||||
private IStockLotService stockLotService;
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.InventoryCostJournal journal;
|
||||
public record MoveRequest(Long projectId,Long itemId,Long fromAreaId,Long toAreaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark) {}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:stock:query')") @GetMapping("/events")
|
||||
public AjaxResult events(Long projectId,Long itemId) { return success(journal.events(projectId,itemId)); }
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:stock:query')") @GetMapping("/adjustments")
|
||||
public AjaxResult adjustments(Long projectId,Long itemId){return success(journal.adjustments(projectId,itemId));}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:stock:out') and @ss.hasPermi('project:inventory:use')")
|
||||
@PostMapping("/move") @Log(title="项目库存移库",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult move(@RequestBody MoveRequest request) {
|
||||
return success(journal.move(request.projectId(),request.itemId(),request.fromAreaId(),request.toAreaId(),request.quantity(),request.key(),request.date(),request.remark()));
|
||||
}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:stock:out') and @ss.hasPermi('project:inventory:use')")
|
||||
@PostMapping("/move/{id}/revoke") @Log(title="撤销移库",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult revokeMove(@PathVariable Long id,@RequestBody java.util.Map<String,String> request){journal.revokeMove(id,request.get("reason"));return success();}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:stock:list')")
|
||||
@GetMapping("/list")
|
||||
|
||||
@ -0,0 +1,19 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.controller.BaseController;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.warehouse.service.impl.SupplierService;
|
||||
@RestController @RequestMapping("/warehouse/suppliers")
|
||||
public class SupplierController extends BaseController {
|
||||
@Autowired private SupplierService service;
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')") @GetMapping
|
||||
public AjaxResult list(String keyword){return success(service.list(keyword));}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')") @PostMapping @Log(title="供应商维护",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult save(@RequestBody SupplierService.Supplier input){service.save(input);return success();}
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')") @DeleteMapping("/{id}") @Log(title="删除未使用供应商",businessType=BusinessType.DELETE)
|
||||
public AjaxResult remove(@PathVariable Long id){service.remove(id);return success();}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
|
||||
/** Supplier-facing aggregation never changes internal project purchase lines. */
|
||||
public final class SupplierPurchaseExport {
|
||||
private SupplierPurchaseExport(){}
|
||||
private record Key(Long supplier,String batch,Long item){}
|
||||
private static final class Group {
|
||||
final PurchaseRequest first; BigDecimal quantity=BigDecimal.ZERO,amount=BigDecimal.ZERO;
|
||||
BigDecimal price; boolean missingPrice,multiplePrices; final Set<String> links=new LinkedHashSet<>();
|
||||
Group(PurchaseRequest first){this.first=first;this.price=first.getFinalUnitPrice();}
|
||||
void add(PurchaseRequest row){quantity=quantity.add(row.getQuantity());BigDecimal current=row.getFinalUnitPrice();if(current==null)missingPrice=true;else amount=amount.add(row.getQuantity().multiply(current));if(price==null?current!=null:current==null||price.compareTo(current)!=0)multiplePrices=true;if(row.getPurchaseLink()!=null&&!row.getPurchaseLink().isBlank())links.add(row.getPurchaseLink());}
|
||||
}
|
||||
public static XSSFWorkbook workbook(List<PurchaseRequest> lines){
|
||||
var groups=new LinkedHashMap<Key,Group>();
|
||||
for(var line:lines){if(Integer.valueOf(5).equals(line.getPurchaseStatus())||Boolean.TRUE.equals(line.getHistorical()))continue;if(line.getProductId()==null)throw new com.ruoyi.common.exception.ServiceException("采购 "+line.getRequestNo()+" 尚未关联物品档案,请先补全");var key=new Key(line.getSupplierId(),line.getPurchaseBatchNo(),line.getProductId());groups.computeIfAbsent(key,k->new Group(line)).add(line);}
|
||||
var workbook=new XSSFWorkbook();var sheet=workbook.createSheet("供应商采购汇总");String[] headers={"供应商","采购批次","物品编码","物品名称","品牌","规格型号","单位","采购数量","最终单价","采购金额","采购链接","说明"};var header=sheet.createRow(0);
|
||||
for(int i=0;i<headers.length;i++){header.createCell(i).setCellValue(headers[i]);sheet.setColumnWidth(i,(i==10?55:i==3||i==5?26:18)*256);}sheet.createFreezePane(0,1);int index=1;
|
||||
for(var group:groups.values()){var p=group.first;Object[] values={p.getSupplierName(),p.getPurchaseBatchNo(),p.getProductCode(),p.getMaterialName(),p.getMaterialBrand(),p.getMaterialParams(),p.getUnit(),group.quantity,group.multiplePrices?"多种单价":group.price,group.missingPrice?null:group.amount,String.join("\n",group.links),group.missingPrice?"存在未定价明细;已知金额 "+group.amount.toPlainString():"同批同物品合并;内部项目来源保留"};var row=sheet.createRow(index++);for(int i=0;i<values.length;i++){var cell=row.createCell(i);if(values[i] instanceof BigDecimal number)cell.setCellValue(number.doubleValue());else if(values[i]!=null)cell.setCellValue(values[i].toString());}}
|
||||
sheet.setAutoFilter(new org.apache.poi.ss.util.CellRangeAddress(0,Math.max(0,index-1),0,headers.length-1));return workbook;
|
||||
}
|
||||
}
|
||||
@ -6,7 +6,7 @@ spring:
|
||||
druid:
|
||||
# 主库数据源
|
||||
master:
|
||||
url: jdbc:mysql://192.168.28.10:3306/wms-dev?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
||||
url: jdbc:mysql://192.168.28.10:3306/cmvr-project-dev?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
||||
username: root
|
||||
password: cmvr2468
|
||||
# 从库数据源
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
ruoyi:
|
||||
# 名称
|
||||
name: RuoYi
|
||||
cacheNamespace: ${RUOYI_CACHE_NAMESPACE:cmvr-project-dev}
|
||||
# 版本
|
||||
version: 3.9.2
|
||||
# 版权年份
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!-- 日志存放路径 -->
|
||||
<property name="log.path" value="/home/ruoyi/logs" />
|
||||
<property name="log.path" value="${RUOYI_LOG_PATH:-logs}" />
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
|
||||
|
||||
@ -90,4 +90,4 @@
|
||||
<logger name="sys-user" level="info">
|
||||
<appender-ref ref="sys-user"/>
|
||||
</logger>
|
||||
</configuration>
|
||||
</configuration>
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.mapping.Environment;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
|
||||
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import com.ruoyi.framework.config.ProjectDatabaseGuard;
|
||||
|
||||
final class AuthorizedDatabaseTestSupport {
|
||||
private AuthorizedDatabaseTestSupport() { }
|
||||
static com.ruoyi.warehouse.service.impl.BusinessNumberService rawNumbers(org.springframework.jdbc.core.JdbcTemplate jdbc){var raw=new com.ruoyi.warehouse.service.impl.BusinessNumberService();org.springframework.test.util.ReflectionTestUtils.setField(raw,"jdbc",jdbc);return raw;}
|
||||
/** Fixture savepoints deliberately override independent allocation so test metadata also rolls back. */
|
||||
static com.ruoyi.warehouse.service.impl.BusinessNumberService numbers(org.springframework.jdbc.core.JdbcTemplate jdbc,org.springframework.transaction.PlatformTransactionManager manager){
|
||||
var raw=new com.ruoyi.warehouse.service.impl.BusinessNumberService();org.springframework.test.util.ReflectionTestUtils.setField(raw,"jdbc",jdbc);
|
||||
var source=new org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource();source.setTransactionAttribute(new org.springframework.transaction.interceptor.DefaultTransactionAttribute(org.springframework.transaction.TransactionDefinition.PROPAGATION_NESTED));
|
||||
var proxy=new org.springframework.aop.framework.ProxyFactory(raw);proxy.setProxyTargetClass(true);proxy.addAdvice(new org.springframework.transaction.interceptor.TransactionInterceptor(manager,source));return (com.ruoyi.warehouse.service.impl.BusinessNumberService)proxy.getProxy();
|
||||
}
|
||||
static Configuration configuration(String... resources) throws Exception {
|
||||
Configuration config = new Configuration(); config.getTypeAliasRegistry().registerAliases("com.ruoyi.warehouse.domain");
|
||||
// The manual test session spans many requests; do not reuse objects later mutated as request DTOs.
|
||||
config.setLocalCacheScope(LocalCacheScope.STATEMENT);
|
||||
for (String resource : resources) {
|
||||
try (var input = AuthorizedDatabaseTestSupport.class.getClassLoader().getResourceAsStream(resource)) {
|
||||
if (input == null) throw new IllegalStateException("Mapper missing: " + resource);
|
||||
new XMLMapperBuilder(input, config, resource, config.getSqlFragments()).parse();
|
||||
}
|
||||
}
|
||||
config.setEnvironment(new Environment("authorized-rollback-only", new JdbcTransactionFactory(), new UnpooledDataSource()));
|
||||
return config;
|
||||
}
|
||||
static Connection connection() throws Exception {
|
||||
Path root = Path.of(System.getProperty("user.dir")); if (!Files.isDirectory(root.resolve("ruoyi-admin"))) root = root.getParent();
|
||||
Map<?, ?> yaml;
|
||||
try (var input = Files.newInputStream(root.resolve("ruoyi-admin/src/main/resources/application-druid.yml"))) { yaml = new Yaml().load(input); }
|
||||
Map<?, ?> master = (Map<?, ?>) ((Map<?, ?>) ((Map<?, ?>) ((Map<?, ?>) yaml.get("spring")).get("datasource")).get("druid")).get("master");
|
||||
String url = resolve(String.valueOf(master.get("url"))); ProjectDatabaseGuard.assertAllowedUrl(url);
|
||||
Properties properties = new Properties(); properties.setProperty("user", resolve(String.valueOf(master.get("username"))));
|
||||
properties.setProperty("password", resolve(String.valueOf(master.get("password"))));
|
||||
properties.setProperty("connectTimeout", "5000"); properties.setProperty("socketTimeout", "15000");
|
||||
Connection connection = DriverManager.getConnection(url, properties);
|
||||
try {
|
||||
try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("select database()")) {
|
||||
if (!result.next() || !ProjectDatabaseGuard.ALLOWED_DATABASE.equals(result.getString(1))) throw new IllegalStateException("Wrong database");
|
||||
}
|
||||
connection.setAutoCommit(false); return connection;
|
||||
} catch (Exception failure) { connection.close(); throw failure; }
|
||||
}
|
||||
private static String resolve(String value) {
|
||||
if (!value.startsWith("${") || !value.endsWith("}")) return value;
|
||||
String inside = value.substring(2, value.length()-1); int separator = inside.indexOf(':');
|
||||
return Objects.requireNonNullElse(System.getenv(separator < 0 ? inside : inside.substring(0, separator)), separator < 0 ? "" : inside.substring(separator+1));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,111 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.mapper.BomMapper;
|
||||
import com.ruoyi.production.service.BomService;
|
||||
import com.ruoyi.project.domain.ProjectInfo;
|
||||
import com.ruoyi.project.mapper.ProjectInfoMapper;
|
||||
import com.ruoyi.project.service.impl.ProjectInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.ProductInfo;
|
||||
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
import com.ruoyi.warehouse.service.impl.ProductInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.service.impl.CatalogWriteLock;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BomDatabaseTest {
|
||||
private Configuration config() throws Exception {
|
||||
return AuthorizedDatabaseTestSupport.configuration("mapper/production/BomMapper.xml", "mapper/warehouse/ProductInfoMapper.xml", "mapper/project/ProjectInfoMapper.xml");
|
||||
}
|
||||
@Test void mapperStatementsParseWithoutDatabase() throws Exception {
|
||||
assertTrue(config().hasStatement(BomMapper.class.getName() + ".selectGraphLines"));
|
||||
}
|
||||
private ProductInfo item(ProductInfoMapper items, String suffix) {
|
||||
ProductInfo item = new ProductInfo(); item.setProductName("回滚BOM验证-" + suffix + UUID.randomUUID()); item.setUnit("件");
|
||||
item.setCategory("测试"); items.insertProductInfo(item); return item;
|
||||
}
|
||||
private BomLine line(Long itemId, String quantity, Long child) {
|
||||
BomLine line = new BomLine(); line.setItemId(itemId); line.setUnitQuantity(new BigDecimal(quantity)); line.setChildBomId(child); return line;
|
||||
}
|
||||
private BomVersion bom(Long itemId, String tag, boolean defaultVersion, BomLine... lines) {
|
||||
BomVersion bom = new BomVersion(); bom.setItemId(itemId); bom.setVersionTag(tag); bom.setIsDefault(defaultVersion); bom.setLines(new ArrayList<>(List.of(lines))); return bom;
|
||||
}
|
||||
@Test @EnabledIfSystemProperty(named="projectDbTests", matches="true")
|
||||
void nestedProjectAndTaskCopiesDefaultsCyclesAndHistoryStayInsideRollback() throws Exception {
|
||||
var factory = new SqlSessionFactoryBuilder().build(config());
|
||||
try (var connection = AuthorizedDatabaseTestSupport.connection()) {
|
||||
try (SqlSession session = factory.openSession(connection); var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("rollback-test");
|
||||
var mapper = session.getMapper(BomMapper.class); var items = session.getMapper(ProductInfoMapper.class);
|
||||
var projects = session.getMapper(ProjectInfoMapper.class);
|
||||
var projectService = new ProjectInfoServiceImpl(); ReflectionTestUtils.setField(projectService, "projectInfoMapper", projects);
|
||||
var service = new BomService(); ReflectionTestUtils.setField(service, "mapper", mapper);
|
||||
ReflectionTestUtils.setField(service, "items", items); ReflectionTestUtils.setField(service, "projects", projectService);
|
||||
ProductInfo robot = item(items, "机器人"), assembly = item(items, "组件"), screw = item(items, "螺丝");
|
||||
ProjectInfo project = new ProjectInfo(); project.setProjectCode("BOM-" + UUID.randomUUID()); project.setProjectName("回滚BOM项目");
|
||||
project.setProjectStatus(3); project.setProjectType("PRODUCT"); project.setTotalAmount(BigDecimal.ZERO); project.setCreateBy("rollback-test"); projects.insertProjectInfo(project);
|
||||
BomVersion child = service.save(bom(assembly.getId(), "v1", true, line(screw.getId(), "8", null)));
|
||||
BomVersion root = service.save(bom(robot.getId(), "v1", true, line(assembly.getId(), "0.0019", child.getId())));
|
||||
assertEquals(new BigDecimal("0.0019"), root.getLines().get(0).getUnitQuantity());
|
||||
ProjectProduct link = new ProjectProduct(); link.setProjectId(project.getId()); link.setItemId(robot.getId()); link.setBomId(root.getId());
|
||||
ProjectProduct linked = service.link(link); BomVersion projectBom = service.get(linked.getBomId());
|
||||
Long projectChildId = projectBom.getLines().get(0).getChildBomId();
|
||||
assertNotEquals(root.getId(), projectBom.getId()); assertNotEquals(child.getId(), projectChildId);
|
||||
assertEquals("PROJECT", projectBom.getScopeType()); assertEquals(root.getId(), projectBom.getSourceVersionId());
|
||||
child.getLines().get(0).setUnitQuantity(new BigDecimal("12")); service.save(child);
|
||||
assertEquals(new BigDecimal("8.0000"), service.get(projectChildId).getLines().get(0).getUnitQuantity());
|
||||
BomVersion task = service.snapshotForTask(projectBom.getId(), project.getId(), 999L);
|
||||
assertEquals("TASK", task.getScopeType()); assertNotEquals(projectChildId, task.getLines().get(0).getChildBomId());
|
||||
projectBom.getLines().get(0).setUnitQuantity(new BigDecimal("0.0020")); service.save(projectBom);
|
||||
assertEquals(new BigDecimal("0.0019"), service.get(task.getId()).getLines().get(0).getUnitQuantity());
|
||||
assertThrows(ServiceException.class, () -> service.save(task));
|
||||
// The same subassembly/tag can legitimately have two independently edited project copies.
|
||||
projectBom.getLines().add(line(assembly.getId(), "1", child.getId()));
|
||||
service.save(projectBom);
|
||||
BomVersion branchedTask = service.snapshotForTask(projectBom.getId(), project.getId(), 1000L);
|
||||
assertEquals(2, branchedTask.getLines().size());
|
||||
Long firstBranch = branchedTask.getLines().get(0).getChildBomId(), secondBranch = branchedTask.getLines().get(1).getChildBomId();
|
||||
assertNotEquals(firstBranch, secondBranch);
|
||||
assertEquals(new BigDecimal("8.0000"), service.get(firstBranch).getLines().get(0).getUnitQuantity());
|
||||
assertEquals(new BigDecimal("12.0000"), service.get(secondBranch).getLines().get(0).getUnitQuantity());
|
||||
BomVersion cycle = service.get(child.getId()); cycle.getLines().add(line(robot.getId(), "1", null));
|
||||
assertThrows(ServiceException.class, () -> service.save(cycle));
|
||||
session.clearCache();
|
||||
assertEquals(1, service.get(child.getId()).getLines().size());
|
||||
BomVersion v2 = service.copy(root.getId(), "v2", "默认版本验证", true);
|
||||
assertEquals(v2.getId(), mapper.selectDefault(robot.getId()).getId()); assertFalse(service.get(root.getId()).getIsDefault());
|
||||
assertThrows(ServiceException.class, () -> service.save(root));
|
||||
assertThrows(ServiceException.class, () -> service.delete(root.getId()));
|
||||
BomVersion publicCannotUseProject = bom(robot.getId(), "bad", false, line(assembly.getId(), "1", projectChildId));
|
||||
assertThrows(ServiceException.class, () -> service.save(publicCannotUseProject));
|
||||
assertEquals(2, service.list(robot.getId(), null).size()); assertTrue(service.logs(root.getId()).size() >= 1);
|
||||
assertTrue(projects.countProjectBusiness(project.getId()) > 0);
|
||||
var itemService = new ProductInfoServiceImpl(); ReflectionTestUtils.setField(itemService, "productInfoMapper", items);
|
||||
ReflectionTestUtils.setField(itemService, "catalogWriteLock", mock(CatalogWriteLock.class));
|
||||
assertThrows(ServiceException.class, () -> itemService.deleteProductInfoByIds(new Long[]{screw.getId()}));
|
||||
ProductInfo changedUnit = items.selectProductInfoById(screw.getId()); changedUnit.setUnit("包");
|
||||
assertThrows(ServiceException.class, () -> itemService.updateProductInfo(changedUnit));
|
||||
assertEquals("件", items.selectProductInfoById(screw.getId()).getUnit());
|
||||
BomVersion previous=service.get(root.getId());
|
||||
List<Long> lineIds=previous.getLines().stream().map(BomLine::getId).toList();
|
||||
BomVersion selected=service.setDefault(root.getId(),previous.getVersion());
|
||||
assertEquals(root.getId(),mapper.selectDefault(robot.getId()).getId());assertFalse(service.get(v2.getId()).getIsDefault());
|
||||
assertEquals(lineIds,selected.getLines().stream().map(BomLine::getId).toList());
|
||||
assertEquals(new BigDecimal("0.0019"),service.get(task.getId()).getLines().get(0).getUnitQuantity());
|
||||
assertTrue(service.logs(root.getId()).stream().anyMatch(log->"SET_DEFAULT".equals(log.get("operation"))));
|
||||
assertThrows(ServiceException.class,()->service.setDefault(root.getId(),previous.getVersion()));
|
||||
assertThrows(ServiceException.class,()->service.setDefault(task.getId(),task.getVersion()));
|
||||
Long rootId = root.getId(); session.rollback(true); session.clearCache();
|
||||
assertNull(mapper.selectVersion(rootId)); assertNull(projects.selectProjectInfoByCode(project.getProjectCode()));
|
||||
} finally { if (!connection.isClosed()) connection.rollback(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.util.BomGraphRules;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BomGraphRulesTest {
|
||||
private BomVersion version(long id, long item, BomLine... lines) {
|
||||
BomVersion bom = new BomVersion(); bom.setId(id); bom.setItemId(item); bom.setLines(List.of(lines)); return bom;
|
||||
}
|
||||
private BomLine line(long item, Long child) {
|
||||
BomLine line = new BomLine(); line.setItemId(item); line.setChildBomId(child); return line;
|
||||
}
|
||||
@Test void sharedSubassemblyAndOrdinaryScrewsAreValid() {
|
||||
BomVersion child = version(2, 20, line(30, null));
|
||||
BomVersion root = version(1, 10, line(20, 2L), line(20, 2L), line(30, null));
|
||||
assertDoesNotThrow(() -> BomGraphRules.validate(root, Map.of(1L, root, 2L, child)));
|
||||
}
|
||||
@Test void directSelfUseIsRejectedEvenWithoutChildVersion() {
|
||||
BomVersion root = version(1, 10, line(10, null));
|
||||
assertThrows(ServiceException.class, () -> BomGraphRules.validate(root, Map.of(1L, root)));
|
||||
}
|
||||
@Test void cyclesAcrossDifferentVersionsOfSameItemAreRejected() {
|
||||
BomVersion root = version(1, 10, line(20, 2L));
|
||||
BomVersion child = version(2, 20, line(10, 3L));
|
||||
BomVersion differentRoot = version(3, 10);
|
||||
assertThrows(ServiceException.class, () -> BomGraphRules.validate(root, Map.of(1L, root, 2L, child, 3L, differentRoot)));
|
||||
}
|
||||
@Test void missingOrMismatchingChildCannotBeSaved() {
|
||||
BomVersion root = version(1, 10, line(20, 2L));
|
||||
assertThrows(ServiceException.class, () -> BomGraphRules.validate(root, Map.of(1L, root)));
|
||||
assertThrows(ServiceException.class, () -> BomGraphRules.validate(root, Map.of(1L, root, 2L, version(2, 99))));
|
||||
}
|
||||
@Test void childMayNotContainAncestorAsPurchasedMaterialEither() {
|
||||
BomVersion root = version(1, 10, line(20, 2L));
|
||||
BomVersion child = version(2, 20, line(10, null));
|
||||
assertThrows(ServiceException.class, () -> BomGraphRules.validate(root, Map.of(1L, root, 2L, child)));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.production.service.BomService;
|
||||
import com.ruoyi.warehouse.domain.ProductInfo;
|
||||
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
import com.ruoyi.web.controller.production.BomController;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BomImportTest {
|
||||
@Test void previewChecksIdentityQuantityAndDoesNotSave() throws Exception {
|
||||
var controller=new BomController();var items=mock(ProductInfoMapper.class);var service=mock(BomService.class);
|
||||
ReflectionTestUtils.setField(controller,"items",items);ReflectionTestUtils.setField(controller,"service",service);
|
||||
for(long id=1;id<=4;id++){var item=new ProductInfo();item.setId(id);item.setProductCode("ITEM-"+id);item.setProductName("物品"+id);item.setUnit("件");when(items.checkProductCodeUnique(item.getProductCode())).thenReturn(item);}
|
||||
try(var workbook=new XSSFWorkbook();var bytes=new ByteArrayOutputStream()){
|
||||
var sheet=workbook.createSheet("用料");var header=sheet.createRow(0);header.createCell(0).setCellValue("物品编码");header.createCell(1).setCellValue("单台用量");
|
||||
String[][] values={{"ITEM-2","0.0019"},{"ITEM-2","1"},{"ITEM-1","1"},{"ITEM-3","0"},{"ITEM-4","0.00001"},{"UNKNOWN","1"}};
|
||||
for(int i=0;i<values.length;i++){var row=sheet.createRow(i+1);row.createCell(0).setCellValue(values[i][0]);row.createCell(1).setCellValue(values[i][1]);}
|
||||
workbook.write(bytes);var file=new MockMultipartFile("file","bom.xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",bytes.toByteArray());
|
||||
var rows=(List<Map<String,Object>>)controller.preview(file,1L).get("data");assertEquals(6,rows.size());assertNull(rows.get(0).get("error"));
|
||||
assertEquals(new BigDecimal("0.0019"),((com.ruoyi.production.domain.BomLine)rows.get(0).get("row")).getUnitQuantity());
|
||||
for(int i=1;i<rows.size();i++)assertNotNull(rows.get(i).get("error"));
|
||||
verifyNoInteractions(service);verify(items,never()).insertProductInfo(any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,86 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.mapper.BomMapper;
|
||||
import com.ruoyi.production.service.BomService;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.warehouse.domain.ProductInfo;
|
||||
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BomServiceTest {
|
||||
private BomMapper mapper;
|
||||
private ProductInfoMapper items;
|
||||
private BomService service;
|
||||
@BeforeEach void setup() {
|
||||
mapper = mock(BomMapper.class); items = mock(ProductInfoMapper.class); service = new BomService();
|
||||
ReflectionTestUtils.setField(service, "mapper", mapper); ReflectionTestUtils.setField(service, "items", items);
|
||||
ReflectionTestUtils.setField(service, "projects", mock(IProjectInfoService.class)); when(mapper.lockGraph()).thenReturn(1);
|
||||
ProductInfo item = new ProductInfo(); item.setId(1L); item.setProductName("机器人"); item.setUnit("台"); when(items.selectProductInfoById(anyLong())).thenReturn(item);
|
||||
}
|
||||
private BomVersion request() { BomVersion bom = new BomVersion(); bom.setItemId(1L); bom.setVersionTag("v1"); bom.setLines(new ArrayList<>()); return bom; }
|
||||
private BomLine line(String quantity) { BomLine line = new BomLine(); line.setItemId(2L); line.setUnitQuantity(new BigDecimal(quantity)); return line; }
|
||||
@Test void invalidQuantitiesNeverPersistLines() {
|
||||
for (String quantity : List.of("0", "-1", "0.00001", "10000000000000000")) {
|
||||
BomVersion bom = request(); bom.getLines().add(line(quantity)); assertThrows(ServiceException.class, () -> service.save(bom));
|
||||
}
|
||||
verify(mapper, never()).insertVersion(any()); verify(mapper, never()).insertLine(any());
|
||||
}
|
||||
@Test void missingUnitsMustBeFixedInArchiveBeforeUse() {
|
||||
ProductInfo item = new ProductInfo(); item.setProductName("缺单位物品"); when(items.selectProductInfoById(1L)).thenReturn(item);
|
||||
assertThrows(ServiceException.class, () -> service.save(request())); verify(mapper, never()).insertVersion(any());
|
||||
}
|
||||
@Test void taskSnapshotsAndStaleEditsAreProtected() {
|
||||
BomVersion existing = request(); existing.setId(9L); existing.setVersion(1); existing.setScopeType("TASK"); when(mapper.selectVersion(9L)).thenReturn(existing);
|
||||
BomVersion request = request(); request.setId(9L); request.setVersion(1);
|
||||
assertThrows(ServiceException.class, () -> service.save(request));
|
||||
existing.setScopeType("PUBLIC"); request.setVersion(0); assertThrows(ServiceException.class, () -> service.save(request));
|
||||
verify(mapper, never()).updateVersion(any());
|
||||
}
|
||||
@Test void publicBomCannotPointToPrivateProjectCopy() {
|
||||
BomVersion child = request(); child.setId(9L); child.setItemId(2L); child.setScopeType("PROJECT"); child.setProjectId(5L);
|
||||
when(mapper.selectVersion(9L)).thenReturn(child); BomVersion request = request(); BomLine line = line("1"); line.setChildBomId(9L); request.getLines().add(line);
|
||||
assertThrows(ServiceException.class, () -> service.save(request)); verify(mapper, never()).insertVersion(any());
|
||||
}
|
||||
@Test void newPublicBomIgnoresForgedScopeAndKeepsFractionalQuantity() {
|
||||
BomVersion request = request(); request.setScopeType("TASK"); request.setScopeKey("FORGED"); request.setProjectId(9L); request.setSourceVersionId(8L);
|
||||
request.getLines().add(line("0.001900")); request.setIsDefault(true);
|
||||
ProductionProduct product = new ProductionProduct(); product.setId(1L); product.setItemId(1L); when(mapper.selectProductByItem(1L)).thenReturn(product); when(mapper.selectProduct(1L)).thenReturn(product);
|
||||
doAnswer(call -> { ((BomVersion) call.getArgument(0)).setId(99L); return 1; }).when(mapper).insertVersion(any());
|
||||
when(mapper.selectVersion(99L)).thenAnswer(call -> request); when(mapper.selectLines(99L)).thenAnswer(call -> request.getLines());
|
||||
try (var security = mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::getUsername).thenReturn("tester"); service.save(request); }
|
||||
assertEquals("PUBLIC", request.getScopeType()); assertEquals("PUBLIC", request.getScopeKey()); assertNull(request.getProjectId()); assertNull(request.getSourceVersionId());
|
||||
assertEquals(new BigDecimal("0.0019"), request.getLines().get(0).getUnitQuantity()); verify(mapper).clearDefault(1L, null); verify(mapper).insertLine(any());
|
||||
}
|
||||
@Test void settingDefaultChangesMetadataOnlyAndDoesNotRewriteLines() {
|
||||
BomVersion bom=request();bom.setId(9L);bom.setScopeType("PUBLIC");bom.setVersion(0);bom.setIsDefault(false);
|
||||
when(mapper.selectVersion(9L)).thenReturn(bom);when(mapper.selectLines(9L)).thenReturn(List.of(line("2")));when(mapper.updateVersion(any())).thenReturn(1);
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("tester");
|
||||
BomVersion result=service.setDefault(9L,0);assertTrue(result.getIsDefault());assertEquals(1,result.getVersion());assertEquals(new BigDecimal("2"),result.getLines().get(0).getUnitQuantity());
|
||||
service.setDefault(9L,1);
|
||||
}
|
||||
verify(mapper).clearDefault(1L,9L);verify(mapper,times(1)).updateVersion(any());
|
||||
verify(mapper,never()).retireLines(anyLong());verify(mapper,never()).insertLine(any());verify(mapper,never()).insertVersion(any());
|
||||
verify(mapper).insertLog(any(),eq("SET_DEFAULT"),anyString(),eq("tester"));
|
||||
}
|
||||
@Test void privateAndStaleDefaultRequestsNeverPersist() {
|
||||
BomVersion bom=request();bom.setId(9L);bom.setScopeType("PUBLIC");bom.setVersion(2);when(mapper.selectVersion(9L)).thenReturn(bom);
|
||||
assertThrows(ServiceException.class,()->service.setDefault(9L,1));assertThrows(ServiceException.class,()->service.setDefault(9L,null));
|
||||
bom.setScopeType("PROJECT");assertThrows(ServiceException.class,()->service.setDefault(9L,2));
|
||||
verify(mapper,never()).clearDefault(anyLong(),anyLong());verify(mapper,never()).updateVersion(any());
|
||||
}
|
||||
@Test void productRemarkAndTaskIdAreValidated() {
|
||||
ProductionProduct product = new ProductionProduct(); product.setItemId(1L); product.setRemark("x".repeat(501));
|
||||
assertThrows(ServiceException.class, () -> service.saveProduct(product)); assertThrows(ServiceException.class, () -> service.snapshotForTask(1L, 1L, null));
|
||||
verify(mapper, never()).insertProduct(any()); verify(mapper, never()).insertVersion(any());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
|
||||
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
import com.ruoyi.warehouse.service.impl.BusinessNumberService;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@EnabledIfSystemProperty(named="projectDbTests",matches="true")
|
||||
class BusinessNumberDatabaseTest {
|
||||
@Test void allKindsMonthlyResetSeedAndReservationsPreserveHistory() throws Exception {
|
||||
try(var connection=AuthorizedDatabaseTestSupport.connection()) {
|
||||
var db=new JdbcTemplate(new SingleConnectionDataSource(connection,true));
|
||||
var numbers=AuthorizedDatabaseTestSupport.rawNumbers(db);
|
||||
var date=LocalDate.of(8900,1,1);
|
||||
String old="OLD-"+UUID.randomUUID();
|
||||
try {
|
||||
db.update("insert into product_info(product_code,product_name,unit) values(?,?,'件')",old,"编号回滚测试");
|
||||
db.update("insert into product_info(product_code,product_name,unit) values('WP8900010012',?,'件')","已有新规则编号回滚测试");
|
||||
for(var kind:BusinessNumberService.Kind.values()) {
|
||||
String no=numbers.next(kind.prefix,date);
|
||||
assertEquals(kind.prefix+"890001"+(kind==BusinessNumberService.Kind.ITEM?"0013":"0001"),no);
|
||||
}
|
||||
String key="rollback:"+UUID.randomUUID();
|
||||
assertEquals("WP8900010014",numbers.reserve("ITEM",date,key));
|
||||
assertEquals("WP8900010014",numbers.reserve("ITEM",date.plusMonths(1),key));
|
||||
assertEquals("WP8900020001",numbers.next("ITEM",date.plusMonths(1)));
|
||||
assertEquals(1,db.queryForObject("select count(*) from product_info where product_code=?",Integer.class,old));
|
||||
assertThrows(RuntimeException.class,()->numbers.next("invalid_table",date));
|
||||
} finally { connection.rollback(); }
|
||||
}
|
||||
}
|
||||
|
||||
private BusinessNumberService independent(JdbcTemplate db,DataSourceTransactionManager manager) {
|
||||
var proxy=new ProxyFactory(AuthorizedDatabaseTestSupport.rawNumbers(db));proxy.setProxyTargetClass(true);
|
||||
proxy.addAdvice(new TransactionInterceptor(manager,new AnnotationTransactionAttributeSource()));
|
||||
return (BusinessNumberService)proxy.getProxy();
|
||||
}
|
||||
|
||||
@Test void realIndependentTransactionsAllocateConcurrentlyAndSurviveServiceRestart() throws Exception {
|
||||
// Metadata-only future month. No projects, stock or documents are created or modified.
|
||||
var source=new AbstractDataSource() {
|
||||
@Override public Connection getConnection() throws SQLException {
|
||||
try {var c=AuthorizedDatabaseTestSupport.connection();c.setAutoCommit(true);return c;}
|
||||
catch(SQLException failure){throw failure;}catch(Exception failure){throw new SQLException(failure);}
|
||||
}
|
||||
@Override public Connection getConnection(String user,String password) throws SQLException {throw new SQLException("Explicit credentials unsupported");}
|
||||
};
|
||||
var db=new JdbcTemplate(source);var manager=new DataSourceTransactionManager(source);
|
||||
LocalDate date=LocalDate.of(8999,12,1);String month="899912",key="number-concurrency:"+UUID.randomUUID();
|
||||
String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(key.getBytes(StandardCharsets.UTF_8)));
|
||||
assertEquals(0,db.queryForObject("select count(*) from business_number_sequence where prefix='SC' and period=?",Integer.class,month));
|
||||
assertEquals(0,db.queryForObject("select count(*) from production_task where task_no like 'SC899912%'",Integer.class));
|
||||
var pool=Executors.newFixedThreadPool(4);
|
||||
try {
|
||||
var numbers=independent(db,manager);
|
||||
List<Callable<String>> calls=new ArrayList<>();for(int i=0;i<48;i++)calls.add(()->numbers.next("TASK",date));
|
||||
Set<String> allocated=new HashSet<>();for(var result:pool.invokeAll(calls))allocated.add(result.get());
|
||||
assertEquals(48,allocated.size());assertTrue(allocated.contains("SC8999120001"));assertTrue(allocated.contains("SC8999120048"));
|
||||
calls.clear();for(int i=0;i<16;i++)calls.add(()->numbers.reserve("TASK",date,key));
|
||||
Set<String> repeated=new HashSet<>();for(var result:pool.invokeAll(calls))repeated.add(result.get());
|
||||
assertEquals(Set.of("SC8999120049"),repeated);
|
||||
assertEquals("SC8999120049",numbers.reserve("TASK",date.minusMonths(1),key));
|
||||
assertEquals("SC8999120050",independent(db,manager).next("TASK",date));
|
||||
} finally {
|
||||
pool.shutdown();assertTrue(pool.awaitTermination(30,TimeUnit.SECONDS));
|
||||
// Resolve and validate the exact test-owned metadata before removing it.
|
||||
var cleanup=new org.springframework.transaction.support.TransactionTemplate(manager);
|
||||
cleanup.executeWithoutResult(status->{
|
||||
var counters=db.queryForList("select serial_value from business_number_sequence where prefix='SC' and period=? for update",Long.class,month);
|
||||
if(counters.isEmpty())return;
|
||||
long value=counters.get(0);assertTrue(value>0&&value<=50,"Unexpected counter modification; cleanup refused");
|
||||
assertEquals(0,db.queryForObject("select count(*) from production_task where task_no like 'SC899912%'",Integer.class));
|
||||
var reservations=db.queryForList("select business_no from business_number_reservation where prefix='SC' and business_no like 'SC899912%'",String.class);
|
||||
assertTrue(reservations.size()<=1,"Unexpected reservations; cleanup refused");
|
||||
for(String no:reservations)assertEquals(1,db.update("delete from business_number_reservation where prefix='SC' and request_hash=? and business_no=?",hash,no));
|
||||
assertEquals(1,db.update("delete from business_number_sequence where prefix='SC' and period=? and serial_value=?",month,value));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.util.List;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.project.domain.ExpenseCategory;
|
||||
import com.ruoyi.project.mapper.ProjectBudgetMapper;
|
||||
import com.ruoyi.project.service.impl.ProjectBudgetServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ConfirmedFieldContractTest
|
||||
{
|
||||
@Test
|
||||
void retiredCompatibilityCategoriesNeverReturnToBusinessMaintenance()
|
||||
{
|
||||
ProjectBudgetMapper mapper = mock(ProjectBudgetMapper.class);
|
||||
when(mapper.selectExpenseCategoryList(any())).thenReturn(List.of(
|
||||
category("MATERIAL", "材料费"), category("EQUIPMENT", "设备费"),
|
||||
category("PROCESSING", "加工费"), category("TRIAL", "试制费"),
|
||||
category("OTHER", "其他费用"), category("LEGACY", "历史待归属")));
|
||||
ProjectBudgetServiceImpl service = new ProjectBudgetServiceImpl();
|
||||
ReflectionTestUtils.setField(service, "projectBudgetMapper", mapper);
|
||||
|
||||
assertEquals(List.of("MATERIAL", "EQUIPMENT", "PROCESSING"),
|
||||
service.selectExpenseCategoryList(new ExpenseCategory()).stream()
|
||||
.map(ExpenseCategory::getCategoryCode).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void purchaseApiDoesNotExposeRemovedRequesterOrExpectedArrivalFields() throws Exception
|
||||
{
|
||||
PurchaseRequest request = new PurchaseRequest();
|
||||
request.setApplicantId(1L);
|
||||
request.setApplicantName("internal-audit-only");
|
||||
String json = new ObjectMapper().writeValueAsString(request);
|
||||
assertFalse(json.contains("applicantId"));
|
||||
assertFalse(json.contains("applicantName"));
|
||||
assertFalse(json.contains("expectedDate"));
|
||||
}
|
||||
|
||||
private ExpenseCategory category(String code, String name)
|
||||
{
|
||||
ExpenseCategory category = new ExpenseCategory();
|
||||
category.setCategoryCode(code);
|
||||
category.setCategoryName(name);
|
||||
return category;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,146 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.*;
|
||||
import org.springframework.transaction.interceptor.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.project.domain.ProjectInfo;
|
||||
import com.ruoyi.project.mapper.ProjectInfoMapper;
|
||||
import com.ruoyi.project.service.impl.ProjectInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.service.impl.InventoryCostJournal;
|
||||
import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class InventoryCostJournalDatabaseTest {
|
||||
private Configuration config() throws Exception {
|
||||
return AuthorizedDatabaseTestSupport.configuration("mapper/warehouse/InventoryCostMapper.xml", "mapper/warehouse/ProductInfoMapper.xml", "mapper/warehouse/WarehouseAreaMapper.xml", "mapper/project/ProjectInfoMapper.xml", "mapper/warehouse/OutRecordMapper.xml", "mapper/warehouse/StockInfoMapper.xml", "mapper/warehouse/StockCheckRecordMapper.xml");
|
||||
}
|
||||
private BigDecimal n(String value) { return new BigDecimal(value); }
|
||||
@Test void mapperStatementsParseWithoutDatabase() throws Exception {
|
||||
assertTrue(config().hasStatement(InventoryCostMapper.class.getName()+".insertChange"));
|
||||
}
|
||||
private ProjectInfo project(ProjectInfoMapper mapper,String code) {
|
||||
ProjectInfo project = new ProjectInfo(); project.setProjectCode(code); project.setProjectName("回滚库存成本验证");
|
||||
project.setProjectType("RESEARCH"); project.setProjectStatus(2); project.setTotalAmount(BigDecimal.ZERO); project.setCreateBy("rollback-test"); mapper.insertProjectInfo(project); return project;
|
||||
}
|
||||
@Test @EnabledIfSystemProperty(named="projectDbTests", matches="true")
|
||||
void crossAreaAverageIdempotencyRepricingAndAtomicRollbackUseOnlyTestDatabase() throws Exception {
|
||||
String key = "COST-"+UUID.randomUUID();
|
||||
try (var connection = AuthorizedDatabaseTestSupport.connection(); var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("rollback-test");
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
var source = new SingleConnectionDataSource(connection,true);
|
||||
var transactionManager = new DataSourceTransactionManager(source);
|
||||
Configuration config = config(); config.setEnvironment(new org.apache.ibatis.mapping.Environment("authorized-cost-test",new SpringManagedTransactionFactory(),source));
|
||||
var session = new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config));
|
||||
var mapper = session.getMapper(InventoryCostMapper.class); var projects = session.getMapper(ProjectInfoMapper.class);
|
||||
var items = session.getMapper(ProductInfoMapper.class); var areas = session.getMapper(WarehouseAreaMapper.class);
|
||||
var projectService = new ProjectInfoServiceImpl(); ReflectionTestUtils.setField(projectService,"projectInfoMapper",projects);
|
||||
var raw = new InventoryCostJournal(); ReflectionTestUtils.setField(raw,"mapper",mapper); ReflectionTestUtils.setField(raw,"projects",projectService);
|
||||
ReflectionTestUtils.setField(raw,"items",items); ReflectionTestUtils.setField(raw,"areas",areas);
|
||||
ReflectionTestUtils.setField(raw,"adjustmentDatabase",new org.springframework.jdbc.core.JdbcTemplate(source));
|
||||
var numbers=AuthorizedDatabaseTestSupport.numbers(new org.springframework.jdbc.core.JdbcTemplate(source),transactionManager);ReflectionTestUtils.setField(raw,"businessNumbers",numbers);
|
||||
// Each operation uses a real JDBC savepoint under an outer rollback-only fixture transaction.
|
||||
var attributes = new MatchAlwaysTransactionAttributeSource(); attributes.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED));
|
||||
var proxy = new ProxyFactory(raw); proxy.setProxyTargetClass(true); proxy.addAdvice(new TransactionInterceptor(transactionManager,attributes));
|
||||
var service = (InventoryCostJournal)proxy.getProxy();
|
||||
try {
|
||||
new TransactionTemplate(transactionManager).executeWithoutResult(status -> {
|
||||
status.setRollbackOnly();
|
||||
ProjectInfo project = project(projects,key), other = project(projects,key+"-OTHER");
|
||||
ProductInfo item = new ProductInfo(); item.setProductName(key); item.setUnit("件"); item.setCategory("测试"); items.insertProductInfo(item);
|
||||
List<WarehouseArea> available = areas.selectWarehouseAreaAll(); assertTrue(available.size()>=2);
|
||||
Long a=available.get(0).getId(), b=available.get(1).getId(), p=project.getId(), i=item.getId();
|
||||
InventoryCostEvent first = service.append(event(p,i,a,"RECEIPT",n("10"),n("100"),null,key+"-R1"));
|
||||
service.append(event(p,i,b,"RECEIPT",n("10"),n("300"),null,key+"-R2"));
|
||||
assertEquals(n("20.000000"),service.balance(p,i).getAverageUnitCost());
|
||||
assertThrows(ServiceException.class,() -> service.append(event(p,i,a,"ISSUE",n("15"),null,null,key+"-BADAREA")));
|
||||
assertNull(mapper.selectEventByKey(key+"-BADAREA")); assertEquals(n("10.0000"),mapper.selectAreaQuantity(p,i,a));
|
||||
InventoryCostEvent issued = service.append(event(p,i,a,"ISSUE",n("5"),null,null,key+"-OUT"));
|
||||
assertEquals(n("100.000000"),issued.getOriginalCost());
|
||||
assertEquals(issued.getId(),service.append(event(p,i,a,"ISSUE",n("5"),null,null,key+"-OUT")).getId());
|
||||
service.append(event(p,i,b,"RETURN",n("2"),null,issued.getId(),key+"-RETURN"));
|
||||
assertEquals(n("340.000000"),service.balance(p,i).getAmount());
|
||||
assertThrows(ServiceException.class,() -> service.append(event(p,i,b,"RETURN",n("4"),null,issued.getId(),key+"-BADRETURN")));
|
||||
assertNull(mapper.selectEventByKey(key+"-BADRETURN")); assertEquals(n("340.000000"),service.balance(p,i).getAmount());
|
||||
service.append(event(p,i,b,"RECEIPT",n("3"),n("90"),null,key+"-R3"));
|
||||
service.move(p,i,a,b,n("2"),key+"-MOVE");
|
||||
assertEquals(n("20.0000"),service.balance(p,i).getQuantity()); assertEquals(n("430.000000"),service.balance(p,i).getAmount());
|
||||
assertEquals(n("3.0000"),mapper.selectAreaQuantity(p,i,a)); assertEquals(n("17.0000"),mapper.selectAreaQuantity(p,i,b));
|
||||
assertThrows(ServiceException.class,() -> service.move(p,i,a,Long.MAX_VALUE,n("1"),key+"-FAILMOVE"));
|
||||
assertNull(mapper.selectEventByKey(key+"-FAILMOVE:out")); assertEquals(n("3.0000"),mapper.selectAreaQuantity(p,i,a));
|
||||
Integer version = service.balance(p,i).getVersion();
|
||||
InventoryCostRevision revision = service.reviseReceipt(first.getId(),n("200"),key+"-SETTLE",version);
|
||||
assertFalse(service.adjustments(p,i).isEmpty());
|
||||
assertEquals(n("515.000000"),service.balance(p,i).getAmount()); assertEquals(n("20.0000"),service.balance(p,i).getQuantity());
|
||||
InventoryCostEvent corrected = mapper.selectEvent(issued.getId()); assertEquals(n("100.000000"),corrected.getOriginalCost()); assertEquals(n("125.000000"),corrected.getEffectiveCost());
|
||||
assertEquals(n("100.000000"),mapper.selectEvent(first.getId()).getReceiptAmount());
|
||||
assertEquals(n("3.0000"),mapper.selectAreaQuantity(p,i,a)); assertEquals(n("17.0000"),mapper.selectAreaQuantity(p,i,b));
|
||||
Integer settledVersion = service.balance(p,i).getVersion();
|
||||
assertEquals(revision.getId(),service.reviseReceipt(first.getId(),n("200"),key+"-SETTLE",version).getId());
|
||||
assertEquals(settledVersion,service.balance(p,i).getVersion());
|
||||
assertThrows(ServiceException.class,() -> service.reviseReceipt(first.getId(),n("300"),key+"-SETTLE",version));
|
||||
assertThrows(ServiceException.class,() -> service.reviseReceipt(first.getId(),n("300"),key+"-STALE",version));
|
||||
assertEquals(n("515.000000"),service.balance(p,i).getAmount());
|
||||
assertThrows(ServiceException.class,() -> service.voidLastEvent(first.getId(),"逐步撤销验证"));
|
||||
service.voidMove(key+"-MOVE","移库纠错");
|
||||
assertEquals(n("515.000000"),service.balance(p,i).getAmount()); assertEquals(n("5.0000"),mapper.selectAreaQuantity(p,i,a));
|
||||
List<InventoryCostEvent> active = service.events(p,i).stream().filter(row -> Boolean.TRUE.equals(row.getActive())).toList();
|
||||
for (int position=active.size()-1;position>=0;position--) service.voidLastEvent(active.get(position).getId(),"回滚路径验证");
|
||||
assertEquals(n("0.0000"),service.balance(p,i).getQuantity()); assertEquals(n("0.000000"),service.balance(p,i).getAmount());
|
||||
assertThrows(ServiceException.class,() -> service.append(event(p,i,a,"ISSUE",n("5"),null,null,key+"-OUT")));
|
||||
service.append(event(p,i,a,"RECEIPT",n("1"),null,null,key+"-UNKNOWN")); assertFalse(service.balance(p,i).isComplete());
|
||||
service.append(event(p,i,a,"ISSUE",n("1"),null,null,key+"-UNKNOWNOUT")); assertTrue(service.balance(p,i).isComplete());
|
||||
service.append(event(p,i,a,"RECEIPT",n("2"),n("20"),null,key+"-KNOWN"));
|
||||
service.append(event(other.getId(),i,b,"RECEIPT",n("10"),n("999"),null,key+"-OTHERRECEIPT"));
|
||||
assertEquals(n("10.000000"),service.balance(p,i).getAverageUnitCost()); assertEquals(n("99.900000"),service.balance(other.getId(),i).getAverageUnitCost());
|
||||
var rawOut=new com.ruoyi.warehouse.service.impl.OutRecordServiceImpl();
|
||||
ReflectionTestUtils.setField(rawOut,"businessNumbers",numbers);
|
||||
ReflectionTestUtils.setField(rawOut,"outRecordMapper",session.getMapper(OutRecordMapper.class));
|
||||
ReflectionTestUtils.setField(rawOut,"journal",service);ReflectionTestUtils.setField(rawOut,"costs",mapper);ReflectionTestUtils.setField(rawOut,"projectInfoService",projectService);
|
||||
var outProxy=new ProxyFactory(rawOut);outProxy.setProxyTargetClass(true);outProxy.addAdvice(new TransactionInterceptor(transactionManager,attributes));
|
||||
var outbound=(com.ruoyi.warehouse.service.impl.OutRecordServiceImpl)outProxy.getProxy();
|
||||
var stockMapper=session.getMapper(StockInfoMapper.class);
|
||||
var filter=new StockInfo();filter.setProjectId(p);filter.setProductId(i);assertEquals(1,stockMapper.selectStockInfoList(filter).size());
|
||||
var out=new OutRecord();out.setOutNo("BOUT-"+key);out.setUsageProjectId(p);out.setProductId(i);out.setAreaId(a);out.setOutType(4);out.setOutNum(n("2"));out.setOutTime(java.util.Date.from(java.time.LocalDate.of(2020,1,2).atStartOfDay(java.time.ZoneId.systemDefault()).toInstant()));out.setRemark("现场批量领用");
|
||||
for(int oldType=1;oldType<=3;oldType++){out.setOutType(oldType);assertThrows(ServiceException.class,()->outbound.insertOutRecord(out));}
|
||||
out.setOutType(4);outbound.insertOutRecord(out);Long outId=out.getId();out.setId(null);outbound.insertOutRecord(out);assertEquals(outId,out.getId());assertEquals(n("0.0000"),service.balance(p,i).getQuantity());
|
||||
assertEquals(java.time.LocalDate.of(2020,1,2),mapper.selectEventByKey("OUT:"+out.getOutNo()).getBusinessDate());
|
||||
assertTrue(stockMapper.selectStockInfoList(filter).isEmpty());filter.setIncludeZero(true);assertFalse(stockMapper.selectStockInfoList(filter).isEmpty());
|
||||
out.setOutNum(n("1"));assertThrows(ServiceException.class,()->outbound.insertOutRecord(out));
|
||||
var rawWithdrawal=new com.ruoyi.warehouse.service.impl.BusinessWithdrawalService();
|
||||
ReflectionTestUtils.setField(rawWithdrawal,"db",new org.springframework.jdbc.core.JdbcTemplate(source));ReflectionTestUtils.setField(rawWithdrawal,"journal",service);ReflectionTestUtils.setField(rawWithdrawal,"outbound",outbound);
|
||||
var withdrawalProxy=new ProxyFactory(rawWithdrawal);withdrawalProxy.setProxyTargetClass(true);withdrawalProxy.addAdvice(new TransactionInterceptor(transactionManager,attributes));
|
||||
var withdrawal=(com.ruoyi.warehouse.service.impl.BusinessWithdrawalService)withdrawalProxy.getProxy();
|
||||
var request=new com.ruoyi.warehouse.service.impl.BusinessWithdrawalService.Request("OUT",outId,n("0.5"),key+"-PARTIAL","部分领多纠正");
|
||||
var correctedOut=withdrawal.withdraw(request);withdrawal.withdraw(request);Long remainingId=((Number)correctedOut.get("remaining_id")).longValue();
|
||||
assertEquals(n("0.5000"),service.balance(p,i).getQuantity());assertEquals(n("5.000000"),service.balance(p,i).getAmount());
|
||||
var remainder=outbound.selectOutRecordById(remainingId);assertEquals(n("1.5000"),remainder.getOutNum());assertEquals("现场批量领用",remainder.getRemark());assertEquals(java.time.LocalDate.of(2020,1,2),mapper.selectEvent(remainder.getCostEventId()).getBusinessDate());
|
||||
assertThrows(ServiceException.class,()->withdrawal.withdraw(new com.ruoyi.warehouse.service.impl.BusinessWithdrawalService.Request("OUT",outId,n("1"),key+"-PARTIAL","重复不同数量")));
|
||||
outbound.revoke(remainingId,"撤销剩余领用验证");assertEquals(n("2.0000"),service.balance(p,i).getQuantity());
|
||||
var moved=service.move(p,i,a,b,n("1"),"MOVE:"+key,java.time.LocalDate.of(2020,2,3),"现场移库");assertEquals("现场移库",moved.get(1).getRemark());service.revokeMove(moved.get(1).getId(),"撤销移库验证");assertEquals(n("2.0000"),mapper.selectAreaQuantity(p,i,a));
|
||||
var rawCheck=new com.ruoyi.warehouse.service.impl.StockCheckRecordServiceImpl();ReflectionTestUtils.setField(rawCheck,"stockCheckRecordMapper",session.getMapper(StockCheckRecordMapper.class));ReflectionTestUtils.setField(rawCheck,"journal",service);ReflectionTestUtils.setField(rawCheck,"costs",mapper);ReflectionTestUtils.setField(rawCheck,"projects",projectService);
|
||||
var checkProxy=new ProxyFactory(rawCheck);checkProxy.setProxyTargetClass(true);checkProxy.addAdvice(new TransactionInterceptor(transactionManager,attributes));var checking=(com.ruoyi.warehouse.service.impl.StockCheckRecordServiceImpl)checkProxy.getProxy();
|
||||
ReflectionTestUtils.setField(rawCheck,"businessNumbers",numbers);
|
||||
var check=new StockCheckRecord();check.setProjectId(p);check.setProductId(i);check.setAreaId(a);check.setRealNum(n("1"));check.setReason("盘亏验证");check.setCheckUser("rollback-test");checking.insertStockCheckRecord(check);checking.confirmStockCheckRecord(check.getId(),"rollback-test");assertEquals(n("1.0000"),mapper.selectAreaQuantity(p,i,a));
|
||||
checking.revoke(check.getId(),"纠正盘点");checking.revoke(check.getId(),"重试");assertEquals(n("2.0000"),mapper.selectAreaQuantity(p,i,a));assertEquals(2,checking.selectStockCheckRecordById(check.getId()).getCheckStatus());assertThrows(ServiceException.class,()->checking.confirmStockCheckRecord(check.getId(),"rollback-test"));assertThrows(ServiceException.class,()->checking.deleteStockCheckRecordByIds(new Long[]{check.getId()}));
|
||||
});
|
||||
assertNull(mapper.selectEventByKey(key+"-R1")); assertNull(projects.selectProjectInfoByCode(key));
|
||||
} finally { connection.rollback(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.util.MovingAverageCost;
|
||||
import com.ruoyi.warehouse.util.MovingAverageCost.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class MovingAverageCostTest {
|
||||
private BigDecimal n(String value) { return value == null ? null : new BigDecimal(value); }
|
||||
private Event receipt(long id, String qty, String value) { return new Event(id, Type.RECEIPT, n(qty), n(value), null, true); }
|
||||
private Event issue(long id, String qty) { return new Event(id, Type.ISSUE, n(qty), null, null, true); }
|
||||
private Event returned(long id, String qty, long source) { return new Event(id, Type.RETURN, n(qty), null, source, true); }
|
||||
@Test void differentPurchasePricesUseAverageNotFifo() {
|
||||
Result result = MovingAverageCost.replay(List.of(receipt(1,"10","100"), receipt(2,"10","300"), issue(3,"5")));
|
||||
assertEquals(n("100.000000"), result.events().get(2).amount()); assertEquals(n("300.000000"), result.balance().amount()); assertEquals(n("20.000000"), result.balance().averageUnitCost());
|
||||
}
|
||||
@Test void emptyInventoryClearsRoundingTail() {
|
||||
Result result = MovingAverageCost.replay(List.of(receipt(1,"3","1"), issue(2,"1"), issue(3,"1"), issue(4,"1")));
|
||||
assertEquals(n("0.333333"), result.events().get(1).amount()); assertEquals(n("0.333334"), result.events().get(2).amount()); assertEquals(n("0.333333"), result.events().get(3).amount());
|
||||
assertEquals(n("0.000000"), result.balance().amount()); assertEquals(n("0.0000"), result.balance().quantity());
|
||||
}
|
||||
@Test void returnUsesOriginalCostEvenAfterNewPriceReceipts() {
|
||||
Result result = MovingAverageCost.replay(List.of(receipt(1,"10","100"), issue(2,"5"), receipt(3,"5","150"), returned(4,"2",2)));
|
||||
assertEquals(n("20.000000"), result.events().get(3).amount()); assertEquals(n("220.000000"), result.balance().amount());
|
||||
}
|
||||
@Test void manyTinyReturnsDoNotOverReturnValue() {
|
||||
List<Event> events = new ArrayList<>(List.of(receipt(1,"10","0.000005"), issue(2,"10")));
|
||||
for (long id=3; id<=12; id++) events.add(returned(id,"1",2));
|
||||
Result result = MovingAverageCost.replay(events);
|
||||
assertEquals(n("0.000005"), result.balance().amount());
|
||||
assertEquals(n("0.000005"), result.events().stream().filter(value -> value.type()==Type.RETURN).map(Valuation::amount).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
}
|
||||
@Test void settlementRepricesConsumedAndReturnedCostsWithoutChangingOriginalsOrQuantities() {
|
||||
List<Event> events = List.of(receipt(1,"10","100"), issue(2,"6"), returned(3,"2",2));
|
||||
Result original = MovingAverageCost.replay(events), settled = MovingAverageCost.replay(events, Map.of(1L,n("200")));
|
||||
assertEquals(n("120.000000"), settled.events().get(1).amount()); assertEquals(n("40.000000"), settled.events().get(2).amount()); assertEquals(n("120.000000"), settled.balance().amount());
|
||||
assertEquals(original.balance().quantity(), settled.balance().quantity()); assertEquals(n("100"), events.get(0).amount());
|
||||
List<Difference> changes = MovingAverageCost.differences(original, settled); assertEquals(3,changes.size()); assertEquals(n("60.000000"),changes.get(1).delta());
|
||||
assertTrue(MovingAverageCost.differences(settled, MovingAverageCost.replay(events, Map.of(1L,n("200")))).isEmpty());
|
||||
}
|
||||
@Test void settlementWhenAllStockConsumedStillAdjustsConsumption() {
|
||||
List<Event> events = List.of(receipt(1,"10","100"), issue(2,"10"));
|
||||
Result settled = MovingAverageCost.replay(events, Map.of(1L,n("250")));
|
||||
assertEquals(n("250.000000"), settled.events().get(1).amount()); assertEquals(n("0.000000"), settled.balance().amount());
|
||||
}
|
||||
@Test void missingHistoricalPricesRemainUnknownNotZeroAndCanLaterBeResolved() {
|
||||
List<Event> events = List.of(receipt(1,"10",null), receipt(2,"10","100"), issue(3,"5"));
|
||||
Result unknown = MovingAverageCost.replay(events); assertFalse(unknown.balance().complete()); assertNull(unknown.events().get(2).amount()); assertNull(unknown.balance().averageUnitCost());
|
||||
Result resolved = MovingAverageCost.replay(events, Map.of(1L,n("100"))); assertEquals(n("10.000000"),resolved.balance().averageUnitCost()); assertNull(MovingAverageCost.differences(unknown,resolved).get(0).delta());
|
||||
}
|
||||
@Test void unknownInventoryCanReachZeroAndNewInventoryBeKnown() {
|
||||
Result result = MovingAverageCost.replay(List.of(receipt(1,"1",null), issue(2,"1"), receipt(3,"2","20")));
|
||||
assertNull(result.events().get(1).amount()); assertEquals(n("10.000000"), result.balance().averageUnitCost());
|
||||
Result unknownReturn = MovingAverageCost.replay(List.of(receipt(1,"1",null), issue(2,"1"), receipt(3,"2","20"), returned(4,"1",2)));
|
||||
assertNull(unknownReturn.balance().amount());
|
||||
}
|
||||
@Test void negativeInventoryOverReturnsInvalidSourcesAndOrderAreRejected() {
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(issue(1,"1"))));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(receipt(1,"1","1"), issue(2,"1"), returned(3,"2",2))));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(receipt(1,"1","1"), returned(2,"1",1))));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(receipt(2,"1","1"), receipt(1,"1","1"))));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(receipt(1,"1","1")),Map.of(9L,n("2"))));
|
||||
}
|
||||
@Test void quantityAndPricePrecisionRemainFourAndSixPlaces() {
|
||||
assertEquals(n("0.002346"), MovingAverageCost.receiptAmount(n("0.0019"),n("1.234567")));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.receiptAmount(n("0.00001"),n("1")));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.receiptAmount(n("1"),n("0.0000001")));
|
||||
assertNull(MovingAverageCost.receiptAmount(n("1"),null));
|
||||
}
|
||||
@Test void voidedSourceCannotRemainLinkedAndCostAdjustmentsCannotChangeQuantities() {
|
||||
Event voidIssue = new Event(2,Type.ISSUE,n("1"),null,null,false);
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.replay(List.of(receipt(1,"1","1"),voidIssue,returned(3,"1",2))));
|
||||
Result before = MovingAverageCost.replay(List.of(receipt(1,"1","1")));
|
||||
Result after = MovingAverageCost.replay(List.of(receipt(1,"2","2")));
|
||||
assertThrows(ServiceException.class, () -> MovingAverageCost.differences(before,after));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.ruoyi.framework.config.NamespacedRedisKeySerializer;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class NamespacedRedisKeySerializerTest {
|
||||
@Test void keysPatternsAndDeletionRoundTripStayInsideNamespace() {
|
||||
var serializer = new NamespacedRedisKeySerializer("cmvr-project-dev");
|
||||
assertEquals("cmvr-project-dev:*",new String(serializer.serialize("*"),StandardCharsets.UTF_8));
|
||||
assertEquals("sys_config:*",serializer.deserialize(serializer.serialize("sys_config:*")));
|
||||
assertEquals("login_tokens:test",serializer.deserialize(serializer.serialize("login_tokens:test")));
|
||||
assertThrows(RuntimeException.class,() -> serializer.deserialize("other:token".getBytes(StandardCharsets.UTF_8)));
|
||||
assertNull(serializer.serialize(null)); assertNull(serializer.deserialize(null));
|
||||
}
|
||||
@Test void wildcardNamespacesCannotEscapeIsolation() {
|
||||
assertThrows(IllegalArgumentException.class,() -> new NamespacedRedisKeySerializer("*"));
|
||||
assertThrows(IllegalArgumentException.class,() -> new NamespacedRedisKeySerializer(""));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.*;
|
||||
import org.springframework.transaction.interceptor.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.project.domain.*;
|
||||
import com.ruoyi.project.mapper.*;
|
||||
import com.ruoyi.project.service.*;
|
||||
import com.ruoyi.project.service.impl.ProjectInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.service.*;
|
||||
import com.ruoyi.warehouse.service.impl.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class OptionalInitializationDatabaseTest {
|
||||
static BigDecimal n(String v){return new BigDecimal(v);}
|
||||
static void set(Object object,String field,Object value){ReflectionTestUtils.setField(object,field,value);}
|
||||
static <T>T tx(T target,DataSourceTransactionManager manager){var source=new MatchAlwaysTransactionAttributeSource();source.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED));var factory=new ProxyFactory(target);factory.setProxyTargetClass(true);factory.addAdvice(new TransactionInterceptor(manager,source));return (T)factory.getProxy();}
|
||||
@Test @EnabledIfSystemProperty(named="projectDbTests",matches="true") void optionalImportsDoNotDoubleInventoryExpensesOrDebt()throws Exception{
|
||||
try(var connection=AuthorizedDatabaseTestSupport.connection();var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(SecurityUtils::getUsername).thenReturn("rollback-test");
|
||||
var ds=new SingleConnectionDataSource(connection,true);var db=new JdbcTemplate(ds);var tm=new DataSourceTransactionManager(ds);
|
||||
var config=AuthorizedDatabaseTestSupport.configuration("mapper/project/ProjectInfoMapper.xml","mapper/project/ProjectBudgetMapper.xml","mapper/project/ProjectLoanMapper.xml","mapper/warehouse/PurchaseRequestMapper.xml","mapper/warehouse/PurchaseArrivalMapper.xml","mapper/warehouse/PurchaseBatchMapper.xml","mapper/warehouse/InRecordMapper.xml","mapper/warehouse/InventoryCostMapper.xml","mapper/warehouse/ProductInfoMapper.xml","mapper/warehouse/WarehouseAreaMapper.xml");
|
||||
config.setEnvironment(new org.apache.ibatis.mapping.Environment("initialization-rollback",new SpringManagedTransactionFactory(),ds));var session=new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config));
|
||||
var pm=session.getMapper(ProjectInfoMapper.class);var items=session.getMapper(ProductInfoMapper.class);var areas=session.getMapper(WarehouseAreaMapper.class);var budgets=session.getMapper(ProjectBudgetMapper.class);var requests=session.getMapper(PurchaseRequestMapper.class);var receiptMapper=session.getMapper(InRecordMapper.class);var arrivalMapper=session.getMapper(PurchaseArrivalMapper.class);
|
||||
var projects=new ProjectInfoServiceImpl();set(projects,"projectInfoMapper",pm);var rawJournal=new InventoryCostJournal();set(rawJournal,"mapper",session.getMapper(InventoryCostMapper.class));set(rawJournal,"projects",projects);set(rawJournal,"items",items);set(rawJournal,"areas",areas);var journal=tx(rawJournal,tm);
|
||||
var rawLoans=new ProjectLoanService();set(rawLoans,"mapper",session.getMapper(ProjectLoanMapper.class));set(rawLoans,"journal",journal);set(rawLoans,"projects",projects);var loans=tx(rawLoans,tm);
|
||||
var logs=mock(IPurchaseOperationLogService.class);var rawPrice=new PurchasePriceService();set(rawPrice,"purchaseRequestMapper",requests);set(rawPrice,"projectBudgetMapper",budgets);set(rawPrice,"projectInfoService",projects);set(rawPrice,"operationLogService",logs);var price=tx(rawPrice,tm);
|
||||
var rawPurchase=new PurchaseRequestServiceImpl();set(rawPurchase,"purchaseRequestMapper",requests);set(rawPurchase,"productInfoMapper",items);set(rawPurchase,"purchaseArrivalMapper",arrivalMapper);set(rawPurchase,"projectInfoMapper",pm);set(rawPurchase,"projectBudgetMapper",budgets);set(rawPurchase,"projectInfoService",projects);set(rawPurchase,"priceService",price);set(rawPurchase,"purchaseOperationLogService",logs);set(rawPurchase,"loans",loans);set(rawPurchase,"taskDatabase",db);var purchase=tx(rawPurchase,tm);
|
||||
var rawArrival=new PurchaseArrivalServiceImpl();set(rawArrival,"journal",journal);set(rawArrival,"database",db);set(rawArrival,"purchaseRequestMapper",requests);set(rawArrival,"purchaseArrivalMapper",arrivalMapper);set(rawArrival,"inRecordMapper",receiptMapper);set(rawArrival,"purchaseOperationLogService",logs);var arrival=tx(rawArrival,tm);
|
||||
var rawIn=new InRecordServiceImpl();set(rawIn,"inRecordMapper",receiptMapper);set(rawIn,"journal",journal);set(rawIn,"projectInfoService",projects);set(rawIn,"loans",loans);set(rawIn,"purchaseRequestMapper",requests);set(rawIn,"purchaseOperationLogService",logs);var inbound=tx(rawIn,tm);
|
||||
var rawInit=new InitializationService();set(rawInit,"db",db);set(rawInit,"journal",journal);set(rawInit,"inbound",inbound);set(rawInit,"purchases",purchase);set(rawInit,"arrivals",arrival);var init=tx(rawInit,tm);
|
||||
var numbers=AuthorizedDatabaseTestSupport.numbers(db,tm);for(var target:List.of(rawJournal,rawLoans,rawPurchase,rawArrival,rawIn,rawInit,rawPrice))set(target,"businessNumbers",numbers);
|
||||
String prefix="INIT-"+UUID.randomUUID();new TransactionTemplate(tm).executeWithoutResult(status->{status.setRollbackOnly();
|
||||
var p=new ProjectInfo();p.setProjectCode(prefix);p.setProjectName(prefix);p.setProjectType("RESEARCH");p.setProjectStatus(0);p.setTotalAmount(n("1000"));pm.insertProjectInfo(p);
|
||||
var lender=new ProjectInfo();lender.setProjectCode(prefix+"L");lender.setProjectName(prefix+"L");lender.setProjectType("PRODUCT");lender.setProjectStatus(3);lender.setTotalAmount(n("0"));pm.insertProjectInfo(lender);
|
||||
var item=new ProductInfo();item.setProductCode(prefix);item.setProductName(prefix);item.setUnit("件");item.setCategory("测试");items.insertProductInfo(item);var area=areas.selectWarehouseAreaAll().get(0);
|
||||
var suppliers=new SupplierService();set(suppliers,"db",db);suppliers.save(new SupplierService.Supplier(null,prefix,"联系人","123","测试",null));Long supplier=((Number)suppliers.list(prefix).get(0).get("id")).longValue();
|
||||
var row=new InitializationService.Row();row.sourceKey=prefix+"-stock";row.projectCode=p.getProjectCode();row.itemCode=item.getProductCode();row.areaName=area.getAreaName();row.quantity=n("5");row.unitPrice=n("3");row.date=LocalDate.of(2020,1,2);
|
||||
assertNull(init.preview("STOCK",List.of(row)).get(0).get("error"));init.apply("STOCK",row);init.apply("STOCK",row);assertEquals(n("5.0000"),journal.balance(p.getId(),item.getId()).getQuantity());assertEquals(n("15.000000"),journal.balance(p.getId(),item.getId()).getAmount());
|
||||
var debt=new InitializationService.Row();debt.sourceKey=prefix+"-loan";debt.projectCode=p.getProjectCode();debt.lenderCode=lender.getProjectCode();debt.itemCode=item.getProductCode();debt.quantity=n("4");debt.returnedQuantity=n("1");Long loanId=((Number)init.apply("LOAN",debt).get("businessId")).longValue();assertEquals(n("3.0000"),loans.get(loanId).getOutstandingQuantity());assertEquals(n("5.0000"),journal.balance(p.getId(),item.getId()).getQuantity());
|
||||
loans.returnStock(loanId,area.getId(),area.getId(),n("1"),prefix+"-repay");assertEquals(n("2.0000"),loans.get(loanId).getOutstandingQuantity());assertThrows(ServiceException.class,()->loans.revokeLoan(loanId,"仍有系统归还"));loans.revokeStockReturn(loanId,"LOAN-RETURN:"+prefix+"-repay","撤销归还");loans.revokeLoan(loanId,"撤销历史余额");assertEquals(n("5.0000"),journal.balance(p.getId(),item.getId()).getQuantity());
|
||||
var history=new InitializationService.Row();history.sourceKey=prefix+"-purchase";history.projectCode=p.getProjectCode();history.itemCode=item.getProductCode();history.supplierName=prefix;history.categoryCode="MATERIAL";history.quantity=n("10");history.unitPrice=n("2");history.receivedQuantity=n("6");history.acceptedQuantity=n("2");history.date=LocalDate.of(2019,2,3);
|
||||
var result=init.apply("PURCHASE",history);Long archive=((Number)result.get("businessId")).longValue(),ongoing=((Number)result.get("relatedId")).longValue();init.apply("PURCHASE",history);
|
||||
assertTrue(requests.selectPurchaseRequestByIdForUpdate(archive).getHistorical());assertEquals(n("6.0000"),requests.selectPurchaseRequestByIdForUpdate(archive).getAcceptedQuantity()==null?requests.selectPurchaseRequestById(archive,null).getAcceptedQuantity():requests.selectPurchaseRequestByIdForUpdate(archive).getAcceptedQuantity());assertEquals(n("4.0000"),requests.selectPurchaseRequestByIdForUpdate(ongoing).getQuantity());
|
||||
assertEquals(n("5.0000"),journal.balance(p.getId(),item.getId()).getQuantity());assertEquals(0,pm.selectProjectInfoById(p.getId(),null).getSpentAmount().signum());price.lockPrice(archive);price.lockPrice(ongoing);assertEquals(n("20.000000"),pm.selectProjectInfoById(p.getId(),null).getSpentAmount());
|
||||
var batch=session.getMapper(PurchaseBatchMapper.class).selectPurchaseBatchList(new PurchaseBatch()).stream().filter(b->supplier.equals(b.getSupplierId())).findFirst().orElseThrow();assertEquals(prefix,batch.getSupplierName());assertThrows(ServiceException.class,()->suppliers.remove(supplier));
|
||||
var request=new PurchaseRequest();request.setSupplierId(supplier);assertEquals(2,requests.selectPurchaseRequestList(request).size());request.setNotArrived(true);assertEquals(1,requests.selectPurchaseRequestList(request).size());
|
||||
var extra=new PurchaseArrival();extra.setPurchaseRequestId(archive);extra.setArrivalQuantity(n("1"));extra.setArrivalDate(new java.util.Date());assertThrows(ServiceException.class,()->arrival.insertPurchaseArrival(extra));
|
||||
var replacement=new PurchaseArrival();replacement.setPurchaseRequestId(ongoing);replacement.setArrivalQuantity(n("2"));replacement.setArrivalDate(new java.util.Date());replacement.setRequestKey(prefix);arrival.insertPurchaseArrival(replacement);Long arrivalId=replacement.getId();arrival.insertPurchaseArrival(replacement);assertEquals(arrivalId,replacement.getId());assertEquals(2,arrivalMapper.selectPurchaseArrivalList(ongoing).size());
|
||||
var expanded=requests.selectPurchaseRequestById(ongoing,null);expanded.setQuantity(n("6"));purchase.updatePurchaseRequest(expanded);assertEquals(n("24.000000"),pm.selectProjectInfoById(p.getId(),null).getSpentAmount());
|
||||
assertThrows(ServiceException.class,()->purchase.cancelRemaining(ongoing,n("5"),"过期数量"));purchase.cancelRemaining(ongoing,n("6"),"不再采购剩余数量");purchase.cancelRemaining(ongoing,n("6"),"重试取消");assertEquals(n("4.0000"),requests.selectPurchaseRequestByIdForUpdate(ongoing).getQuantity());assertEquals(n("20.000000"),pm.selectProjectInfoById(p.getId(),null).getSpentAmount());assertThrows(ServiceException.class,()->purchase.cancelRemaining(archive,n("6"),"历史不可取消剩余"));
|
||||
var previewRow=new PurchaseRequest();previewRow.setProjectCode(p.getProjectCode());previewRow.setExpenseCategoryCode("MATERIAL");previewRow.setProductCode(item.getProductCode());previewRow.setQuantity(n("1"));previewRow.setFinalUnitPrice(n("2"));Long before=db.queryForObject("select count(*) from purchase_request where project_id=?",Long.class,p.getId());assertNull(purchase.previewImport(List.of(previewRow)).get(0).get("error"));assertEquals(before,db.queryForObject("select count(*) from purchase_request where project_id=?",Long.class,p.getId()));
|
||||
var rawImport=new WarehouseImportReceiptService();set(rawImport,"db",db);set(rawImport,"journal",journal);var importer=tx(rawImport,tm);var calls=new java.util.concurrent.atomic.AtomicInteger();byte[] content=prefix.getBytes(java.nio.charset.StandardCharsets.UTF_8);importer.apply("PRODUCT",content,()->"新增 "+calls.incrementAndGet());importer.apply("PRODUCT",content,()->"新增 "+calls.incrementAndGet());assertEquals(1,calls.get());
|
||||
});assertEquals(0,db.queryForObject("select count(*) from project_info where project_code=?",Integer.class,prefix));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package com.ruoyi.projectdev;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.domain.ProductInfo;
|
||||
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
import com.ruoyi.warehouse.service.impl.ProductInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.service.impl.CatalogWriteLock;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
class ProductImportTest {
|
||||
ProductInfo row(){var r=new ProductInfo();r.setProductName("测试螺丝");r.setUnit("个");r.setCategory("零件");return r;}
|
||||
ProductInfoServiceImpl service(ProductInfoMapper mapper){var service=new ProductInfoServiceImpl();ReflectionTestUtils.setField(service,"productInfoMapper",mapper);ReflectionTestUtils.setField(service,"catalogWriteLock",mock(CatalogWriteLock.class));var numbers=mock(com.ruoyi.warehouse.service.impl.BusinessNumberService.class);when(numbers.reserve(eq("ITEM"),any(),any())).thenReturn("WP2026100001");ReflectionTestUtils.setField(service,"businessNumbers",numbers);return service;}
|
||||
@Test void previewIsReadOnlyAndDetectsDuplicateFileRows(){var mapper=mock(ProductInfoMapper.class);var service=service(mapper);var result=service.previewImport(List.of(row(),row()));assertNull(result.get(0).get("error"));assertNotNull(result.get(1).get("error"));verify(mapper,never()).insertProductInfo(any());assertThrows(ServiceException.class,()->service.importNew(List.of(row(),row())));verify(mapper,never()).insertProductInfo(any());}
|
||||
@Test void newItemsReceiveCodesAndExistingCodesCannotBeOverwritten(){var mapper=mock(ProductInfoMapper.class);var service=service(mapper);var item=row();service.insertProductInfo(item);assertEquals("WP2026100001",item.getProductCode());var existing=row();existing.setId(9L);when(mapper.checkProductCodeUnique("OLD")).thenReturn(existing);var duplicate=row();duplicate.setProductCode("OLD");assertThrows(ServiceException.class,()->service.insertProductInfo(duplicate));var missing=row();missing.setUnit(null);assertThrows(ServiceException.class,()->service.insertProductInfo(missing));}
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.*;
|
||||
import org.springframework.transaction.interceptor.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.mapper.BomMapper;
|
||||
import com.ruoyi.production.service.*;
|
||||
import com.ruoyi.project.domain.ProjectInfo;
|
||||
import com.ruoyi.project.mapper.ProjectInfoMapper;
|
||||
import com.ruoyi.project.service.impl.ProjectInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.service.impl.*;
|
||||
import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ProductionLifecycleDatabaseTest {
|
||||
private static BigDecimal n(String value){return new BigDecimal(value);}
|
||||
private static Long id(Map<String,Object> value){return ((Number)value.get("id")).longValue();}
|
||||
private static void set(Object target,String field,Object value){ReflectionTestUtils.setField(target,field,value);}
|
||||
private static <T>T proxy(T target,DataSourceTransactionManager tm){var attrs=new MatchAlwaysTransactionAttributeSource();attrs.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED));var p=new ProxyFactory(target);p.setProxyTargetClass(true);p.addAdvice(new TransactionInterceptor(tm,attrs));return (T)p.getProxy();}
|
||||
private static ProductionCommand command(String kind,Long task,Long project,Long item,Long area,String quantity,Long source){var c=new ProductionCommand();c.kind=kind;c.taskId=task;c.projectId=project;c.itemId=item;c.areaId=area;c.quantity=n(quantity);c.sourceId=source;c.key=UUID.randomUUID().toString();c.reason="回滚业务验证";if("DELIVERY".equals(kind))c.recipient="回滚测试接收方";return c;}
|
||||
@Test @EnabledIfSystemProperty(named="projectDbTests",matches="true") void productionSettlementPropagatesThroughConsumedDeliveredAndScrappedOutputs()throws Exception{
|
||||
try(var connection=AuthorizedDatabaseTestSupport.connection();var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::getUsername).thenReturn("rollback-test");var ds=new SingleConnectionDataSource(connection,true);var db=new JdbcTemplate(ds);var tm=new DataSourceTransactionManager(ds);
|
||||
var config=AuthorizedDatabaseTestSupport.configuration("mapper/production/BomMapper.xml","mapper/project/ProjectInfoMapper.xml","mapper/warehouse/InventoryCostMapper.xml","mapper/warehouse/ProductInfoMapper.xml","mapper/warehouse/WarehouseAreaMapper.xml","mapper/warehouse/InRecordMapper.xml");config.setEnvironment(new org.apache.ibatis.mapping.Environment("production-rollback",new SpringManagedTransactionFactory(),ds));var session=new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config));
|
||||
var pm=session.getMapper(ProjectInfoMapper.class);var items=session.getMapper(ProductInfoMapper.class);var areas=session.getMapper(WarehouseAreaMapper.class);var costs=session.getMapper(InventoryCostMapper.class);var receipts=session.getMapper(InRecordMapper.class);
|
||||
var projects=new ProjectInfoServiceImpl();set(projects,"projectInfoMapper",pm);var rawJournal=new InventoryCostJournal();set(rawJournal,"mapper",costs);set(rawJournal,"projects",projects);set(rawJournal,"items",items);set(rawJournal,"areas",areas);var journal=proxy(rawJournal,tm);
|
||||
var rawBoms=new BomService();set(rawBoms,"mapper",session.getMapper(BomMapper.class));set(rawBoms,"items",items);set(rawBoms,"projects",projects);var boms=proxy(rawBoms,tm);
|
||||
var rawProduction=new ProductionService();set(rawProduction,"db",db);set(rawProduction,"boms",boms);set(rawProduction,"journal",journal);set(rawProduction,"costs",costs);set(rawProduction,"receipts",receipts);set(rawProduction,"items",items);set(rawProduction,"projects",projects);var production=proxy(rawProduction,tm);
|
||||
var rawIn=new InRecordServiceImpl();set(rawIn,"inRecordMapper",receipts);set(rawIn,"journal",journal);set(rawIn,"projectInfoService",projects);set(rawIn,"production",production);set(rawIn,"loans",mock(com.ruoyi.project.service.ProjectLoanService.class));var inbound=proxy(rawIn,tm);
|
||||
var numbers=AuthorizedDatabaseTestSupport.numbers(db,tm);set(rawJournal,"businessNumbers",numbers);set(rawProduction,"businessNumbers",numbers);set(rawIn,"businessNumbers",numbers);
|
||||
String key="PRODTEST-"+UUID.randomUUID();new TransactionTemplate(tm).executeWithoutResult(status->{status.setRollbackOnly();
|
||||
var p=new ProjectInfo();p.setProjectCode(key);p.setProjectName(key);p.setProjectType("PRODUCT");p.setProjectStatus(2);p.setTotalAmount(n("0"));pm.insertProjectInfo(p);Long project=p.getId(),area=areas.selectWarehouseAreaAll().get(0).getId();
|
||||
List<Long> itemIds=new ArrayList<>();for(int x=0;x<3;x++){var i=new ProductInfo();i.setProductName(key+x);i.setUnit("件");items.insertProductInfo(i);itemIds.add(i.getId());}Long raw=itemIds.get(0),child=itemIds.get(1),finished=itemIds.get(2);db.update("insert into production_product(item_id,create_by) values(?,?)",finished,"rollback-test");
|
||||
journal.append(event(project,raw,area,"RECEIPT",n("20"),n("200"),null,key));
|
||||
var childBom=new BomVersion();childBom.setItemId(child);childBom.setVersionTag("V1");var line=new BomLine();line.setItemId(raw);line.setUnitQuantity(n("2"));childBom.setLines(List.of(line));childBom=boms.save(childBom);
|
||||
var parentBom=new BomVersion();parentBom.setItemId(finished);parentBom.setVersionTag("V1");var parentLine=new BomLine();parentLine.setItemId(child);parentLine.setUnitQuantity(n("2"));parentLine.setChildBomId(childBom.getId());parentBom.setLines(List.of(parentLine));parentBom=boms.save(parentBom);
|
||||
var pc=command(null,null,project,finished,null,"1",null);pc.bomId=parentBom.getId();Long parentTask=id(production.save(pc));assertEquals(parentTask,id(production.save(pc)));
|
||||
Long frozenChild=boms.get(((Number)production.task(parentTask).get("bom_id")).longValue()).getLines().get(0).getChildBomId();var cc=command(null,null,project,child,null,"2",null);cc.bomId=frozenChild;cc.parentTaskId=parentTask;Long childTask=id(production.save(cc));
|
||||
var issue=command("ISSUE",childTask,project,raw,area,"4",null);Long issueId=id(production.perform(issue));assertEquals(issueId,id(production.perform(issue)));
|
||||
Long completeId=id(production.perform(command("COMPLETE",childTask,project,null,null,"2",null)));Long root=db.queryForObject("select id from in_record where completion_id=? and receipt_root=1",Long.class,completeId);
|
||||
inbound.receive(root,area,n("1"),key+"-child1","rollback-test");inbound.receive(root,area,n("1"),key+"-child2","rollback-test");assertEquals(n("40.000000"),journal.balance(project,child).getAmount());
|
||||
production.perform(command("ISSUE",parentTask,project,child,area,"2",null));Long parentComplete=id(production.perform(command("COMPLETE",parentTask,project,null,null,"1",null)));Long parentRoot=db.queryForObject("select id from in_record where completion_id=? and receipt_root=1",Long.class,parentComplete);inbound.receive(parentRoot,area,n("1"),key+"-parent","rollback-test");
|
||||
var delivered=production.perform(command("DELIVERY",null,project,finished,area,"1",null));Long deliveryId=id(delivered),deliveryEvent=((Number)delivered.get("cost_event_id")).longValue();assertEquals(n("40.000000"),costs.selectEvent(deliveryEvent).getEffectiveCost());production.settle(parentTask);
|
||||
production.perform(command("RETURN",childTask,project,raw,area,"1",issueId));production.perform(command("SCRAP_ISSUED",childTask,project,raw,null,"1",issueId));production.settle(childTask);
|
||||
assertEquals(n("30.000000"),production.task(parentTask).get("material_cost"));assertEquals(n("30.000000"),costs.selectEvent(deliveryEvent).getEffectiveCost());assertEquals(n("40.000000"),costs.selectEvent(deliveryEvent).getOriginalCost());
|
||||
assertThrows(ServiceException.class,()->production.perform(command("RETURN",childTask,project,raw,area,"3",issueId)));
|
||||
production.perform(command("RETURN",childTask,project,raw,area,"1",issueId));assertEquals(n("20.000000"),costs.selectEvent(deliveryEvent).getEffectiveCost());
|
||||
production.perform(command("DELIVERY_RETURN",null,project,finished,area,"1",deliveryId));assertEquals(n("20.000000"),journal.balance(project,finished).getAmount());
|
||||
var scrap=production.perform(command("SCRAP_FINISHED",null,project,finished,area,"1",null));assertEquals(0,journal.balance(project,finished).getQuantity().signum());production.revoke(id(scrap),"恢复误报废");assertEquals(n("20.000000"),journal.balance(project,finished).getAmount());
|
||||
assertThrows(ServiceException.class,()->production.revoke(parentComplete,"仍有入库"));
|
||||
var lossCommand=command(null,null,project,child,null,"1",null);lossCommand.bomId=frozenChild;Long lossTask=id(production.save(lossCommand));production.perform(command("ISSUE",lossTask,project,raw,area,"1",null));production.perform(command("SCRAP_ASSEMBLY",lossTask,project,null,null,"1",null));production.settle(lossTask);assertNull(production.task(lossTask).get("unit_cost"));assertEquals(n("10.000000"),production.task(lossTask).get("material_cost"));
|
||||
var overPlanTaskCommand=command(null,null,project,child,null,"1",null);overPlanTaskCommand.bomId=frozenChild;Long overPlanTask=id(production.save(overPlanTaskCommand));var overPlanCompletion=command("COMPLETE",overPlanTask,project,null,null,"2",null);assertThrows(ServiceException.class,()->production.perform(overPlanCompletion));overPlanCompletion.adjustPlan=true;production.perform(overPlanCompletion);assertEquals(0,n(production.task(overPlanTask),"planned_quantity").compareTo(n("2.0000")));
|
||||
assertEquals(0,pm.selectProjectInfoById(project,null).getSpentAmount().signum());
|
||||
var rawWithdrawal=new BusinessWithdrawalService();set(rawWithdrawal,"db",db);set(rawWithdrawal,"journal",journal);set(rawWithdrawal,"production",production);var withdrawal=proxy(rawWithdrawal,tm);
|
||||
var partialScrap=production.perform(command("SCRAP_FINISHED",null,project,finished,area,"1",null));var partial=new BusinessWithdrawalService.Request("PRODUCTION",id(partialScrap),n("0.4"),key+"-partial","部分误报废");var correction=withdrawal.withdraw(partial);withdrawal.withdraw(partial);assertNotNull(correction.get("remaining_id"));assertEquals(n("0.4000"),journal.balance(project,finished).getQuantity());assertEquals(n("8.000000"),journal.balance(project,finished).getAmount());assertEquals(n("20.000000"),production.task(parentTask).get("material_cost"));assertThrows(ServiceException.class,()->withdrawal.withdraw(new BusinessWithdrawalService.Request("PRODUCTION",id(partialScrap),n("0.5"),key+"-partial","重复不同数量")));
|
||||
// Resuming preserves historical settlements, quantities and receipt costs; only the next settlement reprices outputs.
|
||||
var beforeResume=production.detail(childTask);int resumeVersion=((Number)beforeResume.get("version")).intValue();
|
||||
int historySize=((List<?>)beforeResume.get("settlements")).size();BigDecimal quantityBefore=journal.balance(project,finished).getQuantity();
|
||||
assertThrows(ServiceException.class,()->production.perform(command("ISSUE",childTask,project,raw,area,"1",null)));
|
||||
assertThrows(ServiceException.class,()->production.reopen(childTask,resumeVersion-1));
|
||||
assertEquals("SETTLED",production.task(childTask).get("status"));
|
||||
var resumed=production.reopen(childTask,resumeVersion);assertEquals("OPEN",resumed.get("status"));
|
||||
assertEquals(beforeResume.get("good_quantity"),resumed.get("good_quantity"));assertEquals(historySize,((List<?>)resumed.get("settlements")).size());
|
||||
assertEquals(quantityBefore,journal.balance(project,finished).getQuantity());assertEquals(n("20.000000"),costs.selectEvent(deliveryEvent).getEffectiveCost());
|
||||
assertEquals(n("10.000000"),production.receiptUnit(childTask));
|
||||
production.perform(command("ISSUE",childTask,project,raw,area,"1",null));
|
||||
assertThrows(ServiceException.class,()->production.perform(command("ISSUE",childTask,project,finished,area,"1",null)));
|
||||
assertThrows(ServiceException.class,()->production.settle(childTask,resumeVersion));
|
||||
production.settle(childTask,((Number)production.task(childTask).get("version")).intValue());
|
||||
assertEquals("SETTLED",production.task(childTask).get("status"));assertEquals(historySize+1,((List<?>)production.detail(childTask).get("settlements")).size());
|
||||
assertEquals(n("30.000000"),costs.selectEvent(deliveryEvent).getEffectiveCost());assertEquals(quantityBefore,journal.balance(project,finished).getQuantity());
|
||||
});assertEquals(0,db.queryForObject("select count(*) from project_info where project_code=?",Integer.class,key));
|
||||
}
|
||||
}
|
||||
private static BigDecimal n(Map<String,Object> row,String key){return new BigDecimal(String.valueOf(row.get(key)));}
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import com.ruoyi.framework.config.ProjectDatabaseGuard;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ProjectDatabaseGuardTest {
|
||||
private static final String ALLOWED = "jdbc:mysql://192.168.28.10:3306/cmvr-project-dev";
|
||||
@Test void onlyExactAuthorizedDatabaseAndHostAreAllowed() {
|
||||
assertDoesNotThrow(() -> ProjectDatabaseGuard.assertAllowedUrl(ALLOWED + "?characterEncoding=utf8"));
|
||||
for (String url : new String[] { null, ALLOWED + "-copy", ALLOWED.replace("cmvr-project-dev", "wms-dev"), ALLOWED.replace("cmvr-project-dev", "wms-test"), ALLOWED.replace("192.168.28.10", "127.0.0.1") })
|
||||
assertThrows(IllegalStateException.class, () -> ProjectDatabaseGuard.assertAllowedUrl(url));
|
||||
}
|
||||
@Test void initializationAndMultiStatementParametersCannotBypassGuard() {
|
||||
for (String parameter : new String[] { "sessionVariables=sql_mode=x", "initCommand=x", "allowMultiQueries=true" })
|
||||
assertThrows(IllegalStateException.class, () -> ProjectDatabaseGuard.assertAllowedUrl(ALLOWED + "?" + parameter));
|
||||
}
|
||||
@Test void guardRunsBeforeDataSourceInitialization() {
|
||||
try (DruidDataSource source = new DruidDataSource()) {
|
||||
source.setUrl(ALLOWED.replace("cmvr-project-dev", "wms-dev"));
|
||||
assertThrows(IllegalStateException.class, () -> new ProjectDatabaseGuard().postProcessBeforeInitialization(source, "masterDataSource"));
|
||||
assertFalse(source.isInited());
|
||||
}
|
||||
}
|
||||
@Test void springPropertyBindingOccursBeforeGuardWithoutConnecting() {
|
||||
new ApplicationContextRunner().withUserConfiguration(TestSource.class)
|
||||
.withPropertyValues("spring.datasource.druid.master.url=" + ALLOWED)
|
||||
.run(context -> {
|
||||
assertNull(context.getStartupFailure());
|
||||
assertEquals(ALLOWED, context.getBean(DruidDataSource.class).getUrl());
|
||||
assertFalse(context.getBean(DruidDataSource.class).isInited());
|
||||
});
|
||||
}
|
||||
@Test void springEnvironmentOverrideToAnotherDatabaseFailsBeforeConnection() {
|
||||
new ApplicationContextRunner().withUserConfiguration(TestSource.class)
|
||||
.withPropertyValues("spring.datasource.druid.master.url=" + ALLOWED.replace("cmvr-project-dev", "wms-test"))
|
||||
.run(context -> {
|
||||
assertNotNull(context.getStartupFailure());
|
||||
Throwable cause = context.getStartupFailure();
|
||||
while (cause.getCause() != null) cause = cause.getCause();
|
||||
assertInstanceOf(IllegalStateException.class, cause);
|
||||
});
|
||||
}
|
||||
@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties
|
||||
static class TestSource {
|
||||
@Bean static ProjectDatabaseGuard projectDatabaseGuard() { return new ProjectDatabaseGuard(); }
|
||||
@Bean @ConfigurationProperties("spring.datasource.druid.master")
|
||||
DruidDataSource masterDataSource() { return new DruidDataSource(); }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,63 @@
|
||||
package com.ruoyi.projectdev;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.*;
|
||||
import org.springframework.transaction.interceptor.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.project.domain.*;
|
||||
import com.ruoyi.project.mapper.*;
|
||||
import com.ruoyi.project.service.*;
|
||||
import com.ruoyi.project.service.impl.ProjectInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.service.impl.InventoryCostJournal;
|
||||
import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ProjectLoanDatabaseTest {
|
||||
private Configuration config()throws Exception{return AuthorizedDatabaseTestSupport.configuration("mapper/project/ProjectLoanMapper.xml","mapper/project/ProjectInfoMapper.xml","mapper/warehouse/InventoryCostMapper.xml","mapper/warehouse/ProductInfoMapper.xml","mapper/warehouse/WarehouseAreaMapper.xml");}
|
||||
@Test void xmlParses()throws Exception{assertTrue(config().hasStatement(ProjectLoanMapper.class.getName()+".insertReturn"));}
|
||||
private BigDecimal n(String s){return new BigDecimal(s);}
|
||||
private <T>T proxy(T target,DataSourceTransactionManager tm){var attrs=new MatchAlwaysTransactionAttributeSource();attrs.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED));var p=new ProxyFactory(target);p.setProxyTargetClass(true);p.addAdvice(new TransactionInterceptor(tm,attrs));return (T)p.getProxy();}
|
||||
@Test @EnabledIfSystemProperty(named="projectDbTests",matches="true") void borrowingRepaymentAndMultiHopCostCorrectionAreAtomic()throws Exception{
|
||||
String key="LOANTEST-"+UUID.randomUUID();
|
||||
try(var connection=AuthorizedDatabaseTestSupport.connection();var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::getUsername).thenReturn("rollback-test");var ds=new SingleConnectionDataSource(connection,true);var tm=new DataSourceTransactionManager(ds);var config=config();config.setEnvironment(new org.apache.ibatis.mapping.Environment("loan-rollback",new SpringManagedTransactionFactory(),ds));var session=new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config));
|
||||
var pm=session.getMapper(ProjectInfoMapper.class);var items=session.getMapper(ProductInfoMapper.class);var areas=session.getMapper(WarehouseAreaMapper.class);var costs=session.getMapper(InventoryCostMapper.class);var lm=session.getMapper(ProjectLoanMapper.class);
|
||||
var projects=new ProjectInfoServiceImpl();ReflectionTestUtils.setField(projects,"projectInfoMapper",pm);
|
||||
var raw=new InventoryCostJournal();ReflectionTestUtils.setField(raw,"mapper",costs);ReflectionTestUtils.setField(raw,"projects",projects);ReflectionTestUtils.setField(raw,"items",items);ReflectionTestUtils.setField(raw,"areas",areas);var journal=proxy(raw,tm);
|
||||
var loanRaw=new ProjectLoanService();ReflectionTestUtils.setField(loanRaw,"mapper",lm);ReflectionTestUtils.setField(loanRaw,"journal",journal);ReflectionTestUtils.setField(loanRaw,"projects",projects);var loans=proxy(loanRaw,tm);
|
||||
var numbers=AuthorizedDatabaseTestSupport.numbers(new org.springframework.jdbc.core.JdbcTemplate(ds),tm);ReflectionTestUtils.setField(raw,"businessNumbers",numbers);ReflectionTestUtils.setField(loanRaw,"businessNumbers",numbers);
|
||||
try{new TransactionTemplate(tm).executeWithoutResult(status->{status.setRollbackOnly();
|
||||
List<Long> ids=new ArrayList<>();for(int x=0;x<3;x++){var p=new ProjectInfo();p.setProjectCode(key+x);p.setProjectName("回滚借还验证");p.setProjectType("RESEARCH");p.setProjectStatus(2);p.setTotalAmount(n("0"));p.setCreateBy("rollback-test");pm.insertProjectInfo(p);ids.add(p.getId());}
|
||||
var item=new ProductInfo();item.setProductName(key);item.setUnit("件");items.insertProductInfo(item);Long i=item.getId(),a=areas.selectWarehouseAreaAll().get(0).getId(),b=areas.selectWarehouseAreaAll().get(1).getId(),p=ids.get(0),q=ids.get(1),r=ids.get(2);
|
||||
var receipt=journal.append(event(p,i,a,"RECEIPT",n("10"),n("100"),null,key));
|
||||
var first=loans.borrow(p,q,i,a,b,n("4"),key+"-BORROW",null);assertEquals(n("4.0000"),first.getOutstandingQuantity());
|
||||
assertEquals(first.getId(),loans.borrow(p,q,i,a,b,n("4"),key+"-BORROW",null).getId());assertEquals(1,loans.list(p,i,false).size());
|
||||
var second=loans.borrow(q,r,i,b,a,n("2"),key+"-SECOND",null);var consumed=journal.append(event(r,i,a,"ISSUE",n("2"),null,null,key+"-CONSUME"));
|
||||
assertEquals(n("20.000000"),consumed.getOriginalCost());journal.reviseReceipt(receipt.getId(),n("200"),key+"-SETTLE",journal.balance(p,i).getVersion());
|
||||
assertEquals(n("40.000000"),journal.balance(q,i).getAmount());assertEquals(n("40.000000"),costs.selectEvent(consumed.getId()).getEffectiveCost());assertEquals(n("20.000000"),costs.selectEvent(consumed.getId()).getOriginalCost());
|
||||
assertThrows(ServiceException.class,()->journal.reviseReceipt(first.getInEventId(),n("0"),key+"-BAD",journal.balance(q,i).getVersion()));
|
||||
var returned=loans.returnStock(first.getId(),b,a,n("1"),key+"-RETURN");assertEquals(n("1.0000"),returned.getReturnedQuantity());assertEquals(n("3.0000"),returned.getOutstandingQuantity());
|
||||
assertEquals(n("1.0000"),loans.returnStock(first.getId(),b,a,n("1"),key+"-RETURN").getReturnedQuantity());
|
||||
assertThrows(ServiceException.class,()->loans.returnStock(first.getId(),b,a,n("4"),key+"-EXCESS"));assertEquals(1,loans.returns(first.getId()).size());
|
||||
journal.reviseReceipt(receipt.getId(),n("100"),key+"-CORRECTION",journal.balance(p,i).getVersion());assertEquals(n("70.000000"),journal.balance(p,i).getAmount());assertEquals(n("10.000000"),journal.balance(q,i).getAmount());assertEquals(n("20.000000"),costs.selectEvent(consumed.getId()).getEffectiveCost());
|
||||
assertThrows(ServiceException.class,()->loans.revokeLoan(first.getId(),"已有下游"));assertTrue(loans.get(first.getId()).getActive());
|
||||
loans.revokeStockReturn(first.getId(),"LOAN-RETURN:"+key+"-RETURN","归还纠错");assertEquals(n("0.0000"),loans.get(first.getId()).getReturnedQuantity());
|
||||
journal.voidLastEvent(consumed.getId(),"先撤销消耗");loans.revokeLoan(second.getId(),"撤销第二层借用");loans.revokeLoan(first.getId(),"撤销首层借用");
|
||||
assertEquals(n("10.0000"),journal.balance(p,i).getQuantity());assertEquals(n("100.000000"),journal.balance(p,i).getAmount());assertEquals(n("0.0000"),journal.balance(q,i).getQuantity());
|
||||
});assertNull(costs.selectEventByKey(key));}finally{connection.rollback();}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,246 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.mapping.Environment;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
|
||||
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.framework.config.ProjectDatabaseGuard;
|
||||
import com.ruoyi.project.domain.*;
|
||||
import com.ruoyi.project.mapper.*;
|
||||
import com.ruoyi.project.service.impl.ProjectInfoServiceImpl;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchasePriceService;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** No application startup or Redis access. Database writes are explicitly opted in and always rolled back. */
|
||||
class ProjectPurchaseDatabaseTest {
|
||||
private Configuration configuration() throws Exception {
|
||||
Configuration config = new Configuration();
|
||||
config.getTypeAliasRegistry().registerAliases("com.ruoyi.warehouse.domain");
|
||||
for (String resource : List.of("mapper/project/ProjectInfoMapper.xml", "mapper/project/ProjectBudgetMapper.xml", "mapper/warehouse/PurchaseRequestMapper.xml", "mapper/warehouse/InRecordMapper.xml", "mapper/warehouse/StockInfoMapper.xml", "mapper/warehouse/StockLotMapper.xml", "mapper/warehouse/InventoryCostMapper.xml", "mapper/warehouse/ProductInfoMapper.xml", "mapper/warehouse/WarehouseAreaMapper.xml")) {
|
||||
try (var input = getClass().getClassLoader().getResourceAsStream(resource)) {
|
||||
assertNotNull(input, resource);
|
||||
new XMLMapperBuilder(input, config, resource, config.getSqlFragments()).parse();
|
||||
}
|
||||
}
|
||||
try (var input=getClass().getClassLoader().getResourceAsStream("mapper/warehouse/PurchaseArrivalMapper.xml")) {
|
||||
new XMLMapperBuilder(input,config,"mapper/warehouse/PurchaseArrivalMapper.xml",config.getSqlFragments()).parse();
|
||||
}
|
||||
return config;
|
||||
}
|
||||
@Test void mapperXmlAndStatementsParseWithoutDatabaseAccess() throws Exception {
|
||||
Configuration config = configuration();
|
||||
assertTrue(config.hasStatement(PurchaseRequestMapper.class.getName() + ".updatePriceState"));
|
||||
assertTrue(config.hasStatement(ProjectBudgetMapper.class.getName() + ".selectFundLedgerList"));
|
||||
}
|
||||
|
||||
@Test @EnabledIfSystemProperty(named = "projectDbTests", matches = "true")
|
||||
void actualMysqlLockEditCancelAndClosedProjectQueriesStayInsideRollback() throws Exception {
|
||||
Path root = Path.of(System.getProperty("user.dir"));
|
||||
if (!Files.isDirectory(root.resolve("ruoyi-admin"))) root = root.getParent();
|
||||
Map<?, ?> yaml;
|
||||
try (var input = Files.newInputStream(root.resolve("ruoyi-admin/src/main/resources/application-druid.yml"))) {
|
||||
yaml = new Yaml().load(input);
|
||||
}
|
||||
Map<?, ?> spring = (Map<?, ?>) yaml.get("spring");
|
||||
Map<?, ?> source = (Map<?, ?>) spring.get("datasource");
|
||||
Map<?, ?> druid = (Map<?, ?>) source.get("druid");
|
||||
Map<?, ?> master = (Map<?, ?>) druid.get("master");
|
||||
String url = resolve(String.valueOf(master.get("url")));
|
||||
ProjectDatabaseGuard.assertAllowedUrl(url);
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", resolve(String.valueOf(master.get("username"))));
|
||||
properties.setProperty("password", resolve(String.valueOf(master.get("password"))));
|
||||
properties.setProperty("connectTimeout", "5000"); properties.setProperty("socketTimeout", "15000");
|
||||
Configuration config = configuration();
|
||||
config.setEnvironment(new Environment("authorized-project-only", new JdbcTransactionFactory(), new UnpooledDataSource()));
|
||||
var factory = new SqlSessionFactoryBuilder().build(config);
|
||||
try (Connection connection = DriverManager.getConnection(url, properties)) {
|
||||
try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("select database()")) {
|
||||
assertTrue(result.next()); assertEquals(ProjectDatabaseGuard.ALLOWED_DATABASE, result.getString(1));
|
||||
}
|
||||
connection.setAutoCommit(false);
|
||||
try (SqlSession session = factory.openSession(connection); var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("rollback-test");
|
||||
ProjectInfoMapper projects = session.getMapper(ProjectInfoMapper.class);
|
||||
ProjectBudgetMapper budgets = session.getMapper(ProjectBudgetMapper.class);
|
||||
PurchaseRequestMapper purchases = session.getMapper(PurchaseRequestMapper.class);
|
||||
ProjectInfo project = new ProjectInfo(); project.setProjectCode("CHECK-" + UUID.randomUUID());
|
||||
project.setProjectName("事务回滚验证"); project.setProjectType("RESEARCH"); project.setProjectStatus(2);
|
||||
project.setTotalAmount(new BigDecimal("1000.00")); project.setCreateBy("rollback-test");
|
||||
assertEquals(1, projects.insertProjectInfo(project));
|
||||
ProjectInfoServiceImpl projectService = new ProjectInfoServiceImpl();
|
||||
ReflectionTestUtils.setField(projectService, "projectInfoMapper", projects);
|
||||
assertDoesNotThrow(() -> projectService.requireActiveProject(project.getId()));
|
||||
assertTrue(projects.selectProjectOptions(project.getProjectCode(), null, false).stream().anyMatch(row -> project.getId().equals(row.getId())));
|
||||
ExpenseCategory material = budgets.selectExpenseCategoryByCode("MATERIAL");
|
||||
ExpenseCategory equipment = budgets.selectExpenseCategoryByCode("EQUIPMENT");
|
||||
assertNotNull(material); assertNotNull(equipment);
|
||||
PurchaseRequest row = new PurchaseRequest(); row.setRequestNo("CHECK-" + UUID.randomUUID());
|
||||
row.setProjectId(project.getId()); row.setExpenseCategoryId(material.getId()); row.setMaterialName("回滚测试螺丝");
|
||||
row.setQuantity(new BigDecimal("0.0019")); row.setFinalUnitPrice(new BigDecimal("1.234567"));
|
||||
row.setUnit("件"); row.setApplicantId(1L); row.setApplicantName("rollback-test"); row.setPurchaseStatus(0);
|
||||
assertEquals(1, purchases.insertPurchaseRequest(row));
|
||||
assertEquals(0, projects.selectProjectInfoById(project.getId(), null).getSpentAmount().compareTo(BigDecimal.ZERO));
|
||||
PurchasePriceService pricing = new PurchasePriceService();
|
||||
ReflectionTestUtils.setField(pricing,"businessNumbers",AuthorizedDatabaseTestSupport.rawNumbers(new org.springframework.jdbc.core.JdbcTemplate(new org.springframework.jdbc.datasource.SingleConnectionDataSource(connection,true))));
|
||||
ReflectionTestUtils.setField(pricing, "purchaseRequestMapper", purchases);
|
||||
ReflectionTestUtils.setField(pricing, "projectBudgetMapper", budgets);
|
||||
ReflectionTestUtils.setField(pricing, "projectInfoService", projectService);
|
||||
ReflectionTestUtils.setField(pricing, "operationLogService", mock(IPurchaseOperationLogService.class));
|
||||
pricing.lockPrice(row.getId()); pricing.lockPrice(row.getId());
|
||||
PurchaseRequest locked = purchases.selectPurchaseRequestByIdForUpdate(row.getId());
|
||||
assertEquals(new BigDecimal("0.002346"), locked.getLockedAmount()); assertEquals(1, locked.getLockRevision());
|
||||
assertEquals(0, projects.selectProjectInfoById(project.getId(), null).getSpentAmount().compareTo(locked.getLockedAmount()));
|
||||
ProjectFundLedger query = new ProjectFundLedger(); query.setProjectId(project.getId());
|
||||
assertEquals(1, budgets.selectFundLedgerList(query, null).size());
|
||||
assertTrue(budgets.selectProjectBudgetList(project.getId(), null).get(0).getAvailableAmount().signum() < 0);
|
||||
PurchaseRequest changed = new PurchaseRequest();
|
||||
org.springframework.beans.BeanUtils.copyProperties(locked, changed);
|
||||
changed.setExpenseCategoryId(equipment.getId());
|
||||
assertEquals(1, purchases.updatePurchaseRequest(changed, null));
|
||||
pricing.refreshLockedAmount(locked, changed, "PRICE_MOVE");
|
||||
assertEquals(3, budgets.selectFundLedgerList(query, null).size());
|
||||
assertEquals(0, budgets.selectFundLedgerList(query, null).stream().map(ProjectFundLedger::getSpentDelta).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(locked.getLockedAmount()));
|
||||
PurchaseRequest beforeCancel = purchases.selectPurchaseRequestByIdForUpdate(row.getId());
|
||||
changed = new PurchaseRequest(); org.springframework.beans.BeanUtils.copyProperties(beforeCancel, changed);
|
||||
changed.setPurchaseStatus(5);
|
||||
purchases.updatePurchaseStatus(changed.getId(), 5, "回滚验证", "rollback-test"); pricing.refreshLockedAmount(beforeCancel, changed, "PRICE_CANCEL");
|
||||
assertEquals(0, projects.selectProjectInfoById(project.getId(), null).getSpentAmount().compareTo(BigDecimal.ZERO));
|
||||
assertEquals(0, budgets.selectFundLedgerList(query, null).stream().map(ProjectFundLedger::getSpentDelta).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(BigDecimal.ZERO));
|
||||
PurchaseRequest cancelled = purchases.selectPurchaseRequestByIdForUpdate(row.getId());
|
||||
PurchaseRequest reopened = new PurchaseRequest(); org.springframework.beans.BeanUtils.copyProperties(cancelled, reopened);
|
||||
reopened.setPurchaseStatus(0); purchases.updatePurchaseStatus(row.getId(), 0, "回滚验证", "rollback-test");
|
||||
pricing.refreshLockedAmount(cancelled, reopened, "PRICE_REOPEN");
|
||||
Long productId;
|
||||
try (PreparedStatement insert = connection.prepareStatement("insert into product_info(product_name,unit) values (?,?)", Statement.RETURN_GENERATED_KEYS)) {
|
||||
insert.setString(1, "回滚测试专用物品"); insert.setString(2, "件"); assertEquals(1, insert.executeUpdate());
|
||||
try (ResultSet key = insert.getGeneratedKeys()) { assertTrue(key.next()); productId = key.getLong(1); }
|
||||
}
|
||||
var receipts = session.getMapper(com.ruoyi.warehouse.mapper.InRecordMapper.class);
|
||||
var stocks = session.getMapper(com.ruoyi.warehouse.mapper.StockInfoMapper.class);
|
||||
var lots = session.getMapper(com.ruoyi.warehouse.mapper.StockLotMapper.class);
|
||||
var journal = new com.ruoyi.warehouse.service.impl.InventoryCostJournal();
|
||||
ReflectionTestUtils.setField(journal,"businessNumbers",AuthorizedDatabaseTestSupport.rawNumbers(new org.springframework.jdbc.core.JdbcTemplate(new org.springframework.jdbc.datasource.SingleConnectionDataSource(connection,true))));
|
||||
var costs=session.getMapper(com.ruoyi.warehouse.mapper.InventoryCostMapper.class);
|
||||
ReflectionTestUtils.setField(journal,"mapper",costs); ReflectionTestUtils.setField(journal,"projects",projectService);
|
||||
ReflectionTestUtils.setField(journal,"items",session.getMapper(com.ruoyi.warehouse.mapper.ProductInfoMapper.class));
|
||||
ReflectionTestUtils.setField(journal,"areas",session.getMapper(com.ruoyi.warehouse.mapper.WarehouseAreaMapper.class));
|
||||
var receiptService = new com.ruoyi.warehouse.service.impl.InRecordServiceImpl();
|
||||
var numbers=AuthorizedDatabaseTestSupport.rawNumbers(new org.springframework.jdbc.core.JdbcTemplate(new org.springframework.jdbc.datasource.SingleConnectionDataSource(connection,true)));
|
||||
ReflectionTestUtils.setField(receiptService,"businessNumbers",numbers);
|
||||
ReflectionTestUtils.setField(receiptService, "inRecordMapper", receipts);
|
||||
ReflectionTestUtils.setField(receiptService, "journal", journal);
|
||||
ReflectionTestUtils.setField(receiptService, "projectInfoService", projectService);
|
||||
ReflectionTestUtils.setField(receiptService,"loans",mock(com.ruoyi.project.service.ProjectLoanService.class));
|
||||
ReflectionTestUtils.setField(receiptService, "purchaseRequestMapper", purchases);
|
||||
ReflectionTestUtils.setField(receiptService, "purchaseOperationLogService", mock(IPurchaseOperationLogService.class));
|
||||
var receipt = new com.ruoyi.warehouse.domain.InRecord();
|
||||
Long areaId=session.getMapper(com.ruoyi.warehouse.mapper.WarehouseAreaMapper.class).selectWarehouseAreaAll().get(0).getId();
|
||||
receipt.setInNo("CHECK-" + UUID.randomUUID()); receipt.setProductId(productId); receipt.setAreaId(areaId);
|
||||
receipt.setPurchaseRequestId(row.getId()); receipt.setSourceProjectId(project.getId());
|
||||
receipt.setExpenseCategoryId(material.getId());
|
||||
receipt.setInType(2); receipt.setInNum(new BigDecimal("0.0019")); receipt.setInStatus(0);
|
||||
receipts.insertInRecord(receipt);
|
||||
assertEquals(1, receiptService.confirmInRecord(receipt.getId(), "rollback-test"));
|
||||
assertEquals(1, purchases.countConfirmedInbound(row.getId()));
|
||||
assertEquals(equipment.getId(), receipts.selectInRecordById(receipt.getId()).getExpenseCategoryId());
|
||||
assertEquals(new BigDecimal("0.0019"), stocks.selectStockInfoByAreaProduct(areaId, productId).getStockNum());
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class, () -> com.ruoyi.warehouse.util.PurchasePriceRules.requireEditablePrice(purchases.countConfirmedInbound(row.getId()), reopened.getFinalUnitPrice(), new BigDecimal("2")));
|
||||
assertEquals(1, receiptService.revokeInRecord(receipt.getId(), "价格维护", "rollback-test"));
|
||||
assertEquals(0, purchases.countConfirmedInbound(row.getId()));
|
||||
assertEquals(0, stocks.selectStockInfoByAreaProduct(areaId, productId).getStockNum().signum());
|
||||
assertEquals(0, projects.selectProjectInfoById(project.getId(), null).getSpentAmount().compareTo(new BigDecimal("0.002346")));
|
||||
PurchaseRequest oldPrice = purchases.selectPurchaseRequestByIdForUpdate(row.getId());
|
||||
PurchaseRequest newPrice = new PurchaseRequest(); org.springframework.beans.BeanUtils.copyProperties(oldPrice, newPrice);
|
||||
newPrice.setFinalUnitPrice(new BigDecimal("2.000000")); purchases.updatePurchaseRequest(newPrice, null);
|
||||
pricing.refreshLockedAmount(oldPrice, newPrice, "PRICE_EDIT");
|
||||
assertEquals(1, receiptService.confirmInRecord(receipt.getId(), "rollback-test"));
|
||||
var newReceipt=receipts.selectInRecordById(receipt.getId());
|
||||
assertEquals(new BigDecimal("2.000000"),newReceipt.getReceiptUnitCost());
|
||||
assertEquals(new BigDecimal("0.003800"),costs.selectEvent(newReceipt.getCostEventId()).getEffectiveCost());
|
||||
var issued=journal.append(com.ruoyi.warehouse.service.impl.InventoryCostJournal.event(project.getId(),productId,areaId,"ISSUE",new BigDecimal("0.0001"),null,null,"TEST-OUT:"+UUID.randomUUID()));
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class, () -> receiptService.revokeInRecord(receipt.getId(), "已有领用", "rollback-test"));
|
||||
assertEquals(1, receipts.selectInRecordById(receipt.getId()).getInStatus());
|
||||
journal.voidLastEvent(issued.getId(),"分次入库测试清理");
|
||||
receiptService.revokeInRecord(receipt.getId(),"测试分次入库", "rollback-test");
|
||||
var rootReceipt=new com.ruoyi.warehouse.domain.InRecord();
|
||||
org.springframework.beans.BeanUtils.copyProperties(receipt,rootReceipt);
|
||||
rootReceipt.setId(null);rootReceipt.setInNo("ROOT-"+UUID.randomUUID());rootReceipt.setReceiptRoot(true);rootReceipt.setCostEventId(null);rootReceipt.setCostRevision(0);rootReceipt.setInStatus(0);
|
||||
receipts.insertInRecord(rootReceipt);
|
||||
String firstKey="PART-"+UUID.randomUUID(),secondKey="PART-"+UUID.randomUUID();
|
||||
assertEquals(1,receiptService.receive(rootReceipt.getId(),areaId,new BigDecimal("0.0009"),firstKey,"rollback-test"));
|
||||
assertEquals(new BigDecimal("0.0010"),receipts.selectInRecordById(rootReceipt.getId()).getInNum());
|
||||
assertEquals(1,purchases.countConfirmedInbound(row.getId()));
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class,()->receiptService.receive(rootReceipt.getId(),areaId,new BigDecimal("0.0011"),secondKey,"rollback-test"));
|
||||
assertEquals(1,receiptService.receive(rootReceipt.getId(),areaId,new BigDecimal("0.0010"),secondKey,"rollback-test"));
|
||||
assertEquals(1,receiptService.receive(rootReceipt.getId(),areaId,new BigDecimal("0.0009"),firstKey,"rollback-test"));
|
||||
assertEquals(2,purchases.countConfirmedInbound(row.getId()));
|
||||
assertEquals(1,receipts.selectInRecordById(rootReceipt.getId()).getInStatus());
|
||||
var firstChild=receipts.checkInNoUnique(numbers.reserve("IN",null,"receipt:"+firstKey));
|
||||
var secondChild=receipts.checkInNoUnique(numbers.reserve("IN",null,"receipt:"+secondKey));
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class,()->receiptService.revokeInRecord(firstChild.getId(),"必须倒序撤销","rollback-test"));
|
||||
receiptService.revokeInRecord(secondChild.getId(),"退回待入库","rollback-test");
|
||||
assertEquals(new BigDecimal("0.0010"),receipts.selectInRecordById(rootReceipt.getId()).getInNum());
|
||||
assertEquals(1,purchases.countConfirmedInbound(row.getId()));
|
||||
assertEquals(2,receipts.selectInRecordById(secondChild.getId()).getInStatus());
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class,()->receiptService.confirmInRecord(secondChild.getId(),"rollback-test"));
|
||||
receiptService.revokeInRecord(firstChild.getId(),"退回待入库","rollback-test");
|
||||
assertEquals(0,purchases.countConfirmedInbound(row.getId()));
|
||||
assertEquals(new BigDecimal("0.0019"),receipts.selectInRecordById(rootReceipt.getId()).getInNum());
|
||||
assertEquals(0,stocks.selectStockInfoByAreaProduct(areaId,productId).getStockNum().signum());
|
||||
// Partially undo a received quantity, then return only what is pending.
|
||||
String thirdKey="PART-"+UUID.randomUUID(),keepKey="KEEP-"+UUID.randomUUID();
|
||||
receiptService.receive(rootReceipt.getId(),areaId,new BigDecimal("0.0019"),thirdKey,"rollback-test",java.time.LocalDate.of(2020,3,4),"原入库备注");
|
||||
var thirdChild=receipts.checkInNoUnique(numbers.reserve("IN",java.time.LocalDate.of(2020,3,4),"receipt:"+thirdKey));
|
||||
receiptService.withdraw(thirdChild.getId(),new BigDecimal("0.0005"),"部分退货",keepKey,"rollback-test");
|
||||
var keptChild=receipts.checkInNoUnique(numbers.reserve("IN",null,"receipt:"+keepKey));
|
||||
assertEquals(java.time.LocalDate.of(2020,3,4),keptChild.getBusinessDate());assertEquals("原入库备注",keptChild.getRemark());
|
||||
assertEquals(new BigDecimal("0.0005"),receipts.selectInRecordById(rootReceipt.getId()).getInNum());
|
||||
assertEquals(new BigDecimal("0.0014"),stocks.selectStockInfoByAreaProduct(areaId,productId).getStockNum());
|
||||
var arrivals=session.getMapper(com.ruoyi.warehouse.mapper.PurchaseArrivalMapper.class);
|
||||
var arrival=new com.ruoyi.warehouse.domain.PurchaseArrival();arrival.setArrivalNo("RET-"+UUID.randomUUID());arrival.setPurchaseRequestId(row.getId());arrival.setArrivalQuantity(new BigDecimal("0.0019"));arrival.setArrivalDate(new java.util.Date());arrivals.insertPurchaseArrival(arrival);
|
||||
arrival.setAcceptanceStatus(1);arrival.setDefectiveQuantity(BigDecimal.ZERO);arrivals.updatePurchaseArrivalAcceptance(arrival);
|
||||
var db=new org.springframework.jdbc.core.JdbcTemplate(new org.springframework.jdbc.datasource.SingleConnectionDataSource(connection,true));
|
||||
db.update("update in_record set arrival_id=? where id=?",arrival.getId(),rootReceipt.getId());
|
||||
var returns=new com.ruoyi.warehouse.service.impl.PurchaseReturnService();
|
||||
ReflectionTestUtils.setField(returns,"db",db);ReflectionTestUtils.setField(returns,"journal",journal);ReflectionTestUtils.setField(returns,"purchases",purchases);ReflectionTestUtils.setField(returns,"arrivals",arrivals);ReflectionTestUtils.setField(returns,"receipts",receipts);ReflectionTestUtils.setField(returns,"prices",pricing);
|
||||
var tooMany=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0006"),false,null,"超量",UUID.randomUUID().toString());
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class,()->returns.returnGoods(tooMany));
|
||||
var replace=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0002"),false,null,"等补货",UUID.randomUUID().toString());
|
||||
returns.returnGoods(replace);returns.returnGoods(replace);
|
||||
assertEquals(new BigDecimal("0.003800"),purchases.selectPurchaseRequestByIdForUpdate(row.getId()).getLockedAmount());
|
||||
var cancelPart=new com.ruoyi.warehouse.service.impl.PurchaseReturnService.Request(arrival.getId(),new BigDecimal("0.0003"),true,null,"取消部分",UUID.randomUUID().toString());
|
||||
returns.returnGoods(cancelPart);returns.returnGoods(cancelPart);
|
||||
assertEquals(new BigDecimal("0.0016"),purchases.selectPurchaseRequestByIdForUpdate(row.getId()).getQuantity());
|
||||
assertEquals(new BigDecimal("0.003200"),purchases.selectPurchaseRequestByIdForUpdate(row.getId()).getLockedAmount());
|
||||
assertEquals(new BigDecimal("0.0014"),arrivals.selectAcceptedQuantityByRequestId(row.getId()));
|
||||
assertEquals(2,returns.history(arrival.getId()).size());
|
||||
assertEquals(new BigDecimal("0.0014"),stocks.selectStockInfoByAreaProduct(areaId,productId).getStockNum());
|
||||
ProjectInfo stale = projects.selectProjectInfoById(project.getId(), null);
|
||||
assertEquals(1, projects.updateProjectInfo(stale)); assertEquals(0, projects.updateProjectInfo(stale));
|
||||
session.rollback(true);
|
||||
assertNull(projects.selectProjectInfoByCode(project.getProjectCode()));
|
||||
} finally { if (!connection.isClosed()) connection.rollback(); }
|
||||
}
|
||||
}
|
||||
private String resolve(String value) {
|
||||
if (!value.startsWith("${") || !value.endsWith("}")) return value;
|
||||
String inside = value.substring(2, value.length() - 1); int separator = inside.indexOf(':');
|
||||
String name = separator < 0 ? inside : inside.substring(0, separator);
|
||||
return Objects.requireNonNullElse(System.getenv(name), separator < 0 ? "" : inside.substring(separator + 1));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.warehouse.service.impl.BusinessNumberService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseBatchNumber;
|
||||
import com.ruoyi.warehouse.util.WarehouseNoUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchaseBatchNumberTest {
|
||||
@Test void batchEntrancesShareMonthlyPrefixAndFormatting() {
|
||||
var allocator=mock(BusinessNumberService.class);var numbers=new PurchaseBatchNumber();
|
||||
ReflectionTestUtils.setField(numbers,"businessNumbers",allocator);
|
||||
LocalDate date=LocalDate.of(2026,10,12);
|
||||
when(allocator.next("CG",date)).thenReturn("CG2026100001");
|
||||
assertEquals("CG2026100001",numbers.next(date));verify(allocator).next("CG",date);
|
||||
assertEquals("XM2026100001",WarehouseNoUtils.format("XM",date,1));
|
||||
assertEquals("XM20261010000",WarehouseNoUtils.format("XM",date,10000));
|
||||
assertEquals("WP2026110001",WarehouseNoUtils.format("WP",date.plusMonths(1),1));
|
||||
assertThrows(IllegalArgumentException.class,()->WarehouseNoUtils.format("LONG",date,1));
|
||||
assertThrows(IllegalArgumentException.class,()->WarehouseNoUtils.format("xm",date,1));
|
||||
assertEquals(BusinessNumberService.Kind.values().length,java.util.Arrays.stream(BusinessNumberService.Kind.values()).map(k->k.prefix).distinct().count());
|
||||
assertTrue(java.util.Arrays.stream(BusinessNumberService.Kind.values()).allMatch(k->k.prefix.matches("[A-Z]{1,3}")));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.util.List;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.PurchaseBatch;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseBatchMapper;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseBatchServiceImpl;
|
||||
import com.ruoyi.warehouse.service.impl.SupplierService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchaseBatchNumber;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchaseBatchSupplierTest {
|
||||
@Test void plannedBatchCanSaveWithoutSupplier() {
|
||||
Fixture f=new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
PurchaseBatch batch=new PurchaseBatch();batch.setPurchaseStatus(1);
|
||||
f.service.insertPurchaseBatch(batch);
|
||||
verify(f.suppliers,never()).requireActive(any());
|
||||
verify(f.batches).insertPurchaseBatch(batch);
|
||||
}
|
||||
}
|
||||
@Test void executingBatchRequiresSupplier() {
|
||||
Fixture f=new Fixture();doThrow(new ServiceException("供应商必填")).when(f.suppliers).requireActive(null);
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
PurchaseBatch batch=new PurchaseBatch();batch.setPurchaseStatus(2);
|
||||
assertThrows(ServiceException.class,()->f.service.insertPurchaseBatch(batch));
|
||||
verify(f.batches,never()).insertPurchaseBatch(any());
|
||||
}
|
||||
}
|
||||
@Test void supplierCannotBeClearedAfterPriceConfirmation() {
|
||||
Fixture f=new Fixture();PurchaseBatch existing=new PurchaseBatch();existing.setId(4L);existing.setSupplierId(7L);existing.setPurchaseStatus(2);
|
||||
when(f.batches.selectPurchaseBatchById(4L)).thenReturn(existing);
|
||||
PurchaseRequest locked=new PurchaseRequest();locked.setPriceLocked(true);when(f.requests.selectPurchaseRequestList(any())).thenReturn(List.of(locked));
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
PurchaseBatch batch=new PurchaseBatch();batch.setId(4L);batch.setPurchaseStatus(1);
|
||||
assertThrows(ServiceException.class,()->f.service.updatePurchaseBatch(batch));
|
||||
verify(f.batches,never()).updatePurchaseBatch(any());
|
||||
}
|
||||
}
|
||||
private static class Fixture {
|
||||
final PurchaseBatchMapper batches=mock(PurchaseBatchMapper.class);
|
||||
final PurchaseRequestMapper requests=mock(PurchaseRequestMapper.class);
|
||||
final SupplierService suppliers=mock(SupplierService.class);
|
||||
final PurchaseBatchServiceImpl service=new PurchaseBatchServiceImpl();
|
||||
Fixture(){ReflectionTestUtils.setField(service,"purchaseBatchMapper",batches);ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"suppliers",suppliers);ReflectionTestUtils.setField(service,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));var numbers=mock(PurchaseBatchNumber.class);when(numbers.next(any())).thenReturn("2026101201");ReflectionTestUtils.setField(service,"batchNumbers",numbers);}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.util.PurchasePriceRules;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PurchasePriceRulesTest {
|
||||
@Test void quantityAndFinalPriceUseSixDecimalAmount() {
|
||||
assertEquals(new BigDecimal("1.234560"), PurchasePriceRules.amount(new BigDecimal("10.0000"), new BigDecimal("0.123456")));
|
||||
}
|
||||
|
||||
@Test void roundedMultiplicationAndZeroPriceAreAllowed() {
|
||||
assertEquals(new BigDecimal("0.002346"), PurchasePriceRules.amount(new BigDecimal("0.0019"), new BigDecimal("1.234567")));
|
||||
assertEquals(new BigDecimal("0.000000"), PurchasePriceRules.amount(new BigDecimal("0.0001"), BigDecimal.ZERO));
|
||||
}
|
||||
|
||||
@Test void missingPriceOrInvalidNumbersCannotLock() {
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.amount(BigDecimal.ONE, null));
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.amount(BigDecimal.ZERO, BigDecimal.ONE));
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.amount(new BigDecimal("0.00001"), BigDecimal.ONE));
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.amount(BigDecimal.ONE, new BigDecimal("-1")));
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.amount(BigDecimal.ONE, new BigDecimal("0.1234567")));
|
||||
}
|
||||
|
||||
@Test void AnyEffectiveInboundBlocksPriceChangesButNotUnchangedPrices() {
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.requireEditablePrice(1, new BigDecimal("5"), new BigDecimal("6")));
|
||||
assertThrows(ServiceException.class, () -> PurchasePriceRules.requireEditablePrice(2, new BigDecimal("5"), null));
|
||||
assertDoesNotThrow(() -> PurchasePriceRules.requireEditablePrice(2, new BigDecimal("5.00"), new BigDecimal("5.000000")));
|
||||
assertDoesNotThrow(() -> PurchasePriceRules.requireEditablePrice(0, new BigDecimal("5"), new BigDecimal("6")));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,99 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.project.domain.ExpenseCategory;
|
||||
import com.ruoyi.project.mapper.ProjectBudgetMapper;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import com.ruoyi.warehouse.service.impl.PurchasePriceService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PurchasePriceServiceTest {
|
||||
PurchaseRequestMapper purchase = mock(PurchaseRequestMapper.class);
|
||||
ProjectBudgetMapper budgets = mock(ProjectBudgetMapper.class);
|
||||
IProjectInfoService projects = mock(IProjectInfoService.class);
|
||||
IPurchaseOperationLogService logs = mock(IPurchaseOperationLogService.class);
|
||||
PurchasePriceService service = new PurchasePriceService();
|
||||
PurchaseRequest existing;
|
||||
|
||||
@BeforeEach void setUp() {
|
||||
ReflectionTestUtils.setField(service, "purchaseRequestMapper", purchase);
|
||||
ReflectionTestUtils.setField(service, "projectBudgetMapper", budgets);
|
||||
ReflectionTestUtils.setField(service, "projectInfoService", projects);
|
||||
ReflectionTestUtils.setField(service, "operationLogService", logs);
|
||||
var numbers=mock(com.ruoyi.warehouse.service.impl.BusinessNumberService.class);
|
||||
when(numbers.next("FUND")).thenReturn("FY2026100001","FY2026100002","FY2026100003");
|
||||
ReflectionTestUtils.setField(service,"businessNumbers",numbers);
|
||||
existing = request();
|
||||
when(purchase.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(existing);
|
||||
when(purchase.updatePriceState(any())).thenReturn(1);
|
||||
ExpenseCategory category = new ExpenseCategory(); category.setStatus(0);
|
||||
when(budgets.selectExpenseCategoryById(8L)).thenReturn(category);
|
||||
}
|
||||
private PurchaseRequest request() {
|
||||
PurchaseRequest row = new PurchaseRequest(); row.setId(1L); row.setRequestNo("TEST");
|
||||
row.setProjectId(2L); row.setExpenseCategoryId(8L); row.setQuantity(new BigDecimal("3.0000"));
|
||||
row.setFinalUnitPrice(new BigDecimal("0.123456")); row.setPurchaseStatus(0);
|
||||
row.setPriceLocked(false); row.setLockedAmount(BigDecimal.ZERO); row.setLockRevision(0); return row;
|
||||
}
|
||||
@Test void lockRecordsExactlyOneFeeAndDoesNotUseBudgetAsHardLimit() {
|
||||
try (var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("test");
|
||||
service.lockPrice(1L);
|
||||
verify(purchase).updatePriceState(argThat(row -> row.getLockedAmount().equals(new BigDecimal("0.370368")) && row.getLockRevision() == 1 && row.getPriceLocked()));
|
||||
verify(purchase).insertPriceLedger(eq(existing), any(), eq("PRICE_LOCK"), eq("FY2026100001"), isNull());
|
||||
verify(budgets).ensureBudget(2L, 8L);
|
||||
verify(budgets, never()).selectProjectBudgetForUpdate(any(), any());
|
||||
}
|
||||
}
|
||||
@Test void alreadyLockedDoesNotCreateAnotherFeeOrLedger() {
|
||||
existing.setPriceLocked(true); existing.setLockRevision(1);
|
||||
service.lockPrice(1L);
|
||||
verify(purchase, never()).updatePriceState(any()); verify(purchase, never()).insertPriceLedger(any(), any(), any(), any(), any());
|
||||
}
|
||||
@Test void cancelledOrMissingPriceCannotLock() {
|
||||
existing.setPurchaseStatus(5); assertThrows(ServiceException.class, () -> service.lockPrice(1L));
|
||||
existing.setPurchaseStatus(0); existing.setFinalUnitPrice(null);
|
||||
assertThrows(ServiceException.class, () -> service.lockPrice(1L));
|
||||
verify(purchase, never()).updatePriceState(any());
|
||||
}
|
||||
@Test void lockedQuantityEditRecalculatesAndCancellationReversesAmount() {
|
||||
existing.setPriceLocked(true); existing.setLockedAmount(new BigDecimal("0.370368")); existing.setLockRevision(1);
|
||||
PurchaseRequest changed = request(); changed.setQuantity(new BigDecimal("4.0000"));
|
||||
try (var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("test");
|
||||
service.refreshLockedAmount(existing, changed, "PRICE_EDIT");
|
||||
assertEquals(new BigDecimal("0.493824"), changed.getLockedAmount());
|
||||
changed.setPurchaseStatus(5); service.refreshLockedAmount(existing, changed, "PRICE_CANCEL");
|
||||
assertEquals(new BigDecimal("0.000000"), changed.getLockedAmount());
|
||||
verify(purchase, times(2)).insertPriceLedger(any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
@Test void categoryMoveWithSameAmountStillRecordsTransfer() {
|
||||
existing.setPriceLocked(true); existing.setLockedAmount(new BigDecimal("0.370368")); existing.setLockRevision(1);
|
||||
PurchaseRequest changed = request(); changed.setExpenseCategoryId(9L);
|
||||
try (var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("test");
|
||||
service.refreshLockedAmount(existing, changed, "PRICE_MOVE");
|
||||
verify(purchase).insertPriceLedger(eq(existing), eq(changed), eq("PRICE_MOVE"), eq("FY2026100001"), eq("FY2026100002"));
|
||||
verify(budgets).ensureBudget(2L, 9L);
|
||||
}
|
||||
}
|
||||
@Test void concurrentChangeFailsInsteadOfCreatingOrphanFeeHistory() {
|
||||
when(purchase.updatePriceState(any())).thenReturn(0);
|
||||
try (var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUsername).thenReturn("test");
|
||||
assertThrows(ServiceException.class, () -> service.lockPrice(1L));
|
||||
verify(purchase, never()).insertPriceLedger(any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,223 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.core.domain.entity.SysDictData;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.framework.config.ProjectDatabaseGuard;
|
||||
import com.ruoyi.project.domain.*;
|
||||
import com.ruoyi.project.mapper.*;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.system.service.ISysDictTypeService;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.service.*;
|
||||
import com.ruoyi.warehouse.service.impl.*;
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.mapping.Environment;
|
||||
import org.apache.ibatis.session.*;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
|
||||
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Real MySQL saves/locks run inside a rollback-only transaction, never against another database. */
|
||||
@EnabledIfSystemProperty(named="projectDbTests", matches="true")
|
||||
class PurchaseSheetDatabaseTest {
|
||||
@Test void mixedProjectSaveDedupQuotesAndLockingAreAtomic() throws Exception {
|
||||
Fixture f = new Fixture();
|
||||
try (var security = mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");
|
||||
security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
new TransactionTemplate(f.manager).execute(status -> {
|
||||
try {
|
||||
PurchaseSheet draft = f.draft();
|
||||
PurchaseSheet saved = f.service.save(draft);
|
||||
assertTrue(saved.getBatch().getBatchNo().matches("CG"+java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMM"))+"[0-9]{4,}"));
|
||||
PurchaseSheet another=f.service.load(saved.getBatch().getId());another.getBatch().setId(null);another.getRows().forEach(row->row.setId(null));another.setVersion(null);
|
||||
PurchaseSheet second=f.service.save(another);
|
||||
assertEquals(Integer.parseInt(saved.getBatch().getBatchNo().substring(8))+1,Integer.parseInt(second.getBatch().getBatchNo().substring(8)),"Shared day numbering increments without a random suffix");
|
||||
assertEquals(2, saved.getRows().size());
|
||||
assertEquals(saved.getRows().get(0).getProductId(), saved.getRows().get(1).getProductId());
|
||||
assertNotEquals(saved.getRows().get(0).getProjectId(), saved.getRows().get(1).getProjectId());
|
||||
assertEquals(1, f.jdbc.queryForObject("select count(*) from product_info where product_name=?", Integer.class, f.name));
|
||||
assertEquals(0, f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)", Integer.class, saved.getRows().get(0).getId(),saved.getRows().get(1).getId()));
|
||||
String stale = saved.getVersion();
|
||||
saved.getRows().get(0).setQuantity(new BigDecimal("3"));
|
||||
saved = f.service.save(saved);
|
||||
assertEquals(2, saved.getRows().size());
|
||||
assertNotEquals(stale, saved.getVersion());
|
||||
assertEquals(1, f.jdbc.queryForObject("select count(*) from product_info where product_name=?", Integer.class, f.name));
|
||||
saved.getRows().get(0).setFinalUnitPrice(null);
|
||||
saved=f.service.save(saved);
|
||||
assertNull(saved.getRows().get(0).getFinalUnitPrice(),"Clearing a quote must not restore the legacy estimated price");
|
||||
saved.getRows().get(0).setFinalUnitPrice(new BigDecimal("1.25"));
|
||||
saved=f.service.save(saved);
|
||||
PurchaseSheet locked = f.service.confirm(saved.getBatch().getId(),saved.getVersion());
|
||||
assertTrue(locked.getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked())));
|
||||
assertEquals(0, locked.getRows().get(0).getLockedAmount().compareTo(new BigDecimal("3.75")));
|
||||
f.service.confirm(locked.getBatch().getId(),locked.getVersion());
|
||||
assertEquals(2,f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)",Integer.class,locked.getRows().get(0).getId(),locked.getRows().get(1).getId()));
|
||||
locked.getRows().get(0).setQuantity(new BigDecimal("10"));
|
||||
assertThrows(ServiceException.class,()->f.service.save(locked));
|
||||
assertEquals(0,f.jdbc.queryForObject("select quantity from purchase_request where id=?",BigDecimal.class,locked.getRows().get(0).getId()).compareTo(new BigDecimal("3")));
|
||||
} finally { status.setRollbackOnly(); }
|
||||
return null;
|
||||
});
|
||||
}
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name));
|
||||
}
|
||||
|
||||
@Test void invalidSecondRowRollsBackBatchArchiveAndFirstRow() throws Exception {
|
||||
Fixture f = new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");
|
||||
security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
assertThrows(ServiceException.class,()->new TransactionTemplate(f.manager).execute(status->{
|
||||
PurchaseSheet draft=f.draft();draft.getRows().get(1).setUnit("箱");
|
||||
return f.service.save(draft);
|
||||
}));
|
||||
}
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name));
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name));
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name));
|
||||
assertEquals(1,f.jdbc.queryForObject("select get_lock('cmvr-project-dev:catalog-write',0)",Integer.class));
|
||||
f.jdbc.queryForObject("select release_lock('cmvr-project-dev:catalog-write')",Integer.class);
|
||||
}
|
||||
|
||||
@Test void staleVersionAndOmittedRowsCannotOverwriteBatch() throws Exception {
|
||||
Fixture f=new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
new TransactionTemplate(f.manager).execute(status->{
|
||||
try {
|
||||
PurchaseSheet saved=f.service.save(f.draft());
|
||||
saved.setVersion("stale");assertThrows(ServiceException.class,()->f.service.save(saved));
|
||||
PurchaseSheet omitted=f.service.load(saved.getBatch().getId());
|
||||
omitted.setRows(List.of(omitted.getRows().get(0)));
|
||||
assertThrows(ServiceException.class,()->f.service.save(omitted));
|
||||
PurchaseSheet cleared=f.service.load(saved.getBatch().getId());
|
||||
cleared.setDeletedIds(cleared.getRows().stream().map(PurchaseRequest::getId).toList());
|
||||
cleared.setRows(List.of());
|
||||
assertTrue(f.service.save(cleared).getRows().isEmpty());
|
||||
}finally{status.setRollbackOnly();}return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test void supplierCanBeDeferredUntilConfirmationAndUnbatchedFilterIsReal() throws Exception {
|
||||
Fixture f=new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
new TransactionTemplate(f.manager).execute(status->{
|
||||
try {
|
||||
PurchaseSheet draft=f.draft();Long supplier=draft.getBatch().getSupplierId();draft.getBatch().setSupplierId(null);
|
||||
PurchaseSheet saved=f.service.save(draft);
|
||||
assertNull(saved.getBatch().getSupplierId());assertEquals(2,saved.getRows().size());
|
||||
PurchaseRequest unbatched=new PurchaseRequest();unbatched.setUnbatched(true);unbatched.setMaterialName(f.name);
|
||||
assertTrue(f.purchaseRows.selectPurchaseRequestList(unbatched).isEmpty());
|
||||
assertThrows(ServiceException.class,()->f.service.confirm(saved.getBatch().getId(),saved.getVersion()));
|
||||
assertFalse(f.service.load(saved.getBatch().getId()).getRows().stream().anyMatch(r->Boolean.TRUE.equals(r.getPriceLocked())));
|
||||
saved.getBatch().setSupplierId(supplier);PurchaseSheet assigned=f.service.save(saved);
|
||||
PurchaseSheet locked=f.service.confirm(assigned.getBatch().getId(),assigned.getVersion());
|
||||
assertTrue(locked.getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked())));
|
||||
locked.getBatch().setSupplierId(null);assertThrows(ServiceException.class,()->f.service.save(locked));
|
||||
}finally{status.setRollbackOnly();}return null;
|
||||
});
|
||||
}
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name));
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name));
|
||||
}
|
||||
|
||||
@Test void missingCategoryRejectsBeforeCreatingAnyArchiveOrPurchase() throws Exception {
|
||||
Fixture f=new Fixture();
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
|
||||
ServiceException error=assertThrows(ServiceException.class,()->new TransactionTemplate(f.manager).execute(status->{
|
||||
PurchaseSheet draft=f.draft();draft.getRows().get(0).setCategory(" ");return f.service.save(draft);
|
||||
}));assertTrue(error.getMessage().contains("物品类别"));
|
||||
}
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name));
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name));
|
||||
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name));
|
||||
}
|
||||
|
||||
private static class Fixture {
|
||||
final String name="SHEET-CHECK-"+UUID.randomUUID();
|
||||
final JdbcTemplate jdbc;
|
||||
final DataSourceTransactionManager manager;
|
||||
final PurchaseSheetService service;
|
||||
final ProjectInfoMapper projects;
|
||||
final ProjectBudgetMapper budgets;
|
||||
final PurchaseRequestMapper purchaseRows;
|
||||
Fixture() throws Exception {
|
||||
Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-admin")))root=root.getParent();
|
||||
Map<?,?> yaml;try(var input=Files.newInputStream(root.resolve("ruoyi-admin/src/main/resources/application-druid.yml"))){yaml=new Yaml().load(input);}
|
||||
Map<?,?> source=(Map<?,?>)((Map<?,?>)((Map<?,?>)((Map<?,?>)yaml.get("spring")).get("datasource")).get("druid")).get("master");
|
||||
String url=resolve(String.valueOf(source.get("url")));ProjectDatabaseGuard.assertAllowedUrl(url);
|
||||
DriverManagerDataSource ds=new DriverManagerDataSource(url,resolve(String.valueOf(source.get("username"))),resolve(String.valueOf(source.get("password"))));
|
||||
jdbc=new JdbcTemplate(ds);assertEquals("cmvr-project-dev",jdbc.queryForObject("select database()",String.class));
|
||||
manager=new DataSourceTransactionManager(ds);
|
||||
Configuration config=new Configuration();config.getTypeAliasRegistry().registerAliases("com.ruoyi.warehouse.domain");
|
||||
config.setEnvironment(new Environment("sheet-rollback",new SpringManagedTransactionFactory(),ds));
|
||||
for(String file:List.of("project/ProjectInfo","project/ProjectBudget","warehouse/PurchaseRequest","warehouse/ProductInfo","warehouse/PurchaseBatch","warehouse/PurchaseArrival")) {
|
||||
String resource="mapper/"+file+"Mapper.xml";
|
||||
try(var input=getClass().getClassLoader().getResourceAsStream(resource)){assertNotNull(input,resource);new XMLMapperBuilder(input,config,resource,config.getSqlFragments()).parse();}
|
||||
}
|
||||
var session=new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config));
|
||||
projects=session.getMapper(ProjectInfoMapper.class);budgets=session.getMapper(ProjectBudgetMapper.class);
|
||||
var purchases=session.getMapper(PurchaseRequestMapper.class);var catalog=session.getMapper(ProductInfoMapper.class);
|
||||
purchaseRows=purchases;
|
||||
IProjectInfoService projectAccess=mock(IProjectInfoService.class);
|
||||
IPurchaseOperationLogService logs=mock(IPurchaseOperationLogService.class);
|
||||
CatalogWriteLock lock=new CatalogWriteLock();set(lock,"jdbc",jdbc);
|
||||
var allocator=AuthorizedDatabaseTestSupport.numbers(jdbc,manager);PurchaseBatchNumber numbers=new PurchaseBatchNumber();set(numbers,"businessNumbers",allocator);
|
||||
ProductInfoServiceImpl productTarget=new ProductInfoServiceImpl();set(productTarget,"productInfoMapper",catalog);set(productTarget,"catalogWriteLock",lock);
|
||||
set(productTarget,"businessNumbers",allocator);
|
||||
var productService=proxy(productTarget);
|
||||
PurchasePriceService prices=new PurchasePriceService();set(prices,"purchaseRequestMapper",purchases);set(prices,"projectBudgetMapper",budgets);set(prices,"projectInfoService",projectAccess);set(prices,"operationLogService",logs);
|
||||
set(prices,"businessNumbers",allocator);
|
||||
PurchaseRequestServiceImpl purchaseTarget=new PurchaseRequestServiceImpl();set(purchaseTarget,"purchaseRequestMapper",purchases);set(purchaseTarget,"productInfoMapper",catalog);set(purchaseTarget,"productInfoService",productService);set(purchaseTarget,"purchaseArrivalMapper",session.getMapper(PurchaseArrivalMapper.class));set(purchaseTarget,"projectInfoMapper",projects);set(purchaseTarget,"projectBudgetMapper",budgets);set(purchaseTarget,"projectInfoService",projectAccess);set(purchaseTarget,"priceService",prices);set(purchaseTarget,"purchaseOperationLogService",logs);set(purchaseTarget,"taskDatabase",jdbc);
|
||||
SupplierService supplier=new SupplierService();set(supplier,"db",jdbc);
|
||||
set(purchaseTarget,"businessNumbers",allocator);
|
||||
ISysDictTypeService dict=mock(ISysDictTypeService.class);SysDictData unit=new SysDictData();unit.setDictLabel("件");unit.setStatus("0");when(dict.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit));
|
||||
PurchaseSheetService target=new PurchaseSheetService();set(target,"batches",session.getMapper(PurchaseBatchMapper.class));set(target,"requests",purchases);set(target,"catalog",catalog);set(target,"products",productService);set(target,"purchases",proxy(purchaseTarget));set(target,"prices",prices);set(target,"suppliers",supplier);set(target,"catalogLock",lock);set(target,"jdbc",jdbc);set(target,"json",new ObjectMapper().findAndRegisterModules());set(target,"dictTypes",dict);
|
||||
set(target,"batchNumbers",numbers); service=proxy(target);
|
||||
}
|
||||
PurchaseSheet draft() {
|
||||
jdbc.update("insert into supplier_info(name,active,create_by) values(?,1,'sheet-rollback-test')",name);
|
||||
Long supplier=jdbc.queryForObject("select id from supplier_info where name=?",Long.class,name);
|
||||
ExpenseCategory category=budgets.selectExpenseCategoryByCode("MATERIAL");assertNotNull(category);
|
||||
List<PurchaseRequest> rows=new ArrayList<>();
|
||||
for(int n=0;n<2;n++) {
|
||||
ProjectInfo project=new ProjectInfo();project.setProjectCode(name+"-"+n);project.setProjectName(name+"-"+n);project.setProjectType("RESEARCH");project.setProjectStatus(0);project.setTotalAmount(BigDecimal.TEN);projects.insertProjectInfo(project);
|
||||
PurchaseRequest row=new PurchaseRequest();row.setProjectId(project.getId());row.setExpenseCategoryId(category.getId());row.setMaterialName(name);row.setMaterialBrand("测试品牌");row.setMaterialParams("M4");row.setCategory("测试类别");row.setUnit("件");row.setQuantity(new BigDecimal("2"));row.setFinalUnitPrice(new BigDecimal("1.25"));row.setPurchasePurpose("SELF");rows.add(row);
|
||||
}
|
||||
PurchaseBatch batch=new PurchaseBatch();batch.setSupplierId(supplier);batch.setBatchName(name);batch.setBusinessDate(java.time.LocalDate.now());
|
||||
PurchaseSheet result=new PurchaseSheet();result.setBatch(batch);result.setRows(rows);result.setDeletedIds(List.of());return result;
|
||||
}
|
||||
// Each simulated HTTP request has a savepoint; a rejected request must not poison
|
||||
// later requests sharing the outer rollback-only fixture transaction.
|
||||
@SuppressWarnings("unchecked") <T> T proxy(T target){var attributes=new org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource();attributes.setTransactionAttribute(new org.springframework.transaction.interceptor.DefaultTransactionAttribute(org.springframework.transaction.TransactionDefinition.PROPAGATION_NESTED));ProxyFactory factory=new ProxyFactory(target);factory.setProxyTargetClass(true);factory.addAdvice(new TransactionInterceptor(manager,attributes));return (T)factory.getProxy();}
|
||||
void set(Object target,String field,Object value){ReflectionTestUtils.setField(target,field,value);}
|
||||
}
|
||||
private static String resolve(String value){if(!value.startsWith("${")||!value.endsWith("}"))return value;String body=value.substring(2,value.length()-1);int pos=body.indexOf(':');return Objects.requireNonNullElse(System.getenv(pos<0?body:body.substring(0,pos)),pos<0?"":body.substring(pos+1));}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
package com.ruoyi.projectdev;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.warehouse.domain.WarehouseArea;
|
||||
import com.ruoyi.warehouse.mapper.WarehouseAreaMapper;
|
||||
import com.ruoyi.warehouse.service.impl.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class WarehouseAreaSafetyTest {
|
||||
@Test void stockPreventsDeletionAndDeactivation(){
|
||||
var service=new WarehouseAreaServiceImpl();var mapper=mock(WarehouseAreaMapper.class);var db=mock(JdbcTemplate.class);
|
||||
ReflectionTestUtils.setField(service,"warehouseAreaMapper",mapper);ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));
|
||||
var area=new WarehouseArea();area.setId(10L);area.setAreaName("有库存库区");area.setStatus(1);when(mapper.selectWarehouseAreaById(10L)).thenReturn(area);
|
||||
when(db.queryForObject(anyString(),eq(Long.class),eq(10L))).thenReturn(1L);
|
||||
assertThrows(ServiceException.class,()->service.deleteWarehouseAreaByIds(new Long[]{10L}));assertThrows(ServiceException.class,()->service.updateWarehouseArea(area));
|
||||
verify(mapper,never()).deleteWarehouseAreaByIds(any());verify(mapper,never()).updateWarehouseArea(any());
|
||||
}
|
||||
@Test void emptyAreaWithHistoryIsRetainedButMayBeDeactivated(){
|
||||
var service=new WarehouseAreaServiceImpl();var mapper=mock(WarehouseAreaMapper.class);var db=mock(JdbcTemplate.class);
|
||||
ReflectionTestUtils.setField(service,"warehouseAreaMapper",mapper);ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));
|
||||
when(db.queryForObject(anyString(),eq(Long.class),eq(10L))).thenReturn(0L);
|
||||
when(db.queryForObject(anyString(),eq(Long.class),eq(10L),eq(10L),eq(10L),eq(10L),eq(10L))).thenReturn(1L);
|
||||
assertThrows(ServiceException.class,()->service.deleteWarehouseAreaByIds(new Long[]{10L}));verify(mapper,never()).deleteWarehouseAreaByIds(any());
|
||||
var area=new WarehouseArea();area.setId(10L);area.setAreaName("历史库区");area.setStatus(1);when(mapper.selectWarehouseAreaById(10L)).thenReturn(area);when(mapper.updateWarehouseArea(area)).thenReturn(1);
|
||||
assertEquals(1,service.updateWarehouseArea(area));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package com.ruoyi.projectdev;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import com.ruoyi.common.core.domain.entity.SysMenu;
|
||||
import com.ruoyi.system.mapper.SysMenuMapper;
|
||||
import com.ruoyi.system.service.impl.SysMenuServiceImpl;
|
||||
import com.ruoyi.system.domain.vo.RouterVo;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class WebNavigationDatabaseTest {
|
||||
@Test @EnabledIfSystemProperty(named="projectDbTests",matches="true")
|
||||
void realBusinessMenuTreeResolvesToExistingPagesWithoutDuplicateRoutes()throws Exception{
|
||||
try(var connection=AuthorizedDatabaseTestSupport.connection();var statement=connection.createStatement()){
|
||||
var menus=new ArrayList<SysMenu>();
|
||||
try(var rows=statement.executeQuery("select * from sys_menu where menu_type in ('M','C') and status='0' order by parent_id,order_num,menu_id")){
|
||||
while(rows.next()){var m=new SysMenu();m.setMenuId(rows.getLong("menu_id"));m.setParentId(rows.getLong("parent_id"));m.setMenuName(rows.getString("menu_name"));m.setPath(rows.getString("path"));m.setComponent(rows.getString("component"));m.setRouteName(rows.getString("route_name"));m.setMenuType(rows.getString("menu_type"));m.setVisible(rows.getString("visible"));m.setIsFrame(rows.getString("is_frame"));m.setIsCache(rows.getString("is_cache"));m.setIcon(rows.getString("icon"));menus.add(m);}
|
||||
}
|
||||
var mapper=mock(SysMenuMapper.class);when(mapper.selectMenuTreeAll()).thenReturn(menus);var service=new SysMenuServiceImpl();ReflectionTestUtils.setField(service,"menuMapper",mapper);
|
||||
var routes=service.buildMenus(service.selectMenuTreeByUserId(1L));var pages=new HashMap<String,String>();var names=new HashSet<String>();walk(routes,"",pages,names);
|
||||
var expected=Map.ofEntries(Map.entry("/project/info","project/info/index"),Map.entry("/procurement/details","warehouse/purchase/index"),Map.entry("/procurement/arrival","warehouse/arrival/index"),Map.entry("/warehouse/pending","warehouse/pending/index"),Map.entry("/warehouse/stock","warehouse/stock/index"),Map.entry("/warehouse/loans","warehouse/loans/index"),Map.entry("/production/tasks","production/tasks/index"),Map.entry("/production/operations","production/operations/index"),Map.entry("/costManagement/products","production/cost/index"),Map.entry("/businessBasics/product","warehouse/product/index"),Map.entry("/businessBasics/products","production/product/index"),Map.entry("/businessBasics/bom","production/bom/index"),Map.entry("/businessBasics/suppliers","warehouse/suppliers/index"),Map.entry("/businessBasics/area","warehouse/area/index"),Map.entry("/system/dict","system/businessDictionaries/index"),Map.entry("/system/initialization","system/initialization/index"),Map.entry("/system/operlog","monitor/operlog/index"));
|
||||
Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-ui")))root=root.getParent();
|
||||
for(var e:expected.entrySet()){assertEquals(e.getValue(),pages.get(e.getKey()),e.getKey());assertTrue(Files.exists(root.resolve("ruoyi-ui/src/views/"+e.getValue()+".vue")),e.getValue());}
|
||||
assertEquals("项目管理",routes.get(0).getMeta().getTitle());
|
||||
try(var rows=statement.executeQuery("select group_concat(menu_name order by order_num separator ',') from sys_menu where parent_id=0 and status='0' and visible='0'")){rows.next();assertEquals("项目管理,采购管理,库存管理,生产管理,材料成本,基础资料,系统管理",rows.getString(1));}
|
||||
try(var rows=statement.executeQuery("select count(*) from sys_menu where parent_id=0 and path in ('monitor','tool') and visible='1'")){rows.next();assertEquals(2,rows.getInt(1));}
|
||||
try(var rows=statement.executeQuery("select count(*) from sys_dict_data where status='0' and dict_type in ('wms_item_category','wms_item_unit')")){rows.next();assertTrue(rows.getInt(1)>=25);}
|
||||
try(var rows=statement.executeQuery("select count(*) from expense_category where status=0 and category_code in ('TRIAL','OTHER','LEGACY')")){rows.next();assertEquals(0,rows.getInt(1),"Unconfirmed expense categories must not be selectable");}
|
||||
connection.rollback();
|
||||
}
|
||||
}
|
||||
private void walk(List<RouterVo> routes,String parent,Map<String,String> pages,Set<String> names){
|
||||
for(var r:routes){if(r.getName()!=null&&!r.getName().isBlank())assertTrue(names.add(r.getName()),"Duplicate route name "+r.getName());String path=r.getPath().startsWith("/")?r.getPath():parent+"/"+r.getPath();path=path.replaceAll("/+","/");if(r.getChildren()!=null)walk(r.getChildren(),path,pages,names);else if(r.getComponent()!=null)assertNull(pages.put(path,r.getComponent()),"Duplicate page path "+path);}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
package com.ruoyi.web.controller.warehouse;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.ruoyi.warehouse.domain.PurchaseRequest;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
class SupplierPurchaseExportTest {
|
||||
private PurchaseRequest row(Long project,Long supplier,String batch,String quantity,String price){var r=new PurchaseRequest();r.setProjectId(project);r.setSupplierId(supplier);r.setSupplierName("供应商"+supplier);r.setProductId(101L);r.setPurchaseBatchNo(batch);r.setQuantity(new BigDecimal(quantity));r.setFinalUnitPrice(price==null?null:new BigDecimal(price));r.setMaterialName("=不应执行为公式");return r;}
|
||||
@Test void mergesAcrossProjectsButNotSupplierOrBatchAndPreservesMissingPrices()throws Exception{
|
||||
var a=row(1L,1L,"B1","2","3");var b=row(2L,1L,"B1","4","3");var c=row(1L,2L,"B1","1",null);var d=row(1L,1L,"B2","1","7");
|
||||
var cancelled=row(1L,1L,"B1","100","3");cancelled.setPurchaseStatus(5);
|
||||
try(var book=SupplierPurchaseExport.workbook(List.of(a,b,c,d,cancelled))){var sheet=book.getSheetAt(0);assertEquals(3,sheet.getLastRowNum());assertEquals(6,sheet.getRow(1).getCell(7).getNumericCellValue());assertEquals(18,sheet.getRow(1).getCell(9).getNumericCellValue());assertEquals(org.apache.poi.ss.usermodel.CellType.STRING,sheet.getRow(1).getCell(3).getCellType());assertEquals(org.apache.poi.ss.usermodel.CellType.BLANK,sheet.getRow(2).getCell(9).getCellType());}
|
||||
assertEquals(new BigDecimal("2"),a.getQuantity());assertEquals(1L,a.getProjectId());assertEquals(2L,b.getProjectId());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package com.ruoyi.framework.config;
|
||||
|
||||
import org.springframework.data.redis.serializer.SerializationException;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/** Isolate this development system's tokens/config/dictionary keys on a shared Redis server. */
|
||||
public final class NamespacedRedisKeySerializer extends StringRedisSerializer {
|
||||
private final String prefix;
|
||||
public NamespacedRedisKeySerializer(String namespace) {
|
||||
if (namespace == null || !namespace.matches("[A-Za-z0-9_-]{1,80}")) throw new IllegalArgumentException("缓存命名空间不能为空或包含通配符");
|
||||
prefix = namespace + ":";
|
||||
}
|
||||
@Override public byte[] serialize(String value) { return value == null ? null : super.serialize(prefix + value); }
|
||||
@Override public String deserialize(byte[] value) {
|
||||
String key = super.deserialize(value);
|
||||
if (key == null) return null;
|
||||
if (!key.startsWith(prefix)) throw new SerializationException("拒绝读取其他实例的缓存键");
|
||||
return key.substring(prefix.length());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package com.ruoyi.framework.config;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Prevent this project branch from connecting to a different database. */
|
||||
@Component
|
||||
public class ProjectDatabaseGuard implements BeanPostProcessor
|
||||
{
|
||||
public static final String ALLOWED_DATABASE = "cmvr-project-dev";
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
|
||||
{
|
||||
if (bean instanceof DruidDataSource)
|
||||
{
|
||||
assertAllowedUrl(((DruidDataSource) bean).getUrl());
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
public static void assertAllowedUrl(String url)
|
||||
{
|
||||
if (url == null || !url.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/"
|
||||
+ ALLOWED_DATABASE + "(?:\\?[^\\r\\n]*)?$"))
|
||||
{
|
||||
throw new IllegalStateException("本项目只允许连接数据库 " + ALLOWED_DATABASE
|
||||
+ ",已阻止其他数据库连接。请检查当前环境配置。");
|
||||
}
|
||||
// Session initialization or automatic catalog changes must not bypass the database boundary.
|
||||
if (url.toLowerCase(java.util.Locale.ROOT).matches(".*(?:sessionvariables|initcommand|allowmultiqueries)=.*"))
|
||||
{
|
||||
throw new IllegalStateException("数据库连接不能包含会话初始化或多语句执行参数。");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package com.ruoyi.framework.config;
|
||||
|
||||
import org.springframework.cache.annotation.CachingConfigurerSupport;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@ -19,17 +20,21 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
@EnableCaching
|
||||
public class RedisConfig extends CachingConfigurerSupport
|
||||
{
|
||||
@Value("${ruoyi.cacheNamespace:cmvr-project-dev}")
|
||||
private String cacheNamespace;
|
||||
@Bean
|
||||
@SuppressWarnings(value = { "unchecked", "rawtypes" })
|
||||
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
|
||||
{
|
||||
if(connectionFactory instanceof org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory lettuce)
|
||||
lettuce.setValidateConnection(true);
|
||||
RedisTemplate<Object, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(connectionFactory);
|
||||
|
||||
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
|
||||
|
||||
// 使用StringRedisSerializer来序列化和反序列化redis的key值
|
||||
template.setKeySerializer(new StringRedisSerializer());
|
||||
template.setKeySerializer(new NamespacedRedisKeySerializer(cacheNamespace));
|
||||
template.setValueSerializer(serializer);
|
||||
|
||||
// Hash的key也采用StringRedisSerializer的序列化方式
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
package com.ruoyi.production.domain;
|
||||
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class BomLine extends BaseEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long id;
|
||||
private Long bomId;
|
||||
private Long itemId;
|
||||
@com.ruoyi.common.annotation.Excel(name="物品编码") private String itemCode;
|
||||
@com.ruoyi.common.annotation.Excel(name="物品名称",type=com.ruoyi.common.annotation.Excel.Type.EXPORT) private String itemName;
|
||||
@com.ruoyi.common.annotation.Excel(name="品牌",type=com.ruoyi.common.annotation.Excel.Type.EXPORT) private String brand;
|
||||
@com.ruoyi.common.annotation.Excel(name="规格型号",type=com.ruoyi.common.annotation.Excel.Type.EXPORT) private String spec;
|
||||
@com.ruoyi.common.annotation.Excel(name="单位",type=com.ruoyi.common.annotation.Excel.Type.EXPORT) private String unit;
|
||||
@com.ruoyi.common.annotation.Excel(name="单台用量") private java.math.BigDecimal unitQuantity;
|
||||
private Long childBomId;
|
||||
@com.ruoyi.common.annotation.Excel(name="下级BOM版本",prompt="可空;非空时必须是该物品已有的公共版本") private String childVersionTag;
|
||||
@com.ruoyi.common.annotation.Excel(name="备注") private String remark;
|
||||
private Integer sortOrder;
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long value) { id = value; }
|
||||
public Long getBomId() { return bomId; }
|
||||
public void setBomId(Long value) { bomId = value; }
|
||||
public Long getItemId() { return itemId; }
|
||||
public void setItemId(Long value) { itemId = value; }
|
||||
public String getItemCode() { return itemCode; }
|
||||
public void setItemCode(String value) { itemCode = value; }
|
||||
public String getItemName() { return itemName; }
|
||||
public void setItemName(String value) { itemName = value; }
|
||||
public String getBrand() { return brand; }
|
||||
public void setBrand(String value) { brand = value; }
|
||||
public String getSpec() { return spec; }
|
||||
public void setSpec(String value) { spec = value; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String value) { unit = value; }
|
||||
public java.math.BigDecimal getUnitQuantity() { return unitQuantity; }
|
||||
public void setUnitQuantity(java.math.BigDecimal value) { unitQuantity = value; }
|
||||
public Long getChildBomId() { return childBomId; }
|
||||
public void setChildBomId(Long value) { childBomId = value; }
|
||||
public String getChildVersionTag() { return childVersionTag; }
|
||||
public void setChildVersionTag(String value) { childVersionTag = value; }
|
||||
public String getRemark() { return remark; }
|
||||
public void setRemark(String value) { remark = value; }
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer value) { sortOrder = value; }
|
||||
}
|
||||
|
||||
@ -0,0 +1,56 @@
|
||||
package com.ruoyi.production.domain;
|
||||
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class BomVersion extends BaseEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long id;
|
||||
private Long itemId;
|
||||
private String itemCode;
|
||||
private String itemName;
|
||||
private String brand;
|
||||
private String spec;
|
||||
private String unit;
|
||||
private String versionTag;
|
||||
private String description;
|
||||
private Boolean isDefault;
|
||||
private String scopeType;
|
||||
private String scopeKey;
|
||||
private Long projectId;
|
||||
private Long sourceVersionId;
|
||||
private Integer version;
|
||||
private java.util.List<BomLine> lines;
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long value) { id = value; }
|
||||
public Long getItemId() { return itemId; }
|
||||
public void setItemId(Long value) { itemId = value; }
|
||||
public String getItemCode() { return itemCode; }
|
||||
public void setItemCode(String value) { itemCode = value; }
|
||||
public String getItemName() { return itemName; }
|
||||
public void setItemName(String value) { itemName = value; }
|
||||
public String getBrand() { return brand; }
|
||||
public void setBrand(String value) { brand = value; }
|
||||
public String getSpec() { return spec; }
|
||||
public void setSpec(String value) { spec = value; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String value) { unit = value; }
|
||||
public String getVersionTag() { return versionTag; }
|
||||
public void setVersionTag(String value) { versionTag = value; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String value) { description = value; }
|
||||
public Boolean getIsDefault() { return isDefault; }
|
||||
public void setIsDefault(Boolean value) { isDefault = value; }
|
||||
public String getScopeType() { return scopeType; }
|
||||
public void setScopeType(String value) { scopeType = value; }
|
||||
public String getScopeKey() { return scopeKey; }
|
||||
public void setScopeKey(String value) { scopeKey = value; }
|
||||
public Long getProjectId() { return projectId; }
|
||||
public void setProjectId(Long value) { projectId = value; }
|
||||
public Long getSourceVersionId() { return sourceVersionId; }
|
||||
public void setSourceVersionId(Long value) { sourceVersionId = value; }
|
||||
public Integer getVersion() { return version; }
|
||||
public void setVersion(Integer value) { version = value; }
|
||||
public java.util.List<BomLine> getLines() { return lines; }
|
||||
public void setLines(java.util.List<BomLine> value) { lines = value; }
|
||||
}
|
||||
|
||||
@ -0,0 +1,15 @@
|
||||
package com.ruoyi.production.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** Only user-entered business fields; inventory values and actors are always derived on the server. */
|
||||
public class ProductionCommand {
|
||||
public Long id, projectId, itemId, bomId, parentTaskId, taskId, areaId, sourceId;
|
||||
public BigDecimal quantity;
|
||||
public String key, kind, reason, remark, recipient;
|
||||
public LocalDate date;
|
||||
public Integer version;
|
||||
/** Completion may explicitly raise the task plan to the new cumulative completed quantity. */
|
||||
public Boolean adjustPlan;
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
package com.ruoyi.production.domain;
|
||||
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class ProductionProduct extends BaseEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long id;
|
||||
private Long itemId;
|
||||
private String itemCode;
|
||||
private String itemName;
|
||||
private String category;
|
||||
private String brand;
|
||||
private String spec;
|
||||
private String unit;
|
||||
private Integer version;
|
||||
private Long defaultBomId;
|
||||
private String defaultVersionTag;
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long value) { id = value; }
|
||||
public Long getItemId() { return itemId; }
|
||||
public void setItemId(Long value) { itemId = value; }
|
||||
public String getItemCode() { return itemCode; }
|
||||
public void setItemCode(String value) { itemCode = value; }
|
||||
public String getItemName() { return itemName; }
|
||||
public void setItemName(String value) { itemName = value; }
|
||||
public String getCategory() { return category; }
|
||||
public void setCategory(String value) { category = value; }
|
||||
public String getBrand() { return brand; }
|
||||
public void setBrand(String value) { brand = value; }
|
||||
public String getSpec() { return spec; }
|
||||
public void setSpec(String value) { spec = value; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String value) { unit = value; }
|
||||
public Integer getVersion() { return version; }
|
||||
public void setVersion(Integer value) { version = value; }
|
||||
public Long getDefaultBomId() { return defaultBomId; }
|
||||
public void setDefaultBomId(Long value) { defaultBomId = value; }
|
||||
public String getDefaultVersionTag() { return defaultVersionTag; }
|
||||
public void setDefaultVersionTag(String value) { defaultVersionTag = value; }
|
||||
}
|
||||
|
||||
@ -0,0 +1,41 @@
|
||||
package com.ruoyi.production.domain;
|
||||
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class ProjectProduct extends BaseEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long id;
|
||||
private Long projectId;
|
||||
private Long itemId;
|
||||
private String itemCode;
|
||||
private String itemName;
|
||||
private String brand;
|
||||
private String spec;
|
||||
private String unit;
|
||||
private Long bomId;
|
||||
private String versionTag;
|
||||
private Integer version;
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long value) { id = value; }
|
||||
public Long getProjectId() { return projectId; }
|
||||
public void setProjectId(Long value) { projectId = value; }
|
||||
public Long getItemId() { return itemId; }
|
||||
public void setItemId(Long value) { itemId = value; }
|
||||
public String getItemCode() { return itemCode; }
|
||||
public void setItemCode(String value) { itemCode = value; }
|
||||
public String getItemName() { return itemName; }
|
||||
public void setItemName(String value) { itemName = value; }
|
||||
public String getBrand() { return brand; }
|
||||
public void setBrand(String value) { brand = value; }
|
||||
public String getSpec() { return spec; }
|
||||
public void setSpec(String value) { spec = value; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String value) { unit = value; }
|
||||
public Long getBomId() { return bomId; }
|
||||
public void setBomId(Long value) { bomId = value; }
|
||||
public String getVersionTag() { return versionTag; }
|
||||
public void setVersionTag(String value) { versionTag = value; }
|
||||
public Integer getVersion() { return version; }
|
||||
public void setVersion(Integer value) { version = value; }
|
||||
}
|
||||
|
||||
@ -0,0 +1,40 @@
|
||||
package com.ruoyi.production.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.production.domain.*;
|
||||
|
||||
public interface BomMapper {
|
||||
Integer lockGraph();
|
||||
List<BomVersion> selectPublicVersions(@Param("itemId") Long itemId, @Param("keyword") String keyword);
|
||||
BomVersion selectVersion(Long id);
|
||||
BomVersion selectDefault(Long itemId);
|
||||
List<BomVersion> selectGraphVersions();
|
||||
List<BomLine> selectGraphLines();
|
||||
List<BomLine> selectLines(Long bomId);
|
||||
int countVersionTag(@Param("itemId") Long itemId, @Param("scopeKey") String scopeKey, @Param("tag") String tag, @Param("exceptId") Long exceptId);
|
||||
int insertVersion(BomVersion bom);
|
||||
int updateVersion(BomVersion bom);
|
||||
int clearDefault(@Param("itemId") Long itemId, @Param("exceptId") Long exceptId);
|
||||
int retireLines(Long bomId);
|
||||
int insertLine(BomLine line);
|
||||
int countVersionReferences(Long id);
|
||||
int deleteVersion(Long id);
|
||||
int insertLog(@Param("bom") BomVersion bom, @Param("operation") String operation, @Param("snapshot") String snapshot, @Param("operator") String operator);
|
||||
List<Map<String, Object>> selectLogs(Long id);
|
||||
List<ProductionProduct> selectProducts(String keyword);
|
||||
ProductionProduct selectProduct(Long id);
|
||||
ProductionProduct selectProductByItem(Long itemId);
|
||||
int insertProduct(ProductionProduct product);
|
||||
int updateProduct(ProductionProduct product);
|
||||
int countProductReferences(Long itemId);
|
||||
int deleteProduct(Long id);
|
||||
int restoreProduct(Long id);
|
||||
List<ProjectProduct> selectProjectProducts(Long projectId);
|
||||
ProjectProduct selectProjectProduct(Long id);
|
||||
ProjectProduct selectProjectProductByItem(@Param("projectId") Long projectId, @Param("itemId") Long itemId);
|
||||
int insertProjectProduct(ProjectProduct product);
|
||||
int updateProjectProduct(ProjectProduct product);
|
||||
int deleteProjectProduct(Long id);
|
||||
}
|
||||
@ -0,0 +1,248 @@
|
||||
package com.ruoyi.production.service;
|
||||
|
||||
import java.util.*;
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.production.mapper.BomMapper;
|
||||
import com.ruoyi.production.util.BomGraphRules;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.warehouse.domain.ProductInfo;
|
||||
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
|
||||
|
||||
@Service
|
||||
public class BomService {
|
||||
@Autowired private BomMapper mapper;
|
||||
@Autowired private ProductInfoMapper items;
|
||||
@Autowired private IProjectInfoService projects;
|
||||
|
||||
public List<BomVersion> list(Long itemId, String keyword) { return mapper.selectPublicVersions(itemId, keyword); }
|
||||
public BomVersion get(Long id) {
|
||||
BomVersion bom = requireVersion(id);
|
||||
if (bom.getProjectId() != null) projects.requireProjectAccess(bom.getProjectId());
|
||||
bom.setLines(mapper.selectLines(id)); return bom;
|
||||
}
|
||||
public List<Map<String, Object>> logs(Long id) { get(id); return mapper.selectLogs(id); }
|
||||
|
||||
@Transactional public BomVersion save(BomVersion request) {
|
||||
lockGraph();
|
||||
if (request == null) throw new ServiceException("BOM内容不能为空");
|
||||
BomVersion existing = request.getId() == null ? null : get(request.getId());
|
||||
if (existing == null) {
|
||||
request.setScopeType("PUBLIC"); request.setScopeKey("PUBLIC"); request.setProjectId(null);
|
||||
request.setSourceVersionId(null); request.setVersion(0);
|
||||
} else {
|
||||
if (!"PUBLIC".equals(existing.getScopeType()) && !"PROJECT".equals(existing.getScopeType()))
|
||||
throw new ServiceException("任务用料快照不能通过公共BOM入口修改");
|
||||
if (!Objects.equals(existing.getVersion(), request.getVersion())) throw stale();
|
||||
request.setItemId(existing.getItemId()); request.setScopeType(existing.getScopeType());
|
||||
request.setScopeKey(existing.getScopeKey()); request.setProjectId(existing.getProjectId());
|
||||
request.setSourceVersionId(existing.getSourceVersionId());
|
||||
}
|
||||
requireItem(request.getItemId()); normalize(request);
|
||||
if (!"PUBLIC".equals(request.getScopeType())) request.setIsDefault(false);
|
||||
if (mapper.countVersionTag(request.getItemId(), request.getScopeKey(), request.getVersionTag(), request.getId()) > 0)
|
||||
throw new ServiceException("该物品的BOM版本号已存在,删除后也不复用");
|
||||
if (request.getLines() == null) request.setLines(new ArrayList<>());
|
||||
for (BomLine line : request.getLines()) {
|
||||
validateLine(line);
|
||||
if (line.getChildBomId() == null) continue;
|
||||
BomVersion child = requireVersion(line.getChildBomId());
|
||||
if ("PUBLIC".equals(request.getScopeType()) && !"PUBLIC".equals(child.getScopeType()))
|
||||
throw new ServiceException("公共BOM不能引用项目或任务副本");
|
||||
if ("PROJECT".equals(request.getScopeType())) {
|
||||
if ("PUBLIC".equals(child.getScopeType())) {
|
||||
if (!Objects.equals(line.getItemId(), child.getItemId())) throw new ServiceException("下级BOM与物品不匹配");
|
||||
line.setChildBomId(cloneGraph(child.getId(), "PROJECT", request.getProjectId(), snapshotKey("PROJECT", request.getProjectId())).getId());
|
||||
} else if (!"PROJECT".equals(child.getScopeType()) || !Objects.equals(child.getProjectId(), request.getProjectId()))
|
||||
throw new ServiceException("只能引用本项目的下级BOM副本");
|
||||
}
|
||||
}
|
||||
Map<Long, BomVersion> graph = graph();
|
||||
if (request.getId() != null) graph.put(request.getId(), request);
|
||||
BomGraphRules.validate(request, graph);
|
||||
// A child edit must also keep every existing parent acyclic.
|
||||
for (BomVersion parent : graph.values()) BomGraphRules.validate(parent, graph);
|
||||
if (Boolean.TRUE.equals(request.getIsDefault())) mapper.clearDefault(request.getItemId(), request.getId());
|
||||
String actor = SecurityUtils.getUsername();
|
||||
if (existing == null) {
|
||||
ensureProduct(request.getItemId()); request.setCreateBy(actor); mapper.insertVersion(request);
|
||||
} else {
|
||||
request.setUpdateBy(actor); if (mapper.updateVersion(request) != 1) throw stale();
|
||||
request.setVersion(request.getVersion() + 1); mapper.retireLines(request.getId());
|
||||
}
|
||||
writeLines(request); audit(request, existing == null ? "CREATE" : "EDIT"); return get(request.getId());
|
||||
}
|
||||
@Transactional public BomVersion setDefault(Long id, Integer expectedVersion) {
|
||||
lockGraph(); BomVersion bom = get(id);
|
||||
if (!"PUBLIC".equals(bom.getScopeType())) throw new ServiceException("只能将公共BOM设为默认版本");
|
||||
if (expectedVersion == null || !Objects.equals(expectedVersion, bom.getVersion())) throw stale();
|
||||
if (Boolean.TRUE.equals(bom.getIsDefault())) return bom;
|
||||
mapper.clearDefault(bom.getItemId(), bom.getId());
|
||||
bom.setIsDefault(true); bom.setUpdateBy(SecurityUtils.getUsername());
|
||||
if (mapper.updateVersion(bom) != 1) throw stale();
|
||||
bom.setVersion(bom.getVersion() + 1); audit(bom, "SET_DEFAULT");
|
||||
return get(id);
|
||||
}
|
||||
@Transactional public BomVersion copy(Long id, String tag, String description, Boolean makeDefault) {
|
||||
lockGraph(); BomVersion source = get(id);
|
||||
if (!"PUBLIC".equals(source.getScopeType())) throw new ServiceException("复制公共版本请从公共BOM选择");
|
||||
BomVersion copy = new BomVersion(); copy.setItemId(source.getItemId()); copy.setVersionTag(tag);
|
||||
copy.setDescription(description); copy.setIsDefault(Boolean.TRUE.equals(makeDefault));
|
||||
copy.setLines(new ArrayList<>());
|
||||
for (BomLine line : source.getLines()) {
|
||||
BomLine next = new BomLine(); BeanUtils.copyProperties(line, next); next.setId(null); copy.getLines().add(next);
|
||||
}
|
||||
return save(copy);
|
||||
}
|
||||
@Transactional public void delete(Long id) {
|
||||
lockGraph(); BomVersion bom = get(id);
|
||||
if (!"PUBLIC".equals(bom.getScopeType())) throw new ServiceException("项目副本从项目产品入口维护,不删除任务快照");
|
||||
if (mapper.countVersionReferences(id) > 0) throw new ServiceException("该BOM已被下级关联、项目或快照引用,不能删除");
|
||||
audit(bom, "DELETE"); if (mapper.deleteVersion(id) != 1) throw stale();
|
||||
}
|
||||
public List<ProductionProduct> products(String keyword) { return mapper.selectProducts(keyword); }
|
||||
@Transactional public ProductionProduct saveProduct(ProductionProduct request) {
|
||||
lockGraph(); if (request == null) throw new ServiceException("请选择物品");
|
||||
checkText(request.getRemark(), 500, "产品说明");
|
||||
if (request.getId() == null) {
|
||||
requireItem(request.getItemId());
|
||||
ProductionProduct product = ensureProduct(request.getItemId());
|
||||
if (StringUtils.isNotBlank(request.getRemark())) {
|
||||
product.setRemark(request.getRemark()); product.setUpdateBy(SecurityUtils.getUsername());
|
||||
if (mapper.updateProduct(product) != 1) throw stale();
|
||||
}
|
||||
return mapper.selectProduct(product.getId());
|
||||
}
|
||||
ProductionProduct existing = mapper.selectProduct(request.getId());
|
||||
if (existing == null) throw new ServiceException("产品不存在");
|
||||
request.setItemId(existing.getItemId()); checkText(request.getRemark(), 500, "产品说明");
|
||||
request.setUpdateBy(SecurityUtils.getUsername()); if (mapper.updateProduct(request) != 1) throw stale();
|
||||
return mapper.selectProduct(request.getId());
|
||||
}
|
||||
@Transactional public void deleteProduct(Long id) {
|
||||
lockGraph(); ProductionProduct product = mapper.selectProduct(id);
|
||||
if (product == null) throw new ServiceException("产品不存在");
|
||||
if (mapper.countProductReferences(product.getItemId()) > 0) throw new ServiceException("产品已被BOM或项目引用,不能删除");
|
||||
mapper.deleteProduct(id);
|
||||
}
|
||||
public List<ProjectProduct> projectProducts(Long projectId) {
|
||||
projects.requireProjectAccess(projectId); return mapper.selectProjectProducts(projectId);
|
||||
}
|
||||
@Transactional public ProjectProduct link(ProjectProduct request) {
|
||||
lockGraph(); if (request == null) throw new ServiceException("请选择项目及产品");
|
||||
ProjectProduct existing = request.getId() == null ? null : mapper.selectProjectProduct(request.getId());
|
||||
if (request.getId() != null && existing == null) throw new ServiceException("项目产品不存在");
|
||||
if (existing != null) {
|
||||
request.setProjectId(existing.getProjectId()); request.setItemId(existing.getItemId());
|
||||
if (!Objects.equals(existing.getVersion(), request.getVersion())) throw stale();
|
||||
}
|
||||
projects.requireProjectAccess(request.getProjectId()); requireItem(request.getItemId());
|
||||
checkText(request.getRemark(), 500, "备注"); ensureProduct(request.getItemId());
|
||||
if (existing == null && mapper.selectProjectProductByItem(request.getProjectId(), request.getItemId()) != null)
|
||||
throw new ServiceException("该项目已关联此产品,请直接维护已有项目用料");
|
||||
if (existing == null || !Objects.equals(existing.getBomId(), request.getBomId())) {
|
||||
BomVersion source = request.getBomId() == null ? mapper.selectDefault(request.getItemId()) : get(request.getBomId());
|
||||
if (source != null && (!"PUBLIC".equals(source.getScopeType()) || !Objects.equals(source.getItemId(), request.getItemId())))
|
||||
throw new ServiceException("请选择该产品的公共BOM版本");
|
||||
BomVersion snapshot;
|
||||
if (source == null) {
|
||||
snapshot = new BomVersion(); snapshot.setItemId(request.getItemId()); snapshot.setVersionTag("项目用料");
|
||||
snapshot.setDescription("未选公共BOM,直接维护本项目用料"); snapshot.setScopeType("PROJECT");
|
||||
snapshot.setScopeKey(snapshotKey("PROJECT", request.getProjectId())); snapshot.setProjectId(request.getProjectId());
|
||||
snapshot.setIsDefault(false); snapshot.setVersion(0); snapshot.setLines(new ArrayList<>());
|
||||
snapshot.setCreateBy(SecurityUtils.getUsername()); mapper.insertVersion(snapshot); audit(snapshot, "PROJECT_CREATE");
|
||||
} else snapshot = cloneGraph(source.getId(), "PROJECT", request.getProjectId(), snapshotKey("PROJECT", request.getProjectId()));
|
||||
request.setBomId(snapshot.getId());
|
||||
}
|
||||
String actor = SecurityUtils.getUsername();
|
||||
if (existing == null) { request.setCreateBy(actor); mapper.insertProjectProduct(request); }
|
||||
else { request.setUpdateBy(actor); if (mapper.updateProjectProduct(request) != 1) throw stale(); }
|
||||
return mapper.selectProjectProduct(request.getId());
|
||||
}
|
||||
@Transactional public void unlink(Long id) {
|
||||
lockGraph(); ProjectProduct existing = mapper.selectProjectProduct(id);
|
||||
if (existing == null) throw new ServiceException("项目产品不存在");
|
||||
projects.requireProjectAccess(existing.getProjectId()); mapper.deleteProjectProduct(id);
|
||||
// The snapshot is retained so future task/history references are never erased.
|
||||
}
|
||||
/** Production tasks call this inside their transaction; all nested versions are frozen too. */
|
||||
@Transactional public BomVersion snapshotForTask(Long sourceId, Long projectId, Long taskId) {
|
||||
if (taskId == null || taskId <= 0) throw new ServiceException("生产任务不能为空");
|
||||
lockGraph(); projects.requireProjectAccess(projectId); BomVersion source = get(sourceId);
|
||||
if (!"PUBLIC".equals(source.getScopeType()) && !Objects.equals(projectId, source.getProjectId()))
|
||||
throw new ServiceException("任务不能使用其他项目的BOM");
|
||||
return cloneGraph(sourceId, "TASK", projectId, "TASK:" + taskId + ":" + UUID.randomUUID());
|
||||
}
|
||||
private BomVersion cloneGraph(Long sourceId, String scope, Long projectId, String key) {
|
||||
Map<Long, BomVersion> originals = graph(); BomVersion root = originals.get(sourceId);
|
||||
if (root == null) throw new ServiceException("来源BOM不存在"); BomGraphRules.validate(root, originals);
|
||||
return cloneNode(root, originals, new HashMap<>(), scope, projectId, key);
|
||||
}
|
||||
private BomVersion cloneNode(BomVersion source, Map<Long, BomVersion> originals, Map<Long, BomVersion> copied, String scope, Long projectId, String key) {
|
||||
if (copied.containsKey(source.getId())) return copied.get(source.getId());
|
||||
BomVersion next = new BomVersion(); next.setItemId(source.getItemId()); next.setVersionTag(source.getVersionTag());
|
||||
// Different project branches may hold independently edited copies with the same item/version tag.
|
||||
// Give each copied node its own namespace, while preserving shared references to the same original node.
|
||||
String nodeKey = copied.isEmpty() ? key : key.substring(0, key.lastIndexOf(':') + 1) + UUID.randomUUID();
|
||||
next.setDescription(source.getDescription()); next.setScopeType(scope); next.setScopeKey(nodeKey); next.setProjectId(projectId);
|
||||
next.setSourceVersionId(source.getId()); next.setIsDefault(false); next.setVersion(0); next.setCreateBy(SecurityUtils.getUsername());
|
||||
next.setLines(new ArrayList<>()); mapper.insertVersion(next); copied.put(source.getId(), next);
|
||||
for (BomLine line : source.getLines()) {
|
||||
BomLine target = new BomLine(); BeanUtils.copyProperties(line, target); target.setId(null);
|
||||
if (line.getChildBomId() != null) target.setChildBomId(cloneNode(originals.get(line.getChildBomId()), originals, copied, scope, projectId, key).getId());
|
||||
next.getLines().add(target);
|
||||
}
|
||||
writeLines(next); audit(next, scope + "_SNAPSHOT"); return next;
|
||||
}
|
||||
private Map<Long, BomVersion> graph() {
|
||||
Map<Long, BomVersion> graph = new LinkedHashMap<>();
|
||||
for (BomVersion bom : mapper.selectGraphVersions()) { bom.setLines(new ArrayList<>()); graph.put(bom.getId(), bom); }
|
||||
for (BomLine line : mapper.selectGraphLines()) if (graph.containsKey(line.getBomId())) graph.get(line.getBomId()).getLines().add(line);
|
||||
return graph;
|
||||
}
|
||||
private void writeLines(BomVersion bom) {
|
||||
int position = 0;
|
||||
for (BomLine line : bom.getLines()) { line.setId(null); line.setBomId(bom.getId()); line.setSortOrder(position++); mapper.insertLine(line); }
|
||||
}
|
||||
private void validateLine(BomLine line) {
|
||||
if (line == null) throw new ServiceException("BOM明细不能为空"); requireItem(line.getItemId());
|
||||
if (line.getUnitQuantity() == null || line.getUnitQuantity().signum() <= 0 || line.getUnitQuantity().stripTrailingZeros().scale() > 4
|
||||
|| line.getUnitQuantity().precision() - line.getUnitQuantity().scale() > 16)
|
||||
throw new ServiceException("单台用量必须大于0,最多4位小数");
|
||||
line.setUnitQuantity(line.getUnitQuantity().stripTrailingZeros()); checkText(line.getRemark(), 500, "明细备注");
|
||||
}
|
||||
private ProductInfo requireItem(Long id) {
|
||||
ProductInfo item = id == null ? null : items.selectProductInfoById(id);
|
||||
if (item == null) throw new ServiceException("物品不存在,请先维护物品档案");
|
||||
if (StringUtils.isBlank(item.getUnit())) throw new ServiceException("物品“" + item.getProductName() + "”缺少单位,请先补齐物品档案");
|
||||
return item;
|
||||
}
|
||||
private ProductionProduct ensureProduct(Long itemId) {
|
||||
ProductionProduct existing = mapper.selectProductByItem(itemId);
|
||||
if (existing != null) {
|
||||
if (mapper.selectProduct(existing.getId()) == null) { mapper.restoreProduct(existing.getId()); return mapper.selectProduct(existing.getId()); }
|
||||
return existing;
|
||||
}
|
||||
ProductionProduct product = new ProductionProduct(); product.setItemId(itemId); product.setCreateBy(SecurityUtils.getUsername());
|
||||
mapper.insertProduct(product); return mapper.selectProduct(product.getId());
|
||||
}
|
||||
private void normalize(BomVersion bom) {
|
||||
bom.setVersionTag(StringUtils.trim(bom.getVersionTag()));
|
||||
if (StringUtils.isBlank(bom.getVersionTag())) throw new ServiceException("BOM版本不能为空");
|
||||
checkText(bom.getVersionTag(), 64, "版本号"); checkText(bom.getDescription(), 500, "版本说明");
|
||||
bom.setIsDefault(Boolean.TRUE.equals(bom.getIsDefault()));
|
||||
}
|
||||
private void checkText(String value, int length, String label) { if (value != null && value.length() > length) throw new ServiceException(label + "长度超过" + length + "字"); }
|
||||
private BomVersion requireVersion(Long id) { BomVersion bom = id == null ? null : mapper.selectVersion(id); if (bom == null) throw new ServiceException("BOM不存在或已删除"); return bom; }
|
||||
private void lockGraph() { if (mapper.lockGraph() == null) throw new ServiceException("BOM数据结构未初始化"); }
|
||||
private String snapshotKey(String scope, Long projectId) { return scope + ":" + projectId + ":" + UUID.randomUUID(); }
|
||||
private void audit(BomVersion bom, String operation) { mapper.insertLog(bom, operation, JSON.toJSONString(bom), SecurityUtils.getUsername()); }
|
||||
private ServiceException stale() { return new ServiceException("数据已被其他操作修改,请刷新后重试"); }
|
||||
}
|
||||
@ -0,0 +1,188 @@
|
||||
package com.ruoyi.production.service;
|
||||
|
||||
import java.math.*;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.production.domain.*;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.mapper.*;
|
||||
import com.ruoyi.warehouse.service.impl.InventoryCostJournal;
|
||||
import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.details;
|
||||
|
||||
@Service
|
||||
public class ProductionService {
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers;
|
||||
@Autowired private JdbcTemplate db;
|
||||
@Autowired private BomService boms;
|
||||
@Autowired private InventoryCostJournal journal;
|
||||
@Autowired private InventoryCostMapper costs;
|
||||
@Autowired private InRecordMapper receipts;
|
||||
@Autowired private ProductInfoMapper items;
|
||||
@Autowired private IProjectInfoService projects;
|
||||
private static final BigDecimal ZERO=BigDecimal.ZERO;
|
||||
private static final String TASK_SELECT="select t.*,p.project_name,i.product_name item_name,i.product_code,i.brand,i.spec,i.unit,b.version_tag,coalesce((select sum(quantity) from production_action where task_id=t.id and active=1 and kind='COMPLETE'),0) good_quantity,coalesce((select sum(quantity) from production_action where task_id=t.id and active=1 and kind='SCRAP_ASSEMBLY'),0) scrap_quantity from production_task t join project_info p on p.id=t.project_id join product_info i on i.id=t.item_id left join bom_version b on b.id=t.bom_id";
|
||||
private static final String ACTION_SELECT="select a.*,p.project_name,i.product_name item_name,i.brand,i.spec,i.unit,w.area_name,e.original_cost,e.effective_cost,t.task_no,coalesce((select sum(r.quantity) from production_action r where r.source_id=a.id and r.active=1 and r.kind in ('RETURN','DELIVERY_RETURN','SCRAP_ISSUED')),0) handled_quantity from production_action a join project_info p on p.id=a.project_id join product_info i on i.id=a.item_id left join warehouse_area w on w.id=a.area_id left join inventory_cost_event e on e.id=a.cost_event_id left join production_task t on t.id=a.task_id";
|
||||
|
||||
public List<Map<String,Object>> tasks(Long projectId,Long itemId){return db.queryForList(TASK_SELECT+" where (? is null or t.project_id=?) and (? is null or t.item_id=?) order by t.id desc",projectId,projectId,itemId,itemId);}
|
||||
public List<Map<String,Object>> costHistory(Long itemId,Long bomId,Long projectId){
|
||||
var result=new ArrayList<Map<String,Object>>();
|
||||
for(var row:tasks(projectId,itemId)){
|
||||
Long source=l(row,"source_bom_id");boolean matches=bomId==null,adjusted=false;var visited=new HashSet<Long>();
|
||||
while(source!=null&&visited.add(source)){if(source.equals(bomId))matches=true;var version=boms.get(source);if("PROJECT".equals(version.getScopeType()))adjusted=true;source=version.getSourceVersionId();}
|
||||
if(matches){row.put("project_adjusted",adjusted);result.add(row);}
|
||||
}
|
||||
result.sort(Comparator.comparing((Map<String,Object> r)->Objects.toString(r.get("settled_time"),"")).reversed());return result;
|
||||
}
|
||||
public Map<String,Object> task(Long id){var rows=db.queryForList(TASK_SELECT+" where t.id=?",id);if(rows.isEmpty())throw fail("生产任务不存在");projects.requireProjectAccess(l(rows.get(0),"project_id"));return rows.get(0);}
|
||||
public List<Map<String,Object>> actions(Long projectId,Long taskId){return db.queryForList(ACTION_SELECT+" where (? is null or a.project_id=?) and (? is null or a.task_id=?) order by a.id desc",projectId,projectId,taskId,taskId);}
|
||||
private Map<String,Object> action(Long id){var rows=db.queryForList(ACTION_SELECT+" where a.id=?",id);if(rows.isEmpty())throw fail("业务记录不存在");return rows.get(0);}
|
||||
public Map<String,Object> detail(Long id){var result=new LinkedHashMap<>(task(id));result.put("current_material_cost",material(id,null));result.put("actions",actions(null,id));result.put("needs",needs(id));result.put("settlements",db.queryForList("select * from production_settlement where task_id=? order by version desc",id));return result;}
|
||||
|
||||
@Transactional public Map<String,Object> save(ProductionCommand c){
|
||||
journal.lockInventory();quantity(c.quantity);text(c.remark,500);LocalDate date=c.date==null?LocalDate.now():c.date;
|
||||
if(c.id!=null){var t=task(c.id);if("SETTLED".equals(t.get("status")))throw fail("已结算任务不能修改;如需调整,请新建任务");if(c.version==null||c.version.intValue()!=l(t,"version").intValue())throw fail("任务已变化,请刷新");if(c.quantity.compareTo(n(t,"good_quantity").add(n(t,"scrap_quantity")))<0)throw fail("计划数量不能低于已经合格及报废数量");db.update("update production_task set planned_quantity=?,business_date=?,remark=?,version=version+1 where id=?",c.quantity,date,c.remark,c.id);return task(c.id);}
|
||||
key(c.key);projects.requireProjectAccess(c.projectId);var source=boms.get(c.bomId);if(!Objects.equals(source.getItemId(),c.itemId))throw fail("产品与BOM不一致");
|
||||
if(c.parentTaskId!=null){var parent=task(c.parentTaskId);if(!Objects.equals(c.projectId,l(parent,"project_id")))throw fail("子任务须在父任务项目中");boolean found=boms.get(l(parent,"bom_id")).getLines().stream().anyMatch(line->Objects.equals(line.getItemId(),c.itemId)&&Objects.equals(line.getChildBomId(),c.bomId));if(!found)throw fail("请选择父任务用料对应的下级BOM");}
|
||||
String no="TASK-"+UUID.nameUUIDFromBytes(c.key.getBytes(java.nio.charset.StandardCharsets.UTF_8));var duplicate=db.queryForList("select * from production_task where task_no=?",no);
|
||||
if(duplicate.isEmpty()){no=businessNumbers.reserve("TASK",date,c.key);duplicate=db.queryForList("select * from production_task where task_no=?",no);}
|
||||
if(!duplicate.isEmpty()){var d=duplicate.get(0);if(!Objects.equals(l(d,"project_id"),c.projectId)||!Objects.equals(l(d,"item_id"),c.itemId)||!Objects.equals(l(d,"source_bom_id"),c.bomId)||!Objects.equals(l(d,"parent_task_id"),c.parentTaskId)||n(d,"planned_quantity").compareTo(c.quantity)!=0)throw fail("重复任务内容不一致");return task(l(d,"id"));}
|
||||
Long id=insert("insert into production_task(task_no,project_id,item_id,source_bom_id,parent_task_id,planned_quantity,business_date,remark,create_by) values(?,?,?,?,?,?,?,?,?)",no,c.projectId,c.itemId,c.bomId,c.parentTaskId,c.quantity,date,c.remark,actor());
|
||||
var snapshot=boms.snapshotForTask(c.bomId,c.projectId,id);db.update("update production_task set bom_id=? where id=?",snapshot.getId(),id);return task(id);
|
||||
}
|
||||
public List<Map<String,Object>> needs(Long id){var t=task(id);List<Map<String,Object>> rows=new ArrayList<>();for(var line:boms.get(l(t,"bom_id")).getLines()){
|
||||
BigDecimal needed=line.getUnitQuantity().multiply(n(t,"planned_quantity")).setScale(4,RoundingMode.HALF_UP),issued=sum(id,line.getItemId(),"ISSUE"),returned=sum(id,line.getItemId(),"RETURN"),scrap=sum(id,line.getItemId(),"SCRAP_ISSUED");var stock=journal.balance(l(t,"project_id"),line.getItemId());BigDecimal available=stock==null?ZERO:stock.getQuantity();
|
||||
var row=new LinkedHashMap<String,Object>();row.put("itemId",line.getItemId());row.put("itemName",line.getItemName());row.put("brand",line.getBrand());row.put("spec",line.getSpec());row.put("unit",line.getUnit());row.put("childBomId",line.getChildBomId());row.put("required",needed);row.put("issued",issued);row.put("returned",returned);row.put("scrapped",scrap);row.put("available",available);row.put("shortage",needed.subtract(issued.subtract(returned)).subtract(available).max(ZERO));rows.add(row);
|
||||
}return rows;}
|
||||
private BigDecimal sum(Long taskId,Long itemId,String kind){return db.queryForObject("select coalesce(sum(quantity),0) from production_action where task_id=? and (? is null or item_id=?) and active=1 and kind=?",BigDecimal.class,taskId,itemId,itemId,kind);}
|
||||
|
||||
@Transactional public Map<String,Object> perform(ProductionCommand c){
|
||||
journal.lockInventory();key(c.key);quantity(c.quantity);text(c.reason,300);text(c.remark,500);text(c.recipient,200);if(c.date==null)c.date=LocalDate.now();
|
||||
Set<String> allowed=Set.of("ISSUE","RETURN","COMPLETE","SCRAP_ISSUED","SCRAP_ASSEMBLY","SCRAP_STOCK","SCRAP_FINISHED","DELIVERY","DELIVERY_RETURN");if(!allowed.contains(Objects.toString(c.kind,"")))throw fail("操作类型不正确");
|
||||
if(c.sourceId!=null&&!Set.of("RETURN","SCRAP_ISSUED","DELIVERY_RETURN").contains(c.kind))throw fail("本次操作不允许指定原领用或交付记录");
|
||||
Map<String,Object> t=c.taskId==null?null:task(c.taskId),source=null;
|
||||
if(Set.of("RETURN","SCRAP_ISSUED","DELIVERY_RETURN").contains(c.kind)){
|
||||
source=action(c.sourceId);if(!active(source)||!("DELIVERY_RETURN".equals(c.kind)?"DELIVERY":"ISSUE").equals(source.get("kind")))throw fail("请选择有效的原领用或交付记录");
|
||||
c.taskId=l(source,"task_id");c.projectId=l(source,"project_id");c.itemId=l(source,"item_id");t=c.taskId==null?null:task(c.taskId);
|
||||
}else if(t!=null){c.projectId=l(t,"project_id");if(Set.of("COMPLETE","SCRAP_ASSEMBLY").contains(c.kind))c.itemId=l(t,"item_id");}
|
||||
if(Set.of("ISSUE","RETURN","COMPLETE","SCRAP_ISSUED","SCRAP_ASSEMBLY").contains(c.kind)&&t==null)throw fail("请选择生产任务");
|
||||
if(Set.of("SCRAP_STOCK","SCRAP_FINISHED","DELIVERY","DELIVERY_RETURN").contains(c.kind)&&t!=null)throw fail("库存报废及交付不直接分摊到生产任务");
|
||||
projects.requireProjectAccess(c.projectId);if(c.itemId==null||items.selectProductInfoById(c.itemId)==null)throw fail("请选择物品");
|
||||
var dup=db.queryForList("select * from production_action where business_key=?",c.key);if(!dup.isEmpty()){var d=dup.get(0);if(!active(d)||!Objects.equals(c.kind,d.get("kind"))||!Objects.equals(c.projectId,l(d,"project_id"))||!Objects.equals(c.taskId,l(d,"task_id"))||!Objects.equals(c.itemId,l(d,"item_id"))||!Objects.equals(c.areaId,l(d,"area_id"))||!Objects.equals(c.sourceId,l(d,"source_id"))||c.quantity.compareTo(n(d,"quantity"))!=0)throw fail("重复操作内容不一致或已撤销");return action(l(d,"id"));}
|
||||
if(t!=null&&"SETTLED".equals(t.get("status"))&&Set.of("ISSUE","COMPLETE","SCRAP_ASSEMBLY").contains(c.kind))throw fail("任务已结算,不能再新增领料、完工或组装报废");
|
||||
if("ISSUE".equals(c.kind)&&boms.get(l(t,"bom_id")).getLines().stream().noneMatch(line->Objects.equals(line.getItemId(),c.itemId)))throw fail("所选物品不在该任务的BOM用料中");
|
||||
boolean finishedProduct=db.queryForObject("select count(*) from production_product where item_id=? and del_flag='0'",Integer.class,c.itemId)>0;
|
||||
if(Set.of("DELIVERY","SCRAP_FINISHED").contains(c.kind)&&!finishedProduct)throw fail("只有产品档案中的成品库存才能交付或办理成品报废");
|
||||
if("SCRAP_STOCK".equals(c.kind)&&finishedProduct)throw fail("该物品属于成品,请选择成品报废");
|
||||
if("DELIVERY".equals(c.kind)&&(c.recipient==null||c.recipient.isBlank()))throw fail("请填写交付接收方");
|
||||
if(c.kind.startsWith("SCRAP")&&(c.reason==null||c.reason.isBlank()))throw fail("请填写报废原因");
|
||||
if(source!=null&&c.quantity.compareTo(n(source,"quantity").subtract(n(source,"handled_quantity")))>0)throw fail("超过尚未退回或报废的数量");
|
||||
if("ISSUE".equals(c.kind)&&Objects.equals(c.itemId,l(t,"item_id")))throw fail("不能把任务自己的产出作为该任务用料");
|
||||
BigDecimal planRemaining=t==null?null:n(t,"planned_quantity").subtract(n(t,"good_quantity")).subtract(n(t,"scrap_quantity"));
|
||||
if(Set.of("COMPLETE","SCRAP_ASSEMBLY").contains(c.kind)&&c.quantity.compareTo(planRemaining)>0){
|
||||
if("COMPLETE".equals(c.kind)&&Boolean.TRUE.equals(c.adjustPlan)){
|
||||
BigDecimal adjusted=n(t,"good_quantity").add(n(t,"scrap_quantity")).add(c.quantity).setScale(4,RoundingMode.HALF_UP);
|
||||
db.update("update production_task set planned_quantity=?,version=version+1 where id=?",adjusted,c.taskId);
|
||||
t=task(c.taskId);
|
||||
}else throw fail("超过计划剩余数量;完工验收可勾选同步增加计划数量");
|
||||
}
|
||||
InventoryCostEvent e=null;
|
||||
if(Set.of("ISSUE","SCRAP_STOCK","SCRAP_FINISHED","DELIVERY").contains(c.kind))e=journal.append(details(event(c.projectId,c.itemId,c.areaId,"ISSUE",c.quantity,null,null,"PROD:"+c.key),c.date,c.remark));
|
||||
if(Set.of("RETURN","DELIVERY_RETURN").contains(c.kind))e=journal.append(details(event(c.projectId,c.itemId,c.areaId,"RETURN",c.quantity,null,l(source,"cost_event_id"),"PROD:"+c.key),c.date,c.remark));
|
||||
Long id=insert("insert into production_action(business_key,kind,task_id,project_id,item_id,area_id,quantity,source_id,cost_event_id,business_date,recipient,reason,remark,create_by) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",c.key,c.kind,c.taskId,c.projectId,c.itemId,c.areaId,c.quantity,c.sourceId,e==null?null:e.getId(),c.date,c.recipient,c.reason,c.remark,actor());
|
||||
if("COMPLETE".equals(c.kind)){
|
||||
var in=new InRecord();in.setInNo(businessNumbers.reserve("IN",c.date,"completion:"+c.key));in.setSourceNo(String.valueOf(t.get("task_no")));in.setSourceProjectId(c.projectId);in.setProductId(c.itemId);in.setInNum(c.quantity);in.setInStatus(0);in.setInType(1);in.setInOperator(actor());in.setOperator(actor());in.setReceiptRoot(true);in.setProductionTaskId(c.taskId);in.setCompletionId(id);in.setRemark(c.remark);receipts.insertInRecord(in);
|
||||
}
|
||||
if(c.taskId!=null)db.update("update production_task set version=version+1 where id=?",c.taskId);
|
||||
recalculateSettled();return action(id);
|
||||
}
|
||||
@Transactional public void revoke(Long id,String reason){
|
||||
journal.lockInventory();if(reason==null||reason.isBlank())throw fail("请填写撤销原因");text(reason,300);var a=action(id);projects.requireProjectAccess(l(a,"project_id"));if(!active(a))return;
|
||||
if(db.queryForObject("select count(*) from production_action where source_id=? and active=1",Long.class,id)>0)throw fail("请先撤销该记录的退料、退回或报废记录");
|
||||
String kind=String.valueOf(a.get("kind"));if("OUTPUT".equals(kind))throw fail("请从入库记录撤销本次入库");
|
||||
if("COMPLETE".equals(kind)){var roots=db.queryForList("select id from in_record where completion_id=? and receipt_root=1",id);for(var root:roots){Long inId=l(root,"id");if(receipts.receivedQuantity(inId).signum()>0)throw fail("请先撤销这次完工对应的入库");receipts.updateRootStatus(inId,2);}}
|
||||
if(l(a,"cost_event_id")!=null)journal.voidLastEvent(l(a,"cost_event_id"),reason);
|
||||
db.update("update production_action set active=0,void_reason=?,void_by=?,void_time=current_timestamp where id=?",reason,actor(),id);
|
||||
if(l(a,"task_id")!=null)db.update("update production_task set version=version+1 where id=?",l(a,"task_id"));
|
||||
recalculateSettled();
|
||||
}
|
||||
@Transactional public BigDecimal receiptUnit(Long taskId){journal.lockInventory();var t=task(taskId);if("SETTLED".equals(t.get("status")))return nullable(t,"unit_cost");if(l(t,"provisional_set")==0){var quote=reference(l(t,"bom_id"),l(t,"project_id"),taskId);BigDecimal unit=Boolean.TRUE.equals(quote.get("complete"))?(BigDecimal)quote.get("amount"):null;db.update("update production_task set provisional_set=1,provisional_unit_cost=? where id=?",unit,taskId);return unit;}return nullable(t,"provisional_unit_cost");}
|
||||
@Transactional public void received(InRecord in,InventoryCostEvent e){
|
||||
var completion=action(in.getCompletionId());
|
||||
if(!active(completion)||!Objects.equals(l(completion,"task_id"),in.getProductionTaskId())||!Objects.equals(l(completion,"item_id"),in.getProductId())||!Objects.equals(l(completion,"project_id"),in.getSourceProjectId()))throw fail("完工入库来源不一致或已撤销");
|
||||
insert("insert into production_action(business_key,kind,task_id,project_id,item_id,area_id,quantity,source_id,cost_event_id,business_date,remark,create_by) values(?,'OUTPUT',?,?,?,?,?,?,?,?,?,?)",
|
||||
"OUTPUT:"+e.getId(),in.getProductionTaskId(),in.getSourceProjectId(),in.getProductId(),in.getAreaId(),in.getInNum(),in.getCompletionId(),e.getId(),in.getBusinessDate()==null?LocalDate.now():in.getBusinessDate(),in.getRemark(),actor());
|
||||
db.update("update production_task set version=version+1 where id=?",in.getProductionTaskId());recalculateSettled();
|
||||
}
|
||||
@Transactional public void receiptRevoked(Long eventId){db.update("update production_task set version=version+1 where id in (select task_id from production_action where cost_event_id=? and kind='OUTPUT' and active=1)",eventId);db.update("update production_action set active=0,void_reason='撤销入库',void_by=?,void_time=current_timestamp where cost_event_id=? and kind='OUTPUT'",actor(),eventId);}
|
||||
@Transactional public Map<String,Object> settle(Long id){return settle(id,null);}
|
||||
@Transactional public Map<String,Object> settle(Long id,Integer version){
|
||||
journal.lockInventory();var t=task(id);checkTaskVersion(t,version);
|
||||
db.update("update production_task set status='SETTLED',version=version+1 where id=?",id);recalculateSettled();return detail(id);
|
||||
}
|
||||
/** Resume without deleting quantities, settlements or inventory cost revisions. */
|
||||
@Transactional public Map<String,Object> reopen(Long id,Integer version){
|
||||
journal.lockInventory();var t=task(id);checkTaskVersion(t,version);
|
||||
if("OPEN".equals(t.get("status")))return detail(id);
|
||||
if(!"SETTLED".equals(t.get("status")))throw fail("当前任务状态不支持继续生产");
|
||||
// New receipts use the previous settled unit as a provisional basis until the next settlement.
|
||||
db.update("update production_task set status='OPEN',provisional_set=1,provisional_unit_cost=unit_cost,version=version+1 where id=?",id);
|
||||
return detail(id);
|
||||
}
|
||||
private void checkTaskVersion(Map<String,Object> task,Integer version){
|
||||
if(version!=null&&!Objects.equals(l(task,"version"),version.longValue()))throw fail("任务已被其他操作更新,请刷新后重试");
|
||||
}
|
||||
|
||||
/** Replays settled tasks until all downstream material inputs agree with their source outputs. */
|
||||
public void recalculateSettled(){
|
||||
var all=db.queryForList("select id from production_task where status='SETTLED' order by id");int limit=Math.max(4,all.size()*2+2);
|
||||
for(int pass=0;pass<limit;pass++){boolean changed=false;
|
||||
for(var row:all){Long id=l(row,"id");var t=task(id);BigDecimal material=material(id,null),good=n(t,"good_quantity"),unit=material==null||good.signum()==0?null:material.divide(good,6,RoundingMode.HALF_UP);
|
||||
var last=db.queryForList("select * from production_settlement where task_id=? order by version desc limit 1",id);boolean update=last.isEmpty()||!equal(material,nullable(t,"material_cost"))||!equal(unit,nullable(t,"unit_cost"))||!equal(good,n(last.get(0),"good_quantity"));
|
||||
if(update){int version=l(t,"settlement_version").intValue()+1;db.update("update production_task set material_cost=?,unit_cost=?,settlement_version=?,settled_time=current_timestamp where id=?",material,unit,version,id);db.update("insert into production_settlement(task_id,version,good_quantity,material_cost,unit_cost,create_by) values(?,?,?,?,?,?)",id,version,good,material,unit,actor());changed=true;}
|
||||
var outputs=db.queryForList("select a.cost_event_id,a.quantity from production_action a where a.task_id=? and a.kind='OUTPUT' and a.active=1 order by a.id",id);
|
||||
BigDecimal totalReceived=outputs.stream().map(o->n(o,"quantity")).reduce(ZERO,BigDecimal::add),allocated=ZERO;
|
||||
for(int x=0;x<outputs.size();x++){var out=outputs.get(x);BigDecimal amount=unit==null?null:material.multiply(n(out,"quantity")).divide(good,6,RoundingMode.HALF_UP);if(amount!=null&&x==outputs.size()-1&&totalReceived.compareTo(good)==0)amount=material.subtract(allocated);if(amount!=null)allocated=allocated.add(amount);var event=costs.selectEvent(l(out,"cost_event_id"));if(equal(event.getEffectiveCost(),amount))continue;journal.reviseReceipt(event.getId(),amount,"SETTLE:"+UUID.randomUUID(),journal.balance(event.getProjectId(),event.getItemId()).getVersion());changed=true;}
|
||||
}if(!changed)return;
|
||||
}throw fail("任务成本存在循环依赖,无法完成结算,请检查相互领料记录");
|
||||
}
|
||||
private BigDecimal material(Long taskId,Long itemId){var rows=db.queryForList("select a.kind,e.effective_cost from production_action a join inventory_cost_event e on e.id=a.cost_event_id where a.task_id=? and a.active=1 and a.kind in ('ISSUE','RETURN') and (? is null or a.item_id=?)",taskId,itemId,itemId);BigDecimal total=ZERO;for(var row:rows){BigDecimal value=nullable(row,"effective_cost");if(value==null)return null;total="RETURN".equals(row.get("kind"))?total.subtract(value):total.add(value);}return total.setScale(6);}
|
||||
public Map<String,Object> reference(Long bomId,Long projectId,Long taskId){if(taskId!=null){var t=task(taskId);if(!Objects.equals(bomId,l(t,"bom_id"))||!Objects.equals(projectId,l(t,"project_id")))throw fail("任务、项目与BOM不一致");}return reference(bomId,projectId,taskId,new HashSet<>());}
|
||||
private Map<String,Object> reference(Long bomId,Long projectId,Long taskId,Set<Long> path){if(!path.add(bomId))throw fail("BOM存在循环");var bom=boms.get(bomId);var lines=new ArrayList<Map<String,Object>>();BigDecimal total=ZERO;boolean complete=true;
|
||||
for(var line:bom.getLines()){BigDecimal unit=null,partial=null;String source="缺价";
|
||||
if(taskId!=null){BigDecimal net=sum(taskId,line.getItemId(),"ISSUE").subtract(sum(taskId,line.getItemId(),"RETURN")),amount=material(taskId,line.getItemId());if(net.signum()>0&&amount!=null){unit=amount.divide(net,6,RoundingMode.HALF_UP);source="任务净领料";}}
|
||||
if(unit==null&&projectId!=null){var balance=journal.balance(projectId,line.getItemId());if(balance!=null&&balance.getQuantity().signum()>0&&balance.getAmount()!=null){unit=balance.getAmount().divide(balance.getQuantity(),6,RoundingMode.HALF_UP);source="项目库存";}}
|
||||
if(unit==null){boolean selfMade=line.getChildBomId()!=null;var prices=selfMade?db.queryForList("select unit_cost price from production_task where item_id=? and status='SETTLED' and unit_cost is not null order by settled_time desc,id desc limit 1",line.getItemId()):db.queryForList("select final_unit_price price from purchase_request where product_id=? and del_flag='0' and price_locked=1 and purchase_status<>5 and final_unit_price is not null order by coalesce(original_date,create_time) desc,id desc limit 1",line.getItemId());if(!prices.isEmpty()){unit=nullable(prices.get(0),"price");source=selfMade?"最近结算成本":"最近锁价采购";}}
|
||||
if(unit==null&&line.getChildBomId()!=null){var child=reference(line.getChildBomId(),projectId,null,new HashSet<>(path));if(Boolean.TRUE.equals(child.get("complete"))){unit=(BigDecimal)child.get("amount");source="下级BOM";}else{partial=(BigDecimal)child.get("amount");source="下级BOM已知部分(缺价)";}}
|
||||
BigDecimal amount=unit==null?(partial==null?null:partial.multiply(line.getUnitQuantity()).setScale(6,RoundingMode.HALF_UP)):unit.multiply(line.getUnitQuantity()).setScale(6,RoundingMode.HALF_UP);if(unit==null)complete=false;if(amount!=null)total=total.add(amount);var row=new LinkedHashMap<String,Object>();row.put("itemId",line.getItemId());row.put("itemName",line.getItemName());row.put("unitQuantity",line.getUnitQuantity());row.put("unitCost",unit);row.put("amount",amount);row.put("source",source);row.put("complete",unit!=null);lines.add(row);
|
||||
}var result=new LinkedHashMap<String,Object>();result.put("amount",total);result.put("complete",complete);result.put("lines",lines);return result;
|
||||
}
|
||||
public Map<String,Object> overview(Long projectId){
|
||||
projects.requireProjectAccess(projectId);var result=new LinkedHashMap<String,Object>();
|
||||
result.put("pendingPurchases",db.queryForObject("select count(*) from purchase_request p where project_id=? and del_flag='0' and historical=0 and purchase_status<>5 and quantity>coalesce((select sum(arrival_quantity-defective_quantity-returned_quantity) from purchase_arrival a where a.purchase_request_id=p.id and a.acceptance_status=1),0)",Long.class,projectId));
|
||||
result.put("pendingReceipts",db.queryForObject("select count(*) from in_record where source_project_id=? and in_status=0",Long.class,projectId));
|
||||
result.put("openTasks",db.queryForObject("select count(*) from production_task where project_id=? and status='OPEN'",Long.class,projectId));
|
||||
result.put("outstandingLoans",db.queryForObject("select count(*) from project_loan l left join (select loan_id,sum(quantity) returned_quantity from project_loan_return where active=1 group by loan_id) r on r.loan_id=l.id where l.active=1 and (l.lender_project_id=? or l.borrower_project_id=?) and l.quantity>l.historical_returned+coalesce(r.returned_quantity,0)",Long.class,projectId,projectId));
|
||||
result.put("remainingStocks",db.queryForObject("select count(*) from project_stock_balance where project_id=? and quantity>0",Long.class,projectId));
|
||||
result.put("tasks",tasks(projectId,null));result.put("actions",actions(projectId,null));return result;
|
||||
}
|
||||
private Long insert(String sql,Object... values){var holder=new GeneratedKeyHolder();db.update(connection->{var statement=connection.prepareStatement(sql,java.sql.Statement.RETURN_GENERATED_KEYS);for(int i=0;i<values.length;i++)statement.setObject(i+1,values[i]);return statement;},holder);return Objects.requireNonNull(holder.getKey()).longValue();}
|
||||
private static Long l(Map<String,Object> row,String key){Object value=row.get(key);return value==null?null:value instanceof Boolean b?(b?1L:0L):((Number)value).longValue();}
|
||||
private static BigDecimal nullable(Map<String,Object> row,String key){Object v=row.get(key);return v==null?null:new BigDecimal(v.toString());}
|
||||
private static BigDecimal n(Map<String,Object> row,String key){BigDecimal n=nullable(row,key);return n==null?ZERO:n;}
|
||||
private static boolean active(Map<String,Object> row){return Long.valueOf(1).equals(l(row,"active"));}
|
||||
private static boolean equal(BigDecimal a,BigDecimal b){return a==null||b==null?a==b:a.compareTo(b)==0;}
|
||||
private static void key(String value){if(value==null||value.isBlank()||value.length()>120)throw fail("业务标识无效,请重新打开操作窗口");}
|
||||
private static void quantity(BigDecimal q){if(q==null||q.signum()<=0||q.stripTrailingZeros().scale()>4)throw fail("数量必须大于0,最多4位小数");}
|
||||
private static void text(String value,int maximum){if(value!=null&&value.length()>maximum)throw fail("填写内容超过长度限制:"+maximum);}
|
||||
private static String actor(){return SecurityUtils.getUsername();}
|
||||
private static ServiceException fail(String message){return new ServiceException(message);}
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
package com.ruoyi.production.util;
|
||||
|
||||
import java.util.*;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.production.domain.*;
|
||||
|
||||
public final class BomGraphRules {
|
||||
private BomGraphRules() { }
|
||||
public static void validate(BomVersion root, Map<Long, BomVersion> versions) {
|
||||
walk(root, versions, new LinkedHashSet<>(), new LinkedHashSet<>());
|
||||
}
|
||||
private static void walk(BomVersion bom, Map<Long, BomVersion> versions, Set<Long> pathVersions, Set<Long> pathItems) {
|
||||
if (pathVersions.size() >= 100 || pathItems.contains(bom.getItemId()) || bom.getId() != null && pathVersions.contains(bom.getId()))
|
||||
throw new ServiceException("BOM存在循环引用或层级异常,请检查产品及下级BOM");
|
||||
if (bom.getId() != null) pathVersions.add(bom.getId());
|
||||
pathItems.add(bom.getItemId());
|
||||
for (BomLine line : bom.getLines() == null ? List.<BomLine>of() : bom.getLines()) {
|
||||
if (pathItems.contains(line.getItemId())) throw new ServiceException("BOM用料不能引用自身或上级产出物品");
|
||||
if (line.getChildBomId() == null) continue;
|
||||
BomVersion child = versions.get(line.getChildBomId());
|
||||
if (child == null) throw new ServiceException("下级BOM不存在或已删除");
|
||||
if (!Objects.equals(line.getItemId(), child.getItemId())) throw new ServiceException("下级BOM的所属物品与该行物品不一致");
|
||||
walk(child, versions, pathVersions, pathItems);
|
||||
}
|
||||
pathItems.remove(bom.getItemId());
|
||||
if (bom.getId() != null) pathVersions.remove(bom.getId());
|
||||
}
|
||||
}
|
||||
@ -1,8 +1,5 @@
|
||||
package com.ruoyi.project.domain;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class ProjectInfo extends BaseEntity
|
||||
@ -12,17 +9,11 @@ public class ProjectInfo extends BaseEntity
|
||||
private Long id;
|
||||
private String projectCode;
|
||||
private String projectName;
|
||||
private Long managerId;
|
||||
private String managerName;
|
||||
private Long deptId;
|
||||
private String deptName;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date startDate;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date endDate;
|
||||
private String projectType;
|
||||
private java.math.BigDecimal totalAmount;
|
||||
private Integer version;
|
||||
private Integer projectStatus;
|
||||
private String currency;
|
||||
private List<Long> memberIds;
|
||||
private java.math.BigDecimal budgetAmount;
|
||||
private java.math.BigDecimal committedAmount;
|
||||
private java.math.BigDecimal spentAmount;
|
||||
@ -34,24 +25,16 @@ public class ProjectInfo extends BaseEntity
|
||||
public void setProjectCode(String projectCode) { this.projectCode = projectCode; }
|
||||
public String getProjectName() { return projectName; }
|
||||
public void setProjectName(String projectName) { this.projectName = projectName; }
|
||||
public Long getManagerId() { return managerId; }
|
||||
public void setManagerId(Long managerId) { this.managerId = managerId; }
|
||||
public String getManagerName() { return managerName; }
|
||||
public void setManagerName(String managerName) { this.managerName = managerName; }
|
||||
public Long getDeptId() { return deptId; }
|
||||
public void setDeptId(Long deptId) { this.deptId = deptId; }
|
||||
public String getDeptName() { return deptName; }
|
||||
public void setDeptName(String deptName) { this.deptName = deptName; }
|
||||
public Date getStartDate() { return startDate; }
|
||||
public void setStartDate(Date startDate) { this.startDate = startDate; }
|
||||
public Date getEndDate() { return endDate; }
|
||||
public void setEndDate(Date endDate) { this.endDate = endDate; }
|
||||
public String getProjectType() { return projectType; }
|
||||
public void setProjectType(String projectType) { this.projectType = projectType; }
|
||||
public java.math.BigDecimal getTotalAmount() { return totalAmount; }
|
||||
public void setTotalAmount(java.math.BigDecimal totalAmount) { this.totalAmount = totalAmount; }
|
||||
public Integer getVersion() { return version; }
|
||||
public void setVersion(Integer version) { this.version = version; }
|
||||
public Integer getProjectStatus() { return projectStatus; }
|
||||
public void setProjectStatus(Integer projectStatus) { this.projectStatus = projectStatus; }
|
||||
public String getCurrency() { return currency; }
|
||||
public void setCurrency(String currency) { this.currency = currency; }
|
||||
public List<Long> getMemberIds() { return memberIds; }
|
||||
public void setMemberIds(List<Long> memberIds) { this.memberIds = memberIds; }
|
||||
public java.math.BigDecimal getBudgetAmount() { return budgetAmount; }
|
||||
public void setBudgetAmount(java.math.BigDecimal budgetAmount) { this.budgetAmount = budgetAmount; }
|
||||
public java.math.BigDecimal getCommittedAmount() { return committedAmount; }
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
package com.ruoyi.project.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.ruoyi.common.annotation.Excel;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class ProjectLoan extends BaseEntity {
|
||||
private Long id,lenderProjectId,borrowerProjectId,itemId,outEventId,inEventId;
|
||||
@Excel(name="借用编号") private String loanNo;
|
||||
@Excel(name="借出项目") private String lenderProjectName;
|
||||
@Excel(name="借入项目") private String borrowerProjectName;
|
||||
@Excel(name="物品") private String itemName;
|
||||
@Excel(name="品牌") private String brand;
|
||||
@Excel(name="规格") private String spec;
|
||||
@Excel(name="单位") private String unit;
|
||||
@Excel(name="借用数量") private BigDecimal quantity;
|
||||
@Excel(name="已还数量") private BigDecimal returnedQuantity;
|
||||
@Excel(name="未还数量") private BigDecimal outstandingQuantity;
|
||||
private Boolean active;
|
||||
private BigDecimal historicalReturned;
|
||||
private Long originalAreaId;
|
||||
public Long getOriginalAreaId(){return originalAreaId;}
|
||||
public void setOriginalAreaId(Long value){originalAreaId=value;}
|
||||
@com.ruoyi.common.annotation.Excel(name="借用日期",dateFormat="yyyy-MM-dd")
|
||||
private java.time.LocalDate businessDate;
|
||||
public java.time.LocalDate getBusinessDate(){return businessDate;}
|
||||
public void setBusinessDate(java.time.LocalDate value){businessDate=value;}
|
||||
public BigDecimal getHistoricalReturned(){return historicalReturned;}
|
||||
public void setHistoricalReturned(BigDecimal value){historicalReturned=value;}
|
||||
public Long getId(){return id;} public void setId(Long v){id=v;}
|
||||
public Long getLenderProjectId(){return lenderProjectId;} public void setLenderProjectId(Long v){lenderProjectId=v;}
|
||||
public Long getBorrowerProjectId(){return borrowerProjectId;} public void setBorrowerProjectId(Long v){borrowerProjectId=v;}
|
||||
public Long getItemId(){return itemId;} public void setItemId(Long v){itemId=v;}
|
||||
public Long getOutEventId(){return outEventId;} public void setOutEventId(Long v){outEventId=v;}
|
||||
public Long getInEventId(){return inEventId;} public void setInEventId(Long v){inEventId=v;}
|
||||
public String getLoanNo(){return loanNo;} public void setLoanNo(String v){loanNo=v;}
|
||||
public String getLenderProjectName(){return lenderProjectName;} public void setLenderProjectName(String v){lenderProjectName=v;}
|
||||
public String getBorrowerProjectName(){return borrowerProjectName;} public void setBorrowerProjectName(String v){borrowerProjectName=v;}
|
||||
public String getItemName(){return itemName;} public void setItemName(String v){itemName=v;}
|
||||
public String getBrand(){return brand;} public void setBrand(String v){brand=v;}
|
||||
public String getSpec(){return spec;} public void setSpec(String v){spec=v;}
|
||||
public String getUnit(){return unit;} public void setUnit(String v){unit=v;}
|
||||
public BigDecimal getQuantity(){return quantity;} public void setQuantity(BigDecimal v){quantity=v;}
|
||||
public BigDecimal getReturnedQuantity(){return returnedQuantity;} public void setReturnedQuantity(BigDecimal v){returnedQuantity=v;}
|
||||
public BigDecimal getOutstandingQuantity(){return outstandingQuantity;} public void setOutstandingQuantity(BigDecimal v){outstandingQuantity=v;}
|
||||
public Boolean getActive(){return active;} public void setActive(Boolean v){active=v;}
|
||||
}
|
||||
@ -8,6 +8,8 @@ import com.ruoyi.project.domain.ProjectFundLedger;
|
||||
|
||||
public interface ProjectBudgetMapper
|
||||
{
|
||||
int ensureBudget(@org.apache.ibatis.annotations.Param("projectId") Long projectId,
|
||||
@org.apache.ibatis.annotations.Param("categoryId") Long categoryId);
|
||||
List<ExpenseCategory> selectExpenseCategoryList(ExpenseCategory category);
|
||||
|
||||
ExpenseCategory selectExpenseCategoryById(Long id);
|
||||
|
||||
@ -23,14 +23,5 @@ public interface ProjectInfoMapper
|
||||
|
||||
int countProjectBusiness(Long projectId);
|
||||
|
||||
int deleteProjectMembers(Long projectId);
|
||||
|
||||
int insertProjectMember(@Param("projectId") Long projectId, @Param("userId") Long userId,
|
||||
@Param("memberRole") String memberRole, @Param("createBy") String createBy);
|
||||
|
||||
List<Long> selectProjectMemberIds(Long projectId);
|
||||
|
||||
int countProjectAccess(@Param("projectId") Long projectId, @Param("userId") Long userId);
|
||||
|
||||
Long selectLegacyProjectId();
|
||||
}
|
||||
|
||||
@ -0,0 +1,17 @@
|
||||
package com.ruoyi.project.mapper;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.project.domain.ProjectLoan;
|
||||
public interface ProjectLoanMapper {
|
||||
List<ProjectLoan> list(@Param("projectId") Long projectId,@Param("itemId") Long itemId,@Param("outstandingOnly") boolean outstandingOnly);
|
||||
ProjectLoan get(Long id);
|
||||
ProjectLoan byNo(String no);
|
||||
int insert(ProjectLoan loan);
|
||||
int deactivate(Long id);
|
||||
int insertReturn(@Param("loanId") Long loanId,@Param("quantity") BigDecimal quantity,@Param("key") String key,@Param("type") String type,@Param("outId") Long outId,@Param("inId") Long inId,@Param("actor") String actor);
|
||||
Map<String,Object> returnByKey(String key);
|
||||
List<Map<String,Object>> returns(Long loanId);
|
||||
int deactivateReturn(Long inId);
|
||||
Long returnLoanForEvent(Long inId);
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
package com.ruoyi.project.service;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.project.domain.ProjectLoan;
|
||||
import com.ruoyi.project.mapper.ProjectLoanMapper;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.service.impl.InventoryCostJournal;
|
||||
import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
|
||||
@Service public class ProjectLoanService {
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers;
|
||||
@Autowired private ProjectLoanMapper mapper;
|
||||
@Autowired private InventoryCostJournal journal;
|
||||
@Autowired private IProjectInfoService projects;
|
||||
public List<ProjectLoan> list(Long projectId,Long itemId,boolean outstandingOnly){if(projectId!=null) projects.requireProjectAccess(projectId);return mapper.list(projectId,itemId,outstandingOnly);}
|
||||
public ProjectLoan get(Long id){ProjectLoan l=id==null?null:mapper.get(id);if(l==null) throw error("借用记录不存在");projects.requireProjectAccess(l.getLenderProjectId());projects.requireProjectAccess(l.getBorrowerProjectId());return l;}
|
||||
public List<Map<String,Object>> returns(Long id){get(id);return mapper.returns(id);}
|
||||
@Transactional public ProjectLoan borrow(Long lender,Long borrower,Long item,Long fromArea,Long toArea,BigDecimal quantity,String key,String remark){
|
||||
return borrow(lender,borrower,item,fromArea,toArea,quantity,key,remark,null);
|
||||
}
|
||||
@Transactional public ProjectLoan borrow(Long lender,Long borrower,Long item,Long fromArea,Long toArea,BigDecimal quantity,String key,String remark,java.time.LocalDate date){
|
||||
journal.lockInventory();key=key(key);if(Objects.equals(lender,borrower)) throw error("借出和借入项目不能相同");
|
||||
projects.requireProjectAccess(lender);projects.requireProjectAccess(borrower);
|
||||
String no="LOAN-"+UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8));
|
||||
ProjectLoan duplicate=mapper.byNo(no);
|
||||
if(duplicate==null){no=businessNumbers.reserve("LOAN",date,key);duplicate=mapper.byNo(no);}
|
||||
if(duplicate!=null && !Boolean.TRUE.equals(duplicate.getActive())) throw error("借用已撤销,请使用新业务标识重新办理");
|
||||
var out=journal.append(InventoryCostJournal.details(event(lender,item,fromArea,"ISSUE",quantity,null,null,no+":out"),date,remark));
|
||||
var in=journal.append(InventoryCostJournal.details(event(borrower,item,toArea,"RECEIPT",quantity,out.getEffectiveCost(),null,no+":in"),date,remark));journal.bindTransfer(out.getId(),in.getId());
|
||||
if(duplicate!=null){if(!Objects.equals(duplicate.getLenderProjectId(),lender)||!Objects.equals(duplicate.getBorrowerProjectId(),borrower)||!Objects.equals(duplicate.getItemId(),item)) throw error("重复借用内容不一致");return duplicate;}
|
||||
if(remark!=null&&remark.length()>500) throw error("说明最多500字");
|
||||
ProjectLoan loan=new ProjectLoan();loan.setBusinessDate(out.getBusinessDate());loan.setLoanNo(no);loan.setLenderProjectId(lender);loan.setBorrowerProjectId(borrower);loan.setItemId(item);loan.setQuantity(quantity);loan.setOutEventId(out.getId());loan.setInEventId(in.getId());loan.setRemark(remark);loan.setCreateBy(SecurityUtils.getUsername());mapper.insert(loan);return get(loan.getId());
|
||||
}
|
||||
@Transactional public ProjectLoan returnStock(Long id,Long fromArea,Long toArea,BigDecimal quantity,String key){
|
||||
return returnStock(id,fromArea,toArea,quantity,key,null,null);
|
||||
}
|
||||
@Transactional public ProjectLoan returnStock(Long id,Long fromArea,Long toArea,BigDecimal quantity,String key,java.time.LocalDate date,String remark){
|
||||
journal.lockInventory();key="LOAN-RETURN:"+key(key);ProjectLoan loan=get(id);
|
||||
if(mapper.returnByKey(key)==null) requireRemaining(loan,quantity);
|
||||
var out=journal.append(InventoryCostJournal.details(event(loan.getBorrowerProjectId(),loan.getItemId(),fromArea,"ISSUE",quantity,null,null,key+":out"),date,remark));
|
||||
var in=journal.append(InventoryCostJournal.details(event(loan.getLenderProjectId(),loan.getItemId(),toArea,"RECEIPT",quantity,out.getEffectiveCost(),null,key+":in"),date,remark));journal.bindTransfer(out.getId(),in.getId());
|
||||
registerReturn(loan,quantity,key,"STOCK",out.getId(),in.getId());return get(id);
|
||||
}
|
||||
public ProjectLoan validatePurchase(Long loanId,Long projectId,Long itemId){ProjectLoan l=get(loanId);if(!Boolean.TRUE.equals(l.getActive())||!Objects.equals(l.getBorrowerProjectId(),projectId)||!Objects.equals(l.getItemId(),itemId)) throw error("归还采购必须对应借入项目和同一物品的有效借用");return l;}
|
||||
@Transactional public void purchaseReceived(Long loanId,Long purchaseProject,Long itemId,InventoryCostEvent receipt){
|
||||
journal.lockInventory();ProjectLoan loan=validatePurchase(loanId,purchaseProject,itemId);
|
||||
if(!Objects.equals(receipt.getProjectId(),loan.getLenderProjectId())||!Objects.equals(receipt.getItemId(),itemId)||!"RECEIPT".equals(receipt.getEventType())) throw error("归还入库项目或物品不正确");
|
||||
registerReturn(loan,receipt.getQuantity(),"PURCHASE-RETURN:"+receipt.getId(),"PURCHASE",null,receipt.getId());
|
||||
}
|
||||
@Transactional public void revokePurchaseReceipt(Long eventId){journal.lockInventory();Long id=mapper.returnLoanForEvent(eventId);if(id!=null){get(id);mapper.deactivateReturn(eventId);}}
|
||||
@Transactional public void revokeLoan(Long id,String reason){journal.lockInventory();ProjectLoan loan=get(id);if(!Boolean.TRUE.equals(loan.getActive())) return;if(reason==null||reason.isBlank()||reason.length()>300)throw error("请填写撤销原因,最多300字");if(loan.getReturnedQuantity().subtract(loan.getHistoricalReturned()==null?BigDecimal.ZERO:loan.getHistoricalReturned()).signum()>0) throw error("请先撤销系统内归还记录");if(loan.getInEventId()!=null){journal.voidLastEvent(loan.getInEventId(),reason);journal.voidLastEvent(loan.getOutEventId(),reason);}mapper.deactivate(id);}
|
||||
@Transactional public void revokeStockReturn(Long loanId,String key,String reason){journal.lockInventory();get(loanId);Map<String,Object> row=mapper.returnByKey(key);if(row==null||!Objects.equals(((Number)row.get("loanId")).longValue(),loanId)||!"STOCK".equals(row.get("returnType"))) throw error("库存归还记录不存在;采购归还请从入库入口撤销");Long in=((Number)row.get("inEventId")).longValue(),out=((Number)row.get("outEventId")).longValue();journal.voidLastEvent(in,reason);journal.voidLastEvent(out,reason);mapper.deactivateReturn(in);}
|
||||
private void registerReturn(ProjectLoan loan,BigDecimal quantity,String key,String type,Long outId,Long inId){Map<String,Object> existing=mapper.returnByKey(key);if(existing!=null){if(!Objects.equals(((Number)existing.get("loanId")).longValue(),loan.getId())||!Objects.equals(((Number)existing.get("inEventId")).longValue(),inId)||((BigDecimal)existing.get("quantity")).compareTo(quantity)!=0) throw error("重复归还内容不一致");if(((Number)existing.get("active")).intValue()!=1) throw error("该归还已撤销");return;}requireRemaining(loan,quantity);mapper.insertReturn(loan.getId(),quantity,key,type,outId,inId,SecurityUtils.getUsername());}
|
||||
private void requireRemaining(ProjectLoan loan,BigDecimal quantity){if(!Boolean.TRUE.equals(loan.getActive())||quantity==null||quantity.signum()<=0||quantity.stripTrailingZeros().scale()>4||quantity.compareTo(loan.getOutstandingQuantity())>0) throw error("归还数量必须大于0且不能超过未还数量:"+loan.getOutstandingQuantity());}
|
||||
private String key(String key){if(StringUtils.isBlank(key)||key.length()>100) throw error("业务标识不能为空或超长");return key;}
|
||||
private ServiceException error(String message){return new ServiceException(message);}
|
||||
}
|
||||
@ -21,6 +21,7 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
{
|
||||
private static final BigDecimal ZERO = BigDecimal.ZERO.setScale(2);
|
||||
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers;
|
||||
@Autowired
|
||||
private ProjectBudgetMapper projectBudgetMapper;
|
||||
|
||||
@ -30,7 +31,9 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
@Override
|
||||
public List<ExpenseCategory> selectExpenseCategoryList(ExpenseCategory category)
|
||||
{
|
||||
return projectBudgetMapper.selectExpenseCategoryList(category);
|
||||
return projectBudgetMapper.selectExpenseCategoryList(category).stream()
|
||||
.filter(item -> !isRetiredCompatibilityCategory(item.getCategoryCode()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -53,7 +56,7 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
throw new ServiceException("经费科目ID不能为空");
|
||||
}
|
||||
ExpenseCategory existing = projectBudgetMapper.selectExpenseCategoryById(category.getId());
|
||||
if (existing == null || "LEGACY".equals(existing.getCategoryCode()))
|
||||
if (existing == null || isRetiredCompatibilityCategory(existing.getCategoryCode()))
|
||||
{
|
||||
throw new ServiceException("经费科目不存在或不能修改");
|
||||
}
|
||||
@ -67,7 +70,7 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
public int deleteExpenseCategory(Long id)
|
||||
{
|
||||
ExpenseCategory existing = projectBudgetMapper.selectExpenseCategoryById(id);
|
||||
if (existing == null || "LEGACY".equals(existing.getCategoryCode()))
|
||||
if (existing == null || isRetiredCompatibilityCategory(existing.getCategoryCode()))
|
||||
{
|
||||
throw new ServiceException("经费科目不存在或不能删除");
|
||||
}
|
||||
@ -78,6 +81,11 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
return projectBudgetMapper.deleteExpenseCategory(id);
|
||||
}
|
||||
|
||||
private boolean isRetiredCompatibilityCategory(String categoryCode)
|
||||
{
|
||||
return "TRIAL".equals(categoryCode) || "OTHER".equals(categoryCode) || "LEGACY".equals(categoryCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProjectBudget> selectProjectBudgetList(Long projectId)
|
||||
{
|
||||
@ -117,10 +125,6 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
"BUDGET:" + budget.getId() + ":CREATE", "设置项目预算");
|
||||
return rows;
|
||||
}
|
||||
if (target.compareTo(money(existing.getCommittedAmount()).add(money(existing.getSpentAmount()))) < 0)
|
||||
{
|
||||
throw new ServiceException("预算金额不能小于已占用与已支出之和");
|
||||
}
|
||||
BigDecimal delta = target.subtract(money(existing.getBudgetAmount()));
|
||||
existing.setBudgetAmount(target);
|
||||
existing.setAlertPercent(validAlertPercent(budget.getAlertPercent()));
|
||||
@ -191,12 +195,6 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
{
|
||||
throw new ServiceException("经费流水会导致预算、占用或支出出现负数");
|
||||
}
|
||||
if (newCommitted.add(newSpent).compareTo(newBudget) > 0)
|
||||
{
|
||||
throw new ServiceException("项目经费不足,可用金额:"
|
||||
+ money(budget.getBudgetAmount()).subtract(money(budget.getCommittedAmount()))
|
||||
.subtract(money(budget.getSpentAmount())));
|
||||
}
|
||||
budget.setBudgetAmount(newBudget);
|
||||
budget.setCommittedAmount(newCommitted);
|
||||
budget.setSpentAmount(newSpent);
|
||||
@ -210,7 +208,7 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
BigDecimal spentDelta, String bizType, Long bizId, String bizNo, String idempotencyKey, String remark)
|
||||
{
|
||||
ProjectFundLedger ledger = new ProjectFundLedger();
|
||||
ledger.setLedgerNo(WarehouseNoUtils.next("FUND"));
|
||||
ledger.setLedgerNo(businessNumbers.next("FUND"));
|
||||
ledger.setProjectId(budget.getProjectId());
|
||||
ledger.setExpenseCategoryId(budget.getExpenseCategoryId());
|
||||
ledger.setBizType(bizType);
|
||||
@ -267,7 +265,6 @@ public class ProjectBudgetServiceImpl implements IProjectBudgetService
|
||||
|
||||
private Long currentScopeUserId()
|
||||
{
|
||||
return SecurityUtils.isAdmin() || SecurityUtils.hasPermi("project:project:manage")
|
||||
? null : SecurityUtils.getUserId();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,14 +1,13 @@
|
||||
package com.ruoyi.project.service.impl;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.warehouse.util.WarehouseNoUtils;
|
||||
import com.ruoyi.project.domain.ProjectInfo;
|
||||
import com.ruoyi.project.mapper.ProjectInfoMapper;
|
||||
import com.ruoyi.project.service.IProjectInfoService;
|
||||
@ -16,6 +15,7 @@ import com.ruoyi.project.service.IProjectInfoService;
|
||||
@Service
|
||||
public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
{
|
||||
@Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers;
|
||||
@Autowired
|
||||
private ProjectInfoMapper projectInfoMapper;
|
||||
|
||||
@ -33,7 +33,6 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
{
|
||||
throw new ServiceException("项目不存在或无权访问");
|
||||
}
|
||||
project.setMemberIds(projectInfoMapper.selectProjectMemberIds(id));
|
||||
return project;
|
||||
}
|
||||
|
||||
@ -47,6 +46,7 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
@Transactional
|
||||
public int insertProjectInfo(ProjectInfo project)
|
||||
{
|
||||
project.setProjectCode(businessNumbers.next("PROJ"));
|
||||
normalizeAndValidate(project);
|
||||
if (projectInfoMapper.selectProjectInfoByCode(project.getProjectCode()) != null)
|
||||
{
|
||||
@ -54,7 +54,6 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
}
|
||||
project.setCreateBy(SecurityUtils.getUsername());
|
||||
int rows = projectInfoMapper.insertProjectInfo(project);
|
||||
replaceMembers(project);
|
||||
return rows;
|
||||
}
|
||||
|
||||
@ -71,6 +70,11 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
{
|
||||
throw new ServiceException("项目不存在或历史待归属项目不能修改");
|
||||
}
|
||||
project.setProjectCode(existing.getProjectCode());
|
||||
if (project.getVersion() == null || !project.getVersion().equals(existing.getVersion()))
|
||||
{
|
||||
throw new ServiceException("项目已被修改,请刷新后重试");
|
||||
}
|
||||
normalizeAndValidate(project);
|
||||
ProjectInfo sameCode = projectInfoMapper.selectProjectInfoByCode(project.getProjectCode());
|
||||
if (sameCode != null && !sameCode.getId().equals(project.getId()))
|
||||
@ -79,7 +83,7 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
}
|
||||
project.setUpdateBy(SecurityUtils.getUsername());
|
||||
int rows = projectInfoMapper.updateProjectInfo(project);
|
||||
replaceMembers(project);
|
||||
if (rows != 1) throw new ServiceException("项目已被修改,请刷新后重试");
|
||||
return rows;
|
||||
}
|
||||
|
||||
@ -94,9 +98,8 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
}
|
||||
if (projectInfoMapper.countProjectBusiness(id) > 0)
|
||||
{
|
||||
throw new ServiceException("项目已有预算、采购、库存或出库业务,不能删除,可改为已归档");
|
||||
throw new ServiceException("项目已有预算、采购、库存或出库业务,不能删除,可改为结题或终止");
|
||||
}
|
||||
projectInfoMapper.deleteProjectMembers(id);
|
||||
return projectInfoMapper.deleteProjectInfo(id);
|
||||
}
|
||||
|
||||
@ -107,10 +110,6 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
{
|
||||
throw new ServiceException("项目不能为空");
|
||||
}
|
||||
if (!isManageAll() && projectInfoMapper.countProjectAccess(projectId, SecurityUtils.getUserId()) == 0)
|
||||
{
|
||||
throw new ServiceException("无权使用该项目");
|
||||
}
|
||||
if (projectInfoMapper.selectProjectInfoById(projectId, null) == null)
|
||||
{
|
||||
throw new ServiceException("项目不存在");
|
||||
@ -121,11 +120,7 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
public void requireActiveProject(Long projectId)
|
||||
{
|
||||
requireProjectAccess(projectId);
|
||||
ProjectInfo project = projectInfoMapper.selectProjectInfoById(projectId, null);
|
||||
if (project.getProjectStatus() == null || (project.getProjectStatus() != 0 && project.getProjectStatus() != 1))
|
||||
{
|
||||
throw new ServiceException("项目已完成或归档,不能新增业务");
|
||||
}
|
||||
// Explicitly authorized: closed projects remain operable; controller permissions still apply.
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -134,28 +129,6 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
return projectInfoMapper.selectLegacyProjectId();
|
||||
}
|
||||
|
||||
private void replaceMembers(ProjectInfo project)
|
||||
{
|
||||
projectInfoMapper.deleteProjectMembers(project.getId());
|
||||
Set<Long> memberIds = new LinkedHashSet<>();
|
||||
if (project.getMemberIds() != null)
|
||||
{
|
||||
memberIds.addAll(project.getMemberIds());
|
||||
}
|
||||
if (project.getManagerId() != null)
|
||||
{
|
||||
memberIds.add(project.getManagerId());
|
||||
}
|
||||
for (Long userId : memberIds)
|
||||
{
|
||||
if (userId != null)
|
||||
{
|
||||
projectInfoMapper.insertProjectMember(project.getId(), userId,
|
||||
userId.equals(project.getManagerId()) ? "MANAGER" : "MEMBER", SecurityUtils.getUsername());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void normalizeAndValidate(ProjectInfo project)
|
||||
{
|
||||
project.setProjectCode(StringUtils.trim(project.getProjectCode()));
|
||||
@ -168,15 +141,25 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
{
|
||||
throw new ServiceException("项目编码只能包含字母、数字、下划线和中划线");
|
||||
}
|
||||
if (project.getStartDate() != null && project.getEndDate() != null
|
||||
&& project.getStartDate().after(project.getEndDate()))
|
||||
{
|
||||
throw new ServiceException("项目结束日期不能早于开始日期");
|
||||
}
|
||||
if (project.getProjectStatus() == null)
|
||||
{
|
||||
project.setProjectStatus(1);
|
||||
project.setProjectStatus(0);
|
||||
}
|
||||
if (project.getProjectStatus() < 0 || project.getProjectStatus() > 3)
|
||||
{
|
||||
throw new ServiceException("项目状态不正确");
|
||||
}
|
||||
if (StringUtils.isBlank(project.getProjectType())) project.setProjectType("RESEARCH");
|
||||
if (!java.util.Set.of("RESEARCH", "PRODUCT").contains(project.getProjectType()))
|
||||
{
|
||||
throw new ServiceException("项目类型不正确");
|
||||
}
|
||||
if (project.getTotalAmount() == null || project.getTotalAmount().signum() < 0)
|
||||
{
|
||||
throw new ServiceException("项目总金额不能为空或为负数");
|
||||
}
|
||||
project.setTotalAmount(project.getTotalAmount().setScale(2, java.math.RoundingMode.HALF_UP));
|
||||
if (project.getProjectName().length() > 200) throw new ServiceException("项目名称不能超过200字");
|
||||
if (StringUtils.isBlank(project.getCurrency()))
|
||||
{
|
||||
project.setCurrency("CNY");
|
||||
@ -185,13 +168,8 @@ public class ProjectInfoServiceImpl implements IProjectInfoService
|
||||
|
||||
private Long currentScopeUserId()
|
||||
{
|
||||
return isManageAll() ? null : SecurityUtils.getUserId();
|
||||
// Authorized internal roles share all projects; menu/action permissions are unchanged.
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isManageAll()
|
||||
{
|
||||
return SecurityUtils.isAdmin()
|
||||
|| SecurityUtils.hasPermi("project:project:manage")
|
||||
|| SecurityUtils.hasPermi("warehouse:purchase:manage");
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,6 +11,10 @@ import com.ruoyi.common.core.domain.BaseEntity;
|
||||
public class InRecord extends BaseEntity
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
@Excel(name="业务日期",dateFormat="yyyy-MM-dd")
|
||||
private java.time.LocalDate businessDate;
|
||||
public java.time.LocalDate getBusinessDate(){return businessDate;}
|
||||
public void setBusinessDate(java.time.LocalDate value){businessDate=value;}
|
||||
|
||||
@Excel(name = "入库ID")
|
||||
private Long id;
|
||||
@ -23,8 +27,36 @@ public class InRecord extends BaseEntity
|
||||
private Long productId;
|
||||
|
||||
private Long purchaseRequestId;
|
||||
private String sourceKind;
|
||||
private String purchaseProjectName;
|
||||
private String purchaseBatchNo;
|
||||
public String getSourceKind(){return sourceKind;}
|
||||
public void setSourceKind(String v){sourceKind=v;}
|
||||
public String getPurchaseProjectName(){return purchaseProjectName;}
|
||||
public void setPurchaseProjectName(String v){purchaseProjectName=v;}
|
||||
public String getPurchaseBatchNo(){return purchaseBatchNo;}
|
||||
public void setPurchaseBatchNo(String v){purchaseBatchNo=v;}
|
||||
|
||||
private Long arrivalId;
|
||||
private Long productionTaskId;
|
||||
private Long completionId;
|
||||
public Long getProductionTaskId(){return productionTaskId;}
|
||||
public void setProductionTaskId(Long v){productionTaskId=v;}
|
||||
public Long getCompletionId(){return completionId;}
|
||||
public void setCompletionId(Long v){completionId=v;}
|
||||
private Boolean receiptRoot;
|
||||
private Long parentInId;
|
||||
private BigDecimal receivedQuantity;
|
||||
public Boolean getReceiptRoot(){return receiptRoot;}
|
||||
public void setReceiptRoot(Boolean v){receiptRoot=v;}
|
||||
public Long getParentInId(){return parentInId;}
|
||||
public void setParentInId(Long v){parentInId=v;}
|
||||
public BigDecimal getReceivedQuantity(){return receivedQuantity;}
|
||||
public void setReceivedQuantity(BigDecimal v){receivedQuantity=v;}
|
||||
private Long costEventId;
|
||||
private Integer costRevision;
|
||||
@Excel(name="入库单位成本")
|
||||
private BigDecimal receiptUnitCost;
|
||||
|
||||
private Long sourceProjectId;
|
||||
|
||||
@ -83,6 +115,12 @@ public class InRecord extends BaseEntity
|
||||
private String unit;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public Long getCostEventId() { return costEventId; }
|
||||
public void setCostEventId(Long costEventId) { this.costEventId=costEventId; }
|
||||
public Integer getCostRevision() { return costRevision; }
|
||||
public void setCostRevision(Integer costRevision) { this.costRevision=costRevision; }
|
||||
public BigDecimal getReceiptUnitCost() { return receiptUnitCost; }
|
||||
public void setReceiptUnitCost(BigDecimal receiptUnitCost) { this.receiptUnitCost=receiptUnitCost; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getInNo() { return inNo; }
|
||||
public void setInNo(String inNo) { this.inNo = inNo; }
|
||||
@ -114,7 +152,7 @@ public class InRecord extends BaseEntity
|
||||
public void setInType(Integer inType) { this.inType = inType; }
|
||||
|
||||
@NotNull(message = "入库数量不能为空")
|
||||
@DecimalMin(value = "0.001", message = "入库数量必须大于0")
|
||||
@DecimalMin(value = "0", inclusive = false, message = "入库数量必须大于0")
|
||||
public BigDecimal getInNum() { return inNum; }
|
||||
public void setInNum(BigDecimal inNum) { this.inNum = inNum; }
|
||||
public Integer getInStatus() { return inStatus; }
|
||||
|
||||
@ -0,0 +1,53 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class InventoryCostEvent extends BaseEntity {
|
||||
private java.time.LocalDate businessDate;
|
||||
public java.time.LocalDate getBusinessDate(){return businessDate;}
|
||||
public void setBusinessDate(java.time.LocalDate value){businessDate=value;}
|
||||
private Long id;
|
||||
private Long projectId;
|
||||
private Long itemId;
|
||||
private Long areaId;
|
||||
private String eventKey;
|
||||
private String eventNo;
|
||||
public String getEventNo(){return eventNo;}
|
||||
public void setEventNo(String value){eventNo=value;}
|
||||
private String eventType;
|
||||
private BigDecimal quantity;
|
||||
private BigDecimal receiptAmount;
|
||||
private Long sourceId;
|
||||
private BigDecimal originalCost;
|
||||
private BigDecimal effectiveCost;
|
||||
private Boolean active;
|
||||
private String voidReason;
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long value) { id = value; }
|
||||
public Long getProjectId() { return projectId; }
|
||||
public void setProjectId(Long value) { projectId = value; }
|
||||
public Long getItemId() { return itemId; }
|
||||
public void setItemId(Long value) { itemId = value; }
|
||||
public Long getAreaId() { return areaId; }
|
||||
public void setAreaId(Long value) { areaId = value; }
|
||||
public String getEventKey() { return eventKey; }
|
||||
public void setEventKey(String value) { eventKey = value; }
|
||||
public String getEventType() { return eventType; }
|
||||
public void setEventType(String value) { eventType = value; }
|
||||
public BigDecimal getQuantity() { return quantity; }
|
||||
public void setQuantity(BigDecimal value) { quantity = value; }
|
||||
public BigDecimal getReceiptAmount() { return receiptAmount; }
|
||||
public void setReceiptAmount(BigDecimal value) { receiptAmount = value; }
|
||||
public Long getSourceId() { return sourceId; }
|
||||
public void setSourceId(Long value) { sourceId = value; }
|
||||
public BigDecimal getOriginalCost() { return originalCost; }
|
||||
public void setOriginalCost(BigDecimal value) { originalCost = value; }
|
||||
public BigDecimal getEffectiveCost() { return effectiveCost; }
|
||||
public void setEffectiveCost(BigDecimal value) { effectiveCost = value; }
|
||||
public Boolean getActive() { return active; }
|
||||
public void setActive(Boolean value) { active = value; }
|
||||
public String getVoidReason() { return voidReason; }
|
||||
public void setVoidReason(String value) { voidReason = value; }
|
||||
}
|
||||
|
||||
@ -0,0 +1,26 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
|
||||
public class InventoryCostRevision extends BaseEntity {
|
||||
private Long id;
|
||||
private String revisionKey;
|
||||
private String revisionNo;
|
||||
public String getRevisionNo(){return revisionNo;}
|
||||
public void setRevisionNo(String value){revisionNo=value;}
|
||||
private Long targetEventId;
|
||||
private BigDecimal newAmount;
|
||||
private Integer expectedVersion;
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long value) { id = value; }
|
||||
public String getRevisionKey() { return revisionKey; }
|
||||
public void setRevisionKey(String value) { revisionKey = value; }
|
||||
public Long getTargetEventId() { return targetEventId; }
|
||||
public void setTargetEventId(Long value) { targetEventId = value; }
|
||||
public BigDecimal getNewAmount() { return newAmount; }
|
||||
public void setNewAmount(BigDecimal value) { newAmount = value; }
|
||||
public Integer getExpectedVersion() { return expectedVersion; }
|
||||
public void setExpectedVersion(Integer value) { expectedVersion = value; }
|
||||
}
|
||||
|
||||
@ -21,11 +21,16 @@ public class OutRecord extends BaseEntity
|
||||
private Long areaId;
|
||||
private Long productId;
|
||||
private Long usageProjectId;
|
||||
private Long costEventId;
|
||||
private Boolean active;
|
||||
@Excel(name = "有效材料成本")
|
||||
private BigDecimal costAmount;
|
||||
private BigDecimal returnedQuantity;
|
||||
|
||||
@Excel(name = "使用项目")
|
||||
private String usageProjectName;
|
||||
|
||||
@Excel(name = "出库类型", readConverterExp = "1=生产出库,2=退货出库,3=销售出库")
|
||||
@Excel(name = "出库类型", readConverterExp = "1=生产出库,2=退货出库,3=销售出库,4=项目领用")
|
||||
private Integer outType;
|
||||
|
||||
@Excel(name = "出库数量")
|
||||
@ -77,6 +82,14 @@ public class OutRecord extends BaseEntity
|
||||
private String unit;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public Long getCostEventId() { return costEventId; }
|
||||
public void setCostEventId(Long costEventId) { this.costEventId=costEventId; }
|
||||
public Boolean getActive() { return active; }
|
||||
public void setActive(Boolean active) { this.active=active; }
|
||||
public BigDecimal getCostAmount() { return costAmount; }
|
||||
public void setCostAmount(BigDecimal costAmount) { this.costAmount=costAmount; }
|
||||
public BigDecimal getReturnedQuantity() { return returnedQuantity; }
|
||||
public void setReturnedQuantity(BigDecimal returnedQuantity) { this.returnedQuantity=returnedQuantity; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getOutNo() { return outNo; }
|
||||
public void setOutNo(String outNo) { this.outNo = outNo; }
|
||||
@ -98,7 +111,7 @@ public class OutRecord extends BaseEntity
|
||||
public void setOutType(Integer outType) { this.outType = outType; }
|
||||
|
||||
@NotNull(message = "出库数量不能为空")
|
||||
@DecimalMin(value = "0.001", message = "出库数量必须大于0")
|
||||
@DecimalMin(value = "0.0001", message = "出库数量必须大于0,最多4位小数")
|
||||
public BigDecimal getOutNum() { return outNum; }
|
||||
public void setOutNum(BigDecimal outNum) { this.outNum = outNum; }
|
||||
public String getSourceNo() { return sourceNo; }
|
||||
|
||||
@ -8,9 +8,10 @@ public class ProductInfo extends BaseEntity
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Excel(name = "产品ID")
|
||||
@Excel(name = "产品ID",type=Excel.Type.EXPORT)
|
||||
private Long id;
|
||||
|
||||
@Excel(name="物品编码",prompt="新增时可留空,系统自动生成;已有编码不可重复导入")
|
||||
private String productCode;
|
||||
|
||||
@Excel(name = "产品名称")
|
||||
|
||||
@ -0,0 +1,26 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
import com.ruoyi.warehouse.util.MovingAverageCost;
|
||||
|
||||
public class ProjectItemCost extends BaseEntity {
|
||||
private Long projectId;
|
||||
private Long itemId;
|
||||
private BigDecimal quantity;
|
||||
private BigDecimal amount;
|
||||
private Integer version;
|
||||
public Long getProjectId() { return projectId; }
|
||||
public void setProjectId(Long value) { projectId = value; }
|
||||
public Long getItemId() { return itemId; }
|
||||
public void setItemId(Long value) { itemId = value; }
|
||||
public BigDecimal getQuantity() { return quantity; }
|
||||
public void setQuantity(BigDecimal value) { quantity = value; }
|
||||
public BigDecimal getAmount() { return amount; }
|
||||
public void setAmount(BigDecimal value) { amount = value; }
|
||||
public Integer getVersion() { return version; }
|
||||
public void setVersion(Integer value) { version = value; }
|
||||
public BigDecimal getAverageUnitCost() { return new MovingAverageCost.Balance(quantity, amount).averageUnitCost(); }
|
||||
public boolean isComplete() { return amount != null; }
|
||||
}
|
||||
|
||||
@ -3,15 +3,22 @@ package com.ruoyi.warehouse.domain;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class PurchaseArrival extends BaseEntity
|
||||
{
|
||||
private java.math.BigDecimal defectiveQuantity;
|
||||
public java.math.BigDecimal getDefectiveQuantity(){return defectiveQuantity;}
|
||||
public void setDefectiveQuantity(java.math.BigDecimal v){defectiveQuantity=v;}
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
private String requestKey;
|
||||
public String getRequestKey(){return requestKey;}
|
||||
public void setRequestKey(String value){requestKey=value;}
|
||||
private String arrivalNo;
|
||||
private Long purchaseRequestId;
|
||||
private BigDecimal arrivalQuantity;
|
||||
@ -37,7 +44,9 @@ public class PurchaseArrival extends BaseEntity
|
||||
private String revokeRemark;
|
||||
|
||||
private String requestNo;
|
||||
@JsonIgnore
|
||||
private Long applicantId;
|
||||
@JsonIgnore
|
||||
private String applicantName;
|
||||
private Long productId;
|
||||
private String productCode;
|
||||
@ -59,7 +68,7 @@ public class PurchaseArrival extends BaseEntity
|
||||
public void setPurchaseRequestId(Long purchaseRequestId) { this.purchaseRequestId = purchaseRequestId; }
|
||||
|
||||
@NotNull(message = "到货数量不能为空")
|
||||
@DecimalMin(value = "0.001", message = "到货数量必须大于0")
|
||||
@DecimalMin(value = "0", inclusive = false, message = "到货数量必须大于0")
|
||||
public BigDecimal getArrivalQuantity() { return arrivalQuantity; }
|
||||
public void setArrivalQuantity(BigDecimal arrivalQuantity) { this.arrivalQuantity = arrivalQuantity; }
|
||||
public BigDecimal getActualUnitPrice() { return actualUnitPrice; }
|
||||
|
||||
@ -7,6 +7,9 @@ public class PurchaseArrivalAcceptanceRequest
|
||||
@NotNull(message = "验收结果不能为空")
|
||||
private Integer acceptanceStatus;
|
||||
private String acceptanceRemark;
|
||||
private java.math.BigDecimal defectiveQuantity;
|
||||
public java.math.BigDecimal getDefectiveQuantity(){return defectiveQuantity;}
|
||||
public void setDefectiveQuantity(java.math.BigDecimal v){defectiveQuantity=v;}
|
||||
|
||||
public Integer getAcceptanceStatus() { return acceptanceStatus; }
|
||||
public void setAcceptanceStatus(Integer acceptanceStatus) { this.acceptanceStatus = acceptanceStatus; }
|
||||
|
||||
@ -7,6 +7,45 @@ public class PurchaseBatch extends BaseEntity
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
private Long projectId;
|
||||
private String materialName;
|
||||
private String projectNames;
|
||||
private java.math.BigDecimal totalAmount;
|
||||
private java.math.BigDecimal lockedTotal;
|
||||
private Integer unlockedCount;
|
||||
private Integer unpricedCount;
|
||||
private Integer openCount;
|
||||
private Integer pendingCount;
|
||||
private Integer partialCount;
|
||||
public Integer getPartialCount(){return partialCount;}
|
||||
public void setPartialCount(Integer value){partialCount=value;}
|
||||
public Long getProjectId(){return projectId;}
|
||||
public void setProjectId(Long value){projectId=value;}
|
||||
public String getMaterialName(){return materialName;}
|
||||
public void setMaterialName(String value){materialName=value;}
|
||||
public String getProjectNames(){return projectNames;}
|
||||
public void setProjectNames(String value){projectNames=value;}
|
||||
public java.math.BigDecimal getTotalAmount(){return totalAmount;}
|
||||
public void setTotalAmount(java.math.BigDecimal value){totalAmount=value;}
|
||||
public java.math.BigDecimal getLockedTotal(){return lockedTotal;}
|
||||
public void setLockedTotal(java.math.BigDecimal value){lockedTotal=value;}
|
||||
public Integer getUnlockedCount(){return unlockedCount;}
|
||||
public void setUnlockedCount(Integer value){unlockedCount=value;}
|
||||
public Integer getUnpricedCount(){return unpricedCount;}
|
||||
public void setUnpricedCount(Integer value){unpricedCount=value;}
|
||||
public Integer getOpenCount(){return openCount;}
|
||||
public void setOpenCount(Integer value){openCount=value;}
|
||||
public Integer getPendingCount(){return pendingCount;}
|
||||
public void setPendingCount(Integer value){pendingCount=value;}
|
||||
private Long supplierId;
|
||||
private String supplierName;
|
||||
private java.time.LocalDate businessDate;
|
||||
public Long getSupplierId(){return supplierId;}
|
||||
public void setSupplierId(Long value){supplierId=value;}
|
||||
public String getSupplierName(){return supplierName;}
|
||||
public void setSupplierName(String value){supplierName=value;}
|
||||
public java.time.LocalDate getBusinessDate(){return businessDate;}
|
||||
public void setBusinessDate(java.time.LocalDate value){businessDate=value;}
|
||||
private String batchNo;
|
||||
private String batchName;
|
||||
private Integer purchaseStatus;
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.ruoyi.common.annotation.Excel;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
@ -18,6 +17,32 @@ public class PurchaseRequest extends BaseEntity
|
||||
private String requestNo;
|
||||
|
||||
private Long productId;
|
||||
@Excel(name="采购用途",readConverterExp="SELF=本项目使用,REPAY=归还借用") private String purchasePurpose;
|
||||
private Long loanId;
|
||||
private Long productionTaskId;
|
||||
private Boolean historical;
|
||||
private java.time.LocalDate originalDate;
|
||||
public Boolean getHistorical(){return historical;}
|
||||
public void setHistorical(Boolean value){historical=value;}
|
||||
public java.time.LocalDate getOriginalDate(){return originalDate;}
|
||||
public void setOriginalDate(java.time.LocalDate value){originalDate=value;}
|
||||
private Long supplierId;
|
||||
private String supplierName;
|
||||
private Boolean notArrived;
|
||||
private Boolean unbatched;
|
||||
public Boolean getUnbatched(){return unbatched;}
|
||||
public void setUnbatched(Boolean value){unbatched=value;}
|
||||
private Boolean notReceived;
|
||||
public Long getSupplierId(){return supplierId;}
|
||||
public void setSupplierId(Long value){supplierId=value;}
|
||||
public String getSupplierName(){return supplierName;}
|
||||
public void setSupplierName(String value){supplierName=value;}
|
||||
public Boolean getNotArrived(){return notArrived;}
|
||||
public void setNotArrived(Boolean value){notArrived=value;}
|
||||
public Boolean getNotReceived(){return notReceived;}
|
||||
public void setNotReceived(Boolean value){notReceived=value;}
|
||||
public Long getProductionTaskId(){return productionTaskId;}
|
||||
public void setProductionTaskId(Long value){productionTaskId=value;}
|
||||
|
||||
private Long purchaseBatchId;
|
||||
|
||||
@ -40,7 +65,7 @@ public class PurchaseRequest extends BaseEntity
|
||||
@Excel(name = "关联物料编码", prompt = "已有物料建议填写准确编码;留空时按名称、品牌、类别、参数规格匹配")
|
||||
private String productCode;
|
||||
|
||||
@Excel(name = "物料名称", prompt = "必填;无匹配物料时将自动新增产品信息")
|
||||
@Excel(name = "物料名称", prompt = "须匹配已有物品档案;不会自动新增物品")
|
||||
private String materialName;
|
||||
|
||||
@Excel(name = "品牌")
|
||||
@ -58,22 +83,25 @@ public class PurchaseRequest extends BaseEntity
|
||||
@Excel(name = "需求数量")
|
||||
private BigDecimal quantity;
|
||||
|
||||
@Excel(name = "预计含税单价")
|
||||
private BigDecimal estimatedUnitPrice;
|
||||
|
||||
@Excel(name = "预计总金额", type = Excel.Type.EXPORT)
|
||||
@Excel(name = "采购总金额", type = Excel.Type.EXPORT)
|
||||
private BigDecimal estimatedAmount;
|
||||
@Excel(name = "最终含税单价")
|
||||
private BigDecimal finalUnitPrice;
|
||||
@Excel(name = "价格锁定", readConverterExp = "true=已锁定,false=未锁定", type = Excel.Type.EXPORT)
|
||||
private Boolean priceLocked;
|
||||
@Excel(name = "已计项目费用", type = Excel.Type.EXPORT)
|
||||
private BigDecimal lockedAmount;
|
||||
private Integer lockRevision;
|
||||
|
||||
@Excel(name = "单位")
|
||||
private String unit;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
@Excel(name = "期望到货日期", width = 20, dateFormat = "yyyy-MM-dd")
|
||||
private Date expectedDate;
|
||||
|
||||
@JsonIgnore
|
||||
private Long applicantId;
|
||||
|
||||
@Excel(name = "申请人", type = Excel.Type.EXPORT)
|
||||
@JsonIgnore
|
||||
private String applicantName;
|
||||
|
||||
@Excel(name = "采购状态", readConverterExp = "0=待采购,1=已下单,2=采购中,3=部分到货,4=已到齐,5=已取消", type = Excel.Type.EXPORT)
|
||||
@ -104,6 +132,9 @@ public class PurchaseRequest extends BaseEntity
|
||||
@Excel(name = "待验收数量", type = Excel.Type.EXPORT)
|
||||
private BigDecimal pendingArrivalQuantity;
|
||||
|
||||
/** 已确认入库数量,用于锁定采购价格和归属字段的编辑入口。 */
|
||||
private BigDecimal receivedQuantity;
|
||||
|
||||
private BigDecimal remainingQuantity;
|
||||
|
||||
/** 仅查询存在待验收到货记录的采购申请。 */
|
||||
@ -114,6 +145,10 @@ public class PurchaseRequest extends BaseEntity
|
||||
public String getRequestNo() { return requestNo; }
|
||||
public void setRequestNo(String requestNo) { this.requestNo = requestNo; }
|
||||
public Long getProductId() { return productId; }
|
||||
public String getPurchasePurpose() { return purchasePurpose; }
|
||||
public void setPurchasePurpose(String v) { purchasePurpose=v; }
|
||||
public Long getLoanId() { return loanId; }
|
||||
public void setLoanId(Long v) { loanId=v; }
|
||||
public void setProductId(Long productId) { this.productId = productId; }
|
||||
public Long getPurchaseBatchId() { return purchaseBatchId; }
|
||||
public void setPurchaseBatchId(Long purchaseBatchId) { this.purchaseBatchId = purchaseBatchId; }
|
||||
@ -145,17 +180,23 @@ public class PurchaseRequest extends BaseEntity
|
||||
public void setPurchaseLink(String purchaseLink) { this.purchaseLink = purchaseLink; }
|
||||
|
||||
@NotNull(message = "需求数量不能为空")
|
||||
@DecimalMin(value = "0.001", message = "需求数量必须大于0")
|
||||
@DecimalMin(value = "0", inclusive = false, message = "需求数量必须大于0")
|
||||
public BigDecimal getQuantity() { return quantity; }
|
||||
public void setQuantity(BigDecimal quantity) { this.quantity = quantity; }
|
||||
public BigDecimal getEstimatedUnitPrice() { return estimatedUnitPrice; }
|
||||
public void setEstimatedUnitPrice(BigDecimal estimatedUnitPrice) { this.estimatedUnitPrice = estimatedUnitPrice; }
|
||||
public BigDecimal getEstimatedAmount() { return estimatedAmount; }
|
||||
public void setEstimatedAmount(BigDecimal estimatedAmount) { this.estimatedAmount = estimatedAmount; }
|
||||
public BigDecimal getFinalUnitPrice() { return finalUnitPrice; }
|
||||
public void setFinalUnitPrice(BigDecimal value) { finalUnitPrice = value; }
|
||||
public Boolean getPriceLocked() { return priceLocked; }
|
||||
public void setPriceLocked(Boolean value) { priceLocked = value; }
|
||||
public BigDecimal getLockedAmount() { return lockedAmount; }
|
||||
public void setLockedAmount(BigDecimal value) { lockedAmount = value; }
|
||||
public Integer getLockRevision() { return lockRevision; }
|
||||
public void setLockRevision(Integer value) { lockRevision = value; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
public Date getExpectedDate() { return expectedDate; }
|
||||
public void setExpectedDate(Date expectedDate) { this.expectedDate = expectedDate; }
|
||||
public Long getApplicantId() { return applicantId; }
|
||||
public void setApplicantId(Long applicantId) { this.applicantId = applicantId; }
|
||||
public String getApplicantName() { return applicantName; }
|
||||
@ -184,6 +225,8 @@ public class PurchaseRequest extends BaseEntity
|
||||
public void setAcceptedQuantity(BigDecimal acceptedQuantity) { this.acceptedQuantity = acceptedQuantity; }
|
||||
public BigDecimal getPendingArrivalQuantity() { return pendingArrivalQuantity; }
|
||||
public void setPendingArrivalQuantity(BigDecimal pendingArrivalQuantity) { this.pendingArrivalQuantity = pendingArrivalQuantity; }
|
||||
public BigDecimal getReceivedQuantity() { return receivedQuantity; }
|
||||
public void setReceivedQuantity(BigDecimal receivedQuantity) { this.receivedQuantity = receivedQuantity; }
|
||||
public BigDecimal getRemainingQuantity() { return remainingQuantity; }
|
||||
public void setRemainingQuantity(BigDecimal remainingQuantity) { this.remainingQuantity = remainingQuantity; }
|
||||
public Boolean getPendingAcceptance() { return pendingAcceptance; }
|
||||
|
||||
@ -0,0 +1,20 @@
|
||||
package com.ruoyi.warehouse.domain;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** A full batch snapshot. Deletions are explicit; omitted rows cannot be silently removed. */
|
||||
public class PurchaseSheet
|
||||
{
|
||||
private PurchaseBatch batch;
|
||||
private List<PurchaseRequest> rows;
|
||||
private List<Long> deletedIds;
|
||||
private String version;
|
||||
public PurchaseBatch getBatch() { return batch; }
|
||||
public void setBatch(PurchaseBatch value) { batch = value; }
|
||||
public List<PurchaseRequest> getRows() { return rows; }
|
||||
public void setRows(List<PurchaseRequest> value) { rows = value; }
|
||||
public List<Long> getDeletedIds() { return deletedIds; }
|
||||
public void setDeletedIds(List<Long> value) { deletedIds = value; }
|
||||
public String getVersion() { return version; }
|
||||
public void setVersion(String value) { version = value; }
|
||||
}
|
||||
@ -11,6 +11,10 @@ import com.ruoyi.common.core.domain.BaseEntity;
|
||||
public class StockCheckRecord extends BaseEntity
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
@Excel(name="盘点日期",dateFormat="yyyy-MM-dd")
|
||||
private java.time.LocalDate businessDate;
|
||||
public java.time.LocalDate getBusinessDate(){return businessDate;}
|
||||
public void setBusinessDate(java.time.LocalDate value){businessDate=value;}
|
||||
|
||||
@Excel(name = "盘点ID")
|
||||
private Long id;
|
||||
@ -20,6 +24,11 @@ public class StockCheckRecord extends BaseEntity
|
||||
|
||||
private Long areaId;
|
||||
private Long productId;
|
||||
private Long projectId;
|
||||
@Excel(name="所属项目") private String projectName;
|
||||
private Long costEventId;
|
||||
private Integer bookVersion;
|
||||
@Excel(name="盘盈单位成本") private BigDecimal receiptUnitCost;
|
||||
|
||||
@Excel(name = "账面库存")
|
||||
private BigDecimal bookNum;
|
||||
@ -30,7 +39,7 @@ public class StockCheckRecord extends BaseEntity
|
||||
@Excel(name = "差异数量")
|
||||
private BigDecimal diffNum;
|
||||
|
||||
@Excel(name = "盘点状态", readConverterExp = "0=待确认,1=盘点生效")
|
||||
@Excel(name = "盘点状态", readConverterExp = "0=待确认,1=盘点生效,2=已撤销")
|
||||
private Integer checkStatus;
|
||||
|
||||
@Excel(name = "盘点人")
|
||||
@ -69,6 +78,16 @@ public class StockCheckRecord extends BaseEntity
|
||||
private String unit;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public Long getProjectId() { return projectId; }
|
||||
public void setProjectId(Long projectId) { this.projectId=projectId; }
|
||||
public String getProjectName() { return projectName; }
|
||||
public void setProjectName(String projectName) { this.projectName=projectName; }
|
||||
public Long getCostEventId() { return costEventId; }
|
||||
public void setCostEventId(Long costEventId) { this.costEventId=costEventId; }
|
||||
public Integer getBookVersion() { return bookVersion; }
|
||||
public void setBookVersion(Integer bookVersion) { this.bookVersion=bookVersion; }
|
||||
public BigDecimal getReceiptUnitCost() { return receiptUnitCost; }
|
||||
public void setReceiptUnitCost(BigDecimal receiptUnitCost) { this.receiptUnitCost=receiptUnitCost; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getCheckNo() { return checkNo; }
|
||||
public void setCheckNo(String checkNo) { this.checkNo = checkNo; }
|
||||
|
||||
@ -13,6 +13,14 @@ public class StockInfo extends BaseEntity
|
||||
private Long id;
|
||||
private Long areaId;
|
||||
private Long productId;
|
||||
private Long projectId;
|
||||
@Excel(name = "所属项目")
|
||||
private String projectName;
|
||||
@Excel(name = "项目物品平均单价")
|
||||
private BigDecimal averageUnitCost;
|
||||
@Excel(name = "库区库存金额")
|
||||
private BigDecimal stockAmount;
|
||||
private Integer version;
|
||||
|
||||
@Excel(name = "当前库存")
|
||||
private BigDecimal stockNum;
|
||||
@ -43,7 +51,23 @@ public class StockInfo extends BaseEntity
|
||||
@Excel(name = "单位")
|
||||
private String unit;
|
||||
|
||||
/** 是否为产品档案中启用的成品。只有成品库存可以办理成品报废和交付。 */
|
||||
private Boolean finishedProduct;
|
||||
|
||||
private Boolean includeZero = false;
|
||||
public Boolean getIncludeZero() { return includeZero; }
|
||||
public void setIncludeZero(Boolean includeZero) { this.includeZero = includeZero; }
|
||||
public Long getId() { return id; }
|
||||
public Long getProjectId() { return projectId; }
|
||||
public void setProjectId(Long projectId) { this.projectId = projectId; }
|
||||
public String getProjectName() { return projectName; }
|
||||
public void setProjectName(String projectName) { this.projectName = projectName; }
|
||||
public BigDecimal getAverageUnitCost() { return averageUnitCost; }
|
||||
public void setAverageUnitCost(BigDecimal averageUnitCost) { this.averageUnitCost = averageUnitCost; }
|
||||
public BigDecimal getStockAmount() { return stockAmount; }
|
||||
public void setStockAmount(BigDecimal stockAmount) { this.stockAmount = stockAmount; }
|
||||
public Integer getVersion() { return version; }
|
||||
public void setVersion(Integer version) { this.version = version; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public Long getAreaId() { return areaId; }
|
||||
public void setAreaId(Long areaId) { this.areaId = areaId; }
|
||||
@ -69,4 +93,6 @@ public class StockInfo extends BaseEntity
|
||||
public void setSpec(String spec) { this.spec = spec; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
public Boolean getFinishedProduct() { return finishedProduct; }
|
||||
public void setFinishedProduct(Boolean finishedProduct) { this.finishedProduct = finishedProduct; }
|
||||
}
|
||||
|
||||
@ -15,6 +15,9 @@ public class WarehouseArea extends BaseEntity
|
||||
|
||||
@Excel(name = "库区名称")
|
||||
private String areaName;
|
||||
private Integer status;
|
||||
public Integer getStatus(){return status;}
|
||||
public void setStatus(Integer status){this.status=status;}
|
||||
|
||||
public Long getId()
|
||||
{
|
||||
|
||||
@ -23,7 +23,6 @@ public class AgentResultItem
|
||||
private BigDecimal acceptedQuantity;
|
||||
private BigDecimal pendingArrivalQuantity;
|
||||
private BigDecimal estimatedAmount;
|
||||
private String expectedDate;
|
||||
|
||||
public Long getId()
|
||||
{
|
||||
@ -151,6 +150,4 @@ public class AgentResultItem
|
||||
public void setPendingArrivalQuantity(BigDecimal pendingArrivalQuantity) { this.pendingArrivalQuantity = pendingArrivalQuantity; }
|
||||
public BigDecimal getEstimatedAmount() { return estimatedAmount; }
|
||||
public void setEstimatedAmount(BigDecimal estimatedAmount) { this.estimatedAmount = estimatedAmount; }
|
||||
public String getExpectedDate() { return expectedDate; }
|
||||
public void setExpectedDate(String expectedDate) { this.expectedDate = expectedDate; }
|
||||
}
|
||||
|
||||
@ -5,6 +5,8 @@ import com.ruoyi.warehouse.domain.InRecord;
|
||||
|
||||
public interface InRecordMapper
|
||||
{
|
||||
java.math.BigDecimal receivedQuantity(Long rootId);
|
||||
int updateRootStatus(@org.apache.ibatis.annotations.Param("id") Long id,@org.apache.ibatis.annotations.Param("status") Integer status);
|
||||
public List<InRecord> selectInRecordList(InRecord inRecord);
|
||||
|
||||
public InRecord selectInRecordById(Long id);
|
||||
@ -20,6 +22,7 @@ public interface InRecordMapper
|
||||
public int updateInRecord(InRecord inRecord);
|
||||
|
||||
public int confirmInRecord(InRecord inRecord);
|
||||
public int revokeInRecord(InRecord inRecord);
|
||||
|
||||
public int deleteInRecordByIds(Long[] ids);
|
||||
|
||||
|
||||
@ -0,0 +1,34 @@
|
||||
package com.ruoyi.warehouse.mapper;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.warehouse.domain.*;
|
||||
import com.ruoyi.warehouse.util.MovingAverageCost.Difference;
|
||||
|
||||
public interface InventoryCostMapper {
|
||||
int insertLink(@org.apache.ibatis.annotations.Param("sourceId") Long sourceId,@org.apache.ibatis.annotations.Param("targetId") Long targetId);
|
||||
Long selectLinkSource(Long targetId);
|
||||
java.util.List<Long> selectLinkedTargets(Long sourceId);
|
||||
java.util.List<Long> selectAllLinkedTargets();
|
||||
Integer selectAreaVersion(@org.apache.ibatis.annotations.Param("projectId") Long projectId,@org.apache.ibatis.annotations.Param("itemId") Long itemId,@org.apache.ibatis.annotations.Param("areaId") Long areaId);
|
||||
int syncLegacyArea(@org.apache.ibatis.annotations.Param("itemId") Long itemId, @org.apache.ibatis.annotations.Param("areaId") Long areaId);
|
||||
Integer lockJournal();
|
||||
InventoryCostEvent selectEvent(Long id);
|
||||
InventoryCostEvent selectEventByKey(String key);
|
||||
List<InventoryCostEvent> selectEvents(@Param("projectId") Long projectId, @Param("itemId") Long itemId);
|
||||
int insertEvent(InventoryCostEvent event);
|
||||
int setOriginalCost(@Param("id") Long id, @Param("amount") BigDecimal amount);
|
||||
int setEffectiveCost(@Param("id") Long id, @Param("amount") BigDecimal amount);
|
||||
int voidEvent(@Param("id") Long id, @Param("reason") String reason, @Param("actor") String actor);
|
||||
int ensureCost(@Param("projectId") Long projectId, @Param("itemId") Long itemId);
|
||||
ProjectItemCost selectCost(@Param("projectId") Long projectId, @Param("itemId") Long itemId);
|
||||
int updateCost(@Param("projectId") Long projectId, @Param("itemId") Long itemId, @Param("quantity") BigDecimal quantity, @Param("amount") BigDecimal amount);
|
||||
int increaseArea(@Param("projectId") Long projectId, @Param("itemId") Long itemId, @Param("areaId") Long areaId, @Param("quantity") BigDecimal quantity);
|
||||
int decreaseArea(@Param("projectId") Long projectId, @Param("itemId") Long itemId, @Param("areaId") Long areaId, @Param("quantity") BigDecimal quantity);
|
||||
BigDecimal selectAreaQuantity(@Param("projectId") Long projectId, @Param("itemId") Long itemId, @Param("areaId") Long areaId);
|
||||
List<InventoryCostRevision> selectOverrides(@Param("projectId") Long projectId, @Param("itemId") Long itemId);
|
||||
InventoryCostRevision selectRevisionByKey(String key);
|
||||
int insertRevision(InventoryCostRevision revision);
|
||||
int insertChange(@Param("revisionId") Long revisionId, @Param("change") Difference change);
|
||||
}
|
||||
@ -5,6 +5,7 @@ import com.ruoyi.warehouse.domain.OutRecord;
|
||||
|
||||
public interface OutRecordMapper
|
||||
{
|
||||
int revoke(Long id);
|
||||
public List<OutRecord> selectOutRecordList(OutRecord outRecord);
|
||||
|
||||
public OutRecord selectOutRecordById(Long id);
|
||||
|
||||
@ -26,4 +26,8 @@ public interface ProductInfoMapper
|
||||
public int updateProductInfo(ProductInfo productInfo);
|
||||
|
||||
public int deleteProductInfoByIds(Long[] ids);
|
||||
|
||||
public int countBusinessReferences(Long id);
|
||||
|
||||
public ProductInfo selectProductInfoForUpdate(Long id);
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ import com.ruoyi.warehouse.domain.PurchaseTaskSummary;
|
||||
|
||||
public interface PurchaseRequestMapper
|
||||
{
|
||||
List<PurchaseRequest> selectPurchaseSheetRows(Long batchId);
|
||||
List<PurchaseRequest> selectPurchaseRequestList(PurchaseRequest purchaseRequest);
|
||||
PurchaseTaskSummary selectPurchaseTaskSummary();
|
||||
PurchaseRequest selectPurchaseRequestById(@Param("id") Long id, @Param("applicantId") Long applicantId);
|
||||
@ -17,4 +18,8 @@ public interface PurchaseRequestMapper
|
||||
int deletePurchaseRequestByIds(@Param("ids") Long[] ids, @Param("applicantId") Long applicantId);
|
||||
int updatePurchaseStatus(@Param("id") Long id, @Param("purchaseStatus") Integer purchaseStatus,
|
||||
@Param("progressRemark") String progressRemark, @Param("updateBy") String updateBy);
|
||||
int countConfirmedInbound(Long id);
|
||||
int updatePriceState(PurchaseRequest request);
|
||||
int insertPriceLedger(@Param("existing") PurchaseRequest existing, @Param("updated") PurchaseRequest updated,
|
||||
@Param("operation") String operation, @Param("newLedgerNo") String newLedgerNo, @Param("oldLedgerNo") String oldLedgerNo);
|
||||
}
|
||||
|
||||
@ -18,6 +18,7 @@ public interface StockCheckRecordMapper
|
||||
public int updateStockCheckRecord(StockCheckRecord stockCheckRecord);
|
||||
|
||||
public int confirmStockCheckRecord(StockCheckRecord stockCheckRecord);
|
||||
int revoke(@org.apache.ibatis.annotations.Param("id") Long id,@org.apache.ibatis.annotations.Param("reason") String reason,@org.apache.ibatis.annotations.Param("username") String username);
|
||||
|
||||
public int deleteStockCheckRecordByIds(Long[] ids);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user