diff --git a/.gitignore b/.gitignore index 1db319f..2221de4 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/android-app/app/build.gradle b/android-app/app/build.gradle new file mode 100644 index 0000000..0e06e76 --- /dev/null +++ b/android-app/app/build.gradle @@ -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' } diff --git a/android-app/app/src/main/AndroidManifest.xml b/android-app/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3320635 --- /dev/null +++ b/android-app/app/src/main/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/android-app/app/src/main/java/cn/cmvr/projectwarehouse/BundleStore.java b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/BundleStore.java new file mode 100644 index 0000000..d588779 --- /dev/null +++ b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/BundleStore.java @@ -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);}}}} + } +} diff --git a/android-app/app/src/main/java/cn/cmvr/projectwarehouse/EdgeBackLayout.java b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/EdgeBackLayout.java new file mode 100644 index 0000000..8648143 --- /dev/null +++ b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/EdgeBackLayout.java @@ -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); } +} diff --git a/android-app/app/src/main/java/cn/cmvr/projectwarehouse/LocalWebServer.java b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/LocalWebServer.java new file mode 100644 index 0000000..2a181d7 --- /dev/null +++ b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/LocalWebServer.java @@ -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 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 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();} +} diff --git a/android-app/app/src/main/java/cn/cmvr/projectwarehouse/MainActivity.java b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/MainActivity.java new file mode 100644 index 0000000..8db7787 --- /dev/null +++ b/android-app/app/src/main/java/cn/cmvr/projectwarehouse/MainActivity.java @@ -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();} +} diff --git a/android-app/app/src/test/java/cn/cmvr/projectwarehouse/LocalTransportTest.java b/android-app/app/src/test/java/cn/cmvr/projectwarehouse/LocalTransportTest.java new file mode 100644 index 0000000..102a8b2 --- /dev/null +++ b/android-app/app/src/test/java/cn/cmvr/projectwarehouse/LocalTransportTest.java @@ -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"),"mobile-test".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);}} +} diff --git a/android-app/build.gradle b/android-app/build.gradle new file mode 100644 index 0000000..74c6c79 --- /dev/null +++ b/android-app/build.gradle @@ -0,0 +1 @@ +plugins { id 'com.android.application' version '8.9.2' apply false } diff --git a/android-app/gradle.properties b/android-app/gradle.properties new file mode 100644 index 0000000..28b6668 --- /dev/null +++ b/android-app/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +org.gradle.daemon=false diff --git a/android-app/settings.gradle b/android-app/settings.gradle new file mode 100644 index 0000000..cc4da50 --- /dev/null +++ b/android-app/settings.gradle @@ -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' diff --git a/docs/项目采购库存生产成本管理系统设计确认稿.md b/docs/项目采购库存生产成本管理系统设计确认稿.md index 1e8f86d..9855b27 100644 --- a/docs/项目采购库存生产成本管理系统设计确认稿.md +++ b/docs/项目采购库存生产成本管理系统设计确认稿.md @@ -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、离线库存和系统内安装包下载。成品拆解回收及人工费、其他费用录入已明确删除。 diff --git a/docs/项目采购库存生产成本系统开发交付说明.md b/docs/项目采购库存生产成本系统开发交付说明.md new file mode 100644 index 0000000..b2dc9f8 --- /dev/null +++ b/docs/项目采购库存生产成本系统开发交付说明.md @@ -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 个页面接口及产品成本历史接口全部返回成功。 +- 字段验收:项目接口无负责人、成员、部门和起止日期;采购接口无申请人和预计到货日期;费用分类仅返回材料费、设备费、加工费。 + +自动化验证不能替代真实人员在浏览器和安卓设备上的最终业务验收。当前电脑的界面控制辅助进程异常退出,未能完成自动点击截图;安卓也尚未在实体设备安装操作。正式使用前仍应由项目组用一组真实项目数据,在浏览器和安卓设备完整走一次采购、到货、入库、生产、交付及撤销链路。 diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 07444d9..b062998 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -17,6 +17,12 @@ + + org.springframework.boot + spring-boot-starter-test + test + + org.springframework.boot @@ -58,6 +64,11 @@ + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.3 + org.springframework.boot spring-boot-maven-plugin diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java new file mode 100644 index 0000000..22c70c9 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/BomController.java @@ -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 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>();var seen=new java.util.HashSet();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();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(); } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionExcel.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionExcel.java new file mode 100644 index 0000000..8a833f7 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/production/ProductionExcel.java @@ -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> 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 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","有效"}}); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java new file mode 100644 index 0000000..d7e1ea6 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ProjectLoanController.java @@ -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),"项目借还");} +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/BusinessWithdrawalController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/BusinessWithdrawalController.java new file mode 100644 index 0000000..d63177e --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/BusinessWithdrawalController.java @@ -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));} +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java index 4cdc214..68b731e 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InRecordController.java @@ -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 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())); + } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InitializationController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InitializationController.java new file mode 100644 index 0000000..fb3aeb7 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/InitializationController.java @@ -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 columns(String kind){var result=new ArrayList(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;i10*1024*1024)throw new ServiceException("请选择10MB以内Excel");var cols=columns(kind);var rows=new ArrayList(); + 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 rows){return success(service.preview(kind,rows));} + @PostMapping("/{kind}/apply") @Log(title="可选历史初始化",businessType=BusinessType.IMPORT) + public AjaxResult apply(@PathVariable String kind,@RequestBody List rows){ + if(rows==null||rows.size()>2000)throw new ServiceException("每次最多2000行");var results=new ArrayList>();for(var row:rows){var result=new LinkedHashMap();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); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/OutRecordController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/OutRecordController.java index d0e08c4..1274a0c 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/OutRecordController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/OutRecordController.java @@ -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") diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java index 0d7c956..f0a172e 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/ProductInfoController.java @@ -29,6 +29,17 @@ public class ProductInfoController extends BaseController { @Autowired private IProductInfoService productInfoService; + @Autowired private com.ruoyi.warehouse.service.impl.WarehouseImportReceiptService importReceipts; + private List 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") diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchasePriceController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchasePriceController.java new file mode 100644 index 0000000..c8677ec --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchasePriceController.java @@ -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> result = new ArrayList<>(); + for (Long id : new LinkedHashSet<>(Arrays.asList(ids))) + { + Map 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); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java index 4e17ee6..8715bdc 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseRequestController.java @@ -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(); + 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 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 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 util = new ExcelUtil(PurchaseRequest.class); List 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')") diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java new file mode 100644 index 0000000..7978683 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseReturnController.java @@ -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));} +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseTemplateExcelUtil.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseTemplateExcelUtil.java index 1461a8f..b0f94d5 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseTemplateExcelUtil.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/PurchaseTemplateExcelUtil.java @@ -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); } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockCheckRecordController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockCheckRecordController.java index 8dea542..c4cadfa 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockCheckRecordController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockCheckRecordController.java @@ -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 body){return toAjax(stockCheckRecordService.revoke(id,body.get("reason")));} + @PreAuthorize("@ss.hasPermi('warehouse:check:remove')") @Log(title = "盘库记录", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java index 4e846af..5b4eb0b 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/StockInfoController.java @@ -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 request){journal.revokeMove(id,request.get("reason"));return success();} @PreAuthorize("@ss.hasPermi('warehouse:stock:list')") @GetMapping("/list") diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierController.java new file mode 100644 index 0000000..9996763 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierController.java @@ -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();} +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierPurchaseExport.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierPurchaseExport.java new file mode 100644 index 0000000..51c8dc8 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/warehouse/SupplierPurchaseExport.java @@ -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 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 lines){ + var groups=new LinkedHashMap(); + 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 - + @@ -90,4 +90,4 @@ - \ No newline at end of file + diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/AuthorizedDatabaseTestSupport.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/AuthorizedDatabaseTestSupport.java new file mode 100644 index 0000000..9f217a1 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/AuthorizedDatabaseTestSupport.java @@ -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)); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java new file mode 100644 index 0000000..d2e108b --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomDatabaseTest.java @@ -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 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(); } + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomGraphRulesTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomGraphRulesTest.java new file mode 100644 index 0000000..250e681 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomGraphRulesTest.java @@ -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))); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomImportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomImportTest.java new file mode 100644 index 0000000..ba9a4d6 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BomImportTest.java @@ -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>)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()); 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()); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BusinessNumberDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BusinessNumberDatabaseTest.java new file mode 100644 index 0000000..adfe6e8 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/BusinessNumberDatabaseTest.java @@ -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> calls=new ArrayList<>();for(int i=0;i<48;i++)calls.add(()->numbers.next("TASK",date)); + Set 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 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)); + }); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ConfirmedFieldContractTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ConfirmedFieldContractTest.java new file mode 100644 index 0000000..285d4b6 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ConfirmedFieldContractTest.java @@ -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; + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/InventoryCostJournalDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/InventoryCostJournalDatabaseTest.java new file mode 100644 index 0000000..0aef24c --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/InventoryCostJournalDatabaseTest.java @@ -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 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 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(); } + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/MovingAverageCostTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/MovingAverageCostTest.java new file mode 100644 index 0000000..0851546 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/MovingAverageCostTest.java @@ -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 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 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 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 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 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)); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/NamespacedRedisKeySerializerTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/NamespacedRedisKeySerializerTest.java new file mode 100644 index 0000000..dcf0e82 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/NamespacedRedisKeySerializerTest.java @@ -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("")); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/OptionalInitializationDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/OptionalInitializationDatabaseTest.java new file mode 100644 index 0000000..197a0f8 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/OptionalInitializationDatabaseTest.java @@ -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 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)); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java new file mode 100644 index 0000000..23e97f0 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductImportTest.java @@ -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));} +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionLifecycleDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionLifecycleDatabaseTest.java new file mode 100644 index 0000000..453ec54 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProductionLifecycleDatabaseTest.java @@ -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 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 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 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 row,String key){return new BigDecimal(String.valueOf(row.get(key)));} +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectDatabaseGuardTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectDatabaseGuardTest.java new file mode 100644 index 0000000..4c13dfc --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectDatabaseGuardTest.java @@ -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(); } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java new file mode 100644 index 0000000..4abdd26 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoanDatabaseTest.java @@ -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 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 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();} + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java new file mode 100644 index 0000000..16e014b --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectPurchaseDatabaseTest.java @@ -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)); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchNumberTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchNumberTest.java new file mode 100644 index 0000000..fd89f85 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchNumberTest.java @@ -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}"))); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchSupplierTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchSupplierTest.java new file mode 100644 index 0000000..a40e90e --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseBatchSupplierTest.java @@ -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);} + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchasePriceRulesTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchasePriceRulesTest.java new file mode 100644 index 0000000..7033ce8 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchasePriceRulesTest.java @@ -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"))); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchasePriceServiceTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchasePriceServiceTest.java new file mode 100644 index 0000000..e4769bd --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchasePriceServiceTest.java @@ -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()); + } + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java new file mode 100644 index 0000000..3904e66 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/PurchaseSheetDatabaseTest.java @@ -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 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 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));} +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WarehouseAreaSafetyTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WarehouseAreaSafetyTest.java new file mode 100644 index 0000000..ed4f783 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WarehouseAreaSafetyTest.java @@ -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)); + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java new file mode 100644 index 0000000..6fd65f2 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/projectdev/WebNavigationDatabaseTest.java @@ -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(); + 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();var names=new HashSet();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 routes,String parent,Map pages,Set 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);} + } +} diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierPurchaseExportTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierPurchaseExportTest.java new file mode 100644 index 0000000..3493ba8 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/warehouse/SupplierPurchaseExportTest.java @@ -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()); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/NamespacedRedisKeySerializer.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/NamespacedRedisKeySerializer.java new file mode 100644 index 0000000..2d4f7af --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/NamespacedRedisKeySerializer.java @@ -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()); + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ProjectDatabaseGuard.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ProjectDatabaseGuard.java new file mode 100644 index 0000000..c229c77 --- /dev/null +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ProjectDatabaseGuard.java @@ -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("数据库连接不能包含会话初始化或多语句执行参数。"); + } + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java index 3453237..64cc14c 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java @@ -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 redisTemplate(RedisConnectionFactory connectionFactory) { + if(connectionFactory instanceof org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory lettuce) + lettuce.setValidateConnection(true); RedisTemplate 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的序列化方式 diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/domain/BomLine.java b/ruoyi-system/src/main/java/com/ruoyi/production/domain/BomLine.java new file mode 100644 index 0000000..fdaec5d --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/domain/BomLine.java @@ -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; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/domain/BomVersion.java b/ruoyi-system/src/main/java/com/ruoyi/production/domain/BomVersion.java new file mode 100644 index 0000000..c741453 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/domain/BomVersion.java @@ -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 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 getLines() { return lines; } + public void setLines(java.util.List value) { lines = value; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProductionCommand.java b/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProductionCommand.java new file mode 100644 index 0000000..81052f0 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProductionCommand.java @@ -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; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProductionProduct.java b/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProductionProduct.java new file mode 100644 index 0000000..10c1cd7 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProductionProduct.java @@ -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; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProjectProduct.java b/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProjectProduct.java new file mode 100644 index 0000000..32b080b --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/domain/ProjectProduct.java @@ -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; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/mapper/BomMapper.java b/ruoyi-system/src/main/java/com/ruoyi/production/mapper/BomMapper.java new file mode 100644 index 0000000..afff6dc --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/mapper/BomMapper.java @@ -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 selectPublicVersions(@Param("itemId") Long itemId, @Param("keyword") String keyword); + BomVersion selectVersion(Long id); + BomVersion selectDefault(Long itemId); + List selectGraphVersions(); + List selectGraphLines(); + List 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> selectLogs(Long id); + List 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 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); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/service/BomService.java b/ruoyi-system/src/main/java/com/ruoyi/production/service/BomService.java new file mode 100644 index 0000000..dc6d835 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/service/BomService.java @@ -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 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> 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 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 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 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 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 originals, Map 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 graph() { + Map 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("数据已被其他操作修改,请刷新后重试"); } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java b/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java new file mode 100644 index 0000000..6285299 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/service/ProductionService.java @@ -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> 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> costHistory(Long itemId,Long bomId,Long projectId){ + var result=new ArrayList>(); + for(var row:tasks(projectId,itemId)){ + Long source=l(row,"source_bom_id");boolean matches=bomId==null,adjusted=false;var visited=new HashSet(); + 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 r)->Objects.toString(r.get("settled_time"),"")).reversed());return result; + } + public Map 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> 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 action(Long id){var rows=db.queryForList(ACTION_SELECT+" where a.id=?",id);if(rows.isEmpty())throw fail("业务记录不存在");return rows.get(0);} + public Map 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 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> needs(Long id){var t=task(id);List> 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();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 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 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 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 settle(Long id){return settle(id,null);} + @Transactional public Map 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 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 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;passn(o,"quantity")).reduce(ZERO,BigDecimal::add),allocated=ZERO; + for(int x=0;x 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 reference(Long bomId,Long projectId,Long taskId,Set path){if(!path.add(bomId))throw fail("BOM存在循环");var bom=boms.get(bomId);var lines=new ArrayList>();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();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();result.put("amount",total);result.put("complete",complete);result.put("lines",lines);return result; + } + public Map overview(Long projectId){ + projects.requireProjectAccess(projectId);var result=new LinkedHashMap(); + 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 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 row,String key){Object v=row.get(key);return v==null?null:new BigDecimal(v.toString());} + private static BigDecimal n(Map row,String key){BigDecimal n=nullable(row,key);return n==null?ZERO:n;} + private static boolean active(Map 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);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/production/util/BomGraphRules.java b/ruoyi-system/src/main/java/com/ruoyi/production/util/BomGraphRules.java new file mode 100644 index 0000000..cbd66e8 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/production/util/BomGraphRules.java @@ -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 versions) { + walk(root, versions, new LinkedHashSet<>(), new LinkedHashSet<>()); + } + private static void walk(BomVersion bom, Map versions, Set pathVersions, Set 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.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()); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectInfo.java b/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectInfo.java index f093782..c913f5b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectInfo.java +++ b/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectInfo.java @@ -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 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 getMemberIds() { return memberIds; } - public void setMemberIds(List 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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectLoan.java b/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectLoan.java new file mode 100644 index 0000000..b767825 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/project/domain/ProjectLoan.java @@ -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;} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectBudgetMapper.java b/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectBudgetMapper.java index af5d351..54fbd83 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectBudgetMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectBudgetMapper.java @@ -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 selectExpenseCategoryList(ExpenseCategory category); ExpenseCategory selectExpenseCategoryById(Long id); diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectInfoMapper.java b/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectInfoMapper.java index e7334cd..5628902 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectInfoMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectInfoMapper.java @@ -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 selectProjectMemberIds(Long projectId); - - int countProjectAccess(@Param("projectId") Long projectId, @Param("userId") Long userId); - Long selectLegacyProjectId(); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectLoanMapper.java b/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectLoanMapper.java new file mode 100644 index 0000000..ee4bd36 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/project/mapper/ProjectLoanMapper.java @@ -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 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 returnByKey(String key); + List> returns(Long loanId); + int deactivateReturn(Long inId); + Long returnLoanForEvent(Long inId); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/service/ProjectLoanService.java b/ruoyi-system/src/main/java/com/ruoyi/project/service/ProjectLoanService.java new file mode 100644 index 0000000..792b43f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/project/service/ProjectLoanService.java @@ -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 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> 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 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 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);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectBudgetServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectBudgetServiceImpl.java index fe9f5e4..c705602 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectBudgetServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectBudgetServiceImpl.java @@ -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 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 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; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectInfoServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectInfoServiceImpl.java index 2fb1f0b..bc09cca 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectInfoServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/project/service/impl/ProjectInfoServiceImpl.java @@ -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 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"); - } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java index b1d0c73..f9e1f65 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InRecord.java @@ -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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InventoryCostEvent.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InventoryCostEvent.java new file mode 100644 index 0000000..5a9eec2 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InventoryCostEvent.java @@ -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; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InventoryCostRevision.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InventoryCostRevision.java new file mode 100644 index 0000000..5c8e04f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/InventoryCostRevision.java @@ -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; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/OutRecord.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/OutRecord.java index c97588e..65db78e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/OutRecord.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/OutRecord.java @@ -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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java index 8c9f774..f51ec5b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProductInfo.java @@ -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 = "产品名称") diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProjectItemCost.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProjectItemCost.java new file mode 100644 index 0000000..3a54e9a --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/ProjectItemCost.java @@ -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; } +} + diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrival.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrival.java index 0dcb408..b0b7adb 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrival.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrival.java @@ -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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrivalAcceptanceRequest.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrivalAcceptanceRequest.java index 991a425..d0e6882 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrivalAcceptanceRequest.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseArrivalAcceptanceRequest.java @@ -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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java index 128b7e7..4c46cf1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseBatch.java @@ -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; diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java index a12c56d..b3d14be 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseRequest.java @@ -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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java new file mode 100644 index 0000000..3c63d08 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/PurchaseSheet.java @@ -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 rows; + private List deletedIds; + private String version; + public PurchaseBatch getBatch() { return batch; } + public void setBatch(PurchaseBatch value) { batch = value; } + public List getRows() { return rows; } + public void setRows(List value) { rows = value; } + public List getDeletedIds() { return deletedIds; } + public void setDeletedIds(List value) { deletedIds = value; } + public String getVersion() { return version; } + public void setVersion(String value) { version = value; } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockCheckRecord.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockCheckRecord.java index 2346a15..cd8de25 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockCheckRecord.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockCheckRecord.java @@ -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; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java index 648260f..5cb4842 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/StockInfo.java @@ -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; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/WarehouseArea.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/WarehouseArea.java index a76b20f..0786c0a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/WarehouseArea.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/WarehouseArea.java @@ -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() { diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/agent/AgentResultItem.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/agent/AgentResultItem.java index 07a8324..602ba52 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/agent/AgentResultItem.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/domain/agent/AgentResultItem.java @@ -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; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InRecordMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InRecordMapper.java index bf54096..a5fc9d8 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InRecordMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InRecordMapper.java @@ -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 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); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InventoryCostMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InventoryCostMapper.java new file mode 100644 index 0000000..559c570 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/InventoryCostMapper.java @@ -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 selectLinkedTargets(Long sourceId); + java.util.List 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 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 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); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/OutRecordMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/OutRecordMapper.java index 3131a47..f5f11b7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/OutRecordMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/OutRecordMapper.java @@ -5,6 +5,7 @@ import com.ruoyi.warehouse.domain.OutRecord; public interface OutRecordMapper { + int revoke(Long id); public List selectOutRecordList(OutRecord outRecord); public OutRecord selectOutRecordById(Long id); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java index afdd66d..998eae3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/ProductInfoMapper.java @@ -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); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseRequestMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseRequestMapper.java index d98d6bc..366ba49 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseRequestMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/PurchaseRequestMapper.java @@ -7,6 +7,7 @@ import com.ruoyi.warehouse.domain.PurchaseTaskSummary; public interface PurchaseRequestMapper { + List selectPurchaseSheetRows(Long batchId); List 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); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockCheckRecordMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockCheckRecordMapper.java index 72ec34c..d9905b9 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockCheckRecordMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockCheckRecordMapper.java @@ -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); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockLotMapper.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockLotMapper.java index 4282fb5..0a8d0c6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockLotMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/mapper/StockLotMapper.java @@ -13,6 +13,10 @@ public interface StockLotMapper @Param("productId") Long productId); StockLot selectStockLotByInRecordId(Long inRecordId); + StockLot selectStockLotByInRecordIdForUpdate(Long inRecordId); + int countOutReferences(Long stockLotId); + int revokeInboundLot(@Param("id") Long id, @Param("username") String username); + int reactivateInboundLot(StockLot lot); int insertStockLot(StockLot lot); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IInRecordService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IInRecordService.java index 0471f55..1f535cf 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IInRecordService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IInRecordService.java @@ -12,4 +12,8 @@ public interface IInRecordService public int updateInRecord(InRecord inRecord); public int deleteInRecordByIds(Long[] ids); public int confirmInRecord(Long id, String username); + int receive(Long id,Long areaId,java.math.BigDecimal quantity,String key,String username); + int receive(Long id,Long areaId,java.math.BigDecimal quantity,String key,String username,java.time.LocalDate date,String remark); + public int revokeInRecord(Long id, String reason, String username); + int withdraw(Long id,java.math.BigDecimal quantity,String reason,String key,String username); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IOutRecordService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IOutRecordService.java index a010ea0..7b0aea1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IOutRecordService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IOutRecordService.java @@ -9,4 +9,8 @@ public interface IOutRecordService public OutRecord selectOutRecordById(Long id); public boolean checkOutNoUnique(OutRecord outRecord); public int insertOutRecord(OutRecord outRecord); + int revoke(Long id,String reason); + java.util.List returns(Long id); + void revokeReturn(Long id,Long eventId,String reason); + com.ruoyi.warehouse.domain.InventoryCostEvent returnMaterial(Long id,Long areaId,java.math.BigDecimal quantity,String key); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IProductInfoService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IProductInfoService.java index 53ef7f2..cdcc2f6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IProductInfoService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IProductInfoService.java @@ -15,4 +15,6 @@ public interface IProductInfoService public int insertProductInfo(ProductInfo productInfo); public int updateProductInfo(ProductInfo productInfo); public int deleteProductInfoByIds(Long[] ids); + List> previewImport(List rows); + String importNew(List rows); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseRequestService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseRequestService.java index 6acd3d9..e0b6b83 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseRequestService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IPurchaseRequestService.java @@ -14,6 +14,8 @@ public interface IPurchaseRequestService int updatePurchaseRequest(PurchaseRequest purchaseRequest); int deletePurchaseRequestByIds(Long[] ids); int updatePurchaseStatus(Long id, PurchaseStatusUpdateRequest request); + int cancelRemaining(Long id,java.math.BigDecimal expectedQuantity,String reason); int batchInsertPurchaseRequest(List requestList); String importPurchaseRequest(List requestList, String username); + List> previewImport(List rows); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IStockCheckRecordService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IStockCheckRecordService.java index 2f0628d..588471d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IStockCheckRecordService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/IStockCheckRecordService.java @@ -12,4 +12,5 @@ public interface IStockCheckRecordService public int updateStockCheckRecord(StockCheckRecord stockCheckRecord); public int deleteStockCheckRecordByIds(Long[] ids); public int confirmStockCheckRecord(Long id, String username); + int revoke(Long id,String reason); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/AgentServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/AgentServiceImpl.java index a3ca79f..77d1186 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/AgentServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/AgentServiceImpl.java @@ -73,7 +73,7 @@ public class AgentServiceImpl implements IAgentService private static final String ACTION_CREATE_AREA = "create_area"; private static final String ACTION_UNKNOWN = "unknown"; - private static final Pattern IN_NO_PATTERN = Pattern.compile("(IN\\d+)", Pattern.CASE_INSENSITIVE); + private static final Pattern IN_NO_PATTERN = Pattern.compile("((?:RK\\d{10,}|IN\\d+|RIN-[0-9a-f-]+|FIN-\\d+|AIN\\d+))", Pattern.CASE_INSENSITIVE); private static final Pattern INDEX_PATTERN = Pattern.compile("第\\s*([0-9一二两三四五六七八九十]+)\\s*(个|条|项)?"); private static final Pattern REFERENCE_PATTERN = Pattern.compile("上一个|上一条|刚才(?:的)?(?:那个|那条|那项)|刚刚(?:的)?(?:那个|那条|那项)|这个|那个|它|上述|上面(?:的)?"); private static final Pattern QUANTITY_WITH_UNIT_PATTERN = Pattern.compile("([0-9]+(?:\\.[0-9]+)?)\\s*(个|件|箱|支|台|套|包|卷|瓶|袋|张|本)"); @@ -434,7 +434,7 @@ public class AgentServiceImpl implements IAgentService } if (ACTION_CREATE_OUT.equals(plan.getAction()) && plan.getOutType() == null) { - plan.setOutType(1); + plan.setOutType(4); plan.getWarnings().add("未识别出库类型,默认生产出库"); } @@ -750,7 +750,7 @@ public class AgentServiceImpl implements IAgentService + "quantity 只表示本次入库、出库或盘点的数量,规格型号里的数字不算数量,‘一个’表示数量 1。" + "类似‘2进6出’、‘8口’的描述优先放入 spec,不要把人员姓名、‘东西’、‘产品’放入 productName。" + "入库类型 inType:1生产入库,2采购入库,3归还入库,4退货入库。" - + "出库类型 outType:1生产出库,2退货出库,3销售出库。" + + "直接出库 outType:4项目领用。生产领料、采购退货、成品交付需引导用户从对应业务页面办理,不创建普通出库。" + "新增产品时尽量从用户输入提取 productName, brand, category, spec, unit;如果用户未提供 category,优先从 existingCategories 选择合适类别,不合适时推断一个简短合理的类别。" + "除 category 可按规则推断外,不要编造其他字段;无法识别就填 null。新增库区提取 areaName。"; } @@ -872,10 +872,6 @@ public class AgentServiceImpl implements IAgentService item.setAcceptedQuantity(request.getAcceptedQuantity()); item.setPendingArrivalQuantity(request.getPendingArrivalQuantity()); item.setEstimatedAmount(request.getEstimatedAmount()); - if (request.getExpectedDate() != null) - { - item.setExpectedDate(DateUtils.parseDateToStr("yyyy-MM-dd", request.getExpectedDate())); - } plan.getResults().add(item); } } @@ -1193,7 +1189,8 @@ public class AgentServiceImpl implements IAgentService { return 2; } - return text.contains("出库") ? 3 : null; + if (text.contains("销售") || text.contains("交付")) return 3; + return text.contains("出库") || text.contains("领用") ? 4 : null; } private void resolveArea(AgentPlan plan, String originalText, boolean required) diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/BusinessNumberService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/BusinessNumberService.java new file mode 100644 index 0000000..ef697d7 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/BusinessNumberService.java @@ -0,0 +1,74 @@ +package com.ruoyi.warehouse.service.impl; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.*; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.warehouse.util.WarehouseNoUtils; + +/** Number allocation commits independently: retries reuse reservations, cancelled saves never reuse a code. */ +@Service +public class BusinessNumberService { + @Autowired private JdbcTemplate jdbc; + public enum Kind { + PROJECT("XM","project_info","project_code","PROJ"), ITEM("WP","product_info","product_code","ITEM"), + PURCHASE_BATCH("CG","purchase_batch","batch_no","CG"), PURCHASE_REQUEST("SQ","purchase_request","request_no","PR"), + ARRIVAL("DH","purchase_arrival","arrival_no","PA"), INBOUND("RK","in_record","in_no","IN"), + OUTBOUND("CK","out_record","out_no","OUT"), STOCK_CHECK("PD","stock_check_record","check_no","CHK"), + PRODUCTION("SC","production_task","task_no","TASK"), LOAN("JY","project_loan","loan_no","LOAN"), + FUND_LEDGER("FY","project_fund_ledger","ledger_no","FUND"), STOCK_LOT("KC","stock_lot","lot_no","LOT"), + STOCK_ADJUSTMENT("TZ","stock_lot","lot_no","ADJ"), IMPORT_JOB("DR","wms_batch_job","job_no","BATCH"), + AREA("KQ","warehouse_area","area_code","AREA"), + INVENTORY_EVENT("LS","inventory_cost_event","event_no","EVENT"), + COST_REVISION("CZ","inventory_cost_revision","revision_no","REVISION"); + public final String prefix; final String table,column,alias; + Kind(String prefix,String table,String column,String alias){this.prefix=prefix;this.table=table;this.column=column;this.alias=alias;} + static Kind find(String prefix){return Arrays.stream(values()).filter(k->k.prefix.equals(prefix)||k.alias.equals(prefix)).findFirst().orElseThrow(()->new ServiceException("未知业务编码类型"));} + } + @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED) + public String next(String kind){return allocate(Kind.find(kind),LocalDate.now(),null);} + @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED) + public String next(String kind,LocalDate date){return allocate(Kind.find(kind),date,null);} + @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED) + public String reserve(String kind,LocalDate date,String requestKey){return allocate(Kind.find(kind),date,requestKey);} + private String allocate(Kind kind,LocalDate date,String requestKey){ + date=date==null?LocalDate.now():date; + if(date.getYear()<1||date.getYear()>9999)throw new ServiceException("业务日期年份须为四位"); + String hash=null; + if(requestKey!=null){ + if(requestKey.isBlank()||requestKey.length()>500)throw new ServiceException("编号防重复标识无效"); + try{hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(requestKey.getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);} + String existing=reserved(kind.prefix,hash);if(existing!=null)return existing; + } + String month=date.format(DateTimeFormatter.ofPattern("yyyyMM")),base=kind.prefix+month; + // Seed once from existing matching codes, without rewriting or locking business records. + var existingCounter=jdbc.queryForList("select serial_value from business_number_sequence where prefix=? and period=? for update",Long.class,kind.prefix,month); + if(existingCounter.isEmpty()){ + String records=kind==Kind.FUND_LEDGER + ? "(select ledger_no from project_fund_ledger union all select new_ledger_no from purchase_price_ledger union all select old_ledger_no from purchase_price_ledger) numbered" + : kind.table; + Long seed=jdbc.queryForObject("select coalesce(max(cast(substring("+kind.column+",?) as unsigned)),0) from "+records+" where "+kind.column+" regexp ?",Long.class,base.length()+1,"^"+base+"[0-9]{4,}$"); + // A duplicate UPDATE takes an exclusive lock. INSERT IGNORE would leave shared + // locks on a concurrently created row and deadlock when both callers upgrade. + jdbc.update("insert into business_number_sequence(prefix,period,serial_value) values(?,?,?) on duplicate key update serial_value=business_number_sequence.serial_value",kind.prefix,month,seed==null?0L:seed); + } + Long last=jdbc.queryForObject("select serial_value from business_number_sequence where prefix=? and period=? for update",Long.class,kind.prefix,month); + if(hash!=null){String existing=reserved(kind.prefix,hash);if(existing!=null)return existing;} + long value=Math.addExact(Objects.requireNonNull(last),1); + String number=WarehouseNoUtils.format(kind.prefix,date,value); + jdbc.update("update business_number_sequence set serial_value=? where prefix=? and period=?",value,kind.prefix,month); + if(hash!=null){ + try{jdbc.update("insert into business_number_reservation(prefix,request_hash,business_no) values(?,?,?)",kind.prefix,hash,number);} + catch(DuplicateKeyException e){String existing=reserved(kind.prefix,hash);if(existing==null)throw e;return existing;} + } + return number; + } + private String reserved(String prefix,String hash){var rows=jdbc.queryForList("select business_no from business_number_reservation where prefix=? and request_hash=?",String.class,prefix,hash);return rows.isEmpty()?null:rows.get(0);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/BusinessWithdrawalService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/BusinessWithdrawalService.java new file mode 100644 index 0000000..1ccb1d0 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/BusinessWithdrawalService.java @@ -0,0 +1,46 @@ +package com.ruoyi.warehouse.service.impl; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +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.ProductionCommand; +import com.ruoyi.production.service.ProductionService; +import com.ruoyi.warehouse.domain.OutRecord; +import com.ruoyi.warehouse.service.IOutRecordService; + +/** Partial corrections retain the original voided record and explicitly link its retained remainder. */ +@Service public class BusinessWithdrawalService { + @Autowired private JdbcTemplate db; + @Autowired private InventoryCostJournal journal; + @Autowired private ProductionService production; + @Autowired private IOutRecordService outbound; + public record Request(String type,Long id,BigDecimal quantity,String key,String reason){} + @Transactional public Map withdraw(Request r){ + journal.lockInventory(); + if(!Set.of("PRODUCTION","OUT").contains(Objects.toString(r.type(),""))||r.id()==null)throw fail("请选择原业务记录"); + if(r.quantity()==null||r.quantity().signum()<=0||r.quantity().stripTrailingZeros().scale()>4)throw fail("撤销数量必须大于0,最多4位小数"); + if(r.key()==null||r.key().isBlank()||r.key().length()>100||r.reason()==null||r.reason().isBlank()||r.reason().length()>300)throw fail("请填写撤销原因并使用有效操作标识"); + var previous=db.queryForList("select * from business_withdrawal where business_key=?",r.key()); + if(!previous.isEmpty()){var p=previous.get(0);if(!r.type().equals(p.get("business_type"))||!r.id().equals(number(p,"source_id"))||r.quantity().compareTo((BigDecimal)p.get("quantity"))!=0)throw fail("重复撤销内容不一致");return p;} + Long remainder=null;String remainderKey="WITHDRAW:"+UUID.nameUUIDFromBytes(r.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + if("OUT".equals(r.type())){ + OutRecord source=outbound.selectOutRecordById(r.id());if(source==null||!Boolean.TRUE.equals(source.getActive()))throw fail("出库记录不存在或已撤销"); + BigDecimal keep=remaining(source.getOutNum(),r.quantity());outbound.revoke(r.id(),r.reason()); + if(keep.signum()>0){var next=new OutRecord();org.springframework.beans.BeanUtils.copyProperties(source,next);next.setId(null);next.setCostEventId(null);next.setOutNo("BOUT-"+remainderKey);next.setOutNum(keep);outbound.insertOutRecord(next);remainder=next.getId();} + }else{ + var found=db.queryForList("select * from production_action where id=?",r.id());if(found.isEmpty())throw fail("业务记录不存在");var source=found.get(0);if(((Number)source.get("active")).intValue()!=1)throw fail("记录已撤销");if("OUTPUT".equals(source.get("kind")))throw fail("生产入库请从入库记录撤销"); + BigDecimal keep=remaining((BigDecimal)source.get("quantity"),r.quantity());production.revoke(r.id(),r.reason()); + if(keep.signum()>0){var next=new ProductionCommand();next.kind=(String)source.get("kind");next.projectId=number(source,"project_id");next.itemId=number(source,"item_id");next.taskId=number(source,"task_id");next.sourceId=number(source,"source_id");next.areaId=number(source,"area_id");next.quantity=keep;next.key=remainderKey;next.reason=(String)source.get("reason");next.remark=(String)source.get("remark");next.recipient=(String)source.get("recipient");Object date=source.get("business_date");next.date=date==null?LocalDate.now():LocalDate.parse(date.toString());remainder=number(production.perform(next),"id");} + } + db.update("insert into business_withdrawal(business_key,business_type,source_id,quantity,remaining_id,reason,create_by) values(?,?,?,?,?,?,?)",r.key(),r.type(),r.id(),r.quantity(),remainder,r.reason(),SecurityUtils.getUsername()); + return db.queryForMap("select * from business_withdrawal where business_key=?",r.key()); + } + private BigDecimal remaining(BigDecimal quantity,BigDecimal withdrawn){if(withdrawn.compareTo(quantity)>0)throw fail("撤销数量不能超过当前有效数量");return quantity.subtract(withdrawn);} + private Long number(Map row,String key){Object value=row.get(key);return value==null?null:((Number)value).longValue();} + private ServiceException fail(String message){return new ServiceException(message);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/CatalogWriteLock.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/CatalogWriteLock.java new file mode 100644 index 0000000..03e3389 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/CatalogWriteLock.java @@ -0,0 +1,32 @@ +package com.ruoyi.warehouse.service.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import com.ruoyi.common.exception.ServiceException; + +/** Serializes catalog resolution through commit, including saves on different batches. */ +@Component +public class CatalogWriteLock +{ + private static final String KEY = "cmvr-project-dev:catalog-write"; + @Autowired private JdbcTemplate jdbc; + + public void acquire() + { + if (!TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Catalog writes require a transaction"); + if (TransactionSynchronizationManager.hasResource(KEY)) return; + Integer result = jdbc.queryForObject("select get_lock(?, 10)", Integer.class, KEY); + if (!Integer.valueOf(1).equals(result)) throw new ServiceException("物品正在保存,请稍后重试"); + TransactionSynchronizationManager.bindResource(KEY, Boolean.TRUE); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override public void afterCompletion(int status) { + try { jdbc.queryForObject("select release_lock(?)", Integer.class, KEY); } + finally { TransactionSynchronizationManager.unbindResourceIfPossible(KEY); } + } + }); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InRecordServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InRecordServiceImpl.java index 3f9ec1c..199c90f 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InRecordServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InRecordServiceImpl.java @@ -21,11 +21,11 @@ import com.ruoyi.warehouse.util.WarehouseNoUtils; @Service public class InRecordServiceImpl implements IInRecordService { + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private InRecordMapper inRecordMapper; - @Autowired - private StockInfoMapper stockInfoMapper; + @Autowired private InventoryCostJournal journal; @Autowired private IProjectInfoService projectInfoService; @@ -34,7 +34,11 @@ public class InRecordServiceImpl implements IInRecordService private ProjectBudgetMapper projectBudgetMapper; @Autowired - private IStockLotService stockLotService; + private com.ruoyi.warehouse.mapper.PurchaseRequestMapper purchaseRequestMapper; + @Autowired + private com.ruoyi.warehouse.service.IPurchaseOperationLogService purchaseOperationLogService; + @Autowired private com.ruoyi.project.service.ProjectLoanService loans; + @Autowired private com.ruoyi.production.service.ProductionService production; @Override public List selectInRecordList(InRecord inRecord) @@ -59,37 +63,41 @@ public class InRecordServiceImpl implements IInRecordService @Override public int insertInRecord(InRecord inRecord) { - inRecord.setInOperator(StringUtils.trim(inRecord.getInOperator())); - requireManualSourceProject(inRecord); - validateInRecord(inRecord); - if (StringUtils.isBlank(inRecord.getInNo())) - { - inRecord.setInNo(WarehouseNoUtils.next("IN")); - } - else if (!checkInNoUnique(inRecord)) - { - throw new ServiceException("入库单号已存在"); - } - inRecord.setInStatus(0); - return inRecordMapper.insertInRecord(inRecord); - } - - @Override - public int updateInRecord(InRecord inRecord) - { - inRecord.setInOperator(StringUtils.trim(inRecord.getInOperator())); + if (inRecord.getArrivalId()!=null || inRecord.getPurchaseRequestId()!=null || inRecord.getParentInId()!=null || Boolean.TRUE.equals(inRecord.getReceiptRoot()) || inRecord.getProductionTaskId()!=null || inRecord.getCompletionId()!=null) + throw new ServiceException("采购待入库和分次入库记录由系统生成,不能手工关联采购来源"); + inRecord.setReceiptRoot(false); + inRecord.setParentInId(null); + inRecord.setCostEventId(null); + inRecord.setCostRevision(0); + inRecord.setInOperator(com.ruoyi.common.utils.SecurityUtils.getUsername()); requireManualSourceProject(inRecord); validateInRecord(inRecord); if (StringUtils.isNotBlank(inRecord.getInNo()) && !checkInNoUnique(inRecord)) { throw new ServiceException("入库单号已存在"); } - InRecord dbRecord = inRecordMapper.selectInRecordById(inRecord.getId()); + inRecord.setInNo(businessNumbers.reserve("IN",inRecord.getBusinessDate(),StringUtils.isBlank(inRecord.getInNo())?null:"manual:"+inRecord.getInNo())); + if(!checkInNoUnique(inRecord))throw new ServiceException("该入库已提交,请刷新记录"); + inRecord.setInStatus(0); + return inRecordMapper.insertInRecord(inRecord); + } + + @Override + @Transactional public int updateInRecord(InRecord inRecord) + { + journal.lockInventory(); + inRecord.setInOperator(com.ruoyi.common.utils.SecurityUtils.getUsername()); + if (StringUtils.isNotBlank(inRecord.getInNo()) && !checkInNoUnique(inRecord)) + { + throw new ServiceException("入库单号已存在"); + } + InRecord dbRecord = lockRecordAfterPurchase(inRecord.getId()); + if (dbRecord.getParentInId()!=null) throw new ServiceException("分次入库记录不能直接修改,请先撤销该次入库"); if (dbRecord != null && Integer.valueOf(1).equals(dbRecord.getInStatus())) { throw new ServiceException("已入库记录不能修改"); } - if (dbRecord != null && dbRecord.getArrivalId() != null) + if (dbRecord != null && (dbRecord.getArrivalId() != null || dbRecord.getProductionTaskId()!=null)) { inRecord.setInNo(dbRecord.getInNo()); inRecord.setProductId(dbRecord.getProductId()); @@ -101,20 +109,25 @@ public class InRecordServiceImpl implements IInRecordService inRecord.setInType(dbRecord.getInType()); inRecord.setInNum(dbRecord.getInNum()); } + inRecord.setPurchaseRequestId(dbRecord.getPurchaseRequestId()); + inRecord.setArrivalId(dbRecord.getArrivalId()); + requireManualSourceProject(inRecord); + validateInRecord(inRecord); return inRecordMapper.updateInRecord(inRecord); } @Override - public int deleteInRecordByIds(Long[] ids) + @Transactional public int deleteInRecordByIds(Long[] ids) { + journal.lockInventory(); for (Long id : ids) { - InRecord dbRecord = inRecordMapper.selectInRecordById(id); + InRecord dbRecord = lockRecordAfterPurchase(id); if (dbRecord != null && Integer.valueOf(1).equals(dbRecord.getInStatus())) { throw new ServiceException("已入库记录不能删除"); } - if (dbRecord != null && dbRecord.getArrivalId() != null) + if (dbRecord != null && (dbRecord.getArrivalId() != null || dbRecord.getParentInId()!=null || dbRecord.getCostEventId()!=null || dbRecord.getProductionTaskId()!=null)) { throw new ServiceException("采购验收生成的待入库记录不能删除"); } @@ -126,15 +139,34 @@ public class InRecordServiceImpl implements IInRecordService @Transactional public int confirmInRecord(Long id, String username) { - InRecord inRecord = inRecordMapper.selectInRecordByIdForUpdate(id); + journal.lockInventory(); + InRecord inRecord = lockRecordAfterPurchase(id); + if (Boolean.TRUE.equals(inRecord.getReceiptRoot())) + return receive(id,inRecord.getAreaId(),inRecord.getInNum().subtract(inRecordMapper.receivedQuantity(id)),java.util.UUID.randomUUID().toString(),username); if (inRecord == null) { throw new ServiceException("入库记录不存在"); } - if (Integer.valueOf(1).equals(inRecord.getInStatus())) + if (!Integer.valueOf(0).equals(inRecord.getInStatus())) { throw new ServiceException("该入库记录已确认"); } + if (StringUtils.isBlank(inRecord.getInOperator())) inRecord.setInOperator(username); + if (inRecord.getPurchaseRequestId() != null) + { + com.ruoyi.warehouse.domain.PurchaseRequest purchase = purchaseRequestMapper + .selectPurchaseRequestByIdForUpdate(inRecord.getPurchaseRequestId()); + if (purchase == null || !Boolean.TRUE.equals(purchase.getPriceLocked()) + || purchase.getFinalUnitPrice() == null || Integer.valueOf(5).equals(purchase.getPurchaseStatus())) + throw new ServiceException("请先填写最终价格并锁价,再确认采购入库"); + if (purchase.getProductId()!=null && !java.util.Objects.equals(purchase.getProductId(),inRecord.getProductId())) + throw new ServiceException("入库物品与采购明细不一致,请刷新后重试"); + inRecord.setSourceProjectId("REPAY".equals(purchase.getPurchasePurpose()) + ? loans.validatePurchase(purchase.getLoanId(),purchase.getProjectId(),inRecord.getProductId()).getLenderProjectId() : purchase.getProjectId()); + inRecord.setExpenseCategoryId(purchase.getExpenseCategoryId()); + inRecord.setReceiptUnitCost(purchase.getFinalUnitPrice()); + } + if (inRecord.getProductionTaskId()!=null) inRecord.setReceiptUnitCost(production.receiptUnit(inRecord.getProductionTaskId())); validateInRecord(inRecord); if (inRecord.getAreaId() == null) { @@ -144,26 +176,123 @@ public class InRecordServiceImpl implements IInRecordService { throw new ServiceException("入库产品不能为空"); } - stockInfoMapper.upsertIncreaseStock(inRecord.getAreaId(), inRecord.getProductId(), inRecord.getInNum()); + projectInfoService.requireProjectAccess(inRecord.getSourceProjectId()); + var cost = journal.append(InventoryCostJournal.details(InventoryCostJournal.event(inRecord.getSourceProjectId(),inRecord.getProductId(),inRecord.getAreaId(),"RECEIPT", + inRecord.getInNum(),com.ruoyi.warehouse.util.MovingAverageCost.receiptAmount(inRecord.getInNum(),inRecord.getReceiptUnitCost()),null, + "IN:"+id+":"+(inRecord.getCostRevision()==null ? 1 : inRecord.getCostRevision()+1)),inRecord.getBusinessDate(),inRecord.getRemark())); + if (inRecord.getPurchaseRequestId()!=null) { + var purchase=purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(inRecord.getPurchaseRequestId()); + if ("REPAY".equals(purchase.getPurchasePurpose())) loans.purchaseReceived(purchase.getLoanId(),purchase.getProjectId(),inRecord.getProductId(),cost); + } + if (inRecord.getProductionTaskId()!=null) production.received(inRecord,cost); InRecord confirmRecord = new InRecord(); confirmRecord.setId(id); confirmRecord.setInStatus(1); confirmRecord.setOperator(username); confirmRecord.setConfirmTime(new Date()); + confirmRecord.setSourceProjectId(inRecord.getSourceProjectId()); + confirmRecord.setExpenseCategoryId(inRecord.getExpenseCategoryId()); + confirmRecord.setCostEventId(cost.getId()); + confirmRecord.setReceiptUnitCost(inRecord.getReceiptUnitCost()); int rows = inRecordMapper.confirmInRecord(confirmRecord); if (rows != 1) { throw new ServiceException("入库记录状态已变化,请刷新后重试"); } - stockLotService.createInboundLot(inRecord, username); + recordPurchaseOperation(inRecord, username, "INBOUND_CONFIRM", "确认采购入库", "库区:" + inRecord.getAreaId() + ";数量:" + inRecord.getInNum()); return rows; } + @Override @Transactional public int receive(Long id,Long areaId,java.math.BigDecimal quantity,String key,String username) { + return receive(id,areaId,quantity,key,username,null,null); + } + @Override @Transactional public int receive(Long id,Long areaId,java.math.BigDecimal quantity,String key,String username,java.time.LocalDate date,String remark) { + journal.lockInventory(); + if(remark!=null&&remark.length()>500)throw new ServiceException("备注最多500字"); + if (StringUtils.isBlank(key) || key.length()>100) throw new ServiceException("入库业务标识不能为空或超长"); + String no="RIN-"+java.util.UUID.nameUUIDFromBytes(key.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + InRecord root=lockRecordAfterPurchase(id),duplicate=inRecordMapper.checkInNoUnique(no); + if(duplicate==null){no=businessNumbers.reserve("IN",date,"receipt:"+key);duplicate=inRecordMapper.checkInNoUnique(no);} + if (!Boolean.TRUE.equals(root.getReceiptRoot())) throw new ServiceException("分次入库请选择采购或完工验收生成的待入库记录"); + if (duplicate!=null) { + if (!java.util.Objects.equals(duplicate.getParentInId(),id) || !java.util.Objects.equals(duplicate.getAreaId(),areaId) || quantity==null || duplicate.getInNum().compareTo(quantity)!=0 || !Integer.valueOf(1).equals(duplicate.getInStatus())) + throw new ServiceException("重复入库内容不一致或已撤销,请刷新后重试"); + return 1; + } + java.math.BigDecimal remaining=root.getInNum().subtract(inRecordMapper.receivedQuantity(id)); + if (!Integer.valueOf(0).equals(root.getInStatus()) || quantity==null || quantity.signum()<=0 || quantity.stripTrailingZeros().scale()>4 || quantity.compareTo(remaining)>0) + throw new ServiceException("入库数量必须大于0且不能超过待入库数量:"+remaining); + if (areaId==null) throw new ServiceException("请选择本次入库库区"); + InRecord child=new InRecord();org.springframework.beans.BeanUtils.copyProperties(root,child); + child.setId(null);child.setInNo(no);child.setParentInId(id);child.setReceiptRoot(false);child.setArrivalId(null);child.setAreaId(areaId);child.setInNum(quantity); + child.setInStatus(0);child.setCostEventId(null);child.setCostRevision(0);child.setInOperator(username);child.setOperator(username); + child.setBusinessDate(date==null?java.time.LocalDate.now():date); + if(remark!=null)child.setRemark(remark); + inRecordMapper.insertInRecord(child);confirmInRecord(child.getId(),username); + inRecordMapper.updateRootStatus(id,remaining.compareTo(quantity)==0 ? 1 : 0); + return 1; + } + + @Override + @Transactional + public int revokeInRecord(Long id, String reason, String username) + { + if (StringUtils.isBlank(reason) || reason.trim().length() > 300) + throw new ServiceException("请填写撤销原因,最多300字"); + journal.lockInventory(); + InRecord record = lockRecordAfterPurchase(id); + if (!Integer.valueOf(1).equals(record.getInStatus())) + throw new ServiceException("该记录不是已入库状态"); + if (record.getCostEventId()==null) throw new ServiceException("该历史入库的可用库存已转为期初,未补录历史成本链,不能自动撤销历史单据"); + journal.voidLastEvent(record.getCostEventId(),reason); + loans.revokePurchaseReceipt(record.getCostEventId()); + if(record.getProductionTaskId()!=null) production.receiptRevoked(record.getCostEventId()); + record.setOperator(username); + if (inRecordMapper.revokeInRecord(record) != 1) + throw new ServiceException("入库状态已变化,未撤销,请刷新后重试"); + if (record.getParentInId()!=null) inRecordMapper.updateRootStatus(record.getParentInId(),0); + recordPurchaseOperation(record, username, "INBOUND_REVOKE", "撤销入库至待入库", "数量:" + record.getInNum() + ";原因:" + reason.trim()); + // This changes inventory only. A locked purchase remains charged to the project. + return 1; + } + + private InRecord lockRecordAfterPurchase(Long id) + { + InRecord snapshot = inRecordMapper.selectInRecordById(id); + if (snapshot == null) throw new ServiceException("入库记录不存在"); + if (snapshot.getPurchaseRequestId() != null) + purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(snapshot.getPurchaseRequestId()); + InRecord locked = inRecordMapper.selectInRecordByIdForUpdate(id); + if (locked == null) throw new ServiceException("入库记录不存在"); + if (!java.util.Objects.equals(snapshot.getPurchaseRequestId(), locked.getPurchaseRequestId())) + throw new ServiceException("入库来源已变化,请刷新后重试"); + return locked; + } + + @Override @Transactional public int withdraw(Long id,java.math.BigDecimal quantity,String reason,String key,String username){ + journal.lockInventory();InRecord record=lockRecordAfterPurchase(id); + if(quantity==null||quantity.signum()<=0||quantity.stripTrailingZeros().scale()>4||quantity.compareTo(record.getInNum())>0) + throw new ServiceException("撤销数量必须大于0且不超过本次入库数量"); + if(record.getParentInId()==null&&quantity.compareTo(record.getInNum())!=0)throw new ServiceException("期初或历史入库请整条撤销后重新录入"); + int result=revokeInRecord(id,reason,username); + java.math.BigDecimal keep=record.getInNum().subtract(quantity); + if(keep.signum()>0)receive(record.getParentInId(),record.getAreaId(),keep,key,username,record.getBusinessDate(),record.getRemark()); + return result; + } + + private void recordPurchaseOperation(InRecord record, String username, String type, String title, String detail) + { + if (record.getPurchaseRequestId() == null) return; + var purchase = purchaseRequestMapper.selectPurchaseRequestById(record.getPurchaseRequestId(), null); + if (purchase != null) purchaseOperationLogService.record(purchase.getId(), purchase.getRequestNo(), type, title, + "入库单:" + record.getInNo() + ";" + detail); + } private void validateInRecord(InRecord inRecord) { - if (inRecord.getInNum() == null || inRecord.getInNum().signum() <= 0) + if (inRecord.getInNum() == null || inRecord.getInNum().signum() <= 0 + || inRecord.getInNum().stripTrailingZeros().scale() > 4) { - throw new ServiceException("入库数量必须大于0"); + throw new ServiceException("入库数量必须大于0,最多4位小数"); } if (StringUtils.isBlank(inRecord.getInOperator())) { @@ -177,16 +306,13 @@ public class InRecordServiceImpl implements IInRecordService { return; } - if (inRecord.getSourceProjectId() == null || inRecord.getExpenseCategoryId() == null) + if (inRecord.getSourceProjectId() == null) { - throw new ServiceException("手工入库必须选择来源项目和经费科目"); + throw new ServiceException("入库必须选择所属项目"); } projectInfoService.requireActiveProject(inRecord.getSourceProjectId()); - ExpenseCategory category = projectBudgetMapper.selectExpenseCategoryById(inRecord.getExpenseCategoryId()); - if (category == null || Integer.valueOf(1).equals(category.getStatus())) - { - throw new ServiceException("经费科目不存在或已停用"); - } + if (inRecord.getReceiptUnitCost()!=null && (inRecord.getReceiptUnitCost().signum()<0 || inRecord.getReceiptUnitCost().stripTrailingZeros().scale()>6)) + throw new ServiceException("单位成本不能为负数,最多6位小数"); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java new file mode 100644 index 0000000..560e81a --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InitializationService.java @@ -0,0 +1,81 @@ +package com.ruoyi.warehouse.service.impl; + +import java.math.*; +import java.time.LocalDate; +import java.util.*; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +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.warehouse.domain.*; +import com.ruoyi.warehouse.service.*; + +/** Optional opening balances are independent from historical purchasing and debt. */ +@Service public class InitializationService { + @Autowired private BusinessNumberService businessNumbers; + @Autowired private JdbcTemplate db; + @Autowired private InventoryCostJournal journal; + @Autowired private IInRecordService inbound; + @Autowired private IPurchaseRequestService purchases; + @Autowired private IPurchaseArrivalService arrivals; + public static class Row { + public String sourceKey,projectCode,itemCode,areaName,supplierName,categoryCode,lenderCode,remark; + public BigDecimal quantity,unitPrice,receivedQuantity,acceptedQuantity,returnedQuantity; + public LocalDate date; + } + private record Resolved(Long project,Long item,Long area,Long supplier,Long category,Long lender){} + public List> preview(String kind,List rows){ + permission(kind);if(rows==null||rows.size()>2000)throw fail("每次最多2000行");var seen=new HashSet();var result=new ArrayList>();int line=1; + for(var row:rows){String error=null;try{validate(kind,row);if(!seen.add(row.sourceKey))throw fail("文件中来源编号重复");if(!db.queryForList("select id from initialization_record where kind=? and source_key=?",kind,row.sourceKey).isEmpty())throw fail("该来源编号已导入,请勿重复导入");}catch(Exception e){error=e.getMessage();}var item=new LinkedHashMap();item.put("line",++line);item.put("row",row);item.put("error",error);result.add(item);}return result; + } + @Transactional public Map apply(String kind,Row row){ + permission(kind);journal.lockInventory();var r=validate(kind,row);String hash=hash(row); + var previous=db.queryForList("select content_hash,business_id,related_id from initialization_record where kind=? and source_key=?",kind,row.sourceKey); + if(!previous.isEmpty()){if(!hash.equals(previous.get(0).get("content_hash")))throw fail("来源编号已使用且内容不同");return previous.get(0);} + Long id,related=null; + if("STOCK".equals(kind)){ + if(db.queryForObject("select coalesce(sum(quantity),0) from project_stock_balance where project_id=? and item_id=? and area_id=?",BigDecimal.class,r.project,r.item,r.area).signum()>0)throw fail("该项目物品库区已有库存,不能重复建立期初;现场差异请盘点"); + var record=new InRecord();record.setBusinessDate(row.date);record.setSourceProjectId(r.project);record.setProductId(r.item);record.setAreaId(r.area);record.setInNum(row.quantity);record.setReceiptUnitCost(row.unitPrice);record.setInType(1);record.setRemark("期初:"+row.sourceKey+";原日期:"+row.date+";"+Objects.toString(row.remark,"")); + inbound.insertInRecord(record);inbound.confirmInRecord(record.getId(),SecurityUtils.getUsername());id=record.getId(); + }else if("LOAN".equals(kind)){ + id=insert("insert into project_loan(loan_no,lender_project_id,borrower_project_id,item_id,quantity,historical_returned,business_date,remark,create_by) values(?,?,?,?,?,?,?,?,?)",businessNumbers.reserve("LOAN",row.date,"history:"+row.sourceKey),r.lender,r.project,r.item,row.quantity,zero(row.returnedQuantity),row.date,row.remark,SecurityUtils.getUsername()); + }else{ + BigDecimal received=row.receivedQuantity==null?row.quantity:row.receivedQuantity,remaining=row.quantity.subtract(received),accepted=zero(row.acceptedQuantity); + Long batch=insert("insert into purchase_batch(batch_no,batch_name,purchase_status,progress_remark,supplier_id,business_date,create_by,create_time) values(?,?,1,?,?,?,?,current_timestamp)",businessNumbers.reserve("CG",row.date,"history:"+row.sourceKey),row.sourceKey,row.remark,r.supplier,row.date,SecurityUtils.getUsername()); + id=null; + if(received.signum()>0){id=purchase(row,r,received,batch,true);} + if(remaining.signum()>0){related=purchase(row,r,remaining,batch,false);if(accepted.signum()>0){var arrival=new PurchaseArrival();arrival.setPurchaseRequestId(related);arrival.setArrivalQuantity(accepted);arrival.setArrivalDate(java.sql.Date.valueOf(row.date));arrival.setRequestKey("HISTORY:"+UUID.nameUUIDFromBytes(row.sourceKey.getBytes(java.nio.charset.StandardCharsets.UTF_8)));arrivals.insertPurchaseArrival(arrival);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(1);acceptance.setDefectiveQuantity(BigDecimal.ZERO);arrivals.acceptPurchaseArrival(arrival.getId(),acceptance);}} + if(id==null){id=related;related=null;} + } + db.update("insert into initialization_record(kind,source_key,content_hash,business_id,related_id,create_by) values(?,?,?,?,?,?)",kind,row.sourceKey,hash,id,related,SecurityUtils.getUsername()); + var result=new LinkedHashMap();result.put("businessId",id);result.put("relatedId",related);return result; + } + private Long purchase(Row row,Resolved r,BigDecimal quantity,Long batch,boolean historical){ + var p=new PurchaseRequest();p.setProjectId(r.project);p.setProductId(r.item);p.setExpenseCategoryId(r.category);p.setQuantity(quantity);p.setFinalUnitPrice(row.unitPrice);p.setPurchasePurpose("SELF");p.setRemark("历史来源:"+row.sourceKey+";"+Objects.toString(row.remark,""));purchases.insertPurchaseRequest(p); + db.update("update purchase_request set historical=?,original_date=?,purchase_batch_id=?,purchase_batch_no=(select batch_no from purchase_batch where id=?),purchase_status=? where id=?",historical,row.date,batch,batch,historical?4:2,p.getId());return p.getId(); + } + private Resolved validate(String kind,Row r){ + if(r==null||r.sourceKey==null||r.sourceKey.isBlank()||r.sourceKey.length()>120)throw fail("来源编号必填且最多120字(用于防重复)"); + positive(r.quantity,"数量");if(r.remark!=null&&r.remark.length()>300)throw fail("备注最多300字"); + if(r.unitPrice!=null&&(r.unitPrice.signum()<0||r.unitPrice.stripTrailingZeros().scale()>6))throw fail("单价不能为负,最多6位小数"); + Long project=lookup("select id from project_info where project_code=? and del_flag='0'",r.projectCode,"项目编码"),item=lookup("select id from product_info where product_code=?",r.itemCode,"物品编码"),area=null,supplier=null,category=null,lender=null; + if("STOCK".equals(kind))area=lookup("select id from warehouse_area where area_name=?",r.areaName,"库区名称"); + else if("LOAN".equals(kind)){lender=lookup("select id from project_info where project_code=? and del_flag='0'",r.lenderCode,"借出项目编码");if(lender.equals(project))throw fail("借出与借入项目不能相同");nonnegative(zero(r.returnedQuantity),"历史已还量");if(zero(r.returnedQuantity).compareTo(r.quantity)>0)throw fail("历史已还不能超过原借量");} + else if("PURCHASE".equals(kind)){supplier=lookup("select id from supplier_info where name=? and active=1",r.supplierName,"供应商名称");category=lookup("select id from expense_category where category_code=? and status=0",r.categoryCode,"费用分类编码");if(r.unitPrice==null||r.date==null)throw fail("历史采购必须填写最终单价和原日期");BigDecimal received=r.receivedQuantity==null?r.quantity:r.receivedQuantity;nonnegative(received,"已入库量");nonnegative(zero(r.acceptedQuantity),"已验收待入库量");if(received.add(zero(r.acceptedQuantity)).compareTo(r.quantity)>0)throw fail("已入库加待入库不能超过总采购量");} + else throw fail("初始化类型无效"); + return new Resolved(project,item,area,supplier,category,lender); + } + private Long lookup(String sql,String value,String label){if(value==null||value.isBlank())throw fail(label+"必填");var rows=db.queryForList(sql,Long.class,value.trim());if(rows.size()!=1)throw fail(label+"未找到唯一有效档案:"+value);return rows.get(0);} + private static void positive(BigDecimal value,String label){nonnegative(value,label);if(value.signum()==0)throw fail(label+"必须大于0");} + private static void nonnegative(BigDecimal value,String label){if(value==null||value.signum()<0||value.stripTrailingZeros().scale()>4)throw fail(label+"必须非负且最多4位小数");} + private static BigDecimal zero(BigDecimal value){return value==null?BigDecimal.ZERO:value;} + private static String hash(Row row){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(com.alibaba.fastjson2.JSON.toJSONString(row).getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}} + 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;iuse&&SecurityUtils.hasPermi("warehouse:in:add")&&SecurityUtils.hasPermi("warehouse:in:confirm");case "LOAN"->use;case "PURCHASE"->SecurityUtils.hasPermi("warehouse:purchase:import")||SecurityUtils.hasPermi("warehouse:purchase:manage");default->false;};if(!allowed)throw fail("没有对应初始化业务权限");} + private static ServiceException fail(String message){return new ServiceException(message);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InventoryCostJournal.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InventoryCostJournal.java new file mode 100644 index 0000000..e47c521 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/InventoryCostJournal.java @@ -0,0 +1,218 @@ +package com.ruoyi.warehouse.service.impl; + +import java.math.BigDecimal; +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.service.IProjectInfoService; +import com.ruoyi.warehouse.domain.*; +import com.ruoyi.warehouse.mapper.*; +import com.ruoyi.warehouse.util.MovingAverageCost; +import com.ruoyi.warehouse.util.MovingAverageCost.*; + +/** Project moving-average journal; the old aggregate is a compatibility projection, never a cost source. */ +@Service +public class InventoryCostJournal { + @Autowired private BusinessNumberService businessNumbers; + @Autowired private InventoryCostMapper mapper; + @Autowired private IProjectInfoService projects; + @Autowired private ProductInfoMapper items; + @Autowired private WarehouseAreaMapper areas; + @Autowired private org.springframework.jdbc.core.JdbcTemplate adjustmentDatabase; + /** Business adapters acquire this before document locks to maintain a single lock order. */ + public void lockInventory() { lock(); } + + public ProjectItemCost balance(Long projectId, Long itemId) { + projects.requireProjectAccess(projectId); return mapper.selectCost(projectId, itemId); + } + public List events(Long projectId, Long itemId) { + projects.requireProjectAccess(projectId); return mapper.selectEvents(projectId, itemId); + } + public List> adjustments(Long projectId,Long itemId){ + projects.requireProjectAccess(projectId); + return adjustmentDatabase.queryForList("select c.*,r.revision_key,r.revision_no,r.create_time,r.create_by,e.event_key,e.event_no,e.event_type from inventory_cost_change c join inventory_cost_revision r on r.id=c.revision_id join inventory_cost_event e on e.id=c.event_id where e.project_id=? and e.item_id=? order by r.id desc,c.id",projectId,itemId); + } + @Transactional public void bindTransfer(Long sourceId,Long targetId) { + lock(); InventoryCostEvent source=requireEvent(sourceId),target=requireEvent(targetId); + projects.requireProjectAccess(source.getProjectId()); projects.requireProjectAccess(target.getProjectId()); + if (!Boolean.TRUE.equals(source.getActive()) || !Boolean.TRUE.equals(target.getActive()) || !"ISSUE".equals(source.getEventType()) || !"RECEIPT".equals(target.getEventType()) + || !Objects.equals(source.getItemId(),target.getItemId()) || sourceId>=targetId || source.getQuantity().compareTo(target.getQuantity())!=0 + || !equalAmount(source.getEffectiveCost(),target.getEffectiveCost())) throw error("库存转移成本关联不完整"); + Long existing=mapper.selectLinkSource(targetId); + if (existing!=null) { if (!Objects.equals(existing,sourceId)) throw error("该入库已有其他成本来源"); return; } + mapper.insertLink(sourceId,targetId); + } + @Transactional public InventoryCostEvent append(InventoryCostEvent event) { + lock(); normalize(event); projects.requireProjectAccess(event.getProjectId()); + if (items.selectProductInfoById(event.getItemId()) == null || areas.selectWarehouseAreaById(event.getAreaId()) == null) + throw error("物品或库区不存在"); + InventoryCostEvent duplicate = mapper.selectEventByKey(event.getEventKey()); + if (duplicate != null) { + if (!sameEvent(event, duplicate)) throw error("重复业务标识对应的库存内容不一致"); + if (!Boolean.TRUE.equals(duplicate.getActive())) throw error("该库存业务已撤销,重新办理应使用新修订标识"); + return duplicate; + } + if(Integer.valueOf(1).equals(areas.selectWarehouseAreaById(event.getAreaId()).getStatus()))throw error("该库区已停用,请选择启用的库区"); + if ("RETURN".equals(event.getEventType())) { + InventoryCostEvent source = event.getSourceId() == null ? null : mapper.selectEvent(event.getSourceId()); + if (source == null || !Boolean.TRUE.equals(source.getActive()) || !"ISSUE".equals(source.getEventType()) + || !Objects.equals(source.getProjectId(), event.getProjectId()) || !Objects.equals(source.getItemId(), event.getItemId())) + throw error("退料只能关联本项目同一物品的有效领用"); + } + if ("ISSUE".equals(event.getEventType()) && areaQuantity(event).compareTo(event.getQuantity()) < 0) + throw error("该项目在所选库区的库存不足"); + mapper.ensureCost(event.getProjectId(), event.getItemId()); + event.setId(null);event.setEventNo(businessNumbers.reserve("EVENT",event.getBusinessDate(),event.getEventKey())); event.setCreateBy(SecurityUtils.getUsername()); mapper.insertEvent(event); + Result result = replay(event.getProjectId(), event.getItemId(), overrides(event.getProjectId(), event.getItemId())); + Valuation valuation = result.events().stream().filter(value -> value.eventId()==event.getId()).findFirst().orElseThrow(); + mapper.setOriginalCost(event.getId(), valuation.amount()); + changeArea(event, !"ISSUE".equals(event.getEventType())); persist(event.getProjectId(), event.getItemId(), result); + return mapper.selectEvent(event.getId()); + } + @Transactional public List move(Long projectId, Long itemId, Long fromArea, Long toArea, BigDecimal quantity, String key) { + return move(projectId,itemId,fromArea,toArea,quantity,key,null,null); + } + public static InventoryCostEvent details(InventoryCostEvent event,java.time.LocalDate date,String remark){ + event.setBusinessDate(date);event.setRemark(remark);return event; + } + @Transactional public List move(Long projectId, Long itemId, Long fromArea, Long toArea, BigDecimal quantity, String key,java.time.LocalDate date,String remark) { + if (Objects.equals(fromArea, toArea)) throw error("源库区和目标库区不能相同"); + checkKey(key, 150); + InventoryCostEvent out = details(event(projectId,itemId,fromArea,"ISSUE",quantity,null,null,key+":out"),date,remark); + InventoryCostEvent issued = append(out); + InventoryCostEvent received = append(details(event(projectId,itemId,toArea,"RETURN",quantity,null,issued.getId(),key+":in"),date,remark)); + return List.of(issued,received); + } + @Transactional public InventoryCostRevision reviseReceipt(Long eventId, BigDecimal newAmount, String revisionKey, Integer expectedVersion) { + lock(); + if (mapper.selectLinkSource(eventId)!=null) throw error("借还转移入库的成本由来源自动联动,不能单独改价"); + InventoryCostRevision result=reviseLocal(eventId,newAmount,revisionKey,expectedVersion); + cascadeTransferCosts(revisionKey); + return result; + } + @Transactional public void revokeMove(Long incomingId,String reason) { + lock();InventoryCostEvent incoming=requireEvent(incomingId); + String key=incoming.getEventKey(); + if(key==null||!key.startsWith("MOVE:")||!key.endsWith(":in")||!"RETURN".equals(incoming.getEventType())||incoming.getSourceId()==null) + throw error("请选择移库入账记录"); + InventoryCostEvent outgoing=requireEvent(incoming.getSourceId()); + if(!Objects.equals(outgoing.getEventKey(),key.substring(0,key.length()-3)+":out")||!Objects.equals(outgoing.getProjectId(),incoming.getProjectId())||!Objects.equals(outgoing.getItemId(),incoming.getItemId())) + throw error("移库对应关系不完整"); + projects.requireProjectAccess(incoming.getProjectId()); + voidLastEvent(incomingId,reason);voidLastEvent(outgoing.getId(),reason); + } + private InventoryCostRevision reviseLocal(Long eventId, BigDecimal newAmount, String revisionKey, Integer expectedVersion) { + lock(); checkKey(revisionKey,160); InventoryCostEvent target = requireEvent(eventId); + projects.requireProjectAccess(target.getProjectId()); + newAmount = validatedReceiptAmount(target.getQuantity(),newAmount); + InventoryCostRevision duplicate = mapper.selectRevisionByKey(revisionKey); + if (duplicate != null) { + if (!Objects.equals(duplicate.getTargetEventId(),eventId) || !equalAmount(duplicate.getNewAmount(),newAmount) + || !Objects.equals(duplicate.getExpectedVersion(),expectedVersion)) throw error("重复结算标识对应的内容不一致"); + return duplicate; + } + if (!Boolean.TRUE.equals(target.getActive()) || !"RECEIPT".equals(target.getEventType())) throw error("只能调整有效入库的来源成本"); + ProjectItemCost balance = mapper.selectCost(target.getProjectId(),target.getItemId()); + if (balance == null || !Objects.equals(balance.getVersion(),expectedVersion)) throw error("库存成本基准已变化,请重新计算"); + Map overrides = overrides(target.getProjectId(),target.getItemId()); + Result before = replay(target.getProjectId(),target.getItemId(),overrides); + overrides.put(eventId,newAmount); Result after = replay(target.getProjectId(),target.getItemId(),overrides); + List changes = MovingAverageCost.differences(before,after); + InventoryCostRevision revision = new InventoryCostRevision(); revision.setRevisionKey(revisionKey); revision.setTargetEventId(eventId); + revision.setRevisionNo(businessNumbers.reserve("REVISION",null,revisionKey));revision.setNewAmount(newAmount); revision.setExpectedVersion(expectedVersion); revision.setCreateBy(SecurityUtils.getUsername()); mapper.insertRevision(revision); + for (Difference change : changes) mapper.insertChange(revision.getId(),change); + persist(target.getProjectId(),target.getItemId(),after); return revision; + } + private void cascadeTransferCosts(String revisionKey) { + // Forward immutable event links also cover multi-hop borrowing and repayment. + java.util.PriorityQueue targets=new java.util.PriorityQueue<>(); + Set scheduled=new HashSet<>(); + for (Long target : mapper.selectAllLinkedTargets()) { targets.add(target); scheduled.add(target); } + int correction=0; + while (!targets.isEmpty()) { + Long id=targets.remove(); scheduled.remove(id); InventoryCostEvent target=requireEvent(id); + InventoryCostEvent source=requireEvent(mapper.selectLinkSource(id)); + if (!Boolean.TRUE.equals(source.getActive())) throw error("转移入库依赖的出库已撤销,成本链不完整"); + BigDecimal current=overrides(target.getProjectId(),target.getItemId()).getOrDefault(id,target.getReceiptAmount()); + if (equalAmount(current,source.getEffectiveCost())) continue; + if (++correction>10000) throw error("成本联动超过安全限额,请管理员检查关联"); + String key="TRANSFER:"+UUID.nameUUIDFromBytes((revisionKey+":"+id+":"+correction).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + reviseLocal(id,source.getEffectiveCost(),key,mapper.selectCost(target.getProjectId(),target.getItemId()).getVersion()); + for (InventoryCostEvent event : mapper.selectEvents(target.getProjectId(),target.getItemId())) + for (Long next : mapper.selectLinkedTargets(event.getId())) if (scheduled.add(next)) targets.add(next); + } + } + @Transactional public void voidLastEvent(Long eventId, String reason) { + lock(); if (StringUtils.isBlank(reason) || reason.trim().length()>300) throw error("请填写撤销原因,最多300字"); + InventoryCostEvent target = requireEvent(eventId); projects.requireProjectAccess(target.getProjectId()); + if (!Boolean.TRUE.equals(target.getActive())) return; + if (!mapper.selectLinkedTargets(eventId).isEmpty()) throw error("该出库已有借用或归还入库,请先撤销关联入库"); + List stream = mapper.selectEvents(target.getProjectId(),target.getItemId()); + var later = stream.stream().filter(event -> Boolean.TRUE.equals(event.getActive()) && event.getId()>eventId).max(Comparator.comparing(InventoryCostEvent::getId)); + if (later.isPresent()) + throw error("请先撤销后续库存业务:"+later.get().getEventKey()+"(流水ID:"+later.get().getId()+")"); + if (mapper.voidEvent(eventId,reason.trim(),SecurityUtils.getUsername())!=1) throw error("库存事件状态已变化"); + changeArea(target,"ISSUE".equals(target.getEventType())); + persist(target.getProjectId(),target.getItemId(),replay(target.getProjectId(),target.getItemId(),overrides(target.getProjectId(),target.getItemId()))); + } + @Transactional public void voidMove(String key, String reason) { + lock(); checkKey(key,150); + InventoryCostEvent out = mapper.selectEventByKey(key+":out"), in = mapper.selectEventByKey(key+":in"); + if (out==null || in==null || !Objects.equals(in.getSourceId(),out.getId()) || !"ISSUE".equals(out.getEventType()) || !"RETURN".equals(in.getEventType())) + throw error("移库关联不完整,不能撤销"); + voidLastEvent(in.getId(),reason); voidLastEvent(out.getId(),reason); + } + private Result replay(Long projectId,Long itemId,Map overrides) { + List stream = mapper.selectEvents(projectId,itemId).stream().map(event -> new Event(event.getId(),Type.valueOf(event.getEventType()),event.getQuantity(),event.getReceiptAmount(),event.getSourceId(),Boolean.TRUE.equals(event.getActive()))).toList(); + return MovingAverageCost.replay(stream,overrides); + } + private Map overrides(Long projectId,Long itemId) { + Map overrides = new HashMap<>(); + for (InventoryCostRevision revision : mapper.selectOverrides(projectId,itemId)) overrides.put(revision.getTargetEventId(),revision.getNewAmount()); + return overrides; + } + private void persist(Long projectId,Long itemId,Result result) { + for (Valuation event : result.events()) mapper.setEffectiveCost(event.eventId(),event.amount()); + if (mapper.updateCost(projectId,itemId,result.balance().quantity(),result.balance().amount())!=1) throw error("库存成本余额不存在"); + } + private void changeArea(InventoryCostEvent event,boolean increase) { + if (increase) mapper.increaseArea(event.getProjectId(),event.getItemId(),event.getAreaId(),event.getQuantity()); + else if (mapper.decreaseArea(event.getProjectId(),event.getItemId(),event.getAreaId(),event.getQuantity())!=1) throw error("所选库区库存不足,操作未完成"); + mapper.syncLegacyArea(event.getItemId(),event.getAreaId()); + } + private BigDecimal areaQuantity(InventoryCostEvent event) { + BigDecimal quantity = mapper.selectAreaQuantity(event.getProjectId(),event.getItemId(),event.getAreaId()); return quantity==null ? BigDecimal.ZERO : quantity; + } + private void normalize(InventoryCostEvent event) { + if(event.getBusinessDate()==null)event.setBusinessDate(java.time.LocalDate.now()); + if(event.getRemark()!=null&&event.getRemark().length()>500)throw error("备注最多500字"); + if (event==null || event.getProjectId()==null || event.getItemId()==null || event.getAreaId()==null) throw error("请选择项目、物品和库区"); + checkKey(event.getEventKey(),160); + try { event.setEventType(Type.valueOf(StringUtils.trim(event.getEventType())).name()); } catch (RuntimeException failure) { throw error("库存事件类型不正确"); } + MovingAverageCost.receiptAmount(event.getQuantity(),null); event.setQuantity(event.getQuantity().setScale(4)); + if ("RECEIPT".equals(event.getEventType())) { + if (event.getSourceId()!=null) throw error("普通入库不能引用领用来源"); + event.setReceiptAmount(validatedReceiptAmount(event.getQuantity(),event.getReceiptAmount())); + } else if (event.getReceiptAmount()!=null || "ISSUE".equals(event.getEventType()) && event.getSourceId()!=null) throw error("出库及退料不能手填成本"); + } + private BigDecimal validatedReceiptAmount(BigDecimal quantity,BigDecimal amount) { + return MovingAverageCost.replay(List.of(new Event(1,Type.RECEIPT,quantity,amount,null,true))).balance().amount(); + } + private boolean sameEvent(InventoryCostEvent left,InventoryCostEvent right) { + return Objects.equals(left.getProjectId(),right.getProjectId()) && Objects.equals(left.getItemId(),right.getItemId()) && Objects.equals(left.getAreaId(),right.getAreaId()) + && Objects.equals(left.getEventType(),right.getEventType()) && Objects.equals(left.getSourceId(),right.getSourceId()) && equalAmount(left.getQuantity(),right.getQuantity()) && equalAmount(left.getReceiptAmount(),right.getReceiptAmount()); + } + private boolean equalAmount(BigDecimal left,BigDecimal right) { return left==null || right==null ? left==right : left.compareTo(right)==0; } + private void checkKey(String key,int maximum) { if (StringUtils.isBlank(key) || key.length()>maximum) throw error("业务修订标识不能为空或超长"); } + private void lock() { if (mapper.lockJournal()==null) throw error("库存成本结构未初始化"); } + private InventoryCostEvent requireEvent(Long id) { InventoryCostEvent event = id==null ? null : mapper.selectEvent(id); if (event==null) throw error("库存事件不存在"); return event; } + public static InventoryCostEvent event(Long projectId,Long itemId,Long areaId,String type,BigDecimal quantity,BigDecimal amount,Long sourceId,String key) { + InventoryCostEvent event = new InventoryCostEvent(); event.setProjectId(projectId); event.setItemId(itemId); event.setAreaId(areaId); event.setEventType(type); + event.setQuantity(quantity); event.setReceiptAmount(amount); event.setSourceId(sourceId); event.setEventKey(key); return event; + } + private ServiceException error(String message) { return new ServiceException(message); } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/OutRecordServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/OutRecordServiceImpl.java index 77f1f30..d1c211a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/OutRecordServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/OutRecordServiceImpl.java @@ -15,24 +15,21 @@ import com.ruoyi.warehouse.domain.StockInfo; import com.ruoyi.warehouse.mapper.OutRecordMapper; import com.ruoyi.warehouse.mapper.StockInfoMapper; import com.ruoyi.warehouse.service.IOutRecordService; -import com.ruoyi.warehouse.service.IStockLotService; import com.ruoyi.warehouse.util.WarehouseNoUtils; @Service public class OutRecordServiceImpl implements IOutRecordService { + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private OutRecordMapper outRecordMapper; - @Autowired - private StockInfoMapper stockInfoMapper; + @Autowired private InventoryCostJournal journal; + @Autowired private com.ruoyi.warehouse.mapper.InventoryCostMapper costs; @Autowired private IProjectInfoService projectInfoService; - @Autowired - private IStockLotService stockLotService; - @Override public List selectOutRecordList(OutRecord outRecord) { @@ -57,12 +54,14 @@ public class OutRecordServiceImpl implements IOutRecordService @Transactional public int insertOutRecord(OutRecord outRecord) { - outRecord.setOutOperator(StringUtils.trim(outRecord.getOutOperator())); + journal.lockInventory(); + outRecord.setOutOperator(SecurityUtils.getUsername()); + outRecord.setOperator(SecurityUtils.getUsername()); if (outRecord.getOutType() == null) { throw new ServiceException("出库类型不能为空"); } - if (outRecord.getOutNum() == null || outRecord.getOutNum().signum() <= 0) + if (outRecord.getOutNum() == null || outRecord.getOutNum().signum() <= 0 || outRecord.getOutNum().stripTrailingZeros().scale()>4) { throw new ServiceException("出库数量必须大于0"); } @@ -79,33 +78,50 @@ public class OutRecordServiceImpl implements IOutRecordService throw new ServiceException("无项目物资使用权限"); } projectInfoService.requireActiveProject(outRecord.getUsageProjectId()); - if (StringUtils.isBlank(outRecord.getOutNo())) - { - outRecord.setOutNo(WarehouseNoUtils.next("OUT")); + String suppliedNo=outRecord.getOutNo(); + var previous=StringUtils.isBlank(suppliedNo)?null:outRecordMapper.checkOutNoUnique(suppliedNo); + if(previous==null){outRecord.setOutNo(businessNumbers.reserve("OUT",outRecord.getOutTime()==null?null:new java.sql.Date(outRecord.getOutTime().getTime()).toLocalDate(),StringUtils.isBlank(suppliedNo)?null:"out:"+suppliedNo));previous=outRecordMapper.checkOutNoUnique(outRecord.getOutNo());} + if(previous!=null){ + if(Boolean.TRUE.equals(previous.getActive())&&java.util.Objects.equals(previous.getUsageProjectId(),outRecord.getUsageProjectId())&&java.util.Objects.equals(previous.getProductId(),outRecord.getProductId())&&java.util.Objects.equals(previous.getAreaId(),outRecord.getAreaId())&&java.util.Objects.equals(previous.getOutType(),outRecord.getOutType())&&previous.getOutNum().compareTo(outRecord.getOutNum())==0){outRecord.setId(previous.getId());outRecord.setOutNo(previous.getOutNo());return 1;} + throw new ServiceException("重复出库内容不一致或已撤销,请刷新后重试"); } - else if (!checkOutNoUnique(outRecord)) - { - throw new ServiceException("出库单号已存在"); - } - StockInfo stockInfo = stockInfoMapper.selectStockInfoByAreaProductForUpdate(outRecord.getAreaId(), outRecord.getProductId()); - if (stockInfo == null) - { - throw new ServiceException("库存不存在,不能出库"); - } - if (stockInfo.getStockNum().compareTo(outRecord.getOutNum()) < 0) - { - throw new ServiceException("库存不足,当前库存:" + stockInfo.getStockNum()); - } - outRecord.setOutTime(new Date()); + if (!Integer.valueOf(4).equals(outRecord.getOutType())) throw new ServiceException("直接出库请选择项目领用;生产领料请关联生产任务,采购退货请从到货记录办理,成品交付请从库存现场操作办理"); + if(outRecord.getOutTime()==null)outRecord.setOutTime(new Date()); outRecord.setCrossProjectFlag(0); - int rows = stockInfoMapper.deductStock(outRecord.getAreaId(), outRecord.getProductId(), outRecord.getOutNum()); - if (rows <= 0) - { - throw new ServiceException("库存扣减失败"); - } + var costEvent = journal.append(InventoryCostJournal.details(InventoryCostJournal.event(outRecord.getUsageProjectId(),outRecord.getProductId(),outRecord.getAreaId(), + "ISSUE",outRecord.getOutNum(),null,null,"OUT:"+outRecord.getOutNo()),outRecord.getOutTime().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate(),outRecord.getRemark())); + outRecord.setCostEventId(costEvent.getId()); int result = outRecordMapper.insertOutRecord(outRecord); - stockLotService.allocateOutboundLots(outRecord); return result; } - + @Override @Transactional public int revoke(Long id,String reason) { + requireUsePermission(); journal.lockInventory(); OutRecord record=requireCurrent(id); + journal.voidLastEvent(record.getCostEventId(),reason); return outRecordMapper.revoke(id); + } + @Override @Transactional public com.ruoyi.warehouse.domain.InventoryCostEvent returnMaterial(Long id,Long areaId,java.math.BigDecimal quantity,String key) { + if (StringUtils.isBlank(key) || key.length()>145) throw new ServiceException("退料业务标识不能为空或超长"); + requireUsePermission(); journal.lockInventory(); OutRecord record=requireCurrent(id); + return journal.append(InventoryCostJournal.event(record.getUsageProjectId(),record.getProductId(),areaId,"RETURN",quantity,null,record.getCostEventId(),"OUT-RETURN:"+key)); + } + private void requireUsePermission() { + if (!SecurityUtils.isAdmin() && !SecurityUtils.hasPermi("project:inventory:use")) throw new ServiceException("无项目物资使用权限"); + } + @Override public List returns(Long id) { + var record=requireCurrent(id); + return costs.selectEvents(record.getUsageProjectId(),record.getProductId()).stream() + .filter(e->"RETURN".equals(e.getEventType())&&java.util.Objects.equals(record.getCostEventId(),e.getSourceId())&&e.getEventKey().startsWith("OUT-RETURN:")).toList(); + } + @Override @Transactional public void revokeReturn(Long id,Long eventId,String reason) { + requireUsePermission();journal.lockInventory(); + var event=returns(id).stream().filter(e->java.util.Objects.equals(eventId,e.getId())).findFirst() + .orElseThrow(()->new ServiceException("退料记录与原出库不一致")); + journal.voidLastEvent(event.getId(),reason); + } + private OutRecord requireCurrent(Long id) { + OutRecord record=outRecordMapper.selectOutRecordById(id); + if (record==null || !Boolean.TRUE.equals(record.getActive())) throw new ServiceException("有效出库记录不存在"); + projectInfoService.requireProjectAccess(record.getUsageProjectId()); + if (record.getCostEventId()==null) throw new ServiceException("该历史出库未补录成本链,不能自动撤销或退料;现有库存已作为期初保留"); + return record; + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java index d631f51..99f5e75 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/ProductInfoServiceImpl.java @@ -7,6 +7,7 @@ import java.util.Locale; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.StringUtils; @@ -20,8 +21,10 @@ public class ProductInfoServiceImpl implements IProductInfoService private volatile List categoryHistoryCache = List.of(); private volatile long categoryHistoryCacheExpiresAt; + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private ProductInfoMapper productInfoMapper; + @Autowired private CatalogWriteLock catalogWriteLock; @Override public List selectProductInfoList(ProductInfo productInfo) @@ -79,17 +82,32 @@ public class ProductInfoServiceImpl implements IProductInfoService } @Override + @Transactional public int insertProductInfo(ProductInfo productInfo) { + catalogWriteLock.acquire(); normalizeProductInfo(productInfo); + validateFields(productInfo); + if(!checkProductCodeUnique(productInfo))throw new ServiceException("物品编码已存在"); validateProductInfoUnique(productInfo); + productInfo.setProductCode(businessNumbers.reserve("ITEM",null,StringUtils.isBlank(productInfo.getProductCode())?null:"archive:"+productInfo.getProductCode())); + if(!checkProductCodeUnique(productInfo))throw new ServiceException("该物品已建档,请使用已有物品"); return productInfoMapper.insertProductInfo(productInfo); } @Override + @Transactional public int updateProductInfo(ProductInfo productInfo) { + catalogWriteLock.acquire(); normalizeProductInfo(productInfo); + validateFields(productInfo); + if(!checkProductCodeUnique(productInfo))throw new ServiceException("物品编码已存在"); + ProductInfo existing = productInfoMapper.selectProductInfoForUpdate(productInfo.getId()); + if (existing == null) throw new ServiceException("物品不存在"); + if (StringUtils.isNotBlank(productInfo.getUnit()) && !java.util.Objects.equals(existing.getUnit(), productInfo.getUnit()) + && StringUtils.isNotBlank(existing.getUnit()) && productInfoMapper.countBusinessReferences(existing.getId()) > 0) + throw new ServiceException("物品已被业务引用,不能更换计量单位;不同单位请分别建档"); validateProductInfoUnique(productInfo); int rows = productInfoMapper.updateProductInfo(productInfo); invalidateCategoryHistory(); @@ -97,8 +115,15 @@ public class ProductInfoServiceImpl implements IProductInfoService } @Override + @Transactional public int deleteProductInfoByIds(Long[] ids) { + if (ids == null || ids.length == 0) throw new ServiceException("请选择物品"); + for (Long id : java.util.Arrays.stream(ids).distinct().sorted().toList()) { + ProductInfo item = productInfoMapper.selectProductInfoForUpdate(id); + if (item != null && productInfoMapper.countBusinessReferences(id) > 0) + throw new ServiceException("物品“" + item.getProductName() + "”已被采购、库存或BOM引用,不能删除"); + } int rows = productInfoMapper.deleteProductInfoByIds(ids); invalidateCategoryHistory(); return rows; @@ -120,6 +145,16 @@ public class ProductInfoServiceImpl implements IProductInfoService productInfo.setCategory(inferProductCategory(productInfo)); } } + private void validateFields(ProductInfo item){ + if(StringUtils.isBlank(item.getProductName())||StringUtils.isBlank(item.getUnit()))throw new ServiceException("物品名称和单位必填"); + if(item.getProductName().length()>100||item.getUnit().length()>32||item.getProductCode()!=null&&item.getProductCode().length()>64)throw new ServiceException("物品名称最多100字,单位32字,编码64字"); + } + @Override public List> previewImport(List rows){ + if(rows==null||rows.isEmpty()||rows.size()>2000)throw new ServiceException("请上传1至2000行物品"); + var results=new java.util.ArrayList>();var codes=new java.util.HashSet();var signatures=new java.util.HashSet();int line=1; + for(var item:rows){String error=null;try{item.setId(null);normalizeProductInfo(item);validateFields(item);validateProductInfoUnique(item);if(!checkProductCodeUnique(item))throw new ServiceException("物品编码已存在");if(item.getProductCode()!=null&&!codes.add(item.getProductCode().toLowerCase(Locale.ROOT)))throw new ServiceException("文件内编码重复");String signature=java.util.Arrays.asList(item.getProductName(),item.getBrand(),item.getCategory(),item.getSpec()).toString().toLowerCase(Locale.ROOT);if(!signatures.add(signature))throw new ServiceException("文件内相同物品重复");}catch(Exception e){error=e.getMessage();}var result=new LinkedHashMap();result.put("line",++line);result.put("summary",String.valueOf(item.getProductCode())+" / "+item.getProductName()+" / "+item.getUnit());result.put("error",error);results.add(result);}return results; + } + @Override @Transactional public String importNew(List rows){var preview=previewImport(rows);for(var result:preview)if(result.get("error")!=null)throw new ServiceException("第"+result.get("line")+"行:"+result.get("error"));for(var item:rows){item.setId(null);insertProductInfo(item);}return "新增物品 "+rows.size()+" 条,未覆盖已有档案";} private void validateProductInfoUnique(ProductInfo productInfo) { diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java index 816c8ed..8b91515 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseArrivalServiceImpl.java @@ -26,6 +26,9 @@ import com.ruoyi.warehouse.util.WarehouseNoUtils; @Service public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService { + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; + @Autowired private InventoryCostJournal journal; + @Autowired private org.springframework.jdbc.core.JdbcTemplate database; @Autowired private PurchaseArrivalMapper purchaseArrivalMapper; @@ -57,17 +60,30 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService @Transactional public int insertPurchaseArrival(PurchaseArrival arrival) { + journal.lockInventory(); if (arrival == null || arrival.getPurchaseRequestId() == null) { throw new ServiceException("采购申请不能为空"); } PurchaseRequest request = purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId()); - requireOwnerOrManager(request); + if (request == null) + { + throw new ServiceException("采购申请不存在"); + } + if(Boolean.TRUE.equals(request.getHistorical()))throw new ServiceException("历史已入库采购只归档计费,不重复到货或入库"); + String stableNo=null; + if(arrival.getRequestKey()!=null){ + if(arrival.getRequestKey().isBlank()||arrival.getRequestKey().length()>120)throw new ServiceException("到货业务标识无效"); + stableNo="ARR-"+java.util.UUID.nameUUIDFromBytes(arrival.getRequestKey().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + var duplicate=database.queryForList("select id,purchase_request_id,arrival_quantity from purchase_arrival where arrival_no=?",stableNo); + if(duplicate.isEmpty()){stableNo=businessNumbers.reserve("PA",arrival.getArrivalDate()==null?null:new java.sql.Date(arrival.getArrivalDate().getTime()).toLocalDate(),arrival.getRequestKey());duplicate=database.queryForList("select id,purchase_request_id,arrival_quantity from purchase_arrival where arrival_no=?",stableNo);} + if(!duplicate.isEmpty()){var previous=duplicate.get(0);if(!java.util.Objects.equals(((Number)previous.get("purchase_request_id")).longValue(),arrival.getPurchaseRequestId())||arrival.getArrivalQuantity()==null||new BigDecimal(previous.get("arrival_quantity").toString()).compareTo(arrival.getArrivalQuantity())!=0)throw new ServiceException("重复到货内容不一致");arrival.setId(((Number)previous.get("id")).longValue());arrival.setArrivalNo(stableNo);return 1;} + } if (Integer.valueOf(5).equals(request.getPurchaseStatus())) { throw new ServiceException("已取消的采购申请不能登记到货"); } - if (arrival.getArrivalQuantity() == null || arrival.getArrivalQuantity().signum() <= 0) + if (arrival.getArrivalQuantity() == null || arrival.getArrivalQuantity().signum() <= 0 || arrival.getArrivalQuantity().stripTrailingZeros().scale()>4) { throw new ServiceException("到货数量必须大于0"); } @@ -75,21 +91,17 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService { throw new ServiceException("到货日期不能为空"); } - BigDecimal unitPrice = arrival.getActualUnitPrice() == null - ? request.getEstimatedUnitPrice() : arrival.getActualUnitPrice(); - if (unitPrice == null || unitPrice.signum() <= 0) - { - throw new ServiceException("本批实际含税单价必须大于0"); - } - arrival.setActualUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP)); - arrival.setActualAmount(arrival.getArrivalQuantity().multiply(arrival.getActualUnitPrice()) - .setScale(2, RoundingMode.HALF_UP)); + BigDecimal unitPrice = request.getFinalUnitPrice() != null + ? request.getFinalUnitPrice() : request.getEstimatedUnitPrice(); + arrival.setActualUnitPrice(unitPrice); + arrival.setActualAmount(unitPrice == null ? null + : arrival.getArrivalQuantity().multiply(unitPrice).setScale(6, RoundingMode.HALF_UP)); BigDecimal activeQuantity = purchaseArrivalMapper.selectActiveQuantityByRequestId(request.getId()); if (activeQuantity.add(arrival.getArrivalQuantity()).compareTo(request.getQuantity()) > 0) { throw new ServiceException("本次到货数量超过剩余可登记数量"); } - arrival.setArrivalNo(generateArrivalNo()); + arrival.setArrivalNo(stableNo==null?generateArrivalNo():stableNo); arrival.setAcceptanceStatus(0); arrival.setCreateBy(SecurityUtils.getUsername()); arrival.setRemark(trimToNull(arrival.getRemark())); @@ -97,7 +109,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService purchaseOperationLogService.record(request.getId(), request.getRequestNo(), "ARRIVAL_REGISTER", "登记到货", "到货单:" + arrival.getArrivalNo() + ";数量:" + decimalText(arrival.getArrivalQuantity()) + unitText(request.getUnit()) - + ";实际金额:¥" + arrival.getActualAmount().toPlainString()); + + ";实际金额:¥" + (arrival.getActualAmount() == null ? "未锁价" : arrival.getActualAmount().toPlainString())); return rows; } @@ -105,12 +117,12 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService @Transactional public int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest acceptance) { + journal.lockInventory(); PurchaseArrival arrival = purchaseArrivalMapper.selectPurchaseArrivalByIdForUpdate(id); if (arrival == null) { throw new ServiceException("到货记录不存在"); } - requireOwnerOrManager(arrival.getApplicantId()); if (!Integer.valueOf(0).equals(arrival.getAcceptanceStatus())) { throw new ServiceException("该到货记录已验收,不能重复操作"); @@ -123,6 +135,12 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService String username = SecurityUtils.getUsername(); PurchaseRequest request = purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId()); + BigDecimal defective=acceptance.getDefectiveQuantity()==null ? BigDecimal.ZERO : acceptance.getDefectiveQuantity(); + if (defective.signum()<0 || defective.stripTrailingZeros().scale()>4 || defective.compareTo(arrival.getArrivalQuantity())>0) + throw new ServiceException("不合格数量不能为负数或超过到货数量,最多4位小数"); + if (Integer.valueOf(2).equals(acceptance.getAcceptanceStatus())) defective=arrival.getArrivalQuantity(); + if (defective.compareTo(arrival.getArrivalQuantity())==0) acceptance.setAcceptanceStatus(2); + arrival.setDefectiveQuantity(defective); if (Integer.valueOf(1).equals(acceptance.getAcceptanceStatus())) { arrival.setPreAcceptPurchaseStatus(request.getPurchaseStatus()); @@ -137,13 +155,6 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService if (Integer.valueOf(1).equals(arrival.getAcceptanceStatus())) { createPendingInRecord(arrival, username); - BigDecimal committedRelease = request.getEstimatedUnitPrice() - .multiply(arrival.getArrivalQuantity()).setScale(2, RoundingMode.HALF_UP); - projectBudgetService.settleExpense(request.getProjectId(), request.getExpenseCategoryId(), - committedRelease, arrival.getActualAmount(), "PURCHASE_ARRIVAL_SETTLE", arrival.getId(), - arrival.getArrivalNo(), "ARRIVAL:" + arrival.getId() + ":ACCEPT:" - + arrival.getAcceptedTime().getTime(), - "采购到货验收转实际支出"); BigDecimal accepted = purchaseArrivalMapper.selectAcceptedQuantityByRequestId(arrival.getPurchaseRequestId()); int status = accepted.compareTo(request.getQuantity()) >= 0 ? 4 : 3; purchaseRequestMapper.updatePurchaseStatus(request.getId(), status, @@ -166,12 +177,14 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService @Transactional public int revokePurchaseArrivalAcceptance(Long id, PurchaseArrivalRevokeRequest revoke) { + journal.lockInventory(); + if(database.queryForObject("select count(*) from purchase_return where arrival_id=?",Long.class,id)>0) + throw new ServiceException("这次到货已有退货记录,请继续登记补货;不能把已退货历史改回待验收"); PurchaseArrival arrival = purchaseArrivalMapper.selectPurchaseArrivalByIdForUpdate(id); if (arrival == null) { throw new ServiceException("到货记录不存在"); } - requireOwnerOrManager(arrival.getApplicantId()); if (Integer.valueOf(0).equals(arrival.getAcceptanceStatus())) { throw new ServiceException("该到货记录尚未验收,无需撤销"); @@ -196,6 +209,9 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService } else { + BigDecimal restoringDefects=arrival.getDefectiveQuantity()==null ? BigDecimal.ZERO : arrival.getDefectiveQuantity(); + if(purchaseArrivalMapper.selectActiveQuantityByRequestId(request.getId()).add(restoringDefects).compareTo(request.getQuantity())>0) + throw new ServiceException("不合格部分已有补货,请先退回对应补货,再撤销本次验收"); InRecord inRecord = inRecordMapper.selectInRecordByArrivalIdForUpdate(id); if (inRecord == null) { @@ -205,6 +221,8 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService { throw new ServiceException("该批到货已经确认入库,不能直接撤销,请先办理库存冲销"); } + if (Boolean.TRUE.equals(inRecord.getReceiptRoot()) && inRecordMapper.receivedQuantity(inRecord.getId()).signum()>0) + throw new ServiceException("已有分次入库,请先逐步撤销各次入库记录"); if (inRecordMapper.deletePendingInRecordByArrivalId(id) != 1) { throw new ServiceException("待入库记录状态已变化,请刷新后重试"); @@ -224,12 +242,6 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService if (Integer.valueOf(1).equals(arrival.getAcceptanceStatus())) { - BigDecimal committedRestore = request.getEstimatedUnitPrice() - .multiply(arrival.getArrivalQuantity()).setScale(2, RoundingMode.HALF_UP); - projectBudgetService.reverseSettlement(request.getProjectId(), request.getExpenseCategoryId(), - committedRestore, arrival.getActualAmount(), "PURCHASE_ARRIVAL_REVERSE", arrival.getId(), - arrival.getArrivalNo(), "ARRIVAL:" + arrival.getId() + ":REVOKE:" + arrival.getRevokedTime().getTime(), - "撤销采购到货验收"); BigDecimal accepted = purchaseArrivalMapper.selectAcceptedQuantityByRequestId(request.getId()); int status; if (accepted.signum() == 0) @@ -254,12 +266,12 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService @Transactional public int deletePurchaseArrival(Long id) { + journal.lockInventory(); PurchaseArrival arrival = purchaseArrivalMapper.selectPurchaseArrivalById(id); if (arrival == null) { throw new ServiceException("到货记录不存在"); } - requireOwnerOrManager(arrival.getApplicantId()); if (!Integer.valueOf(0).equals(arrival.getAcceptanceStatus())) { throw new ServiceException("已验收的到货记录不能删除"); @@ -277,7 +289,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService private void createPendingInRecord(PurchaseArrival arrival, String username) { InRecord inRecord = new InRecord(); - inRecord.setInNo("AIN" + arrival.getId()); + inRecord.setInNo(businessNumbers.reserve("IN",new java.sql.Date(arrival.getArrivalDate().getTime()).toLocalDate(),"arrival:"+arrival.getId())); inRecord.setAreaId(null); inRecord.setProductId(arrival.getProductId()); inRecord.setPurchaseRequestId(arrival.getPurchaseRequestId()); @@ -286,7 +298,8 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService inRecord.setExpenseCategoryId(arrival.getExpenseCategoryId()); inRecord.setSourceNo(arrival.getArrivalNo()); inRecord.setInType(2); - inRecord.setInNum(arrival.getArrivalQuantity()); + inRecord.setInNum(arrival.getArrivalQuantity().subtract(arrival.getDefectiveQuantity()==null ? BigDecimal.ZERO : arrival.getDefectiveQuantity())); + inRecord.setReceiptRoot(true); inRecord.setInStatus(0); inRecord.setOperator(username); inRecord.setInOperator(null); @@ -294,28 +307,6 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService inRecordMapper.insertInRecord(inRecord); } - private void requireOwnerOrManager(PurchaseRequest request) - { - if (request == null) - { - throw new ServiceException("采购申请不存在"); - } - requireOwnerOrManager(request.getApplicantId()); - } - - private void requireOwnerOrManager(Long applicantId) - { - if (!isManager() && !SecurityUtils.getUserId().equals(applicantId)) - { - throw new ServiceException("只能处理自己的采购到货"); - } - } - - private boolean isManager() - { - return SecurityUtils.isAdmin() || SecurityUtils.hasPermi("warehouse:purchase:manage"); - } - private String trimToNull(String value) { return StringUtils.isBlank(value) ? null : value.trim(); @@ -323,7 +314,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService private String generateArrivalNo() { - return WarehouseNoUtils.next("PA"); + return businessNumbers.next("PA"); } private String decimalText(BigDecimal value) diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchNumber.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchNumber.java new file mode 100644 index 0000000..60fa370 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchNumber.java @@ -0,0 +1,12 @@ +package com.ruoyi.warehouse.service.impl; + +import java.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** Both procurement entrances use the same monthly CG series. */ +@Component +public class PurchaseBatchNumber { + @Autowired private BusinessNumberService businessNumbers; + public String next(LocalDate businessDate){return businessNumbers.next("CG",businessDate);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java index 6b0104e..6ad75d4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java @@ -27,6 +27,8 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService @Autowired private IPurchaseOperationLogService purchaseOperationLogService; + @Autowired private SupplierService suppliers; + @Autowired private PurchaseBatchNumber batchNumbers; @Override public List selectPurchaseBatchList(PurchaseBatch batch) @@ -47,13 +49,14 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService } @Override - public int insertPurchaseBatch(PurchaseBatch batch) + @Transactional public int insertPurchaseBatch(PurchaseBatch batch) { checkManager(); if (batch.getPurchaseStatus() == null) { batch.setPurchaseStatus(1); } + batch.setBatchNo(null); // New batches use CG + year/month + shared sequence. normalizeAndValidate(batch); if (purchaseBatchMapper.selectPurchaseBatchByNo(batch.getBatchNo()) != null) { @@ -73,6 +76,15 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService { throw new ServiceException("采购批次不存在"); } + if (existing.getSupplierId() != null && !java.util.Objects.equals(existing.getSupplierId(), batch.getSupplierId())) { + PurchaseRequest query = new PurchaseRequest(); query.setPurchaseBatchId(batch.getId()); + if (purchaseRequestMapper.selectPurchaseRequestList(query).stream().anyMatch(row -> + Boolean.TRUE.equals(row.getPriceLocked()) || Boolean.TRUE.equals(row.getHistorical()) + || row.getAcceptedQuantity() != null && row.getAcceptedQuantity().signum() > 0 + || row.getPendingArrivalQuantity() != null && row.getPendingArrivalQuantity().signum() > 0)) + throw new ServiceException("已确认采购或已有到货的批次不能更换供应商"); + } + if(StringUtils.isBlank(batch.getBatchNo()))batch.setBatchNo(existing.getBatchNo()); normalizeAndValidate(batch); PurchaseBatch sameNo = purchaseBatchMapper.selectPurchaseBatchByNo(batch.getBatchNo()); if (sameNo != null && !sameNo.getId().equals(batch.getId())) @@ -150,12 +162,15 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService private void normalizeAndValidate(PurchaseBatch batch) { + if (batch.getSupplierId() != null || batch.getPurchaseStatus() != null && batch.getPurchaseStatus() >= 2 && batch.getPurchaseStatus() <= 4) + suppliers.requireActive(batch.getSupplierId()); + if(batch.getBusinessDate()==null)batch.setBusinessDate(java.time.LocalDate.now()); batch.setBatchNo(StringUtils.trim(batch.getBatchNo())); batch.setBatchName(StringUtils.trim(batch.getBatchName())); batch.setProgressRemark(StringUtils.trim(batch.getProgressRemark())); if (StringUtils.isBlank(batch.getBatchNo())) { - throw new ServiceException("采购批次编号不能为空"); + batch.setBatchNo(batchNumbers.next(batch.getBusinessDate())); } if (batch.getPurchaseStatus() == null || batch.getPurchaseStatus() < 1 || batch.getPurchaseStatus() > 5) { diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchasePriceService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchasePriceService.java new file mode 100644 index 0000000..8c36a3f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchasePriceService.java @@ -0,0 +1,80 @@ +package com.ruoyi.warehouse.service.impl; + +import java.math.BigDecimal; +import java.util.Objects; +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.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.util.PurchasePriceRules; + +@Service +public class PurchasePriceService +{ + @Autowired private PurchaseRequestMapper purchaseRequestMapper; + @Autowired private ProjectBudgetMapper projectBudgetMapper; + @Autowired private IProjectInfoService projectInfoService; + @Autowired private IPurchaseOperationLogService operationLogService; + @Autowired private BusinessNumberService businessNumbers; + + @Transactional + public String lockPrice(Long id) + { + PurchaseRequest existing = purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(id); + if (existing == null) throw new ServiceException("采购明细不存在"); + projectInfoService.requireProjectAccess(existing.getProjectId()); + if (Integer.valueOf(5).equals(existing.getPurchaseStatus())) throw new ServiceException("已取消的采购不能锁价"); + if (Boolean.TRUE.equals(existing.getPriceLocked())) return "已锁定,未重复计费"; + ExpenseCategory category = projectBudgetMapper.selectExpenseCategoryById(existing.getExpenseCategoryId()); + if (category == null || Integer.valueOf(1).equals(category.getStatus())) throw new ServiceException("请填写有效费用分类"); + BigDecimal price = existing.getFinalUnitPrice(); + if (price == null) price = existing.getEstimatedUnitPrice(); + PurchaseRequest updated = new PurchaseRequest(); + updated.setId(existing.getId()); updated.setProjectId(existing.getProjectId()); + updated.setExpenseCategoryId(existing.getExpenseCategoryId()); + updated.setFinalUnitPrice(price); updated.setPriceLocked(true); + updated.setLockedAmount(PurchasePriceRules.amount(existing.getQuantity(), price)); + persist(existing, updated, "PRICE_LOCK"); + return "价格已锁定并计入项目费用"; + } + + /** Called inside the transaction which edits/cancels the locked purchase. */ + public void refreshLockedAmount(PurchaseRequest existing, PurchaseRequest updated, String operation) + { + updated.setPriceLocked(Boolean.TRUE.equals(existing.getPriceLocked())); + if (!Boolean.TRUE.equals(existing.getPriceLocked())) return; + BigDecimal amount = Integer.valueOf(5).equals(updated.getPurchaseStatus()) + ? BigDecimal.ZERO.setScale(6) : PurchasePriceRules.amount(updated.getQuantity(), updated.getFinalUnitPrice()); + updated.setLockedAmount(amount); + if (amount.compareTo(existing.getLockedAmount() == null ? BigDecimal.ZERO : existing.getLockedAmount()) == 0 + && Objects.equals(existing.getProjectId(), updated.getProjectId()) + && Objects.equals(existing.getExpenseCategoryId(), updated.getExpenseCategoryId())) return; + persist(existing, updated, operation); + } + + private void persist(PurchaseRequest existing, PurchaseRequest updated, String operation) + { + if (existing.getLockedAmount() == null) existing.setLockedAmount(BigDecimal.ZERO.setScale(6)); + updated.setLockRevision((existing.getLockRevision() == null ? 0 : existing.getLockRevision()) + 1); + updated.setUpdateBy(SecurityUtils.getUsername()); + projectBudgetMapper.ensureBudget(updated.getProjectId(), updated.getExpenseCategoryId()); + if (purchaseRequestMapper.updatePriceState(updated) != 1) + throw new ServiceException("采购明细已被修改,请刷新后重试"); + String newLedgerNo=businessNumbers.next("FUND"); + String oldLedgerNo=existing.getLockedAmount().signum()!=0 + && (!Objects.equals(existing.getProjectId(),updated.getProjectId()) + || !Objects.equals(existing.getExpenseCategoryId(),updated.getExpenseCategoryId())) + ? businessNumbers.next("FUND") : null; + purchaseRequestMapper.insertPriceLedger(existing, updated, operation, newLedgerNo, oldLedgerNo); + operationLogService.record(existing.getId(), existing.getRequestNo(), operation, + "采购锁定费用变动", "原金额:" + existing.getLockedAmount().toPlainString() + + ";现金额:" + updated.getLockedAmount().toPlainString()); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java index e25b963..7c170d3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseRequestServiceImpl.java @@ -9,7 +9,6 @@ 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.DateUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.project.domain.ExpenseCategory; @@ -29,10 +28,12 @@ import com.ruoyi.warehouse.service.IProductInfoService; import com.ruoyi.warehouse.service.IPurchaseOperationLogService; import com.ruoyi.warehouse.service.IPurchaseRequestService; import com.ruoyi.warehouse.util.WarehouseNoUtils; +import com.ruoyi.warehouse.util.PurchasePriceRules; @Service public class PurchaseRequestServiceImpl implements IPurchaseRequestService { + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private PurchaseRequestMapper purchaseRequestMapper; @@ -57,8 +58,13 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService @Autowired private IProjectBudgetService projectBudgetService; + @Autowired + private PurchasePriceService priceService; + @Autowired private IPurchaseOperationLogService purchaseOperationLogService; + @Autowired private com.ruoyi.project.service.ProjectLoanService loans; + @Autowired private org.springframework.jdbc.core.JdbcTemplate taskDatabase; @Override public List selectPurchaseRequestList(PurchaseRequest purchaseRequest) @@ -84,31 +90,26 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { normalize(purchaseRequest); resolveFunding(purchaseRequest); + resolveProduct(purchaseRequest); validateRequest(purchaseRequest); + validatePurpose(purchaseRequest); purchaseRequest.setApplicantId(SecurityUtils.getUserId()); purchaseRequest.setApplicantName(SecurityUtils.getUsername()); purchaseRequest.setCreateBy(SecurityUtils.getUsername()); purchaseRequest.setPurchaseStatus(0); purchaseRequest.setPurchaseBatchNo(null); purchaseRequest.setProgressRemark(null); - if (StringUtils.isBlank(purchaseRequest.getRequestNo())) - { - purchaseRequest.setRequestNo(generateRequestNo()); - } - else if (purchaseRequestMapper.checkRequestNoUnique(purchaseRequest.getRequestNo()) != null) + if (StringUtils.isNotBlank(purchaseRequest.getRequestNo()) && purchaseRequestMapper.checkRequestNoUnique(purchaseRequest.getRequestNo()) != null) { throw new ServiceException("申请单号已存在"); } - resolveProduct(purchaseRequest); + purchaseRequest.setRequestNo(businessNumbers.reserve("PR",null,StringUtils.isBlank(purchaseRequest.getRequestNo())?null:"request:"+purchaseRequest.getRequestNo())); + if(purchaseRequestMapper.checkRequestNoUnique(purchaseRequest.getRequestNo())!=null)throw new ServiceException("该采购明细已提交,请勿重复导入"); int rows = purchaseRequestMapper.insertPurchaseRequest(purchaseRequest); - projectBudgetService.changeCommitment(purchaseRequest.getProjectId(), purchaseRequest.getExpenseCategoryId(), - purchaseRequest.getEstimatedAmount(), "PURCHASE_COMMIT", purchaseRequest.getId(), - purchaseRequest.getRequestNo(), "PURCHASE:" + purchaseRequest.getId() + ":CREATE", - "采购申请占用经费"); purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(), "CREATE", "创建采购申请", "物料:" + purchaseRequest.getMaterialName() + ";数量:" + decimalText(purchaseRequest.getQuantity()) + unitText(purchaseRequest.getUnit()) - + ";预计金额:¥" + money(purchaseRequest.getEstimatedAmount()).toPlainString()); + + ";采购金额:" + (purchaseRequest.getEstimatedAmount() == null ? "待定价" : "¥" + money(purchaseRequest.getEstimatedAmount()).toPlainString())); return rows; } @@ -120,11 +121,14 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("采购申请ID不能为空"); } - PurchaseRequest existing = requireRequest(purchaseRequest.getId()); - checkOwnerOrManager(existing); + PurchaseRequest existing = requireRequestForUpdate(purchaseRequest.getId()); + if(existing.getProductionTaskId()!=null)purchaseRequest.setProductionTaskId(existing.getProductionTaskId()); + if (purchaseRequest.getPurchasePurpose()==null) { purchaseRequest.setPurchasePurpose(existing.getPurchasePurpose()); purchaseRequest.setLoanId(existing.getLoanId()); } normalize(purchaseRequest); resolveFunding(purchaseRequest); + resolveProduct(purchaseRequest); validateRequest(purchaseRequest); + validatePurpose(purchaseRequest); BigDecimal activeArrivalQuantity = purchaseArrivalMapper.selectActiveQuantityByRequestId(existing.getId()); if (activeArrivalQuantity.compareTo(purchaseRequest.getQuantity()) > 0) @@ -135,13 +139,17 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("已有到货记录,不能更换采购物料"); } - if (activeArrivalQuantity.signum() > 0 + int confirmedInbound = purchaseRequestMapper.countConfirmedInbound(existing.getId()); + PurchasePriceRules.requireEditablePrice(confirmedInbound, + existing.getFinalUnitPrice(), purchaseRequest.getFinalUnitPrice()); + if (confirmedInbound > 0 && (!Objects.equals(existing.getProjectId(), purchaseRequest.getProjectId()) - || !Objects.equals(existing.getExpenseCategoryId(), purchaseRequest.getExpenseCategoryId()) - || money(existing.getEstimatedUnitPrice()).compareTo(money(purchaseRequest.getEstimatedUnitPrice())) != 0)) + || !Objects.equals(existing.getExpenseCategoryId(), purchaseRequest.getExpenseCategoryId()))) { - throw new ServiceException("已有到货记录,不能更换项目、经费科目或预计单价"); + throw new ServiceException("已入库的采购不能更改归属,请先逐步退回至待入库"); } + if (confirmedInbound>0 && (!Objects.equals(existing.getPurchasePurpose(),purchaseRequest.getPurchasePurpose()) || !Objects.equals(existing.getLoanId(),purchaseRequest.getLoanId()))) + throw new ServiceException("已入库的采购不能更改使用或归还用途,请先逐步退回至待入库"); if (StringUtils.isBlank(purchaseRequest.getRequestNo())) { @@ -161,11 +169,10 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService purchaseRequest.setPurchaseBatchNo(existing.getPurchaseBatchNo()); purchaseRequest.setProgressRemark(existing.getProgressRemark()); purchaseRequest.setUpdateBy(SecurityUtils.getUsername()); - resolveProduct(purchaseRequest); int rows = purchaseRequestMapper.updatePurchaseRequest(purchaseRequest, currentApplicantScope()); if (rows == 0) { - throw new ServiceException("无权修改其他员工的采购申请"); + throw new ServiceException("采购明细已变化,请刷新后重试"); } adjustPurchaseCommitment(existing, purchaseRequest); purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(), "UPDATE", @@ -181,27 +188,25 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("请选择采购申请"); } + ids = java.util.Arrays.stream(ids).distinct().toArray(Long[]::new); for (Long id : ids) { - PurchaseRequest request = requireRequest(id); - checkOwnerOrManager(request); - if (purchaseArrivalMapper.countByRequestId(id) > 0) + PurchaseRequest request = requireRequestForUpdate(id); + if (purchaseArrivalMapper.selectActiveQuantityByRequestId(id).signum() > 0) { throw new ServiceException("申请 " + request.getRequestNo() + " 已有到货记录,不能删除"); } - if (!Integer.valueOf(5).equals(request.getPurchaseStatus())) - { - projectBudgetService.changeCommitment(request.getProjectId(), request.getExpenseCategoryId(), - money(request.getEstimatedAmount()).negate(), "PURCHASE_DELETE_RELEASE", request.getId(), - request.getRequestNo(), "PURCHASE:" + request.getId() + ":DELETE", "删除采购申请释放经费"); - } + PurchaseRequest cancelled = new PurchaseRequest(); + org.springframework.beans.BeanUtils.copyProperties(request, cancelled); + cancelled.setPurchaseStatus(5); + priceService.refreshLockedAmount(request, cancelled, "PURCHASE_DELETE"); purchaseOperationLogService.record(request.getId(), request.getRequestNo(), "DELETE", "删除采购申请", "物料:" + request.getMaterialName()); } int rows = purchaseRequestMapper.deletePurchaseRequestByIds(ids, currentApplicantScope()); if (rows != ids.length) { - throw new ServiceException("只能删除自己的采购申请"); + throw new ServiceException("采购明细已变化,删除未完成,请刷新后重试"); } return rows; } @@ -210,8 +215,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService @Transactional public int updatePurchaseStatus(Long id, PurchaseStatusUpdateRequest request) { - PurchaseRequest existing = requireRequest(id); - checkOwnerOrManager(existing); + PurchaseRequest existing = requireRequestForUpdate(id); Integer status = request.getPurchaseStatus(); if (status == null || (status != 0 && status != 1 && status != 2 && status != 5)) { @@ -225,18 +229,10 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("已有待验收或已验收到货,不能取消采购申请"); } - if (!Integer.valueOf(5).equals(existing.getPurchaseStatus()) && Integer.valueOf(5).equals(status)) - { - projectBudgetService.changeCommitment(existing.getProjectId(), existing.getExpenseCategoryId(), - money(existing.getEstimatedAmount()).negate(), "PURCHASE_CANCEL_RELEASE", existing.getId(), - existing.getRequestNo(), "PURCHASE:" + existing.getId() + ":CANCEL", "取消采购释放经费"); - } - else if (Integer.valueOf(5).equals(existing.getPurchaseStatus()) && !Integer.valueOf(5).equals(status)) - { - projectBudgetService.changeCommitment(existing.getProjectId(), existing.getExpenseCategoryId(), - money(existing.getEstimatedAmount()), "PURCHASE_REOPEN_COMMIT", existing.getId(), - existing.getRequestNo(), null, "恢复采购重新占用经费"); - } + PurchaseRequest updated = new PurchaseRequest(); + org.springframework.beans.BeanUtils.copyProperties(existing, updated); + updated.setPurchaseStatus(status); + priceService.refreshLockedAmount(existing, updated, "PURCHASE_STATUS"); int rows = purchaseRequestMapper.updatePurchaseStatus(id, status, trimToNull(request.getProgressRemark()), SecurityUtils.getUsername()); if (rows > 0) @@ -280,6 +276,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService @Transactional public String importPurchaseRequest(List requestList, String username) { + for(var row:previewImport(requestList))if(row.get("error")!=null)throw new ServiceException("第"+row.get("line")+"行:"+row.get("error")); if (requestList == null || requestList.isEmpty()) { throw new ServiceException("导入数据不能为空"); @@ -318,23 +315,22 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService } return request; } - - private void checkOwnerOrManager(PurchaseRequest request) - { - if (!isPurchaseManager() && !SecurityUtils.getUserId().equals(request.getApplicantId())) - { - throw new ServiceException("无权操作其他员工的采购申请"); - } - } - - private boolean isPurchaseManager() - { - return SecurityUtils.isAdmin() || SecurityUtils.hasPermi("warehouse:purchase:manage"); + @Override public List> previewImport(List rows){ + if(rows==null||rows.isEmpty()||rows.size()>2000)throw new ServiceException("请上传1至2000行采购明细"); + var result=new java.util.ArrayList>();var seen=new java.util.HashSet();int line=1; + for(var row:rows){String error=null;try{normalize(row);resolveFunding(row);resolveProduct(row);validateRequest(row);validatePurpose(row);String signature=java.util.Arrays.asList(row.getProjectId(),row.getProductId(),row.getExpenseCategoryId(),row.getQuantity(),row.getFinalUnitPrice(),row.getPurchasePurpose(),row.getLoanId()).toString();if(!seen.add(signature))throw new ServiceException("文件内存在完全相同的采购行,请核对是否重复");}catch(Exception e){error=e.getMessage();}var item=new java.util.LinkedHashMap();item.put("line",++line);item.put("summary",row.getProjectCode()+" / "+row.getMaterialName()+" / "+row.getQuantity());item.put("error",error);result.add(item);}return result; } private Long currentApplicantScope() { - return isPurchaseManager() ? null : SecurityUtils.getUserId(); + return null; + } + + private PurchaseRequest requireRequestForUpdate(Long id) + { + PurchaseRequest request = purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(id); + if (request == null) throw new ServiceException("采购明细不存在"); + return request; } private void normalize(PurchaseRequest request) @@ -362,6 +358,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("物料名称不能为空"); } + if (StringUtils.isBlank(request.getCategory()))throw new ServiceException("请选择物品类别;档案缺少类别时请先补全"); if (request.getQuantity() == null || request.getQuantity().signum() <= 0) { throw new ServiceException("需求数量必须大于0"); @@ -370,9 +367,14 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("采购项目和经费科目不能为空"); } - if (request.getEstimatedUnitPrice() == null || request.getEstimatedUnitPrice().signum() <= 0) + if (request.getFinalUnitPrice() != null && request.getFinalUnitPrice().signum() < 0) { - throw new ServiceException("预计含税单价必须大于0"); + throw new ServiceException("最终单价不能小于0"); + } + if (request.getQuantity().stripTrailingZeros().scale() > 4 + || request.getFinalUnitPrice() != null && request.getFinalUnitPrice().stripTrailingZeros().scale() > 6) + { + throw new ServiceException("数量最多4位小数,单价最多6位小数"); } if (StringUtils.isNotBlank(request.getPurchaseLink()) && !request.getPurchaseLink().matches("(?i)^https?://.+")) @@ -381,6 +383,31 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService } } + private void validatePurpose(PurchaseRequest request) { + if(request.getProductionTaskId()!=null&&taskDatabase.queryForObject("select count(*) from production_task where id=? and project_id=?",Long.class,request.getProductionTaskId(),request.getProjectId())!=1L) + throw new ServiceException("生产任务与采购项目不一致"); + if (StringUtils.isBlank(request.getPurchasePurpose())) request.setPurchasePurpose("SELF"); + if ("SELF".equals(request.getPurchasePurpose())) request.setLoanId(null); + else if ("REPAY".equals(request.getPurchasePurpose())) { + var loan=loans.validatePurchase(request.getLoanId(),request.getProjectId(),request.getProductId()); + BigDecimal already=request.getId()==null?BigDecimal.ZERO:taskDatabase.queryForObject("select coalesce(sum(in_num),0) from in_record where purchase_request_id=? and in_status=1 and receipt_root=0",BigDecimal.class,request.getId()); + if(request.getQuantity().subtract(already).compareTo(loan.getOutstandingQuantity())>0)throw new ServiceException("归还采购数量超过待归还数量,多出部分请拆为自用采购"); + } + else throw new ServiceException("采购用途只能选择本项目使用或归还借用"); + } + @Override @Transactional public int cancelRemaining(Long id,BigDecimal expectedQuantity,String reason){ + PurchaseRequest existing=requireRequestForUpdate(id); + if(StringUtils.isBlank(reason)||reason.length()>300)throw new ServiceException("取消原因必填且最多300字"); + if(Boolean.TRUE.equals(existing.getHistorical()))throw new ServiceException("历史已完成采购没有待取消数量"); + BigDecimal active=purchaseArrivalMapper.selectActiveQuantityByRequestId(id); + if(Integer.valueOf(5).equals(existing.getPurchaseStatus())||existing.getQuantity().compareTo(active)==0)return 1; + if(expectedQuantity==null||expectedQuantity.compareTo(existing.getQuantity())!=0)throw new ServiceException("采购数量已变化,请刷新后重试"); + if(active.signum()==0){var status=new PurchaseStatusUpdateRequest();status.setPurchaseStatus(5);status.setProgressRemark(reason);return updatePurchaseStatus(id,status);} + var updated=new PurchaseRequest();org.springframework.beans.BeanUtils.copyProperties(existing,updated);updated.setQuantity(active);int changed=updatePurchaseRequest(updated); + BigDecimal accepted=purchaseArrivalMapper.selectAcceptedQuantityByRequestId(id); + purchaseRequestMapper.updatePurchaseStatus(id,accepted.compareTo(active)>=0?4:accepted.signum()>0?3:2,existing.getProgressRemark(),SecurityUtils.getUsername()); + purchaseOperationLogService.record(id,existing.getRequestNo(),"CANCEL_REMAINING","取消未到货部分","取消数量:"+existing.getQuantity().subtract(active)+";原因:"+reason);return changed; + } private void resolveFunding(PurchaseRequest request) { ProjectInfo project = null; @@ -417,39 +444,18 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService request.setExpenseCategoryId(category.getId()); request.setExpenseCategoryCode(category.getCategoryCode()); request.setExpenseCategoryName(category.getCategoryName()); - request.setEstimatedUnitPrice(money(request.getEstimatedUnitPrice())); - request.setEstimatedAmount(request.getQuantity().multiply(request.getEstimatedUnitPrice()) - .setScale(2, RoundingMode.HALF_UP)); + BigDecimal finalPrice = request.getFinalUnitPrice() != null + ? request.getFinalUnitPrice() : request.getEstimatedUnitPrice(); + request.setFinalUnitPrice(finalPrice == null ? null : finalPrice.stripTrailingZeros()); + request.setEstimatedUnitPrice(request.getFinalUnitPrice()); + request.setQuantity(request.getQuantity() == null ? null : request.getQuantity().stripTrailingZeros()); + request.setEstimatedAmount(request.getQuantity() == null || finalPrice == null + ? null : request.getQuantity().multiply(finalPrice).setScale(6, RoundingMode.HALF_UP)); } private void adjustPurchaseCommitment(PurchaseRequest existing, PurchaseRequest updated) { - if (Integer.valueOf(5).equals(existing.getPurchaseStatus())) - { - return; - } - BigDecimal oldAmount = money(existing.getEstimatedAmount()); - BigDecimal newAmount = money(updated.getEstimatedAmount()); - if (!Objects.equals(existing.getProjectId(), updated.getProjectId()) - || !Objects.equals(existing.getExpenseCategoryId(), updated.getExpenseCategoryId())) - { - if (oldAmount.signum() != 0) - { - projectBudgetService.changeCommitment(existing.getProjectId(), existing.getExpenseCategoryId(), - oldAmount.negate(), "PURCHASE_MOVE_RELEASE", existing.getId(), existing.getRequestNo(), - null, "采购申请更换项目或科目,释放原占用"); - } - projectBudgetService.changeCommitment(updated.getProjectId(), updated.getExpenseCategoryId(), - newAmount, "PURCHASE_MOVE_COMMIT", updated.getId(), updated.getRequestNo(), - null, "采购申请更换项目或科目,重新占用"); - return; - } - BigDecimal delta = newAmount.subtract(oldAmount); - if (delta.signum() != 0) - { - projectBudgetService.changeCommitment(updated.getProjectId(), updated.getExpenseCategoryId(), delta, - "PURCHASE_COMMIT_ADJUST", updated.getId(), updated.getRequestNo(), null, "调整采购预计金额"); - } + priceService.refreshLockedAmount(existing, updated, "PURCHASE_EDIT"); } private BigDecimal money(BigDecimal value) @@ -466,9 +472,9 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService appendChange(changes, "参数规格", existing.getMaterialParams(), updated.getMaterialParams()); appendChange(changes, "数量", decimalText(existing.getQuantity()) + unitText(existing.getUnit()), decimalText(updated.getQuantity()) + unitText(updated.getUnit())); - appendChange(changes, "预计单价", moneyText(existing.getEstimatedUnitPrice()), + appendChange(changes, "最终单价", moneyText(existing.getEstimatedUnitPrice()), moneyText(updated.getEstimatedUnitPrice())); - appendChange(changes, "预计金额", moneyText(existing.getEstimatedAmount()), + appendChange(changes, "采购金额", moneyText(existing.getEstimatedAmount()), moneyText(updated.getEstimatedAmount())); if (!Objects.equals(existing.getProjectId(), updated.getProjectId())) { @@ -478,7 +484,6 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { changes.add("经费科目已调整"); } - appendChange(changes, "期望到货", dateText(existing.getExpectedDate()), dateText(updated.getExpectedDate())); if (!Objects.equals(trimToNull(existing.getPurchaseLink()), trimToNull(updated.getPurchaseLink()))) { changes.add("采购链接已修改"); @@ -518,11 +523,6 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService return "¥" + money(value).toPlainString(); } - private String dateText(java.util.Date value) - { - return value == null ? null : DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, value); - } - private String statusText(Integer status) { if (status == null) return "未知"; @@ -557,29 +557,20 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService { throw new ServiceException("选择的产品信息不存在"); } - if (sameProduct(draft, selected)) - { - product = selected; - } + product = selected; } if (product == null) { product = resolveProductByCode(draft); } - if (product == null && StringUtils.isBlank(draft.getCategory())) - { - draft.setCategory(productInfoService.inferProductCategory(draft)); - request.setCategory(draft.getCategory()); - } if (product == null) { product = productInfoMapper.checkProductInfoUnique(draft); } if (product == null) { - productInfoService.insertProductInfo(draft); - product = draft; + throw new ServiceException("未匹配到物品档案,请先建立物品并选择;采购不会自动新建或猜测物品"); } request.setProductId(product.getId()); @@ -653,6 +644,6 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService private String generateRequestNo() { - return WarehouseNoUtils.next("PR"); + return businessNumbers.next("PR"); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java new file mode 100644 index 0000000..2d49ec4 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseReturnService.java @@ -0,0 +1,36 @@ +package com.ruoyi.warehouse.service.impl; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +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.warehouse.mapper.*; + +@Service +public class PurchaseReturnService { + @Autowired private JdbcTemplate db; + @Autowired private InventoryCostJournal journal; + @Autowired private PurchaseRequestMapper purchases; + @Autowired private PurchaseArrivalMapper arrivals; + @Autowired private InRecordMapper receipts; + @Autowired private PurchasePriceService prices; + public record Request(Long arrivalId,BigDecimal quantity,boolean cancelPurchase,LocalDate date,String remark,String key){} + @Transactional public void returnGoods(Request r){ + journal.lockInventory();if(r.key()==null||r.key().isBlank()||r.key().length()>120||r.quantity()==null||r.quantity().signum()<=0||r.quantity().stripTrailingZeros().scale()>4)throw new ServiceException("请填写有效数量并重新打开退货窗口"); + var arrival=arrivals.selectPurchaseArrivalByIdForUpdate(r.arrivalId());if(arrival==null||!Integer.valueOf(1).equals(arrival.getAcceptanceStatus()))throw new ServiceException("请选择已验收的到货记录"); + var purchase=purchases.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId());var dup=db.queryForList("select * from purchase_return where business_key=?",r.key());if(!dup.isEmpty()){var d=dup.get(0);boolean cancel=Boolean.TRUE.equals(d.get("cancel_purchase"))||"1".equals(String.valueOf(d.get("cancel_purchase")));if(((Number)d.get("arrival_id")).longValue()!=r.arrivalId()||new BigDecimal(d.get("quantity").toString()).compareTo(r.quantity())!=0||cancel!=r.cancelPurchase())throw new ServiceException("重复退货内容不一致");return;} + var root=receipts.selectInRecordByArrivalIdForUpdate(r.arrivalId());if(root==null||!Boolean.TRUE.equals(root.getReceiptRoot()))throw new ServiceException("该历史验收未建立分次入库来源,请先核对历史记录"); + BigDecimal received=receipts.receivedQuantity(root.getId()),pending=root.getInNum().subtract(received);if(r.quantity().compareTo(pending)>0)throw new ServiceException("退货超过待入库数量,请先撤销对应入库"); + BigDecimal remaining=root.getInNum().subtract(r.quantity());db.update("update in_record set in_num=?,in_status=?,update_time=current_timestamp where id=?",remaining,remaining.compareTo(received)==0?1:0,root.getId()); + db.update("update purchase_arrival set returned_quantity=returned_quantity+?,update_time=current_timestamp where id=?",r.quantity(),r.arrivalId()); + db.update("insert into purchase_return(business_key,arrival_id,quantity,cancel_purchase,business_date,remark,create_by) values(?,?,?,?,?,?,?)",r.key(),r.arrivalId(),r.quantity(),r.cancelPurchase(),r.date()==null?LocalDate.now():r.date(),r.remark(),SecurityUtils.getUsername()); + BigDecimal quantity=r.cancelPurchase()?purchase.getQuantity().subtract(r.quantity()):purchase.getQuantity();BigDecimal accepted=arrivals.selectAcceptedQuantityByRequestId(purchase.getId());int status=quantity.signum()==0?5:accepted.compareTo(quantity)>=0?4:accepted.signum()>0?3:2; + db.update("update purchase_request set quantity=?,purchase_status=?,update_time=current_timestamp where id=?",quantity,status,purchase.getId());var updated=purchases.selectPurchaseRequestByIdForUpdate(purchase.getId());prices.refreshLockedAmount(purchase,updated,"PURCHASE_RETURN"); + } + public List> history(Long arrivalId){return db.queryForList("select * from purchase_return where arrival_id=? order by id desc",arrivalId);} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java new file mode 100644 index 0000000..e66bd2d --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSheetService.java @@ -0,0 +1,227 @@ +package com.ruoyi.warehouse.service.impl; + +import java.util.*; +import java.security.MessageDigest; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +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.warehouse.domain.*; +import com.ruoyi.warehouse.mapper.*; +import com.ruoyi.warehouse.service.*; + +@Service +public class PurchaseSheetService +{ + @Autowired private PurchaseBatchMapper batches; + @Autowired private PurchaseRequestMapper requests; + @Autowired private ProductInfoMapper catalog; + @Autowired private IProductInfoService products; + @Autowired private IPurchaseRequestService purchases; + @Autowired private PurchasePriceService prices; + @Autowired private SupplierService suppliers; + @Autowired private CatalogWriteLock catalogLock; + @Autowired private PurchaseBatchNumber batchNumbers; + @Autowired private JdbcTemplate jdbc; + @Autowired private ObjectMapper json; + @Autowired private com.ruoyi.system.service.ISysDictTypeService dictTypes; + + @Transactional(readOnly = true, isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ) + public PurchaseSheet load(Long id) + { + PurchaseBatch batch = batches.selectPurchaseBatchById(id); + if (batch == null) throw new ServiceException("采购批次不存在"); + List rows = requests.selectPurchaseSheetRows(id); + rows.sort(Comparator.comparing(PurchaseRequest::getId)); + PurchaseSheet result = new PurchaseSheet(); + result.setBatch(batch); result.setRows(rows); result.setDeletedIds(List.of()); + result.setVersion(version(batch, rows)); + return result; + } + + @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) + public PurchaseSheet save(PurchaseSheet sheet) + { + if (sheet == null || sheet.getBatch() == null || sheet.getRows() == null + || sheet.getRows().size() > 2000 || sheet.getBatch().getId() == null && sheet.getRows().isEmpty()) + throw new ServiceException("请填写1至2000行采购明细"); + PurchaseBatch batch = sheet.getBatch(); + requirePermission(batch.getId() == null ? "add" : "edit"); + catalogLock.acquire(); + List oldRows = List.of(); + PurchaseBatch oldBatch = null; + if (batch.getId() != null) { + lockBatch(batch.getId()); + oldBatch = batches.selectPurchaseBatchById(batch.getId()); + oldRows = requests.selectPurchaseSheetRows(batch.getId()); + oldRows.sort(Comparator.comparing(PurchaseRequest::getId)); + for (PurchaseRequest row : oldRows) requests.selectPurchaseRequestByIdForUpdate(row.getId()); + // Re-read after obtaining locks so a concurrent receipt or single-line edit is detected. + oldRows = requests.selectPurchaseSheetRows(batch.getId()); + oldRows.sort(Comparator.comparing(PurchaseRequest::getId)); + if (!Objects.equals(sheet.getVersion(), version(oldBatch, oldRows))) + throw new ServiceException("该批次已被其他操作更新,请重新打开后再保存"); + } + Map old = new LinkedHashMap<>(); + oldRows.forEach(row -> old.put(row.getId(), row)); + Set submitted = new HashSet<>(); + for (PurchaseRequest row : sheet.getRows()) { + if (row == null) throw new ServiceException("采购明细不能为空"); + if (row.getId() != null && (!old.containsKey(row.getId()) || !submitted.add(row.getId()))) + throw new ServiceException("采购明细不属于当前批次或重复提交"); + if (row.getId() == null) requirePermission("add"); + } + List deleted = sheet.getDeletedIds() == null ? List.of() : sheet.getDeletedIds(); + for (Long id : deleted) { + if (!old.containsKey(id) || !submitted.add(id)) throw new ServiceException("删除明细不属于当前批次或重复提交"); + requirePermission("remove"); + } + if (!submitted.equals(old.keySet())) throw new ServiceException("采购明细不完整,请重新打开批次"); + // A saved preparation list may not have a supplier until the quote is confirmed. + if (batch.getSupplierId() != null) suppliers.requireActive(batch.getSupplierId()); + if (oldBatch != null && oldBatch.getSupplierId() != null && !Objects.equals(batch.getSupplierId(), oldBatch.getSupplierId()) + && oldRows.stream().anyMatch(this::committed)) + throw new ServiceException("已确认采购或已有到货的批次不能更换供应商"); + if (oldBatch == null) { + if (batch.getBusinessDate() == null) batch.setBusinessDate(java.time.LocalDate.now()); + batch.setBatchNo(batchNumbers.next(batch.getBusinessDate())); batch.setPurchaseStatus(1); + batch.setCreateBy(SecurityUtils.getUsername()); + if (batch.getBusinessDate() == null) batch.setBusinessDate(java.time.LocalDate.now()); + batches.insertPurchaseBatch(batch); + } else { + batch.setBatchNo(oldBatch.getBatchNo()); batch.setPurchaseStatus(oldBatch.getPurchaseStatus()); + batch.setUpdateBy(SecurityUtils.getUsername()); + batches.updatePurchaseBatch(batch); + } + List items = new ArrayList<>(catalog.selectProductInfoAll()); + int line = 0; + for (PurchaseRequest row : sheet.getRows()) { + line++; + PurchaseRequest existing = old.get(row.getId()); + if (existing != null && sameEditable(existing, row)) continue; + if (existing != null && (Boolean.TRUE.equals(existing.getHistorical()) || Integer.valueOf(5).equals(existing.getPurchaseStatus()))) { + if (!sameEditable(existing, row)) throw new ServiceException("第" + line + "行已完成或取消,不能修改"); + continue; + } + if (existing != null && Boolean.TRUE.equals(existing.getPriceLocked())) { + if (!sameEditable(existing, row)) throw new ServiceException("第" + line + "行已确认采购,请在明细维护中按现有退回规则修改"); + continue; + } + try { + resolveItem(row, items); + row.setPurchaseBatchId(batch.getId()); + row.setEstimatedUnitPrice(row.getFinalUnitPrice()); + if (existing == null) { + row.setRequestNo(null); row.setHistorical(false); + purchases.insertPurchaseRequest(row); + // insertPurchaseRequest intentionally resets the free-text batch number. + jdbc.update("update purchase_request set purchase_batch_id=?,purchase_batch_no=? where id=?", batch.getId(), batch.getBatchNo(), row.getId()); + } else if (!sameEditable(existing, row)) purchases.updatePurchaseRequest(row); + } catch (Exception e) { throw new ServiceException("第" + line + "行:" + e.getMessage()); } + } + if (!deleted.isEmpty()) { + if (deleted.stream().map(old::get).anyMatch(this::committed)) + throw new ServiceException("已确认采购或已有到货的明细不能在表格中删除"); + purchases.deletePurchaseRequestByIds(deleted.toArray(Long[]::new)); + } + return load(batch.getId()); + } + + @Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED) + public PurchaseSheet confirm(Long id, String expectedVersion) + { + requirePermission("edit"); lockBatch(id); + PurchaseSheet sheet = load(id); + for (PurchaseRequest row : sheet.getRows()) requests.selectPurchaseRequestByIdForUpdate(row.getId()); + sheet = load(id); + if (!Objects.equals(expectedVersion, sheet.getVersion())) throw new ServiceException("批次已更新,请刷新后确认"); + suppliers.requireActive(sheet.getBatch().getSupplierId()); + if (sheet.getRows().isEmpty()) throw new ServiceException("批次没有采购明细"); + for (PurchaseRequest row : sheet.getRows()) { + if (Integer.valueOf(5).equals(row.getPurchaseStatus()) || Boolean.TRUE.equals(row.getHistorical())) continue; + prices.lockPrice(row.getId()); + if (Integer.valueOf(0).equals(row.getPurchaseStatus())) { + PurchaseStatusUpdateRequest status = new PurchaseStatusUpdateRequest(); status.setPurchaseStatus(1); + purchases.updatePurchaseStatus(row.getId(), status); + } + } + PurchaseBatch batch = sheet.getBatch(); batch.setPurchaseStatus(2); + batch.setUpdateBy(SecurityUtils.getUsername()); batches.updatePurchaseBatch(batch); + return load(id); + } + + private void resolveItem(PurchaseRequest row, List items) + { + ProductInfo match = null; + for (ProductInfo item : items) if (identity(row).equals(identity(item))) { + if (match != null && row.getProductId() == null) throw new ServiceException("相同名称、品牌、规格存在多份档案,请从物品档案明确选择编码"); + match = item; + } + if (row.getProductId() != null) { + ProductInfo selected = items.stream().filter(p -> p.getId().equals(row.getProductId())).findFirst().orElse(null); + if (selected == null || !identity(row).equals(identity(selected))) throw new ServiceException("物品选择已失效,请重新选择品牌和规格"); + match = selected; + } + if (match == null) { + if (norm(row.getMaterialName()).isEmpty() || norm(row.getUnit()).isEmpty()) throw new ServiceException("物品名称和单位必填"); + if (norm(row.getCategory()).isEmpty()) throw new ServiceException("请选择物品类别"); + if (dictTypes.selectDictDataByType("wms_item_unit").stream() + .noneMatch(unit -> "0".equals(unit.getStatus()) && norm(unit.getDictLabel()).equals(norm(row.getUnit())))) + throw new ServiceException("新物品请选择字典中的单位"); + if (row.getMaterialName().length() > 100 || text(row.getMaterialBrand()).length() > 100 + || text(row.getMaterialParams()).length() > 500) throw new ServiceException("物品名称、品牌或规格过长"); + match = new ProductInfo(); match.setProductName(clean(row.getMaterialName())); + match.setBrand(clean(row.getMaterialBrand())); match.setSpec(clean(row.getMaterialParams())); + match.setUnit(clean(row.getUnit())); match.setCategory(clean(row.getCategory())); + products.insertProductInfo(match); items.add(match); + } else if (!norm(row.getUnit()).isEmpty() && !norm(row.getUnit()).equals(norm(match.getUnit()))) { + throw new ServiceException("单位与物品档案不一致,不能将不同单位混用"); + } + if(norm(match.getCategory()).isEmpty()) { + if(norm(row.getCategory()).isEmpty())throw new ServiceException("请选择物品类别"); + match.setCategory(clean(row.getCategory())); products.updateProductInfo(match); + } + row.setProductId(match.getId()); row.setProductCode(match.getProductCode()); + row.setMaterialName(match.getProductName()); row.setMaterialBrand(match.getBrand()); + row.setMaterialParams(match.getSpec()); row.setCategory(match.getCategory()); row.setUnit(match.getUnit()); + } + + static List identity(PurchaseRequest row) { return List.of(norm(row.getMaterialName()), norm(row.getMaterialBrand()), norm(row.getMaterialParams())); } + static List identity(ProductInfo row) { return List.of(norm(row.getProductName()), norm(row.getBrand()), norm(row.getSpec())); } + private static String text(String value) { return value == null ? "" : value; } + private static String clean(String value) { return text(value).trim().replaceAll("\\s+", " "); } + private static String norm(String value) { return clean(value).toLowerCase(Locale.ROOT); } + private boolean committed(PurchaseRequest row) { + return Boolean.TRUE.equals(row.getPriceLocked()) || Boolean.TRUE.equals(row.getHistorical()) + || row.getAcceptedQuantity() != null && row.getAcceptedQuantity().signum() > 0 + || row.getPendingArrivalQuantity() != null && row.getPendingArrivalQuantity().signum() > 0; + } + private boolean sameEditable(PurchaseRequest a, PurchaseRequest b) { + return identity(a).equals(identity(b)) && Objects.equals(a.getProjectId(), b.getProjectId()) + && Objects.equals(a.getExpenseCategoryId(), b.getExpenseCategoryId()) + && Objects.equals(a.getProductionTaskId(), b.getProductionTaskId()) + && Objects.equals(a.getLoanId(), b.getLoanId()) && norm(a.getPurchasePurpose()).equals(norm(b.getPurchasePurpose())) + && norm(a.getUnit()).equals(norm(b.getUnit())) + && norm(a.getCategory()).equals(norm(b.getCategory())) + && decimal(a.getQuantity()).equals(decimal(b.getQuantity())) + && decimal(a.getFinalUnitPrice()).equals(decimal(b.getFinalUnitPrice())) + && text(a.getPurchaseLink()).equals(text(b.getPurchaseLink())) && text(a.getRemark()).equals(text(b.getRemark())); + } + private String decimal(java.math.BigDecimal value) { return value == null ? "" : value.stripTrailingZeros().toPlainString(); } + private String version(PurchaseBatch batch, List rows) { + try { + byte[] bytes = json.writeValueAsBytes(List.of(batch, rows)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception e) { throw new IllegalStateException("Cannot version purchase batch", e); } + } + private void lockBatch(Long id) { + if (jdbc.queryForList("select id from purchase_batch where id=? for update", id).isEmpty()) throw new ServiceException("采购批次不存在"); + } + private void requirePermission(String action) { + if (!SecurityUtils.isAdmin() && !SecurityUtils.hasPermi("warehouse:purchase:manage") + && !SecurityUtils.hasPermi("warehouse:purchase:" + action)) throw new ServiceException("没有相应采购操作权限"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSmartImportServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSmartImportServiceImpl.java index f4f7431..449aff4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSmartImportServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseSmartImportServiceImpl.java @@ -172,7 +172,7 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi + "使用紧凑JSON且不要格式化换行,只返回需要修改或补全的字段,格式:" + "{\"patches\":[{\"rowIndex\":0,\"fields\":{\"字段\":\"新值\"},\"warning\":\"仅有歧义时说明\"}]}。" + "常规补全不要返回warning或inferredFields。允许字段仅为productCode,materialName,materialBrand," - + "category,materialParams,unit,quantity,expectedDate,purchaseLink,productRemark,remark。无修改返回空patches。rows=" + + "category,materialParams,unit,quantity,purchaseLink,productRemark,remark。无修改返回空patches。rows=" + rows.toJSONString() + ",existingCategories=" + existingCategories.toJSONString(); tasks.add(CompletableFuture.supplyAsync(() -> { try @@ -269,7 +269,7 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi JSONArray samples = new JSONArray(); for (int i = 0; i < Math.min(3, rows.size()); i++) samples.add(rows.get(i)); String prompt = "只分析Excel表头映射,不处理每行数据。可用目标字段为productCode,materialName," - + "materialBrand,category,materialParams,unit,quantity,expectedDate,purchaseLink,productRemark,remark。" + + "materialBrand,category,materialParams,unit,quantity,purchaseLink,productRemark,remark。" + "单价、总价、申请人等无关列不要映射。只返回JSON:{\"mapping\":{\"原表头\":\"目标字段\"}}。" + "headers=" + first.keySet() + ", samples=" + samples.toJSONString(); String output = callInventoryModel(JSONArray.of(message("system", "你是Excel表头映射器,只返回JSON对象。"), @@ -496,7 +496,6 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi if (List.of("参数规格", "规格型号", "型号规格", "规格", "型号", "参数", "spec", "model").contains(value)) return "materialParams"; if (List.of("单位", "计量单位", "unit").contains(value)) return "unit"; if (List.of("需求数量", "采购数量", "数量", "qty", "quantity").contains(value)) return "quantity"; - if (List.of("期望到货日期", "期望到货", "预计到货日期", "到货日期", "expecteddate").contains(value)) return "expectedDate"; if (List.of("采购链接", "参考链接", "商品链接", "链接", "url", "purchaselink").contains(value)) return "purchaseLink"; if (List.of("产品备注", "物料备注", "productremark").contains(value)) return "productRemark"; if (List.of("申请备注", "备注", "remark").contains(value)) return "remark"; @@ -506,7 +505,7 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi private boolean isImportField(String field) { return List.of("productCode", "materialName", "materialBrand", "category", "materialParams", "unit", - "quantity", "expectedDate", "purchaseLink", "productRemark", "remark").contains(field); + "quantity", "purchaseLink", "productRemark", "remark").contains(field); } private boolean isIgnoredHeader(String header) @@ -650,7 +649,7 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi private void copyFields(JSONObject source, JSONObject target) { String[] fields = { "productCode", "materialName", "materialBrand", "category", - "materialParams", "unit", "quantity", "expectedDate", "purchaseLink", "productRemark", "remark" }; + "materialParams", "unit", "quantity", "purchaseLink", "productRemark", "remark" }; for (String field : fields) { target.put(field, source.get(field)); @@ -671,7 +670,6 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi if ("materialParams".equals(field)) return "参数规格"; if ("unit".equals(field)) return "单位"; if ("quantity".equals(field)) return "数量"; - if ("expectedDate".equals(field)) return "期望到货日期"; if ("purchaseLink".equals(field)) return "采购链接"; if ("productRemark".equals(field)) return "产品备注"; if ("remark".equals(field)) return "申请备注"; @@ -722,10 +720,10 @@ public class PurchaseSmartImportServiceImpl implements IPurchaseSmartImportServi private String systemPrompt() { return "你是采购清单智能整理器,只返回JSON对象。输出格式为{items:[...]},每项字段必须包含" - + "productId,productCode,materialName,materialBrand,category,materialParams,unit,quantity,expectedDate,purchaseLink,productRemark,remark,inferredFields,warning。" + + "productId,productCode,materialName,materialBrand,category,materialParams,unit,quantity,purchaseLink,productRemark,remark,inferredFields,warning。" + "识别任意中文或英文表头并正确映射,不能因列顺序不同而错位。单价、总价和申请人不是导入字段,不要混入其他字段。" + "参数规格中若含品牌或明确型号,可补全materialBrand;能从知名型号可靠判断品牌时允许推断,否则品牌留空。" - + "category可合理归类,quantity缺失填null,expectedDate统一yyyy-MM-dd。" + + "category可合理归类,quantity缺失填null。" + "优先从existingProducts中选择完全一致的物料并返回其productId和productCode,不要把相似但型号不同的物料关联。" + "inferredFields列出所有不是源表直接提供、而是系统匹配或AI推断得到的字段名;不确定信息写入warning。最多返回100项。"; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockCheckRecordServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockCheckRecordServiceImpl.java index 320ad7c..72701f0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockCheckRecordServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockCheckRecordServiceImpl.java @@ -20,14 +20,13 @@ import com.ruoyi.warehouse.util.WarehouseNoUtils; @Service public class StockCheckRecordServiceImpl implements IStockCheckRecordService { + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private StockCheckRecordMapper stockCheckRecordMapper; - @Autowired - private StockInfoMapper stockInfoMapper; - - @Autowired - private IStockLotService stockLotService; + @Autowired private InventoryCostJournal journal; + @Autowired private com.ruoyi.warehouse.mapper.InventoryCostMapper costs; + @Autowired private com.ruoyi.project.service.IProjectInfoService projects; @Override public List selectStockCheckRecordList(StockCheckRecord stockCheckRecord) @@ -50,25 +49,28 @@ public class StockCheckRecordServiceImpl implements IStockCheckRecordService } @Override - public int insertStockCheckRecord(StockCheckRecord stockCheckRecord) + @Transactional public int insertStockCheckRecord(StockCheckRecord stockCheckRecord) { - if (stockCheckRecord.getRealNum() == null || stockCheckRecord.getRealNum().signum() < 0) + journal.lockInventory(); projects.requireProjectAccess(stockCheckRecord.getProjectId()); + if (stockCheckRecord.getRealNum() == null || stockCheckRecord.getRealNum().signum() < 0 || stockCheckRecord.getRealNum().stripTrailingZeros().scale()>4) { throw new ServiceException("实际盘点数量不能小于0"); } - if (StringUtils.isBlank(stockCheckRecord.getCheckNo())) - { - stockCheckRecord.setCheckNo(WarehouseNoUtils.next("CHK")); - } - else if (!checkCheckNoUnique(stockCheckRecord)) + if (StringUtils.isNotBlank(stockCheckRecord.getCheckNo()) && !checkCheckNoUnique(stockCheckRecord)) { throw new ServiceException("盘点单号已存在"); } - StockInfo stockInfo = stockInfoMapper.selectStockInfoByAreaProduct(stockCheckRecord.getAreaId(), stockCheckRecord.getProductId()); - BigDecimal bookNum = stockInfo == null ? BigDecimal.ZERO : stockInfo.getStockNum(); + stockCheckRecord.setCheckNo(businessNumbers.reserve("CHK",stockCheckRecord.getBusinessDate(),StringUtils.isBlank(stockCheckRecord.getCheckNo())?null:"manual:"+stockCheckRecord.getCheckNo())); + if(!checkCheckNoUnique(stockCheckRecord))throw new ServiceException("该盘点已提交,请刷新记录"); + BigDecimal bookNum = costs.selectAreaQuantity(stockCheckRecord.getProjectId(),stockCheckRecord.getProductId(),stockCheckRecord.getAreaId()); + if (bookNum==null) bookNum=BigDecimal.ZERO; + Integer version=costs.selectAreaVersion(stockCheckRecord.getProjectId(),stockCheckRecord.getProductId(),stockCheckRecord.getAreaId()); + stockCheckRecord.setBookVersion(version==null ? -1 : version); stockCheckRecord.setBookNum(bookNum); stockCheckRecord.setDiffNum(stockCheckRecord.getRealNum().subtract(bookNum)); stockCheckRecord.setCheckStatus(0); + if(stockCheckRecord.getBusinessDate()==null)stockCheckRecord.setBusinessDate(java.time.LocalDate.now()); + if(stockCheckRecord.getRemark()!=null&&stockCheckRecord.getRemark().length()>500)throw new ServiceException("备注最多500字"); return stockCheckRecordMapper.insertStockCheckRecord(stockCheckRecord); } @@ -80,10 +82,12 @@ public class StockCheckRecordServiceImpl implements IStockCheckRecordService { throw new ServiceException("盘点记录不存在"); } - if (Integer.valueOf(1).equals(dbRecord.getCheckStatus())) + if (!Integer.valueOf(0).equals(dbRecord.getCheckStatus())) { throw new ServiceException("已生效盘点记录不能修改"); } + if (stockCheckRecord.getRealNum()==null || stockCheckRecord.getRealNum().signum()<0 || stockCheckRecord.getRealNum().stripTrailingZeros().scale()>4) + throw new ServiceException("实际数量不能为负数,最多4位小数"); stockCheckRecord.setDiffNum(stockCheckRecord.getRealNum().subtract(dbRecord.getBookNum())); return stockCheckRecordMapper.updateStockCheckRecord(stockCheckRecord); } @@ -94,7 +98,7 @@ public class StockCheckRecordServiceImpl implements IStockCheckRecordService for (Long id : ids) { StockCheckRecord dbRecord = stockCheckRecordMapper.selectStockCheckRecordById(id); - if (dbRecord != null && Integer.valueOf(1).equals(dbRecord.getCheckStatus())) + if (dbRecord != null && !Integer.valueOf(0).equals(dbRecord.getCheckStatus())) { throw new ServiceException("已生效盘点记录不能删除"); } @@ -106,26 +110,51 @@ public class StockCheckRecordServiceImpl implements IStockCheckRecordService @Transactional public int confirmStockCheckRecord(Long id, String username) { + journal.lockInventory(); StockCheckRecord checkRecord = stockCheckRecordMapper.selectStockCheckRecordByIdForUpdate(id); if (checkRecord == null) { throw new ServiceException("盘点记录不存在"); } - if (Integer.valueOf(1).equals(checkRecord.getCheckStatus())) + if (!Integer.valueOf(0).equals(checkRecord.getCheckStatus())) { throw new ServiceException("该盘点记录已生效"); } - StockInfo currentStock = stockInfoMapper.selectStockInfoByAreaProductForUpdate( - checkRecord.getAreaId(), checkRecord.getProductId()); - BigDecimal currentQuantity = currentStock == null ? BigDecimal.ZERO : currentStock.getStockNum(); - stockLotService.adjustLots(checkRecord.getAreaId(), checkRecord.getProductId(), - checkRecord.getRealNum().subtract(currentQuantity), checkRecord.getId(), username); - stockInfoMapper.upsertSetStock(checkRecord.getAreaId(), checkRecord.getProductId(), checkRecord.getRealNum()); + projects.requireProjectAccess(checkRecord.getProjectId()); + Integer currentVersion=costs.selectAreaVersion(checkRecord.getProjectId(),checkRecord.getProductId(),checkRecord.getAreaId()); + if (!java.util.Objects.equals(checkRecord.getBookVersion(),currentVersion==null ? -1 : currentVersion)) + throw new ServiceException("盘点后库存已发生变动,请重新盘点,系统未覆盖新库存"); + BigDecimal difference=checkRecord.getRealNum().subtract(checkRecord.getBookNum()); + Long eventId=null; + if (difference.signum()!=0) { + if (StringUtils.isBlank(checkRecord.getReason())) throw new ServiceException("有差异时请填写原因"); + BigDecimal unitCost=checkRecord.getReceiptUnitCost(); + if (difference.signum()>0 && unitCost==null) { + var balance=journal.balance(checkRecord.getProjectId(),checkRecord.getProductId()); + unitCost=balance==null ? null : balance.getAverageUnitCost(); + } + if (difference.signum()>0 && unitCost==null) throw new ServiceException("该物品成本未知,盘盈请填写单位成本"); + var event=journal.append(InventoryCostJournal.details(InventoryCostJournal.event(checkRecord.getProjectId(),checkRecord.getProductId(),checkRecord.getAreaId(), + difference.signum()>0 ? "RECEIPT" : "ISSUE",difference.abs(),difference.signum()>0 ? com.ruoyi.warehouse.util.MovingAverageCost.receiptAmount(difference,unitCost) : null,null,"CHECK:"+id),checkRecord.getBusinessDate(),checkRecord.getRemark())); + eventId=event.getId(); + } StockCheckRecord confirmRecord = new StockCheckRecord(); confirmRecord.setId(id); confirmRecord.setCheckStatus(1); confirmRecord.setConfirmUser(username); confirmRecord.setConfirmTime(new Date()); + confirmRecord.setCostEventId(eventId); return stockCheckRecordMapper.confirmStockCheckRecord(confirmRecord); } + @Override @Transactional public int revoke(Long id,String reason){ + journal.lockInventory(); + if(StringUtils.isBlank(reason)||reason.length()>300)throw new ServiceException("撤销原因必填且最多300字"); + var record=stockCheckRecordMapper.selectStockCheckRecordByIdForUpdate(id); + if(record==null)throw new ServiceException("盘点记录不存在"); + projects.requireProjectAccess(record.getProjectId()); + if(Integer.valueOf(2).equals(record.getCheckStatus()))return 1; + if(!Integer.valueOf(1).equals(record.getCheckStatus()))throw new ServiceException("只能撤销已生效盘点"); + if(record.getCostEventId()!=null)journal.voidLastEvent(record.getCostEventId(),reason); + return stockCheckRecordMapper.revoke(id,reason,com.ruoyi.common.utils.SecurityUtils.getUsername()); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockInfoServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockInfoServiceImpl.java index 239c95a..a9398ef 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockInfoServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockInfoServiceImpl.java @@ -159,6 +159,9 @@ public class StockInfoServiceImpl implements IStockInfoService throw new ServiceException("库存记录不存在"); } outRecord.setId(null); + if (outRecord.getUsageProjectId()!=null && !outRecord.getUsageProjectId().equals(stockInfo.getProjectId())) + throw new ServiceException("只能领用本项目库存,跨项目使用请先办理借用"); + outRecord.setUsageProjectId(stockInfo.getProjectId()); outRecord.setAreaId(stockInfo.getAreaId()); outRecord.setProductId(stockInfo.getProductId()); return outRecordService.insertOutRecord(outRecord); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockLotServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockLotServiceImpl.java index 407b815..6a02521 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockLotServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/StockLotServiceImpl.java @@ -24,6 +24,7 @@ import com.ruoyi.warehouse.util.WarehouseNoUtils; @Service public class StockLotServiceImpl implements IStockLotService { + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private StockLotMapper stockLotMapper; @@ -39,6 +40,9 @@ public class StockLotServiceImpl implements IStockLotService @Autowired private IProjectInfoService projectInfoService; + @Autowired + private com.ruoyi.warehouse.mapper.PurchaseRequestMapper purchaseRequestMapper; + @Override public List selectStockLotList(StockLot lot) { @@ -48,7 +52,8 @@ public class StockLotServiceImpl implements IStockLotService @Override public void createInboundLot(InRecord inRecord, String username) { - if (stockLotMapper.selectStockLotByInRecordId(inRecord.getId()) != null) + StockLot previous = stockLotMapper.selectStockLotByInRecordId(inRecord.getId()); + if (previous != null && !Integer.valueOf(3).equals(previous.getLotStatus())) { return; } @@ -63,8 +68,16 @@ public class StockLotServiceImpl implements IStockLotService ExpenseCategory legacy = projectBudgetMapper.selectExpenseCategoryByCode("LEGACY"); categoryId = legacy == null ? null : legacy.getId(); } - BigDecimal unitCost = BigDecimal.ZERO.setScale(2); - if (inRecord.getArrivalId() != null) + BigDecimal unitCost = BigDecimal.ZERO.setScale(6); + if (inRecord.getPurchaseRequestId() != null) + { + com.ruoyi.warehouse.domain.PurchaseRequest purchase = purchaseRequestMapper + .selectPurchaseRequestById(inRecord.getPurchaseRequestId(), null); + if (purchase == null || !Boolean.TRUE.equals(purchase.getPriceLocked()) || purchase.getFinalUnitPrice() == null) + throw new ServiceException("采购尚未锁价,不能入库"); + unitCost = purchase.getFinalUnitPrice().setScale(6, RoundingMode.HALF_UP); + } + else if (inRecord.getArrivalId() != null) { PurchaseArrival arrival = purchaseArrivalMapper.selectPurchaseArrivalById(inRecord.getArrivalId()); if (arrival != null && arrival.getActualUnitPrice() != null) @@ -73,7 +86,7 @@ public class StockLotServiceImpl implements IStockLotService } } StockLot lot = new StockLot(); - lot.setLotNo(WarehouseNoUtils.next("LOT")); + lot.setLotNo(businessNumbers.next("LOT")); lot.setAreaId(inRecord.getAreaId()); lot.setProductId(inRecord.getProductId()); lot.setSourceProjectId(sourceProjectId); @@ -87,7 +100,13 @@ public class StockLotServiceImpl implements IStockLotService lot.setLotStatus(0); lot.setRemark("入库单:" + inRecord.getInNo()); lot.setCreateBy(username); - stockLotMapper.insertStockLot(lot); + if (previous == null) stockLotMapper.insertStockLot(lot); + else + { + lot.setId(previous.getId()); lot.setUpdateBy(username); + if (stockLotMapper.reactivateInboundLot(lot) != 1) + throw new ServiceException("来源库存状态已变化,请刷新后重试"); + } } @Override @@ -153,7 +172,7 @@ public class StockLotServiceImpl implements IStockLotService { ExpenseCategory legacy = projectBudgetMapper.selectExpenseCategoryByCode("LEGACY"); StockLot lot = new StockLot(); - lot.setLotNo(WarehouseNoUtils.next("ADJ")); + lot.setLotNo(businessNumbers.next("ADJ")); lot.setAreaId(areaId); lot.setProductId(productId); lot.setSourceProjectId(projectInfoService.selectLegacyProjectId()); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/SupplierService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/SupplierService.java new file mode 100644 index 0000000..8e69cad --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/SupplierService.java @@ -0,0 +1,28 @@ +package com.ruoyi.warehouse.service.impl; + +import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.common.utils.SecurityUtils; + +@Service +public class SupplierService { + @Autowired private JdbcTemplate db; + public record Supplier(Long id,String name,String contact,String phone,String remark,Integer version){} + public List> list(String keyword){return db.queryForList("select * from supplier_info where active=1 and (? is null or name like concat('%',?,'%')) order by name",keyword,keyword);} + @Transactional public void save(Supplier r){ + String name=r.name()==null?"":r.name().trim();if(name.isEmpty()||name.length()>200)throw new ServiceException("供应商名称必填,最多200字"); + if(r.contact()!=null&&r.contact().length()>100||r.phone()!=null&&r.phone().length()>100||r.remark()!=null&&r.remark().length()>500)throw new ServiceException("联系方式或备注过长"); + if(r.id()==null)db.update("insert into supplier_info(name,contact,phone,remark,create_by) values(?,?,?,?,?)",name,r.contact(),r.phone(),r.remark(),SecurityUtils.getUsername()); + else if(db.update("update supplier_info set name=?,contact=?,phone=?,remark=?,version=version+1,update_by=?,update_time=current_timestamp where id=? and version=? and active=1",name,r.contact(),r.phone(),r.remark(),SecurityUtils.getUsername(),r.id(),r.version())!=1)throw new ServiceException("供应商已变化,请刷新"); + } + @Transactional public void remove(Long id){ + if(db.queryForList("select id from supplier_info where id=? and active=1 for update",id).isEmpty())throw new ServiceException("供应商不存在"); + if(db.queryForObject("select count(*) from purchase_batch where supplier_id=?",Long.class,id)>0)throw new ServiceException("该供应商已有采购批次,请保留历史资料"); + db.update("update supplier_info set active=0,version=version+1,update_by=?,update_time=current_timestamp where id=?",SecurityUtils.getUsername(),id); + } + public void requireActive(Long id){if(id==null||db.queryForList("select id from supplier_info where id=? and active=1 for update",id).isEmpty())throw new ServiceException("请选择有效供应商");} +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseAreaServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseAreaServiceImpl.java index fa6fb0b..35e56bf 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseAreaServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseAreaServiceImpl.java @@ -12,8 +12,11 @@ import com.ruoyi.warehouse.service.IWarehouseAreaService; @Service public class WarehouseAreaServiceImpl implements IWarehouseAreaService { + @Autowired private BusinessNumberService businessNumbers; @Autowired private WarehouseAreaMapper warehouseAreaMapper; + @Autowired private InventoryCostJournal journal; + @Autowired private org.springframework.jdbc.core.JdbcTemplate db; @Override public List selectWarehouseAreaList(WarehouseArea warehouseArea) @@ -48,22 +51,38 @@ public class WarehouseAreaServiceImpl implements IWarehouseAreaService @Override public int insertWarehouseArea(WarehouseArea warehouseArea) { - normalizeAreaCode(warehouseArea); + warehouseArea.setStatus(0); + warehouseArea.setAreaCode(businessNumbers.next("AREA")); return warehouseAreaMapper.insertWarehouseArea(warehouseArea); } @Override + @org.springframework.transaction.annotation.Transactional public int updateWarehouseArea(WarehouseArea warehouseArea) { + journal.lockInventory(); + var existing=warehouseAreaMapper.selectWarehouseAreaById(warehouseArea.getId()); + if(existing==null)throw new com.ruoyi.common.exception.ServiceException("库区不存在"); + if(warehouseArea.getStatus()==null)warehouseArea.setStatus(existing.getStatus()); + if(!java.util.Set.of(0,1).contains(warehouseArea.getStatus()))throw new com.ruoyi.common.exception.ServiceException("库区状态不正确"); + if(Integer.valueOf(1).equals(warehouseArea.getStatus())&&hasStock(warehouseArea.getId()))throw new com.ruoyi.common.exception.ServiceException("库区仍有库存,请先移出库存再停用"); normalizeAreaCode(warehouseArea); return warehouseAreaMapper.updateWarehouseArea(warehouseArea); } @Override + @org.springframework.transaction.annotation.Transactional public int deleteWarehouseAreaByIds(Long[] ids) { + journal.lockInventory(); + for(Long id:ids){ + if(hasStock(id))throw new com.ruoyi.common.exception.ServiceException("库区仍有库存,不能删除"); + Long history=db.queryForObject("select (select count(*) from inventory_cost_event where area_id=?)+(select count(*) from in_record where area_id=?)+(select count(*) from out_record where area_id=?)+(select count(*) from stock_check_record where area_id=?)+(select count(*) from stock_lot where area_id=?)",Long.class,id,id,id,id,id); + if(history!=null&&history>0)throw new com.ruoyi.common.exception.ServiceException("库区有历史业务,不能删除;可在修改中停用,历史仍可查询"); + } return warehouseAreaMapper.deleteWarehouseAreaByIds(ids); } + private boolean hasStock(Long id){return db.queryForObject("select count(*) from project_stock_balance where area_id=? and quantity<>0",Long.class,id)>0;} private void normalizeAreaCode(WarehouseArea warehouseArea) { diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseImportReceiptService.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseImportReceiptService.java new file mode 100644 index 0000000..da51afd --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WarehouseImportReceiptService.java @@ -0,0 +1,20 @@ +package com.ruoyi.warehouse.service.impl; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.function.Supplier; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.ruoyi.common.utils.SecurityUtils; +@Service public class WarehouseImportReceiptService { + @Autowired private JdbcTemplate db; + @Autowired private InventoryCostJournal journal; + @Transactional public String apply(String kind,byte[] content,Supplier action){ + journal.lockInventory();String hash; + try{hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content));}catch(Exception e){throw new IllegalStateException(e);} + var previous=db.queryForList("select result_message from warehouse_import_receipt where kind=? and file_hash=?",String.class,kind,hash); + if(!previous.isEmpty())return "该文件已处理,未重复导入。"+previous.get(0); + String result=action.get();db.update("insert into warehouse_import_receipt(kind,file_hash,result_message,create_by) values(?,?,?,?)",kind,hash,result,SecurityUtils.getUsername());return result; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WmsBatchImportServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WmsBatchImportServiceImpl.java index 60309d5..2734b0a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WmsBatchImportServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/WmsBatchImportServiceImpl.java @@ -105,6 +105,7 @@ public class WmsBatchImportServiceImpl implements IWmsBatchImportService @Value("${agent.model.model}") private String model; + @Autowired private com.ruoyi.warehouse.service.impl.BusinessNumberService businessNumbers; @Autowired private WmsBatchJobMapper jobMapper; @@ -147,7 +148,7 @@ public class WmsBatchImportServiceImpl implements IWmsBatchImportService { String extension = WarehouseFileUtils.validateUpload(file, MAX_UPLOAD_SIZE, ALLOWED_EXTENSIONS); - String jobNo = WarehouseNoUtils.next("BATCH"); + String jobNo = businessNumbers.next("BATCH"); String safeName = jobNo + "." + extension; Path dir = Paths.get(RuoYiConfig.getUploadPath(), "wms-batch").toAbsolutePath().normalize(); Files.createDirectories(dir); diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/MovingAverageCost.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/MovingAverageCost.java new file mode 100644 index 0000000..0a6da8e --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/MovingAverageCost.java @@ -0,0 +1,119 @@ +package com.ruoyi.warehouse.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.*; +import com.ruoyi.common.exception.ServiceException; + +/** + * Deterministic valuation for ONE project/item stream across all warehouse areas. + * Original events remain immutable; settlement overrides produce separate differences. + * A null amount means an unknown historical cost, never a free item. + */ +public final class MovingAverageCost { + private static final BigDecimal ZERO_QTY = BigDecimal.ZERO.setScale(4); + private static final BigDecimal ZERO_AMOUNT = BigDecimal.ZERO.setScale(6); + private MovingAverageCost() { } + public enum Type { RECEIPT, ISSUE, RETURN } + public record Event(long id, Type type, BigDecimal quantity, BigDecimal amount, Long sourceId, boolean active) { } + public record Balance(BigDecimal quantity, BigDecimal amount) { + public boolean complete() { return amount != null; } + public BigDecimal averageUnitCost() { + return amount == null ? null : quantity.signum() == 0 ? ZERO_AMOUNT : amount.divide(quantity, 6, RoundingMode.HALF_UP); + } + } + public record Valuation(long eventId, Type type, BigDecimal quantity, BigDecimal amount, boolean active, Balance balance) { } + public record Result(List events, Balance balance) { } + public record Difference(long eventId, BigDecimal oldAmount, BigDecimal newAmount, BigDecimal delta) { } + + /** Cost of a receipt at a known price; callers must preserve null for missing prices. */ + public static BigDecimal receiptAmount(BigDecimal quantity, BigDecimal unitPrice) { + BigDecimal q = quantity(quantity); + if (unitPrice == null) return null; + if (unitPrice.signum() < 0 || unitPrice.stripTrailingZeros().scale() > 6) throw error("单价必须非负,最多6位小数"); + return amount(q.multiply(unitPrice).setScale(6, RoundingMode.HALF_UP)); + } + public static Result replay(List events) { return replay(events, Map.of()); } + + /** Overrides apply to receipt VALUE, not quantity, and include the entire receipt's settled amount. */ + public static Result replay(List events, Map receiptOverrides) { + if (events == null || receiptOverrides == null) throw error("库存成本事件不能为空"); + List results = new ArrayList<>(); Map effective = new HashMap<>(); + Map returnedQty = new HashMap<>(), returnedAmount = new HashMap<>(); + Set overridden = new HashSet<>(); + BigDecimal stockQty = ZERO_QTY, stockAmount = ZERO_AMOUNT; long lastId = 0; + for (Event event : events) { + if (event == null || event.type() == null || event.id() <= lastId) throw error("库存事件必须按唯一递增顺序处理"); + lastId = event.id(); BigDecimal qty = quantity(event.quantity()); + if (!event.active()) { + if (receiptOverrides.containsKey(event.id())) throw error("不能调整已撤销的入库成本"); + results.add(new Valuation(event.id(), event.type(), qty, ZERO_AMOUNT, false, new Balance(stockQty, stockAmount))); continue; + } + BigDecimal value; + switch (event.type()) { + case RECEIPT -> { + if (event.sourceId() != null) throw error("普通入库不能关联领用来源"); + if (receiptOverrides.containsKey(event.id())) { value = amount(receiptOverrides.get(event.id())); overridden.add(event.id()); } + else value = amount(event.amount()); + stockQty = quantityBalance(stockQty.add(qty)); stockAmount = addKnown(stockAmount, value); + } + case ISSUE -> { + if (event.sourceId() != null || event.amount() != null) throw error("普通出库由平均成本自动计价,不接受手填成本"); + if (qty.compareTo(stockQty) > 0) throw error("事件" + event.id() + "库存不足,不能出现负库存"); + value = stockAmount == null ? null : qty.compareTo(stockQty) == 0 ? stockAmount : stockAmount.multiply(qty).divide(stockQty, 6, RoundingMode.HALF_UP); + stockQty = quantityBalance(stockQty.subtract(qty)); + stockAmount = stockQty.signum() == 0 ? ZERO_AMOUNT : stockAmount == null ? null : stockAmount.subtract(value); + } + case RETURN -> { + if (event.amount() != null) throw error("退料成本来自原领用,不接受手填成本"); + Valuation source = event.sourceId() == null ? null : effective.get(event.sourceId()); + if (source == null || source.type() != Type.ISSUE) throw error("退料必须关联此前有效领用"); + BigDecimal alreadyQty = returnedQty.getOrDefault(event.sourceId(), ZERO_QTY), totalQty = alreadyQty.add(qty); + if (totalQty.compareTo(source.quantity()) > 0) throw error("累计退料超过原领用数量"); + BigDecimal alreadyAmount = returnedAmount.getOrDefault(event.sourceId(), ZERO_AMOUNT); + // Use cumulative proportional allocation: many tiny returns must not accumulate rounding errors. + BigDecimal totalValue = source.amount() == null ? null : totalQty.compareTo(source.quantity()) == 0 ? source.amount() + : source.amount().multiply(totalQty).divide(source.quantity(), 6, RoundingMode.HALF_UP); + value = totalValue == null ? null : totalValue.subtract(alreadyAmount); + returnedQty.put(event.sourceId(), totalQty); returnedAmount.put(event.sourceId(), totalValue); + stockQty = quantityBalance(stockQty.add(qty)); stockAmount = addKnown(stockAmount, value); + } + default -> throw error("不支持的库存成本事件"); + } + if (receiptOverrides.containsKey(event.id()) && event.type() != Type.RECEIPT) throw error("只能调整入库来源成本"); + Valuation result = new Valuation(event.id(), event.type(), qty, value, true, new Balance(stockQty, stockAmount)); + effective.put(event.id(), result); results.add(result); + } + if (!overridden.equals(receiptOverrides.keySet())) throw error("成本调整引用不存在或无效的入库事件"); + return new Result(List.copyOf(results), new Balance(stockQty, stockAmount)); + } + /** Differences are append-only adjustment inputs; no original event is rewritten. */ + public static List differences(Result before, Result after) { + Map previous = new HashMap<>(); before.events().forEach(value -> previous.put(value.eventId(), value)); + if (before.events().size() != after.events().size()) throw error("成本结算不能增加或删除数量事件"); + List differences = new ArrayList<>(); + for (Valuation current : after.events()) { + Valuation old = previous.get(current.eventId()); + if (old == null || old.type() != current.type() || old.active() != current.active() || old.quantity().compareTo(current.quantity()) != 0) + throw error("成本结算不能改变业务数量或有效状态"); + if (!Objects.equals(old.amount(), current.amount())) differences.add(new Difference(current.eventId(), old.amount(), current.amount(), + old.amount() == null || current.amount() == null ? null : current.amount().subtract(old.amount()))); + } + return List.copyOf(differences); + } + private static BigDecimal quantity(BigDecimal value) { + if (value == null || value.signum() <= 0) throw error("库存数量必须大于0"); + return quantityBalance(value); + } + private static BigDecimal quantityBalance(BigDecimal value) { + if (value.signum() < 0 || value.stripTrailingZeros().scale() > 4 || value.precision() - value.scale() > 16) throw error("库存数量超出范围或超过4位小数"); + return value.setScale(4); + } + private static BigDecimal amount(BigDecimal value) { + if (value == null) return null; + if (value.signum() < 0 || value.stripTrailingZeros().scale() > 6 || value.precision() - value.scale() > 18) throw error("库存金额超出范围或超过6位小数"); + return value.setScale(6); + } + private static BigDecimal addKnown(BigDecimal left, BigDecimal right) { return left == null || right == null ? null : amount(left.add(right)); } + private static ServiceException error(String message) { return new ServiceException(message); } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/PurchasePriceRules.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/PurchasePriceRules.java new file mode 100644 index 0000000..ed2d122 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/PurchasePriceRules.java @@ -0,0 +1,26 @@ +package com.ruoyi.warehouse.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import com.ruoyi.common.exception.ServiceException; + +public final class PurchasePriceRules +{ + private PurchasePriceRules() { } + + public static BigDecimal amount(BigDecimal quantity, BigDecimal unitPrice) + { + if (quantity == null || quantity.signum() <= 0 || quantity.scale() > 4) + throw new ServiceException("采购数量必须大于0,最多4位小数"); + if (unitPrice == null || unitPrice.signum() < 0 || unitPrice.scale() > 6) + throw new ServiceException("锁价前请填写有效的最终单价,最多6位小数"); + return quantity.multiply(unitPrice).setScale(6, RoundingMode.HALF_UP); + } + + public static void requireEditablePrice(int confirmedInboundCount, BigDecimal before, BigDecimal after) + { + boolean changed = before == null ? after != null : after == null || before.compareTo(after) != 0; + if (confirmedInboundCount > 0 && changed) + throw new ServiceException("已入库不能改价,请先逐步退回后续业务,并撤销该明细全部入库至待入库"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/WarehouseNoUtils.java b/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/WarehouseNoUtils.java index 9a2fcec..4efed2c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/WarehouseNoUtils.java +++ b/ruoyi-system/src/main/java/com/ruoyi/warehouse/util/WarehouseNoUtils.java @@ -1,20 +1,20 @@ package com.ruoyi.warehouse.util; -import java.time.LocalDateTime; +import java.time.LocalDate; import java.time.format.DateTimeFormatter; -import java.util.UUID; +import java.util.Locale; public final class WarehouseNoUtils { - private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"); + private static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM"); private WarehouseNoUtils() { } - public static String next(String prefix) + public static String format(String prefix, LocalDate date, long sequence) { - String random = UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase(); - return prefix + TIME_FORMATTER.format(LocalDateTime.now()) + random; + if(prefix==null||!prefix.matches("[A-Z]{1,3}")||date==null||sequence<1)throw new IllegalArgumentException("Invalid business number"); + return prefix + MONTH_FORMATTER.format(date) + String.format(Locale.ROOT,"%04d",sequence); } } diff --git a/ruoyi-system/src/main/resources/mapper/production/BomMapper.xml b/ruoyi-system/src/main/resources/mapper/production/BomMapper.xml new file mode 100644 index 0000000..9e128b5 --- /dev/null +++ b/ruoyi-system/src/main/resources/mapper/production/BomMapper.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select b.*, i.product_code item_code, i.product_name item_name, i.brand,i.spec,i.unit + from bom_version b join product_info i on i.id=b.item_id + + + + + select l.*, i.product_code item_code,i.product_name item_name,i.brand,i.spec,i.unit,c.version_tag child_version_tag + from bom_line l join product_info i on i.id=l.item_id left join bom_version c on c.id=l.child_bom_id + + + + + insert into bom_version(item_id,version_tag,description,is_default,scope_type,scope_key,project_id,source_version_id,create_by) + values(#{itemId},#{versionTag},#{description},#{isDefault},#{scopeType},#{scopeKey},#{projectId},#{sourceVersionId},#{createBy}) + + update bom_version set version_tag=#{versionTag},description=#{description},is_default=#{isDefault},version=version+1,update_by=#{updateBy},update_time=sysdate() + where id=#{id} and del_flag='0' and version=#{version} + update bom_version set is_default=0,version=version+1,update_time=sysdate() where item_id=#{itemId} and scope_type='PUBLIC' and is_default=1 and del_flag='0'and id != #{exceptId} + update bom_line set del_flag='2' where bom_id=#{bomId} and del_flag='0' + insert into bom_line(bom_id,item_id,unit_quantity,child_bom_id,remark,sort_order) values(#{bomId},#{itemId},#{unitQuantity},#{childBomId},#{remark},#{sortOrder}) + + update bom_version set del_flag='2',is_default=0,version=version+1,update_time=sysdate() where id=#{id} and del_flag='0' + insert into bom_change_log(bom_id,version,operation,snapshot,operator) values(#{bom.id},#{bom.version},#{operation},#{snapshot},#{operator}) + + select p.*,i.product_code item_code,i.product_name item_name,i.category,i.brand,i.spec,i.unit,b.id default_bom_id,b.version_tag default_version_tag + from production_product p join product_info i on i.id=p.item_id left join bom_version b on b.item_id=p.item_id and b.scope_type='PUBLIC' and b.is_default=1 and b.del_flag='0' + + + + insert into production_product(item_id,remark,create_by) values(#{itemId},#{remark},#{createBy}) + update production_product set remark=#{remark},version=version+1,update_by=#{updateBy},update_time=sysdate() where id=#{id} and del_flag='0' and version=#{version} + + update production_product set del_flag='2',version=version+1,update_time=sysdate() where id=#{id} and del_flag='0' + update production_product set del_flag='0',version=version+1,update_time=sysdate() where id=#{id} and del_flag='2' + select p.*,i.product_code item_code,i.product_name item_name,i.brand,i.spec,i.unit,b.version_tag from project_product p join product_info i on i.id=p.item_id left join bom_version b on b.id=p.bom_id + + + + insert into project_product(project_id,item_id,bom_id,remark,create_by) values(#{projectId},#{itemId},#{bomId},#{remark},#{createBy}) + update project_product set bom_id=#{bomId},remark=#{remark},version=version+1,update_by=#{updateBy},update_time=sysdate() where id=#{id} and version=#{version} and del_flag='0' + update project_product set del_flag='2',version=version+1,update_time=sysdate() where id=#{id} and del_flag='0' + diff --git a/ruoyi-system/src/main/resources/mapper/project/ProjectBudgetMapper.xml b/ruoyi-system/src/main/resources/mapper/project/ProjectBudgetMapper.xml index 4d092b0..b1320b1 100644 --- a/ruoyi-system/src/main/resources/mapper/project/ProjectBudgetMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/project/ProjectBudgetMapper.xml @@ -1,6 +1,12 @@ + + insert into project_budget(project_id, expense_category_id, budget_amount, committed_amount, + spent_amount, alert_percent, version, create_by, create_time) + values(#{projectId}, #{categoryId}, 0, 0, 0, 80, 0, 'system', sysdate()) + on duplicate key update id = id + @@ -94,12 +100,18 @@ select b.id, b.project_id, p.project_code, p.project_name, b.expense_category_id, - c.category_code, c.category_name, b.budget_amount, b.committed_amount, b.spent_amount, - b.budget_amount - b.committed_amount - b.spent_amount as available_amount, + c.category_code, c.category_name, b.budget_amount, 0 as committed_amount, + coalesce(cost.amount, 0) as spent_amount, + b.budget_amount - coalesce(cost.amount, 0) as available_amount, b.alert_percent, b.version, b.remark from project_budget b join project_info p on p.id = b.project_id join expense_category c on c.id = b.expense_category_id + left join ( + select project_id, expense_category_id, sum(locked_amount) amount + from purchase_request where price_locked = 1 and purchase_status != 5 and del_flag = '0' + group by project_id, expense_category_id + ) cost on cost.project_id = b.project_id and cost.expense_category_id = b.expense_category_id where b.id = #{id} @@ -144,7 +162,25 @@ + p.del_flag = '0' and p.project_code like concat('%', #{project.projectCode}, '%') and p.project_name like concat('%', #{project.projectName}, '%') - and p.manager_id = #{project.managerId} and p.project_status = #{project.projectStatus} - - and (p.manager_id = #{userId} or exists ( - select 1 from project_member pm where pm.project_id = p.id and pm.user_id = #{userId} - )) - order by p.id desc - insert into project_info(project_code, project_name, manager_id, dept_id, start_date, end_date, + insert into project_info(project_code, project_name, project_type, total_amount, project_status, currency, remark, create_by, create_time) - values(#{projectCode}, #{projectName}, #{managerId}, #{deptId}, #{startDate}, #{endDate}, - #{projectStatus}, #{currency}, #{remark}, #{createBy}, sysdate()) + values(#{projectCode}, #{projectName}, #{projectType}, #{totalAmount}, + #{projectStatus}, 'CNY', #{remark}, #{createBy}, sysdate()) update project_info - set project_code = #{projectCode}, project_name = #{projectName}, manager_id = #{managerId}, - dept_id = #{deptId}, start_date = #{startDate}, end_date = #{endDate}, - project_status = #{projectStatus}, currency = #{currency}, remark = #{remark}, + set project_name = #{projectName}, project_type = #{projectType}, total_amount = #{totalAmount}, + project_status = #{projectStatus}, remark = #{remark}, version = version + 1, update_by = #{updateBy}, update_time = sysdate() - where id = #{id} and project_code != 'LEGACY' + where id = #{id} and project_code != 'LEGACY' and del_flag = '0' and version = #{version} - delete from project_info where id = #{id} and project_code != 'LEGACY' + update project_info set del_flag = '2', update_time = sysdate() + where id = #{id} and project_code != 'LEGACY' and del_flag = '0' - - - delete from project_member where project_id = #{projectId} - - - - insert into project_member(project_id, user_id, member_role, create_by, create_time) - values(#{projectId}, #{userId}, #{memberRole}, #{createBy}, sysdate()) - on duplicate key update member_role = values(member_role) - - - - - and (l.lender_project_id=#{projectId} or l.borrower_project_id=#{projectId})and l.item_id=#{itemId}and l.active=1 and l.quantity>l.historical_returned+coalesce(r.returned_quantity,0)order by l.id desc + + + insert into project_loan(loan_no,lender_project_id,borrower_project_id,item_id,quantity,out_event_id,in_event_id,remark,create_by,business_date) values(#{loanNo},#{lenderProjectId},#{borrowerProjectId},#{itemId},#{quantity},#{outEventId},#{inEventId},#{remark},#{createBy},#{businessDate}) + update project_loan set active=0 where id=#{id} and active=1 + insert into project_loan_return(loan_id,quantity,business_key,return_type,out_event_id,in_event_id,create_by) values(#{loanId},#{quantity},#{key},#{type},#{outId},#{inId},#{actor}) + + + update project_loan_return set active=0 where in_event_id=#{inId} and active=1 + + diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml index 04908fe..ceb66f3 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml @@ -3,16 +3,24 @@ + + + + + + + + @@ -34,19 +42,25 @@ - select ir.id, ir.in_no, ir.area_id, ir.product_id, ir.purchase_request_id, ir.arrival_id, + select ir.id, ir.business_date, ir.in_no, ir.area_id, ir.product_id, ir.purchase_request_id, ir.arrival_id, + ir.cost_event_id,ir.cost_revision,ir.receipt_unit_cost,ir.production_task_id,ir.completion_id, ir.source_project_id, project.project_name as source_project_name, + purchase_project.project_name as purchase_project_name,purchase.purchase_batch_no, ir.expense_category_id, ec.category_name as expense_category_name, ir.source_no, - ir.in_type, ir.in_num, ir.in_status, + ir.in_type,case when ir.receipt_root=1 then ir.in_num-coalesce(child.received,0) else ir.in_num end in_num, ir.in_status, + ir.receipt_root,ir.parent_in_id,coalesce(child.received,0) received_quantity, coalesce(operator_user.nick_name, ir.operator) as operator, ir.in_operator, coalesce(in_user.nick_name, ir.in_operator) as in_operator_name, ir.confirm_time, ir.remark, ir.create_time, ir.update_time, wa.area_code, wa.area_name, pi.product_code, pi.product_name, pi.brand, pi.category, pi.spec, pi.unit from in_record ir + left join (select parent_in_id,sum(in_num) received from in_record where parent_in_id is not null and in_status=1 group by parent_in_id) child on child.parent_in_id=ir.id left join warehouse_area wa on wa.id = ir.area_id left join product_info pi on pi.id = ir.product_id left join project_info project on project.id = ir.source_project_id + left join purchase_request purchase on purchase.id=ir.purchase_request_id + left join project_info purchase_project on purchase_project.id=purchase.project_id left join expense_category ec on ec.id = ir.expense_category_id left join sys_user operator_user on operator_user.user_name = ir.operator left join sys_user in_user on in_user.user_name = ir.in_operator @@ -55,9 +69,15 @@ - + select id, business_date, in_no, area_id, product_id, purchase_request_id, arrival_id, + receipt_root,parent_in_id,production_task_id,completion_id, + cost_event_id,cost_revision,receipt_unit_cost, source_project_id, expense_category_id, source_no, in_type, in_num, in_status, operator, in_operator, confirm_time, remark, create_time, update_time from in_record where id = #{id} for update - + select id, business_date, in_no, area_id, product_id, purchase_request_id, arrival_id, + receipt_root,parent_in_id,production_task_id,completion_id, + cost_event_id,cost_revision,receipt_unit_cost, source_project_id, expense_category_id, source_no, in_type, in_num, in_status, operator, in_operator, confirm_time, remark, create_time, update_time from in_record where arrival_id = #{arrivalId} for update @@ -97,17 +121,18 @@ - insert into in_record(in_no, area_id, product_id, purchase_request_id, arrival_id, + insert into in_record(in_no, business_date, area_id, product_id, purchase_request_id, arrival_id, source_project_id, expense_category_id, source_no, in_type, in_num, - in_status, operator, in_operator, remark, create_time) - values(#{inNo}, #{areaId}, #{productId}, #{purchaseRequestId}, #{arrivalId}, + in_status, operator, in_operator, remark, create_time,receipt_unit_cost,receipt_root,parent_in_id,production_task_id,completion_id) + values(#{inNo}, #{businessDate}, #{areaId}, #{productId}, #{purchaseRequestId}, #{arrivalId}, #{sourceProjectId}, #{expenseCategoryId}, #{sourceNo}, #{inType}, #{inNum}, - #{inStatus}, #{operator}, #{inOperator}, #{remark}, sysdate()) + #{inStatus}, #{operator}, #{inOperator}, #{remark}, sysdate(),#{receiptUnitCost},coalesce(#{receiptRoot},0),#{parentInId},#{productionTaskId},#{completionId}) update in_record + business_date=#{businessDate}, in_no = #{inNo}, area_id = #{areaId}, product_id = #{productId}, @@ -115,6 +140,7 @@ expense_category_id = #{expenseCategoryId}, in_type = #{inType}, in_num = #{inNum}, + receipt_unit_cost = #{receiptUnitCost}, operator = #{operator}, in_operator = #{inOperator}, remark = #{remark}, @@ -125,7 +151,10 @@ update in_record - set in_status = #{inStatus}, operator = #{operator}, confirm_time = #{confirmTime}, update_time = sysdate() + set in_status = #{inStatus}, operator = #{operator}, confirm_time = #{confirmTime}, + cost_event_id=#{costEventId},cost_revision=cost_revision+1,receipt_unit_cost=#{receiptUnitCost}, + in_operator = coalesce(nullif(in_operator, ''), #{operator}), + source_project_id = #{sourceProjectId}, expense_category_id = #{expenseCategoryId}, update_time = sysdate() where id = #{id} and in_status = 0 @@ -134,7 +163,15 @@ #{id} + + update in_record set in_status = case when parent_in_id is null then 0 else 2 end, confirm_time = null, + operator = #{operator}, update_time = sysdate() + where id = #{id} and in_status = 1 + + delete from in_record where arrival_id = #{arrivalId} and in_status = 0 + + update in_record set in_status=#{status},update_time=sysdate() where id=#{id} and receipt_root=1 diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/InventoryCostMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/InventoryCostMapper.xml new file mode 100644 index 0000000..b42b810 --- /dev/null +++ b/ruoyi-system/src/main/resources/mapper/warehouse/InventoryCostMapper.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + insert into inventory_cost_link(source_event_id,target_event_id) values(#{sourceId},#{targetId}) + + + + insert into stock_info(area_id,product_id,stock_num,create_time,update_time) + select #{areaId},#{itemId},coalesce(sum(quantity),0),sysdate(),sysdate() from project_stock_balance where item_id=#{itemId} and area_id=#{areaId} + on duplicate key update stock_num=values(stock_num),update_time=sysdate() + + + + insert into inventory_cost_event(project_id,item_id,area_id,event_key,event_no,event_type,quantity,receipt_amount,source_id,create_by,business_date,remark) values(#{projectId},#{itemId},#{areaId},#{eventKey},#{eventNo},#{eventType},#{quantity},#{receiptAmount},#{sourceId},#{createBy},#{businessDate},#{remark}) + update inventory_cost_event set original_cost=#{amount} where id=#{id} + update inventory_cost_event set effective_cost=#{amount} where id=#{id} + update inventory_cost_event set active=0,void_reason=#{reason},void_by=#{actor},void_time=sysdate() where id=#{id} and active=1 + insert into project_item_cost(project_id,item_id) select #{projectId},#{itemId} where not exists(select 1 from project_item_cost where project_id=#{projectId} and item_id=#{itemId}) + + update project_item_cost set quantity=#{quantity},amount=#{amount},version=version+1 where project_id=#{projectId} and item_id=#{itemId} + insert into project_stock_balance(project_id,item_id,area_id,quantity) values(#{projectId},#{itemId},#{areaId},#{quantity}) on duplicate key update quantity=quantity+#{quantity},version=version+1 + update project_stock_balance set quantity=quantity-#{quantity},version=version+1 where project_id=#{projectId} and item_id=#{itemId} and area_id=#{areaId} and quantity >= #{quantity} + + + + + insert into inventory_cost_revision(revision_key,revision_no,target_event_id,new_amount,expected_version,create_by) values(#{revisionKey},#{revisionNo},#{targetEventId},#{newAmount},#{expectedVersion},#{createBy}) + insert into inventory_cost_change(revision_id,event_id,old_amount,new_amount,delta_amount) values(#{revisionId},#{change.eventId},#{change.oldAmount},#{change.newAmount},#{change.delta}) + diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/OutRecordMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/OutRecordMapper.xml index 5ca239b..773238c 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/OutRecordMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/OutRecordMapper.xml @@ -7,6 +7,10 @@ + + + + @@ -33,6 +37,8 @@ select orr.id, orr.out_no, orr.area_id, orr.product_id, orr.usage_project_id, + orr.cost_event_id,orr.active,ce.effective_cost as cost_amount, + coalesce((select sum(quantity) from inventory_cost_event where source_id=orr.cost_event_id and active=1),0) returned_quantity, usage_project.project_name as usage_project_name, orr.out_type, orr.out_num, orr.source_no, orr.cross_project_flag, orr.cross_project_reason, lot_project.source_project_names, @@ -42,6 +48,7 @@ orr.out_time, orr.remark, orr.create_time, orr.update_time, wa.area_code, wa.area_name, pi.product_code, pi.product_name, pi.brand, pi.category, pi.spec, pi.unit from out_record orr + left join inventory_cost_event ce on ce.id=orr.cost_event_id left join warehouse_area wa on wa.id = orr.area_id left join product_info pi on pi.id = orr.product_id left join project_info usage_project on usage_project.id = orr.usage_project_id @@ -87,11 +94,12 @@ insert into out_record(out_no, area_id, product_id, usage_project_id, out_type, out_num, source_no, - cross_project_flag, cross_project_reason, operator, out_operator, out_time, remark, create_time) + cross_project_flag, cross_project_reason, operator, out_operator, out_time, remark, create_time,cost_event_id) values(#{outNo}, #{areaId}, #{productId}, #{usageProjectId}, #{outType}, #{outNum}, #{sourceNo}, - #{crossProjectFlag}, #{crossProjectReason}, #{operator}, #{outOperator}, #{outTime}, #{remark}, sysdate()) + #{crossProjectFlag}, #{crossProjectReason}, #{operator}, #{outOperator}, #{outTime}, #{remark}, sysdate(),#{costEventId}) + update out_record set active=0,update_time=sysdate() where id=#{id} and active=1 update out_record set cross_project_flag = #{crossProjectFlag}, cross_project_reason = #{crossProjectReason}, update_time = sysdate() diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml index d4fe39f..fb48886 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/ProductInfoMapper.xml @@ -23,7 +23,7 @@ and product_code like concat('%', #{productCode}, '%') - and lower(concat_ws(' ', product_name, brand, category, spec, unit)) + and lower(concat_ws(' ', product_code, product_name, brand, category, spec, unit)) like concat('%', lower(#{productName}), '%') and brand like concat('%', #{brand}, '%') @@ -59,6 +59,25 @@ where id = #{id} + + + + diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseArrivalMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseArrivalMapper.xml index 39bdd80..bee59de 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseArrivalMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseArrivalMapper.xml @@ -6,6 +6,7 @@ + @@ -40,6 +41,7 @@ select pa.id, pa.arrival_no, pa.purchase_request_id, pa.arrival_quantity, + pa.defective_quantity, pa.actual_unit_price, pa.actual_amount, pa.arrival_date, pa.acceptance_status, pa.acceptance_remark, coalesce(accepted_user.nick_name, pa.accepted_by) as accepted_by, pa.accepted_time, @@ -77,6 +79,7 @@ - + select coalesce(sum(arrival_quantity-case when acceptance_status=1 then defective_quantity+returned_quantity else 0 end), 0) from purchase_arrival where purchase_request_id = #{purchaseRequestId} and acceptance_status in (0, 1) - + select coalesce(sum(arrival_quantity-defective_quantity-returned_quantity), 0) from purchase_arrival where purchase_request_id = #{purchaseRequestId} and acceptance_status = 1 @@ -118,6 +121,7 @@ update purchase_arrival set acceptance_status = #{acceptanceStatus}, acceptance_remark = #{acceptanceRemark}, + defective_quantity=#{defectiveQuantity}, accepted_by = #{acceptedBy}, accepted_time = #{acceptedTime}, pre_accept_purchase_status = #{preAcceptPurchaseStatus}, update_by = #{updateBy}, update_time = sysdate() @@ -127,6 +131,7 @@ update purchase_arrival set acceptance_status = 0, + defective_quantity=0, acceptance_remark = null, accepted_by = null, accepted_time = null, revoked_by = #{revokedBy}, revoked_time = #{revokedTime}, revoke_remark = #{revokeRemark}, update_by = #{updateBy}, update_time = sysdate() diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml index f109a0b..9173edb 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml @@ -3,11 +3,20 @@ + + + + + + + + + @@ -15,22 +24,34 @@ - insert into purchase_batch(batch_no, batch_name, purchase_status, progress_remark, create_by, create_time) - values(#{batchNo}, #{batchName}, #{purchaseStatus}, #{progressRemark}, #{createBy}, sysdate()) + insert into purchase_batch(batch_no, batch_name, purchase_status, progress_remark, create_by, create_time,supplier_id,business_date) + values(#{batchNo}, #{batchName}, #{purchaseStatus}, #{progressRemark}, #{createBy}, sysdate(),#{supplierId},#{businessDate}) update purchase_batch - set batch_no = #{batchNo}, batch_name = #{batchName}, purchase_status = #{purchaseStatus}, + set supplier_id=#{supplierId},business_date=#{businessDate}, batch_no = #{batchNo}, batch_name = #{batchName}, purchase_status = #{purchaseStatus}, progress_remark = #{progressRemark}, update_by = #{updateBy}, update_time = sysdate() where id = #{id} diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml index 980eb4f..e5ba2ed 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/PurchaseRequestMapper.xml @@ -5,6 +5,10 @@ + + + + @@ -20,8 +24,11 @@ + + + + - @@ -42,6 +49,7 @@ + @@ -57,22 +65,25 @@ - select pr.id, pr.request_no, pr.product_id, pr.purchase_batch_id, + select pr.id, pr.request_no, pr.product_id, pr.purchase_batch_id,pb.supplier_id,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name, + pr.purchase_purpose,pr.loan_id,pr.production_task_id,pr.historical,pr.original_date, pr.project_id, project.project_code, project.project_name, pr.expense_category_id, ec.category_code as expense_category_code, ec.category_name as expense_category_name, pr.material_name, pr.material_brand, pr.category, pr.material_params, pr.purchase_link, pr.quantity, pr.estimated_unit_price, pr.estimated_amount, - pr.unit, pr.expected_date, pr.applicant_id, + pr.final_unit_price, pr.price_locked, pr.locked_amount, pr.lock_revision, + pr.unit, pr.applicant_id, coalesce(applicant_user.nick_name, pr.applicant_name) as applicant_name, pr.purchase_status, pr.purchase_batch_no, pb.batch_name as purchase_batch_name, pr.progress_remark, pr.remark, pr.create_by, pr.create_time, pr.update_by, pr.update_time, pi.product_code, pi.product_name, pi.brand as product_brand, pi.category as product_category, pi.spec as product_spec, pi.remark as product_remark, - coalesce(pa.accepted_quantity, 0) as accepted_quantity, + case when pr.historical=1 then pr.quantity else coalesce(pa.accepted_quantity, 0) end as accepted_quantity, coalesce(pa.pending_quantity, 0) as pending_arrival_quantity, - greatest(pr.quantity - coalesce(pa.accepted_quantity, 0) - coalesce(pa.pending_quantity, 0), 0) as remaining_quantity + coalesce((select sum(ir.in_num) from in_record ir where ir.purchase_request_id=pr.id and ir.in_status=1 and ir.receipt_root=0),0) as received_quantity, + case when pr.historical=1 then 0 else greatest(pr.quantity - coalesce(pa.accepted_quantity, 0) - coalesce(pa.pending_quantity, 0), 0) end as remaining_quantity from purchase_request pr left join product_info pi on pi.id = pr.product_id left join project_info project on project.id = pr.project_id @@ -81,7 +92,7 @@ left join sys_user applicant_user on applicant_user.user_id = pr.applicant_id left join ( select purchase_request_id, - sum(case when acceptance_status = 1 then arrival_quantity else 0 end) as accepted_quantity, + sum(case when acceptance_status = 1 then arrival_quantity-defective_quantity-returned_quantity else 0 end) as accepted_quantity, sum(case when acceptance_status = 0 then arrival_quantity else 0 end) as pending_quantity from purchase_arrival where acceptance_status in (0, 1) @@ -89,13 +100,22 @@ ) pa on pa.purchase_request_id = pr.id + - select pr.id, pr.request_no, pr.product_id, pr.purchase_batch_id, pr.project_id, + pr.purchase_purpose,pr.loan_id,pr.production_task_id,pr.historical,pr.original_date, pr.expense_category_id, pr.material_name, pr.material_brand, pr.category, pr.material_params, pr.purchase_link, pr.quantity, - pr.estimated_unit_price, pr.estimated_amount, pr.unit, pr.expected_date, + pr.estimated_unit_price, pr.estimated_amount, pr.final_unit_price, + pr.price_locked, pr.locked_amount, pr.lock_revision, pr.unit, pr.applicant_id, pr.applicant_name, pr.purchase_status, pr.purchase_batch_no, pr.progress_remark, pr.remark, pr.create_by, pr.create_time, pr.update_by, pr.update_time - from purchase_request pr where pr.id = #{id} for update + from purchase_request pr where pr.id = #{id} and pr.del_flag = '0' for update + select count(*) from in_record where purchase_request_id = #{id} and in_status = 1 and receipt_root=0 + + + + update purchase_request set final_unit_price = #{finalUnitPrice}, + price_locked = #{priceLocked}, locked_amount = #{lockedAmount}, lock_revision = #{lockRevision}, + update_by = #{updateBy}, update_time = sysdate() + where id = #{id} and del_flag = '0' and lock_revision = #{lockRevision} - 1 + + + + insert into purchase_price_ledger(purchase_request_id, revision, old_project_id, old_category_id, + new_project_id, new_category_id, old_amount, new_amount, operation, operator, new_ledger_no, old_ledger_no) + values(#{updated.id}, #{updated.lockRevision}, #{existing.projectId}, #{existing.expenseCategoryId}, + #{updated.projectId}, #{updated.expenseCategoryId}, #{existing.lockedAmount}, + #{updated.lockedAmount}, #{operation}, #{updated.updateBy}, #{newLedgerNo}, #{oldLedgerNo}) + diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/StockCheckRecordMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/StockCheckRecordMapper.xml index 9c9ab4c..5e61d76 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/StockCheckRecordMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/StockCheckRecordMapper.xml @@ -6,6 +6,8 @@ + + @@ -14,6 +16,7 @@ + @@ -27,13 +30,15 @@ - select scr.id, scr.check_no, scr.area_id, scr.product_id, scr.book_num, scr.real_num, scr.diff_num, + select scr.id, scr.business_date, scr.remark, scr.check_no, scr.area_id, scr.product_id, scr.book_num, scr.real_num, scr.diff_num, + scr.project_id,p.project_name,scr.cost_event_id,scr.book_version,scr.receipt_unit_cost, scr.check_status, coalesce(check_user.nick_name, scr.check_user) as check_user, coalesce(confirm_user.nick_name, scr.confirm_user) as confirm_user, scr.confirm_time, scr.reason, scr.create_time, scr.update_time, wa.area_code, wa.area_name, pi.product_code, pi.product_name, pi.brand, pi.category, pi.spec, pi.unit from stock_check_record scr + left join project_info p on p.id=scr.project_id left join warehouse_area wa on wa.id = scr.area_id left join product_info pi on pi.id = scr.product_id left join sys_user check_user on check_user.user_name = scr.check_user @@ -45,6 +50,7 @@ and scr.area_id = #{areaId} and scr.product_id = #{productId} + and scr.project_id = #{projectId} and wa.area_name like concat('%', #{areaName}, '%') and pi.product_name like concat('%', #{productName}, '%') and pi.brand like concat('%', #{brand}, '%') @@ -59,8 +65,9 @@ where scr.id = #{id} - + select id, business_date, remark, check_no, area_id, product_id, book_num, real_num, diff_num, check_status, + project_id,cost_event_id,book_version,receipt_unit_cost, check_user, confirm_user, confirm_time, reason, create_time, update_time from stock_check_record where id = #{id} for update @@ -70,8 +77,8 @@ - insert into stock_check_record(check_no, area_id, product_id, book_num, real_num, diff_num, check_status, check_user, reason, create_time) - values(#{checkNo}, #{areaId}, #{productId}, #{bookNum}, #{realNum}, #{diffNum}, #{checkStatus}, #{checkUser}, #{reason}, sysdate()) + insert into stock_check_record(check_no, area_id, product_id, book_num, real_num, diff_num, check_status, check_user, reason, create_time,project_id,book_version,receipt_unit_cost,business_date,remark) + values(#{checkNo}, #{areaId}, #{productId}, #{bookNum}, #{realNum}, #{diffNum}, #{checkStatus}, #{checkUser}, #{reason}, sysdate(),#{projectId},#{bookVersion},#{receiptUnitCost},#{businessDate},#{remark}) @@ -80,6 +87,9 @@ real_num = #{realNum}, diff_num = #{diffNum}, reason = #{reason}, + business_date=#{businessDate}, + remark=#{remark}, + receipt_unit_cost=#{receiptUnitCost}, update_time = sysdate() where id = #{id} and check_status = 0 @@ -87,10 +97,11 @@ update stock_check_record - set check_status = #{checkStatus}, confirm_user = #{confirmUser}, confirm_time = #{confirmTime}, update_time = sysdate() + set check_status = #{checkStatus}, confirm_user = #{confirmUser}, confirm_time = #{confirmTime},cost_event_id=#{costEventId}, update_time = sysdate() where id = #{id} and check_status = 0 + update stock_check_record set check_status=2,void_reason=#{reason},void_by=#{username},void_time=current_timestamp,update_time=current_timestamp where id=#{id} and check_status=1 delete from stock_check_record where check_status = 0 and id in #{id} diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml index 83fbf16..51bb77d 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/StockInfoMapper.xml @@ -5,6 +5,11 @@ + + + + + @@ -17,21 +22,31 @@ + - select si.id, si.area_id, si.product_id, si.stock_num, si.last_check_time, si.create_time, si.update_time, - wa.area_code, wa.area_name, pi.product_code, pi.product_name, pi.brand, pi.category, pi.spec, pi.unit - from stock_info si + select si.id, si.area_id, si.item_id as product_id, si.quantity as stock_num, si.project_id, si.version, + p.project_name, round(c.amount/nullif(c.quantity,0),6) as average_unit_cost, + round(c.amount*si.quantity/nullif(c.quantity,0),6) as stock_amount, + legacy.last_check_time, + wa.area_code, wa.area_name, pi.product_code, pi.product_name, pi.brand, pi.category, pi.spec, pi.unit, + exists(select 1 from production_product pp where pp.item_id=si.item_id and pp.del_flag='0') as finished_product + from project_stock_balance si + join project_info p on p.id=si.project_id + join project_item_cost c on c.project_id=si.project_id and c.item_id=si.item_id + left join stock_info legacy on legacy.area_id=si.area_id and legacy.product_id=si.item_id left join warehouse_area wa on wa.id = si.area_id - left join product_info pi on pi.id = si.product_id + left join product_info pi on pi.id = si.item_id + select * from stock_lot where in_record_id = #{inRecordId} for update + + + + update stock_lot set available_quantity = 0, lot_status = 3, + update_by = #{username}, update_time = sysdate() + where id = #{id} and lot_status = 0 and available_quantity = received_quantity + + + update stock_lot set area_id = #{areaId}, product_id = #{productId}, + source_project_id = #{sourceProjectId}, expense_category_id = #{expenseCategoryId}, + received_quantity = #{receivedQuantity}, available_quantity = #{availableQuantity}, + unit_cost = #{unitCost}, lot_status = 0, update_by = #{updateBy}, update_time = sysdate() + where id = #{id} and lot_status = 3 and available_quantity = 0 + + update stock_lot set available_quantity = available_quantity - #{quantity}, diff --git a/ruoyi-system/src/main/resources/mapper/warehouse/WarehouseAreaMapper.xml b/ruoyi-system/src/main/resources/mapper/warehouse/WarehouseAreaMapper.xml index af552b0..f43aa45 100644 --- a/ruoyi-system/src/main/resources/mapper/warehouse/WarehouseAreaMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/warehouse/WarehouseAreaMapper.xml @@ -5,13 +5,14 @@ + - select id, area_code, area_name, remark, create_time, update_time from warehouse_area + select id, area_code, area_name, status, remark, create_time, update_time from warehouse_area