diff --git a/app/build.gradle b/app/build.gradle index 29328a32..75059e7d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,8 +10,8 @@ apply plugin: 'com.google.gms.google-services' android { - def appVersionCode = 485 - def appVersionName = '1.45.03' + def appVersionCode = 492 + def appVersionName = '1.46.04' signingConfigs { release { @@ -62,6 +62,8 @@ android { android.buildFeatures.dataBinding true android.buildFeatures.buildConfig true + android.dataBinding.enabledForTests true + compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 @@ -110,7 +112,7 @@ dependencies { //Firebase // Import the Firebase BoM - implementation platform('com.google.firebase:firebase-bom:33.8.0') + implementation platform('com.google.firebase:firebase-bom:33.9.0') implementation 'com.google.firebase:firebase-analytics' implementation 'com.google.firebase:firebase-crashlytics' implementation 'com.google.firebase:firebase-perf' @@ -121,6 +123,7 @@ dependencies { runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + implementation 'com.google.guava:guava:33.4.0-android' implementation 'androidx.appcompat:appcompat:1.7.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' @@ -139,8 +142,7 @@ dependencies { implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.annimon:stream:1.2.2' - implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.8.7' -// implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' + implementation 'androidx.lifecycle:lifecycle-runtime:2.8.7' implementation 'org.apache.commons:commons-text:1.9' //MVVM diff --git a/app/src/main/java/it/integry/integrywmsnative/MainApplicationComponent.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationComponent.java index 7e32be22..c7116656 100644 --- a/app/src/main/java/it/integry/integrywmsnative/MainApplicationComponent.java +++ b/app/src/main/java/it/integry/integrywmsnative/MainApplicationComponent.java @@ -132,6 +132,8 @@ import it.integry.integrywmsnative.view.dialogs.basket_lu.DialogBasketLUComponen import it.integry.integrywmsnative.view.dialogs.basket_lu.DialogBasketLUModule; import it.integry.integrywmsnative.view.dialogs.bind_product_barcode_with_package.DialogBindProductBarcodeWithPackageComponent; import it.integry.integrywmsnative.view.dialogs.bind_product_barcode_with_package.DialogBindProductBarcodeWithPackageModule; +import it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts.DialogChooseArtFromListaArtsComponent; +import it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts.DialogChooseArtFromListaArtsModule; import it.integry.integrywmsnative.view.dialogs.choose_arts_from_lista_arts.DialogChooseArtsFromMtbAartListComponent; import it.integry.integrywmsnative.view.dialogs.choose_arts_from_lista_arts.DialogChooseArtsFromMtbAartListModule; import it.integry.integrywmsnative.view.dialogs.choose_arts_from_mtbcolr_list.DialogChooseArtsFromMtbColrListComponent; @@ -248,7 +250,8 @@ import it.integry.integrywmsnative.view.dialogs.update_available.DialogUpdateAva DialogAskLivelloPosizioneModule.class, VerificaGiacenzeModule.class, DialogExtraInfoModule.class, - DialogAskDepositoModule.class + DialogAskDepositoModule.class, + DialogChooseArtFromListaArtsModule.class }) public interface MainApplicationComponent { @@ -417,6 +420,8 @@ public interface MainApplicationComponent { DialogAskDepositoComponent.Factory dialogAskDepositoComponent(); + DialogChooseArtFromListaArtsComponent.Factory dialogChooseArtFromListaArtsComponent(); + void inject(MainApplication mainApplication); void inject(AppContext mainApplication); diff --git a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java index 83e05b10..26feba57 100644 --- a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java @@ -49,6 +49,7 @@ import it.integry.integrywmsnative.core.rest.consumers.ProductionLinesRESTConsum import it.integry.integrywmsnative.core.rest.consumers.ProduzioneRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.SystemRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.VettoriRESTConsumer; +import it.integry.integrywmsnative.core.rest.watcher.ServerStatusChecker; import it.integry.integrywmsnative.core.services.inventario.InventarioService; import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.sound.SoundAlertService; @@ -100,8 +101,14 @@ public class MainApplicationModule { @Provides @Singleton - MainContext providesMainContextNew(MenuService menuService, AppDatabase appDatabase, SystemRESTConsumer systemRESTConsumer, AuthenticationRESTConsumer authenticationRESTConsumer) { - return new MainContext(mApplication.getApplicationContext(), menuService, appDatabase, systemRESTConsumer, authenticationRESTConsumer); + ServerStatusChecker providesServerStatusChecker(Handler handler) { + return new ServerStatusChecker(handler); + } + + @Provides + @Singleton + MainContext providesMainContextNew(MenuService menuService, AppDatabase appDatabase, AuthenticationRESTConsumer authenticationRESTConsumer, ExecutorService executorService, Handler handler, ServerStatusChecker serverStatusChecker) { + return new MainContext(mApplication.getApplicationContext(), menuService, appDatabase, authenticationRESTConsumer, executorService, handler, serverStatusChecker); } @Provides @@ -151,8 +158,8 @@ public class MainApplicationModule { @Provides @Singleton - OrdiniRESTConsumer provideOrdiniRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, EntityRESTConsumer entityRESTConsumer) { - return new OrdiniRESTConsumer(restBuilder, systemRESTConsumer, entityRESTConsumer); + OrdiniRESTConsumer provideOrdiniRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, SystemRESTConsumer systemRESTConsumer, EntityRESTConsumer entityRESTConsumer) { + return new OrdiniRESTConsumer(restBuilder, executorService, systemRESTConsumer, entityRESTConsumer); } @Provides @@ -169,14 +176,14 @@ public class MainApplicationModule { @Provides @Singleton - CommessaRESTConsumer provideCommessaRESTConsumer(SystemRESTConsumer systemRESTConsumer) { - return new CommessaRESTConsumer(systemRESTConsumer); + CommessaRESTConsumer provideCommessaRESTConsumer(ExecutorService executorService, SystemRESTConsumer systemRESTConsumer) { + return new CommessaRESTConsumer(executorService, systemRESTConsumer); } @Provides @Singleton - DepositoRESTConsumer provideDepositoRESTConsumer(EntityRESTConsumer entityRESTConsumer, SystemRESTConsumer systemRESTConsumer) { - return new DepositoRESTConsumer(entityRESTConsumer, systemRESTConsumer); + DepositoRESTConsumer provideDepositoRESTConsumer(ExecutorService executorService, SystemRESTConsumer systemRESTConsumer) { + return new DepositoRESTConsumer(executorService, systemRESTConsumer); } @Provides @@ -199,18 +206,19 @@ public class MainApplicationModule { @Provides @Singleton - EntityRESTConsumer provideEntityRESTConsumer(RESTBuilder restBuilder) { - return new EntityRESTConsumer(restBuilder); + EntityRESTConsumer provideEntityRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService) { + return new EntityRESTConsumer(restBuilder, executorService); } @Provides @Singleton - ColliMagazzinoRESTConsumer provideColliMagazzinoRESTConsumer(RESTBuilder restBuilder, + ColliMagazzinoRESTConsumer provideColliMagazzinoRESTConsumer(ExecutorService executorService, + RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, ArticoloRESTConsumer articoloRESTConsumer, EntityRESTConsumer entityRESTConsumer, SettingsManager settingsManager) { - return new ColliMagazzinoRESTConsumer(restBuilder, systemRESTConsumer, articoloRESTConsumer, entityRESTConsumer, settingsManager); + return new ColliMagazzinoRESTConsumer(executorService, restBuilder, systemRESTConsumer, articoloRESTConsumer, entityRESTConsumer, settingsManager); } @Provides @@ -251,8 +259,8 @@ public class MainApplicationModule { @Provides @Singleton - PosizioniRESTConsumer providesPosizioniRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer) { - return new PosizioniRESTConsumer(restBuilder, systemRESTConsumer); + PosizioniRESTConsumer providesPosizioniRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, ExecutorService executorService) { + return new PosizioniRESTConsumer(restBuilder, systemRESTConsumer, executorService); } @Provides @@ -317,20 +325,20 @@ public class MainApplicationModule { @Provides @Singleton - ColliSpedizioneRESTConsumer provideColliSpedizioneRESTConsumer(RESTBuilder restBuilder) { - return new ColliSpedizioneRESTConsumer(restBuilder); + ColliSpedizioneRESTConsumer provideColliSpedizioneRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService) { + return new ColliSpedizioneRESTConsumer(restBuilder, executorService); } @Provides @Singleton - ColliLavorazioneRESTConsumer provideColliLavorazioneRESTConsumer(RESTBuilder restBuilder, SettingsManager settingsManager) { - return new ColliLavorazioneRESTConsumer(restBuilder, settingsManager); + ColliLavorazioneRESTConsumer provideColliLavorazioneRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, SettingsManager settingsManager) { + return new ColliLavorazioneRESTConsumer(restBuilder, executorService, settingsManager); } @Provides @Singleton - MagazzinoAutomaticoRESTConsumer provideMagazzinoAutomaticoRESTConsumer(RESTBuilder restBuilder) { - return new MagazzinoAutomaticoRESTConsumer(restBuilder); + MagazzinoAutomaticoRESTConsumer provideMagazzinoAutomaticoRESTConsumer(ExecutorService executorService, RESTBuilder restBuilder) { + return new MagazzinoAutomaticoRESTConsumer(executorService, restBuilder); } @Provides diff --git a/app/src/main/java/it/integry/integrywmsnative/SplashActivity.java b/app/src/main/java/it/integry/integrywmsnative/SplashActivity.java index 608dad3a..8527b644 100644 --- a/app/src/main/java/it/integry/integrywmsnative/SplashActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/SplashActivity.java @@ -5,6 +5,7 @@ import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; +import android.os.Handler; import android.text.SpannableString; import android.text.Spanned; import android.view.LayoutInflater; @@ -37,6 +38,9 @@ public class SplashActivity extends BaseActivity implements MainContext.Listener @Inject MainContext mainContext; + @Inject + Handler handler; + private RunnableArgsss> onRequestPermissionResult; public static void startActivity(Context context) { @@ -103,12 +107,12 @@ public class SplashActivity extends BaseActivity implements MainContext.Listener @Override public void onDBDataLoading(String item) { - runOnUiThread(() -> mBinding.loadingInfoTextview.setText("Caricamento " + item)); + handler.post(() -> mBinding.loadingInfoTextview.setText("Caricamento " + item)); } @Override public void onMenuLoading() { - runOnUiThread(() -> mBinding.loadingInfoTextview.setText("Caricamento menù")); + handler.post(() -> mBinding.loadingInfoTextview.setText("Caricamento menù")); } @Override @@ -151,11 +155,13 @@ public class SplashActivity extends BaseActivity implements MainContext.Listener @Override public void onError(Spanned message) { + handler.post(() -> { + DialogSimpleMessageView.makeErrorDialog( + message, null, this::finish, R.string.logout, () -> { + this.mainContext.logout(MainApplication::exit); + }) + .show(this.getSupportFragmentManager(), "tag"); - DialogSimpleMessageView.makeErrorDialog( - message, null, this::finish, R.string.logout, () -> { - this.mainContext.logout(MainApplication::exit); - }) - .show(this.getSupportFragmentManager(), "tag"); + }); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeCallbackDTO.java b/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeCallbackDTO.java index aa0a61d1..d154a9f6 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeCallbackDTO.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeCallbackDTO.java @@ -7,6 +7,7 @@ public class BarcodeCallbackDTO { private int ID = -1; + private boolean enabled = true; private RunnableArgs onScanSuccessfull; private RunnableArgs onScanFailed; @@ -19,6 +20,15 @@ public class BarcodeCallbackDTO { return this; } + public boolean isEnabled() { + return enabled; + } + + public BarcodeCallbackDTO setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + public RunnableArgs getOnScanSuccessfull() { return onScanSuccessfull; } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeManager.java b/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeManager.java index 6a426201..ab002713 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeManager.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/barcode_reader/BarcodeManager.java @@ -24,10 +24,15 @@ public class BarcodeManager { private static BarcodeReaderInterface mCurrentBarcodeInterface; private static final List mBarcodeCallbacksStacktrace = new ArrayList<>(); - private static boolean mEnabled = true; +// private static boolean mEnabled = true; - private static final Class[] registeredBarcodeReaderInterfaces = new Class[]{PointMobileBarcodeReader.class, ZebraBarcodeReader.class, HoneyWellBarcodeReader.class, KeyboardEmulatorBarcodeReader.class}; + private static final Class[] registeredBarcodeReaderInterfaces = new Class[]{ + PointMobileBarcodeReader.class, + ZebraBarcodeReader.class, + HoneyWellBarcodeReader.class, + KeyboardEmulatorBarcodeReader.class + }; public static void init(Context applicationContext) throws Exception { @@ -56,12 +61,12 @@ public class BarcodeManager { mCurrentBarcodeInterface.register(data -> { BarcodeCallbackDTO callback = getValidCallback(); - if (callback != null && mEnabled) { + if (callback != null && callback.isEnabled()) { callback.getOnScanSuccessfull().run(data); } }, ex -> { BarcodeCallbackDTO callback = getValidCallback(); - if (callback != null && mEnabled) { + if (callback != null && callback.isEnabled()) { callback.getOnScanFailed().run(ex); } }); @@ -103,7 +108,6 @@ public class BarcodeManager { } public static int addCallback(BarcodeCallbackDTO barcodeCallbackDTO) { - int newID = -1; if (!mBarcodeCallbacksStacktrace.isEmpty()) { @@ -133,18 +137,39 @@ public class BarcodeManager { } - public static void disable() { - mEnabled = false; -// UtilityLogger.info("Barcode reader disabled"); + public static void disable(int instanceId) { + mBarcodeCallbacksStacktrace.stream().filter(x -> x.getID() == instanceId) + .findFirst().ifPresent(x -> x.setEnabled(false)); } - public static void enable() { - mEnabled = true; -// UtilityLogger.info("Barcode reader enabled"); + public static void disableLastCallback() { + BarcodeCallbackDTO validCallback = getValidCallback(); + if (validCallback != null) { + validCallback.setEnabled(false); + } } - public static boolean isEnabled() { - return mEnabled; + public static void enable(int instanceId) { + mBarcodeCallbacksStacktrace.stream().filter(x -> x.getID() == instanceId) + .findFirst().ifPresent(x -> x.setEnabled(true)); + } + + public static void enableLastCallback() { + BarcodeCallbackDTO validCallback = getValidCallback(); + if (validCallback != null) { + validCallback.setEnabled(true); + } + } + + public static boolean isEnabled(int instanceId) { + return mBarcodeCallbacksStacktrace.stream().filter(x -> x.getID() == instanceId) + .findFirst() + .map(BarcodeCallbackDTO::isEnabled) + .orElse(false); + } + + public static boolean isLastCallbackEnabled() { + return getValidCallback() != null && getValidCallback().isEnabled(); } public static void changeSettings(List> settings) { diff --git a/app/src/main/java/it/integry/integrywmsnative/core/context/MainContext.java b/app/src/main/java/it/integry/integrywmsnative/core/context/MainContext.java index 42d3fe1b..99a1ec39 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/context/MainContext.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/context/MainContext.java @@ -1,6 +1,7 @@ package it.integry.integrywmsnative.core.context; import android.content.Context; +import android.os.Handler; import android.text.Html; import android.text.SpannableString; import android.text.Spanned; @@ -9,16 +10,15 @@ import android.text.SpannedString; import com.google.firebase.installations.FirebaseInstallations; import java.net.ConnectException; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager; import it.integry.integrywmsnative.core.data_store.db.AppDatabase; import it.integry.integrywmsnative.core.menu.MenuService; -import it.integry.integrywmsnative.core.rest.consumers.SystemRESTConsumer; import it.integry.integrywmsnative.core.rest.watcher.ServerStatusChecker; import it.integry.integrywmsnative.core.settings.SettingsManager; -import it.integry.integrywmsnative.core.utility.UtilityThread; import it.integry.integrywmsnative.gest.login.rest.AuthenticationRESTConsumer; @Singleton @@ -27,17 +27,21 @@ public class MainContext { private final Context applicationContext; private final MenuService menuService; private final AppDatabase appDatabase; - private final SystemRESTConsumer systemRESTConsumer; private final AuthenticationRESTConsumer authenticationRESTConsumer; + private final ExecutorService executorService; + private final Handler handler; + private final ServerStatusChecker serverStatusChecker; private Listener mListener; - public MainContext(Context applicationContext, MenuService menuService, AppDatabase appDatabase, SystemRESTConsumer systemRESTConsumer, AuthenticationRESTConsumer authenticationRESTConsumer) { + public MainContext(Context applicationContext, MenuService menuService, AppDatabase appDatabase, AuthenticationRESTConsumer authenticationRESTConsumer, ExecutorService executorService, Handler handler, ServerStatusChecker serverStatusChecker) { this.applicationContext = applicationContext; this.menuService = menuService; this.appDatabase = appDatabase; - this.systemRESTConsumer = systemRESTConsumer; this.authenticationRESTConsumer = authenticationRESTConsumer; + this.executorService = executorService; + this.handler = handler; + this.serverStatusChecker = serverStatusChecker; } public void init() { @@ -48,34 +52,31 @@ public class MainContext { } - //this.initAuthSession(() -> { -// this.initDeviceId(() -> { - this.initDBData(() -> { - this.initMenu(() -> { + executorService.execute(() -> { - if (mListener != null) mListener.onContextInitialized(); - }); - }); -// }); - //}); + try { + this.initDBData(); + this.initMenu(); + serverStatusChecker.init(); + if (mListener != null) mListener.onContextInitialized(); - this.initServerStatusChecker(); + } catch (Exception ex) { + Spanned message = null; -// EventBus.getDefault().register(this); + if (ex.getCause() != null && ex.getCause() instanceof ConnectException) { + message = Html.fromHtml("Impossibile collegarsi all'host " + SettingsManager.i().getServer().getHost() + ":" + SettingsManager.i().getServer().getPort() + ". Riprovare più tardi."); + } else if (ex.getMessage().startsWith("Status 404:")) { + message = Html.fromHtml("Errore 404. Non è stato possibile soddisfare la richiesta sull'host " + SettingsManager.i().getServer().getHost() + ":" + SettingsManager.i().getServer().getPort() + ". Riprovare più tardi."); + } else { + message = new SpannableString(ex.getMessage()); + } + + if (mListener != null) mListener.onError(message); + } + }); } -// @Subscribe(threadMode = ThreadMode.MAIN) -// public void onSessionExpired(SessionExpiredEvent event) { -// DialogSimpleMessageView.makeErrorDialog( -// new SpannedString("La sessione è scaduta. Effettua nuovamente la login"), -// null, -// () -> { -// logout(MainApplication::exit); -// }) -// .show(activity.getSupportFragmentManager(), "expired-session-error"); -// } - private void initAuthSession(Runnable onComplete) { this.authenticationRESTConsumer.me(obj -> { @@ -105,50 +106,28 @@ public class MainContext { public void logout(Runnable onLoggedOut) { menuService.invalidateCache(); - UtilityThread.executeParallel(() -> { + executorService.execute(() -> { SettingsManager.i().setUser(null); SettingsManager.i().setUserSession(null); SettingsManager.update(); appDatabase.clearAllTables(); - onLoggedOut.run(); - }, true); + handler.post(() -> { + onLoggedOut.run(); + }); + }); } - private void initServerStatusChecker() { - ServerStatusChecker.init(); - } - - private void initDBData(Runnable onComplete) { - + private void initDBData() throws Exception { SettingsManager.loadDBVariables(item -> { - if (mListener != null) mListener.onDBDataLoading(item); - }, - onComplete, - ex -> { - - Spanned message = null; - - if (ex.getCause() != null && ex.getCause() instanceof ConnectException) { - message = Html.fromHtml("Impossibile collegarsi all'host " + SettingsManager.i().getServer().getHost() + ":" + SettingsManager.i().getServer().getPort() + ". Riprovare più tardi."); - } else if (ex.getMessage().startsWith("Status 404:")) { - message = Html.fromHtml("Errore 404. Non è stato possibile soddisfare la richiesta sull'host " + SettingsManager.i().getServer().getHost() + ":" + SettingsManager.i().getServer().getPort() + ". Riprovare più tardi."); - } else { - message = new SpannableString(ex.getMessage()); - } - - if (mListener != null) mListener.onError(message); - - } - ); + if (mListener != null) mListener.onDBDataLoading(item); + }); } - private void initMenu(Runnable onComplete) { + private void initMenu() throws Exception { if (mListener != null) mListener.onMenuLoading(); - this.menuService.init(onComplete, ex -> { - if (mListener != null) mListener.onError(new SpannedString(ex.getMessage())); - }); + this.menuService.init(); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/di/Converters.java b/app/src/main/java/it/integry/integrywmsnative/core/di/Converters.java index 23dcca26..6b7ece87 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/di/Converters.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/di/Converters.java @@ -24,6 +24,10 @@ import androidx.databinding.BindingAdapter; import androidx.databinding.BindingConversion; import androidx.databinding.Observable; import androidx.databinding.ObservableField; +import androidx.lifecycle.LifecycleOwner; +import androidx.lifecycle.LiveData; +import androidx.lifecycle.Observer; +import androidx.lifecycle.ViewTreeLifecycleOwner; import com.google.android.material.datepicker.MaterialDatePicker; import com.google.android.material.textfield.TextInputEditText; @@ -820,11 +824,11 @@ public class Converters { @BindingAdapter("visibilityWhenNotNull") - public static void bindViewVisibilityWhenNotNull(View view, ObservableField bindableObject) { + public static void bindViewVisibilityObservableFieldWhenNotNull(View view, ObservableField bindableObject) { if(bindableObject == null) return; - if (view.getTag(R.id.bound_observable) != bindableObject) { - view.setTag(R.id.bound_observable, bindableObject); + if (view.getTag(R.id.bound_observable_visibility) != bindableObject) { + view.setTag(R.id.bound_observable_visibility, bindableObject); } bindableObject.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() { @@ -838,6 +842,36 @@ public class Converters { } + @BindingAdapter("visibilityWhenNotNull") + public static void bindViewVisibilityLiveDataWhenNotNull(View view, LiveData liveData) { + // Se il LiveData è null, nascondi la view e esci + if (liveData == null) { + view.setVisibility(View.GONE); + return; + } + + // Ottieni il LifecycleOwner dalla view + LifecycleOwner lifecycleOwner = ViewTreeLifecycleOwner.get(view); + if (lifecycleOwner == null) return; + + // Rimuovi eventuali observer precedenti + Observer oldObserver = (Observer) view.getTag(R.id.bound_observable_visibility); + if (oldObserver != null) { + liveData.removeObserver(oldObserver); + } + + // Crea e registra il nuovo observer + Observer newObserver = value -> + view.setVisibility(value == null ? View.GONE : View.VISIBLE); + + liveData.observe(lifecycleOwner, newObserver); + view.setTag(R.id.bound_observable_visibility, newObserver); + + // Imposta lo stato iniziale + view.setVisibility(liveData.getValue() == null ? View.GONE : View.VISIBLE); + } + + @BindingAdapter("visibilityWhenNotNull") public static void bindViewVisibilityWhenNotNull(View view, Object genericObject) { view.setVisibility(genericObject == null ? View.GONE : View.VISIBLE); @@ -845,7 +879,7 @@ public class Converters { @BindingAdapter("visibilityWhenNull") - public static void bindViewVisibilityWhenNull(View view, ObservableField bindableObject) { + public static void bindViewVisibilityObservableFieldWhenNull(View view, ObservableField bindableObject) { if (view.getTag(R.id.bound_observable_visibility) != bindableObject) { view.setTag(R.id.bound_observable_visibility, bindableObject); @@ -864,6 +898,36 @@ public class Converters { } + @BindingAdapter("visibilityWhenNull") + public static void bindViewVisibilityLiveDataWhenNull(View view, LiveData liveData) { + // Se il LiveData è null, nascondi la view e esci + if (liveData == null) { + view.setVisibility(View.VISIBLE); + return; + } + + // Ottieni il LifecycleOwner dalla view + LifecycleOwner lifecycleOwner = ViewTreeLifecycleOwner.get(view); + if (lifecycleOwner == null) return; + + // Rimuovi eventuali observer precedenti + Observer oldObserver = (Observer) view.getTag(R.id.bound_observable_visibility); + if (oldObserver != null) { + liveData.removeObserver(oldObserver); + } + + // Crea e registra il nuovo observer + Observer newObserver = value -> + view.setVisibility(value == null ? View.VISIBLE : View.GONE); + + liveData.observe(lifecycleOwner, newObserver); + view.setTag(R.id.bound_observable_visibility, newObserver); + + // Imposta lo stato iniziale + view.setVisibility(liveData.getValue() == null ? View.VISIBLE : View.GONE); + } + + @BindingAdapter({"reverse_visibility"}) public static void bindViewReverseVisibility(View view, final BindableBoolean bindableBoolean) { if (view.getTag(R.id.bound_reverse_visibility) != bindableBoolean) { diff --git a/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepBarcodeException.java b/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepBarcodeException.java index 8ea4be96..2fabfb53 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepBarcodeException.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepBarcodeException.java @@ -3,6 +3,6 @@ package it.integry.integrywmsnative.core.exception; public class InvalidCodMdepBarcodeException extends RuntimeException { public InvalidCodMdepBarcodeException(String message) { - super(message); + super("Il deposito scansionato non è valido: " + message); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepLUException.java b/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepException.java similarity index 69% rename from app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepLUException.java rename to app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepException.java index f4ee1b97..68ec7019 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepLUException.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/exception/InvalidCodMdepException.java @@ -3,13 +3,13 @@ package it.integry.integrywmsnative.core.exception; import it.integry.integrywmsnative.R; import it.integry.integrywmsnative.core.utility.UtilityResources; -public final class InvalidCodMdepLUException extends Exception { +public final class InvalidCodMdepException extends Exception { - public InvalidCodMdepLUException() { + public InvalidCodMdepException() { super(UtilityResources.getString(R.string.invalid_codmdep_error_message)); } - public InvalidCodMdepLUException(String codMdep) { + public InvalidCodMdepException(String codMdep) { super(UtilityResources.getString(R.string.invalid_codmdep_error_message) + "(" + codMdep + ")"); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseActivity.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseActivity.java index 7dd9641e..f7a358ef 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseActivity.java @@ -34,7 +34,6 @@ public class BaseActivity extends AppCompatActivity { } public void onLoadingStarted() { - BarcodeManager.disable(); this.openProgress(); } @@ -52,14 +51,14 @@ public class BaseActivity extends AppCompatActivity { private void openProgress() { - BarcodeManager.disable(); + BarcodeManager.disableLastCallback(); // executorService.execute(() -> { this.mCurrentProgress.show(getSupportFragmentManager()); // }); } private void closeProgress() { - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); // executorService.execute(() -> { mCurrentProgress.dismiss(); // }); @@ -67,7 +66,7 @@ public class BaseActivity extends AppCompatActivity { @Override public boolean dispatchKeyEvent(KeyEvent event) { - if (BarcodeManager.isEnabled() && BarcodeManager.isKeyboardEmulator()) { + if (BarcodeManager.isLastCallbackEnabled() && BarcodeManager.isKeyboardEmulator()) { if (event.getAction() == KeyEvent.ACTION_DOWN || event.getAction() == KeyEvent.ACTION_MULTIPLE && !isControlKey(event)) { return BarcodeManager.onKeyDown(event.getKeyCode(), event); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialog.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialog.java index f1473f04..2ffdc550 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialog.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialog.java @@ -14,7 +14,7 @@ public class BaseDialog extends Dialog { public BaseDialog(@NonNull Context context) { super(context); - if (BarcodeManager.isEnabled() && BarcodeManager.isKeyboardEmulator()) { + if (BarcodeManager.isLastCallbackEnabled() && BarcodeManager.isKeyboardEmulator()) { setOnKeyListener((dialog, keyCode, event) -> { if (mBarcodeListener && (event.getAction() == KeyEvent.ACTION_DOWN || event.getAction() == KeyEvent.ACTION_MULTIPLE) && !isControlKey(event)) { return BarcodeManager.onKeyDown(event.getKeyCode(), event); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialogFragment.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialogFragment.java index 42b9c1c0..eef851fd 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialogFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseDialogFragment.java @@ -65,25 +65,23 @@ public abstract class BaseDialogFragment extends DialogFragment implements Dialo } public void onLoadingStarted() { - BarcodeManager.disable(); this.openProgress(); } public void onLoadingEnded() { this.closeProgress(); - BarcodeManager.enable(); } private void openProgress() { - BarcodeManager.disable(); + BarcodeManager.disableLastCallback(); // executorService.execute(() -> { this.mCurrentProgress.show(requireActivity().getSupportFragmentManager()); // }); } private void closeProgress() { - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); // executorService.execute(() -> { mCurrentProgress.dismiss(); // }); @@ -91,9 +89,8 @@ public abstract class BaseDialogFragment extends DialogFragment implements Dialo public void onError(Exception ex) { - this.onLoadingEnded(); - requireActivity().runOnUiThread(() -> { + this.onLoadingEnded(); UtilityExceptions.defaultException(requireActivity(), ex); }); } @@ -130,7 +127,7 @@ public abstract class BaseDialogFragment extends DialogFragment implements Dialo .create() .inject(this); - if (BarcodeManager.isEnabled() && BarcodeManager.isKeyboardEmulator() && getDialog() != null) { + if (BarcodeManager.isLastCallbackEnabled() && BarcodeManager.isKeyboardEmulator() && getDialog() != null) { getDialog().setOnKeyListener((dialog, keyCode, event) -> { if (mBarcodeListener && (event.getAction() == KeyEvent.ACTION_DOWN || event.getAction() == KeyEvent.ACTION_MULTIPLE) && !isControlKey(event)) { return BarcodeManager.onKeyDown(event.getKeyCode(), event); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseFragment.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseFragment.java index ef260694..22bcaad5 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/BaseFragment.java @@ -69,14 +69,14 @@ public abstract class BaseFragment extends Fragment { } private void openProgress() { - BarcodeManager.disable(); + BarcodeManager.disableLastCallback(); // executorService.execute(() -> { this.mCurrentProgress.show(requireActivity().getSupportFragmentManager()); // }); } private void closeProgress() { - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); // executorService.execute(() -> { mCurrentProgress.dismiss(); // }); @@ -86,7 +86,6 @@ public abstract class BaseFragment extends Fragment { handler.post(() -> { this.closeProgress(); UtilityExceptions.defaultException(getActivity(), ex); - BarcodeManager.enable(); }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerViewNew.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerViewNew.java new file mode 100644 index 00000000..5f25ac46 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerViewNew.java @@ -0,0 +1,44 @@ +package it.integry.integrywmsnative.core.expansion.view; + +import android.view.View; + +import androidx.databinding.ObservableArrayList; +import androidx.databinding.ObservableList; +import androidx.recyclerview.widget.RecyclerView; + +import it.integry.integrywmsnative.core.expansion.OnListGeneralChangedCallback; + +public abstract class ExtendedSectionedRecyclerViewNew + extends SectionedRecyclerViewAdapter { + + private View mEmptyView; + + public ExtendedSectionedRecyclerViewNew(ObservableArrayList myDataset) { + super(); + + myDataset.addOnListChangedCallback(new OnListGeneralChangedCallback() { + @Override + public void onChanged(ObservableList sender) { + checkIfEmpty(); + } + }); + + checkIfEmpty(); + } + + public ExtendedSectionedRecyclerViewNew setEmptyView(View emptyView) { + this.mEmptyView = emptyView; + this.checkIfEmpty(); + return this; + } + + + + private void checkIfEmpty() { + if (mEmptyView != null) { + final boolean emptyViewVisible = getItemCount() == 0; + mEmptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE); + } + } + +} diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/RecyclerViewProfiler.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/RecyclerViewProfiler.java new file mode 100644 index 00000000..620942b0 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/RecyclerViewProfiler.java @@ -0,0 +1,218 @@ +package it.integry.integrywmsnative.core.expansion.view; + +import android.os.Handler; +import android.os.Looper; +import android.util.Log; +import android.util.SparseArray; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import java.lang.ref.WeakReference; +import java.util.ArrayDeque; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +public class RecyclerViewProfiler { + private static final String TAG = "RVProfiler"; + private final SparseArray bindingTimes; + private final SparseArray creationTimes; + private final Handler mainHandler; + private WeakReference recyclerViewRef; + private boolean isProfilingEnabled = true; + + // Metriche di performance + private long totalBindingTime = 0; + private long totalCreationTime = 0; + private int bindCount = 0; + private int createCount = 0; + private long firstBindTime = 0; + private final ArrayDeque recentBindTimes; + private static final int MAX_RECENT_TIMES = 50; + + public RecyclerViewProfiler(RecyclerView recyclerView) { + this.recyclerViewRef = new WeakReference<>(recyclerView); + this.bindingTimes = new SparseArray<>(); + this.creationTimes = new SparseArray<>(); + this.mainHandler = new Handler(Looper.getMainLooper()); + this.recentBindTimes = new ArrayDeque<>(); + + setupRecyclerViewCallbacks(); + } + + private void setupRecyclerViewCallbacks() { + RecyclerView recyclerView = recyclerViewRef.get(); + if (recyclerView == null) return; + + recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + logPerformanceMetrics(); + } + } + }); + + // Monitora il pre-layout + recyclerView.addOnLayoutChangeListener((v, left, top, right, bottom, + oldLeft, oldTop, oldRight, oldBottom) -> { + if (firstBindTime == 0) { + mainHandler.postDelayed(this::checkInitialPerformance, 500); + } + }); + } + + public void onPreBind(int position) { + if (!isProfilingEnabled) return; + bindingTimes.put(position, System.nanoTime()); + } + + public void onPostBind(int position) { + if (!isProfilingEnabled) return; + + Long startTime = bindingTimes.get(position); + if (startTime != null) { + long bindTime = System.nanoTime() - startTime; + bindingTimes.remove(position); + + if (firstBindTime == 0) { + firstBindTime = bindTime; + } + + totalBindingTime += bindTime; + bindCount++; + + recentBindTimes.addLast(bindTime); + if (recentBindTimes.size() > MAX_RECENT_TIMES) { + recentBindTimes.removeFirst(); + } + + // Segnala binding lenti + if (bindTime > TimeUnit.MILLISECONDS.toNanos(16)) { // 1 frame + Log.w(TAG, String.format("Slow binding at position %d: %.2fms", + position, bindTime / 1_000_000.0)); + } + } + } + + public void onPreCreate(int viewType) { + if (!isProfilingEnabled) return; + creationTimes.put(viewType, System.nanoTime()); + } + + public void onPostCreate(int viewType) { + if (!isProfilingEnabled) return; + + Long startTime = creationTimes.get(viewType); + if (startTime != null) { + long createTime = System.nanoTime() - startTime; + creationTimes.remove(viewType); + + totalCreationTime += createTime; + createCount++; + + // Segnala creazioni lente + if (createTime > TimeUnit.MILLISECONDS.toNanos(8)) { + Log.w(TAG, String.format("Slow view creation for type %d: %.2fms", + viewType, createTime / 1_000_000.0)); + } + } + } + + private void checkInitialPerformance() { + RecyclerView recyclerView = recyclerViewRef.get(); + if (recyclerView == null) return; + + // Verifica inflazione layout + long avgBindTime = bindCount > 0 ? totalBindingTime / bindCount : 0; + if (avgBindTime > TimeUnit.MILLISECONDS.toNanos(8)) { + Log.w(TAG, String.format("High average binding time: %.2fms. " + + "Consider using AsyncLayoutInflater", avgBindTime / 1_000_000.0)); + } + + // Verifica dimensione view pool + RecyclerView.RecycledViewPool pool = recyclerView.getRecycledViewPool(); + if (pool != null) { + int[] viewTypes = getViewTypes(recyclerView); + for (int type : viewTypes) { + if (pool.getRecycledViewCount(type) == 0) { + Log.w(TAG, "ViewPool empty for type " + type + + ". Consider increasing pool size"); + } + } + } + + // Verifica prefetch + if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) { + LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager(); + if (!lm.isItemPrefetchEnabled()) { + Log.w(TAG, "Item prefetch is disabled. Enable it for better performance"); + } + } + } + + private void logPerformanceMetrics() { + if (!isProfilingEnabled || recentBindTimes.isEmpty()) return; + + // Calcola la varianza dei tempi di binding recenti + double mean = recentBindTimes.stream() + .mapToLong(Long::longValue) + .average() + .orElse(0.0); + + double variance = recentBindTimes.stream() + .mapToDouble(time -> Math.pow(time - mean, 2)) + .average() + .orElse(0.0); + + Log.d(TAG, String.format("Performance metrics:\n" + + "Avg binding time: %.2fms\n" + + "Binding time variance: %.2f\n" + + "View creation rate: %.1f%%", + mean / 1_000_000.0, + variance / 1_000_000.0, + createCount * 100.0 / (bindCount + 1))); + } + + private int[] getViewTypes(RecyclerView recyclerView) { + RecyclerView.Adapter adapter = recyclerView.getAdapter(); + if (adapter == null) return new int[0]; + + Set types = new HashSet<>(); + for (int i = 0; i < adapter.getItemCount(); i++) { + types.add(adapter.getItemViewType(i)); + } + return types.stream().mapToInt(Integer::intValue).toArray(); + } + + public void enableProfiling(boolean enabled) { + isProfilingEnabled = enabled; + if (!enabled) { + bindingTimes.clear(); + creationTimes.clear(); + recentBindTimes.clear(); + } + } + + public String getProfilingStats() { + if (bindCount == 0) return "No data collected yet"; + + return String.format(Locale.US, + "Profiling Statistics:\n" + + "Total bindings: %d\n" + + "Average binding time: %.2fms\n" + + "Total view creations: %d\n" + + "Average creation time: %.2fms\n" + + "First binding time: %.2fms\n" + + "Creation/Binding ratio: %.1f%%", + bindCount, + (totalBindingTime / bindCount) / 1_000_000.0, + createCount, + (totalCreationTime / createCount) / 1_000_000.0, + firstBindTime / 1_000_000.0, + createCount * 100.0 / bindCount); + } +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/SectionedRecyclerViewAdapter.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/SectionedRecyclerViewAdapter.java new file mode 100644 index 00000000..80ccea3e --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/SectionedRecyclerViewAdapter.java @@ -0,0 +1,352 @@ +package it.integry.integrywmsnative.core.expansion.view; + +import android.util.SparseArray; +import android.util.SparseIntArray; +import android.view.ViewGroup; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import it.integry.integrywmsnative.BuildConfig; + +public abstract class SectionedRecyclerViewAdapter extends RecyclerView.Adapter { + + private RecyclerViewProfiler profiler; + + private static final int TYPE_HEADER = 0; + private static final int TYPE_ITEM = 1; + + // Utilizziamo SparseArray invece di HashMap per migliori performance su Android + private final SparseArray
sectionsByPosition; + private final ArrayList
sections; + + // Cache per le posizioni degli item per evitare ricalcoli frequenti + private final SparseIntArray positionCache; + private int lastCacheUpdateCount; + + // Pool di View per riutilizzo + private final RecyclerView.RecycledViewPool sharedPool; + + // Dimensione massima della cache delle posizioni + private static final int MAX_POSITION_CACHE_SIZE = 2000; + + public SectionedRecyclerViewAdapter() { + this.sections = new ArrayList<>(); + this.sectionsByPosition = new SparseArray<>(); + this.positionCache = new SparseIntArray(MAX_POSITION_CACHE_SIZE); + this.sharedPool = new RecyclerView.RecycledViewPool(); + + // Aumentiamo il pool di ViewHolder per tipo + sharedPool.setMaxRecycledViews(TYPE_HEADER, 500); + sharedPool.setMaxRecycledViews(TYPE_ITEM, 2000); + } + + @Override + public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { + super.onAttachedToRecyclerView(recyclerView); + profiler = new RecyclerViewProfiler(recyclerView); + profiler.enableProfiling(BuildConfig.DEBUG); + + recyclerView.setRecycledViewPool(sharedPool); + + // Ottimizziamo il layout manager per le prestazioni + if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) { + LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); + layoutManager.setItemPrefetchEnabled(true); +// layoutManager.setInitialPrefetchItemCount(20); + } + +// recyclerView.postDelayed(() -> { + // Precarica alcuni ViewHolder +// for (int i = 0; i < 100; i++) { +// sharedPool.putRecycledView( +// createViewHolder(recyclerView, TYPE_HEADER)); +// } +// for (int i = 0; i < 100; i++) { +// sharedPool.putRecycledView( +// createViewHolder(recyclerView, TYPE_ITEM)); +// } +// }, 50); + } + + protected static class Section { + private final Object headerData; + private final ArrayList itemsData; + private int globalStartPosition; // Posizione globale di inizio sezione + + public Section(Object headerData, int initialCapacity) { + this.headerData = headerData; + this.itemsData = new ArrayList<>(initialCapacity); + this.globalStartPosition = 0; + } + + public Object getHeaderData() { + return headerData; + } + + public List getItemsData() { + return itemsData; + } + + public void addItem(Object item) { + itemsData.add(item); + } + + public int getItemCount() { + return itemsData.size(); + } + + public void setGlobalStartPosition(int position) { + this.globalStartPosition = position; + } + + public int getGlobalStartPosition() { + return globalStartPosition; + } + } + + // ViewHolder pooling e caching + @Override + public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { + super.onViewRecycled(holder); + // Pulizia custom del ViewHolder se necessario + if (holder instanceof OnRecycleListener) { + ((OnRecycleListener) holder).onRecycle(); + } + } + + // Interfaccia per gestire la pulizia custom dei ViewHolder + public interface OnRecycleListener { + void onRecycle(); + } + + @Override + @NonNull + public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + profiler.onPreCreate(viewType); + RecyclerView.ViewHolder holder; + if (viewType == TYPE_HEADER) { + holder = onCreateHeaderViewHolder(parent); + } else { + holder = onCreateItemViewHolder(parent); + } + + // Applichiamo ViewHolder pooling + if (holder.itemView.getLayoutParams() == null) { + holder.itemView.setLayoutParams( + new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) + ); + } + + profiler.onPostCreate(viewType); + return holder; + } + + @Override + public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { + profiler.onPreBind(position); + PositionInfo posInfo = getItemPositionInfo(position); + + if (getItemViewType(position) == TYPE_HEADER) { + onBindHeaderViewHolder((H) holder, + sections.get(posInfo.sectionPosition).getHeaderData(), + posInfo.sectionPosition); + } else { + Section section = sections.get(posInfo.sectionPosition); + onBindItemViewHolder((I) holder, + section.getItemsData().get(posInfo.itemPosition), + posInfo.sectionPosition, + posInfo.itemPosition); + } + profiler.onPostBind(position); + } + + @Override + public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List payloads) { + if (payloads.isEmpty()) { + super.onBindViewHolder(holder, position, payloads); + return; + } + + // Supporto per aggiornamenti parziali + if (getItemViewType(position) == TYPE_HEADER) { + onBindHeaderViewHolderPartial((H) holder, position, payloads); + } else { + onBindItemViewHolderPartial((I) holder, position, payloads); + } + } + + // Metodi per gestire aggiornamenti parziali + protected void onBindHeaderViewHolderPartial(H holder, int position, List payloads) { + onBindViewHolder(holder, position); + } + + protected void onBindItemViewHolderPartial(I holder, int position, List payloads) { + onBindViewHolder(holder, position); + } + + @Override + public int getItemCount() { + int count = 0; + for (Section section : sections) { + count += section.getItemCount() + 1; + } + return count; + } + + @Override + public int getItemViewType(int position) { + return isHeader(position) ? TYPE_HEADER : TYPE_ITEM; + } + + // Metodi ottimizzati per la gestione delle sezioni + public void addSection(T headerData, int expectedItems) { + sections.add(new Section(headerData, expectedItems)); + updatePositionCache(); + notifyDataSetChanged(); + } + + public void addItem(int sectionPosition, Object item) { + if (sectionPosition >= 0 && sectionPosition < sections.size()) { + sections.get(sectionPosition).addItem(item); + updatePositionCache(); + // Notifichiamo solo l'inserimento invece di un refresh completo + notifyItemInserted(getGlobalPositionForItem(sectionPosition, + sections.get(sectionPosition).getItemCount() - 1)); + } + } + + public void setSections(List headers, Map> items) { + sections.clear(); + sectionsByPosition.clear(); + + int position = 0; + for (T header : headers) { + List sectionItems = items.get(header); + Section section = new Section(header, sectionItems != null ? sectionItems.size() : 5); + if (sectionItems != null) { + section.getItemsData().addAll(sectionItems); + } + section.setGlobalStartPosition(position); + sections.add(section); + sectionsByPosition.put(position, section); + + position += section.getItemCount() + 1; + } + + updatePositionCache(); + notifyDataSetChanged(); + } + + // Gestione efficiente della cache delle posizioni + private void updatePositionCache() { + if (sections.size() > MAX_POSITION_CACHE_SIZE) { + positionCache.clear(); + return; + } + + int currentPosition = 0; + for (int i = 0; i < sections.size(); i++) { + Section section = sections.get(i); + section.setGlobalStartPosition(currentPosition); + sectionsByPosition.put(currentPosition, section); + currentPosition += section.getItemCount() + 1; + } + + lastCacheUpdateCount = getItemCount(); + } + + private boolean isHeader(int position) { + Section section = sectionsByPosition.get(position); + if (section != null) { + return true; + } + + for (int i = 0; i < sections.size(); i++) { + section = sections.get(i); + if (position == section.getGlobalStartPosition()) { + return true; + } + if (position < section.getGlobalStartPosition() + section.getItemCount() + 1) { + return false; + } + } + return false; + } + + private static class PositionInfo { + final int sectionPosition; + final int itemPosition; + + PositionInfo(int sectionPosition, int itemPosition) { + this.sectionPosition = sectionPosition; + this.itemPosition = itemPosition; + } + } + + private PositionInfo getItemPositionInfo(int position) { + // Controllo cache + int cachedSection = positionCache.get(position, -1); + if (cachedSection != -1 && lastCacheUpdateCount == getItemCount()) { + Section section = sections.get(cachedSection); + int relativePos = position - section.getGlobalStartPosition(); + if (relativePos == 0) { + return new PositionInfo(cachedSection, -1); + } + return new PositionInfo(cachedSection, relativePos - 1); + } + + // Ricerca ottimizzata + Section targetSection = sectionsByPosition.get(position); + if (targetSection != null) { + int sectionIndex = sections.indexOf(targetSection); + return new PositionInfo(sectionIndex, -1); + } + + // Ricerca binaria nelle sezioni + int left = 0; + int right = sections.size() - 1; + + while (left <= right) { + int mid = (left + right) >>> 1; + Section section = sections.get(mid); + int sectionStart = section.getGlobalStartPosition(); + int sectionEnd = sectionStart + section.getItemCount() + 1; + + if (position >= sectionStart && position < sectionEnd) { + int relativePos = position - sectionStart; + if (relativePos == 0) { + return new PositionInfo(mid, -1); + } + return new PositionInfo(mid, relativePos - 1); + } + + if (position < sectionStart) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + throw new IndexOutOfBoundsException("Position " + position + " is out of bounds"); + } + + private int getGlobalPositionForItem(int sectionPosition, int itemPosition) { + return sections.get(sectionPosition).getGlobalStartPosition() + itemPosition + 1; + } + + // Metodi astratti che devono essere implementati + protected abstract H onCreateHeaderViewHolder(ViewGroup parent); + protected abstract I onCreateItemViewHolder(ViewGroup parent); + protected abstract void onBindHeaderViewHolder(H holder, Object headerData, int sectionPosition); + protected abstract void onBindItemViewHolder(I holder, Object itemData, int sectionPosition, int itemPosition); +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuRESTConsumer.java index 19f8b95d..51288205 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuRESTConsumer.java @@ -1,17 +1,10 @@ package it.integry.integrywmsnative.core.menu; -import androidx.annotation.NonNull; - import javax.inject.Singleton; -import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.model.StbMenu; import it.integry.integrywmsnative.core.rest.RESTBuilder; import it.integry.integrywmsnative.core.rest.consumers._BaseRESTConsumer; -import it.integry.integrywmsnative.core.rest.handler.ManagedErrorCallback; -import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; -import retrofit2.Call; -import retrofit2.Response; @Singleton public class MenuRESTConsumer extends _BaseRESTConsumer { @@ -22,19 +15,12 @@ public class MenuRESTConsumer extends _BaseRESTConsumer { this.restBuilder = restBuilder; } - public void retrieveMenu(String rootCodOpz, RunnableArgs onComplete, RunnableArgs onFailed) { + public StbMenu retrieveMenuSynchronized(String rootCodOpz) throws Exception { MenuRESTConsumerService menuRESTConsumerService = restBuilder.getService(MenuRESTConsumerService.class); - menuRESTConsumerService.retrieveMenuConfig(rootCodOpz).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "retrieveMenu", onComplete, onFailed); - } + var response = menuRESTConsumerService.retrieveMenuConfig(rootCodOpz) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + return analyzeAnswer(response, "retrieveMenu"); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuService.java b/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuService.java index 155e87d9..9868a0c8 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuService.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/menu/MenuService.java @@ -10,7 +10,6 @@ import javax.inject.Singleton; import it.integry.integrywmsnative.core.class_router.configs.BaseMenuConfiguration; import it.integry.integrywmsnative.core.class_router.configs.MenuConfiguration; -import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.menu.exception.MenuNotFoundException; import it.integry.integrywmsnative.core.model.StbMenu; @@ -29,20 +28,18 @@ public class MenuService { this.menuRESTConsumer = menuRESTConsumer; } - public void init(Runnable onMenuInitialized, RunnableArgs onFailed) { - menuRESTConsumer.retrieveMenu(MENU_COD_OPZ, menu -> { - if(menu != null) { - this.mInternalCachedMenu = menu.getStbMenuChildren(); - this.mInternalCachedFlatMenu = new ArrayList<>(); - flattenMenu(this.mInternalCachedMenu); - } + public void init() throws Exception { + var menu = menuRESTConsumer.retrieveMenuSynchronized(MENU_COD_OPZ); - onMenuInitialized.run(); - }, onFailed); + if (menu != null) { + this.mInternalCachedMenu = menu.getStbMenuChildren(); + this.mInternalCachedFlatMenu = new ArrayList<>(); + flattenMenu(this.mInternalCachedMenu); + } } public List getMenu() throws Exception { - if(mInternalCachedMenu == null) throw new MenuNotFoundException(); + if (mInternalCachedMenu == null) throw new MenuNotFoundException(); return mInternalCachedMenu; } @@ -64,10 +61,10 @@ public class MenuService { } private void flattenMenu(List menu) { - for(StbMenu stbMenu : menu) { + for (StbMenu stbMenu : menu) { this.mInternalCachedFlatMenu.add(stbMenu); - if(stbMenu.getStbMenuChildren() != null && !stbMenu.getStbMenuChildren().isEmpty()) { + if (stbMenu.getStbMenuChildren() != null && !stbMenu.getStbMenuChildren().isEmpty()) { flattenMenu(stbMenu.getStbMenuChildren()); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbAart.java b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbAart.java index f575dcf9..fca85348 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbAart.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbAart.java @@ -1,6 +1,7 @@ package it.integry.integrywmsnative.core.model; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.List; import it.integry.integrywmsnative.core.utility.UtilityString; @@ -108,6 +109,104 @@ public class MtbAart extends EntityBase { this.type = "mtb_aart"; } + public MtbAart(MtbAart other) { + this(); + + this.codMart = other.codMart; + this.descrizione = other.descrizione; + this.untMis = other.untMis; + this.barCode = other.barCode; + this.pesoKg = other.pesoKg; // BigDecimal è immutabile + this.qtaCnf = other.qtaCnf; + this.codAliq = other.codAliq; + this.codScoArt = other.codScoArt; + this.codTcolUi = other.codTcolUi; + this.codTcolUl = other.codTcolUl; + this.articoloComposto = other.articoloComposto; + this.esposizioneComp = other.esposizioneComp; + this.descrizioneEstesa = other.descrizioneEstesa; + this.codUltForn = other.codUltForn; + this.dataUltCar = other.dataUltCar; + this.valUltCar = other.valUltCar; + this.codUltClie = other.codUltClie; + this.dataUltScar = other.dataUltScar; + this.valUltScar = other.valUltScar; + this.tipoCodice = other.tipoCodice; + this.note = other.note; + this.posizione = other.posizione; + this.colliPedana = other.colliPedana; + this.untMis2 = other.untMis2; + this.rapConv2 = other.rapConv2; + this.flagInclListino = other.flagInclListino; + this.untMis3 = other.untMis3; + this.rapConv3 = other.rapConv3; + this.codMartStat = other.codMartStat; + this.codMcon = other.codMcon; + this.codMgrp = other.codMgrp; + this.codMsfa = other.codMsfa; + this.codMsgr = other.codMsgr; + this.codMstp = other.codMstp; + this.codMtip = other.codMtip; + this.descrizioneStat = other.descrizioneStat; + this.flagStato = other.flagStato; + this.cambioDiviCar = other.cambioDiviCar; + this.cambioDiviScar = other.cambioDiviScar; + this.ggScadPartita = other.ggScadPartita; + this.volumeMc = other.volumeMc; + this.flagEsponiPrz = other.flagEsponiPrz; + this.dataUltVar = other.dataUltVar; + this.percSfrido = other.percSfrido; + this.codBarreImb = other.codBarreImb; + this.flagCalcPrz = other.flagCalcPrz; + this.esposizioneCompAcq = other.esposizioneCompAcq; + this.flagCalcPrzAcq = other.flagCalcPrzAcq; + this.diacod = other.diacod; + this.plu = other.plu; + this.partIvaProd = other.partIvaProd; + this.ragSocProd = other.ragSocProd; + this.flagRapConvVariabile = other.flagRapConvVariabile; + this.flagMovArtMag = other.flagMovArtMag; + this.flagTracciabilita = other.flagTracciabilita; + this.taraKg = other.taraKg; + this.colliStrato = other.colliStrato; + this.flagQtaCnfFissa = other.flagQtaCnfFissa; + this.flagColliPedanaFisso = other.flagColliPedanaFisso; + this.codCconCosti = other.codCconCosti; + this.codCconRicavi = other.codCconRicavi; + this.codDgrpArt = other.codDgrpArt; + this.codDiviCar = other.codDiviCar; + this.codDiviScar = other.codDiviScar; + this.codEcrCat = other.codEcrCat; + this.codEcrMcat = other.codEcrMcat; + this.codEcrRep = other.codEcrRep; + this.codEcrStipo = other.codEcrStipo; + this.codEcrTipo = other.codEcrTipo; + this.codGrpBolla = other.codGrpBolla; + this.ingredienti = other.ingredienti; + this.idArtEqui = other.idArtEqui; + this.descrCassa = other.descrCassa; + this.codNcIntracee = other.codNcIntracee; + this.marchio = other.marchio; + this.sezione = other.sezione; + this.untMisRifPeso = other.untMisRifPeso; // Enum è immutabile + + this.qtaEsistente = other.qtaEsistente; + this.qtaImpegnata = other.qtaImpegnata; + this.numCnfEsistente = other.numCnfEsistente; + this.numCnfImpegnata = other.numCnfImpegnata; + + // Deep copy della lista + if (other.mtbUntMis != null) { + this.mtbUntMis = new ArrayList<>(); + for (MtbUntMis untMis : other.mtbUntMis) { + this.mtbUntMis.add(new MtbUntMis(untMis)); // Assicurati che MtbUntMis abbia un costruttore di copia + } + } + } + + + + public boolean isFlagTracciabilitaBoolean() { return flagTracciabilita != null && flagTracciabilita.equalsIgnoreCase("S"); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColr.java b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColr.java index 69667c4d..dec4ae35 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColr.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColr.java @@ -67,6 +67,58 @@ public class MtbColr extends EntityBase { } } + public MtbColr(MtbColr other) { + this(); + + this.gestione = other.gestione; + this.serCollo = other.serCollo; + this.numCollo = other.numCollo; + this.dataCollo = other.dataCollo; + this.riga = other.riga; + this.rigaOrd = other.rigaOrd; + this.codMart = other.codMart; + this.codBarre = other.codBarre; + this.codCol = other.codCol; + this.codTagl = other.codTagl; + this.partitaMag = other.partitaMag; + this.gestioneRif = other.gestioneRif; + this.serColloRif = other.serColloRif; + this.note = other.note; + this.dataOrd = other.dataOrd; // LocalDate è immutabile + this.dataColloRif = other.dataColloRif; + this.qtaCnf = other.qtaCnf; // BigDecimal è immutabile + this.qtaCol = other.qtaCol; + this.numOrd = other.numOrd; + this.numEtich = other.numEtich; + this.numColloRif = other.numColloRif; + this.datetimeRow = other.datetimeRow; + this.codJcom = other.codJcom; + this.numCnf = other.numCnf; + this.insPartitaMag = other.insPartitaMag; + this.mtbPartitaMag_descrizione = other.mtbPartitaMag_descrizione; + this.dataScadPartita = other.dataScadPartita; + this.descrizione = other.descrizione; + this.untMis = other.untMis; + this.causale = other.causale; + this.utente = other.utente; + this.codAnagDoc = other.codAnagDoc; + this.codDtipDoc = other.codDtipDoc; + this.dataDoc = other.dataDoc; + this.serDoc = other.serDoc; + this.numDoc = other.numDoc; + this.idRigaDoc = other.idRigaDoc; + this.pesoNettoKg = other.pesoNettoKg; + this.pesoLordoKg = other.pesoLordoKg; + + // Deep copy degli oggetti complessi + this.mtbAart = other.mtbAart != null ? new MtbAart(other.mtbAart) : null; + this.mtbPartitaMag = other.mtbPartitaMag != null ? new MtbPartitaMag(other.mtbPartitaMag) : null; + + // Non copiamo i campi transient + // this.id = other.id; + // this.refMtbColr = other.refMtbColr; + } + public static class Causale { public static final int DEFAULT = 0; diff --git a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColt.java b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColt.java index 8fe74188..dfad9b2d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColt.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbColt.java @@ -3,7 +3,7 @@ package it.integry.integrywmsnative.core.model; import android.text.TextUtils; import androidx.databinding.ObservableArrayList; -import androidx.databinding.ObservableField; +import androidx.lifecycle.MutableLiveData; import com.annimon.stream.Optional; import com.annimon.stream.Stream; @@ -66,7 +66,9 @@ public class MtbColt extends EntityBase { private BigDecimal altezzaCm; private String codJcom; - private final ObservableField mtbTCol = new ObservableField<>(); + private String barcodeUl; + + private final transient MutableLiveData mtbTCol = new MutableLiveData<>(); private Boolean disablePrint; private String ragSocCliente; @@ -261,7 +263,7 @@ public class MtbColt extends EntityBase { public MtbColt setCodTcol(String codTcol) { this.codTcol = codTcol; - if(!UtilityString.isNullOrEmpty(codTcol)) { + if (!UtilityString.isNullOrEmpty(codTcol)) { var fountMtbTcolObservable = SettingsManager.iDB().getInternalImballi().stream() .filter(x -> x.getCodTcol().equalsIgnoreCase(codTcol)) .findFirst() @@ -544,16 +546,25 @@ public class MtbColt extends EntityBase { return this; } - public ObservableMtbTcol getMtbTCol() { - return mtbTCol.get(); + public String getBarcodeUl() { + return barcodeUl; } - public MtbColt setMtbTCol(ObservableMtbTcol mtbTCol) { - this.mtbTCol.set(mtbTCol); + public MtbColt setBarcodeUl(String barcodeUl) { + this.barcodeUl = barcodeUl; return this; } - public ObservableField mtbTcolProperty() { + public ObservableMtbTcol getMtbTCol() { + return mtbTCol.getValue(); + } + + public MtbColt setMtbTCol(ObservableMtbTcol mtbTCol) { + this.mtbTCol.postValue(mtbTCol); + return this; + } + + public MutableLiveData mtbTcolProperty() { return mtbTCol; } @@ -631,8 +642,20 @@ public class MtbColt extends EntityBase { @Override public EntityBase clone() { + return clone(true); + } + + public MtbColt clone(boolean withMtbColr) { MtbColt mtbColt = (MtbColt) super.clone(); - mtbColt.setMtbColr((ObservableArrayList) mtbColt.getMtbColr().clone()); + mtbColt.setMtbColr(new ObservableArrayList<>()); + + if(!withMtbColr) return mtbColt; + + this.getMtbColr().stream() + .map(MtbColr::new) //Genera un clone + .forEach(mtbColr -> { + mtbColt.getMtbColr().add(mtbColr); + }); return mtbColt; } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbPartitaMag.java b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbPartitaMag.java index 909930c0..5fd2429d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbPartitaMag.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbPartitaMag.java @@ -4,34 +4,60 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; -public class MtbPartitaMag extends EntityBase{ - private String codMart; - - private String partitaMag; - private String descrizione; +public class MtbPartitaMag extends EntityBase { + private String codMart; + + private String partitaMag; + private String descrizione; private LocalDateTime dataIns; private LocalDate dataScad; - private Integer scelta; + private Integer scelta; private BigDecimal costoUntUmMag; - private BigDecimal valUntUmMag; - private BigDecimal taraCnfKg; - private BigDecimal qtaCnf; - private String flagImballoArendere; - private String flagStato; - private String codDiviCont; - private BigDecimal cambioDiviCont; - private String barcode; - private String note; - private BigDecimal rapConv2; - private BigDecimal rapConv3; - private String posizione; + private BigDecimal valUntUmMag; + private BigDecimal taraCnfKg; + private BigDecimal qtaCnf; + private String flagImballoArendere; + private String flagStato; + private String codDiviCont; + private BigDecimal cambioDiviCont; + private String barcode; + private String note; + private BigDecimal rapConv2; + private BigDecimal rapConv3; + private String posizione; private String dataAggPrz; - private String partitaMagSec; + private String partitaMagSec; private BigDecimal qtaAttesa; public MtbPartitaMag() { this.type = "mtb_partita_mag"; } + public MtbPartitaMag(MtbPartitaMag other) { + this(); + + this.codMart = other.codMart; + this.partitaMag = other.partitaMag; + this.descrizione = other.descrizione; + this.dataIns = other.dataIns; // LocalDateTime è immutabile + this.dataScad = other.dataScad; // LocalDate è immutabile + this.scelta = other.scelta; + this.costoUntUmMag = other.costoUntUmMag; // BigDecimal è immutabile + this.valUntUmMag = other.valUntUmMag; + this.taraCnfKg = other.taraCnfKg; + this.qtaCnf = other.qtaCnf; + this.flagImballoArendere = other.flagImballoArendere; + this.flagStato = other.flagStato; + this.codDiviCont = other.codDiviCont; + this.cambioDiviCont = other.cambioDiviCont; + this.barcode = other.barcode; + this.note = other.note; + this.rapConv2 = other.rapConv2; + this.rapConv3 = other.rapConv3; + this.posizione = other.posizione; + this.dataAggPrz = other.dataAggPrz; + this.partitaMagSec = other.partitaMagSec; + this.qtaAttesa = other.qtaAttesa; + } public String getCodMart() { diff --git a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbUntMis.java b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbUntMis.java index 8507338e..69b528d5 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/model/MtbUntMis.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/model/MtbUntMis.java @@ -15,6 +15,18 @@ public class MtbUntMis extends EntityBase { this.type = "mtb_unt_mis"; } + // Costruttore di copia + public MtbUntMis(MtbUntMis other) { + this(); + + this.untMis = other.untMis; + this.flagDig = other.flagDig; + this.cifreDec = other.cifreDec; // BigDecimal è immutabile + this.tipoUm = other.tipoUm; + this.flagUnitaKg = other.flagUnitaKg; + this.flagAttivo = other.flagAttivo; + } + public String getUntMis() { return untMis; } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java index db1cda35..18a26043 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/HttpInterceptor.java @@ -36,7 +36,7 @@ public class HttpInterceptor implements Interceptor { //Nel caso in cui il token è scaduto e devo richiamare la refresh non bisogna passare il vecchio token if(SettingsManager.i().getUserSession().getAccessTokenExpiryDate() != null && - UtilityDate.getNowTime().isBefore(SettingsManager.i().getUserSession().getAccessTokenExpiryDate())) { + UtilityDate.getNowTime().isBefore(SettingsManager.i().getUserSession().getAccessTokenExpiryDate().minusSeconds(20))) { accessToken = SettingsManager.i().getUserSession().getAccessToken(); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ArticoloRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ArticoloRESTConsumer.java index 17a960b3..1eae8601 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ArticoloRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ArticoloRESTConsumer.java @@ -108,7 +108,7 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { }); } - public void findIfIsKit(MtbAart mtbAart, RunnableArgs onComplete, RunnableArgs onFailed){ + public void findIfIsKit(MtbAart mtbAart, RunnableArgs onComplete, RunnableArgs onFailed) { ArticoloRESTConsumerService articoloRESTConsumerService = restBuilder.getService(ArticoloRESTConsumerService.class); articoloRESTConsumerService @@ -132,8 +132,7 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { var codMarts = codMartToFind.parallelStream() .filter(Objects::nonNull) .distinct() - .collect(Collectors.toUnmodifiableList()); - +.collect(Collectors.toUnmodifiableList()); ArticoloRESTConsumerService articoloRESTConsumer = restBuilder.getService(ArticoloRESTConsumerService.class); var response = articoloRESTConsumer .getByCodMart(new RetrieveArticoloByCodMartRequestDTO() @@ -210,25 +209,26 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { } - public void getUntMisArts(List inputUntMis, RunnableArgs> onComplete, RunnableArgs onFailed) { - List> whereCondList = Stream.of(inputUntMis) + public List getUntMisArtsSynchronized(List inputUntMis) throws Exception { + List> whereCondList = inputUntMis.parallelStream() .distinct() - .withoutNulls() + .filter(Objects::nonNull) .map(x -> { HashMap data = new HashMap<>(); data.put("unt_mis", x); return data; }) - .toList(); + .collect(Collectors.toUnmodifiableList()); var whereCond = whereCondList.isEmpty() ? "" : " WHERE " + UtilityQuery.concatFieldListInWhereCond(whereCondList); Type typeOfObjectsList = new TypeToken>() { }.getType(); - this.systemRESTConsumer.processSql("SELECT * FROM mtb_unt_mis " + whereCond, typeOfObjectsList, onComplete, onFailed); + + return this.systemRESTConsumer.processSqlSynchronized("SELECT * FROM mtb_unt_mis " + whereCond, typeOfObjectsList); } - public void fillMtbAartsWithMtbUntMis(List inputMtbAart, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List fillMtbAartsWithMtbUntMisSynchronized(List inputMtbAart) throws Exception { var inputUntMis = new ArrayList(); if (inputMtbAart != null && !inputMtbAart.isEmpty()) { @@ -240,21 +240,23 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { } if (inputUntMis.isEmpty()) { - onComplete.run(inputMtbAart); - return; + return inputMtbAart; } - getUntMisArts(inputUntMis, mtbUntMiss -> { - for (var item : inputMtbAart) { - var mtbUntMis = Stream.of(mtbUntMiss).filter(x -> x.getUntMis().equalsIgnoreCase(item.getUntMis())) - .findFirstOrElse(null); + var mtbUntMiss = getUntMisArtsSynchronized(inputUntMis); - if (mtbUntMis != null) - item.setMtbUntMis(Collections.singletonList(mtbUntMis)); - } + for (var item : inputMtbAart) { + var mtbUntMis = mtbUntMiss.stream() + .filter(x -> x.getUntMis().equalsIgnoreCase(item.getUntMis())) + .findFirst() + .orElse(null); + + if (mtbUntMis != null) + item.setMtbUntMis(Collections.singletonList(mtbUntMis)); + } + + return inputMtbAart; - onComplete.run(inputMtbAart); - }, onFailed); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/AziendaRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/AziendaRESTConsumer.java index 2680ef36..2e1ad40a 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/AziendaRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/AziendaRESTConsumer.java @@ -1,16 +1,9 @@ package it.integry.integrywmsnative.core.rest.consumers; -import androidx.annotation.NonNull; - import javax.inject.Singleton; -import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.model.Azienda; import it.integry.integrywmsnative.core.rest.RESTBuilder; -import it.integry.integrywmsnative.core.rest.handler.ManagedErrorCallback; -import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; -import retrofit2.Call; -import retrofit2.Response; @Singleton public class AziendaRESTConsumer extends _BaseRESTConsumer { @@ -21,19 +14,12 @@ public class AziendaRESTConsumer extends _BaseRESTConsumer { this.restBuilder = restBuilder; } - public void retrieveAzienda(RunnableArgs onComplete, RunnableArgs onFailed) { + public Azienda retrieveAziendaSynchronized() throws Exception { AziendaRESTConsumerService aziendaRESTConsumerService = restBuilder.getService(AziendaRESTConsumerService.class); - aziendaRESTConsumerService.retrieveDefaultAzienda().enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "Retrieve default azienda", onComplete, onFailed); - } + var response = aziendaRESTConsumerService.retrieveDefaultAzienda() + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + return analyzeAnswer(response, "Retrieve default azienda"); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliLavorazioneRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliLavorazioneRESTConsumer.java index 9a708bb4..a4e3de1d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliLavorazioneRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliLavorazioneRESTConsumer.java @@ -3,6 +3,7 @@ package it.integry.integrywmsnative.core.rest.consumers; import androidx.annotation.NonNull; import java.math.BigDecimal; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -27,10 +28,8 @@ import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.CreateUDSFromArtRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.CreateUDSRequestDTO; -import it.integry.integrywmsnative.core.rest.model.uds.CreateUDSResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.DeleteUDSRowRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.EditUDSRowRequestDTO; -import it.integry.integrywmsnative.core.rest.model.uds.EditUDSRowResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.InsertUDCRowRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.InsertUDCRowResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.InsertUDSRowRequestDTO; @@ -44,10 +43,12 @@ public class ColliLavorazioneRESTConsumer extends _BaseRESTConsumer implements C private final RESTBuilder restBuilder; + private final ExecutorService executorService; private final SettingsManager settingsManager; - public ColliLavorazioneRESTConsumer(RESTBuilder restBuilder, SettingsManager settingsManager) { + public ColliLavorazioneRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, SettingsManager settingsManager) { this.restBuilder = restBuilder; + this.executorService = executorService; this.settingsManager = settingsManager; } @@ -123,93 +124,111 @@ public class ColliLavorazioneRESTConsumer extends _BaseRESTConsumer implements C }); } - public void createUDS(CreateUDSRequestDTO createUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + public MtbColt createUDSSynchronized(CreateUDSRequestDTO createUDSRequestDTO) throws Exception { ColliLavorazioneRESTConsumerService colliLavorazioneRESTConsumerService = restBuilder.getService(ColliLavorazioneRESTConsumerService.class); - colliLavorazioneRESTConsumerService.createUDS(createUDSRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "lavorazione/createUDS", data -> onComplete.run(data.getMtbColt()), onFailed); - } + var response = colliLavorazioneRESTConsumerService.createUDS(createUDSRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "lavorazione/createUDS"); + return data.getMtbColt(); + } + public void createUDS(CreateUDSRequestDTO createUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = createUDSSynchronized(createUDSRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public CloseUDSResponseDTO closeUDSSynchronized(CloseUDSRequestDTO closeUDSRequestDTO) throws Exception { + ColliLavorazioneRESTConsumerService colliLavorazioneRESTConsumerService = restBuilder.getService(ColliLavorazioneRESTConsumerService.class); + + var response = colliLavorazioneRESTConsumerService.closeUDS(closeUDSRequestDTO) + .execute(); + + var data = analyzeAnswer(response, "lavorazione/closeUDS"); + return data; + } + + public void closeUDS(CloseUDSRequestDTO closeUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = closeUDSSynchronized(closeUDSRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } @Override - public void closeUDS(CloseUDSRequestDTO closeUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + public MtbColr insertUDSRowSynchronized(InsertUDSRowRequestDTO insertUDSRowRequestDTO) throws Exception { ColliLavorazioneRESTConsumerService colliLavorazioneRESTConsumerService = restBuilder.getService(ColliLavorazioneRESTConsumerService.class); - colliLavorazioneRESTConsumerService.closeUDS(closeUDSRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "lavorazione/closeUDS", onComplete, onFailed); - } + Response> response = colliLavorazioneRESTConsumerService.insertUDSRow(insertUDSRowRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "lavorazione/insertUDSRow"); + return data.getSavedMtbColr(); } + @Override public void insertUDSRow(InsertUDSRowRequestDTO insertUDSRowRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = insertUDSRowSynchronized(insertUDSRowRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public MtbColr editUDSRowSynchronized(EditUDSRowRequestDTO editUDSRowRequestDTO) throws Exception { ColliLavorazioneRESTConsumerService colliLavorazioneRESTConsumerService = restBuilder.getService(ColliLavorazioneRESTConsumerService.class); - colliLavorazioneRESTConsumerService.insertUDSRow(insertUDSRowRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "lavorazione/insertUDSRow", data -> onComplete.run(data.getSavedMtbColr()), onFailed); - } + var response = colliLavorazioneRESTConsumerService.editUDSRow(editUDSRowRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "lavorazione/editUDSRow"); + return data.getSavedMtbColr(); } public void editUDSRow(EditUDSRowRequestDTO editUDSRowRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { - ColliLavorazioneRESTConsumerService colliLavorazioneRESTConsumerService = restBuilder.getService(ColliLavorazioneRESTConsumerService.class); - - colliLavorazioneRESTConsumerService.editUDSRow(editUDSRowRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "lavorazione/editUDSRow", data -> onComplete.run(data.getSavedMtbColr()), onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + executorService.execute(() -> { + try { + var response = editUDSRowSynchronized(editUDSRowRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } - @Override - public void deleteUDSRow(DeleteUDSRowRequestDTO deleteUDSRowRequestDTO, Runnable onComplete, RunnableArgs onFailed) { + public void deleteUDSRowSynchronized(DeleteUDSRowRequestDTO deleteUDSRowRequestDTO) throws Exception { ColliLavorazioneRESTConsumerService colliLavorazioneRESTConsumerService = restBuilder.getService(ColliLavorazioneRESTConsumerService.class); - colliLavorazioneRESTConsumerService.deleteUDSRow(deleteUDSRowRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "lavorazione/deleteUDSRow", data -> onComplete.run(), onFailed); - } + var response = colliLavorazioneRESTConsumerService.deleteUDSRow(deleteUDSRowRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + analyzeAnswer(response, "lavorazione/deleteUDSRow"); + } + + public void deleteUDSRow(DeleteUDSRowRequestDTO deleteUDSRowRequestDTO, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + deleteUDSRowSynchronized(deleteUDSRowRequestDTO); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } @Override diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumer.java index 7e3927f3..9ff820df 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumer.java @@ -17,6 +17,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Objects; +import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; import javax.inject.Singleton; @@ -36,8 +37,8 @@ import it.integry.integrywmsnative.core.rest.handler.ManagedErrorCallback; import it.integry.integrywmsnative.core.rest.model.RettificaULDTO; import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.core.rest.model.SpostaArtsTraULRequestDTO; -import it.integry.integrywmsnative.core.rest.model.SpostaArtsTraULResponseDTO; import it.integry.integrywmsnative.core.rest.model.SpostaULRequestDTO; +import it.integry.integrywmsnative.core.rest.model.UpdatePosizioneULRequestDTO; import it.integry.integrywmsnative.core.rest.model.UpdateTipoULRequestDTO; import it.integry.integrywmsnative.core.rest.model.VersamentoAutomaticoULResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.CanULBeDeletedRequestDTO; @@ -60,8 +61,9 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { private final ArticoloRESTConsumer mArticoloRESTConsumer; private final EntityRESTConsumer mEntityRESTConsumer; private final SettingsManager mSettingsManager; + private final ExecutorService executorService; - public ColliMagazzinoRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, + public ColliMagazzinoRESTConsumer(ExecutorService executorService, RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, ArticoloRESTConsumer articoloRESTConsumer, EntityRESTConsumer entityRESTConsumer, SettingsManager settingsManager) { @@ -70,38 +72,36 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { this.mArticoloRESTConsumer = articoloRESTConsumer; this.mEntityRESTConsumer = entityRESTConsumer; this.mSettingsManager = settingsManager; + this.executorService = executorService; } - public void saveCollo(MtbColt mtbColtToSave, RunnableArgs onComplete, RunnableArgs onFailed) { + public MtbColt saveColloSynchronized(MtbColt mtbColtToSave) throws Exception { MtbColt mtbColtToSaveClone = (MtbColt) mtbColtToSave.clone(); mtbColtToSaveClone.setOperation(CommonModelConsts.OPERATION.INSERT_OR_UPDATE); mtbColtToSaveClone.setOnlyPkMaster(false); - - mtbColtToSaveClone.setMtbColr(new ObservableArrayList<>()); - for (int i = 0; i < mtbColtToSave.getMtbColr().size(); i++) { - mtbColtToSaveClone.getMtbColr().add( - ((MtbColr) mtbColtToSave.getMtbColr().get(i).clone()) - .setMtbAart(null) - .setMtbPartitaMag(null)); + mtbColtToSaveClone.getMtbColr().get(i) + .setMtbAart(null) + .setMtbPartitaMag(null); } - this.mEntityRESTConsumer.processEntity(mtbColtToSaveClone, new ISimpleOperationCallback<>() { - @Override - public void onSuccess(MtbColt value) { - if (onComplete != null) onComplete.run(value); - } + return this.mEntityRESTConsumer.processEntitySynchronized(mtbColtToSaveClone, MtbColt.class); + } - @Override - public void onFailed(Exception ex) { + public void saveCollo(MtbColt mtbColtToSave, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var mtbColt = saveColloSynchronized(mtbColtToSave); + if (onComplete != null) onComplete.run(mtbColt); + } catch (Exception ex) { if (onFailed != null) onFailed.run(ex); } - }, MtbColt.class); + }); } - public void saveColli(List mtbColtsToSave, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List saveColliSynchronized(List mtbColtsToSave) throws Exception { for (MtbColt mtbColt : mtbColtsToSave) { for (int i = 0; i < mtbColt.getMtbColr().size(); i++) { @@ -111,28 +111,22 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } } - this.mEntityRESTConsumer.processEntityList(mtbColtsToSave, true, MtbColt.class, onComplete, onFailed); - - } - - public void createColloLavorazione(int segno, RunnableArgs onComplete, RunnableArgs onFailed) { - MtbColt mtbColtToCreate = new MtbColt() - .setSegno(segno); - - mtbColtToCreate.initDefaultFields(GestioneEnum.LAVORAZIONE); - - mtbColtToCreate - .setOperation(CommonModelConsts.OPERATION.INSERT); - - - saveCollo(mtbColtToCreate, value -> { - if (onComplete != null) onComplete.run(value); - }, ex -> { - if (onFailed != null) onFailed.run(ex); - }); + return this.mEntityRESTConsumer.processEntityListSynchronized(mtbColtsToSave, true, MtbColt.class); } public void createColloScaricoDaCarico(MtbColt sourceMtbColt, MtbDepoPosizione posizione, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var mtbColt = createColloScaricoDaCaricoSynchronized(sourceMtbColt, posizione); + if (onComplete != null) onComplete.run(mtbColt); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + + public MtbColt createColloScaricoDaCaricoSynchronized(MtbColt sourceMtbColt, MtbDepoPosizione posizione) throws Exception { MtbColt newMtbColt = new MtbColt() .initDefaultFields(GestioneEnum.LAVORAZIONE) @@ -181,7 +175,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } - saveCollo(newMtbColt, onComplete, onFailed); + return saveColloSynchronized(newMtbColt); } @@ -212,7 +206,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } -// if (sourceMtbColt.getMtbColr().size() != 1) { +// if (sourceMtbColt.getMtbColr().getValue().size() != 1) { // onFailed.run(new Exception()); // return; // } @@ -288,32 +282,34 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { saveCollo(mtbColtToCreate, onComplete, onFailed); } - public void getBySSCC(String ssccString, boolean onlyResiduo, boolean throwExcIfNull, RunnableArgs onComplete, RunnableArgs onFailed) { + public MtbColt getBySsccSynchronized(String ssccString, boolean onlyResiduo, boolean throwExcIfNull) throws Exception { ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService.getColloByBarcode(ssccString, onlyResiduo, throwExcIfNull).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "GetBySSCC", mtbColt -> { + var colloResponse = colliMagazzinoRESTConsumerService.getColloByBarcode(ssccString, onlyResiduo, throwExcIfNull) + .execute(); + var mtbColt = analyzeAnswer(colloResponse, "GetBySSCC"); - if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { - List mtbColtList = new ArrayList<>(); - mtbColtList.add(mtbColt); - fillMtbAartsOfMtbColts(mtbColtList, mtbColts -> onComplete.run(mtbColts.get(0)), onFailed); - } else { - onComplete.run(mtbColt); - } + if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { + List mtbColtList = new ArrayList<>(); + mtbColtList.add(mtbColt); + var mtbColts = fillMtbAartsOfMtbColtsSynchronized(mtbColtList); + return mtbColts.get(0); + } - }, onFailed); - } + return mtbColt; + } - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); + public void getBySSCC(String ssccString, boolean onlyResiduo, boolean throwExcIfNull, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var mtbColt = getBySsccSynchronized(ssccString, onlyResiduo, throwExcIfNull); + if (onComplete != null) onComplete.run(mtbColt); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } }); } - public void fillMtbAartsOfMtbColrs(List mtbColrs, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List fillMtbAartsOfMtbColrsSynchronized(List mtbColrs) throws Exception { List codMarts = new ArrayList<>(mtbColrs.stream() .map(MtbColr::getCodMart) @@ -321,14 +317,48 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { .distinct() .collect(Collectors.toUnmodifiableList())); - mArticoloRESTConsumer.getByCodMarts(codMarts, arts -> { + var arts = mArticoloRESTConsumer.getByCodMartsSynchronized(codMarts); - if (arts != null && !arts.isEmpty()) { - for (MtbColr mtbColr : mtbColrs) { + if (arts != null && !arts.isEmpty()) { + for (MtbColr mtbColr : mtbColrs) { + MtbAart foundMtbAart = null; + + List mtbAartStream = arts.stream() + .filter(x -> x.getCodMart().equalsIgnoreCase(mtbColr.getCodMart())) + .collect(Collectors.toList()); + + if (!mtbAartStream.isEmpty()) { + foundMtbAart = mtbAartStream.get(0); + } + + mtbColr.setMtbAart(foundMtbAart); + } + } + + return mtbColrs; + } + + public List fillMtbAartsOfMtbColtsSynchronized(List mtbColts) throws Exception { + List codMarts = new ArrayList<>(); + + for (MtbColt mtbColt : mtbColts) { + codMarts.addAll(mtbColt.getMtbColr().stream() + .map(MtbColr::getCodMart) + .filter(x -> !UtilityString.isNullOrEmpty(x)) + .distinct() + .collect(Collectors.toList())); + } + + List mtbAarts = mArticoloRESTConsumer.getByCodMartsSynchronized(codMarts); + + for (MtbColt mtbColt : mtbColts) { + for (MtbColr mtbColr : mtbColt.getMtbColr()) { + + if (mtbAarts != null && !mtbAarts.isEmpty()) { MtbAart foundMtbAart = null; - List mtbAartStream = arts.stream() + List mtbAartStream = mtbAarts.parallelStream() .filter(x -> x.getCodMart().equalsIgnoreCase(mtbColr.getCodMart())) .collect(Collectors.toList()); @@ -338,52 +368,26 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { mtbColr.setMtbAart(foundMtbAart); } + + mtbColr.setGestione(mtbColt.getGestione()); + mtbColr.setSerCollo(mtbColt.getSerCollo()); + mtbColr.setNumCollo(mtbColt.getNumCollo()); + mtbColr.setDataCollo(mtbColt.getDataColloS()); } + } - onComplete.run(mtbColrs); - }, onFailed); - + return mtbColts; } public void fillMtbAartsOfMtbColts(List mtbColts, RunnableArgs> onComplete, RunnableArgs onFailed) { - List codMarts = new ArrayList<>(); - - for (MtbColt mtbColt : mtbColts) { - codMarts.addAll(mtbColt.getMtbColr().stream() - .map(MtbColr::getCodMart) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toUnmodifiableList())); - } - - - mArticoloRESTConsumer.getByCodMarts(codMarts, arts -> { - - if (arts != null && !arts.isEmpty()) { - for (MtbColt mtbColt : mtbColts) { - for (MtbColr mtbColr : mtbColt.getMtbColr()) { - - MtbAart foundMtbAart = null; - - List mtbAartStream = arts.stream() - .filter(x -> x.getCodMart().equalsIgnoreCase(mtbColr.getCodMart())) - .collect(Collectors.toList()); - - if (!mtbAartStream.isEmpty()) { - foundMtbAart = mtbAartStream.get(0); - } - - mtbColr.setMtbAart(foundMtbAart); - mtbColr.setGestione(mtbColt.getGestione()); - mtbColr.setSerCollo(mtbColt.getSerCollo()); - mtbColr.setNumCollo(mtbColt.getNumCollo()); - mtbColr.setDataCollo(mtbColt.getDataColloS()); - } - } + executorService.execute(() -> { + try { + List returnedMtbColts = fillMtbAartsOfMtbColtsSynchronized(mtbColts); + if (onComplete != null) onComplete.run(returnedMtbColts); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } - - onComplete.run(mtbColts); - }, onFailed); + }); } public void getMultipleByTestate(List testate, boolean onlyResiduo, RunnableArgs> onComplete, RunnableArgs onFailed) { @@ -404,6 +408,16 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } } + public MtbColt getByChiaveColloSynchronized(GestioneEnum gestione, int numCollo, String dataCollo, String serCollo, boolean onlyResiduo, boolean throwExcIfNull) throws Exception { + MtbColt mtbColtToRetrieve = new MtbColt() + .setGestione(gestione) + .setNumCollo(numCollo) + .setDataCollo(dataCollo) + .setSerCollo(serCollo); + + return getByTestataSynchronized(mtbColtToRetrieve, onlyResiduo, throwExcIfNull); + } + public void getByChiaveCollo(GestioneEnum gestione, int numCollo, String dataCollo, String serCollo, boolean onlyResiduo, boolean throwExcIfNull, RunnableArgs onComplete, RunnableArgs onFailed) { MtbColt mtbColtToRetrieve = new MtbColt() .setGestione(gestione) @@ -414,36 +428,34 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { getByTestata(mtbColtToRetrieve, onlyResiduo, throwExcIfNull, onComplete, onFailed); } - public void getByTestata(MtbColt testata, boolean onlyResiduo, boolean throwExcIfNull, RunnableArgs onComplete, RunnableArgs onFailed) { + public MtbColt getByTestataSynchronized(MtbColt testata, boolean onlyResiduo, boolean throwExcIfNull) throws Exception { testata.setMtbColr(new ObservableArrayList<>()); ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService.getColloInGiac(onlyResiduo, throwExcIfNull, testata) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "getColloInGiac", mtbColt -> { + var response = colliMagazzinoRESTConsumerService.getColloInGiac(onlyResiduo, throwExcIfNull, testata) + .execute(); + var mtbColt = analyzeAnswer(response, "getColloInGiac"); + if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { + var mtbColts = fillMtbAartsOfMtbColtsSynchronized(Collections.singletonList(mtbColt)); + return mtbColts.get(0); + } - if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { - List mtbColtList = new ArrayList<>(); - mtbColtList.add(mtbColt); - fillMtbAartsOfMtbColts(mtbColtList, mtbColts -> onComplete.run(mtbColts.get(0)), onFailed); - } else { - onComplete.run(mtbColt); - } - - }, onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + return mtbColt; } - public void spostaUL(MtbColt mtbColtToMove, String codMdep, String posizione, boolean createDocAutomatically, Runnable onComplete, RunnableArgs onFailed) { + public void getByTestata(MtbColt testata, boolean onlyResiduo, boolean throwExcIfNull, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var data = getByTestataSynchronized(testata, onlyResiduo, throwExcIfNull); + if (onComplete != null) onComplete.run(data); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public void spostaUlSynchronized(MtbColt mtbColtToMove, String codMdep, String posizione, boolean createDocAutomatically) throws Exception { MtbColt mtbColtToMoveClone = (MtbColt) mtbColtToMove.clone(); for (int i = 0; i < mtbColtToMoveClone.getMtbColr().size(); i++) { @@ -459,21 +471,23 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { .setCreateDocAutomatically(createDocAutomatically); ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService + Response> response = colliMagazzinoRESTConsumerService .spostaUL(spostaUlRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spostaUL", mtbColts -> { - onComplete.run(); - }, onFailed); - } + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); - } - }); + analyzeAnswer(response, "spostaUL"); + } + + + public void spostaUL(MtbColt mtbColtToMove, String codMdep, String posizione, boolean createDocAutomatically, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + spostaUlSynchronized(mtbColtToMove, codMdep, posizione, createDocAutomatically); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } public void spostaUL(MtbColt mtbColtToMove, MtbDepoPosizione posizione, Runnable onComplete, RunnableArgs onFailed) { @@ -484,7 +498,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { spostaUL(mtbColtToMove, codMdep, posizioneString, true, onComplete, onFailed); } - public void updateTipoUL(MtbColt mtbColt, String codTcol, Runnable onComplete, RunnableArgs onFailed) { + public void updateTipoULSynchronized(MtbColt mtbColt, String codTcol) throws Exception { MtbColt mtbColtClone = (MtbColt) mtbColt.clone(); mtbColtClone.setMtbColr(new ObservableArrayList<>()); @@ -494,22 +508,52 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { .setCodTcol(codTcol); ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService + Response> response = colliMagazzinoRESTConsumerService .updateTipoUL(updateTipoULRequest) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "updateTipoUL", mtbColts -> { - onComplete.run(); - }, onFailed); - } + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); - } - }); + analyzeAnswer(response, "updateTipoUL"); + } + + public void updateTipoUL(MtbColt mtbColt, String codTcol, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + updateTipoULSynchronized(mtbColt, codTcol); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public void updatePosizioneULSynchronized(MtbColt mtbColt, String posizione) throws Exception { + + MtbColt mtbColtClone = (MtbColt) mtbColt.clone(); + mtbColtClone.setMtbColr(new ObservableArrayList<>()); + + UpdatePosizioneULRequestDTO updateTipoULRequest = new UpdatePosizioneULRequestDTO() + .setMtbColt(mtbColtClone) + .setPosizione(posizione); + + ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); + Response> response = colliMagazzinoRESTConsumerService + .updatePosizioneUL(updateTipoULRequest) + .execute(); + + analyzeAnswer(response, "updatePosizioneUL"); + } + + + public void updatePosizioneUL(MtbColt mtbColt, String posizione, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + updatePosizioneULSynchronized(mtbColt, posizione); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } public void updateDataFine(MtbColt mtbColt, Runnable onComplete, RunnableArgs onFailed) { @@ -572,44 +616,45 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { }); } - public void spostaArtsTraUL(MtbColt sourceMtbColt, MtbColt destMtbColt, boolean flagForceUseRefs, RunnableArgs> onComplete, RunnableArgs onFailed) { - new Thread(() -> { - MtbColt mtbColtToMoveClone = (MtbColt) sourceMtbColt.clone(); - MtbColt mtbColtDestClone = (MtbColt) destMtbColt.clone(); + public List spostaArtsTraULSynchronized(MtbColt sourceMtbColt, MtbColt destMtbColt, boolean flagForceUseRefs) throws Exception { + MtbColt mtbColtToMoveClone = (MtbColt) sourceMtbColt.clone(); + MtbColt mtbColtDestClone = (MtbColt) destMtbColt.clone(); - for (int i = 0; i < mtbColtToMoveClone.getMtbColr().size(); i++) { - mtbColtToMoveClone.getMtbColr().get(i) - .setMtbAart(null) - .setMtbPartitaMag(null); - } + for (int i = 0; i < mtbColtToMoveClone.getMtbColr().size(); i++) { + mtbColtToMoveClone.getMtbColr().get(i) + .setMtbAart(null) + .setMtbPartitaMag(null); + } - mtbColtDestClone.setMtbColr(null); + mtbColtDestClone.setMtbColr(null); - SpostaArtsTraULRequestDTO spostaArtsTraULRequestDTO = new SpostaArtsTraULRequestDTO() - .setSourceMtbColt(mtbColtToMoveClone) - .setDestinationMtbColt(mtbColtDestClone) - .setFlagForceUseRefs(flagForceUseRefs); + SpostaArtsTraULRequestDTO spostaArtsTraULRequestDTO = new SpostaArtsTraULRequestDTO() + .setSourceMtbColt(mtbColtToMoveClone) + .setDestinationMtbColt(mtbColtDestClone) + .setFlagForceUseRefs(flagForceUseRefs); - ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService.spostaArtsTraUL(spostaArtsTraULRequestDTO).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spostaArtsTraUL", data -> { + ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); + var response = colliMagazzinoRESTConsumerService.spostaArtsTraUL(spostaArtsTraULRequestDTO) + .execute(); - fillMtbAartsOfMtbColrs(data.getGeneratedMtbColr(), onComplete, onFailed); + var data = analyzeAnswer(response, "spostaArtsTraUL"); + var mtbColrs = fillMtbAartsOfMtbColrsSynchronized(data.getGeneratedMtbColr()); - }, onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); - } - }); - }).start(); + return mtbColrs; } - public void assegnaLottoSuColloScarico(MtbColt sourceMtbColt, Runnable onComplete, RunnableArgs onFailed) { + public void spostaArtsTraUL(MtbColt sourceMtbColt, MtbColt destMtbColt, boolean flagForceUseRefs, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var result = spostaArtsTraULSynchronized(sourceMtbColt, destMtbColt, flagForceUseRefs); + if (onComplete != null) onComplete.run(result); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public MtbColt assegnaLottoSuColloScaricoSynchronized(MtbColt sourceMtbColt) throws Exception { MtbColt sourceMtbColtClone = (MtbColt) sourceMtbColt.clone(); for (int i = 0; i < sourceMtbColtClone.getMtbColr().size(); i++) { @@ -619,17 +664,20 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService.assegnaLottoSuColloScarico(sourceMtbColtClone).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "assegnaLottoSuColloScarico", data -> { - onComplete.run(); - }, onFailed); - } + var response = colliMagazzinoRESTConsumerService.assegnaLottoSuColloScarico(sourceMtbColtClone) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); + var data = analyzeAnswer(response, "assegnaLottoSuColloScarico"); + return data; + } + + public void assegnaLottoSuColloScarico(MtbColt sourceMtbColt, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var result = assegnaLottoSuColloScaricoSynchronized(sourceMtbColt); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } }); } @@ -735,42 +783,48 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } - public void canULBeDeleted(MtbColt mtbColt, RunnableArgs onComplete, RunnableArgs onFailed) { + public Boolean canULBeDeletedSynchronized(MtbColt mtbColt) throws Exception { CanULBeDeletedRequestDTO canULBeDeletedRequestDTO = new CanULBeDeletedRequestDTO() .setMtbColt(mtbColt); ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - colliMagazzinoRESTConsumerService.canULBeDeleted(canULBeDeletedRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "generic/canULBeDeleted", onComplete, onFailed); - } + var response = colliMagazzinoRESTConsumerService.canULBeDeleted(canULBeDeletedRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "generic/canULBeDeleted"); + return data; + } + public void canULBeDeleted(MtbColt mtbColt, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var result = canULBeDeletedSynchronized(mtbColt); + if (onComplete != null) onComplete.run(result); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public void deleteULSynchronized(DeleteULRequestDTO deleteULRequestDTO) throws Exception { + ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); + + var response = colliMagazzinoRESTConsumerService.deleteUL(deleteULRequestDTO) + .execute(); + + analyzeAnswer(response, "generic/deleteUL"); } public void deleteUL(DeleteULRequestDTO deleteULRequestDTO, Runnable onComplete, RunnableArgs onFailed) { - ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); - - colliMagazzinoRESTConsumerService.deleteUL(deleteULRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "generic/deleteUL", Void -> onComplete.run(), onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + executorService.execute(() -> { + try { + deleteULSynchronized(deleteULRequestDTO); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumerService.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumerService.java index 2724988b..d17b5d1d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumerService.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliMagazzinoRESTConsumerService.java @@ -9,6 +9,7 @@ import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.core.rest.model.SpostaArtsTraULRequestDTO; import it.integry.integrywmsnative.core.rest.model.SpostaArtsTraULResponseDTO; import it.integry.integrywmsnative.core.rest.model.SpostaULRequestDTO; +import it.integry.integrywmsnative.core.rest.model.UpdatePosizioneULRequestDTO; import it.integry.integrywmsnative.core.rest.model.UpdateTipoULRequestDTO; import it.integry.integrywmsnative.core.rest.model.VersamentoAutomaticoULResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.CanULBeDeletedRequestDTO; @@ -37,6 +38,9 @@ public interface ColliMagazzinoRESTConsumerService { @POST("wms/updateTipoUL") Call> updateTipoUL(@Body UpdateTipoULRequestDTO requestDto); + @POST("wms/updatePosizioneUL") + Call> updatePosizioneUL(@Body UpdatePosizioneULRequestDTO requestDto); + @POST("wms/spostaUL") Call> spostaUL(@Body SpostaULRequestDTO requestDto); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliSpedizioneRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliSpedizioneRESTConsumer.java index 4744758f..e86df307 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliSpedizioneRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ColliSpedizioneRESTConsumer.java @@ -1,6 +1,6 @@ package it.integry.integrywmsnative.core.rest.consumers; -import androidx.annotation.NonNull; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -9,134 +9,152 @@ import it.integry.integrywmsnative.core.model.MtbColr; import it.integry.integrywmsnative.core.model.MtbColt; import it.integry.integrywmsnative.core.rest.RESTBuilder; import it.integry.integrywmsnative.core.rest.consumers.interfaces.ColliScaricoRESTConsumerInterface; -import it.integry.integrywmsnative.core.rest.handler.ManagedErrorCallback; import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.CreateUDSRequestDTO; -import it.integry.integrywmsnative.core.rest.model.uds.CreateUDSResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.DeleteUDSRowRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.DuplicateUDSRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.DuplicateUDSResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.EditUDSRowRequestDTO; -import it.integry.integrywmsnative.core.rest.model.uds.EditUDSRowResponseDTO; import it.integry.integrywmsnative.core.rest.model.uds.InsertUDSRowRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.InsertUDSRowResponseDTO; -import retrofit2.Call; import retrofit2.Response; @Singleton public class ColliSpedizioneRESTConsumer extends _BaseRESTConsumer implements ColliScaricoRESTConsumerInterface { private final RESTBuilder restBuilder; + private final ExecutorService executorService; - public ColliSpedizioneRESTConsumer(RESTBuilder restBuilder) { + public ColliSpedizioneRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService) { this.restBuilder = restBuilder; + this.executorService = executorService; + } + + public MtbColt createUDSSynchronized(CreateUDSRequestDTO createUDSRequestDTO) throws Exception { + ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); + + var response = colliSpedizioneRESTConsumerService.createUDS(createUDSRequestDTO) + .execute(); + + var data = analyzeAnswer(response, "spedizione/createUDS"); + return data.getMtbColt(); } public void createUDS(CreateUDSRequestDTO createUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = createUDSSynchronized(createUDSRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public CloseUDSResponseDTO closeUDSSynchronized(CloseUDSRequestDTO closeUDSRequestDTO) throws Exception { ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); - colliSpedizioneRESTConsumerService.createUDS(createUDSRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spedizione/createUDS", data -> onComplete.run(data.getMtbColt()), onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var response = colliSpedizioneRESTConsumerService.closeUDS(closeUDSRequestDTO) + .execute(); + var data = analyzeAnswer(response, "spedizione/closeUDS"); + return data; } public void closeUDS(CloseUDSRequestDTO closeUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = closeUDSSynchronized(closeUDSRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public MtbColr insertUDSRowSynchronized(InsertUDSRowRequestDTO insertUDSRowRequestDTO) throws Exception { ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); - colliSpedizioneRESTConsumerService.closeUDS(closeUDSRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spedizione/closeUDS", onComplete, onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + Response> response = colliSpedizioneRESTConsumerService.insertUDSRow(insertUDSRowRequestDTO) + .execute(); + var data = analyzeAnswer(response, "spedizione/insertUDSRow"); + return data.getSavedMtbColr(); } public void insertUDSRow(InsertUDSRowRequestDTO insertUDSRowRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = insertUDSRowSynchronized(insertUDSRowRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public MtbColr editUDSRowSynchronized(EditUDSRowRequestDTO editUDSRowRequestDTO) throws Exception { ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); - colliSpedizioneRESTConsumerService.insertUDSRow(insertUDSRowRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spedizione/insertUDSRow", data -> onComplete.run(data.getSavedMtbColr()), onFailed); - } + var response = colliSpedizioneRESTConsumerService.editUDSRow(editUDSRowRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "spedizione/editUDSRow"); + return data.getSavedMtbColr(); } public void editUDSRow(EditUDSRowRequestDTO editUDSRowRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = editUDSRowSynchronized(editUDSRowRequestDTO); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public void deleteUDSRowSynchronized(DeleteUDSRowRequestDTO deleteUDSRowRequestDTO) throws Exception { ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); - colliSpedizioneRESTConsumerService.editUDSRow(editUDSRowRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spedizione/editUDSRow", data -> onComplete.run(data.getSavedMtbColr()), onFailed); - } + var response = colliSpedizioneRESTConsumerService.deleteUDSRow(deleteUDSRowRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + analyzeAnswer(response, "spedizione/deleteUDSRow"); } public void deleteUDSRow(DeleteUDSRowRequestDTO deleteUDSRowRequestDTO, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + deleteUDSRowSynchronized(deleteUDSRowRequestDTO); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + public DuplicateUDSResponseDTO duplicateUDSSynchronized(DuplicateUDSRequestDTO duplicateUDSRequestDTO) throws Exception { ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); - colliSpedizioneRESTConsumerService.deleteUDSRow(deleteUDSRowRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "spedizione/deleteUDSRow", data -> onComplete.run(), onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var response = colliSpedizioneRESTConsumerService.duplicateUDS(duplicateUDSRequestDTO) + .execute(); + var data = analyzeAnswer(response, "spedizione/duplicateUDS"); + return data; } public void duplicateUDS(DuplicateUDSRequestDTO duplicateUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed) { - ColliSpedizioneRESTConsumerService colliSpedizioneRESTConsumerService = restBuilder.getService(ColliSpedizioneRESTConsumerService.class); - - colliSpedizioneRESTConsumerService.duplicateUDS(duplicateUDSRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(@NonNull Call> call, @NonNull Response> response) { - analyzeAnswer(response, "spedizione/duplicateUDS", onComplete, onFailed); - } - - @Override - public void onFailure(@NonNull Call> call, @NonNull final Exception e) { - onFailed.run(new Exception()); - } - }); + executorService.execute(() -> { + try { + var data = duplicateUDSSynchronized(duplicateUDSRequestDTO); + if (onComplete != null) onComplete.run(data); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/CommessaRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/CommessaRESTConsumer.java index 2397e97e..9393c916 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/CommessaRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/CommessaRESTConsumer.java @@ -6,6 +6,7 @@ import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; import javax.inject.Singleton; @@ -18,34 +19,42 @@ import it.integry.integrywmsnative.core.utility.UtilityString; @Singleton public class CommessaRESTConsumer extends _BaseRESTConsumer { + private final ExecutorService executorService; private final SystemRESTConsumer systemRESTConsumer; - public CommessaRESTConsumer(SystemRESTConsumer systemRESTConsumer) { + public CommessaRESTConsumer(ExecutorService executorService, SystemRESTConsumer systemRESTConsumer) { + this.executorService = executorService; this.systemRESTConsumer = systemRESTConsumer; } - public void getJtbComts(List itemsToFind, RunnableArgs> onComplete, RunnableArgs onFailed) { - var whereCondMap = itemsToFind.stream() + public List getJtbComtsSynchronized(List itemsToFind) throws Exception { + List> whereCondMap = itemsToFind.stream() .filter(x -> !UtilityString.isNullOrEmpty(x)) - .map(x -> { - HashMap codJcom = new HashMap<>() {{ - put("cod_jcom", x); - }}; - return codJcom; - }) + .map(x -> new HashMap() {{ + put("cod_jcom", x); + }}) .collect(Collectors.toUnmodifiableList()); if(whereCondMap.isEmpty()) { - onComplete.run(new ArrayList<>()); - return; + return new ArrayList<>(); } var whereCond = " WHERE " + UtilityQuery.concatFieldListInWhereCond(whereCondMap); Type typeOfObjectsList = new TypeToken>() {}.getType(); - this.systemRESTConsumer.processSql("SELECT * FROM jtb_comt " + whereCond, typeOfObjectsList, onComplete, onFailed); + return this.systemRESTConsumer.processSqlSynchronized("SELECT * FROM jtb_comt " + whereCond, typeOfObjectsList); + } + public void getJtbComts(List itemsToFind, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var data = getJtbComtsSynchronized(itemsToFind); + if (onComplete != null) onComplete.run(data); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/DepositoRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/DepositoRESTConsumer.java index 93853e04..e4df1bfb 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/DepositoRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/DepositoRESTConsumer.java @@ -5,26 +5,26 @@ import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; -import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.model.MtbDepo; @Singleton public class DepositoRESTConsumer extends _BaseRESTConsumer { - private final EntityRESTConsumer entityRESTConsumer; + private final ExecutorService executorService; private final SystemRESTConsumer systemRESTConsumer; - public DepositoRESTConsumer(EntityRESTConsumer entityRESTConsumer, SystemRESTConsumer systemRESTConsumer) { - this.entityRESTConsumer = entityRESTConsumer; + public DepositoRESTConsumer(ExecutorService executorService, SystemRESTConsumer systemRESTConsumer) { + this.executorService = executorService; this.systemRESTConsumer = systemRESTConsumer; } - public void getAll(RunnableArgs> onComplete, RunnableArgs onFailed) { + public List getAllSynchronized() throws Exception { Type typeOfObjectsList = new TypeToken>() { }.getType(); - this.systemRESTConsumer.processSql("SELECT * FROM mtb_depo", typeOfObjectsList, onComplete, onFailed); + return this.systemRESTConsumer.processSqlSynchronized("SELECT * FROM mtb_depo", typeOfObjectsList); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/EntityRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/EntityRESTConsumer.java index 964043b2..2bfc7879 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/EntityRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/EntityRESTConsumer.java @@ -9,6 +9,7 @@ import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -26,100 +27,93 @@ import retrofit2.Response; public class EntityRESTConsumer extends _BaseRESTConsumer { private final RESTBuilder restBuilder; + private final ExecutorService executorService; - public EntityRESTConsumer(RESTBuilder restBuilder) { + public EntityRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService) { this.restBuilder = restBuilder; + this.executorService = executorService; + } + + public T processEntitySynchronized(T entityToSave, Class type) throws Exception { + EntityRESTConsumerService service = restBuilder.getService(EntityRESTConsumerService.class); + var response = service + .processEntity(entityToSave) + .execute(); + + if (response.isSuccessful()) { + if (response.body() != null) { + if (response.body().getEsito() == EsitoType.OK) { + Gson gson = UtilityGson.createObject(); + + return gson.fromJson(response.body().getEntity(), type); + } else { + Log.e("EntityRESTConsumer", response.body().getErrorMessage()); + throw new Exception(response.body().getErrorMessage()); + } + } else { + Log.e("EntityRESTConsumer", response.message()); + throw new Exception(response.message()); + } + } else { + Log.e("EntityRESTConsumer", "Status " + response.code() + ": " + response.message()); + throw new Exception("Status " + response.code() + ": " + response.message()); + } } public void processEntity(T entityToSave, final ISimpleOperationCallback callback, Class type) { + executorService.execute(() -> { + try { + var data = processEntitySynchronized(entityToSave, type); + if (callback != null) callback.onSuccess(data); + } catch (Exception ex) { + if (callback != null) callback.onFailed(ex); + } + }); - RunnableArgs tmpFailed = ex -> { - if (callback != null) callback.onFailed(ex); - }; + } + public List processEntityListSynchronized(List entitiesToSave, boolean singleTransaction, Class type) throws Exception { EntityRESTConsumerService service = restBuilder.getService(EntityRESTConsumerService.class); - service - .processEntity(entityToSave) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - if (response.isSuccessful()) { + var response = service.processEntityList(singleTransaction, entitiesToSave) + .execute(); - if (response.body() != null) { - if (response.body().getEsito() == EsitoType.OK) { - Gson gson = UtilityGson.createObject(); - T object = gson.fromJson(response.body().getEntity(), type); + if (response.isSuccessful()) { - callback.onSuccess(object); - } else { - Log.e("EntityRESTConsumer", response.body().getErrorMessage()); - tmpFailed.run(new Exception(response.body().getErrorMessage())); - } - } else { - Log.e("EntityRESTConsumer", response.message()); - tmpFailed.run(new Exception(response.message())); - } - } else { - Log.e("EntityRESTConsumer", "Status " + response.code() + ": " + response.message()); - tmpFailed.run(new Exception("Status " + response.code() + ": " + response.message())); - } + if (response.body() != null) { + + ArrayList responseList = new ArrayList<>(); + Gson gson = UtilityGson.createObject(); + + for (ServiceRESTResponse jsonSingleObject : response.body()) { + + if (jsonSingleObject.getEsito() == EsitoType.OK) { + String jsonText = gson.toJson(jsonSingleObject.getEntity()); + responseList.add(gson.fromJson(jsonText, type)); + } else { + Log.e("EntityRESTConsumer", jsonSingleObject.getErrorMessage()); + throw new Exception(jsonSingleObject.getErrorMessage()); } + } - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - tmpFailed.run(e); - } - }); + return responseList; + } else { + Log.e("EntityRESTConsumer", response.message()); + throw new Exception(response.message()); + } + } else { + Log.e("EntityRESTConsumer", "Status " + response.code() + ": " + response.message()); + throw new Exception("Status " + response.code() + ": " + response.message()); + } } public void processEntityList(List entitiesToSave, boolean singleTransaction, Class type, final RunnableArgs> onComplete, final RunnableArgs onFailed) { - - RunnableArgs tmpFailed = ex -> { -// UtilityExceptions.defaultException(null, ex); - if (onFailed != null) onFailed.run(ex); - }; - - EntityRESTConsumerService service = restBuilder.getService(EntityRESTConsumerService.class); - Call>> request = service.processEntityList(singleTransaction, entitiesToSave); - request.enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - if (response.isSuccessful()) { - - if (response.body() != null) { - - ArrayList responseList = new ArrayList<>(); - Gson gson = UtilityGson.createObject(); -// Type typeOfObjectsList = new TypeToken() {}.getType(); - - for (ServiceRESTResponse jsonSingleObject : response.body()) { - - if (jsonSingleObject.getEsito() == EsitoType.OK) { - String jsonText = gson.toJson(jsonSingleObject.getEntity()); - responseList.add(gson.fromJson(jsonText, type)); - } else { - Log.e("EntityRESTConsumer", jsonSingleObject.getErrorMessage()); - tmpFailed.run(new Exception(jsonSingleObject.getErrorMessage())); - - return; - } - } - - onComplete.run(responseList); - } else { - Log.e("EntityRESTConsumer", response.message()); - tmpFailed.run(new Exception(response.message())); - } - } else { - Log.e("EntityRESTConsumer", "Status " + response.code() + ": " + response.message()); - tmpFailed.run(new Exception("Status " + response.code() + ": " + response.message())); - } - } - - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - tmpFailed.run(e); + executorService.execute(() -> { + try { + var data = processEntityListSynchronized(entitiesToSave, singleTransaction, type); + if (onComplete != null) onComplete.run(data); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } }); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GestSetupRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GestSetupRESTConsumer.java index 1af0b430..3749c34b 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GestSetupRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GestSetupRESTConsumer.java @@ -79,32 +79,22 @@ public class GestSetupRESTConsumer extends _BaseRESTConsumer { } - public void getValues(String codMdep, List stbGestSetupList, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List getValuesSynchronized(String codMdep, List stbGestSetupList) throws Exception { var stbGestSetups = stbGestSetupList.stream().map(x -> (StbGestSetup) x).collect(Collectors.toList()); GestSetupRESTConsumerService service = restBuilder.getService(GestSetupRESTConsumerService.class); - service.getGestSetupValues(codMdep, stbGestSetups).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "GestSetup", data -> { + var response = service.getGestSetupValues(codMdep, stbGestSetups) + .execute(); + var data = analyzeAnswer(response, "GestSetup"); + for (StbGestSetup stbGestSetup : data) { + stbGestSetupList.stream().filter(x -> stbGestSetup.getGestName().equalsIgnoreCase(x.getGestName()) && + stbGestSetup.getSection().equalsIgnoreCase(x.getSection()) && + stbGestSetup.getKeySection().equalsIgnoreCase(x.getKeySection())) + .findFirst() + .ifPresent(x -> x.setValue(stbGestSetup.getValue())); + } - for (StbGestSetup stbGestSetup : data) { - stbGestSetupList.stream().filter(x -> stbGestSetup.getGestName().equalsIgnoreCase(x.getGestName()) && - stbGestSetup.getSection().equalsIgnoreCase(x.getSection()) && - stbGestSetup.getKeySection().equalsIgnoreCase(x.getKeySection())) - .findFirst() - .ifPresent(x -> x.setValue(stbGestSetup.getValue())); - } - - onComplete.run(stbGestSetupList); - }, onFailed); - } - - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); - } - }); + return stbGestSetupList; } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaPvRESTConsumerService.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaPvRESTConsumerService.java index 4bb86b7c..c4ef0149 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaPvRESTConsumerService.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaPvRESTConsumerService.java @@ -13,7 +13,7 @@ import retrofit2.http.Query; public interface GiacenzaPvRESTConsumerService { - @GET("giacenza/retrieve") + @GET("wms/pv/verifica_giacenze/retrieve") Call>> retrieve(@Query("codMdep") String codMdep); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaRESTConsumer.java index 83506ee8..1c904428 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/GiacenzaRESTConsumer.java @@ -169,27 +169,28 @@ public class GiacenzaRESTConsumer extends _BaseRESTConsumer { } - public void getInstantItemSituation(String codMdep, String codMart, String partitaMag, String codJcom, RunnableArgs onComplete, RunnableArgs onFailed) { + public InstantItemSituationResponseDto getInstantItemSituationSynchronized(String codMdep, String codMart, String partitaMag, String codJcom) throws Exception { GiacenzaRESTConsumerService giacenzaRESTConsumerService = restBuilder.getService(GiacenzaRESTConsumerService.class); - giacenzaRESTConsumerService.retrieveInstantItemSituation(codMdep, codMart, partitaMag, codJcom) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "getInstantItemSituation", data -> { + var response = giacenzaRESTConsumerService.retrieveInstantItemSituation(codMdep, codMart, partitaMag, codJcom) + .execute(); - fillInstantItemSituationWithMtbAarts(data, onComplete, onFailed); - }, onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "getInstantItemSituation"); + return fillInstantItemSituationWithMtbAartsSynchronized(data); } - private void fillInstantItemSituationWithMtbAarts(InstantItemSituationResponseDto data, RunnableArgs onComplete, RunnableArgs onFailed) { + public void getInstantItemSituation(String codMdep, String codMart, String partitaMag, String codJcom, RunnableArgs onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var response = getInstantItemSituationSynchronized(codMdep, codMart, partitaMag, codJcom); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + + private InstantItemSituationResponseDto fillInstantItemSituationWithMtbAartsSynchronized(InstantItemSituationResponseDto data) throws Exception { var inputCodMarts = new ArrayList(); if (data.getIncomingItems() != null && !data.getIncomingItems().isEmpty()) { @@ -205,37 +206,33 @@ public class GiacenzaRESTConsumer extends _BaseRESTConsumer { } if (inputCodMarts.isEmpty()) { - onComplete.run(data); - return; + return null; } - mArticoloRESTConsumer.getByCodMarts(inputCodMarts, mtbAarts -> { + var mtbAarts = mArticoloRESTConsumer.getByCodMartsSynchronized(inputCodMarts); + var newMtbAarts = mArticoloRESTConsumer.fillMtbAartsWithMtbUntMisSynchronized(mtbAarts); - mArticoloRESTConsumer.fillMtbAartsWithMtbUntMis(mtbAarts, newMtbAarts -> { - if (data.getIncomingItems() != null && !data.getIncomingItems().isEmpty()) { - for (var item : data.getIncomingItems()) { - var mtbAart = Stream.of(newMtbAarts).filter(x -> x.getCodMart().equalsIgnoreCase(item.getCodMart())) - .findFirstOrElse(null); + if (data.getIncomingItems() != null && !data.getIncomingItems().isEmpty()) { + for (var item : data.getIncomingItems()) { + var mtbAart = Stream.of(newMtbAarts).filter(x -> x.getCodMart().equalsIgnoreCase(item.getCodMart())) + .findFirstOrElse(null); - if (mtbAart != null) - item.setMtbAart(mtbAart); - } - } + if (mtbAart != null) + item.setMtbAart(mtbAart); + } + } - if (data.getAvailableItems() != null && !data.getAvailableItems().isEmpty()) { - for (var item : data.getAvailableItems()) { - var mtbAart = Stream.of(newMtbAarts).filter(x -> x.getCodMart().equalsIgnoreCase(item.getCodMart())) - .findFirstOrElse(null); + if (data.getAvailableItems() != null && !data.getAvailableItems().isEmpty()) { + for (var item : data.getAvailableItems()) { + var mtbAart = Stream.of(newMtbAarts).filter(x -> x.getCodMart().equalsIgnoreCase(item.getCodMart())) + .findFirstOrElse(null); - if (mtbAart != null) - item.setMtbAart(mtbAart); - } - } + if (mtbAart != null) + item.setMtbAart(mtbAart); + } + } - onComplete.run(data); - }, onFailed); - - }, onFailed); + return data; } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MagazzinoAutomaticoRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MagazzinoAutomaticoRESTConsumer.java index c938a532..5177dcff 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MagazzinoAutomaticoRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MagazzinoAutomaticoRESTConsumer.java @@ -2,6 +2,8 @@ package it.integry.integrywmsnative.core.rest.consumers; import androidx.annotation.NonNull; +import java.util.concurrent.ExecutorService; + import javax.inject.Singleton; import it.integry.integrywmsnative.core.expansion.RunnableArgs; @@ -18,26 +20,31 @@ import retrofit2.Response; public class MagazzinoAutomaticoRESTConsumer extends _BaseRESTConsumer { + private final ExecutorService executorService; private final RESTBuilder restBuilder; - public MagazzinoAutomaticoRESTConsumer(RESTBuilder restBuilder) { + public MagazzinoAutomaticoRESTConsumer(ExecutorService executorService, RESTBuilder restBuilder) { + this.executorService = executorService; this.restBuilder = restBuilder; } - public void pickItems(MtbDepoPosizione posizione, MagazzinoAutomaticoPickItemsRequestDTO magazzinoAutomaticoPickItemsRequestDTO, Runnable onComplete, RunnableArgs onFailed) { + public void pickItemsSynchronized(MtbDepoPosizione posizione, MagazzinoAutomaticoPickItemsRequestDTO magazzinoAutomaticoPickItemsRequestDTO) throws Exception { MagazzinoAutomaticoRESTConsumerService magazzinoAutomaticoRESTConsumerService = restBuilder.getService(MagazzinoAutomaticoRESTConsumerService.class); - magazzinoAutomaticoRESTConsumerService.pickItems(posizione.getPosizione(), magazzinoAutomaticoPickItemsRequestDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "magazzino-automatico/pickItems", data -> onComplete.run(), onFailed); - } + var response = magazzinoAutomaticoRESTConsumerService.pickItems(posizione.getPosizione(), magazzinoAutomaticoPickItemsRequestDTO) + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + analyzeAnswer(response, "magazzino-automatico/pickItems"); + } + + public void pickItems(MtbDepoPosizione posizione, MagazzinoAutomaticoPickItemsRequestDTO magazzinoAutomaticoPickItemsRequestDTO, Runnable onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + pickItemsSynchronized(posizione, magazzinoAutomaticoPickItemsRequestDTO); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumer.java index da79b417..ada5b12f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumer.java @@ -8,6 +8,7 @@ import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.model.MtbColt; import it.integry.integrywmsnative.core.rest.RESTBuilder; import it.integry.integrywmsnative.core.rest.model.materiali.RecuperaMaterialiRequestDTO; +import it.integry.integrywmsnative.core.rest.model.materiali.VersaMaterialiRequestDTO; @Singleton public class MaterialiRESTConsumer extends _BaseRESTConsumer { @@ -43,4 +44,27 @@ public class MaterialiRESTConsumer extends _BaseRESTConsumer { }); } + public void makeSynchronousVersaRequest(VersaMaterialiRequestDTO request) throws Exception { + var materialiRESTConsumerService = restBuilder.getService(MaterialiRESTConsumerService.class); + + var response = materialiRESTConsumerService.versa(request) + .execute(); + + + var data = analyzeAnswer(response, "versaMateriali"); +// if (data == null) return null; +// return data.getUpdatedMtbColtScarico(); + } + + public void makeVersaRequest(VersaMaterialiRequestDTO request, final Runnable onComplete, final RunnableArgs onFailed) { + executorService.execute(() -> { + try { + makeSynchronousVersaRequest(request); + if (onComplete != null) onComplete.run(); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumerService.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumerService.java index 57b6a67e..b26c51a2 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumerService.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MaterialiRESTConsumerService.java @@ -3,12 +3,16 @@ package it.integry.integrywmsnative.core.rest.consumers; import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.core.rest.model.materiali.RecuperaMaterialiRequestDTO; import it.integry.integrywmsnative.core.rest.model.materiali.RecuperaMaterialiResponseDTO; +import it.integry.integrywmsnative.core.rest.model.materiali.VersaMaterialiRequestDTO; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface MaterialiRESTConsumerService { + @POST("wms/materiali/versa") + Call> versa(@Body VersaMaterialiRequestDTO request); + @POST("wms/materiali/recupera") Call> recupera(@Body RecuperaMaterialiRequestDTO request); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/OrdiniRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/OrdiniRESTConsumer.java index 0aa4af9f..c545f96e 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/OrdiniRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/OrdiniRESTConsumer.java @@ -5,13 +5,13 @@ import androidx.annotation.NonNull; import com.annimon.stream.Optional; import com.annimon.stream.Stream; import com.google.gson.reflect.TypeToken; -import com.orhanobut.logger.Logger; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -39,12 +39,14 @@ import retrofit2.Response; public class OrdiniRESTConsumer extends _BaseRESTConsumer { private final RESTBuilder restBuilder; + private final ExecutorService executorService; private final SystemRESTConsumer mSystemRESTConsumer; private final EntityRESTConsumer mEntityRESTConsumer; - public OrdiniRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, EntityRESTConsumer entityRESTConsumer) { + public OrdiniRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService,SystemRESTConsumer systemRESTConsumer, EntityRESTConsumer entityRESTConsumer) { this.restBuilder = restBuilder; + this.executorService = executorService; this.mSystemRESTConsumer = systemRESTConsumer; this.mEntityRESTConsumer = entityRESTConsumer; } @@ -61,7 +63,7 @@ public class OrdiniRESTConsumer extends _BaseRESTConsumer { for (PickingObjectDTO pickingObjectDTO : pickingObjects) { for (MtbColt mtbColt : pickingObjectDTO.getMtbColts()) { - Stream.of(mtbColt.getMtbColr()) + mtbColt.getMtbColr().stream() .filter(x -> !UtilityString.isNullOrEmpty(x.getPartitaMag())) .forEach(x -> { @@ -125,28 +127,24 @@ public class OrdiniRESTConsumer extends _BaseRESTConsumer { this.mEntityRESTConsumer.processEntityList(partitaMag, true, MtbPartitaMag.class, onComplete, onFailed); } - public void getOrdiniInevasi(String codMdep, GestioneEnum gestione, RunnableArgs> onComplete, RunnableArgs onFailed) { - + public List getOrdiniInevasiSynchronized(String codMdep, GestioneEnum gestione) throws Exception { OrdiniRESTConsumerService service = restBuilder.getService(OrdiniRESTConsumerService.class); - service.getOrdiniInevasi(codMdep, gestione.getText()) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "getOrdiniInevasi", responseDtoList -> { - if (responseDtoList == null) responseDtoList = new ArrayList<>(); - onComplete.run(responseDtoList); - }, ex -> { - Logger.e(ex, "Errore durante il caricamento degli ordini di lavorazione"); - if (onFailed != null) onFailed.run(ex); - }); - } + var response = service.getOrdiniInevasi(codMdep, gestione.getText()) + .execute(); + var data = analyzeAnswer(response, "getOrdiniInevasi"); + return data == null ? new ArrayList<>() : data; + } - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); - } - }); + public void getOrdiniInevasi(String codMdep, GestioneEnum gestione, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var result = getOrdiniInevasiSynchronized(codMdep, gestione); + if (onComplete != null) onComplete.run(result); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } public void retrieveListaArticoliFromOrdiniUscita(String codMdep, List orders, RunnableArgs> onComplete, RunnableArgs onFailed) { diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PosizioniRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PosizioniRESTConsumer.java index 59e276e1..cba52383 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PosizioniRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PosizioniRESTConsumer.java @@ -1,12 +1,11 @@ package it.integry.integrywmsnative.core.rest.consumers; -import androidx.annotation.NonNull; - import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -14,44 +13,33 @@ import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.model.MtbColt; import it.integry.integrywmsnative.core.model.MtbDepoPosizione; import it.integry.integrywmsnative.core.rest.RESTBuilder; -import it.integry.integrywmsnative.core.rest.handler.ManagedErrorCallback; -import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse; import it.integry.integrywmsnative.core.utility.UtilityDB; -import retrofit2.Call; -import retrofit2.Response; @Singleton public class PosizioniRESTConsumer extends _BaseRESTConsumer { private final RESTBuilder restBuilder; private final SystemRESTConsumer mSystemRESTConsumer; + private final ExecutorService executorService; - public PosizioniRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer) { + public PosizioniRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer, ExecutorService executorService) { this.restBuilder = restBuilder; this.mSystemRESTConsumer = systemRESTConsumer; + this.executorService = executorService; } - public void getAvailablePosizioni(RunnableArgs> onComplete, RunnableArgs onFailed) { + public List getAvailablePosizioniSynchronized() throws Exception { String codMdep = null; PosizioniRESTConsumerService posizioniRESTConsumerService = restBuilder.getService(PosizioniRESTConsumerService.class); - posizioniRESTConsumerService.getAvailablePosizioni(codMdep).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "getAvailablePosizioni", (m) -> { - onComplete.run(response.body().getDto()); - }, onFailed); - } + var response = posizioniRESTConsumerService.getAvailablePosizioni(codMdep) + .execute(); - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var data = analyzeAnswer(response, "getAvailablePosizioni"); + return response.body().getDto(); } - - public void getBancaliInPosizione(MtbDepoPosizione mtbDepoPosizione, RunnableArgs> onComplete, RunnableArgs onFailed) { + public ArrayList getBancaliInPosizioneSynchronized(MtbDepoPosizione mtbDepoPosizione) throws Exception { String sql = "SELECT * FROM mtb_colt " + "WHERE segno > 0 " + "AND cod_mdep = " + UtilityDB.valueToString(mtbDepoPosizione.getCodMdep()) + " " + @@ -61,10 +49,18 @@ public class PosizioniRESTConsumer extends _BaseRESTConsumer { Type typeOfObjectsList = new TypeToken>() { }.getType(); - mSystemRESTConsumer.>processSql(sql, typeOfObjectsList, value -> { - if (onComplete != null) onComplete.run(value); - }, ex -> { - if (onFailed != null) onFailed.run(ex); + var value = mSystemRESTConsumer.>processSqlSynchronized(sql, typeOfObjectsList); + return value; + } + + public void getBancaliInPosizione(MtbDepoPosizione mtbDepoPosizione, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var result = getBancaliInPosizioneSynchronized(mtbDepoPosizione); + if (onComplete != null) onComplete.run(result); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PrinterRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PrinterRESTConsumer.java index 460bc337..0c926505 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PrinterRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PrinterRESTConsumer.java @@ -123,27 +123,16 @@ public class PrinterRESTConsumer extends _BaseRESTConsumer { printReportType(reportType, codMdep, null, params, onComplete, onFailed); } - public void printClosedOrders(PrintOrderCloseDTO dto, String codMdep, Runnable onComplete, RunnableArgs onFailed) { + public void printClosedOrdersSynchronized(PrintOrderCloseDTO dto, String codMdep) throws Exception { if (BuildConfig.DEBUG) { - onComplete.run(); return; } PrinterRESTConsumerService printerService = restBuilder.getService(PrinterRESTConsumerService.class, 240); Call> callable = printerService.printClosedOrders(codMdep, dto); - callable.enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "printCollo", data -> { - onComplete.run(); - }, onFailed); - } - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + var response = callable.execute(); + analyzeAnswer(response, "printCollo"); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java index f42791d7..578566df 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java @@ -89,6 +89,11 @@ public class SystemRESTConsumer extends _BaseRESTConsumer { }); } + public List getAvailableCodMdepsSynchronized() throws Exception { + SystemRESTConsumerService service = restBuilder.getService(SystemRESTConsumerService.class); + var response = service.getAvailableCodMdeps().execute(); + return analyzeAnswer(response, "CodMdepsAvailable"); + } public void getAvailableCodMdeps(final RunnableArgs> onSuccess, RunnableArgs onFailed) { SystemRESTConsumerService service = restBuilder.getService(SystemRESTConsumerService.class); diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/interfaces/ColliScaricoRESTConsumerInterface.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/interfaces/ColliScaricoRESTConsumerInterface.java index 103887aa..82babeb2 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/interfaces/ColliScaricoRESTConsumerInterface.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/interfaces/ColliScaricoRESTConsumerInterface.java @@ -12,13 +12,23 @@ import it.integry.integrywmsnative.core.rest.model.uds.InsertUDSRowRequestDTO; public interface ColliScaricoRESTConsumerInterface { + MtbColt createUDSSynchronized(CreateUDSRequestDTO createUDSRequestDTO) throws Exception; + void createUDS(CreateUDSRequestDTO createUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed); + CloseUDSResponseDTO closeUDSSynchronized(CloseUDSRequestDTO closeUDSRequestDTO) throws Exception; + void closeUDS(CloseUDSRequestDTO closeUDSRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed); + MtbColr insertUDSRowSynchronized(InsertUDSRowRequestDTO insertUDSRowRequestDTO) throws Exception; + void insertUDSRow(InsertUDSRowRequestDTO insertUDSRowRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed); + MtbColr editUDSRowSynchronized(EditUDSRowRequestDTO editUDSRowRequestDTO) throws Exception; + void editUDSRow(EditUDSRowRequestDTO editUDSRowRequestDTO, RunnableArgs onComplete, RunnableArgs onFailed); + void deleteUDSRowSynchronized(DeleteUDSRowRequestDTO deleteUDSRequestDTO) throws Exception; + void deleteUDSRow(DeleteUDSRowRequestDTO deleteUDSRequestDTO, Runnable onComplete, RunnableArgs onFailed); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/deserializer/MutableLiveDataDeserializer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/deserializer/MutableLiveDataDeserializer.java new file mode 100644 index 00000000..fb972cfd --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/deserializer/MutableLiveDataDeserializer.java @@ -0,0 +1,21 @@ +package it.integry.integrywmsnative.core.rest.deserializer; + +import androidx.lifecycle.MutableLiveData; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public class MutableLiveDataDeserializer implements JsonDeserializer> { + @Override + public MutableLiveData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + Type type = ((ParameterizedType) typeOfT).getActualTypeArguments()[0]; + MutableLiveData liveData = new MutableLiveData<>(); + liveData.setValue(context.deserialize(json, type)); + return liveData; + } +} diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/model/UpdatePosizioneULRequestDTO.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/UpdatePosizioneULRequestDTO.java new file mode 100644 index 00000000..82e8b488 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/UpdatePosizioneULRequestDTO.java @@ -0,0 +1,27 @@ +package it.integry.integrywmsnative.core.rest.model; + +import it.integry.integrywmsnative.core.model.MtbColt; + +public class UpdatePosizioneULRequestDTO { + + private MtbColt mtbColt; + private String posizione; + + public MtbColt getMtbColt() { + return mtbColt; + } + + public UpdatePosizioneULRequestDTO setMtbColt(MtbColt mtbColt) { + this.mtbColt = mtbColt; + return this; + } + + public String getPosizione() { + return posizione; + } + + public UpdatePosizioneULRequestDTO setPosizione(String posizione) { + this.posizione = posizione; + return this; + } +} diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/model/materiali/VersaMaterialiRequestDTO.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/materiali/VersaMaterialiRequestDTO.java new file mode 100644 index 00000000..8cb1fa80 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/materiali/VersaMaterialiRequestDTO.java @@ -0,0 +1,110 @@ +package it.integry.integrywmsnative.core.rest.model.materiali; + +import java.math.BigDecimal; +import java.time.LocalDate; + +public class VersaMaterialiRequestDTO { + + private String codMart; + private String partitaMag; + private BigDecimal numCnf; + private BigDecimal qtaCnf; + private BigDecimal qtaTot; + + private Integer numCollo; + private LocalDate dataCollo; + private String gestione; + private String serCollo; + private String barcodeUl; + + + public String getCodMart() { + return codMart; + } + + public VersaMaterialiRequestDTO setCodMart(String codMart) { + this.codMart = codMart; + return this; + } + + public String getPartitaMag() { + return partitaMag; + } + + public VersaMaterialiRequestDTO setPartitaMag(String partitaMag) { + this.partitaMag = partitaMag; + return this; + } + + public BigDecimal getNumCnf() { + return numCnf; + } + + public VersaMaterialiRequestDTO setNumCnf(BigDecimal numCnf) { + this.numCnf = numCnf; + return this; + } + + public BigDecimal getQtaCnf() { + return qtaCnf; + } + + public VersaMaterialiRequestDTO setQtaCnf(BigDecimal qtaCnf) { + this.qtaCnf = qtaCnf; + return this; + } + + public BigDecimal getQtaTot() { + return qtaTot; + } + + public VersaMaterialiRequestDTO setQtaTot(BigDecimal qtaTot) { + this.qtaTot = qtaTot; + return this; + } + + public Integer getNumCollo() { + return numCollo; + } + + public VersaMaterialiRequestDTO setNumCollo(Integer numCollo) { + this.numCollo = numCollo; + return this; + } + + public LocalDate getDataCollo() { + return dataCollo; + } + + public VersaMaterialiRequestDTO setDataCollo(LocalDate dataCollo) { + this.dataCollo = dataCollo; + return this; + } + + public String getGestione() { + return gestione; + } + + public VersaMaterialiRequestDTO setGestione(String gestione) { + this.gestione = gestione; + return this; + } + + public String getSerCollo() { + return serCollo; + } + + public VersaMaterialiRequestDTO setSerCollo(String serCollo) { + this.serCollo = serCollo; + return this; + } + + public String getBarcodeUl() { + return barcodeUl; + } + + public VersaMaterialiRequestDTO setBarcodeUl(String barcodeUl) { + this.barcodeUl = barcodeUl; + return this; + } +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/model/materiali/VersaMaterialiResponseDTO.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/materiali/VersaMaterialiResponseDTO.java new file mode 100644 index 00000000..9f997465 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/model/materiali/VersaMaterialiResponseDTO.java @@ -0,0 +1,4 @@ +package it.integry.integrywmsnative.core.rest.model.materiali; + +public class VersaMaterialiResponseDTO { +} diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/serializer/MutableLiveDataSerializer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/serializer/MutableLiveDataSerializer.java new file mode 100644 index 00000000..b6077911 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/serializer/MutableLiveDataSerializer.java @@ -0,0 +1,16 @@ +package it.integry.integrywmsnative.core.rest.serializer; + +import androidx.lifecycle.MutableLiveData; + +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; + +public class MutableLiveDataSerializer implements JsonSerializer> { + @Override + public JsonElement serialize(MutableLiveData src, Type typeOfSrc, JsonSerializationContext context) { + return context.serialize(src.getValue()); + } +} diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/watcher/ServerStatusChecker.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/watcher/ServerStatusChecker.java index 8a9daacb..f9b96232 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/watcher/ServerStatusChecker.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/watcher/ServerStatusChecker.java @@ -12,7 +12,11 @@ import it.integry.integrywmsnative.core.utility.UtilityString; public class ServerStatusChecker { - private static final ServerStatusChecker instance = new ServerStatusChecker(); + + private final Handler handler; + + + private final List> mCallback = new ArrayList<>(); @@ -26,7 +30,29 @@ public class ServerStatusChecker { private final long MILLIS_DELAY = 5 * 1000; - private final Handler handler = new Handler(); + public ServerStatusChecker(Handler handler) { + this.handler = handler; + } + + public void addCallback(RunnableArgs callback) { + this.mCallback.add(callback); + } + + public void removeCallback(RunnableArgs callback) { + this.mCallback.remove(callback); + } + + + public void init() { + this.shouldExecute = true; + + this.handler.post(this.runnableCode); + } + + public void dispose() { + this.shouldExecute = false; + } + private final Runnable runnableCode = new Runnable() { @Override public void run() { @@ -42,27 +68,4 @@ public class ServerStatusChecker { } }; - public void addCallback(RunnableArgs callback) { - this.mCallback.add(callback); - } - - public void removeCallback(RunnableArgs callback) { - this.mCallback.remove(callback); - } - - - public static void init() { - instance.shouldExecute = true; - - instance.handler.post(instance.runnableCode); - } - - public static void dispose() { - instance.shouldExecute = false; - } - - public static ServerStatusChecker getInstance() { - return instance; - } - } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/settings/DBSettingsModel.java b/app/src/main/java/it/integry/integrywmsnative/core/settings/DBSettingsModel.java index 6964148f..39c89a26 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/settings/DBSettingsModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/settings/DBSettingsModel.java @@ -96,6 +96,7 @@ public class DBSettingsModel { private boolean flagEnableArtCreation; private List allowedCodMgrpForArtCreation; private boolean flagAccettazioneGroupListForn = false; + private boolean flagSpedizioneEnableFastPicking = false; public boolean isFlagSpedizioneEnableFakeGiacenza() { return flagSpedizioneEnableFakeGiacenza; @@ -806,4 +807,12 @@ public class DBSettingsModel { public void setFlagAccettazioneGroupListForn(boolean flagAccettazioneGroupListForn) { this.flagAccettazioneGroupListForn = flagAccettazioneGroupListForn; } + + public boolean isFlagSpedizioneEnableFastPicking() { + return flagSpedizioneEnableFastPicking; + } + + public void setFlagSpedizioneEnableFastPicking(boolean flagSpedizioneEnableFastPicking) { + this.flagSpedizioneEnableFastPicking = flagSpedizioneEnableFastPicking; + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsManager.java b/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsManager.java index f0850073..2a707d8f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsManager.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsManager.java @@ -102,136 +102,111 @@ public class SettingsManager { } - public static void loadDBVariables(RunnableArgs onProgress, Runnable onComplete, RunnableArgs onFailed) { + public static void loadDBVariables(RunnableArgs onProgress) throws Exception { dbSettingsModelIstance = new DBSettingsModel(); Trace perfTrace = UtilityFirebase.getNewPerformanceTrace("db_load_vars"); perfTrace.start(); - Runnable tmpOnComplete = () -> { - perfTrace.stop(); - onComplete.run(); - }; - - RunnableArgs tmpOnFailed = ex -> { - UtilityLogger.error(ex); - perfTrace.putAttribute("failed", "true"); - if (!(ex instanceof SocketTimeoutException)) onFailed.run(ex); - else - onFailed.run(new Exception("Errore durante il caricamento dei dati. Riavviare l'applicazione!")); - }; - - - onProgress.run("depositi"); - loadAvailableCodMdeps(() -> { + try { + onProgress.run("depositi"); + loadAvailableCodMdeps(); onProgress.run("posizioni"); - loadAvailablePosizioni(() -> { + loadAvailablePosizioni(); - onProgress.run("impostazioni"); - loadGestSetupValues(() -> { - onProgress.run("dati azienda"); - loadDatiAzienda(() -> { + onProgress.run("impostazioni"); + loadGestSetupValues(); - loadTipiCollo(tmpOnComplete, tmpOnFailed); - }, tmpOnFailed); - }, tmpOnFailed); - }, tmpOnFailed); - }, tmpOnFailed); + onProgress.run("dati azienda"); + loadDatiAzienda(); + loadTipiCollo(); + + perfTrace.stop(); + + } catch (Exception ex) { + UtilityLogger.error(ex); + perfTrace.putAttribute("failed", "true"); + + if (!(ex instanceof SocketTimeoutException)) + throw ex; + else + throw new Exception("Errore durante il caricamento dei dati. Riavviare l'applicazione!"); + } } - private static void loadTipiCollo(Runnable onComplete, RunnableArgs onFailed) { - mImballiRESTConsumer.retrieveImballi(MtbTCol.FlagUiUlEnum.UL, tipiColloUl -> { - mImballiRESTConsumer.retrieveImballi(MtbTCol.FlagUiUlEnum.UI, tipiColloUi -> { + private static void loadTipiCollo() throws Exception { + var tipiColloUl = mImballiRESTConsumer.retrieveImballiSyncronized(MtbTCol.FlagUiUlEnum.UL); + var tipiColloUi = mImballiRESTConsumer.retrieveImballiSyncronized(MtbTCol.FlagUiUlEnum.UI); - var imballiList = new ObservableArrayList(); - imballiList.addAll(tipiColloUi); - imballiList.addAll(tipiColloUl); + var imballiList = new ObservableArrayList(); - SettingsManager.iDB().setInternalImballi(imballiList); - onComplete.run(); - }, onFailed); - }, onFailed); + imballiList.addAll(tipiColloUi); + imballiList.addAll(tipiColloUl); + SettingsManager.iDB().setInternalImballi(imballiList); } - private static void loadDatiAzienda(Runnable onComplete, RunnableArgs onFailed) { + private static void loadDatiAzienda() throws Exception { - mAziendaRESTConsumer.retrieveAzienda(datiAzienda -> { - SettingsManager.iDB().setDatiAzienda(datiAzienda); + var datiAzienda = mAziendaRESTConsumer.retrieveAziendaSynchronized(); - if (!SettingsManager.iDB().isFlagUseCodAnagAziendale()) { - onComplete.run(); - return; - } + SettingsManager.iDB().setDatiAzienda(datiAzienda); - String internalCodAnagsQuery = "SELECT ga.cod_anag,\n" + - " CAST(CASE WHEN vc.cod_anag IS NOT NULL THEN 1 ELSE 0 END AS BIT) AS is_cliente,\n" + - " CAST(CASE WHEN af.cod_anag IS NOT NULL THEN 1 ELSE 0 END AS BIT) AS is_fornitore\n" + - "FROM azienda\n" + - "INNER JOIN gtb_anag ga on azienda.part_iva = ga.part_iva\n" + - "LEFT OUTER JOIN vtb_clie vc on ga.cod_anag = vc.cod_anag AND vc.flag_stato = 'A'\n" + - "LEFT OUTER JOIN atb_forn af on ga.cod_anag = af.cod_anag AND af.flag_stato = 'A'"; + if (!SettingsManager.iDB().isFlagUseCodAnagAziendale()) { + return; + } - Type type = new TypeToken>() { - }.getType(); - mSystemRESTConsumer.>processSql(internalCodAnagsQuery, type, internalCodAnagsList -> { - SettingsManager.iDB().setInternalCodAnags(internalCodAnagsList); + String internalCodAnagsQuery = "SELECT ga.cod_anag,\n" + + " CAST(CASE WHEN vc.cod_anag IS NOT NULL THEN 1 ELSE 0 END AS BIT) AS is_cliente,\n" + + " CAST(CASE WHEN af.cod_anag IS NOT NULL THEN 1 ELSE 0 END AS BIT) AS is_fornitore\n" + + "FROM azienda\n" + + "INNER JOIN gtb_anag ga on azienda.part_iva = ga.part_iva\n" + + "LEFT OUTER JOIN vtb_clie vc on ga.cod_anag = vc.cod_anag AND vc.flag_stato = 'A'\n" + + "LEFT OUTER JOIN atb_forn af on ga.cod_anag = af.cod_anag AND af.flag_stato = 'A'"; - if (onComplete != null) onComplete.run(); - }, onFailed); - - }, onFailed); + Type type = new TypeToken>() { + }.getType(); + var internalCodAnagsList = mSystemRESTConsumer.>processSqlSynchronized(internalCodAnagsQuery, type); + SettingsManager.iDB().setInternalCodAnags(internalCodAnagsList); } - private static void loadAvailableCodMdeps(Runnable onComplete, RunnableArgs onFailed) { - mSystemRESTConsumer.getAvailableCodMdeps(availableCodMdeps -> { - dbSettingsModelIstance.setAvailableCodMdep(availableCodMdeps); + private static void loadAvailableCodMdeps() throws Exception { + var availableCodMdeps = mSystemRESTConsumer.getAvailableCodMdepsSynchronized(); - if (availableCodMdeps == null || availableCodMdeps.isEmpty()) { - onFailed.run(new Exception(mContext.getText(R.string.no_codmdep_available).toString())); - return; - } + dbSettingsModelIstance.setAvailableCodMdep(availableCodMdeps); - boolean codMdepExistsAnymore = false; + if (availableCodMdeps == null || availableCodMdeps.isEmpty()) { + throw new Exception(mContext.getText(R.string.no_codmdep_available).toString()); + } - if (settingsModelIstance.getUserSession().getDepo() != null) { - for (AvailableCodMdepsDTO availableCodMdepDTO : availableCodMdeps) { - //Controllo se il codMdep salvato esiste ancora - if (availableCodMdepDTO.getCodMdep().equalsIgnoreCase(settingsModelIstance.getUserSession().getDepo().getCodMdep())) { - codMdepExistsAnymore = true; - break; - } + boolean codMdepExistsAnymore = false; + + if (settingsModelIstance.getUserSession().getDepo() != null) { + for (AvailableCodMdepsDTO availableCodMdepDTO : availableCodMdeps) { + //Controllo se il codMdep salvato esiste ancora + if (availableCodMdepDTO.getCodMdep().equalsIgnoreCase(settingsModelIstance.getUserSession().getDepo().getCodMdep())) { + codMdepExistsAnymore = true; + break; } } + } - if (!codMdepExistsAnymore) { - settingsModelIstance.getUserSession().setDepo(availableCodMdeps.get(0)); - } - - if (onComplete != null) onComplete.run(); - }, ex -> { - //BOH - if (onFailed != null) onFailed.run(ex); - }); + if (!codMdepExistsAnymore) { + settingsModelIstance.getUserSession().setDepo(availableCodMdeps.get(0)); + } } - private static void loadAvailablePosizioni(Runnable onComplete, RunnableArgs onFailed) { - mPosizioniRESTConsumer.getAvailablePosizioni(availablePosizioni -> { - dbSettingsModelIstance.setAvailablePosizioni(availablePosizioni); - - if (onComplete != null) onComplete.run(); - }, ex -> { - if (onFailed != null) onFailed.run(ex); - } - ); + private static void loadAvailablePosizioni() throws Exception { + var availablePosizioni = mPosizioniRESTConsumer.getAvailablePosizioniSynchronized(); + dbSettingsModelIstance.setAvailablePosizioni(availablePosizioni); } - private static void loadGestSetupValues(Runnable onComplete, RunnableArgs onFailed) { + private static void loadGestSetupValues() throws Exception { List stbGestSetupReaderList = new ArrayList<>(); @@ -583,6 +558,12 @@ public class SettingsManager { .setKeySection("ENABLE_POSITION_CHANGE_REQUEST") .setSetter(dbSettingsModelIstance::setFlagPositionChangeRequest) .setDefaultValue(true)); + stbGestSetupReaderList.add(new StbGestSetupReader<>(Boolean.class) + .setGestName("PICKING") + .setSection("SPEDIZIONE") + .setKeySection("ENABLE_FAST_PICKING") + .setSetter(dbSettingsModelIstance::setFlagSpedizioneEnableFastPicking) + .setDefaultValue(false)); stbGestSetupReaderList.add(new StbGestSetupReader<>(String.class) .setGestName("PICKING") @@ -648,34 +629,33 @@ public class SettingsManager { String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); - mGestSetupRESTConsumer.getValues(codMdep, stbGestSetupReaderList, list -> { + var list = mGestSetupRESTConsumer.getValuesSynchronized(codMdep, stbGestSetupReaderList); - for (var stbGestSetupReader : list) { - var value = stbGestSetupReader.getValue(); - var clazz = stbGestSetupReader.getClazz(); - Object finalValue = null; - if (value != null) { - if (clazz == String.class) { - finalValue = clazz.cast(value); - } else if (clazz == Boolean.class) { - finalValue = clazz.cast("S".equalsIgnoreCase(value)); - } else if (clazz == Integer.class && value != null) { - finalValue = clazz.cast(Integer.parseInt(value)); - } - } else if (stbGestSetupReader.getDefaultValue() == null) { - if (clazz == Boolean.class) { - finalValue = clazz.cast(Boolean.FALSE); - } else if (clazz == Integer.class) { - finalValue = clazz.cast(0); - } - } else finalValue = stbGestSetupReader.getDefaultValue(); + for (var stbGestSetupReader : list) { + var value = stbGestSetupReader.getValue(); + var clazz = stbGestSetupReader.getClazz(); - stbGestSetupReader.getSetter().run(finalValue); - } + Object finalValue = null; + if (value != null) { + if (clazz == String.class) { + finalValue = clazz.cast(value); + } else if (clazz == Boolean.class) { + finalValue = clazz.cast("S".equalsIgnoreCase(value)); + } else if (clazz == Integer.class && value != null) { + finalValue = clazz.cast(Integer.parseInt(value)); + } + } else if (stbGestSetupReader.getDefaultValue() == null) { + if (clazz == Boolean.class) { + finalValue = clazz.cast(Boolean.FALSE); + } else if (clazz == Integer.class) { + finalValue = clazz.cast(0); + } + } else finalValue = stbGestSetupReader.getDefaultValue(); + + stbGestSetupReader.getSetter().run(finalValue); + } - if (onComplete != null) onComplete.run(); - }, onFailed); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityBarcode.java b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityBarcode.java index 2884f6ba..0d446873 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityBarcode.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityBarcode.java @@ -2,7 +2,6 @@ package it.integry.integrywmsnative.core.utility; import android.graphics.Bitmap; -import com.annimon.stream.Stream; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; @@ -12,6 +11,7 @@ import com.journeyapps.barcodescanner.BarcodeEncoder; import java.util.Calendar; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; import it.integry.barcode_base_android_library.model.BarcodeScanDTO; import it.integry.barcode_base_android_library.model.BarcodeType; @@ -61,7 +61,7 @@ public class UtilityBarcode { boolean isPosizione = false; if (SettingsManager.iDB().getAvailablePosizioni() != null) { - Stream tmpStream = Stream.of(SettingsManager.iDB().getAvailablePosizioni()) + Stream tmpStream = SettingsManager.iDB().getAvailablePosizioni().stream() .filter(x -> x.getPosizione().equalsIgnoreCase(barcode) && (!enableCheckCodMdep || currentCodMdep.equalsIgnoreCase(x.getCodMdep()))); if (tmpStream.count() > 0) { diff --git a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityDialog.java b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityDialog.java index fda1521a..fb00af71 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityDialog.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityDialog.java @@ -40,4 +40,5 @@ public class UtilityDialog { // dialog.getWindow().setLayout(width, LinearLayout.LayoutParams.WRAP_CONTENT); // } + } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityExceptions.java b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityExceptions.java index 7c9a097c..03f373b7 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityExceptions.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityExceptions.java @@ -10,6 +10,7 @@ import com.google.firebase.crashlytics.FirebaseCrashlytics; import com.orhanobut.logger.Logger; import it.integry.integrywmsnative.BuildConfig; +import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager; import it.integry.integrywmsnative.core.exception.InvalidConnectionException; import it.integry.integrywmsnative.core.exception.InvalidLUException; import it.integry.integrywmsnative.core.exception.InvalidLUGestioneException; @@ -19,11 +20,12 @@ import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView; public class UtilityExceptions { - private static final Class[] FIREBASE_IGNORED_EXCEPTIONS = new Class[] { + private static final Class[] FIREBASE_IGNORED_EXCEPTIONS = new Class[]{ InvalidConnectionException.class, InvalidLUGestioneException.class, InvalidLUException.class }; + public static void defaultException(Context context, Exception ex) { defaultException(context, ex, false); } @@ -47,7 +49,11 @@ public class UtilityExceptions { FragmentManager fm = ContextHelper.getFragmentManagerFromContext(context); if (fm != null) { - DialogSimpleMessageView.makeErrorDialog(Html.fromHtml(errorMessage), null, null) + boolean isBarcodeEnabled = BarcodeManager.isLastCallbackEnabled(); + if (isBarcodeEnabled) BarcodeManager.disableLastCallback(); + DialogSimpleMessageView.makeErrorDialog(Html.fromHtml(errorMessage), null, () -> { + if (isBarcodeEnabled) BarcodeManager.enableLastCallback(); + }) .show(fm, "tag"); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityGson.java b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityGson.java index 37dc03fa..1fb6ec90 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityGson.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/utility/UtilityGson.java @@ -1,5 +1,7 @@ package it.integry.integrywmsnative.core.utility; +import androidx.lifecycle.MutableLiveData; + import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -12,10 +14,12 @@ import it.integry.integrywmsnative.core.model.secondary.StatoPartitaMag; import it.integry.integrywmsnative.core.rest.deserializer.LocalDateDeserializer; import it.integry.integrywmsnative.core.rest.deserializer.LocalDateTimeDeserializer; import it.integry.integrywmsnative.core.rest.deserializer.MtbTcolFlagUiUlDeserializer; +import it.integry.integrywmsnative.core.rest.deserializer.MutableLiveDataDeserializer; import it.integry.integrywmsnative.core.rest.deserializer.StatoPartitaMagDeserializer; import it.integry.integrywmsnative.core.rest.serializer.LocalDateSerializer; import it.integry.integrywmsnative.core.rest.serializer.LocalDateTimeSerializer; import it.integry.integrywmsnative.core.rest.serializer.MtbTcolFlagUiUlSerializer; +import it.integry.integrywmsnative.core.rest.serializer.MutableLiveDataSerializer; import it.integry.integrywmsnative.core.rest.serializer.StatoPartitaMagSerializer; public class UtilityGson { @@ -24,6 +28,8 @@ public class UtilityGson { return new GsonBuilder() .setDateFormat("dd/MM/yyyy HH:mm:ss") .excludeFieldsWithModifiers(Modifier.TRANSIENT) + .registerTypeAdapter(MutableLiveData.class, new MutableLiveDataDeserializer()) + .registerTypeAdapter(MutableLiveData.class, new MutableLiveDataSerializer()) .registerTypeAdapter(LocalDate.class, new LocalDateDeserializer()) .registerTypeAdapter(LocalDate.class, new LocalDateSerializer()) .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer()) diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingActivity.java index 3f899f04..4d618d3e 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingActivity.java @@ -99,7 +99,7 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac public BindableBoolean noLUPresent = new BindableBoolean(true); public BindableBoolean bottomSheetEnabled = new BindableBoolean(false); - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private boolean mShowSecondaryUntMis = true; private boolean mShouldCloseActivity; private AccettazioneBollaPickingOrderBy.Enum mCurrentOrderBy; @@ -183,10 +183,10 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac this.mBindings.bottomSheetLuContent.collapse(); } else if (!noLUPresent.get()) { this.mShouldCloseActivity = true; - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); this.mViewModel.closeLU(); } else { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } } @@ -200,7 +200,7 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(this, ex, false))); } @@ -591,7 +591,7 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac UtilityExceptions.defaultException(this, ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @Override @@ -601,7 +601,7 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canPartitaMagBeChanged, - boolean canOverflowQuantity, RunnableArgss onComplete) { + boolean canOverflowQuantity, RunnableArgs onComplete) { DialogInputQuantityV2DTO dialogInputQuantityV2DTO = new DialogInputQuantityV2DTO() .setMtbAart(mtbAart) .setInitialNumCnf(initialNumCnf) @@ -609,7 +609,7 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac .setInitialQtaTot(initialQtaTot) .setTotalQtaOrd(totalQtaOrd) .setTotalNumCnfOrd(totalNumCnfOrd) - .setQtaCnfOrd(qtaCnfOrd) + .setTotalQtaCnfOrd(qtaCnfOrd) .setTotalQtaToBeTaken(totalQtaToBeTaken) .setTotalNumCnfToBeTaken(totalNumCnfToBeTaken) .setQtaCnfToBeTaken(qtaCnfToBeTaken) @@ -626,14 +626,19 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if(resultDTO.isAborted()) { + this.mViewModel.resetMatchedRows(); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) .setQtaTot(resultDTO.getQtaTot()) .setPartitaMag(resultDTO.getPartitaMag()) .setDataScad(resultDTO.getDataScad()); - onComplete.run(pickedQuantityDTO, shouldCloseLU); + onComplete.run(pickedQuantityDTO); }) .setOnAbort(() -> this.mViewModel.resetMatchedRows()) .show(getSupportFragmentManager(), "tag"); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingViewModel.java index 2e388663..1c564213 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_bolla_picking/AccettazioneBollaPickingViewModel.java @@ -305,8 +305,8 @@ public class AccettazioneBollaPickingViewModel { private void loadArticolo(String barcodeProd, PickDataDTO pickData, Runnable onComplete) { this.mArticoloRESTConsumer.searchByBarcode(barcodeProd, mtbAartList -> { - if (mtbAartList != null && mtbAartList.size() > 0) { - this.searchArtFromAnag(mtbAartList.get(0), pickData, onComplete); + if (mtbAartList != null && !mtbAartList.isEmpty()) { + this.searchArtFromAnag(mtbAartList.get(0), pickData, null, onComplete); } else { this.manageUnknownBarcode(barcodeProd, onComplete); } @@ -315,28 +315,41 @@ public class AccettazioneBollaPickingViewModel { } - private void searchArtFromAnag(MtbAart mtbAart, PickDataDTO pickData, Runnable onComplete) { + private void searchArtFromAnag(MtbAart mtbAart, PickDataDTO pickData, ArrayList previousSearchedArts, Runnable onComplete) { + if (previousSearchedArts == null) previousSearchedArts = new ArrayList<>(); + + if (previousSearchedArts.contains(mtbAart)) { + manageNoArtFound(mtbAart, pickData); + return; + } + + previousSearchedArts.add(mtbAart); + final List pickingList = mPickingList.getValue(); - List matchPickingObject = Stream.of(pickingList) - .filter(x -> UtilityString.equalsIgnoreCase(mtbAart.getCodMart(), x.getSitBollaAccettazione().getCodMart())) - .toList(); + List matchPickingObject = pickingList == null ? new ArrayList<>() : + pickingList.stream() + .filter(x -> UtilityString.equalsIgnoreCase(mtbAart.getCodMart(), x.getSitBollaAccettazione().getCodMart())) + .collect(Collectors.toList()); for (PickingObjectDTO pickingObjectDTO : matchPickingObject) { pickingObjectDTO.setTempPickData(pickData); } - this.loadMatchedRows(matchPickingObject, mtbAart, pickData); + this.loadMatchedRows(matchPickingObject, mtbAart, pickData, previousSearchedArts); onComplete.run(); } - private void loadMatchedRows(List matchedRows, MtbAart mtbAart, PickDataDTO pickDataDTO) { + private void loadMatchedRows(List matchedRows, MtbAart mtbAart, PickDataDTO pickDataDTO, ArrayList previousSearchedArts) { if (matchedRows == null || matchedRows.isEmpty()) { + this.sendOnLoadingStarted(); this.mArticoloRESTConsumer.findIfIsKit(mtbAart, mtbAartFind -> { - if (mtbAartFind == null){ + this.sendOnLoadingEnded(); + if (mtbAartFind == null) { manageNoArtFound(mtbAart, pickDataDTO); } else { - searchArtFromAnag(mtbAartFind, pickDataDTO, () -> {}); + searchArtFromAnag(mtbAartFind, pickDataDTO, previousSearchedArts, () -> { + }); } }, this::sendError); } else if (matchedRows.size() == 1) { @@ -442,7 +455,7 @@ public class AccettazioneBollaPickingViewModel { dispatchBollaRow(pickingObjectDTO); } - public void dispatchBollaRow(final PickingObjectDTO pickingObjectDTO){ + public void dispatchBollaRow(final PickingObjectDTO pickingObjectDTO) { dispatchBollaRow(pickingObjectDTO, false); } @@ -554,7 +567,7 @@ public class AccettazioneBollaPickingViewModel { UtilityBigDecimal.greaterThan(initialNumCnf, pickingObjectDTO.getMtbAart().getColliPedana())) { initialNumCnf = pickingObjectDTO.getMtbAart().getColliPedana(); initialQtaTot = initialNumCnf.multiply(initialQtaCnf); - } else if(UtilityBigDecimal.greaterThan(initialNumCnf, BigDecimal.ONE) && pickingObjectDTO.getMtbAart().isFlagQtaCnfFissaBoolean()) { + } else if (UtilityBigDecimal.greaterThan(initialNumCnf, BigDecimal.ONE) && pickingObjectDTO.getMtbAart().isFlagQtaCnfFissaBoolean()) { initialNumCnf = BigDecimal.ONE; initialQtaTot = initialNumCnf.multiply(initialQtaCnf); } @@ -577,7 +590,7 @@ public class AccettazioneBollaPickingViewModel { } } - if (!longClick){ + if (!longClick) { this.sendOnItemDispatched( pickingObjectDTO, pickingObjectDTO.getMtbAart(), @@ -594,14 +607,14 @@ public class AccettazioneBollaPickingViewModel { partitaMag, dataScad, true, - (pickedQuantityDTO, shouldCloseLU) -> { + pickedQuantityDTO -> { this.saveNewRow(pickingObjectDTO, pickedQuantityDTO.getNumCnf(), pickedQuantityDTO.getQtaCnf(), pickedQuantityDTO.getQtaTot(), pickedQuantityDTO.getPartitaMag(), pickedQuantityDTO.getDataScad(), - shouldCloseLU); + pickedQuantityDTO.isShouldCloseLu()); }); } else { this.saveNewRow( @@ -693,7 +706,9 @@ public class AccettazioneBollaPickingViewModel { mtbColrToEdit.getPartitaMag(), mtbColrToEdit.getDataScadPartita(), true, - (pickedQuantityDTO, shouldCloseLU) -> { + pickedQuantityDTO -> { + if (pickedQuantityDTO == null) + return; this.saveEditedRow(mtbColrToEdit, pickedQuantityDTO.getNumCnf(), @@ -701,7 +716,7 @@ public class AccettazioneBollaPickingViewModel { pickedQuantityDTO.getQtaTot(), pickedQuantityDTO.getPartitaMag(), pickedQuantityDTO.getDataScad(), - shouldCloseLU); + pickedQuantityDTO.isShouldCloseLu()); }); } @@ -807,7 +822,7 @@ public class AccettazioneBollaPickingViewModel { int listCount = pickingList != null ? pickingList.size() : 0; int anomalie = listCount > 0 ? listCount - mtbColr.size() : 0; - if (anomalie == 0){ + if (anomalie == 0) { closeUdc(closeUDCRequestDTO); } else { onConfirmAnomalie(anomalie, canBeClose -> { @@ -822,7 +837,7 @@ public class AccettazioneBollaPickingViewModel { }, this::sendError); } - private void closeUdc(CloseUDCRequestDTO closeUDCRequestDTO){ + private void closeUdc(CloseUDCRequestDTO closeUDCRequestDTO) { mColliCaricoRESTConsumer.closeUDC(closeUDCRequestDTO, closeUDCResponse -> { Runnable onVersamentoCompleted = () -> { @@ -1002,7 +1017,7 @@ public class AccettazioneBollaPickingViewModel { String partitaMag, LocalDate dataScad, boolean canPartitaMagBeChanged, - RunnableArgss onComplete) { + RunnableArgs onComplete) { if (this.mListener != null) mListener.onItemDispatched(pickingObjectDTO, mtbAart, initialNumCnf, @@ -1058,7 +1073,7 @@ public class AccettazioneBollaPickingViewModel { return this; } - private void onConfirmAnomalie(int anomalie, RunnableArgs onConfirm){ + private void onConfirmAnomalie(int anomalie, RunnableArgs onConfirm) { if (this.mListener != null) mListener.onConfirmAnomalie(anomalie, onConfirm); } @@ -1088,7 +1103,7 @@ public class AccettazioneBollaPickingViewModel { LocalDate dataScad, boolean canPartitaMagBeChanged, boolean canOverflowQuantity, - RunnableArgss onComplete); + RunnableArgs onComplete); void onFilterCodMartApplied(String codMartToFilter); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_ordini_picking/AccettazioneOrdiniPickingActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_ordini_picking/AccettazioneOrdiniPickingActivity.java index e7805e0c..403b0907 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_ordini_picking/AccettazioneOrdiniPickingActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/accettazione_ordini_picking/AccettazioneOrdiniPickingActivity.java @@ -107,7 +107,7 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A public BindableBoolean noLUPresent = new BindableBoolean(true); public BindableBoolean bottomSheetEnabled = new BindableBoolean(false); - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private List mOrders; private List mSitArts; @@ -310,10 +310,10 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A this.mBindings.bottomSheetLuContent.collapse(); } else if (!noLUPresent.get()) { this.mShouldCloseActivity = true; - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); this.mViewModel.closeLU(); } else { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } } @@ -344,7 +344,7 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO().setOnScanSuccessful(onScanSuccessful).setOnScanFailed(ex -> UtilityExceptions.defaultException(this, ex, false))); + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO().setOnScanSuccessful(onScanSuccessful).setOnScanFailed(ex -> UtilityExceptions.defaultException(this, ex, false))); } private void initRecyclerView() { @@ -767,7 +767,7 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A UtilityExceptions.defaultException(this, ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @Override @@ -782,13 +782,20 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A @Override public void onItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canPartitaMagBeChanged, boolean canOverflowQuantity, String customArtDescription, RunnableArgss onComplete) { - DialogInputQuantityV2DTO dialogInputQuantityV2DTO = new DialogInputQuantityV2DTO().setMtbAart(mtbAart).setInitialNumCnf(initialNumCnf).setInitialQtaCnf(initialQtaCnf).setInitialQtaTot(initialQtaTot).setTotalQtaOrd(totalQtaOrd).setTotalNumCnfOrd(totalNumCnfOrd).setQtaCnfOrd(qtaCnfOrd).setTotalQtaToBeTaken(totalQtaToBeTaken).setTotalNumCnfToBeTaken(totalNumCnfToBeTaken).setQtaCnfToBeTaken(qtaCnfToBeTaken).setTotalQtaAvailable(totalQtaAvailable).setTotalNumCnfAvailable(totalNumCnfAvailable).setQtaCnfAvailable(qtaCnfAvailable).setPartitaMag(partitaMag).setDataScad(dataScad).setCanPartitaMagBeChanged(canPartitaMagBeChanged).setCanLUBeClosed(true).setCanOverflowOrderQuantity(canOverflowQuantity).setCustomArtDescription(customArtDescription); + DialogInputQuantityV2DTO dialogInputQuantityV2DTO = new DialogInputQuantityV2DTO().setMtbAart(mtbAart).setInitialNumCnf(initialNumCnf).setInitialQtaCnf(initialQtaCnf).setInitialQtaTot(initialQtaTot).setTotalQtaOrd(totalQtaOrd).setTotalNumCnfOrd(totalNumCnfOrd).setTotalQtaCnfOrd(qtaCnfOrd).setTotalQtaToBeTaken(totalQtaToBeTaken).setTotalNumCnfToBeTaken(totalNumCnfToBeTaken).setQtaCnfToBeTaken(qtaCnfToBeTaken).setTotalQtaAvailable(totalQtaAvailable).setTotalNumCnfAvailable(totalNumCnfAvailable).setQtaCnfAvailable(qtaCnfAvailable).setPartitaMag(partitaMag).setDataScad(dataScad).setCanPartitaMagBeChanged(canPartitaMagBeChanged).setCanLUBeClosed(true).setCanOverflowOrderQuantity(canOverflowQuantity).setCustomArtDescription(customArtDescription); if (!mDialogInputQuantityV2View.isVisible()) - mDialogInputQuantityV2View.setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO).setOnComplete((resultDTO, shouldCloseLU) -> { - PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO().setNumCnf(resultDTO.getNumCnf()).setQtaCnf(resultDTO.getQtaCnf()).setQtaTot(resultDTO.getQtaTot()).setPartitaMag(resultDTO.getPartitaMag()).setDataScad(resultDTO.getDataScad()); - onComplete.run(pickedQuantityDTO, shouldCloseLU); - }).setOnAbort(() -> this.mViewModel.resetMatchedRows()).show(getSupportFragmentManager(), "tag"); + mDialogInputQuantityV2View + .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO).setOnComplete(resultDTO -> { + if (resultDTO == null) { + this.mViewModel.resetMatchedRows(); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO().setNumCnf(resultDTO.getNumCnf()).setQtaCnf(resultDTO.getQtaCnf()).setQtaTot(resultDTO.getQtaTot()).setPartitaMag(resultDTO.getPartitaMag()).setDataScad(resultDTO.getDataScad()); + onComplete.run(pickedQuantityDTO, pickedQuantityDTO.isShouldCloseLu()); + }) + .setOnAbort(() -> this.mViewModel.resetMatchedRows()) + .show(getSupportFragmentManager(), "tag"); } @Override diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/contab_doc_interni/edit_form/DocInterniEditFormActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/contab_doc_interni/edit_form/DocInterniEditFormActivity.java index 818c5109..50dc8c4e 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/contab_doc_interni/edit_form/DocInterniEditFormActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/contab_doc_interni/edit_form/DocInterniEditFormActivity.java @@ -70,7 +70,7 @@ public class DocInterniEditFormActivity extends BaseActivity implements DocInter DialogInputQuantityV2View dialogInputQuantityV2View; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private ActivityContabDocInterniEditBinding binding; public BindableString documentHeader = new BindableString(true); public BindableString documentRifHeader = new BindableString(true); @@ -238,12 +238,12 @@ public class DocInterniEditFormActivity extends BaseActivity implements DocInter } public void manualSearch() { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); DialogSimpleInputHelper.makeInputDialog(this, "Ricerca articolo", null, "Cod articolo / Barcode", - barcodeProd -> this.viewModel.loadArticoloByCodMartOrBarcode(barcodeProd), BarcodeManager::enable).show(); + barcodeProd -> this.viewModel.loadArticoloByCodMartOrBarcode(barcodeProd), () -> BarcodeManager.enable(mBarcodeScannerInstanceID)).show(); } @@ -263,7 +263,7 @@ public class DocInterniEditFormActivity extends BaseActivity implements DocInter return; } - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(this.viewModel::processBarcode) .setOnScanFailed(this::onError)); this.viewModel.fetchDocumentRows(); @@ -271,7 +271,7 @@ public class DocInterniEditFormActivity extends BaseActivity implements DocInter @Override protected void onDestroy() { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onDestroy(); } @@ -356,7 +356,9 @@ public class DocInterniEditFormActivity extends BaseActivity implements DocInter if (!dialogInputQuantityV2View.isAdded()) dialogInputQuantityV2View.setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if(resultDTO == null || resultDTO.isAborted()) return; + this.onLoadingStarted(); this.viewModel.saveRow(row, resultDTO); }) @@ -385,7 +387,7 @@ public class DocInterniEditFormActivity extends BaseActivity implements DocInter @Override public void onBackPressed() { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/inventario/ElencoInventariFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/inventario/ElencoInventariFragment.java index e734ffb4..b2e41b52 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/inventario/ElencoInventariFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/inventario/ElencoInventariFragment.java @@ -43,7 +43,7 @@ public class ElencoInventariFragment extends BaseFragment implements ITitledFrag public ObservableField canCreateInventario = new ObservableField<>(false); - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; public ElencoInventariFragment() { // Required empty public constructor diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/inventario/picking/PickingInventarioActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/inventario/picking/PickingInventarioActivity.java index 43a6895f..a1133ef3 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/inventario/picking/PickingInventarioActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/inventario/picking/PickingInventarioActivity.java @@ -61,7 +61,7 @@ public class PickingInventarioActivity extends BaseActivity implements PickingIn private static final String KEY_INVENTARIO = "key_inventario"; private static final String KEY_INVENTARIO_ARTS = "key_inventario_arts"; - private int barcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; //Pass here all external parameters public static void startActivity(Context context, InventarioEntity inventarioEntity, List inventarioArts) { @@ -125,7 +125,7 @@ public class PickingInventarioActivity extends BaseActivity implements PickingIn @Override public void onBackPressed() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } @@ -177,7 +177,7 @@ public class PickingInventarioActivity extends BaseActivity implements PickingIn } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(this, ex, false))); } @@ -209,14 +209,14 @@ public class PickingInventarioActivity extends BaseActivity implements PickingIn } public void manualSearch() { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); DialogSimpleInputHelper.makeInputDialog(this, "Ricerca articolo", null, "Cod articolo / Barcode", barcodeProd -> - this.mViewModel.loadArticoloByCodMartOrBarcode(barcodeProd, BarcodeManager::enable), - BarcodeManager::enable) + this.mViewModel.loadArticoloByCodMartOrBarcode(barcodeProd, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)), + () -> BarcodeManager.enable(mBarcodeScannerInstanceID)) .show(); } @@ -241,7 +241,9 @@ public class PickingInventarioActivity extends BaseActivity implements PickingIn if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View.setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if(resultDTO == null || resultDTO.isAborted()) return; + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) @@ -249,7 +251,7 @@ public class PickingInventarioActivity extends BaseActivity implements PickingIn .setPartitaMag(resultDTO.getPartitaMag()) .setDataScad(resultDTO.getDataScad()); - onComplete.run(pickedQuantityDTO, shouldCloseLU); + onComplete.run(pickedQuantityDTO, pickedQuantityDTO.isShouldCloseLu()); }) .show(getSupportFragmentManager(), "tag"); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/main/MainActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/main/MainActivity.java index 4d1b416c..0d522fb4 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/main/MainActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/main/MainActivity.java @@ -77,6 +77,9 @@ public class MainActivity extends BaseActivity @Inject DialogProgressView mDialogProgressView; + @Inject + ServerStatusChecker serverStatusChecker; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -194,7 +197,7 @@ public class MainActivity extends BaseActivity fragment = new MainSettingsFragment(); this.adaptViewToFragment(fragment); } else if (id == R.id.nav_logout) { - ServerStatusChecker.dispose(); + serverStatusChecker.dispose(); this.mainContext.logout(() -> { startLoginActivity(); }); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/main/MainFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/main/MainFragment.java index 1873e18b..e31fdc8f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/main/MainFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/main/MainFragment.java @@ -6,6 +6,7 @@ import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Color; import android.os.Bundle; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -20,8 +21,8 @@ import androidx.recyclerview.widget.GridLayoutManager; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Inject; @@ -31,8 +32,6 @@ import it.integry.integrywmsnative.core.class_router.configs.BaseMenuConfigurati import it.integry.integrywmsnative.core.class_router.configs.MenuConfiguration; import it.integry.integrywmsnative.core.data_recover.ColliDataRecoverDTO; import it.integry.integrywmsnative.core.data_recover.ColliDataRecoverService; -import it.integry.integrywmsnative.core.expansion.RunnableArgs; -import it.integry.integrywmsnative.core.expansion.RunnableArgss; import it.integry.integrywmsnative.core.interfaces.IScrollableFragment; import it.integry.integrywmsnative.core.interfaces.ITitledFragment; import it.integry.integrywmsnative.core.menu.MenuService; @@ -43,7 +42,6 @@ import it.integry.integrywmsnative.core.rest.consumers.ColliMagazzinoRESTConsume import it.integry.integrywmsnative.core.rest.consumers.ColliSpedizioneRESTConsumer; import it.integry.integrywmsnative.core.rest.model.AvailableCodMdepsDTO; import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSRequestDTO; -import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSResponseDTO; import it.integry.integrywmsnative.core.rest.watcher.ServerStatusChecker; import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.utility.UtilityDimension; @@ -70,6 +68,11 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab @Inject ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer; + @Inject + ExecutorService executorService; + + @Inject + Handler handler; @Inject MenuService menuService; @@ -77,6 +80,9 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab @Inject ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer; + @Inject + ServerStatusChecker serverStatusChecker; + private FragmentMainBinding mBindings; private final List mOnPreDestroyList = new ArrayList<>(); @@ -141,7 +147,7 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab private void init() { - ServerStatusChecker.getInstance().addCallback(value -> { + serverStatusChecker.addCallback(value -> { if (value && mBindings.noConnectionTopLayout.isExpanded()) { collapseNoConnectionLayout(); } else if (!value && !mBindings.noConnectionTopLayout.isExpanded()) { @@ -170,46 +176,31 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab private void initRecuperoCollo() { if (colliDataRecoverService.thereIsAnExistantSession()) { + startRecoverMode(); - List generatedErrors = new ArrayList<>(); + executorService.execute(() -> { - Iterator sessionsIterator = colliDataRecoverService.getAllSessionIDs().iterator(); - - cyclicRecover(sessionsIterator, () -> { + List generatedErrors = new ArrayList<>(); + for (var sessionIds : colliDataRecoverService.getAllSessionIDs()) { + try { + recoverUL(sessionIds); + } catch (Exception ex) { + generatedErrors.add(ex); + } + } for (Exception ex : generatedErrors) { UtilityExceptions.defaultException(getActivity(), ex); } endRecoverMode(); - }, generatedErrors::add); + }); } } - private void cyclicRecover(Iterator sessionsIterator, Runnable onComplete, RunnableArgs onFailed) { - - RunnableArgss tmpOnFailed = (ex, recoveredMtbColtID) -> { - if (ex.getMessage().contains("Dati entity mtb_colt non trovati") || - ex.getMessage().contains("Dati collo non corretti") || - (ex.getMessage().contains("Il collo numero") && ex.getMessage().contains("non esiste")) || - ex.getMessage().contains("Impossibile eliminare un collo agganciato a documento")) { - colliDataRecoverService.closeSession(recoveredMtbColtID); - onFailed.run(ex); - } else { - onFailed.run(ex); - } - - cyclicRecover(sessionsIterator, onComplete, onFailed); - }; - - if (!sessionsIterator.hasNext()) { - onComplete.run(); - return; - } - - Integer recoveredMtbColtID = sessionsIterator.next(); + private void recoverUL(Integer recoveredMtbColtID) throws Exception { ColliDataRecoverDTO recoveredMtbColtDto = colliDataRecoverService.getSession(recoveredMtbColtID); MtbColt recoveredMtbColt = recoveredMtbColtDto.getMtbColt(); @@ -218,8 +209,8 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab recoveredMtbColt.getGestioneEnum() == GestioneEnum.LAVORAZIONE)) { String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); - if(recoveredMtbColtDto.getTestateOrdini() != null && - !recoveredMtbColtDto.getTestateOrdini().isEmpty()){ + if (recoveredMtbColtDto.getTestateOrdini() != null && + !recoveredMtbColtDto.getTestateOrdini().isEmpty()) { codMdep = recoveredMtbColtDto.getTestateOrdini().get(0).getCodMdep(); } @@ -228,26 +219,29 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab //.setPrintSSCC(shouldPrint) .setOrderCodMdep(codMdep); - RunnableArgs onRequestComplete = closeUDSResponseDto -> { - colliDataRecoverService.closeSession(recoveredMtbColtID); - cyclicRecover(sessionsIterator, onComplete, onFailed); - }; + try { + switch (recoveredMtbColt.getGestioneEnum()) { + case LAVORAZIONE: + colliLavorazioneRESTConsumer.closeUDSSynchronized(closeUDSRequestDto); + break; + case VENDITA: + colliSpedizioneRESTConsumer.closeUDSSynchronized(closeUDSRequestDto); + break; + } - switch (recoveredMtbColt.getGestioneEnum()) { - case LAVORAZIONE: - colliLavorazioneRESTConsumer.closeUDS(closeUDSRequestDto, onRequestComplete, ex -> { - tmpOnFailed.run(ex, recoveredMtbColtID); - }); - break; - case VENDITA: - colliSpedizioneRESTConsumer.closeUDS(closeUDSRequestDto, onRequestComplete, ex -> { - tmpOnFailed.run(ex, recoveredMtbColtID); - }); - break; + colliDataRecoverService.closeSession(recoveredMtbColtID); + } catch (Exception ex) { + if (ex.getMessage().contains("Dati entity mtb_colt non trovati") || + ex.getMessage().contains("Dati collo non corretti") || + (ex.getMessage().contains("Il collo numero") && ex.getMessage().contains("non esiste")) || + ex.getMessage().contains("Impossibile eliminare un collo agganciato a documento")) { + colliDataRecoverService.closeSession(recoveredMtbColtID); + } + + throw ex; } } else { colliDataRecoverService.closeSession(recoveredMtbColtID); - cyclicRecover(sessionsIterator, onComplete, onFailed); } } @@ -267,7 +261,9 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab } private void endRecoverMode() { - mBindings.recoverDataExpandableLayout.collapse(true); + handler.post(() -> { + mBindings.recoverDataExpandableLayout.collapse(true); + }); } @Override diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java index f60e7674..3c9c88d4 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java @@ -2,7 +2,9 @@ package it.integry.integrywmsnative.gest.ordini_uscita_elenco; import android.content.Context; import android.os.Bundle; +import android.os.Handler; import android.text.Html; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -68,12 +70,12 @@ import it.integry.integrywmsnative.gest.ordini_uscita_elenco.filters.FilterViagg import it.integry.integrywmsnative.gest.ordini_uscita_elenco.filters.OrdiniUscitaElencoFiltroViewModel; import it.integry.integrywmsnative.gest.ordini_uscita_elenco.ui.OrdiniUscitaElencoAdapter; import it.integry.integrywmsnative.gest.ordini_uscita_elenco.ui.OrdiniUscitaElencoListModel; -import it.integry.integrywmsnative.ui.filter_chips.filters.FilterCommessaLayoutView; import it.integry.integrywmsnative.gest.spedizione.SpedizioneActivity; import it.integry.integrywmsnative.gest.spedizione.dialogs.row_info.BaseDialogRowInfoView; import it.integry.integrywmsnative.ui.ElevatedToolbar; import it.integry.integrywmsnative.ui.filter_chips.FilterChipDTO; import it.integry.integrywmsnative.ui.filter_chips.FilterChipView; +import it.integry.integrywmsnative.ui.filter_chips.filters.FilterCommessaLayoutView; import it.integry.integrywmsnative.ui.filter_chips.filters.FilterNumeroOrdineLayoutView; import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView; @@ -93,6 +95,9 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF @Inject OrdiniUscitaElencoViewModel mViewModel; + @Inject + Handler handler; + private final OrdiniUscitaElencoFiltroViewModel mAppliedFilterViewModel = new OrdiniUscitaElencoFiltroViewModel(); private FragmentMainOrdiniUscitaBinding mBindings = null; @@ -107,7 +112,7 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF private ElevatedToolbar mToolbar; private final List mOnPreDestroyList = new ArrayList<>(); - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private List mtbDepoCache; private List mtbGrupCache; @@ -164,29 +169,58 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF mBindings.setView(this); mBindings.setViewmodel(mViewModel); - this.initRecyclerView(); + Log.d("onCreateView", "Started"); + this.initBarcodeReader(); - this.initFilters(); - + Log.d("onCreateView", "Ended"); return mBindings.getRoot(); } @Override public void onStart() { super.onStart(); - this.onLoadingStarted(); - this.initMtbDepoCache(() -> { - String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); - mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol); + Log.d("onStart", "Started"); + this.mViewModel.getOrderList().observe(getViewLifecycleOwner(), data -> { + executorService.execute(() -> { + try { + this.onLoadingStarted(); + + this.initMtbDepoCache(); + this.initMtbGrupsCache(); + this.initJtbComtCache(); + + handler.post(() -> { + mAppliedFilterViewModel.init(data); + this.refreshList(data, null); + }); + + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } + }); + }); + + this.onLoadingStarted(); + + this.initRecyclerView(); + this.initFilters(); + + String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); + mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol, () -> { + this.onLoadingEnded(); + }); + + Log.d("onStart", "Ended"); } @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); for (Runnable onPreDestroy : mOnPreDestroyList) { onPreDestroy.run(); @@ -201,16 +235,6 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF boolean canSelectMultipleOrdini = SettingsManager.iDB().isFlagSpedizioneCanSelectMultipleOrders(); boolean canSelectMultipleClienti = SettingsManager.iDB().isFlagMultiClienteOrdV(); - this.mViewModel.getOrderList().observe(getViewLifecycleOwner(), v -> { - this.onLoadingStarted(); - this.initMtbGrupsCache(() -> { - this.initJtbComtCache(this::onLoadingEnded); - }); - - mAppliedFilterViewModel.init(mViewModel.getOrderList().getValue()); - - this.refreshList(null); - }); OrdiniUscitaElencoAdapter ordiniUscitaElencoAdapter = new OrdiniUscitaElencoAdapter(getActivity(), mOrdiniInevasiMutableData) @@ -243,26 +267,28 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF ordiniUscitaElencoAdapter .setEmptyView(this.mBindings.ordiniVenditaEmptyView); - this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter); this.mBindings.venditaMainList.setLayoutManager(new LinearLayoutManager(getActivity())); + this.mBindings.venditaMainList.setItemViewCacheSize(20); + this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter); + // if (mToolbar != null) // mToolbar.setRecyclerView(this.mBindings.venditaMainList); } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private void initFilters() { var onPredicateChanged = new OnGeneralChangedCallback() { @Override public void run() { - refreshList(null); + refreshList(mViewModel.getOrderList().getValue(), null); } }; @@ -714,27 +740,25 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF this.mViewModel.processBarcodeDTO(data, this::onLoadingEnded); }; - private void refreshList(List filteredList) { - requireActivity().runOnUiThread(() -> { - List tmpList; + private void refreshList(List originalData, List filteredList) { + List tmpList; - if (filteredList != null) { - tmpList = filteredList; - } else if (mAppliedFilterViewModel != null) { - mAppliedFilterViewModel.applyAllTests(); - tmpList = mAppliedFilterViewModel.getMutableFilteredOrderList().getValue(); - } else { - tmpList = mViewModel.getOrderList().getValue(); - } + if (filteredList != null) { + tmpList = filteredList; + } else if (mAppliedFilterViewModel != null) { + mAppliedFilterViewModel.applyAllTests(); + tmpList = mAppliedFilterViewModel.getMutableFilteredOrderList().getValue(); + } else { + tmpList = originalData; + } - var list = convertDataModelToListModel(tmpList); + var list = convertDataModelToListModel(tmpList); - this.mOrdiniInevasiMutableData.clear(); - this.mOrdiniInevasiMutableData.addAll(list); + this.mOrdiniInevasiMutableData.clear(); + this.mOrdiniInevasiMutableData.addAll(list); - fabVisible.set(mOrdiniInevasiMutableData.stream() - .anyMatch(y -> y.getSelectedObservable().get())); - }); + fabVisible.set(mOrdiniInevasiMutableData.stream() + .anyMatch(y -> y.getSelectedObservable().get())); } private List convertDataModelToListModel(List dataList) { @@ -744,7 +768,7 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF .thenComparing(ComparatorCompat.comparing(x -> x.getDestinatario() != null ? x.getDestinatario() : "zzzzzzzzz")) .thenComparing(ComparatorCompat.comparing(OrdiniUscitaElencoDTO::getNumOrd)); - List notHiddenElements = Stream.of(dataList) + List notHiddenElements = dataList.stream() .filter(x -> !x.isHidden()) .sorted(comparator) .map(x -> { @@ -774,7 +798,7 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF return listModel; }) - .toList(); + .collect(Collectors.toList()); return notHiddenElements; } @@ -803,18 +827,18 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF @Override public void onFilterNumOrderApplied(List filteredOrder) { - requireActivity().runOnUiThread(() -> { - var numOrders = Stream.of(filteredOrder) + handler.post(() -> { + var numOrders = filteredOrder.parallelStream() .map(OrdineInevasoDTO::getNumOrd) .distinct() - .toList(); + .collect(Collectors.toList()); this.mAppliedFilterViewModel.setNumOrdFilter(numOrders); }); } @Override public void onOrderFiltered(List filteredOrders) { - refreshList(filteredOrders); + refreshList(mViewModel.getOrderList().getValue(), filteredOrders); } @Override @@ -874,38 +898,34 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF } - private void initMtbDepoCache(Runnable onComplete) { - this.mDepositoRESTConsumer.getAll(mtbDepos -> { - this.mtbDepoCache = mtbDepos; - onComplete.run(); - }, this::onError); + private void initMtbDepoCache() throws Exception { + var mtbDepos = this.mDepositoRESTConsumer.getAllSynchronized(); + this.mtbDepoCache = mtbDepos; } - private void initMtbGrupsCache(Runnable onComplete) { - var codMgrpArts = Stream.of(Objects.requireNonNull(this.mViewModel.getOrderList().getValue())) - .flatMap(x -> Stream.of(x.getAvailableClassMerc() != null ? x.getAvailableClassMerc() : new ArrayList<>())) + private void initMtbGrupsCache() throws Exception { + var codMgrpArts = Objects.requireNonNull(this.mViewModel.getOrderList().getValue()).parallelStream() + .filter(x -> x.getAvailableClassMerc() != null && !x.getAvailableClassMerc().isEmpty()) + .flatMap(x -> x.getAvailableClassMerc().stream()) .map(OrdineUscitaInevasoDTO.AvailableClassMerc::getCodMgrp) - .withoutNulls() + .filter(Objects::nonNull) .distinct() - .toList(); + .collect(Collectors.toList()); - this.mArticoloRESTConsumer.getArtsGroups(codMgrpArts, mtbGrupCache -> { - this.mtbGrupCache = mtbGrupCache; - onComplete.run(); - }, this::onError); + var mtbGrupCache = this.mArticoloRESTConsumer.getArtsGroupsSynchronized(codMgrpArts); + this.mtbGrupCache = mtbGrupCache; } - private void initJtbComtCache(Runnable onComplete) { + private void initJtbComtCache() throws Exception { if (this.mViewModel.getOrderList().getValue() == null) { this.jtbComtCache = new ArrayList<>(); - onComplete.run(); return; } List jtbComts = null; - if(this.mViewModel.getOrderList().getValue() != null) { + if (this.mViewModel.getOrderList().getValue() != null) { jtbComts = this.mViewModel.getOrderList().getValue().stream() .map(OrdineUscitaInevasoDTO::getCodJcom) .distinct() @@ -915,13 +935,10 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF if (jtbComts == null || jtbComts.isEmpty()) { this.jtbComtCache = new ArrayList<>(); - onComplete.run(); return; } - this.mCommessaRESTConsumer.getJtbComts(jtbComts, jtbComtCache -> { - this.jtbComtCache = jtbComtCache; - onComplete.run(); - }, this::onError); + var jtbComtCache = this.mCommessaRESTConsumer.getJtbComtsSynchronized(jtbComts); + this.jtbComtCache = jtbComtCache; } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoModule.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoModule.java index 4449fdd9..1bcd6218 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoModule.java @@ -1,5 +1,9 @@ package it.integry.integrywmsnative.gest.ordini_uscita_elenco; +import android.os.Handler; + +import java.util.concurrent.ExecutorService; + import javax.inject.Singleton; import dagger.Module; @@ -20,8 +24,8 @@ public class OrdiniUscitaElencoModule { } @Provides - OrdiniUscitaElencoViewModel providesProdOrdineLavorazioneElencoViewModel(OrdiniRESTConsumer ordiniRESTConsumer, ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, OrdiniUscitaElencoRESTConsumer ordiniUscitaElencoRESTConsumer) { - return new OrdiniUscitaElencoViewModel(ordiniRESTConsumer, colliMagazzinoRESTConsumer, barcodeRESTConsumer, ordiniUscitaElencoRESTConsumer); + OrdiniUscitaElencoViewModel providesProdOrdineLavorazioneElencoViewModel(Handler handler, ExecutorService executorService, OrdiniRESTConsumer ordiniRESTConsumer, ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, OrdiniUscitaElencoRESTConsumer ordiniUscitaElencoRESTConsumer) { + return new OrdiniUscitaElencoViewModel(handler, executorService, ordiniRESTConsumer, colliMagazzinoRESTConsumer, barcodeRESTConsumer, ordiniUscitaElencoRESTConsumer); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoViewModel.java index b9a491b9..8eb8f4ac 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoViewModel.java @@ -8,6 +8,9 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.stream.Collectors; import javax.inject.Inject; @@ -37,6 +40,8 @@ public class OrdiniUscitaElencoViewModel { private final MutableLiveData> mOrderList = new MutableLiveData<>(); + private final android.os.Handler mHandler; + private final ExecutorService executorService; private final OrdiniRESTConsumer mOrdiniRESTConsumer; private final ColliMagazzinoRESTConsumer mColliMagazzinoRESTConsumer; private final BarcodeRESTConsumer mBarcodeRESTConsumer; @@ -49,7 +54,14 @@ public class OrdiniUscitaElencoViewModel { private int mCurrentSegnoCol; @Inject - public OrdiniUscitaElencoViewModel(OrdiniRESTConsumer ordiniRESTConsumer, ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, OrdiniUscitaElencoRESTConsumer ordiniUscitaElencoRESTConsumer) { + public OrdiniUscitaElencoViewModel(android.os.Handler handler, + ExecutorService executorService, + OrdiniRESTConsumer ordiniRESTConsumer, + ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, + BarcodeRESTConsumer barcodeRESTConsumer, + OrdiniUscitaElencoRESTConsumer ordiniUscitaElencoRESTConsumer) { + this.mHandler = handler; + this.executorService = executorService; this.mOrdiniRESTConsumer = ordiniRESTConsumer; this.mColliMagazzinoRESTConsumer = colliMagazzinoRESTConsumer; this.mBarcodeRESTConsumer = barcodeRESTConsumer; @@ -57,39 +69,36 @@ public class OrdiniUscitaElencoViewModel { } - public void init(String currentCodMdep, GestioneEnum gestioneOrd, GestioneEnum gestioneCol, int segnoCol) { + public void init(String currentCodMdep, GestioneEnum gestioneOrd, GestioneEnum gestioneCol, int segnoCol, Runnable onComplete) { this.mCurrentCodMdep = currentCodMdep; this.mCurrentGestioneOrd = gestioneOrd; this.mCurrentGestioneCol = gestioneCol; this.mCurrentSegnoCol = segnoCol; - this.sendOnLoadingStarted(); - Date loadingStartDate = new Date(); + executorService.execute(() -> { - this.mOrdiniRESTConsumer.getOrdiniInevasi(this.mCurrentCodMdep, mCurrentGestioneOrd, - ordiniLavorazione -> { - this.mOrderList.postValue(Stream.of(ordiniLavorazione) - .map(x -> { - try { - return OrdiniUscitaElencoDTO.fromParent(x); - } catch (Exception ex) { - return null; - } - }) - .toList()); + List ordiniLavorazione = null; + try { + ordiniLavorazione = this.mOrdiniRESTConsumer.getOrdiniInevasiSynchronized(this.mCurrentCodMdep, mCurrentGestioneOrd); - long forcedDelaySecs = (new Date().getTime() - loadingStartDate.getTime()) / 1000; + var orderList = ordiniLavorazione.parallelStream() + .map(x -> { + try { + return OrdiniUscitaElencoDTO.fromParent(x); + } catch (Exception ex) { + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); - if (2 - forcedDelaySecs > 0) { - try { - Thread.sleep((2 - forcedDelaySecs) * 1000); - } catch (Exception ignored) { - } - } - - this.sendOnLoadingEnded(); - }, this::sendError); + this.mOrderList.postValue(orderList); + onComplete.run(); + } catch (Exception e) { + this.sendError(e); + } + }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/FilterClienteLayoutView.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/FilterClienteLayoutView.java index dfe6df91..023fbddc 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/FilterClienteLayoutView.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/FilterClienteLayoutView.java @@ -11,13 +11,13 @@ import androidx.databinding.DataBindingUtil; import androidx.lifecycle.MutableLiveData; import com.annimon.stream.ComparatorCompat; -import com.annimon.stream.Stream; import com.ravikoradiya.liveadapter.LiveAdapter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.stream.Collectors; import it.integry.integrywmsnative.BR; import it.integry.integrywmsnative.R; @@ -48,9 +48,9 @@ public class FilterClienteLayoutView extends FilterLayoutView { refreshList(); this.setSearchView(this.mBindings.searchView, newFilter -> { - hiddenClienti = Stream.of(allClienti) + hiddenClienti = allClienti.parallelStream() .filter(x -> !x.toUpperCase(Locale.ROOT).contains(newFilter.toUpperCase(Locale.ROOT))) - .toList(); + .collect(Collectors.toList()); refreshList(); }); @@ -70,7 +70,7 @@ public class FilterClienteLayoutView extends FilterLayoutView { .thenComparing(new ComparatorCompat<>((x, y) -> y.getOriginalModel().compareTo(x.getOriginalModel()))) .reversed(); - listModel.setValue(Stream.of(getAllClienti()) + listModel.setValue(getAllClienti().parallelStream() .filter(x -> !hiddenClienti.contains(x)) .map(x -> { var selectedBoolean = new BindableBoolean(preSelectedClienti.contains(x)); @@ -85,17 +85,17 @@ public class FilterClienteLayoutView extends FilterLayoutView { .setOriginalModel(x); }) .sorted(c) - .toList()); + .collect(Collectors.toList())); } public void onConfirm() { if (onFilterApplied == null) return; - this.onFilterApplied.run(Stream.of(Objects.requireNonNull(listModel.getValue())) + this.onFilterApplied.run(Objects.requireNonNull(listModel.getValue()).parallelStream() .filter(x -> x.selected.get()) .map(x -> x.originalModel) - .toList()); + .collect(Collectors.toList())); dismiss(); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/OrdiniUscitaElencoFiltroViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/OrdiniUscitaElencoFiltroViewModel.java index 5589489b..9450607c 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/OrdiniUscitaElencoFiltroViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/OrdiniUscitaElencoFiltroViewModel.java @@ -9,9 +9,11 @@ import com.annimon.stream.function.Predicate; import org.apache.commons.lang3.time.DateUtils; import java.util.ArrayList; +import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Objects; +import java.util.stream.Collectors; import it.integry.integrywmsnative.core.model.JtbComt; import it.integry.integrywmsnative.core.model.MtbDepo; @@ -349,13 +351,12 @@ public class OrdiniUscitaElencoFiltroViewModel { public List getAllNumOrds() { - return Stream - .of(Objects.requireNonNull(initialOrderList)) + return Objects.requireNonNull(initialOrderList).parallelStream() .filter(x -> x.getNumOrd() != null) - .sortBy(x -> -x.getNumOrd()) + .sorted(Comparator.comparing(OrdineInevasoDTO::getNumOrd)) .map(x -> x.getNumOrd() != null ? x.getNumOrd() : null) .distinct() - .toList(); + .collect(Collectors.toList()); } public List getAvailableNumOrds() { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoAdapter.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoAdapter.java index 9ad20f1d..d58f3dbc 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoAdapter.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoAdapter.java @@ -8,24 +8,59 @@ import android.view.View; import android.view.ViewGroup; import androidx.core.content.res.ResourcesCompat; -import androidx.databinding.DataBindingUtil; import androidx.databinding.ObservableArrayList; +import androidx.databinding.ObservableList; import androidx.recyclerview.widget.RecyclerView; -import it.integry.integrywmsnative.R; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import it.integry.integrywmsnative.core.expansion.OnListGeneralChangedCallback; import it.integry.integrywmsnative.core.expansion.OnSingleClickListener; import it.integry.integrywmsnative.core.expansion.RunnableArgs; -import it.integry.integrywmsnative.core.expansion.view.ExtendedSectionedRecyclerView; +import it.integry.integrywmsnative.core.expansion.view.ExtendedSectionedRecyclerViewNew; import it.integry.integrywmsnative.core.utility.UtilityString; import it.integry.integrywmsnative.databinding.FragmentMainOrdiniUscitaListGroupModelBinding; import it.integry.integrywmsnative.databinding.FragmentMainOrdiniUscitaListModelBinding; -public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerView { +public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerViewNew { private final Context mContext; +// private final AsyncLayoutInflater asyncLayoutInflater; + private final LayoutInflater layoutInflater; + private RunnableArgs mOnGroupItemClicked; private RunnableArgs mOnItemChecked; + private final int transparentColor; + + public OrdiniUscitaElencoAdapter(Context context, ObservableArrayList mutableDataSet) { + super(mutableDataSet); + mContext = context; + layoutInflater = LayoutInflater.from(mContext); + transparentColor = ResourcesCompat.getColor(mContext.getResources(), android.R.color.transparent, null); +// asyncLayoutInflater = new AsyncLayoutInflater(mContext); + + mutableDataSet.addOnListChangedCallback(new OnListGeneralChangedCallback() { + @Override + public void onChanged(ObservableList sender) { + + Map> collect = sender.stream() + .collect(Collectors.groupingBy(OrdiniUscitaElencoListModel::getGroupTitle)); + + String[] keyArray = new String[collect.keySet().size()]; + collect.keySet().toArray(keyArray); + + var keyList = Arrays.asList(keyArray); + keyList.sort(String::compareTo); + setSections(keyList, collect); + } + }); + } + + static class SubheaderHolder extends RecyclerView.ViewHolder { FragmentMainOrdiniUscitaListModelBinding mBinding; @@ -47,11 +82,6 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerView mutableDataSet) { - super(mutableDataSet); - mContext = context; - } - public OrdiniUscitaElencoAdapter setOnGroupItemClicked(RunnableArgs onGroupItemClicked) { this.mOnGroupItemClicked = onGroupItemClicked; return this; @@ -64,59 +94,61 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerView { - if(this.mOnItemChecked != null) this.mOnItemChecked.run(listModel); + if (this.mOnItemChecked != null) this.mOnItemChecked.run(listModel); }); holder.mBinding.getRoot().setOnClickListener(v -> { listModel.getSelectedObservable().set(!listModel.getSelectedObservable().get()); }); } - - @Override - public boolean onPlaceSubheaderBetweenItems(int position) { - - if (getItemSize() == 1) return true; - else if (getItemSize() > 1) { - OrdiniUscitaElencoListModel compare1 = this.mDataset.get(position); - OrdiniUscitaElencoListModel compare2 = this.mDataset.get(position + 1); - - return !UtilityString.equalsIgnoreCase(compare1.getGroupTitle(), compare2.getGroupTitle()); - } - - return true; - } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoListModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoListModel.java index df2d942d..9e49a0fb 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoListModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/ui/OrdiniUscitaElencoListModel.java @@ -1,5 +1,8 @@ package it.integry.integrywmsnative.gest.ordini_uscita_elenco.ui; +import android.text.Html; +import android.text.Spanned; + import androidx.annotation.ColorInt; import it.integry.integrywmsnative.core.di.BindableBoolean; @@ -13,6 +16,11 @@ public class OrdiniUscitaElencoListModel implements Cloneable { private String rightDescription; private String rightSubDescription; + private Spanned descriptionSpanned; + private Spanned subDescriptionSpanned; + private Spanned rightDescriptionSpanned; + private Spanned rightSubDescriptionSpanned; + private @ColorInt Integer etichettaColor; private boolean hidden; @@ -37,6 +45,7 @@ public class OrdiniUscitaElencoListModel implements Cloneable { public OrdiniUscitaElencoListModel setDescription(String description) { this.description = description; + this.descriptionSpanned = description != null ? Html.fromHtml(description) : null; return this; } @@ -46,6 +55,7 @@ public class OrdiniUscitaElencoListModel implements Cloneable { public OrdiniUscitaElencoListModel setSubDescription(String subDescription) { this.subDescription = subDescription; + this.subDescriptionSpanned = subDescription != null ? Html.fromHtml(subDescription) : null; return this; } @@ -55,6 +65,7 @@ public class OrdiniUscitaElencoListModel implements Cloneable { public OrdiniUscitaElencoListModel setRightDescription(String rightDescription) { this.rightDescription = rightDescription; + this.rightDescriptionSpanned = rightDescription != null ? Html.fromHtml(rightDescription) : null; return this; } @@ -64,6 +75,7 @@ public class OrdiniUscitaElencoListModel implements Cloneable { public OrdiniUscitaElencoListModel setRightSubDescription(String rightSubDescription) { this.rightSubDescription = rightSubDescription; + this.rightSubDescriptionSpanned = rightSubDescription != null ? Html.fromHtml(rightSubDescription) : null; return this; } @@ -97,4 +109,20 @@ public class OrdiniUscitaElencoListModel implements Cloneable { this.originalModel = originalModel; return this; } + + public Spanned getDescriptionSpanned() { + return descriptionSpanned; + } + + public Spanned getSubDescriptionSpanned() { + return subDescriptionSpanned; + } + + public Spanned getRightDescriptionSpanned() { + return rightDescriptionSpanned; + } + + public Spanned getRightSubDescriptionSpanned() { + return rightSubDescriptionSpanned; + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoFragment.java index 2ac77b46..4a6859b5 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoFragment.java @@ -3,6 +3,7 @@ package it.integry.integrywmsnative.gest.picking_libero; import android.content.Context; import android.os.Bundle; +import android.os.Handler; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; @@ -76,6 +77,9 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme @Inject DialogInputQuantityV2View mDialogInputQuantityV2View; + @Inject + Handler handler; + public BindableBoolean thereIsAnOpenedUL = new BindableBoolean(false); public BindableBoolean thereIsntAnOpenedUL = new BindableBoolean(true); public BindableBoolean thereIsAnyRowInUL = new BindableBoolean(false); @@ -87,7 +91,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme private PickingLiberoListAdapter mAdapter; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private GestioneEnum mCurrentGestione; private boolean mAskCliente; @@ -171,11 +175,11 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @@ -206,23 +210,41 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); this.onLoadingStarted(); - this.mViewModel.processBarcodeDTO(data, () -> { - BarcodeManager.enable(); - this.onLoadingEnded(); + executorService.execute(() -> { + try { + this.mViewModel.processBarcodeDTO(data); + } catch (Exception e) { + onError(e); + } }); + + this.onLoadingEnded(); }; public void createNewLU() { - this.mViewModel.createNewLU(null, null, () -> { + executorService.execute(() -> { + try { + this.mViewModel.createNewLU(null, null); + } catch (Exception e) { + this.onError(e); + } }); } public void closeLU() { destroyAdapter(); - this.mViewModel.closeLU(null); + + executorService.execute(() -> { + try { + this.onLoadingStarted(); + this.mViewModel.closeLU(); + this.onLoadingEnded(); + } catch (Exception e) { + this.onError(e); + } + }); } @Override @@ -241,7 +263,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme @Override public void onLUOpened(MtbColt mtbColt) { - requireActivity().runOnUiThread(() -> { + handler.post(() -> { mToolbarTitleText.setText(String.format(getActivity().getText(R.string.lu_number_text).toString(), mtbColt.getNumCollo())); initAdapter(); @@ -257,14 +279,14 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme }); Snackbar.make(mBindings.getRoot(), R.string.data_saved, Snackbar.LENGTH_SHORT) - .setBackgroundTint(getResources().getColor(R. color. green_500)) + .setBackgroundTint(getResources().getColor(R.color.green_500)) .show(); }); } @Override public void onLUClosed() { - requireActivity().runOnUiThread(() -> { + handler.post(() -> { mToolbarTitleText.setText(getActivity().getText(R.string.free_picking_title_fragment).toString()); destroyAdapter(); @@ -285,7 +307,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme @Override public void onError(Exception ex) { - requireActivity().runOnUiThread(() -> { + handler.post(() -> { this.onLoadingEnded(); if (ex instanceof InvalidPesoKGException) { @@ -294,7 +316,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme UtilityExceptions.defaultException(getActivity(), ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }); } @@ -321,7 +343,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme DialogChooseArtsFromMtbColrList .newInstance(mtbColrsToPick, mtbAart, onComplete, () -> { onAbort.run(); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }) .show(requireActivity().getSupportFragmentManager(), DialogChooseArtsFromMtbColrList.class.getName()); } @@ -344,7 +366,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme boolean canOverflowOrderQuantity, boolean canPartitaMagBeChanged, boolean canLUBeClosed, - RunnableArgss onComplete) { + RunnableArgs onComplete) { DialogInputQuantityV2DTO dialogInputQuantityV2DTO = new DialogInputQuantityV2DTO() .setMtbAart(mtbAart) @@ -365,7 +387,12 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View.setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if (resultDTO == null || resultDTO.isAborted()) { + onComplete.run(null); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) @@ -373,19 +400,16 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme .setPartitaMag(resultDTO.getPartitaMag()) .setDataScad(resultDTO.getDataScad()); - onComplete.run(pickedQuantityDTO, shouldCloseLU); - }) - .setOnAbort(() -> { - onComplete.run(null, false); + onComplete.run(pickedQuantityDTO); }) .show(requireActivity().getSupportFragmentManager(), "tag"); } @Override public void onRowSaved() { - requireActivity().runOnUiThread(() -> { + handler.post(() -> { Snackbar.make(mBindings.getRoot(), R.string.data_saved, Snackbar.LENGTH_SHORT) - .setBackgroundTint(getResources().getColor(R. color. green_500)) + .setBackgroundTint(getResources().getColor(R.color.green_500)) .show(); }); } @@ -393,19 +417,40 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme @Override public void onMtbColrEdit(MtbColr mtbColr) { - this.mViewModel.dispatchRowEdit(mtbColr); + executorService.execute(() -> { + try { + this.mViewModel.dispatchRowEdit(mtbColr); + } catch (Exception e) { + this.onError(e); + } + }); } @Override public void onMtbColrDelete(MtbColr mtbColr) { - this.mViewModel.deleteRow(mtbColr); + executorService.execute(() -> { + try { + this.mViewModel.deleteRow(mtbColr); + } catch (Exception e) { + this.onError(e); + } + }); } @Override public void onPreDestroy(Runnable onComplete) { - BarcodeManager.removeCallback(barcodeScannerIstanceID); - if (thereIsAnOpenedUL.get()) mViewModel.closeLU(onComplete); - else onComplete.run(); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); + if (thereIsAnOpenedUL.get()) { + executorService.execute(() -> { + try { + this.onLoadingStarted(); + mViewModel.closeLU(); + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } + }); + } else onComplete.run(); } @Override diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoModule.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoModule.java index 43ddcd44..ffda1162 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoModule.java @@ -1,5 +1,7 @@ package it.integry.integrywmsnative.gest.picking_libero; +import android.os.Handler; + import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -22,6 +24,7 @@ public class PickingLiberoModule { @Provides @Singleton PickingLiberoViewModel providesPickingLiberoViewModel(ExecutorService executorService, + Handler handler, ArticoloRESTConsumer articoloRESTConsumer, ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, @@ -34,6 +37,7 @@ public class PickingLiberoModule { ) { return new PickingLiberoViewModel( executorService, + handler, articoloRESTConsumer, colliMagazzinoRESTConsumer, barcodeRESTConsumer, diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoViewModel.java index 3a72013a..d3e57ec2 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoViewModel.java @@ -1,5 +1,8 @@ package it.integry.integrywmsnative.gest.picking_libero; +import android.os.Handler; +import android.util.Pair; + import androidx.databinding.ObservableArrayList; import com.annimon.stream.Stream; @@ -17,7 +20,7 @@ import javax.inject.Inject; import it.integry.barcode_base_android_library.model.BarcodeScanDTO; import it.integry.integrywmsnative.core.data_recover.ColliDataRecoverService; -import it.integry.integrywmsnative.core.exception.InvalidCodMdepLUException; +import it.integry.integrywmsnative.core.exception.InvalidCodMdepException; import it.integry.integrywmsnative.core.exception.NoArtsFoundException; import it.integry.integrywmsnative.core.exception.NoLUFoundException; import it.integry.integrywmsnative.core.exception.NoResultFromBarcodeException; @@ -27,7 +30,6 @@ import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.expansion.RunnableArgss; import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILUBaseOperationsListener; import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener; -import it.integry.integrywmsnative.core.model.CommonModelConsts; import it.integry.integrywmsnative.core.model.JtbComt; import it.integry.integrywmsnative.core.model.MtbAart; import it.integry.integrywmsnative.core.model.MtbColr; @@ -37,6 +39,7 @@ import it.integry.integrywmsnative.core.model.MvwSitArtUdcDetInventario; import it.integry.integrywmsnative.core.model.VtbDest; import it.integry.integrywmsnative.core.model.dto.InternalCodAnagsDTO; import it.integry.integrywmsnative.core.model.dto.PickDataDTO; +import it.integry.integrywmsnative.core.model.observable.ObservableMtbTcol; import it.integry.integrywmsnative.core.model.secondary.GestioneEnum; import it.integry.integrywmsnative.core.rest.consumers.ArticoloRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.BarcodeRESTConsumer; @@ -53,7 +56,10 @@ import it.integry.integrywmsnative.core.rest.model.magazzino_automatico.Magazzin import it.integry.integrywmsnative.core.rest.model.magazzino_automatico.MagazzinoAutomaticoPickItemsRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.CloseUDSRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.CreateUDSRequestDTO; +import it.integry.integrywmsnative.core.rest.model.uds.DeleteUDSRowRequestDTO; import it.integry.integrywmsnative.core.rest.model.uds.DeleteULRequestDTO; +import it.integry.integrywmsnative.core.rest.model.uds.EditUDSRowRequestDTO; +import it.integry.integrywmsnative.core.rest.model.uds.InsertUDSRowRequestDTO; import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.utility.UtilityBarcode; import it.integry.integrywmsnative.core.utility.UtilityBigDecimal; @@ -71,6 +77,7 @@ public class PickingLiberoViewModel { private MtbColt mCurrentMtbColt = null; private final ExecutorService executorService; + private final Handler handler; private final ArticoloRESTConsumer mArticoloRESTConsumer; private final ColliMagazzinoRESTConsumer mColliMagazzinoRESTConsumer; private final BarcodeRESTConsumer mBarcodeRESTConsumer; @@ -96,7 +103,7 @@ public class PickingLiberoViewModel { @Inject - public PickingLiberoViewModel(ExecutorService executorService, + public PickingLiberoViewModel(ExecutorService executorService, Handler handler, ArticoloRESTConsumer articoloRESTConsumer, ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, @@ -107,6 +114,7 @@ public class PickingLiberoViewModel { ColliSpedizioneRESTConsumer colliSpedizioneRESTConsumer, ColliDataRecoverService colliDataRecoverService) { this.executorService = executorService; + this.handler = handler; this.mArticoloRESTConsumer = articoloRESTConsumer; this.mColliMagazzinoRESTConsumer = colliMagazzinoRESTConsumer; this.mBarcodeRESTConsumer = barcodeRESTConsumer; @@ -133,43 +141,41 @@ public class PickingLiberoViewModel { } - public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { + public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO) throws Exception { if (this.mCurrentMtbColt == null) { - this.createNewLU(null, null, () -> { - executeEtichettaBehaviour(barcodeScanDTO, onComplete); - }); - } else { - executeEtichettaBehaviour(barcodeScanDTO, onComplete); + this.createNewLU(null, null); } + + executeEtichettaBehaviour(barcodeScanDTO); } - private void executeEtichettaBehaviour(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { + private void executeEtichettaBehaviour(BarcodeScanDTO barcodeScanDTO) throws Exception { if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { //Cerco gli articoli presenti nell'ul dell'etichetta anonima - this.executeEtichettaLU(barcodeScanDTO.getStringValue(), onComplete); + this.executeEtichettaLU(barcodeScanDTO.getStringValue()); } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)) { //Cerco tramite etichetta un collo in posizione mono ul - this.executeEtichettaPosizione(barcodeScanDTO, onComplete); + this.executeEtichettaPosizione(barcodeScanDTO); } else if (UtilityBarcode.isEtichetta128(barcodeScanDTO)) { //Cerco tramite etichetta ean 128 (che può indicarmi una UL) - this.executeEtichettaEan128(barcodeScanDTO, onComplete); + this.executeEtichettaEan128(barcodeScanDTO); } else if (UtilityBarcode.isEanPeso(barcodeScanDTO) && SettingsManager.iDB().isFlagPickingLiberoEnableScanArt()) { //Cerco tramite etichetta ean 128 (che può indicarmi un articolo o una UL) - this.executeEtichettaEanPeso(barcodeScanDTO, onComplete); + this.executeEtichettaEanPeso(barcodeScanDTO); } else if (SettingsManager.iDB().isFlagPickingLiberoEnableScanArt()) { //Cerco tramite ean13 un collo in posizione mono ul definita in anagrafica articolo, altrimenti se abilitato procedo con picking manuale - this.loadArticolo(barcodeScanDTO.getStringValue(), null, onComplete); + this.loadArticolo(barcodeScanDTO.getStringValue(), null); } else { - this.sendError(new NoArtsFoundException()); + throw new NoArtsFoundException(); } } - private void executeEtichettaPosizione(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { + private void executeEtichettaPosizione(BarcodeScanDTO barcodeScanDTO) throws Exception { MtbDepoPosizione foundPosizione = Stream.of(SettingsManager.iDB().getAvailablePosizioni()) .filter(x -> x.getPosizione().equalsIgnoreCase(barcodeScanDTO.getStringValue())) @@ -177,204 +183,190 @@ public class PickingLiberoViewModel { if (foundPosizione == null) { //Nessuna posizione trovata con questo barcode - this.sendError(new ScannedPositionNotExistException()); - return; + throw new ScannedPositionNotExistException(); } if (foundPosizione.isMagazzinoAutomatico()) { //Eseguo picking da magazzino automatico - this.executeMagazzinoAutomatico(foundPosizione, onComplete); + this.executeMagazzinoAutomatico(foundPosizione); } else { - this.executePosizione(foundPosizione, null, onComplete); + this.executePosizione(foundPosizione, null); } } - private void executeMagazzinoAutomatico(MtbDepoPosizione mtbDepoPosizione, Runnable onComplete) { - mGiacenzaRESTConsumer.getGiacenzeInPosizione(mtbDepoPosizione, availableItems -> { + private void executeMagazzinoAutomatico(MtbDepoPosizione mtbDepoPosizione) throws Exception { + this.sendOnLoadingStarted(); + var availableItems = mGiacenzaRESTConsumer.getGiacenzeInPosizioneSynchronized(mtbDepoPosizione); - var mtbColrs = Stream.of(availableItems) - .map(MvwSitArtUdcDetInventario::toMtbColr) - .toList(); + var mtbColrs = availableItems.stream() + .map(MvwSitArtUdcDetInventario::toMtbColr) + .collect(Collectors.toList()); - List selectedMtbColrs = null; - try { - selectedMtbColrs = this.sendArtSelectionRequest(mtbColrs, null); - } catch (InterruptedException e) { - this.sendError(e); - return; - } - - if (selectedMtbColrs == null) { - this.sendOnLoadingEnded(); - return; - } - - final List magazzinoAutomaticoPickItemRequestDTOList = new ArrayList<>(); - for (MtbColr selectedArt : selectedMtbColrs) { - MagazzinoAutomaticoPickItemRequestDTO itemDto = new MagazzinoAutomaticoPickItemRequestDTO(selectedArt.getCodMart()) - .setQtaTot(selectedArt.getQtaCol()) - .setNumCnf(selectedArt.getNumCnf()) - .setUntMis(selectedArt.getUntMis()); - - magazzinoAutomaticoPickItemRequestDTOList.add(itemDto); - } - - var magazzinoAutomaticoPickRequest = new MagazzinoAutomaticoPickItemsRequestDTO() - .setShouldCreateUDS(true) - .setDefaultGestioneOfNewUDS(mDefaultGestione.getText()) - .setItemsToPick(magazzinoAutomaticoPickItemRequestDTOList); - - mMagazzinoAutomaticoRESTConsumer.pickItems(mtbDepoPosizione, - magazzinoAutomaticoPickRequest, onComplete, this::sendError); + List selectedMtbColrs = this.sendArtSelectionRequest(mtbColrs, null); + if (selectedMtbColrs == null) { this.sendOnLoadingEnded(); + return; + } - }, this::sendError); + final List magazzinoAutomaticoPickItemRequestDTOList = new ArrayList<>(); + for (MtbColr selectedArt : selectedMtbColrs) { + MagazzinoAutomaticoPickItemRequestDTO itemDto = new MagazzinoAutomaticoPickItemRequestDTO(selectedArt.getCodMart()) + .setQtaTot(selectedArt.getQtaCol()) + .setNumCnf(selectedArt.getNumCnf()) + .setUntMis(selectedArt.getUntMis()); + magazzinoAutomaticoPickItemRequestDTOList.add(itemDto); + } + var magazzinoAutomaticoPickRequest = new MagazzinoAutomaticoPickItemsRequestDTO() + .setShouldCreateUDS(true) + .setDefaultGestioneOfNewUDS(mDefaultGestione.getText()) + .setItemsToPick(magazzinoAutomaticoPickItemRequestDTOList); + + mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronized(mtbDepoPosizione, + magazzinoAutomaticoPickRequest); + + this.sendOnLoadingEnded(); } - private void executePosizione(MtbDepoPosizione posizione, MtbAart articolo, Runnable onComplete) { - this.mPosizioniRESTConsumer.getBancaliInPosizione(posizione, mtbColtList -> { + private void executePosizione(MtbDepoPosizione posizione, MtbAart articolo) throws Exception { + var mtbColtList = this.mPosizioniRESTConsumer.getBancaliInPosizioneSynchronized(posizione); - if (mtbColtList == null || mtbColtList.isEmpty()) { - if (articolo != null) { - this.dispatchArt(articolo, null); - } else { - this.sendError(new NoLUFoundException()); - } - } else if (mtbColtList.size() == 1) { - this.mColliMagazzinoRESTConsumer.getByTestata(mtbColtList.get(0), true, false, mtbColt -> { - - boolean codMdepIsValid = Stream.of(SettingsManager.iDB().getAvailableCodMdep()) - .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - - if (codMdepIsValid) { - pickMerceULtoUL(mtbColt, articolo, onComplete); - } else this.sendError(new InvalidCodMdepLUException()); - - }, this::sendError); + if (mtbColtList == null || mtbColtList.isEmpty()) { + if (articolo != null) { + this.dispatchArt(articolo, null); } else { - this.sendError(new TooManyLUFoundInMonoLUPositionException()); + throw new NoLUFoundException(); } + } else if (mtbColtList.size() == 1) { + var mtbColt = this.mColliMagazzinoRESTConsumer.getByTestataSynchronized(mtbColtList.get(0), true, false); - }, this::sendError); - } + boolean codMdepIsValid = Stream.of(SettingsManager.iDB().getAvailableCodMdep()) + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - private void executeEtichettaEanPeso(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - try { - Ean13PesoModel ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue()); - this.loadArticolo(ean13PesoModel.getPrecode(), ean13PesoModel.toEan128(), onComplete); - } catch (Exception ex) { - this.sendError(ex); + if (codMdepIsValid) { + pickMerceULtoUL(mtbColt, articolo); + } else throw new InvalidCodMdepException(); + + + } else { + throw new TooManyLUFoundInMonoLUPositionException(); } } - private void executeEtichettaLU(String sscc, Runnable onComplete) { - mColliMagazzinoRESTConsumer.getBySSCC(sscc, true, false, mtbColtScanned -> { - - if (mtbColtScanned == null) { - this.sendError(new NoLUFoundException()); - } else if ((mtbColtScanned.getGestioneEnum() == GestioneEnum.ACQUISTO || mtbColtScanned.getGestioneEnum() == GestioneEnum.LAVORAZIONE) && mtbColtScanned.getSegno() > 0) { - - boolean codMdepIsValid = Stream.of(SettingsManager.iDB().getAvailableCodMdep()) - .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColtScanned.getCodMdep())); - - if (codMdepIsValid) { - pickMerceULtoUL(mtbColtScanned, onComplete); - } else this.sendError(new InvalidCodMdepLUException()); - - } else { - this.sendError(new NoLUFoundException()); - } - - }, this::sendError); + private void executeEtichettaEanPeso(BarcodeScanDTO barcodeScanDTO) throws Exception { + Ean13PesoModel ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue()); + this.loadArticolo(ean13PesoModel.getPrecode(), ean13PesoModel.toEan128()); } - private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - mBarcodeRESTConsumer.decodeEan128(barcodeScanDTO, ean128Model -> { + private void executeEtichettaLU(String sscc) throws Exception { + var mtbColtScanned = mColliMagazzinoRESTConsumer.getBySsccSynchronized(sscc, true, false); - String barcodeProd = null; + if (mtbColtScanned == null) { + throw new NoLUFoundException(); - if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) barcodeProd = ean128Model.Sscc; - if (!UtilityString.isNullOrEmpty(ean128Model.Gtin)) barcodeProd = ean128Model.Gtin; - if (!UtilityString.isNullOrEmpty(ean128Model.Content)) - barcodeProd = ean128Model.Content; + } else if ((mtbColtScanned.getGestioneEnum() == GestioneEnum.ACQUISTO || mtbColtScanned.getGestioneEnum() == GestioneEnum.LAVORAZIONE) && mtbColtScanned.getSegno() > 0) { - if (!UtilityString.isNullOrEmpty(barcodeProd)) { + boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColtScanned.getCodMdep())); - if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) { - this.executeEtichettaLU(ean128Model.Sscc, onComplete); - } else if (!UtilityString.isNullOrEmpty(barcodeProd) && SettingsManager.iDB().isFlagPickingLiberoEnableScanArt()) { - this.loadArticolo(barcodeProd, ean128Model, onComplete); - } else { - this.sendError(new NoLUFoundException()); - } + if (codMdepIsValid) { + pickMerceULtoUL(mtbColtScanned); + } else throw new InvalidCodMdepException(); - } else { - //EAN 128 non completo o comunque mancano i riferimenti al prodotto - this.sendError(new NoLUFoundException()); - } - }, this::sendError); + } else { + throw new NoLUFoundException(); + } } - private void loadArticolo(String barcodeProd, Ean128Model ean128Model, Runnable onComplete) { - mArticoloRESTConsumer.searchByBarcode(barcodeProd, mtbAartList -> { - if (mtbAartList != null && !mtbAartList.isEmpty()) { - MtbAart articolo = mtbAartList.get(0); - MtbDepoPosizione posizione = UtilityPosizione.getFromCache(articolo.getPosizione()); + private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO) throws Exception { + var ean128Model = mBarcodeRESTConsumer.decodeEan128Synchronized(barcodeScanDTO); - if (posizione != null && posizione.isFlagMonoCollo()) { - this.executePosizione(posizione, articolo, onComplete); - } else if (mDefaultGestione == GestioneEnum.VENDITA) { - this.dispatchArt(articolo, ean128Model); - onComplete.run(); - } else { - this.sendError(new NoResultFromBarcodeException(barcodeProd)); - } + String barcodeProd = null; + + if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) barcodeProd = ean128Model.Sscc; + if (!UtilityString.isNullOrEmpty(ean128Model.Gtin)) barcodeProd = ean128Model.Gtin; + if (!UtilityString.isNullOrEmpty(ean128Model.Content)) + barcodeProd = ean128Model.Content; + + if (!UtilityString.isNullOrEmpty(barcodeProd)) { + + if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) { + this.executeEtichettaLU(ean128Model.Sscc); + + } else if (!UtilityString.isNullOrEmpty(barcodeProd) && SettingsManager.iDB().isFlagPickingLiberoEnableScanArt()) { + this.loadArticolo(barcodeProd, ean128Model); } else { - this.sendError(new NoResultFromBarcodeException(barcodeProd)); + throw new NoLUFoundException(); } - }, this::sendError); + } else { + //EAN 128 non completo o comunque mancano i riferimenti al prodotto + throw new NoLUFoundException(); + } + + } + + private void loadArticolo(String barcodeProd, Ean128Model ean128Model) throws Exception { + var mtbAartList = mArticoloRESTConsumer.searchByBarcodeSynchronized(barcodeProd); + if (mtbAartList != null && !mtbAartList.isEmpty()) { + MtbAart articolo = mtbAartList.get(0); + MtbDepoPosizione posizione = UtilityPosizione.getFromCache(articolo.getPosizione()); + + if (posizione != null && posizione.isFlagMonoCollo()) { + this.executePosizione(posizione, articolo); + + } else if (mDefaultGestione == GestioneEnum.VENDITA) { + this.dispatchArt(articolo, ean128Model); + + } else { + throw new NoResultFromBarcodeException(barcodeProd); + } + + } else { + throw new NoResultFromBarcodeException(barcodeProd); + } } - public void createNewLU(Integer customNumCollo, String customSerCollo, Runnable onComplete) { + public void createNewLU(Integer customNumCollo, String customSerCollo) throws Exception { + VtbDest vtbDest = null; + String codJcom = null; + if (this.mFlagAskCliente) { - this.sendLUClienteRequired((vtbDest, codJcom) -> { - createNewLU_PostClienteAsk(customNumCollo, customSerCollo, vtbDest, onComplete); - }, this::sendOnLoadingEnded); - } else { - createNewLU_PostClienteAsk(customNumCollo, customSerCollo, null, onComplete); + var data = this.sendLUClienteRequired(); + vtbDest = data.first; + codJcom = data.second; } + + createNewLU_PostClienteAsk(customNumCollo, customSerCollo, vtbDest); } - private void createNewLU_PostClienteAsk(Integer customNumCollo, String customSerCollo, VtbDest vtbDest, Runnable onComplete) { + private void createNewLU_PostClienteAsk(Integer customNumCollo, String customSerCollo, VtbDest vtbDest) throws Exception { + DialogAskLineaProdResponse dialogAskLineaProdResponse = null; + if (this.mFlagAskLineaProd) { - this.sendLULineaProdRequired(response -> { - createNewLU_PostLineaProdAsk(customNumCollo, customSerCollo, vtbDest, response.getPosizione(), response.getIdLotto(), onComplete); - - }, this::sendOnLoadingEnded); - } else { - createNewLU_PostLineaProdAsk(customNumCollo, customSerCollo, vtbDest, null, null, onComplete); + dialogAskLineaProdResponse = this.sendLULineaProdRequired(); } + + createNewLU_PostLineaProdAsk(customNumCollo, customSerCollo, vtbDest, + dialogAskLineaProdResponse != null ? dialogAskLineaProdResponse.getPosizione() : null, + dialogAskLineaProdResponse != null ? dialogAskLineaProdResponse.getIdLotto() : null); } - private void createNewLU_PostLineaProdAsk(Integer customNumCollo, String customSerCollo, VtbDest vtbDest, String posizione, Integer idLotto, Runnable onComplete) { + private void createNewLU_PostLineaProdAsk(Integer customNumCollo, String customSerCollo, VtbDest vtbDest, String posizione, Integer idLotto) throws Exception { + JtbComt commessa = null; + if (this.mFlagAskCommessa) { - this.sendLUCommessaRequired(response -> { - createNewLU_PostCommessaAsk(customNumCollo, customSerCollo, vtbDest, posizione, idLotto, response, onComplete); - - }, this::sendOnLoadingEnded); - } else { - createNewLU_PostCommessaAsk(customNumCollo, customSerCollo, vtbDest, null, null, null, onComplete); + commessa = this.sendLUCommessaRequired(); } + createNewLU_PostCommessaAsk(customNumCollo, customSerCollo, vtbDest, posizione, idLotto, commessa); } - private void createNewLU_PostCommessaAsk(Integer customNumCollo, String customSerCollo, VtbDest vtbDest, String codJfas, Integer idLotto, JtbComt codJcom, Runnable onComplete) { + private void createNewLU_PostCommessaAsk(Integer customNumCollo, String customSerCollo, VtbDest vtbDest, String codJfas, Integer idLotto, JtbComt codJcom) throws Exception { this.mDefaultCommessa = codJcom; this.sendOnLoadingStarted(); @@ -404,59 +396,19 @@ public class PickingLiberoViewModel { } - mColliScaricoRESTConsumer.createUDS(createUDSRequest, mtbColt -> { - mMtbColtSessionID = mColliDataRecoverService.startNewSession(mtbColt, null); + var mtbColt = mColliScaricoRESTConsumer.createUDSSynchronized(createUDSRequest); - mtbColt - .setMtbColr(new ObservableArrayList<>()); + mMtbColtSessionID = mColliDataRecoverService.startNewSession(mtbColt, null); - this.mCurrentMtbColt = mtbColt; + mtbColt.setMtbColr(new ObservableArrayList<>()); - this.sendOnLoadingEnded(); + this.mCurrentMtbColt = mtbColt; - if (onComplete != null) onComplete.run(); - this.sendLUOpened(mtbColt); - }, this::sendError); - -// MtbColt mtbColt = new MtbColt(); -// mtbColt.initDefaultFields(mDefaultGestione) -// .setRifOrd(mDefaultGestione == GestioneEnum.LAVORAZIONE ? "PICKING LIBERO" : null) -// .setSegno(-1) -// .setOperation(CommonModelConsts.OPERATION.INSERT_OR_UPDATE); -// -// if (customNumCollo != null) { -// mtbColt.setNumCollo(customNumCollo); -// } -// -// if (!UtilityString.isNullOrEmpty(customSerCollo)) { -// mtbColt.setSerCollo(customSerCollo); -// } -// -// if (vtbDest != null) { -// mtbColt.setCodAnag(vtbDest.getCodAnag()); -// mtbColt.setCodVdes(vtbDest.getCodVdes()); -// } -// -// if (!UtilityString.isNullOrEmpty(codJcom)) { -// mtbColt.setCodJcom(codJcom); -// } - -// mColliMagazzinoRESTConsumer.saveCollo(mtbColt, value -> { -// mtbColt -// .setNumCollo(value.getNumCollo()) -// .setDataCollo(value.getDataColloS()) -// .setMtbColr(new ObservableArrayList<>()); -// -// this.mCurrentMtbColt = mtbColt; -// -// this.sendOnLoadingEnded(); -// -// if (onComplete != null) onComplete.run(); -// this.sendLUOpened(mtbColt); -// }, this::sendError); + this.sendOnLoadingEnded(); + this.sendLUOpened(mtbColt); } - private void dispatchArt(MtbAart mtbAart, Ean128Model ean128Model) { + private void dispatchArt(MtbAart mtbAart, Ean128Model ean128Model) throws Exception { PickingObjectDTO pickingObjectDTO = new PickingObjectDTO() .setMtbAart(mtbAart) .setTempPickData(PickDataDTO.fromEan128(ean128Model)); @@ -485,7 +437,7 @@ public class PickingLiberoViewModel { if (manualPickDTO.isEanPeso()) { if (mtbAart.getUntMisRifPeso() == MtbAart.UntMisRifPesoEnum.M) { if (UtilityBigDecimal.equalsTo(mtbAart.getPesoKg(), BigDecimal.ZERO)) { - this.sendError(new InvalidPesoKGException()); + throw new InvalidPesoKGException(); } else { qtaColDaPrelevare = UtilityBigDecimal.divide(qtaColDaPrelevare, mtbAart.getPesoKg()); } @@ -533,7 +485,7 @@ public class PickingLiberoViewModel { } - this.sendOnItemDispatched( + var pickedQuantityDTO = this.sendOnItemDispatched( pickingObjectDTO, pickingObjectDTO.getMtbAart(), initialNumCnf, @@ -549,86 +501,71 @@ public class PickingLiberoViewModel { dataScad, false, true, - true, - (pickedQuantityDTO, shouldCloseLU) -> { - if (pickedQuantityDTO == null) { - this.sendOnLoadingEnded(); - return; - } + true); - this.saveNewRow(pickingObjectDTO, - pickedQuantityDTO.getNumCnf(), - pickedQuantityDTO.getQtaCnf(), - pickedQuantityDTO.getQtaTot(), - pickedQuantityDTO.getPartitaMag(), - pickedQuantityDTO.getDataScad(), - shouldCloseLU); - }); + if (pickedQuantityDTO == null) { + return; + } + + this.saveNewRow(pickingObjectDTO, + pickedQuantityDTO.getNumCnf(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getPartitaMag(), + pickedQuantityDTO.getDataScad(), + pickedQuantityDTO.isShouldCloseLu()); } - private void pickMerceULtoUL(MtbColt sourceMtbColt, Runnable onComplete) { - pickMerceULtoUL(sourceMtbColt, null, onComplete); + private void pickMerceULtoUL(MtbColt sourceMtbColt) throws Exception { + pickMerceULtoUL(sourceMtbColt, null); } - private void pickMerceULtoUL(MtbColt sourceMtbColt, MtbAart mtbAart, Runnable onComplete) { - executorService.execute(() -> { + private void pickMerceULtoUL(MtbColt sourceMtbColt, MtbAart mtbAart) throws Exception { - try { - List mtbColrsToPick = sourceMtbColt.getMtbColr().stream() - .filter(x -> UtilityBigDecimal.greaterThan(x.getQtaCol(), BigDecimal.ZERO)) - .collect(Collectors.toList()); + List mtbColrsToPick = sourceMtbColt.getMtbColr().stream() + .filter(x -> UtilityBigDecimal.greaterThan(x.getQtaCol(), BigDecimal.ZERO)) + .collect(Collectors.toList()); - List pickedAarts = this.sendArtSelectionRequest(mtbColrsToPick, mtbAart); + List pickedAarts = this.sendArtSelectionRequest(mtbColrsToPick, mtbAart); - if (pickedAarts == null) { - this.sendOnLoadingEnded(); - return; - } + if (pickedAarts == null) { + return; + } - List mtbColrsToMove = new ArrayList<>(); + List mtbColrsToMove = new ArrayList<>(); - if (!pickedAarts.isEmpty()) { - for (var pickedArt : pickedAarts) { - var mtbColr = askSingleQuantity(pickedArt); + if (!pickedAarts.isEmpty()) { + for (var pickedArt : pickedAarts) { + var mtbColr = askSingleQuantity(pickedArt); - if (mtbColr != null) - mtbColrsToMove.add(mtbColr); - } - - if (!mtbColrsToMove.isEmpty()) { - - if (this.mDefaultCommessa != null) - mtbColrsToMove.forEach(x -> x.setCodJcom(this.mDefaultCommessa.getCodJcom())); - - MtbColt clonedSourceTestata = (MtbColt) sourceMtbColt.clone(); - clonedSourceTestata.getMtbColr().clear(); - clonedSourceTestata.getMtbColr().addAll(mtbColrsToMove); - - mColliMagazzinoRESTConsumer.spostaArtsTraUL(clonedSourceTestata, - this.mCurrentMtbColt, true, (generatedMtbColrs) -> { - - mCurrentMtbColt.getMtbColr().addAll(generatedMtbColrs); - - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); - onComplete.run(); - }, this::sendError); - - } else { - onComplete.run(); - this.sendOnLoadingEnded(); - } - - } else { - onComplete.run(); - this.sendOnLoadingEnded(); - } - - } catch (InterruptedException e) { - this.sendError(e); + if (mtbColr != null) + mtbColrsToMove.add(mtbColr); } - }); + if (!mtbColrsToMove.isEmpty()) { + this.sendOnLoadingStarted(); + + if (this.mDefaultCommessa != null) + mtbColrsToMove.forEach(x -> x.setCodJcom(this.mDefaultCommessa.getCodJcom())); + + MtbColt clonedSourceTestata = (MtbColt) sourceMtbColt.clone(); + clonedSourceTestata.getMtbColr().clear(); + clonedSourceTestata.getMtbColr().addAll(mtbColrsToMove); + + var generatedMtbColrs = mColliMagazzinoRESTConsumer.spostaArtsTraULSynchronized(clonedSourceTestata, + this.mCurrentMtbColt, true); + + handler.post(() -> { + mCurrentMtbColt.getMtbColr().addAll(generatedMtbColrs); + }); + + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); + } + + } + + } private MtbColr askSingleQuantity(MtbColr mtbColr) throws InterruptedException { @@ -650,10 +587,7 @@ public class PickingLiberoViewModel { new PickDataDTO() .setSourceMtbColt(sourceMtbColt)); - CountDownLatch countDownLatch = new CountDownLatch(1); - AtomicReference result = new AtomicReference<>(); - - this.sendOnItemDispatched( + var pickedQuantityDTO = this.sendOnItemDispatched( pickingObjectDTO, pickingObjectDTO.getMtbAart(), mtbColr.getNumCnf(), @@ -669,81 +603,87 @@ public class PickingLiberoViewModel { mtbColr.getDataScadPartita(), false, false, - false, - (pickedQuantityDTO, shouldCloseLU) -> { - if (pickedQuantityDTO == null) { - countDownLatch.countDown(); - return; - } + false); - mtbColr - .setPartitaMag(pickedQuantityDTO.getPartitaMag()) - .setDataScadPartita(pickedQuantityDTO.getDataScad()) - .setQtaCol(pickedQuantityDTO.getQtaTot()) - .setQtaCnf(pickedQuantityDTO.getQtaCnf()) - .setNumCnf(pickedQuantityDTO.getNumCnf()) - .setDatetimeRow(UtilityDate.getDateInstance()) - .setMtbAart(pickingObjectDTO.getMtbAart()); + if (pickedQuantityDTO == null) + return null; - result.set(mtbColr); - countDownLatch.countDown(); - }); + mtbColr + .setPartitaMag(pickedQuantityDTO.getPartitaMag()) + .setDataScadPartita(pickedQuantityDTO.getDataScad()) + .setQtaCol(pickedQuantityDTO.getQtaTot()) + .setQtaCnf(pickedQuantityDTO.getQtaCnf()) + .setNumCnf(pickedQuantityDTO.getNumCnf()) + .setDatetimeRow(UtilityDate.getDateInstance()) + .setMtbAart(pickingObjectDTO.getMtbAart()); - - countDownLatch.await(); - return result.get(); + return mtbColr; } - public void saveNewRow(PickingObjectDTO pickingObjectDTO, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) { - this.sendOnLoadingStarted(); - - final MtbColr mtbColr = new MtbColr() - .setCodMart(pickingObjectDTO.getMtbAart().getCodMart()) - .setPartitaMag(partitaMag) - .setDataScadPartita(dataScad) - .setQtaCol(qtaTot) - .setQtaCnf(qtaCnf) - .setNumCnf(numCnf) - .setDescrizione(pickingObjectDTO.getMtbAart().getDescrizioneEstesa()) - .setDatetimeRow(UtilityDate.getDateInstance()) - .setCodJcom(this.mDefaultCommessa.getCodJcom()); - - mtbColr.setOperation(CommonModelConsts.OPERATION.INSERT_OR_UPDATE); - - MtbColt cloneMtbColt = (MtbColt) mCurrentMtbColt.clone(); - cloneMtbColt.setOperation(CommonModelConsts.OPERATION.UPDATE); - - cloneMtbColt.setMtbColr(new ObservableArrayList<>()); - cloneMtbColt.getMtbColr().add((MtbColr) mtbColr.clone()); - + public void saveNewRow(PickingObjectDTO pickingObjectDTO, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) throws Exception { if (UtilityBigDecimal.equalsTo(numCnf, BigDecimal.ZERO) && UtilityBigDecimal.equalsTo(qtaTot, BigDecimal.ZERO)) { this.sendOnLoadingEnded(); return; } - mColliMagazzinoRESTConsumer.saveCollo(cloneMtbColt, value -> { - mtbColr - .setDataCollo(value.getDataColloS()) - .setNumCollo(value.getNumCollo()) - .setGestione(value.getGestione()) - .setSerCollo(value.getSerCollo()) - .setRiga(value.getMtbColr().get(value.getMtbColr().size() - 1).getRiga()) - .setUntMis(pickingObjectDTO.getMtbAart().getUntMis()) - .setMtbAart(pickingObjectDTO.getMtbAart()); + var insertUdsRowRequest = new InsertUDSRowRequestDTO() + .setCodMart(pickingObjectDTO.getMtbAart().getCodMart()) + .setPartitaMag(partitaMag) + .setDataScad(dataScad) + .setQtaTot(qtaTot) + .setQtaCnf(qtaCnf) + .setNumCnf(numCnf) + .setCodJcom(this.mDefaultCommessa.getCodJcom()) + .setTargetMtbColt(mCurrentMtbColt.clone(false)); - mCurrentMtbColt.getMtbColr().add(mtbColr); + MtbColr savedMtbColr = mColliScaricoRESTConsumer.insertUDSRowSynchronized(insertUdsRowRequest); + savedMtbColr.setMtbAart(pickingObjectDTO.getMtbAart()); - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); + mCurrentMtbColt.getMtbColr().add(savedMtbColr); - if (shouldCloseLU) closeLU(null); - }, this::sendError); + this.sendOnRowSaved(); + if (shouldCloseLU) closeLU(); } - private void loadRifULFromMtbColr(MtbColr mtbColr, RunnableArgs onComplete) { + + private void executeDepositChangeIfNeeded(MtbColt refMtbColt) throws Exception { + //Considero solo la prima UDC scansionata + boolean shouldChangeCodMdep = refMtbColt != null && !refMtbColt.getCodMdep().equalsIgnoreCase(mCurrentMtbColt.getCodMdep()) && + mCurrentMtbColt.getMtbColr().isEmpty(); + String newCodMdep = shouldChangeCodMdep ? refMtbColt.getCodMdep() : null; + + if (shouldChangeCodMdep) { + mColliMagazzinoRESTConsumer.spostaUlSynchronized(mCurrentMtbColt, newCodMdep, null, false); + mCurrentMtbColt.setCodMdep(newCodMdep); + } + } + + private void executeTipoUlChangeIfNeeded(MtbColt refMtbColt) throws Exception { + boolean shouldChangeCodTcol = refMtbColt != null && refMtbColt.getCodTcol() != null && + !refMtbColt.getCodTcol().equalsIgnoreCase(mCurrentMtbColt.getCodTcol()) && + mCurrentMtbColt.getMtbColr().isEmpty(); + String newTipoUL = shouldChangeCodTcol ? refMtbColt.getCodTcol() : null; + + ObservableMtbTcol newMtbTcol = SettingsManager.iDB().getInternalImballi().stream() + .filter(x -> x.getCodTcol().equalsIgnoreCase(newTipoUL)) + .findFirst() + .orElse(null); + + if (!UtilityString.isNullOrEmpty(newTipoUL) && newMtbTcol == null) { + throw new Exception("Impossibile riconoscere il tipo UL " + newTipoUL); + } + + if (shouldChangeCodTcol && newMtbTcol != null) { + mColliMagazzinoRESTConsumer.updateTipoULSynchronized(mCurrentMtbColt, newMtbTcol.getCodTcol()); + mCurrentMtbColt.setCodTcol(newMtbTcol.getCodTcol()); + } + } + + + private MtbColt loadRifULFromMtbColr(MtbColr mtbColr) throws Exception { //Se ho dei riferimenti ad una UL devo leggere la QTA ancora disponibile sulla Ul if (mtbColr != null && !UtilityString.isNullOrEmpty(mtbColr.getGestioneRif()) && @@ -751,240 +691,207 @@ public class PickingLiberoViewModel { !UtilityString.isNullOrEmpty(mtbColr.getDataColloRifS()) && mtbColr.getNumColloRif() != null) { - mColliMagazzinoRESTConsumer.getByChiaveCollo( + MtbColt mtbColt = mColliMagazzinoRESTConsumer.getByChiaveColloSynchronized( mtbColr.getGestioneRifEnum(), mtbColr.getNumColloRif(), mtbColr.getDataColloRifS(), mtbColr.getSerColloRif(), true, - false, - onComplete, - this::sendError); + false); - } else { - onComplete.run(null); + return mtbColt; } + + return null; } - public void dispatchRowEdit(MtbColr mtbColrToUpdate) { + public void dispatchRowEdit(MtbColr mtbColrToUpdate) throws Exception { + this.sendOnLoadingStarted(); final PickingObjectDTO pickingObjectDTO = new PickingObjectDTO() .setMtbAart(mtbColrToUpdate.getMtbAart()); - loadRifULFromMtbColr(mtbColrToUpdate, mtbColtRif -> { + var mtbColtRif = loadRifULFromMtbColr(mtbColrToUpdate); - BigDecimal totalQtaAvailable = null; - BigDecimal totalNumCnfAvailable = null; - BigDecimal qtaCnfAvailable = null; + BigDecimal totalQtaAvailable = null; + BigDecimal totalNumCnfAvailable = null; + BigDecimal qtaCnfAvailable = null; - List mtbColrRifs = mtbColtRif != null && - mtbColtRif.getMtbColr() != null ? mtbColtRif.getMtbColr() : null; + List mtbColrRifs = mtbColtRif != null && + mtbColtRif.getMtbColr() != null ? mtbColtRif.getMtbColr() : null; - MtbColr mtbColrRif = null; + MtbColr mtbColrRif = null; - if (mtbColrRifs != null && !mtbColrRifs.isEmpty()) { - //TODO: Da capire se è necessario controllare anche il cod_jcom - mtbColrRif = Stream.of(mtbColrRifs) - .filter(x -> UtilityString.equalsIgnoreCase(x.getCodMart(), mtbColrToUpdate.getCodMart()) && - UtilityString.equalsIgnoreCase(x.getCodCol(), mtbColrToUpdate.getCodCol()) && - UtilityString.equalsIgnoreCase(x.getCodTagl(), mtbColrToUpdate.getCodTagl()) && - UtilityString.equalsIgnoreCase(x.getPartitaMag(), mtbColrToUpdate.getPartitaMag())) - .findFirstOrElse(null); - } + if (mtbColrRifs != null && !mtbColrRifs.isEmpty()) { + //TODO: Da capire se è necessario controllare anche il cod_jcom + mtbColrRif = mtbColrRifs.stream() + .filter(x -> UtilityString.equalsIgnoreCase(x.getCodMart(), mtbColrToUpdate.getCodMart()) && + UtilityString.equalsIgnoreCase(x.getCodCol(), mtbColrToUpdate.getCodCol()) && + UtilityString.equalsIgnoreCase(x.getCodTagl(), mtbColrToUpdate.getCodTagl()) && + UtilityString.equalsIgnoreCase(x.getPartitaMag(), mtbColrToUpdate.getPartitaMag())) + .findFirst() + .orElse(null); + } - if (mtbColrRif != null) { + if (mtbColrRif != null) { + totalQtaAvailable = mtbColrRif.getQtaCol().add(mtbColrToUpdate.getQtaCol()); + totalNumCnfAvailable = mtbColrRif.getNumCnf().add(mtbColrToUpdate.getNumCnf()); + qtaCnfAvailable = mtbColrRif.getQtaCnf(); - totalQtaAvailable = mtbColrRif.getQtaCol().add(mtbColrToUpdate.getQtaCol()); - totalNumCnfAvailable = mtbColrRif.getNumCnf().add(mtbColrToUpdate.getNumCnf()); - qtaCnfAvailable = mtbColrRif.getQtaCnf(); + } else { + totalQtaAvailable = mtbColrToUpdate.getQtaCol(); + totalNumCnfAvailable = mtbColrToUpdate.getNumCnf(); + qtaCnfAvailable = mtbColrToUpdate.getQtaCnf(); - } else { + } + this.sendOnLoadingEnded(); - totalQtaAvailable = mtbColrToUpdate.getQtaCol(); - totalNumCnfAvailable = mtbColrToUpdate.getNumCnf(); - qtaCnfAvailable = mtbColrToUpdate.getQtaCnf(); + var pickedQuantityDTO = this.sendOnItemDispatched( + pickingObjectDTO, + pickingObjectDTO.getMtbAart(), + mtbColrToUpdate.getNumCnf(), + mtbColrToUpdate.getQtaCnf(), + mtbColrToUpdate.getQtaCol(), + totalQtaAvailable, + totalNumCnfAvailable, + qtaCnfAvailable, + null, + null, + null, + mtbColrToUpdate.getPartitaMag(), + mtbColrToUpdate.getDataScadPartita(), + false, + false, + false); - } - - this.sendOnItemDispatched( - pickingObjectDTO, - pickingObjectDTO.getMtbAart(), - mtbColrToUpdate.getNumCnf(), - mtbColrToUpdate.getQtaCnf(), - mtbColrToUpdate.getQtaCol(), - totalQtaAvailable, - totalNumCnfAvailable, - qtaCnfAvailable, - null, - null, - null, - mtbColrToUpdate.getPartitaMag(), - mtbColrToUpdate.getDataScadPartita(), - false, - false, - false, - (pickedQuantityDTO, shouldCloseLU) -> { - if (pickedQuantityDTO == null) { - this.sendOnLoadingEnded(); - return; - } - - this.saveEditedRow(mtbColrToUpdate, - pickedQuantityDTO.getNumCnf(), - pickedQuantityDTO.getQtaCnf(), - pickedQuantityDTO.getQtaTot(), - pickedQuantityDTO.getPartitaMag(), - pickedQuantityDTO.getDataScad(), - shouldCloseLU); - }); - - - }); - } - - - private void saveEditedRow(MtbColr mtbColrToUpdate, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) { - - this.sendOnLoadingStarted(); - - - MtbColt mtbColt = new MtbColt() - .setNumCollo(mtbColrToUpdate.getNumCollo()) - .setDataCollo(mtbColrToUpdate.getDataColloS()) - .setSerCollo(mtbColrToUpdate.getSerCollo()) - .setGestione(mtbColrToUpdate.getGestione()) - .setMtbColr(new ObservableArrayList<>()); - mtbColt.setOperation(CommonModelConsts.OPERATION.NO_OP); - - final MtbColr mtbColr = (MtbColr) mtbColrToUpdate.clone(); - mtbColr.setOperation(CommonModelConsts.OPERATION.UPDATE); - mtbColr - .setNumCnf(numCnf) - .setQtaCnf(qtaCnf) - .setQtaCol(qtaTot) - .setPartitaMag(partitaMag) - .setDataScadPartita(dataScad) - .setDatetimeRow(UtilityDate.getDateInstance()); - - mtbColt.getMtbColr().add(mtbColr); - - this.mColliMagazzinoRESTConsumer.saveCollo(mtbColt, (value) -> { - - mtbColr.setNumCnf(numCnf) - .setQtaCnf(qtaCnf) - .setQtaCol(qtaTot); - - this.mCurrentMtbColt.getMtbColr().remove(mtbColrToUpdate); - this.mCurrentMtbColt.getMtbColr().add(mtbColr); - - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); - - }, this::sendError); - } - - - public void deleteRow(MtbColr mtbColrToDelete) { - this.sendMtbColrDeleteRequest(shouldDelete -> { - if (shouldDelete) { - this.sendOnLoadingStarted(); - - MtbColt mtbColt = new MtbColt() - .setNumCollo(mtbColrToDelete.getNumCollo()) - .setDataCollo(mtbColrToDelete.getDataColloS()) - .setSerCollo(mtbColrToDelete.getSerCollo()) - .setGestione(mtbColrToDelete.getGestione()) - .setMtbColr(new ObservableArrayList<>()); - mtbColt.setOperation(CommonModelConsts.OPERATION.NO_OP); - - MtbColr mtbColr = (MtbColr) mtbColrToDelete.clone(); - - mtbColr.setOperation(CommonModelConsts.OPERATION.DELETE); - mtbColt.getMtbColr().add(mtbColr); - - this.mColliMagazzinoRESTConsumer.saveCollo(mtbColt, (value) -> { - this.mCurrentMtbColt.getMtbColr().remove(mtbColrToDelete); - - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); - - }, this::sendError); - } - }); - } - - - public void closeLU(Runnable onComplete) { - if (mCurrentMtbColt == null) { - if (onComplete != null) onComplete.run(); + if (pickedQuantityDTO == null) { return; } this.sendOnLoadingStarted(); - this.mDefaultCommessa = null; - - mColliMagazzinoRESTConsumer.canULBeDeleted(mCurrentMtbColt, canBeDeleted -> { - if (canBeDeleted) { - deleteLU(() -> { - if (mMtbColtSessionID != null) - this.mColliDataRecoverService.closeSession(mMtbColtSessionID); - - this.sendLUClosed(); - this.sendOnLoadingEnded(); - - this.mCurrentMtbColt = null; - if (onComplete != null) onComplete.run(); - }); - } else { - - this.mColliMagazzinoRESTConsumer.assegnaLottoSuColloScarico(mCurrentMtbColt, () -> { - - var closeUDSRequest = new CloseUDSRequestDTO() - .setMtbColt(mCurrentMtbColt); - - if (this.mDefaultGestione == GestioneEnum.LAVORAZIONE && SettingsManager.iDB().isProduzioneGeneraDocScar()) { - - if(SettingsManager.iDB().getInternalCodAnags() == null || SettingsManager.iDB().getInternalCodAnags().isEmpty()) { - this.sendError(new Exception("Nessuna anagrafica aziendale configurata. Assicurarsi di aver abilitato il flag FLAG_USE_COD_ANAG_AZIENDALE.")); - return; - } - - closeUDSRequest - .setCreateDocument(SettingsManager.iDB().isProduzioneGeneraDocScar()) - .setDocumentCodDtip(SettingsManager.iDB().getProduzioneCodDtipScar()) - .setDocumentCodAnag(SettingsManager.iDB().getInternalCodAnags().stream() - .filter(InternalCodAnagsDTO::isFornitore) - .findFirst() - .get() - .getCodAnag()); - } - - this.mColliScaricoRESTConsumer.closeUDS(closeUDSRequest, response -> { - if (mMtbColtSessionID != null) - this.mColliDataRecoverService.closeSession(mMtbColtSessionID); - - this.sendLUClosed(); - this.sendOnLoadingEnded(); - - this.mCurrentMtbColt = null; - if (onComplete != null) onComplete.run(); - }, this::sendError); - }, this::sendError); - } - }, this::sendError); + this.saveEditedRow(mtbColrToUpdate, + pickedQuantityDTO.getNumCnf(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getPartitaMag(), + pickedQuantityDTO.getDataScad(), + pickedQuantityDTO.isShouldCloseLu()); + this.sendOnLoadingEnded(); } - private void deleteLU(Runnable onComplete) { - DeleteULRequestDTO deleteULRequestDTO = new DeleteULRequestDTO() - .setMtbColt(mCurrentMtbColt); - mColliMagazzinoRESTConsumer.deleteUL(deleteULRequestDTO, () -> { + + private void saveEditedRow(MtbColr mtbColrToUpdate, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) throws Exception { + this.sendOnLoadingStarted(); + + MtbColr mtbColrClone = (MtbColr) mtbColrToUpdate.clone(); + mtbColrClone.setMtbAart(null) + .setMtbPartitaMag(null); + + var editUDSRowRequest = new EditUDSRowRequestDTO() + .setSourceMtbColr(mtbColrClone) + .setNewNumCnf(numCnf) + .setNewQtaCnf(qtaCnf) + .setNewQtaTot(qtaTot); + + mColliScaricoRESTConsumer.editUDSRowSynchronized(editUDSRowRequest); + + mtbColrToUpdate.setNumCnf(numCnf) + .setQtaCnf(qtaCnf) + .setQtaCol(qtaTot); + + handler.post(() -> { + this.mCurrentMtbColt.getMtbColr().remove(mtbColrToUpdate); + this.mCurrentMtbColt.getMtbColr().add(mtbColrToUpdate); + }); + + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); + } + + + public void deleteRow(MtbColr mtbColrToDelete) throws Exception { + var shouldDelete = this.sendMtbColrDeleteRequest(); + if (shouldDelete) { + this.sendOnLoadingStarted(); + + var deleteUdsRowRequest = new DeleteUDSRowRequestDTO() + .setMtbColrToDelete(mtbColrToDelete); + + mColliScaricoRESTConsumer.deleteUDSRowSynchronized(deleteUdsRowRequest); + + handler.post(() -> { + this.mCurrentMtbColt.getMtbColr().remove(mtbColrToDelete); + }); + + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); + } + } + + + public void closeLU() throws Exception { + if (mCurrentMtbColt == null) { + return; + } + + this.mDefaultCommessa = null; + + var canBeDeleted = mColliMagazzinoRESTConsumer.canULBeDeletedSynchronized(mCurrentMtbColt); + + if (canBeDeleted) { + deleteLU(); + + if (mMtbColtSessionID != null) + this.mColliDataRecoverService.closeSession(mMtbColtSessionID); + + this.sendLUClosed(); + this.sendOnLoadingEnded(); + this.mCurrentMtbColt = null; - if (onComplete != null) onComplete.run(); - }, this::sendError); + } else { + this.mColliMagazzinoRESTConsumer.assegnaLottoSuColloScaricoSynchronized(mCurrentMtbColt); + + var closeUDSRequest = new CloseUDSRequestDTO() + .setMtbColt(mCurrentMtbColt); + + if (this.mDefaultGestione == GestioneEnum.LAVORAZIONE && SettingsManager.iDB().isProduzioneGeneraDocScar()) { + + if(SettingsManager.iDB().getInternalCodAnags() == null || SettingsManager.iDB().getInternalCodAnags().isEmpty()) + throw new Exception("Nessuna anagrafica aziendale configurata. Assicurarsi di aver abilitato il flag FLAG_USE_COD_ANAG_AZIENDALE."); + + closeUDSRequest + .setCreateDocument(SettingsManager.iDB().isProduzioneGeneraDocScar()) + .setDocumentCodDtip(SettingsManager.iDB().getProduzioneCodDtipScar()) + .setDocumentCodAnag(SettingsManager.iDB().getInternalCodAnags().stream() + .filter(InternalCodAnagsDTO::isFornitore) + .findFirst() + .get() + .getCodAnag()); + } + + var response = this.mColliScaricoRESTConsumer.closeUDSSynchronized(closeUDSRequest); + + if (mMtbColtSessionID != null) + this.mColliDataRecoverService.closeSession(mMtbColtSessionID); + + this.sendLUClosed(); + + this.mCurrentMtbColt = null; + } + + } + + private void deleteLU() throws Exception { + DeleteULRequestDTO deleteULRequestDTO = new DeleteULRequestDTO() + .setMtbColt(mCurrentMtbColt); + + mColliMagazzinoRESTConsumer.deleteULSynchronized(deleteULRequestDTO); + + this.mCurrentMtbColt = null; } @@ -1008,20 +915,61 @@ public class PickingLiberoViewModel { if (this.mListener != null) mListener.onLUClosed(); } - private void sendMtbColrDeleteRequest(RunnableArgs onComplete) { - if (this.mListener != null) mListener.onMtbColrDeleteRequest(onComplete); + private Boolean sendMtbColrDeleteRequest() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + if (this.mListener != null) mListener.onMtbColrDeleteRequest(data -> { + result.set(data); + countDownLatch.countDown(); + }); + else countDownLatch.countDown(); + + countDownLatch.await(); + return result.get(); } - private void sendLUClienteRequired(RunnableArgss onComplete, Runnable onAbort) { - if (this.mListener != null) mListener.onLUClienteRequired(onComplete, onAbort); + private Pair sendLUClienteRequired() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + AtomicReference> result = new AtomicReference<>(); + + + if (this.mListener != null) mListener.onLUClienteRequired((vtbDest, codJcom) -> { + result.set(new Pair<>(vtbDest, codJcom)); + countDownLatch.countDown(); + }, countDownLatch::countDown); + else countDownLatch.countDown(); + + countDownLatch.await(); + return result.get(); } - private void sendLULineaProdRequired(RunnableArgs onComplete, Runnable onAbort) { - if (this.mListener != null) mListener.onLULineaProdRequired(onComplete, onAbort); + private DialogAskLineaProdResponse sendLULineaProdRequired() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + if (this.mListener != null) mListener.onLULineaProdRequired(data -> { + result.set(data); + countDownLatch.countDown(); + }, countDownLatch::countDown); + else countDownLatch.countDown(); + + countDownLatch.await(); + return result.get(); } - private void sendLUCommessaRequired(RunnableArgs onComplete, Runnable onAbort) { - if (this.mListener != null) mListener.onLUCommessaRequired(onComplete, onAbort); + private JtbComt sendLUCommessaRequired() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + if (this.mListener != null) mListener.onLUCommessaRequired(data -> { + result.set(data); + countDownLatch.countDown(); + }, countDownLatch::countDown); + else countDownLatch.countDown(); + + countDownLatch.await(); + return result.get(); } private List sendArtSelectionRequest(List mtbColrsToPick, MtbAart mtbAart) throws InterruptedException { @@ -1036,28 +984,30 @@ public class PickingLiberoViewModel { }, countDownLatch::countDown); else countDownLatch.countDown(); - countDownLatch.await(); return result.get(); } - private void sendOnItemDispatched(PickingObjectDTO pickingObjectDTO, - MtbAart mtbAart, - BigDecimal initialNumCnf, - BigDecimal initialQtaCnf, - BigDecimal initialQtaTot, - BigDecimal totalQtaAvailable, - BigDecimal totalNumCnfAvailable, - BigDecimal qtaCnfAvailable, - BigDecimal totalQtaToBeTaken, - BigDecimal totalNumCnfToBeTaken, - BigDecimal qtaCnfToBeTaken, - String partitaMag, - LocalDate dataScad, - boolean canOverflowOrderQuantity, - boolean canPartitaMagBeChanged, - boolean canLUBeClosed, - RunnableArgss onComplete) { + private PickedQuantityDTO sendOnItemDispatched(PickingObjectDTO pickingObjectDTO, + MtbAart mtbAart, + BigDecimal initialNumCnf, + BigDecimal initialQtaCnf, + BigDecimal initialQtaTot, + BigDecimal totalQtaAvailable, + BigDecimal totalNumCnfAvailable, + BigDecimal qtaCnfAvailable, + BigDecimal totalQtaToBeTaken, + BigDecimal totalNumCnfToBeTaken, + BigDecimal qtaCnfToBeTaken, + String partitaMag, + LocalDate dataScad, + boolean canOverflowOrderQuantity, + boolean canPartitaMagBeChanged, + boolean canLUBeClosed) throws InterruptedException { + + + CountDownLatch countDownLatch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); if (this.mListener != null) mListener.onItemDispatched(pickingObjectDTO, mtbAart, @@ -1075,7 +1025,17 @@ public class PickingLiberoViewModel { canOverflowOrderQuantity, canPartitaMagBeChanged, canLUBeClosed, - onComplete); + pickedQuantityDTO -> { + if (pickedQuantityDTO != null) { + result.set(pickedQuantityDTO); + } + + countDownLatch.countDown(); + }); + + + countDownLatch.await(); + return result.get(); } private void sendOnRowSaved() { @@ -1115,7 +1075,7 @@ public class PickingLiberoViewModel { boolean canOverflowOrderQuantity, boolean canPartitaMagBeChanged, boolean canLUBeClosed, - RunnableArgss onComplete); + RunnableArgs onComplete); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/picking_resi/PickingResiActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_resi/PickingResiActivity.java index ed13e91d..1acacb2f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/picking_resi/PickingResiActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/picking_resi/PickingResiActivity.java @@ -79,7 +79,7 @@ public class PickingResiActivity extends BaseActivity implements BottomSheetFrag private String mTitle; private List mDocumentiResiList; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private boolean mShouldCloseActivity; @@ -150,10 +150,10 @@ public class PickingResiActivity extends BaseActivity implements BottomSheetFrag this.mBindings.bottomSheetLuContent.collapse(); } else if (!noLUPresent.get()) { this.mShouldCloseActivity = true; - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); this.mViewmodel.closeLU(true); } else { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } } @@ -166,7 +166,7 @@ public class PickingResiActivity extends BaseActivity implements BottomSheetFrag } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(this, ex, false))); } @@ -301,7 +301,7 @@ public class PickingResiActivity extends BaseActivity implements BottomSheetFrag UtilityExceptions.defaultException(this, ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @Override @@ -332,7 +332,12 @@ public class PickingResiActivity extends BaseActivity implements BottomSheetFrag if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if(resultDTO == null || resultDTO.isAborted()) { + this.mViewmodel.resetMatchedRows(); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) @@ -341,7 +346,7 @@ public class PickingResiActivity extends BaseActivity implements BottomSheetFrag .setDataScad(resultDTO.getDataScad()); this.onLoadingStarted(); - onComplete.run(pickedQuantityDTO, shouldCloseLU); + onComplete.run(pickedQuantityDTO, resultDTO.isShouldCloseLu()); }) .setOnAbort(() -> { this.mViewmodel.resetMatchedRows(); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaActivity.java index 1159deb0..20be0869 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaActivity.java @@ -56,7 +56,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett public final BindableString productDescription = new BindableString(); private Runnable onResumeRunnable = null; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; @Inject ProdDettaglioLineaViewModel mViewModel; @@ -152,7 +152,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett @Override public void onSettingsRequest(ProdLineStatusDTO lineaProd) { - BottomSheetLineAction.newInstance(lineaProd, this::requestResources, this::requestOrderChange, this::requestProductionStop, this::requestMaterialRecover, BarcodeManager::enable).show(getSupportFragmentManager(), "BottomSheetLineAction"); + BottomSheetLineAction.newInstance(lineaProd, this::requestResources, this::requestOrderChange, this::requestProductionStop, this::requestMaterialRecover, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)).show(getSupportFragmentManager(), "BottomSheetLineAction"); } @Override @@ -166,7 +166,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett onConfirm, () -> { onLoadingEnded(); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } ).show(getSupportFragmentManager(), "confirmOrderClose"); }); @@ -196,7 +196,12 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett onLoadingEnded(); mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + + if(resultDTO == null || resultDTO.isAborted()) { + this.onLoadingEnded(); + return; + } PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) @@ -220,17 +225,17 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } public void requestResources() { this.onLoadingEnded(); - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); this.runOnUiThread(() -> { @@ -242,7 +247,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett } catch (NumberFormatException ex) { this.onError(new Exception("Inserire un numero di risorse valido")); } - }, BarcodeManager::enable, InputType.TYPE_CLASS_NUMBER).show(); + }, () -> BarcodeManager.enable(mBarcodeScannerInstanceID), InputType.TYPE_CLASS_NUMBER).show(); }); } @@ -257,7 +262,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett public void requestProductionStop() { this.onLoadingEnded(); - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); ProdLineStatusDTO lineaProd = mViewModel.getLineaProd(); if (UtilityString.isNullOrEmpty(lineaProd.getListaOrd())) { mViewModel.stopProduction(); @@ -272,7 +277,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett public void requestMaterialRecover() { this.onLoadingEnded(); - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); this.runOnUiThread(() -> { getSupportFragmentManager() .beginTransaction() @@ -288,7 +293,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett @Override public void successDialog(String message, Runnable onComplete) { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); this.runOnUiThread(() -> DialogSimpleMessageView.makeSuccessDialog(getResources().getString(R.string.success), new SpannableString(message), null, onComplete).show(getSupportFragmentManager(), "successDialog")); @@ -296,10 +301,9 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett } @Override - public void showToast(String message, Runnable onComplete) { + public void showToast(String message) { this.runOnUiThread(() -> { UtilityToast.showToast(message); - onComplete.run(); }); } @@ -332,7 +336,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett onConfirm ).show(getSupportFragmentManager(), "confirmOrderClose"); }, - BarcodeManager::enable + () -> BarcodeManager.enable(mBarcodeScannerInstanceID) ).show(getSupportFragmentManager(), "confirmOrderClose"); }); } @@ -348,7 +352,7 @@ public class ProdDettaglioLineaActivity extends BaseActivity implements ProdDett if (count > 0) { getSupportFragmentManager().popBackStack(); } else { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaViewModel.java index adc601d1..8692cc0a 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/ProdDettaglioLineaViewModel.java @@ -5,7 +5,6 @@ import androidx.lifecycle.MutableLiveData; import javax.inject.Inject; import it.integry.barcode_base_android_library.model.BarcodeScanDTO; -import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager; import it.integry.integrywmsnative.core.exception.NoLUFoundException; import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener; @@ -91,7 +90,7 @@ public class ProdDettaglioLineaViewModel { this.colliMagazzinoRESTConsumer.createColloScaricoDaCarico(mtbColt, posizione, generatedMtbColt -> { this.sendOnLoadingEnded(); - this.mListener.showToast("Versamento completato!", BarcodeManager::enable); + this.mListener.showToast("Versamento completato!"); }, this::sendError); }); }); @@ -221,7 +220,7 @@ public class ProdDettaglioLineaViewModel { void successDialog(String message, Runnable onComplete); - void showToast(String message, Runnable onComplete); + void showToast(String message); void requestQtaVersamento(MtbColr mtbColr, RunnableArgs onComplete); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogRecoverUl.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogRecoverUl.java index 6a1c292a..e21633ed 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogRecoverUl.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogRecoverUl.java @@ -20,7 +20,7 @@ import it.integry.integrywmsnative.core.utility.UtilityBarcode; import it.integry.integrywmsnative.databinding.DialogStartProductionBinding; public class DialogRecoverUl extends BaseDialogFragment { - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private RunnableArgs onScanSuccessful; private DialogStartProductionBinding mBinding; @@ -37,7 +37,7 @@ public class DialogRecoverUl extends BaseDialogFragment { @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onDismiss(dialog); } @@ -60,10 +60,10 @@ public class DialogRecoverUl extends BaseDialogFragment { private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(this::processBarcode) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private void processBarcode(BarcodeScanDTO barcodeScanDTO) { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogStartProduction.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogStartProduction.java index 6f2d2eb7..c66a88b3 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogStartProduction.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_dettaglio_linea/dialogs/DialogStartProduction.java @@ -21,7 +21,7 @@ import it.integry.integrywmsnative.core.utility.UtilityString; import it.integry.integrywmsnative.databinding.DialogStartProductionBinding; public class DialogStartProduction extends BaseDialogFragment { - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private RunnableArgs onScanSuccessful; private DialogStartProductionBinding mBinding; private String title; @@ -57,7 +57,7 @@ public class DialogStartProduction extends BaseDialogFragment { @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onDismiss(dialog); } @@ -88,10 +88,10 @@ public class DialogStartProduction extends BaseDialogFragment { private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(this::processBarcode) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private void processBarcode(BarcodeScanDTO barcodeScanDTO) { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneFragment.java index b1d20c34..ce06cf2a 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneFragment.java @@ -41,7 +41,7 @@ public class ProdLineeProduzioneFragment extends BaseFragment implements ITitled private final ObservableArrayList mLinesObservableList = new ObservableArrayList<>(); private FragmentLineeProdBinding mBinding; private ElevatedToolbar mToolbar; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; public static ProdLineeProduzioneFragment newInstance() { return new ProdLineeProduzioneFragment(); @@ -73,7 +73,7 @@ public class ProdLineeProduzioneFragment extends BaseFragment implements ITitled private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); } @@ -112,7 +112,7 @@ public class ProdLineeProduzioneFragment extends BaseFragment implements ITitled public void requestResources(ProdLineStatusDTO prodLine) { this.onLoadingEnded(); - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); requireActivity().runOnUiThread(() -> { DialogSimpleInputHelper.makeInputDialog(requireContext(), "Inserisci il numero di risorse da allocare", prodLine.getQtaAllocate().toString(), "n. risorse", qta -> { @@ -123,13 +123,13 @@ public class ProdLineeProduzioneFragment extends BaseFragment implements ITitled } catch (NumberFormatException ex) { this.onError(new Exception("Inserire un numero di risorse valido")); } - }, BarcodeManager::enable, InputType.TYPE_CLASS_NUMBER).show(); + }, () -> BarcodeManager.enable(mBarcodeScannerInstanceID), InputType.TYPE_CLASS_NUMBER).show(); }); } @Override public void successDialog(String message, Runnable onComplete) { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); requireActivity().runOnUiThread(() -> DialogSimpleMessageView.makeSuccessDialog(getResources().getString(R.string.success), new SpannableString(message), null, onComplete).show(getChildFragmentManager(), "successDialog")); @@ -138,7 +138,7 @@ public class ProdLineeProduzioneFragment extends BaseFragment implements ITitled @Override public void selectLine(ProdLineStatusDTO dto) { this.onLoadingEnded(); - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); if (!dto.isStarted()) { this.requestResources(dto); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneViewModel.java index 326c8ed2..c4d8fb35 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_linee_produzione/ProdLineeProduzioneViewModel.java @@ -34,9 +34,9 @@ public class ProdLineeProduzioneViewModel { private void reloadLines() { sendOnLoadingStarted(); - BarcodeManager.disable(); + BarcodeManager.disableLastCallback(); this.productionLinesRESTConsumer.getStatoLinee(SettingsManager.i().getUserSession().getDepo().getCodMdep(), lineeProdList -> { - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); prodLines.postValue(lineeProdList); this.sendOnLoadingEnded(); }, this::sendError); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_recupero_materiale/ProdRecuperoMaterialeFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_recupero_materiale/ProdRecuperoMaterialeFragment.java index 7999621e..2a0eefeb 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_recupero_materiale/ProdRecuperoMaterialeFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_recupero_materiale/ProdRecuperoMaterialeFragment.java @@ -56,7 +56,7 @@ public class ProdRecuperoMaterialeFragment extends BaseFragment implements ITitl private FragmentProdRecuperoMaterialeBinding mBinding; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private String codJfas; private String fragmentResultKeyString; @@ -118,8 +118,8 @@ public class ProdRecuperoMaterialeFragment extends BaseFragment implements ITitl public void onStart() { super.onStart(); this.addOnPreDestroy(() -> { - if (barcodeScannerIstanceID > -1) { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + if (mBarcodeScannerInstanceID > -1) { + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); } }); mViewModel.init(codJfas); @@ -133,11 +133,11 @@ public class ProdRecuperoMaterialeFragment extends BaseFragment implements ITitl private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } public String getCodJfas() { @@ -248,7 +248,12 @@ public class ProdRecuperoMaterialeFragment extends BaseFragment implements ITitl if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if(resultDTO == null || resultDTO.isAborted()) { + this.onLoadingEnded(); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/ProdRientroMerceFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/ProdRientroMerceFragment.java index 372fff5a..9bebfab1 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/ProdRientroMerceFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/ProdRientroMerceFragment.java @@ -212,13 +212,13 @@ public class ProdRientroMerceFragment extends BaseFragment implements @Override public void onOrderLoadingStarted() { - BarcodeManager.disable(); + BarcodeManager.disableLastCallback(); this.mProdRientroMerceOrderListFragment.onOrderLoadingStarted(); } @Override public void onOrderLoadingEnded() { - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); this.mProdRientroMerceOrderListFragment.onOrderLoadingEnded(); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/order_list/ProdRientroMerceOrderListFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/order_list/ProdRientroMerceOrderListFragment.java index 3a956920..c64dec63 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/order_list/ProdRientroMerceOrderListFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_rientro_merce/order_list/ProdRientroMerceOrderListFragment.java @@ -278,7 +278,7 @@ public class ProdRientroMerceOrderListFragment extends Fragment { requireActivity().runOnUiThread(() -> { onOrderLoadingEnded(); UtilityExceptions.defaultException(getActivity(), ex); - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_riposizionamento_da_prod/ProdRiposizionamentoDaProdFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_riposizionamento_da_prod/ProdRiposizionamentoDaProdFragment.java index ec00ecf6..753c9614 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_riposizionamento_da_prod/ProdRiposizionamentoDaProdFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_riposizionamento_da_prod/ProdRiposizionamentoDaProdFragment.java @@ -55,7 +55,7 @@ public class ProdRiposizionamentoDaProdFragment extends BaseFragment implements private ProdRiposizionamentoDaProdFilterViewModel mFilterViewModel = new ProdRiposizionamentoDaProdFilterViewModel(); private final Handler mHandler = new Handler(); private final int mInterval = 120 * 1000; //2 minuti - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private AppCompatTextView mAppBarTitle; private String mTextFilter; @@ -220,7 +220,7 @@ public class ProdRiposizionamentoDaProdFragment extends BaseFragment implements public void onInfoClick(ArtsInGiacenzaDTO item) { try { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); DialogInfoGiacenzaView.newInstance(item).show(getChildFragmentManager(), DialogInfoGiacenzaView.class.getName()); } catch (Exception e) { UtilityExceptions.defaultException(this.getContext(), e); @@ -237,11 +237,11 @@ public class ProdRiposizionamentoDaProdFragment extends BaseFragment implements }; private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private final RunnableArgs onScanSuccessful = data -> { @@ -310,7 +310,7 @@ public class ProdRiposizionamentoDaProdFragment extends BaseFragment implements @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); mHandler.removeCallbacks(mRunnable); mViewModel.setListener(null); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeFragment.java index 3aefbe32..3b00ea87 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeFragment.java @@ -23,6 +23,7 @@ import java.util.List; import javax.inject.Inject; +import it.integry.barcode_base_android_library.model.BarcodeScanDTO; import it.integry.integrywmsnative.MainApplication; import it.integry.integrywmsnative.R; import it.integry.integrywmsnative.core.barcode_reader.BarcodeCallbackDTO; @@ -75,7 +76,7 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro public final ObservableField fabVisible = new ObservableField<>(false); - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; public ProdVersamentoMaterialeFragment() { // Required empty public constructor @@ -193,13 +194,27 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() - .setOnScanSuccessful(mViewModel::processBarcodeDTO) + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } + private final RunnableArgs onScanSuccessful = data -> { + this.onLoadingStarted(); + + executorService.execute(() -> { + try { + this.mViewModel.processBarcodeDTO(data); + } catch (Exception e) { + onError(e); + } + }); + + this.onLoadingEnded(); + }; + // private void openLU() { // DialogScanOrCreateLUView.newInstance(false, false, true, false, true, (mtbColt, created) -> { // if (mtbColt == null) { @@ -223,13 +238,14 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro // }).show(requireActivity().getSupportFragmentManager(), "tag"); // } - private void choosePosition(RunnableArgs onComplete) { + private void choosePosition(RunnableArgss onComplete) { DialogAskPositionOfLUView.newInstance(false, (status, mtbDepoPosizione) -> { if (status == DialogConsts.Results.ABORT) { + onComplete.run(false, null); popMe(); } else { - onComplete.run(mtbDepoPosizione); + onComplete.run(true, mtbDepoPosizione); } }) @@ -359,7 +375,7 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro } @Override - public void onRequestChoosePosition(RunnableArgs onComplete) { + public void onRequestChoosePosition(RunnableArgss onComplete) { choosePosition(onComplete); } @@ -383,7 +399,12 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View.setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if(resultDTO == null || resultDTO.isAborted()) { + this.onLoadingEnded(); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) @@ -392,7 +413,7 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro .setDataScad(resultDTO.getDataScad()); this.onLoadingStarted(); - onComplete.run(pickedQuantityDTO, shouldCloseLU); + onComplete.run(pickedQuantityDTO, resultDTO.isShouldCloseLu()); }) .setOnAbort(this::onLoadingEnded) .show(requireActivity().getSupportFragmentManager(), "tag"); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeModule.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeModule.java index 694b6879..f4c88e0a 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeModule.java @@ -6,6 +6,7 @@ import it.integry.integrywmsnative.core.rest.consumers.ArticoloRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.BarcodeRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.ColliLavorazioneRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.ColliMagazzinoRESTConsumer; +import it.integry.integrywmsnative.core.rest.consumers.MaterialiRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.MesRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.PosizioniRESTConsumer; @@ -18,8 +19,9 @@ public class ProdVersamentoMaterialeModule { ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer, MesRESTConsumer mesRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, - ArticoloRESTConsumer articoloRESTConsumer) { - return new ProdVersamentoMaterialeViewModel(posizioniRESTConsumer, colliMagazzinoRESTConsumer, colliLavorazioneRESTConsumer, mesRESTConsumer, barcodeRESTConsumer, articoloRESTConsumer); + ArticoloRESTConsumer articoloRESTConsumer, + MaterialiRESTConsumer materialiRESTConsumer) { + return new ProdVersamentoMaterialeViewModel(posizioniRESTConsumer, colliMagazzinoRESTConsumer, colliLavorazioneRESTConsumer, mesRESTConsumer, barcodeRESTConsumer, articoloRESTConsumer, materialiRESTConsumer); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeViewModel.java index bd75077e..8ec4a251 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/prod_versamento_materiale/ProdVersamentoMaterialeViewModel.java @@ -1,8 +1,8 @@ package it.integry.integrywmsnative.gest.prod_versamento_materiale; -import androidx.lifecycle.MutableLiveData; +import android.util.Pair; -import com.annimon.stream.Stream; +import androidx.lifecycle.MutableLiveData; import org.jetbrains.annotations.NotNull; @@ -10,15 +10,16 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.util.Iterator; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; import javax.inject.Inject; import it.integry.barcode_base_android_library.model.BarcodeScanDTO; -import it.integry.integrywmsnative.core.exception.InvalidCodMdepLUException; +import it.integry.integrywmsnative.core.exception.InvalidCodMdepException; import it.integry.integrywmsnative.core.exception.NoLUFoundException; import it.integry.integrywmsnative.core.exception.NoResultFromBarcodeException; import it.integry.integrywmsnative.core.exception.TooManyLUFoundInMonoLUPositionException; -import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.expansion.RunnableArgss; import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener; import it.integry.integrywmsnative.core.model.MtbAart; @@ -30,6 +31,7 @@ import it.integry.integrywmsnative.core.rest.consumers.ArticoloRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.BarcodeRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.ColliLavorazioneRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.ColliMagazzinoRESTConsumer; +import it.integry.integrywmsnative.core.rest.consumers.MaterialiRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.MesRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.PosizioniRESTConsumer; import it.integry.integrywmsnative.core.rest.model.Ean128Model; @@ -50,6 +52,7 @@ public class ProdVersamentoMaterialeViewModel { private final MesRESTConsumer mMesRESTConsumer; private final BarcodeRESTConsumer mBarcodeRESTConsumer; private final ArticoloRESTConsumer mArticoloRESTConsumer; + private final MaterialiRESTConsumer mMaterialiRESTConsumer; private boolean mFlagVersamentoDirettoProduzione; @@ -66,13 +69,15 @@ public class ProdVersamentoMaterialeViewModel { ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer, MesRESTConsumer mesRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, - ArticoloRESTConsumer articoloRESTConsumer) { + ArticoloRESTConsumer articoloRESTConsumer, + MaterialiRESTConsumer mMaterialiRESTConsumer) { this.mPosizioniRESTConsumer = posizioniRESTConsumer; this.mColliMagazzinoRESTConsumer = colliMagazzinoRESTConsumer; this.mColliLavorazioneRESTConsumer = colliLavorazioneRESTConsumer; this.mMesRESTConsumer = mesRESTConsumer; this.mBarcodeRESTConsumer = barcodeRESTConsumer; this.mArticoloRESTConsumer = articoloRESTConsumer; + this.mMaterialiRESTConsumer = mMaterialiRESTConsumer; } @@ -81,7 +86,7 @@ public class ProdVersamentoMaterialeViewModel { } - public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO) { + public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO) throws Exception { if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)) { this.executeEtichettaPosizione(barcodeScanDTO); } else if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { @@ -94,93 +99,91 @@ public class ProdVersamentoMaterialeViewModel { } - private void executeEtichettaPosizione(BarcodeScanDTO barcodeScanDTO) { - - MtbDepoPosizione foundPosizione = Stream.of(SettingsManager.iDB().getAvailablePosizioni()) + private void executeEtichettaPosizione(BarcodeScanDTO barcodeScanDTO) throws Exception { + MtbDepoPosizione foundPosizione = SettingsManager.iDB().getAvailablePosizioni().stream() .filter(x -> x.getPosizione().equalsIgnoreCase(barcodeScanDTO.getStringValue())) - .single(); + .findFirst() + .orElse(null); + this.executePosizione(foundPosizione); - } - private void executePosizione(MtbDepoPosizione posizione) { - this.mPosizioniRESTConsumer.getBancaliInPosizione(posizione, mtbColtList -> { - - if (mtbColtList == null || mtbColtList.isEmpty()) { - this.sendError(new NoLUFoundException()); - } else if (mtbColtList.size() == 1) { - this.mColliMagazzinoRESTConsumer.getByTestata(mtbColtList.get(0), true, false, mtbColt -> { - - boolean codMdepIsValid = Stream.of(SettingsManager.iDB().getAvailableCodMdep()) - .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - - if (codMdepIsValid) { - this.onLUOpened(mtbColt); - } else this.sendError(new InvalidCodMdepLUException()); - - }, this::sendError); - } else { - this.sendError(new TooManyLUFoundInMonoLUPositionException()); - } - - }, this::sendError); - } + private void executePosizione(MtbDepoPosizione posizione) throws Exception { + var mtbColtList = this.mPosizioniRESTConsumer.getBancaliInPosizioneSynchronized(posizione); - private void executeEtichettaLU(String sscc) { - this.mColliMagazzinoRESTConsumer.getBySSCC(sscc, true, false, mtbColt -> { + if (mtbColtList == null || mtbColtList.isEmpty()) { + this.sendError(new NoLUFoundException()); + } else if (mtbColtList.size() == 1) { + var mtbColt = this.mColliMagazzinoRESTConsumer.getByTestataSynchronized(mtbColtList.get(0), true, false); - boolean codMdepIsValid = Stream.of(SettingsManager.iDB().getAvailableCodMdep()) + boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); if (codMdepIsValid) { this.onLUOpened(mtbColt); - } else this.sendError(new InvalidCodMdepLUException()); + } else + throw new InvalidCodMdepException(); - }, this::sendError); + } else + throw new TooManyLUFoundInMonoLUPositionException(); } - private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO) { - mBarcodeRESTConsumer.decodeEan128(barcodeScanDTO, ean128Model -> { + private void executeEtichettaLU(String sscc) throws Exception { + var mtbColt = this.mColliMagazzinoRESTConsumer.getBySsccSynchronized(sscc, true, false); - String barcodeProd = null; + boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) barcodeProd = ean128Model.Sscc; - if (!UtilityString.isNullOrEmpty(ean128Model.Gtin)) barcodeProd = ean128Model.Gtin; - if (!UtilityString.isNullOrEmpty(ean128Model.Content)) - barcodeProd = ean128Model.Content; - - - if (!UtilityString.isNullOrEmpty(barcodeProd)) { - - if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) { - this.executeEtichettaLU(ean128Model.Sscc); - } else if (!UtilityString.isNullOrEmpty(barcodeProd)) { - this.loadArticolo(barcodeProd, ean128Model); - } else { - this.sendError(new NoLUFoundException()); - } - - - } else { - //EAN 128 non completo o comunque mancano i riferimenti al prodotto - this.sendError(new NoLUFoundException()); - } - }, this::sendError); + if (codMdepIsValid) { + this.onLUOpened(mtbColt); + } else + throw new InvalidCodMdepException(); } - private void loadArticolo(String barcodeProd, Ean128Model ean128Model) { - mArticoloRESTConsumer.searchByBarcode(barcodeProd, mtbAartList -> { - if (mtbAartList != null && !mtbAartList.isEmpty()) { - MtbAart articolo = mtbAartList.get(0); - this.dispatchArt(articolo, ean128Model); - } else { - this.sendError(new NoResultFromBarcodeException(barcodeProd)); - } + private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO) throws Exception { + var ean128Model = mBarcodeRESTConsumer.decodeEan128Synchronized(barcodeScanDTO); + + String barcodeProd = null; + + if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) barcodeProd = ean128Model.Sscc; + if (!UtilityString.isNullOrEmpty(ean128Model.Gtin)) barcodeProd = ean128Model.Gtin; + if (!UtilityString.isNullOrEmpty(ean128Model.Content)) + barcodeProd = ean128Model.Content; + + + if (!UtilityString.isNullOrEmpty(barcodeProd)) { + + if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) { + this.executeEtichettaLU(ean128Model.Sscc); + + } else if (!UtilityString.isNullOrEmpty(barcodeProd)) { + this.loadArticolo(barcodeProd, ean128Model); + + } else + throw new NoLUFoundException(); + + } else + //EAN 128 non completo o comunque mancano i riferimenti al prodotto + throw new NoLUFoundException(); + + + } + + private void loadArticolo(String barcodeProd, Ean128Model ean128Model) throws Exception { + var mtbAartList = mArticoloRESTConsumer.searchByBarcodeSynchronized(barcodeProd); + + if (mtbAartList != null && !mtbAartList.isEmpty()) { + MtbAart articolo = mtbAartList.get(0); + this.dispatchArt(articolo, ean128Model); + + } else { + throw new NoResultFromBarcodeException(barcodeProd); + } + - }, this::sendError); } @@ -261,8 +264,6 @@ public class ProdVersamentoMaterialeViewModel { } - - this.sendOnItemDispatched( pickingObjectDTO, mtbAart, @@ -281,39 +282,58 @@ public class ProdVersamentoMaterialeViewModel { true, (pickedQuantityDTO, shouldCloseLU) -> { - this.sendRequestChoosePosition(mtbDepoPosizione -> { + var changePosizioneResult = this.sendRequestChoosePosition(); + + if (changePosizioneResult == null || !changePosizioneResult.first) { + return; + } + + mColliLavorazioneRESTConsumer.createColloScaricoDaArticolo(mtbAart, + pickedQuantityDTO.getPartitaMag(), + changePosizioneResult.second, + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getNumCnf(), + null, null, + this::sendOnDataSaved, + this::sendError); - mColliLavorazioneRESTConsumer.createColloScaricoDaArticolo(mtbAart, - pickedQuantityDTO.getPartitaMag(), - mtbDepoPosizione, - pickedQuantityDTO.getQtaTot(), - pickedQuantityDTO.getQtaCnf(), - pickedQuantityDTO.getNumCnf(), - null, null, - this::sendOnDataSaved, - this::sendError); - }); }); } - private void onLUOpened(MtbColt mtbColt) { - this.mtbColtMutableLiveData.setValue(mtbColt); - this.sendRequestChoosePosition(this::setPosizione); + private void onLUOpened(MtbColt mtbColt) throws Exception { + this.mtbColtMutableLiveData.postValue(mtbColt); + var posizioneResult = this.sendRequestChoosePosition(); + + if (posizioneResult == null || !posizioneResult.first) { + return; + } + + this.setPosizione(posizioneResult.second); } - public void setPosizione(MtbDepoPosizione mtbDepoPosizione) { + public void setPosizione(MtbDepoPosizione mtbDepoPosizione) throws Exception { this.mtbDepoPosizioneMutableLiveData.postValue(mtbDepoPosizione); MtbColt mtbColt = mtbColtMutableLiveData.getValue(); this.sendOnLoadingStarted(); + if (mtbDepoPosizione != null && mtbDepoPosizione.isFlagLineaProduzione() && mtbColt != null) { + +// mMaterialiRESTConsumer.makeVersaRequest(new VersaMaterialiRequestDTO() +// .setBarcodeUl(mtbColt.getBarcodeUl()), () -> { +// +// String a = ""; +// +// }, this::sendError); + if (!mFlagVersamentoDirettoProduzione) { createColloScarico(mtbDepoPosizione); } else { - if (mtbColt.getMtbColr() == null || mtbColt.getMtbColr().size() <= 0) { + if (mtbColt.getMtbColr() == null || mtbColt.getMtbColr().isEmpty()) { this.sendWarning("Il collo selezionato non presenta articoli versabili sulla linea.", this::sendRequestLUOpen); return; } else if (mtbColt.getMtbColr().size() > 1) { @@ -344,15 +364,13 @@ public class ProdVersamentoMaterialeViewModel { } } - private void createColloScarico(MtbDepoPosizione mtbDepoPosizione) { - + private void createColloScarico(MtbDepoPosizione mtbDepoPosizione) throws Exception { this.sendOnLoadingStarted(); - this.mColliMagazzinoRESTConsumer.createColloScaricoDaCarico(mtbColtMutableLiveData.getValue(), mtbDepoPosizione, - generatedMtbColt -> { - this.sendOnLoadingEnded(); - this.sendOnDataSaved(); - }, this::sendError); + var generatedMtbColt = this.mColliMagazzinoRESTConsumer.createColloScaricoDaCaricoSynchronized(mtbColtMutableLiveData.getValue(), mtbDepoPosizione); + + this.sendOnLoadingEnded(); + this.sendOnDataSaved(); } @@ -426,8 +444,22 @@ public class ProdVersamentoMaterialeViewModel { if (this.mListener != null) mListener.requestLUOpen(); } - private void sendRequestChoosePosition(RunnableArgs onComplete) { - if (this.mListener != null) mListener.onRequestChoosePosition(onComplete); + private Pair sendRequestChoosePosition() { + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference> result = new AtomicReference<>(); + + if (this.mListener != null) mListener.onRequestChoosePosition((status, data) -> { + result.set(new Pair<>(status, data)); + latch.countDown(); + }); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + return null; } private void sendOnLoadingStarted() { @@ -492,7 +524,7 @@ public class ProdVersamentoMaterialeViewModel { void requestLUOpen(); - void onRequestChoosePosition(RunnableArgs onComplete); + void onRequestChoosePosition(RunnableArgss onComplete); void onItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditActivity.java index e4997378..9c4a655f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditActivity.java @@ -52,7 +52,7 @@ public class PVOrdineAcquistoEditActivity extends BaseActivity implements PVOrdi private static String DATA_KEY_ORDER = "keyOrdine"; private static String DATA_LIST_ARTS = "listArts"; private ActivityPvOrdineAcquistoEditBinding mBinding; - private int barcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; @Inject PVOrdineAcquistoEditViewModel mViewModel; @@ -130,11 +130,11 @@ public class PVOrdineAcquistoEditActivity extends BaseActivity implements PVOrdi } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private void initRecyclerView() { @@ -159,7 +159,7 @@ public class PVOrdineAcquistoEditActivity extends BaseActivity implements PVOrdi private void selectAction(ArticoloOrdine articoloOrdine) { mBinding.closeActivityFab.close(false); - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); DialogAskActionView.newInstance(articoloOrdine.getDescrizione(), articoloOrdine.getQtaOrd() + " " + articoloOrdine.getUntMis(), @@ -168,8 +168,8 @@ public class PVOrdineAcquistoEditActivity extends BaseActivity implements PVOrdi }), () -> { this.deleteArticolo(articoloOrdine); - BarcodeManager.enable(); - }, BarcodeManager::enable).show(getSupportFragmentManager(), "tag"); + BarcodeManager.enable(mBarcodeScannerInstanceID); + }, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)).show(getSupportFragmentManager(), "tag"); } @@ -234,16 +234,16 @@ public class PVOrdineAcquistoEditActivity extends BaseActivity implements PVOrdi @Override public void onBackPressed() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onBackPressed(); } public void manualSearch() { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); DialogSimpleInputHelper.makeInputDialog(this, "Inserisci il codice a barre/codice articolo da cercare", barcode -> { this.onLoadingStarted(); this.mViewModel.processBarcode(barcode); - }, BarcodeManager::enable).show(); + }, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)).show(); } private boolean isOrderNewProdsForced() { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditViewModel.java index 351ac62c..1914cf8e 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/PVOrdineAcquistoEditViewModel.java @@ -157,8 +157,8 @@ public class PVOrdineAcquistoEditViewModel { } public void processBarcode(String barcode) { - Runnable onComplete = BarcodeManager::enable; - BarcodeManager.disable(); + Runnable onComplete = BarcodeManager::enableLastCallback; + BarcodeManager.disableLastCallback(); try { List listArticoli = findArticoliByBarcode(barcode); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/dialog/edit_articolo/DialogEditArticoloView.java b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/dialog/edit_articolo/DialogEditArticoloView.java index 57b17796..cf501fe4 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/dialog/edit_articolo/DialogEditArticoloView.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordine_acquisto_edit/dialog/edit_articolo/DialogEditArticoloView.java @@ -50,7 +50,7 @@ public class DialogEditArticoloView extends BaseDialogFragment implements Dialog private DialogPvEditArticoloBinding mBindings; private boolean mEnableDataCallback = true; - private int barcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; public static DialogEditArticoloView newInstance(ArticoloOrdine articolo, RunnableArgs onComplete, Runnable onAbort) { return new DialogEditArticoloView(articolo, onComplete, onAbort); @@ -117,17 +117,17 @@ public class DialogEditArticoloView extends BaseDialogFragment implements Dialog if (this.mOnAbort != null) { this.mOnAbort.run(); } - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onDismiss(dialog); } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful((barcodeScanDTO) -> { }) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private void initBindings() { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/PVOrdiniAcquistoGrigliaFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/PVOrdiniAcquistoGrigliaFragment.java index ff4633f4..92411937 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/PVOrdiniAcquistoGrigliaFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/PVOrdiniAcquistoGrigliaFragment.java @@ -105,7 +105,7 @@ public class PVOrdiniAcquistoGrigliaFragment extends BaseFragment implements ITi } private void init() { - BarcodeManager.enable(); + BarcodeManager.enableLastCallback(); DialogScanGrigliaAcquistoView.newInstance((griglia, listArticoli) -> { if (griglia == null) { ((IPoppableActivity) requireActivity()).pop(); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/dialogs/DialogScanGrigliaAcquistoView.java b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/dialogs/DialogScanGrigliaAcquistoView.java index 048baa31..c312b106 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/dialogs/DialogScanGrigliaAcquistoView.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/pv_ordini_acquisto/dialogs/DialogScanGrigliaAcquistoView.java @@ -36,7 +36,7 @@ import it.integry.integrywmsnative.databinding.DialogScanCodiceGrigliaBinding; public class DialogScanGrigliaAcquistoView extends BaseDialogFragment { private DialogScanCodiceGrigliaBinding mBinding; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; public boolean canIgnoreGrid; private final RunnableArgss> mOnDialogDismiss; @@ -89,18 +89,18 @@ public class DialogScanGrigliaAcquistoView extends BaseDialogFragment { return; } - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); RunnableArgs mOnError = exception -> { this.onError(exception); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }; retrieveArticoli(null, mOnError); } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); @@ -109,18 +109,18 @@ public class DialogScanGrigliaAcquistoView extends BaseDialogFragment { @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); mOnDialogDismiss.run(mGriglia, mListArticoli); super.onDismiss(dialog); } private final RunnableArgs onScanSuccessfull = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); RunnableArgs mOnError = exception -> { this.onError(exception); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }; retrieveArticoli(data.getStringValue(), mOnError); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/pv_verifica_giacenze/VerificaGiacenzeFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/pv_verifica_giacenze/VerificaGiacenzeFragment.java index 5b2c6f19..d4a3d8a0 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/pv_verifica_giacenze/VerificaGiacenzeFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/pv_verifica_giacenze/VerificaGiacenzeFragment.java @@ -141,13 +141,6 @@ public class VerificaGiacenzeFragment extends BaseFragment implements ITitledFra this.initRecyclerView(); this.initBarcodeReader(); - - - this.onLoadingStarted(); - executorService.execute(() -> { - mViewModel.randomizeElements(2000); - this.onLoadingEnded(); - }); }); } @@ -282,6 +275,7 @@ public class VerificaGiacenzeFragment extends BaseFragment implements ITitledFra .setTotalNumCnfInWarehouse(inWarehouseNumCnf) .setTotalQtaInWarehouse(inWarehouseQtaTot) .setTotalQtaOrd(incomingQtaTot) + .setTotalQtaCnfOrd(initialQtaCnf) .setTotalNumCnfOrd(incomingNumCnf) .setPartitaMag(partitaMag) .setDataScad(dataScad) @@ -291,7 +285,7 @@ public class VerificaGiacenzeFragment extends BaseFragment implements ITitledFra handler.post(() -> { dialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeFragment.java index b559bdf1..749b2792 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeFragment.java @@ -5,6 +5,7 @@ import android.content.pm.ActivityInfo; import android.content.res.ColorStateList; import android.content.res.Resources; import android.os.Bundle; +import android.os.Handler; import android.text.Html; import android.text.SpannableString; import android.view.LayoutInflater; @@ -77,6 +78,9 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr @Inject DialogInputQuantityV2View mDialogInputQuantityV2View; + @Inject + Handler handler; + public BindableBoolean thereIsAnOpenedUL = new BindableBoolean(false); public BindableBoolean thereIsntAnOpenedUL = new BindableBoolean(false); @@ -84,7 +88,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr private RettificaGiacenzeMainListAdapter mAdapter; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private GestioneEnum mCurrentGestione; public RettificaGiacenzeFragment() { @@ -165,7 +169,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); } @@ -325,8 +329,8 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr @Override public void onArtListLoaded(ArrayList artList, RunnableArgs onArtChoosed) { - new DialogChooseArtFromListaArtsView(true, artList, onArtChoosed) - .show(requireActivity().getSupportFragmentManager(), "tag"); + DialogChooseArtFromListaArtsView.newInstance(true, artList, onArtChoosed) + .show(requireActivity().getSupportFragmentManager(), "dialog-choose-art"); } @Override @@ -377,7 +381,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr @Override public void onError(Exception ex) { this.onLoadingEnded(); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); if (ex instanceof InvalidPesoKGException) { UtilityToast.showToast(ex.getMessage()); @@ -432,7 +436,9 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if (resultDTO == null || resultDTO.isAborted()) return; + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) @@ -440,7 +446,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr .setPartitaMag(resultDTO.getPartitaMag()) .setDataScad(resultDTO.getDataScad()); - onComplete.run(pickedQuantityDTO, shouldCloseLU); + onComplete.run(pickedQuantityDTO, resultDTO.isShouldCloseLu()); }) .show(requireActivity().getSupportFragmentManager(), "tag"); }, () -> { @@ -562,7 +568,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr if (mViewModel.getCurrentMtbColt() != null) mViewModel.closeLU(false); else { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); onComplete.run(); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeViewModel.java index 3d5c3c39..36cc1223 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeViewModel.java @@ -475,9 +475,10 @@ public class RettificaGiacenzeViewModel { MtbColt cloneMtbColt = (MtbColt) mCurrentMtbColt.clone(); cloneMtbColt.setOperation(CommonModelConsts.OPERATION.UPDATE); cloneMtbColt.setMtbColr(null); - cloneMtbColt.setPosizione(mtbDepoPosizione != null ? mtbDepoPosizione.getPosizione() : CommonModelConsts.ENTITY_NULL_STRING); - this.mColliMagazzinoRESTConsumer.saveCollo(cloneMtbColt, mtbColt -> onComplete.run(), this::sendError); + this.mColliMagazzinoRESTConsumer.updatePosizioneUL(cloneMtbColt, mtbDepoPosizione != null ? mtbDepoPosizione.getPosizione() : CommonModelConsts.ENTITY_NULL_STRING, + onComplete, + this::sendError); } private void postSaveBehaviour(Runnable onComplete) { diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneActivity.java index 6de4b2ab..70b10dee 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneActivity.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneActivity.java @@ -14,6 +14,7 @@ import android.widget.Toast; import androidx.appcompat.widget.PopupMenu; import androidx.databinding.DataBindingUtil; import androidx.databinding.ObservableArrayList; +import androidx.lifecycle.MutableLiveData; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; @@ -25,6 +26,8 @@ import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; import javax.inject.Inject; @@ -104,17 +107,16 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo private final ObservableArrayList mSpedizioneMutableData = new ObservableArrayList<>(); - public BindableBoolean addExtraItemsEnabled = new BindableBoolean(false); public BindableBoolean noItemsToPick = new BindableBoolean(false); - public BindableBoolean noLUPresent = new BindableBoolean(true); + public MutableLiveData noLUPresent = new MutableLiveData<>(true); public BindableBoolean bottomSheetEnabled = new BindableBoolean(false); private boolean mEnableFakeGiacenza; private boolean mFlagShowCodForn; private boolean mDivideByGrpMerc; private boolean mEnableQuantityReset; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private ArrayList mSitArtOrd; private ArrayList mTestateOrdini; @@ -243,31 +245,38 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Override public void onBackPressed() { - if (this.mBindings.bottomSheetLuContent.isExpanded()) { this.mBindings.bottomSheetLuContent.collapse(); - } else if (!noLUPresent.get()) { + } else if (!noLUPresent.getValue()) { this.mShouldCloseActivity = true; - BarcodeManager.removeCallback(barcodeScannerIstanceID); - this.mViewmodel.requestCloseLU(true); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); + executorService.execute(() -> { + try { + this.mViewmodel.requestCloseLU(true); + } catch (Exception e) { + onError(e); + } + }); } else { - BarcodeManager.removeCallback(barcodeScannerIstanceID); - super.onBackPressed(); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); + handler.post(() -> { + super.onBackPressed(); + }); } } private void initVars() { - this.noLUPresent.addOnPropertyChangedCallback(() -> { - this.bottomSheetEnabled.set(!this.noLUPresent.get()); + this.noLUPresent.observeForever(newValue -> { + this.bottomSheetEnabled.set(!newValue); }); } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @@ -324,13 +333,19 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo this.mBindings.spedizionePickingList.setLayoutManager(new LinearLayoutManager(this)); RunnableArgssss onItemClicked = (clickedItem, refMtbColt, refMtbColr, executeImmediately) -> { - if (!noLUPresent.get() && - ((SettingsManager.iDB().isFlagSpedizioneEnableManualPick() && - clickedItem.getSitArtOrdDTO().isFlagEnablePickManuale()) || - clickedItem.getTempPickData() != null)) { - this.mViewmodel.dispatchOrdineRow(clickedItem, refMtbColt, refMtbColr, - SettingsManager.iDB().isFlagSpedizioneEnableManualPick() && clickedItem.getSitArtOrdDTO().isFlagEnablePickManuale(), executeImmediately); - } + executorService.execute(() -> { + if (!noLUPresent.getValue() && + ((SettingsManager.iDB().isFlagSpedizioneEnableManualPick() && + clickedItem.getSitArtOrdDTO().isFlagEnablePickManuale()) || + clickedItem.getTempPickData() != null)) { + try { + this.mViewmodel.dispatchOrdineRow(clickedItem, refMtbColt, refMtbColr, + SettingsManager.iDB().isFlagSpedizioneEnableManualPick() && clickedItem.getSitArtOrdDTO().isFlagEnablePickManuale(), executeImmediately); + } catch (Exception e) { + onError(e); + } + } + }); }; spedizioneListAdapter.setOnItemClicked(onItemClicked); @@ -713,9 +728,15 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo private final RunnableArgs onScanSuccessful = data -> { this.onLoadingStarted(); - this.mViewmodel.processBarcodeDTO(data, () -> { - this.onLoadingEnded(); + executorService.execute(() -> { + try { + this.mViewmodel.processBarcodeDTO(data); + } catch (Exception e) { + onError(e); + } }); + + this.onLoadingEnded(); }; public void addExtraItem() { @@ -723,11 +744,27 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo DialogScanArtView .newInstance(!mEnableFakeGiacenza, (status, mtbAart, ean128Model, mtbColr) -> { if (status == DialogConsts.Results.YES) { - this.mViewmodel.dispatchExtraItem(mtbAart, ean128Model, mtbColr); + + executorService.execute(() -> { + try { + this.mViewmodel.dispatchExtraItem(mtbAart, ean128Model, mtbColr); + } catch (Exception e) { + onError(e); + } + }); + } }, pickMagazzinoAutomaticoPosizione -> { this.onLoadingStarted(); - this.mViewmodel.executeEmptyMagazzinoAutomaticoRequest(pickMagazzinoAutomaticoPosizione, this::onLoadingEnded); + + executorService.execute(() -> { + try { + this.mViewmodel.executeEmptyMagazzinoAutomaticoRequest(pickMagazzinoAutomaticoPosizione); + } catch (Exception e) { + onError(e); + } + this.onLoadingEnded(); + }); }) .show(getSupportFragmentManager(), "tag"); }); @@ -735,13 +772,13 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo public void startManualSearch() { handler.post(() -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); DialogSimpleInputHelper.makeInputDialog(this, "Inserisci il codice a barre", codice -> { this.onScanSuccessful.run(new BarcodeScanDTO().setStringValue(codice).setType(BarcodeType.CODE128)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); - }, BarcodeManager::enable).show(); + }, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)).show(); }); } @@ -757,8 +794,13 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo this.onLoadingStarted(); - this.mViewmodel.createNewLU(null, null, () -> { - this.onLoadingEnded(); + executorService.execute(() -> { + try { + this.mViewmodel.createNewLU(null, null); + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } }); } @@ -793,15 +835,23 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo public void closeOrder() { this.fabPopupMenu.dismiss(); + this.onLoadingStarted(); - this.mViewmodel.closeOrder(); + executorService.execute(() -> { + try { + this.mViewmodel.closeOrder(); + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } + }); } @Override public void onLUOpened(MtbColt mtbColt) { handler.post(() -> { this.addExtraItemsEnabled.set(SettingsManager.iDB().isFlagCanAddExtraItemSpedizione()); - noLUPresent.set(false); + noLUPresent.postValue(false); Snackbar.make(mBindings.getRoot(), R.string.data_saved, Snackbar.LENGTH_SHORT) .setBackgroundTint(getResources().getColor(R.color.green_500)) @@ -815,7 +865,7 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo public void onLUClosed() { handler.post(() -> { this.addExtraItemsEnabled.set(false); - noLUPresent.set(true); + noLUPresent.postValue(true); this.mBottomSheetFragmentLUContentViewModel.setMtbColt(null); if (this.mShouldCloseActivity) super.onBackPressed(); @@ -825,9 +875,7 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Override public void onLUPesoRequired(String codTcol, BigDecimal netWeightKG, BigDecimal grossWeightKG, RunnableArgsss onComplete) { handler.post(() -> { - DialogInputPesoLUView.newInstance(null, new BigDecimal(50), new BigDecimal(55), (newCodTcol, newNetWeight, newGrossWeight) -> { - onComplete.run(newCodTcol, netWeightKG, grossWeightKG); - }) + DialogInputPesoLUView.newInstance(codTcol, netWeightKG, grossWeightKG, onComplete) .show(getSupportFragmentManager(), "tag"); }); } @@ -898,7 +946,9 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Override public void onError(Exception ex, boolean useSnackbar) { + handler.post(() -> { + this.onLoadingEnded(); if (ex instanceof InvalidPesoKGException) { @@ -910,7 +960,8 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo UtilityExceptions.defaultException(this, ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); + }); } @@ -933,7 +984,8 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canPartitaMagBeChanged, - RunnableArgss onComplete) { + RunnableArgs onComplete, + Runnable onAbort) { if (dataScad == null && pickingObjectDTO.getMtbAart().getGgScadPartita() != null && pickingObjectDTO.getMtbAart().getGgScadPartita() > 0) { dataScad = UtilityDate.getNow(); @@ -947,7 +999,7 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo .setInitialQtaTot(initialQtaTot) .setTotalQtaOrd(totalQtaOrd) .setTotalNumCnfOrd(totalNumCnfOrd) - .setQtaCnfOrd(qtaCnfOrd) + .setTotalQtaCnfOrd(qtaCnfOrd) .setTotalQtaToBeTaken(totalQtaToBeTaken) .setTotalNumCnfToBeTaken(totalNumCnfToBeTaken) .setQtaCnfToBeTaken(qtaCnfToBeTaken) @@ -962,25 +1014,29 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo .setCanPartitaMagBeChanged(canPartitaMagBeChanged) .setStatoPartitaMag(pickingObjectDTO != null ? pickingObjectDTO.getStatoArticoloDTO() : null) .setNotifyProductLotStatus(SettingsManager.iDB().isNotifyLotStatus()) - .setMtbPartitaMagList(mViewmodel.getmPartitaMagList()); + .setMtbPartitaMagList(mViewmodel.getmPartitaMagList()) + .setEnableSSCCRead(SettingsManager.iDB().isFlagSpedizioneEnableFastPicking()); if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + if (resultDTO == null || resultDTO.isAborted()) { + onAbort.run(); + return; + } + PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) .setQtaCnf(resultDTO.getQtaCnf()) .setQtaTot(resultDTO.getQtaTot()) .setPartitaMag(resultDTO.getPartitaMag()) - .setDataScad(resultDTO.getDataScad()); - - this.onLoadingStarted(); - onComplete.run(pickedQuantityDTO, shouldCloseLU); - }) - .setOnAbort(() -> { - this.mViewmodel.resetMatchedRows(); + .setDataScad(resultDTO.getDataScad()) + .setShouldCloseLu(resultDTO.isShouldCloseLu()) + .setNextUlBarcode(resultDTO.getNextUlBarcode()); + onComplete.run(pickedQuantityDTO); }) + .setOnAbort(onAbort) .show(getSupportFragmentManager(), "tag"); else Toast.makeText(this, "Dialog già a video", Toast.LENGTH_LONG).show(); } @@ -1006,77 +1062,124 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo }).show(getSupportFragmentManager(), "tag"); } - public void askShouldPrintPackingList(PrintOrderCloseDTO printOrderCloseDTO, RunnableArgs onComplete) { - DialogSimpleMessageView.makeInfoDialog( - getResources().getString(R.string.action_close_order), - new SpannableString(getResources().getString(R.string.message_print_packing_list_on_close_order)), - null, - () -> { - printOrderCloseDTO.setFlagPrintPackingList(true); - if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) { - this.askShouldPrintSSCC(printOrderCloseDTO, onComplete); - } else { - onComplete.run(printOrderCloseDTO); + public boolean askShouldPrintPackingList() { + AtomicReference resultPrintPackingList = new AtomicReference<>(); + CountDownLatch countDownLatch = new CountDownLatch(1); + + handler.post(() -> { + DialogSimpleMessageView.makeInfoDialog( + getResources().getString(R.string.action_close_order), + new SpannableString(getResources().getString(R.string.message_print_packing_list_on_close_order)), + null, + () -> { + resultPrintPackingList.set(true); + countDownLatch.countDown(); + }, + () -> { + resultPrintPackingList.set(false); + countDownLatch.countDown(); } - }, - () -> { - printOrderCloseDTO.setFlagPrintPackingList(false); - if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) { - this.askShouldPrintSSCC(printOrderCloseDTO, onComplete); - } else { - onComplete.run(printOrderCloseDTO); - } - } - ) - .show(getSupportFragmentManager(), "tag"); + ) + .show(getSupportFragmentManager(), "tag"); + }); + + + try { + countDownLatch.await(); + } catch (InterruptedException e) { + this.onError(e); + } + + return resultPrintPackingList.get(); +// +// boolean printPackingList = resultPrintPackingList.get(); +// printOrderCloseDTO.setFlagPrintPackingList(printPackingList); +// +// if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) { +// var shouldPrintSSCCResult = this.askShouldPrintSSCC(printOrderCloseDTO); +// +// printOrderCloseDTO.setFlagPrintSSCC(shouldPrintSSCCResult.isFlagPrintSSCC()); +// printOrderCloseDTO.setFlagSkipPrintedSSCC(shouldPrintSSCCResult.isFlagSkipPrintedSSCC()); +// } +// +// return printOrderCloseDTO; } - public void askShouldPrintSSCC(PrintOrderCloseDTO printOrderCloseDTO, RunnableArgs onComplete) { - DialogPrintOrderSSCCListView.newInstance(printOrderCloseDTO, onComplete).show(this.getSupportFragmentManager(), "dialogPrintOrderSSCCListView"); + public DialogPrintOrderSSCCListView.Result askShouldPrintSSCC(PrintOrderCloseDTO printOrderCloseDTO) { + AtomicReference result = new AtomicReference<>(); + CountDownLatch countDownLatch = new CountDownLatch(1); + + handler.post(() -> { + DialogPrintOrderSSCCListView.newInstance(printOrderCloseDTO, data -> { + result.set(data); + countDownLatch.countDown(); + }) + .show(this.getSupportFragmentManager(), "dialogPrintOrderSSCCListView"); + }); + + try { + countDownLatch.await(); + } catch (InterruptedException e) { + this.onError(e); + } + + return result.get(); } @Override public void onBatchLotSelectionRequest(List availableBatchLots, RunnableArgs onComplete) { - DialogChooseBatchLotView.newInstance(availableBatchLots, onComplete) - .show(getSupportFragmentManager(), "tag"); + handler.post(() -> { + DialogChooseBatchLotView.newInstance(availableBatchLots, onComplete) + .show(getSupportFragmentManager(), "tag"); + }); } @Override - public void onCloseOrderPrintRequest(RunnableArgs onComplete) { + public PrintOrderCloseDTO onCloseOrderPrintRequest() { PrintOrderCloseDTO printOrderCloseDTO = new PrintOrderCloseDTO(); + if (SettingsManager.iDB().isFlagPrintPackingListOnOrderClose()) { - this.askShouldPrintPackingList(printOrderCloseDTO, onComplete); - } else if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) { - this.askShouldPrintSSCC(printOrderCloseDTO, onComplete); + var result = this.askShouldPrintPackingList(); + printOrderCloseDTO.setFlagPrintPackingList(result); } + if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) { + var shouldPrintSSCC = this.askShouldPrintSSCC(printOrderCloseDTO); + + printOrderCloseDTO.setFlagPrintSSCC(shouldPrintSSCC.isFlagPrintSSCC()); + printOrderCloseDTO.setFlagSkipPrintedSSCC(shouldPrintSSCC.isFlagSkipPrintedSSCC()); + } + + return printOrderCloseDTO; } @Override public void onCreateDocsRequest() { - DialogYesNoView.newInstance("Chiusura ordine", "Vuoi creare i documenti per gli ordini selezionati?", result -> { + handler.post(() -> { + DialogYesNoView.newInstance("Chiusura ordine", "Vuoi creare i documenti per gli ordini selezionati?", result -> { - switch (result) { - case YES: - this.mViewmodel.createDocs(); - break; - case NO: - this.onOrderClosed(); - break; - } + switch (result) { + case YES: + this.mViewmodel.createDocs(); + break; + case NO: + this.onOrderClosed(); + break; + } - }).show(this.getSupportFragmentManager(), "tag"); + }).show(this.getSupportFragmentManager(), "tag"); + }); } @Override public void onChooseArtRequest(List artsList, RunnableArgs onComplete) { - new DialogChooseArtFromListaArtsView(true, artsList, onComplete) - .show(getSupportFragmentManager(), "tag"); + DialogChooseArtFromListaArtsView.newInstance(true, artsList, onComplete) + .show(getSupportFragmentManager(), "dialog-choose-art"); } @Override - public void onChooseArtsRequest(List artsList, RunnableArgs> onComplete) { - DialogChooseArtsFromMtbAartListView.newInstance(artsList, onComplete, this::onLoadingEnded) + public void onChooseArtsRequest(List artsList, RunnableArgs> onComplete, Runnable onAbort) { + DialogChooseArtsFromMtbAartListView.newInstance(artsList, onComplete, onAbort) .show(getSupportFragmentManager(), "tag"); } @@ -1105,17 +1208,37 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Override public void onBottomSheetLUClose() { - this.mViewmodel.requestCloseLU(true); + executorService.execute(() -> { + try { + this.mViewmodel.requestCloseLU(true); + } catch (Exception e) { + onError(e); + } + }); } @Override public void onMtbColrEdit(MtbColr mtbColr) { - this.mViewmodel.dispatchRowEdit(mtbColr); + executorService.execute(() -> { + this.onLoadingStarted(); + try { + this.mViewmodel.dispatchRowEdit(mtbColr); + } catch (Exception e) { + onError(e); + } + this.onLoadingEnded(); + }); } @Override public void onMtbColrDelete(MtbColr mtbColr) { - this.mViewmodel.requestDeleteRow(mtbColr); + executorService.execute(() -> { + try { + this.mViewmodel.requestDeleteRow(mtbColr); + } catch (Exception e) { + onError(e); + } + }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneViewModel.java index 7905910f..6c40c773 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneViewModel.java @@ -1,6 +1,7 @@ package it.integry.integrywmsnative.gest.spedizione; import android.os.Handler; +import android.util.Pair; import androidx.databinding.ObservableArrayList; import androidx.lifecycle.MutableLiveData; @@ -16,7 +17,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.inject.Inject; @@ -25,7 +28,7 @@ import it.integry.barcode_base_android_library.model.BarcodeScanDTO; import it.integry.integrywmsnative.core.CommonConst; import it.integry.integrywmsnative.core.data_recover.ColliDataRecoverService; import it.integry.integrywmsnative.core.exception.EmptyLUException; -import it.integry.integrywmsnative.core.exception.InvalidCodMdepLUException; +import it.integry.integrywmsnative.core.exception.InvalidCodMdepException; import it.integry.integrywmsnative.core.exception.InvalidLUException; import it.integry.integrywmsnative.core.exception.NoArtsFoundException; import it.integry.integrywmsnative.core.exception.NoLUFoundException; @@ -352,20 +355,54 @@ public class SpedizioneViewModel { if (this.mListener != null) mListener.onLoadingStarted(); } - private void sendOnCloseOrderPrintRequest(RunnableArgs onComplete) { - if (this.mListener != null) mListener.onCloseOrderPrintRequest(onComplete); + private PrintOrderCloseDTO sendOnCloseOrderPrintRequest() { + if (this.mListener != null) { + return mListener.onCloseOrderPrintRequest(); + } + + return null; } private void sendCreateDocsRequest() { if (this.mListener != null) mListener.onCreateDocsRequest(); } - private void sendChooseArtRequest(List mtbAarts, RunnableArgs onComplete) { - if (this.mListener != null) mListener.onChooseArtRequest(mtbAarts, onComplete); + private MtbAart sendChooseArtRequest(List mtbAarts) { + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + mListener.onChooseArtRequest(mtbAarts, data -> { + result.set(data); + latch.countDown(); + }); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + + return null; } - private void sendChooseArtsRequest(List mtbAarts, RunnableArgs> onComplete) { - if (this.mListener != null) mListener.onChooseArtsRequest(mtbAarts, onComplete); + private List sendChooseArtsRequest(List mtbAarts) { + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference> result = new AtomicReference<>(); + + mListener.onChooseArtsRequest(mtbAarts, data -> { + result.set(data); + latch.countDown(); + }, latch::countDown); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + + return null; } private void sendOnOrderClosed() { @@ -413,39 +450,87 @@ public class SpedizioneViewModel { if (this.mListener != null) mListener.onFilterRemoved(); } - private void sendMtbColrDeleteRequest(RunnableArgs onComplete) { - if (this.mListener != null) mListener.onMtbColrDeleteRequest(onComplete); + private boolean sendMtbColrDeleteRequest() { + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + mListener.onMtbColrDeleteRequest(data -> { + result.set(data); + latch.countDown(); + }); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + + return false; } - private void sendOnFullItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canBatchLotBeChanged, RunnableArgss onComplete) { - if (this.mListener != null) - mListener.onFullItemDispatched(pickingObjectDTO, - mtbAart, - initialNumCnf, - initialQtaCnf, - initialQtaTot, - totalQtaOrd, - totalNumCnfOrd, - qtaCnfOrd, - totalQtaToBeTaken, - totalNumCnfToBeTaken, - qtaCnfToBeTaken, - totalQtaAvailable, - totalNumCnfAvailable, - qtaCnfAvailable, - partitaMag, - dataScad, - canOverflowOrderQuantity, - canBatchLotBeChanged, - onComplete); + private PickedQuantityDTO sendOnFullItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canBatchLotBeChanged) { + + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + mListener.onFullItemDispatched(pickingObjectDTO, + mtbAart, + initialNumCnf, + initialQtaCnf, + initialQtaTot, + totalQtaOrd, + totalNumCnfOrd, + qtaCnfOrd, + totalQtaToBeTaken, + totalNumCnfToBeTaken, + qtaCnfToBeTaken, + totalQtaAvailable, + totalNumCnfAvailable, + qtaCnfAvailable, + partitaMag, + dataScad, + canOverflowOrderQuantity, + canBatchLotBeChanged, + (data) -> { + result.set(data); + latch.countDown(); + }, () -> { + resetMatchedRows(); + latch.countDown(); + }); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + + return null; } private void sendOnRowSaved() { if (this.mListener != null) mListener.onRowSaved(); } - private void sendLUPositionChangeRequest(RunnableArgss onComplete) { - if (this.mListener != null) mListener.onLUPositionChangeRequest(onComplete); + private Pair sendLUPositionChangeRequest() { + + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference> result = new AtomicReference<>(); + + mListener.onLUPositionChangeRequest((status, data) -> { + result.set(new Pair<>(status, data)); + latch.countDown(); + }); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + return null; } private void sendBatchLotSelectionRequest(List availableBatchLots, RunnableArgs onComplete) { @@ -453,8 +538,7 @@ public class SpedizioneViewModel { mListener.onBatchLotSelectionRequest(availableBatchLots, onComplete); } - public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - + public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO) throws Exception { //Se non c'è una UL aperta if (mCurrentMtbColt == null) { @@ -463,272 +547,240 @@ public class SpedizioneViewModel { //Se il collo non esiste allora lo creo associandolo a questa etichetta anonima //invece se esiste apro un collo nuovo e cerco gli articoli presenti nell'ul //dell'etichetta anonima - this.executeEtichettaAnonimaNotOpenedLU(barcodeScanDTO, onComplete); + this.executeEtichettaAnonimaNotOpenedLU(barcodeScanDTO); } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)/* && mDefaultSegnoCol == 1*/) { - this.processBarcodePosizioneNotOpenedLU(barcodeScanDTO, onComplete); + this.processBarcodePosizioneNotOpenedLU(barcodeScanDTO); } else { - this.processBarcodeNotOpenedLU(barcodeScanDTO, onComplete); + this.processBarcodeNotOpenedLU(barcodeScanDTO); } } else { if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { //Cerco gli articoli presenti nell'ul dell'etichetta anonima - this.executeEtichettaLU(barcodeScanDTO.getStringValue(), onComplete); + this.executeEtichettaLU(barcodeScanDTO.getStringValue()); } else { - this.processBarcodeAlreadyOpenedLU(barcodeScanDTO, onComplete); + this.processBarcodeAlreadyOpenedLU(barcodeScanDTO); } } + } - private void processBarcodePosizioneNotOpenedLU(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { + private void processBarcodePosizioneNotOpenedLU(BarcodeScanDTO barcodeScanDTO) throws Exception { MtbDepoPosizione foundPosizione = UtilityPosizione.getFromCache(barcodeScanDTO.getStringValue()); if (foundPosizione == null) { //Nessuna posizione trovata con questo barcode - this.sendError(new ScannedPositionNotExistException()); - return; + throw new ScannedPositionNotExistException(); } if (!foundPosizione.isFlagMonoCollo()) { //La posizione non è Mono-UL - this.sendError(new CurrentMonoLUPositionIsNotCorrectException()); - return; + throw new CurrentMonoLUPositionIsNotCorrectException(); } if (foundPosizione.isMagazzinoAutomatico()) { //La posizione è di un magazzino automatico - this.sendError(new InvalidMagazzinoAutomaticoMovementException(foundPosizione)); - return; + throw new InvalidMagazzinoAutomaticoMovementException(foundPosizione); } - this.mPosizioneRESTConsumer.getBancaliInPosizione(foundPosizione, mtbColtList -> { - if (mtbColtList == null || mtbColtList.size() != 1) { - //Nessuna UL trovata oppure più UL nella stessa posizione - this.sendError(new NoLUFoundException()); - return; - } + var mtbColtList = this.mPosizioneRESTConsumer.getBancaliInPosizioneSynchronized(foundPosizione); - mColliMagazzinoRESTConsumer.getByTestata(mtbColtList.get(0), true, false, mtbColt -> { + if (mtbColtList == null || mtbColtList.size() != 1) { + //Nessuna UL trovata oppure più UL nella stessa posizione + throw new NoLUFoundException(); + } - if (mtbColt.getSegno() != mDefaultSegnoCol) { - this.sendError(new InvalidLUException()); - onComplete.run(); - return; - } + var mtbColt = mColliMagazzinoRESTConsumer.getByTestataSynchronized(mtbColtList.get(0), true, false); - //Reset of existant mtbColrs - mtbColt.setMtbColr(new ObservableArrayList<>()); + if (mtbColt.getSegno() != mDefaultSegnoCol) { + throw new InvalidLUException(); + } - this.mCurrentMtbColt = mtbColt; - this.mMtbColtSessionID = this.mColliDataRecoverService.startNewSession(mtbColt, mTestateOrdini); - this.mIsNewLU = false; + //Reset of existant mtbColrs + mtbColt.setMtbColr(new ObservableArrayList<>()); - this.sendLUOpened(mtbColt); - - onComplete.run(); - - }, this::sendError); - }, this::sendError); + this.mCurrentMtbColt = mtbColt; + this.mMtbColtSessionID = this.mColliDataRecoverService.startNewSession(mtbColt, mTestateOrdini); + this.mIsNewLU = false; + this.sendLUOpened(mtbColt); } - private void processBarcodeNotOpenedLU(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - this.createNewLU(null, null, () -> processBarcodeAlreadyOpenedLU(barcodeScanDTO, onComplete)); + private void processBarcodeNotOpenedLU(BarcodeScanDTO barcodeScanDTO) throws Exception { + this.createNewLU(null, null); + processBarcodeAlreadyOpenedLU(barcodeScanDTO); } - private void processBarcodeAlreadyOpenedLU(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { + private void processBarcodeAlreadyOpenedLU(BarcodeScanDTO barcodeScanDTO) throws Exception { if (UtilityBarcode.isEanPeso(barcodeScanDTO)) { //Cerco tramite etichetta ean 128 (che può indicarmi un articolo o una UL) - this.executeEtichettaEanPeso(barcodeScanDTO, onComplete); + this.executeEtichettaEanPeso(barcodeScanDTO); } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)) { //Cerco l'UL presente all'interno della posizione - this.executeEtichettaPosizione(barcodeScanDTO.getStringValue(), onComplete); + this.executeEtichettaPosizione(barcodeScanDTO.getStringValue()); } else if (UtilityBarcode.isEtichetta128(barcodeScanDTO)) { //Cerco tramite etichetta ean 128 (che può indicarmi un articolo o una UL) - this.executeEtichettaEan128(barcodeScanDTO, onComplete); + this.executeEtichettaEan128(barcodeScanDTO); } else { - this.loadArticolo(barcodeScanDTO.getStringValue(), null, onComplete); + this.loadArticolo(barcodeScanDTO.getStringValue(), null); } } - private void executeEtichettaAnonimaNotOpenedLU(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - mColliMagazzinoRESTConsumer.getBySSCC(barcodeScanDTO.getStringValue(), true, false, mtbColt -> { + private void executeEtichettaAnonimaNotOpenedLU(BarcodeScanDTO barcodeScanDTO) throws Exception { + var mtbColt = mColliMagazzinoRESTConsumer.getBySsccSynchronized(barcodeScanDTO.getStringValue(), true, false); - if (mtbColt == null) { - - if (!UtilityBarcode.isEtichettaAnonimaOfCurrentYear(barcodeScanDTO.getStringValue())) { - this.sendError(new NotCurrentYearLUException()); - } else { - int numCollo = -1; - - try { - numCollo = UtilityBarcode.getNumColloFromULAnonima(barcodeScanDTO.getStringValue()); - this.createNewLU(numCollo, CommonConst.Config.DEFAULT_ANONYMOUS_UL_SERIE, onComplete); - } catch (Exception ex) { - this.sendError(ex); - } - } + if (mtbColt == null) { + if (!UtilityBarcode.isEtichettaAnonimaOfCurrentYear(barcodeScanDTO.getStringValue())) { + throw new NotCurrentYearLUException(); } else { - - boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep() - .stream() - .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - - if (codMdepIsValid) { - this.createNewLU(null, null, () -> searchArtFromUL(mtbColt, onComplete)); - } else this.sendError(new InvalidCodMdepLUException()); - + int numCollo = UtilityBarcode.getNumColloFromULAnonima(barcodeScanDTO.getStringValue()); + this.createNewLU(numCollo, CommonConst.Config.DEFAULT_ANONYMOUS_UL_SERIE); } + } else { - }, this::sendError); + boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep() + .stream() + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); + + if (codMdepIsValid) { + this.createNewLU(null, null); + searchArtFromUL(mtbColt); + } else throw new InvalidCodMdepException(); + + } } - private void executeEtichettaPosizione(String posizione, Runnable onComplete) { + private void executeEtichettaPosizione(String posizione) throws Exception { MtbDepoPosizione foundPosizione = UtilityPosizione.getFromCache(posizione); if (foundPosizione == null) { //Nessuna posizione trovata con questo barcode - this.sendError(new ScannedPositionNotExistException()); - return; + throw new ScannedPositionNotExistException(); } if (!foundPosizione.isFlagMonoCollo()) { //La posizione non è Mono-UL - this.sendError(new CurrentMonoLUPositionIsNotCorrectException()); - return; + throw new CurrentMonoLUPositionIsNotCorrectException(); } if (foundPosizione.isMagazzinoAutomatico()) { //Eseguo picking da magazzino automatico - executeMagazzinoAutomatico(foundPosizione, onComplete); + executeMagazzinoAutomatico(foundPosizione); return; } - this.mPosizioneRESTConsumer.getBancaliInPosizione(foundPosizione, mtbColtList -> { + var mtbColtList = this.mPosizioneRESTConsumer.getBancaliInPosizioneSynchronized(foundPosizione); - if (mtbColtList == null || mtbColtList.size() != 1) { - //Nessuna UL trovata oppure più UL nella stessa posizione - this.sendError(new NoLUFoundException()); - return; - } + if (mtbColtList == null || mtbColtList.size() != 1) { + //Nessuna UL trovata oppure più UL nella stessa posizione + throw new NoLUFoundException(); + } - mColliMagazzinoRESTConsumer.getByTestata(mtbColtList.get(0), true, false, mtbColt -> { - if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { + var mtbColt = mColliMagazzinoRESTConsumer.getByTestataSynchronized(mtbColtList.get(0), true, false); - boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() - .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); + if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { - if (codMdepIsValid) { - this.searchArtFromUL(mtbColt, onComplete); - } else this.sendError(new InvalidCodMdepLUException()); + boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - } else { - this.sendError(new EmptyLUException()); - } + if (codMdepIsValid) { + this.searchArtFromUL(mtbColt); + } else throw new InvalidCodMdepException(); - }, this::sendError); - - }, this::sendError); - - } - - private void executeEtichettaLU(String SSCC, Runnable onComplete) { - mColliMagazzinoRESTConsumer.getBySSCC(SSCC, true, false, mtbColt -> { - - if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { - if (mtbColt.getSegno() != -1) { - - boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() - .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - - if (codMdepIsValid) { - searchArtFromUL(mtbColt, onComplete); - } else this.sendError(new InvalidCodMdepLUException()); - - } else { - this.sendError(new InvalidLUException()); - } - } else { - this.sendError(new EmptyLUException()); - } - - }, this::sendError); - } - - - private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - mBarcodeRESTConsumer.decodeEan128(barcodeScanDTO, ean128Model -> { - - String barcodeProd = null; - - if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) barcodeProd = ean128Model.Sscc; - if (!UtilityString.isNullOrEmpty(ean128Model.Gtin)) barcodeProd = ean128Model.Gtin; - if (!UtilityString.isNullOrEmpty(ean128Model.Content)) - barcodeProd = ean128Model.Content; - - - if (!UtilityString.isNullOrEmpty(barcodeProd)) { - - if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) { - this.executeEtichettaLU(ean128Model.Sscc, onComplete); - - } else { - if (SettingsManager.iDB().isFlagSpedizioneEnableManualPick()) { - PickDataDTO pickDataDTO = PickDataDTO.fromEan128(ean128Model); - this.loadArticolo(barcodeProd, pickDataDTO, onComplete); - - } else { - this.sendError(new NoResultFromBarcodeException(), true); - onComplete.run(); - } - } - } else { - //EAN 128 non completo o comunque mancano i riferimenti al prodotto - onComplete.run(); - } - }, this::sendError); - } - - private void executeEtichettaEanPeso(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - - try { - Ean13PesoModel ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue()); - - this.loadArticolo(ean13PesoModel.getPrecode(), PickDataDTO.fromEan128(ean13PesoModel.toEan128()), onComplete); - } catch (Exception ex) { - this.sendError(ex); + } else { + throw new EmptyLUException(); } } - private void loadArticolo(String barcodeProd, PickDataDTO pickData, Runnable onComplete) { - this.mArticoloRESTConsumer.searchByBarcode(barcodeProd, mtbAartList -> { + private void executeEtichettaLU(String SSCC) throws Exception { + var mtbColt = mColliMagazzinoRESTConsumer.getBySsccSynchronized(SSCC, true, false); + + if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { + if (mtbColt.getSegno() != -1) { + + boolean codMdepMatchPreviousPick = mCurrentMtbColt == null || mCurrentMtbColt.getMtbColr().isEmpty() || mCurrentMtbColt.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep()); + boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); + + if (codMdepIsValid && codMdepMatchPreviousPick) { + searchArtFromUL(mtbColt); + } else throw new InvalidCodMdepException(); - if (mtbAartList != null && !mtbAartList.isEmpty()) { - if (mtbAartList.size() == 1) { - this.searchArtFromAnag(mtbAartList.get(0), pickData, onComplete); - } else { - this.sendChooseArtRequest(mtbAartList, art -> this.searchArtFromAnag(art, pickData, onComplete)); - } } else { - this.sendError(new NoResultFromBarcodeException(barcodeProd)); + throw new InvalidLUException(); } + } else { + throw new EmptyLUException(); + } - }, this::sendError); } - private void executeMagazzinoAutomatico(MtbDepoPosizione mtbDepoPosizione, Runnable onComplete) { + + private void executeEtichettaEan128(BarcodeScanDTO barcodeScanDTO) throws Exception { + var ean128Model = mBarcodeRESTConsumer.decodeEan128Synchronized(barcodeScanDTO); + + String barcodeProd = null; + + if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) barcodeProd = ean128Model.Sscc; + if (!UtilityString.isNullOrEmpty(ean128Model.Gtin)) barcodeProd = ean128Model.Gtin; + if (!UtilityString.isNullOrEmpty(ean128Model.Content)) + barcodeProd = ean128Model.Content; + + + if (!UtilityString.isNullOrEmpty(barcodeProd)) { + + if (!UtilityString.isNullOrEmpty(ean128Model.Sscc)) { + this.executeEtichettaLU(ean128Model.Sscc); + + } else { + if (SettingsManager.iDB().isFlagSpedizioneEnableManualPick()) { + PickDataDTO pickDataDTO = PickDataDTO.fromEan128(ean128Model); + this.loadArticolo(barcodeProd, pickDataDTO); + + } else { + throw new NoResultFromBarcodeException(); + } + } + } + } + + private void executeEtichettaEanPeso(BarcodeScanDTO barcodeScanDTO) throws Exception { + Ean13PesoModel ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue()); + + this.loadArticolo(ean13PesoModel.getPrecode(), PickDataDTO.fromEan128(ean13PesoModel.toEan128())); + + } + + private void loadArticolo(String barcodeProd, PickDataDTO pickData) throws Exception { + var mtbAartList = this.mArticoloRESTConsumer.searchByBarcodeSynchronized(barcodeProd); + + if (mtbAartList != null && !mtbAartList.isEmpty()) { + if (mtbAartList.size() == 1) { + this.searchArtFromAnag(mtbAartList.get(0), pickData); + } else { + var art = this.sendChooseArtRequest(mtbAartList); + if (art == null) return; + this.searchArtFromAnag(art, pickData); + } + } else { + throw new NoResultFromBarcodeException(barcodeProd); + } + + } + + private void executeMagazzinoAutomatico(MtbDepoPosizione mtbDepoPosizione) throws Exception { var magazzinoAutomaticoPickableArts = Objects.requireNonNull(this.mPickingList.getValue()) .stream() .filter(x -> x.getMtbColts().stream() @@ -741,45 +793,45 @@ public class SpedizioneViewModel { .map(PickingObjectDTO::getMtbAart) .collect(Collectors.toList()); - this.sendChooseArtsRequest(mtbAarts, selectedArts -> { - final List orders = this.mTestateOrdini.stream() - .map(x -> new MagazzinoAutomaticoPickOrderRequestDTO(UtilityDate.toLocalDate(x.getDataOrdD()), x.getGestione(), x.getNumOrd()) - .setDataCons(x.getDataConsD() != null ? UtilityDate.toLocalDate(x.getDataConsD()) : null)) - .collect(Collectors.toList()); + var selectedArts = this.sendChooseArtsRequest(mtbAarts); + if (selectedArts == null) return; - final List magazzinoAutomaticoPickItemRequestDTOList = new ArrayList<>(); - for (MtbAart selectedArt : selectedArts) { - final PickingObjectDTO pickingObjectDTO = magazzinoAutomaticoPickableArts.stream() - .filter(x -> x.getMtbAart().getCodMart().equalsIgnoreCase(selectedArt.getCodMart())) - .findFirst() - .orElse(null); + final List orders = this.mTestateOrdini.stream() + .map(x -> new MagazzinoAutomaticoPickOrderRequestDTO(UtilityDate.toLocalDate(x.getDataOrdD()), x.getGestione(), x.getNumOrd()) + .setDataCons(x.getDataConsD() != null ? UtilityDate.toLocalDate(x.getDataConsD()) : null)) + .collect(Collectors.toList()); - if (pickingObjectDTO == null) { - continue; - } + final List magazzinoAutomaticoPickItemRequestDTOList = new ArrayList<>(); + for (MtbAart selectedArt : selectedArts) { + final PickingObjectDTO pickingObjectDTO = magazzinoAutomaticoPickableArts.stream() + .filter(x -> x.getMtbAart().getCodMart().equalsIgnoreCase(selectedArt.getCodMart())) + .findFirst() + .orElse(null); - MagazzinoAutomaticoPickItemRequestDTO itemDto = new MagazzinoAutomaticoPickItemRequestDTO(selectedArt.getCodMart()) - .setQtaTot(pickingObjectDTO.getSitArtOrdDTO().getQtaOrd()) - .setNumCnf(pickingObjectDTO.getSitArtOrdDTO().getNumCnfOrd()) - .setUntMis(selectedArt.getUntMis()); - - magazzinoAutomaticoPickItemRequestDTOList.add(itemDto); + if (pickingObjectDTO == null) { + continue; } + MagazzinoAutomaticoPickItemRequestDTO itemDto = new MagazzinoAutomaticoPickItemRequestDTO(selectedArt.getCodMart()) + .setQtaTot(pickingObjectDTO.getSitArtOrdDTO().getQtaOrd()) + .setNumCnf(pickingObjectDTO.getSitArtOrdDTO().getNumCnfOrd()) + .setUntMis(selectedArt.getUntMis()); - var magazzinoAutomaticoPickRequest = new MagazzinoAutomaticoPickItemsRequestDTO() - .setShouldCreateUDS(true) - .setDefaultGestioneOfNewUDS(mDefaultGestioneOfUL.getText()) - .setOrdersOfNewUDS(orders) - .setItemsToPick(magazzinoAutomaticoPickItemRequestDTOList); + magazzinoAutomaticoPickItemRequestDTOList.add(itemDto); + } - mMagazzinoAutomaticoRESTConsumer.pickItems(mtbDepoPosizione, - magazzinoAutomaticoPickRequest, onComplete, this::sendError); - }); + + var magazzinoAutomaticoPickRequest = new MagazzinoAutomaticoPickItemsRequestDTO() + .setShouldCreateUDS(true) + .setDefaultGestioneOfNewUDS(mDefaultGestioneOfUL.getText()) + .setOrdersOfNewUDS(orders) + .setItemsToPick(magazzinoAutomaticoPickItemRequestDTOList); + + mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronized(mtbDepoPosizione, magazzinoAutomaticoPickRequest); } - public void executeEmptyMagazzinoAutomaticoRequest(MtbDepoPosizione mtbDepoPosizione, Runnable onComplete) { + public void executeEmptyMagazzinoAutomaticoRequest(MtbDepoPosizione mtbDepoPosizione) throws Exception { final List orders = this.mTestateOrdini.stream() .map(x -> new MagazzinoAutomaticoPickOrderRequestDTO(UtilityDate.toLocalDate(x.getDataOrdD()), x.getGestione(), x.getNumOrd()) .setDataCons(UtilityDate.toLocalDate(x.getDataConsD()))) @@ -790,11 +842,10 @@ public class SpedizioneViewModel { .setDefaultGestioneOfNewUDS(mDefaultGestioneOfUL.getText()) .setOrdersOfNewUDS(orders); - mMagazzinoAutomaticoRESTConsumer.pickItems(mtbDepoPosizione, - magazzinoAutomaticoPickRequest, onComplete, this::sendError); + mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronized(mtbDepoPosizione, magazzinoAutomaticoPickRequest); } - private void searchArtFromUL(MtbColt scannedUL, Runnable onComplete) { + private void searchArtFromUL(MtbColt scannedUL) throws Exception { final List pickingList = mPickingList.getValue(); final List matchPickingObject = new ArrayList<>(); @@ -832,16 +883,17 @@ public class SpedizioneViewModel { for (PickingObjectDTO matchedObject : matchPickingObject) { MtbColt cloneMtbColt = (MtbColt) scannedUL.clone(); - ObservableArrayList cloneMtbColrs = (ObservableArrayList) cloneMtbColt.getMtbColr().clone(); + ObservableArrayList cloneMtbColrs = cloneMtbColt.getMtbColr(); - cloneMtbColt.getMtbColr().stream() + var toBeRemoved = cloneMtbColt.getMtbColr().stream() .filter(x -> !(UtilityString.equalsIgnoreCase(x.getCodMart(), matchedObject.getSitArtOrdDTO().getCodMart()) && UtilityString.equalsIgnoreCase(x.getCodTagl(), matchedObject.getSitArtOrdDTO().getCodTagl()) && UtilityString.equalsIgnoreCase(x.getCodCol(), matchedObject.getSitArtOrdDTO().getCodCol()) && (!mEnableCheckPartitaMag || UtilityString.equalsIgnoreCase(x.getPartitaMag(), matchedObject.getSitArtOrdDTO().getPartitaMag()) || UtilityString.isNullOrEmpty(matchedObject.getSitArtOrdDTO().getPartitaMag())))) - .forEach(cloneMtbColrs::remove); + .collect(Collectors.toList()); + cloneMtbColrs.removeAll(toBeRemoved); cloneMtbColt.setMtbColr(cloneMtbColrs); @@ -852,11 +904,10 @@ public class SpedizioneViewModel { this.loadMatchedRows(matchPickingObject); - onComplete.run(); } - private void searchArtFromAnag(MtbAart mtbAart, PickDataDTO pickData, Runnable onComplete) { + private void searchArtFromAnag(MtbAart mtbAart, PickDataDTO pickData) throws Exception { final List pickingList = mPickingList.getValue(); List matchPickingObject = pickingList.stream() @@ -872,13 +923,12 @@ public class SpedizioneViewModel { } this.loadMatchedRows(matchPickingObject); - onComplete.run(); } - private void loadMatchedRows(List matchedRows) { + private void loadMatchedRows(List matchedRows) throws Exception { if (matchedRows == null || matchedRows.isEmpty()) { - this.sendError(new NoArtsFoundException()); + throw new NoArtsFoundException(); } else if (matchedRows.size() == 1) { PickingObjectDTO matchedItem = matchedRows.get(0); @@ -892,6 +942,7 @@ public class SpedizioneViewModel { this.sendFilterApplied(null); this.getPickingList().postValue(pickingList); } else { + MtbColt refMtbColt = matchedItem.getRefMtbColt(); if (matchedItem.getMtbColts() != null && matchedItem.getMtbColts().size() == 1) { refMtbColt = matchedItem.getMtbColts().get(0); @@ -918,7 +969,7 @@ public class SpedizioneViewModel { } - public void dispatchOrdineRow(final PickingObjectDTO pickingObjectDTO, MtbColt refMtbColt, MtbColr refMtbColr, boolean canPartitaMagBeChanged, boolean executeImmediately) { + public void dispatchOrdineRow(final PickingObjectDTO pickingObjectDTO, MtbColt refMtbColt, MtbColr refMtbColr, boolean canPartitaMagBeChanged, boolean executeImmediately) throws Exception { if (pickingObjectDTO.getTempPickData() != null && pickingObjectDTO.getTempPickData().getSourceMtbColt() != null && pickingObjectDTO.getTempPickData().getSourceMtbColt().getMtbColr() != null) { @@ -976,7 +1027,11 @@ public class SpedizioneViewModel { .findFirst() .orElse(null); - dispatchOrdineRowOnPostBatchLotSelection(pickingObjectDTO, refMtbColt, refMtbColr, scannedMtbColr, canPartitaMagBeChanged, executeImmediately); + try { + dispatchOrdineRowOnPostBatchLotSelection(pickingObjectDTO, refMtbColt, refMtbColr, scannedMtbColr, canPartitaMagBeChanged, executeImmediately); + } catch (Exception e) { + this.sendError(e); + } } }); @@ -989,7 +1044,7 @@ public class SpedizioneViewModel { } } - private void dispatchOrdineRowOnPostBatchLotSelection(final PickingObjectDTO pickingObjectDTO, MtbColt refMtbColt, MtbColr refMtbColr, MtbColr scannedMtbColr, boolean canPartitaMagBeChanged, boolean executeImmediately) { + private void dispatchOrdineRowOnPostBatchLotSelection(final PickingObjectDTO pickingObjectDTO, MtbColt refMtbColt, MtbColr refMtbColr, MtbColr scannedMtbColr, boolean canPartitaMagBeChanged, boolean executeImmediately) throws Exception { BigDecimal totalQtaOrd = pickingObjectDTO.getSitArtOrdDTO().getQtaOrd(); BigDecimal totalNumCnfOrd = pickingObjectDTO.getSitArtOrdDTO().getNumCnfOrd(); BigDecimal qtaCnfOrd = pickingObjectDTO.getSitArtOrdDTO().getQtaCnfOrd(); @@ -1119,38 +1174,55 @@ public class SpedizioneViewModel { BigDecimal initialQtaTot = mUseColliPedana ? initialNumCnf.multiply(initialQtaCnf) : mUseQtaOrd ? qtaColDaPrelevare : null; if (executeImmediately) { - this.saveNewRow(pickingObjectDTO, refMtbColt, numCnfDaPrelevare, qtaCnfDaPrelevare, qtaColDaPrelevare, partitaMag, dataScad, false, false); + this.saveNewRow(pickingObjectDTO, + refMtbColt, + numCnfDaPrelevare, + qtaCnfDaPrelevare, + qtaColDaPrelevare, + partitaMag, + dataScad, + false, + false, + null); } else { MtbColt finalRefMtbColt = refMtbColt; - this.onItemDispatched(pickingObjectDTO, pickingObjectDTO.getMtbAart(), initialNumCnf, initialQtaCnf, initialQtaTot, qtaDaEvadere, numCnfDaEvadere, qtaCnfDaEvadere, qtaColDaPrelevare, numCnfDaPrelevare, qtaCnfDaPrelevare, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, mCanOverflowOrderQuantity, canPartitaMagBeChanged, (pickedQuantityDTO, shouldCloseLU) -> { - this.saveNewRow(pickingObjectDTO, finalRefMtbColt, pickedQuantityDTO.getNumCnf(), pickedQuantityDTO.getQtaCnf(), pickedQuantityDTO.getQtaTot(), pickedQuantityDTO.getPartitaMag(), pickedQuantityDTO.getDataScad(), shouldCloseLU, true); - }); - + var pickedQuantityDTO = this.onItemDispatched(pickingObjectDTO, pickingObjectDTO.getMtbAart(), initialNumCnf, initialQtaCnf, initialQtaTot, qtaDaEvadere, numCnfDaEvadere, qtaCnfDaEvadere, qtaColDaPrelevare, numCnfDaPrelevare, qtaCnfDaPrelevare, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, mCanOverflowOrderQuantity, canPartitaMagBeChanged); + if (pickedQuantityDTO == null) return; + this.saveNewRow(pickingObjectDTO, finalRefMtbColt, + pickedQuantityDTO.getNumCnf(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getPartitaMag(), + pickedQuantityDTO.getDataScad(), + pickedQuantityDTO.isShouldCloseLu(), true, + pickedQuantityDTO.getNextUlBarcode()); } } - public void onItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canPartitaMagBeChanged, RunnableArgss onComplete) { + public PickedQuantityDTO onItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canPartitaMagBeChanged) throws Exception { + PickedQuantityDTO pickedQuantities = null; + if (SettingsManager.iDB().isNotifyLotStatus() && !UtilityString.isNullOrEmpty(partitaMag)) { - this.loadProductLotStatus(mtbAart.getCodMart(), partitaMag, (status) -> { - pickingObjectDTO.setStatoArticoloDTO(status); - this.sendOnFullItemDispatched(pickingObjectDTO, mtbAart, initialNumCnf, initialQtaCnf, initialQtaTot, totalQtaOrd, totalNumCnfOrd, qtaCnfOrd, totalQtaToBeTaken, totalNumCnfToBeTaken, qtaCnfToBeTaken, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, canOverflowOrderQuantity, canPartitaMagBeChanged, onComplete); - }); + var status = this.loadProductLotStatus(mtbAart.getCodMart(), partitaMag); + pickingObjectDTO.setStatoArticoloDTO(status); + pickedQuantities = this.sendOnFullItemDispatched(pickingObjectDTO, mtbAart, initialNumCnf, initialQtaCnf, initialQtaTot, totalQtaOrd, totalNumCnfOrd, qtaCnfOrd, totalQtaToBeTaken, totalNumCnfToBeTaken, qtaCnfToBeTaken, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, canOverflowOrderQuantity, canPartitaMagBeChanged); + } else { - this.sendOnFullItemDispatched(pickingObjectDTO, mtbAart, initialNumCnf, initialQtaCnf, initialQtaTot, totalQtaOrd, totalNumCnfOrd, qtaCnfOrd, totalQtaToBeTaken, totalNumCnfToBeTaken, qtaCnfToBeTaken, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, canOverflowOrderQuantity, canPartitaMagBeChanged, onComplete); + pickedQuantities = this.sendOnFullItemDispatched(pickingObjectDTO, mtbAart, initialNumCnf, initialQtaCnf, initialQtaTot, totalQtaOrd, totalNumCnfOrd, qtaCnfOrd, totalQtaToBeTaken, totalNumCnfToBeTaken, qtaCnfToBeTaken, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, canOverflowOrderQuantity, canPartitaMagBeChanged); + } - + return pickedQuantities; } - private void loadProductLotStatus(String codMart, String partitaMag, RunnableArgs onComplete) { + private StatoArticoloDTO loadProductLotStatus(String codMart, String partitaMag) throws Exception { this.sendOnLoadingStarted(); - this.mArticoloRESTConsumer.getStatoPartita(codMart, partitaMag, stati -> { - onComplete.run(!stati.isEmpty() ? stati.get(0) : null); - }, this::sendError); + var stati = this.mArticoloRESTConsumer.getStatoPartitaSynchronized(codMart, partitaMag); + return !stati.isEmpty() ? stati.get(0) : null; } - public void dispatchExtraItem(MtbAart mtbAart, Ean128Model ean128Model, MtbColr mtbColrToUse) { + public void dispatchExtraItem(MtbAart mtbAart, Ean128Model ean128Model, MtbColr mtbColrToUse) throws Exception { PickingObjectDTO pickingObjectDTO = new PickingObjectDTO().setMtbAart(mtbAart).setTempPickData(PickDataDTO.fromEan128(ean128Model)); @@ -1249,15 +1321,23 @@ public class SpedizioneViewModel { MtbColt finalRefMtbColt = refMtbColt; - this.onItemDispatched(pickingObjectDTO, pickingObjectDTO.getMtbAart(), initialNumCnf, initialQtaCnf, initialQtaTot, null, null, null, qtaColDaPrelevare, numCnfDaPrelevare, qtaCnfDaPrelevare, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, mCanOverflowOrderQuantity, true, (pickedQuantityDTO, shouldCloseLU) -> { - this.saveNewRow(pickingObjectDTO, finalRefMtbColt, pickedQuantityDTO.getNumCnf(), pickedQuantityDTO.getQtaCnf(), pickedQuantityDTO.getQtaTot(), pickedQuantityDTO.getPartitaMag(), pickedQuantityDTO.getDataScad(), shouldCloseLU, true); - }); + var pickedQuantityDTO = this.onItemDispatched(pickingObjectDTO, pickingObjectDTO.getMtbAart(), initialNumCnf, initialQtaCnf, initialQtaTot, null, null, null, qtaColDaPrelevare, numCnfDaPrelevare, qtaCnfDaPrelevare, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, mCanOverflowOrderQuantity, true); + if (pickedQuantityDTO == null) return; + + this.saveNewRow(pickingObjectDTO, finalRefMtbColt, + pickedQuantityDTO.getNumCnf(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getPartitaMag(), + pickedQuantityDTO.getDataScad(), + pickedQuantityDTO.isShouldCloseLu(), + true, + pickedQuantityDTO.getNextUlBarcode()); + } - public void dispatchRowEdit(final MtbColr mtbColrToEdit) { - this.sendOnLoadingStarted(); - + public void dispatchRowEdit(final MtbColr mtbColrToEdit) throws Exception { Optional optionalPickingObjectDTO = this.mPickingList.getValue().stream() .filter(x -> x.getWithdrawMtbColrs().stream().anyMatch(y -> y == mtbColrToEdit)) @@ -1271,114 +1351,115 @@ public class SpedizioneViewModel { PickingObjectDTO finalPickingObjectDTO = pickingObjectDTO; - loadRifULFromMtbColr(mtbColrToEdit, mtbColtRif -> { + var mtbColtRif = loadRifULFromMtbColr(mtbColrToEdit); - BigDecimal totalQtaOrd = null; - BigDecimal totalNumCnfOrd = null; - BigDecimal qtaCnfOrd = null; + BigDecimal totalQtaOrd = null; + BigDecimal totalNumCnfOrd = null; + BigDecimal qtaCnfOrd = null; - BigDecimal numCnfDaEvadere = null; - BigDecimal qtaDaEvadere = null; - BigDecimal qtaCnfDaEvadere = null; + BigDecimal numCnfDaEvadere = null; + BigDecimal qtaDaEvadere = null; + BigDecimal qtaCnfDaEvadere = null; - if (finalPickingObjectDTO != null) { - totalQtaOrd = finalPickingObjectDTO.getSitArtOrdDTO().getQtaOrd(); - totalNumCnfOrd = finalPickingObjectDTO.getSitArtOrdDTO().getNumCnfOrd(); - qtaCnfOrd = finalPickingObjectDTO.getSitArtOrdDTO().getQtaCnfOrd(); + if (finalPickingObjectDTO != null) { + totalQtaOrd = finalPickingObjectDTO.getSitArtOrdDTO().getQtaOrd(); + totalNumCnfOrd = finalPickingObjectDTO.getSitArtOrdDTO().getNumCnfOrd(); + qtaCnfOrd = finalPickingObjectDTO.getSitArtOrdDTO().getQtaCnfOrd(); - AtomicBigDecimal numCnfWithdrawRows = new AtomicBigDecimal(0); - AtomicBigDecimal qtaColWithdrawRows = new AtomicBigDecimal(0); + AtomicBigDecimal numCnfWithdrawRows = new AtomicBigDecimal(0); + AtomicBigDecimal qtaColWithdrawRows = new AtomicBigDecimal(0); - finalPickingObjectDTO.getWithdrawMtbColrs() - .forEach(row -> { - numCnfWithdrawRows.addAndGet(row.getNumCnf()); - qtaColWithdrawRows.addAndGet(row.getQtaCol()); - }); + finalPickingObjectDTO.getWithdrawMtbColrs() + .forEach(row -> { + numCnfWithdrawRows.addAndGet(row.getNumCnf()); + qtaColWithdrawRows.addAndGet(row.getQtaCol()); + }); - numCnfDaEvadere = totalNumCnfOrd.subtract(numCnfWithdrawRows.getBigDecimalValue()).add(mtbColrToEdit.getNumCnf()); - qtaDaEvadere = totalQtaOrd.subtract(qtaColWithdrawRows.getBigDecimalValue()).add(mtbColrToEdit.getQtaCol()); - qtaCnfDaEvadere = mtbColrToEdit.getQtaCnf(); - } + numCnfDaEvadere = totalNumCnfOrd.subtract(numCnfWithdrawRows.getBigDecimalValue()).add(mtbColrToEdit.getNumCnf()); + qtaDaEvadere = totalQtaOrd.subtract(qtaColWithdrawRows.getBigDecimalValue()).add(mtbColrToEdit.getQtaCol()); + qtaCnfDaEvadere = mtbColrToEdit.getQtaCnf(); + } - BigDecimal numCnfDaPrelevare = null; - BigDecimal qtaColDaPrelevare = null; - BigDecimal qtaCnfDaPrelevare = null; + BigDecimal numCnfDaPrelevare = null; + BigDecimal qtaColDaPrelevare = null; + BigDecimal qtaCnfDaPrelevare = null; - BigDecimal totalQtaAvailable = null; - BigDecimal totalNumCnfAvailable = null; - BigDecimal qtaCnfAvailable = null; + BigDecimal totalQtaAvailable = null; + BigDecimal totalNumCnfAvailable = null; + BigDecimal qtaCnfAvailable = null; - String partitaMag = null; - LocalDate dataScad = null; + String partitaMag = null; + LocalDate dataScad = null; - List mtbColrRifs = mtbColtRif != null && mtbColtRif.getMtbColr() != null ? mtbColtRif.getMtbColr() : null; + List mtbColrRifs = mtbColtRif != null && mtbColtRif.getMtbColr() != null ? mtbColtRif.getMtbColr() : null; - MtbColr mtbColrRif = null; + MtbColr mtbColrRif = null; - if (mtbColrRifs != null && !mtbColrRifs.isEmpty()) { - //TODO: Da capire se è necessario controllare anche il cod_jcom - Optional optionalMtbColr = - mtbColrRifs.stream() - .filter(x -> UtilityString.equalsIgnoreCase(x.getCodMart(), mtbColrToEdit.getCodMart()) && - UtilityString.equalsIgnoreCase(x.getCodCol(), mtbColrToEdit.getCodCol()) && - UtilityString.equalsIgnoreCase(x.getCodTagl(), mtbColrToEdit.getCodTagl()) && - UtilityString.equalsIgnoreCase(x.getPartitaMag(), mtbColrToEdit.getPartitaMag())) - .findFirst(); + if (mtbColrRifs != null && !mtbColrRifs.isEmpty()) { + //TODO: Da capire se è necessario controllare anche il cod_jcom + Optional optionalMtbColr = + mtbColrRifs.stream() + .filter(x -> UtilityString.equalsIgnoreCase(x.getCodMart(), mtbColrToEdit.getCodMart()) && + UtilityString.equalsIgnoreCase(x.getCodCol(), mtbColrToEdit.getCodCol()) && + UtilityString.equalsIgnoreCase(x.getCodTagl(), mtbColrToEdit.getCodTagl()) && + UtilityString.equalsIgnoreCase(x.getPartitaMag(), mtbColrToEdit.getPartitaMag())) + .findFirst(); - mtbColrRif = optionalMtbColr.isPresent() ? optionalMtbColr.get() : null; - } + mtbColrRif = optionalMtbColr.isPresent() ? optionalMtbColr.get() : null; + } - if (mtbColrRif != null) { + if (mtbColrRif != null) { - totalQtaAvailable = mtbColrRif.getQtaCol(); - totalNumCnfAvailable = mtbColrRif.getNumCnf(); - qtaCnfAvailable = mtbColrRif.getQtaCnf(); + totalQtaAvailable = mtbColrRif.getQtaCol(); + totalNumCnfAvailable = mtbColrRif.getNumCnf(); + qtaCnfAvailable = mtbColrRif.getQtaCnf(); - totalNumCnfAvailable = totalNumCnfAvailable.add(mtbColrToEdit.getNumCnf()); - totalQtaAvailable = totalQtaAvailable.add(mtbColrToEdit.getQtaCol()); - - } else { - - totalQtaAvailable = mtbColrToEdit.getQtaCol(); - totalNumCnfAvailable = mtbColrToEdit.getNumCnf(); - qtaCnfAvailable = mtbColrToEdit.getQtaCnf(); - - } - - - if (UtilityBigDecimal.lowerThan(numCnfDaPrelevare, BigDecimal.ZERO)) - numCnfDaPrelevare = BigDecimal.ZERO; - - if (UtilityBigDecimal.lowerThan(qtaColDaPrelevare, BigDecimal.ZERO)) - qtaColDaPrelevare = BigDecimal.ZERO; - - - partitaMag = mtbColrToEdit.getPartitaMag(); - dataScad = mtbColrToEdit.getDataScadPartita(); - - this.sendOnLoadingEnded(); - - this.onItemDispatched(finalPickingObjectDTO, mtbColrToEdit.getMtbAart(), mtbColrToEdit.getNumCnf(), mtbColrToEdit.getQtaCnf(), mtbColrToEdit.getQtaCol(), qtaDaEvadere, numCnfDaEvadere, qtaCnfDaEvadere, qtaColDaPrelevare, numCnfDaPrelevare, qtaCnfDaPrelevare, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, mCanOverflowOrderQuantity, false, (pickedQuantityDTO, shouldCloseLU) -> { - this.saveEditedRow(mtbColrToEdit, pickedQuantityDTO.getNumCnf(), pickedQuantityDTO.getQtaCnf(), pickedQuantityDTO.getQtaTot(), pickedQuantityDTO.getPartitaMag(), pickedQuantityDTO.getDataScad(), shouldCloseLU); - }); - }); - } - - private void loadRifULFromMtbColr(MtbColr mtbColr, RunnableArgs onComplete) { - //Se ho dei riferimenti ad una UL devo leggere la QTA ancora disponibile sulla Ul - if (mtbColr != null && !UtilityString.isNullOrEmpty(mtbColr.getGestioneRif()) && !UtilityString.isNullOrEmpty(mtbColr.getSerColloRif()) && !UtilityString.isNullOrEmpty(mtbColr.getDataColloRifS()) && mtbColr.getNumColloRif() != null) { - - mColliMagazzinoRESTConsumer.getByChiaveCollo(mtbColr.getGestioneRifEnum(), mtbColr.getNumColloRif(), mtbColr.getDataColloRifS(), mtbColr.getSerColloRif(), true, false, onComplete, this::sendError); + totalNumCnfAvailable = totalNumCnfAvailable.add(mtbColrToEdit.getNumCnf()); + totalQtaAvailable = totalQtaAvailable.add(mtbColrToEdit.getQtaCol()); } else { - onComplete.run(null); + + totalQtaAvailable = mtbColrToEdit.getQtaCol(); + totalNumCnfAvailable = mtbColrToEdit.getNumCnf(); + qtaCnfAvailable = mtbColrToEdit.getQtaCnf(); + } + + + if (UtilityBigDecimal.lowerThan(numCnfDaPrelevare, BigDecimal.ZERO)) + numCnfDaPrelevare = BigDecimal.ZERO; + + if (UtilityBigDecimal.lowerThan(qtaColDaPrelevare, BigDecimal.ZERO)) + qtaColDaPrelevare = BigDecimal.ZERO; + + + partitaMag = mtbColrToEdit.getPartitaMag(); + dataScad = mtbColrToEdit.getDataScadPartita(); + + var pickedQuantityDTO = this.onItemDispatched(finalPickingObjectDTO, mtbColrToEdit.getMtbAart(), mtbColrToEdit.getNumCnf(), mtbColrToEdit.getQtaCnf(), mtbColrToEdit.getQtaCol(), qtaDaEvadere, numCnfDaEvadere, qtaCnfDaEvadere, qtaColDaPrelevare, numCnfDaPrelevare, qtaCnfDaPrelevare, totalQtaAvailable, totalNumCnfAvailable, qtaCnfAvailable, partitaMag, dataScad, mCanOverflowOrderQuantity, false); + if (pickedQuantityDTO == null) return; + + this.saveEditedRow(mtbColrToEdit, + pickedQuantityDTO.getNumCnf(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getPartitaMag(), + pickedQuantityDTO.getDataScad(), + pickedQuantityDTO.isShouldCloseLu()); } - public void createNewLU(Integer customNumCollo, String customSerCollo, Runnable onComplete) { + private MtbColt loadRifULFromMtbColr(MtbColr mtbColr) throws Exception { + //Se ho dei riferimenti ad una UL devo leggere la QTA ancora disponibile sulla Ul + if (mtbColr != null && !UtilityString.isNullOrEmpty(mtbColr.getGestioneRif()) && !UtilityString.isNullOrEmpty(mtbColr.getSerColloRif()) && !UtilityString.isNullOrEmpty(mtbColr.getDataColloRifS()) && mtbColr.getNumColloRif() != null) { + return mColliMagazzinoRESTConsumer.getByChiaveColloSynchronized(mtbColr.getGestioneRifEnum(), mtbColr.getNumColloRif(), mtbColr.getDataColloRifS(), mtbColr.getSerColloRif(), true, false); + } + return null; + } + + public void createNewLU(Integer customNumCollo, String customSerCollo) throws Exception { int causaleCollo = 0; if (mDefaultGestioneOfUL == GestioneEnum.LAVORAZIONE && mDefaultSegnoCol == +1) causaleCollo = 1; @@ -1399,19 +1480,18 @@ public class SpedizioneViewModel { .setCausaleCollo(causaleCollo) .setOrders(orders); - this.mColliScaricoRESTConsumer.createUDS(createUDSRequestDTO, createdUDS -> { - mMtbColtSessionID = this.mColliDataRecoverService.startNewSession(createdUDS, mTestateOrdini); + var createdUDS = this.mColliScaricoRESTConsumer.createUDSSynchronized(createUDSRequestDTO); - this.mCurrentMtbColt = createdUDS; - this.mCurrentMtbColt.setRagSocCliente(mDefaultRagSocOfUL); - this.mIsNewLU = true; + mMtbColtSessionID = this.mColliDataRecoverService.startNewSession(createdUDS, mTestateOrdini); - if (onComplete != null) onComplete.run(); - this.sendLUOpened(createdUDS); - }, this::sendError); + this.mCurrentMtbColt = createdUDS; + this.mCurrentMtbColt.setRagSocCliente(mDefaultRagSocOfUL); + this.mIsNewLU = true; + + this.sendLUOpened(createdUDS); } - public void saveNewRow(PickingObjectDTO pickingObjectDTO, MtbColt refMtbColt, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU, boolean removeFilters) { + public void saveNewRow(PickingObjectDTO pickingObjectDTO, MtbColt refMtbColt, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU, boolean removeFilters, BarcodeScanDTO nextUlBarcode) throws Exception { this.sendOnLoadingStarted(); //TODO: Al posto di prelevare la prima riga bisognerebbe controllare se c'è ne una che corrisponde con la partita richiesta @@ -1455,89 +1535,98 @@ public class SpedizioneViewModel { insertUDSRowRequestDto .setDataScad(dataScad); - executeDepositChangeIfNeeded(refMtbColt, - () -> executeTipoUlChangeIfNeeded(refMtbColt, - () -> this.mColliScaricoRESTConsumer.insertUDSRow(insertUDSRowRequestDto, createdMtbColr -> { - pickingObjectDTO.getWithdrawMtbColrs().add(createdMtbColr); - this.mCurrentMtbColt.getMtbColr().add(createdMtbColr); + MtbColr createdMtbColr = null; + try { + MtbColt sourceMtbColt = pickingObjectDTO.getTempPickData() != null ? pickingObjectDTO.getTempPickData().getSourceMtbColt() : null; + executeDepositChangeIfNeeded(sourceMtbColt); + executeTipoUlChangeIfNeeded(sourceMtbColt); - createdMtbColr - .setUntMis(pickingObjectDTO.getMtbAart().getUntMis()) - .setMtbAart(pickingObjectDTO.getMtbAart()); + createdMtbColr = this.mColliScaricoRESTConsumer.insertUDSRowSynchronized(insertUDSRowRequestDto); + } catch (Exception ex) { + this.sendError(ex); + } + + pickingObjectDTO.getWithdrawMtbColrs().add(createdMtbColr); + this.mCurrentMtbColt.getMtbColr().add(createdMtbColr); + + createdMtbColr + .setUntMis(pickingObjectDTO.getMtbAart().getUntMis()) + .setMtbAart(pickingObjectDTO.getMtbAart()); - if (mEnableGiacenza) { - MtbColr refMtbColr = new MtbColr() - .setCodMart(createdMtbColr.getCodMart()) - .setPartitaMag(createdMtbColr.getPartitaMag()) - .setCodTagl(createdMtbColr.getCodTagl()) - .setCodCol(createdMtbColr.getCodCol()); + if (mEnableGiacenza) { + MtbColr refMtbColr = new MtbColr() + .setCodMart(createdMtbColr.getCodMart()) + .setPartitaMag(createdMtbColr.getPartitaMag()) + .setCodTagl(createdMtbColr.getCodTagl()) + .setCodCol(createdMtbColr.getCodCol()); - if (refMtbColt != null) { + if (refMtbColt != null) { - MtbColr originalRefMtbColr = refMtbColt.getMtbColr() != null && !refMtbColt.getMtbColr().isEmpty() ? refMtbColt.getMtbColr().get(0) : null; + MtbColr originalRefMtbColr = refMtbColt.getMtbColr() != null && !refMtbColt.getMtbColr().isEmpty() ? refMtbColt.getMtbColr().get(0) : null; - if (originalRefMtbColr != null) { - refMtbColr.setId(originalRefMtbColr.getId()); - } + if (originalRefMtbColr != null) { + refMtbColr.setId(originalRefMtbColr.getId()); + } - refMtbColr.setNumCollo(refMtbColt.getNumCollo()) - .setDataCollo(refMtbColt.getDataColloS()) - .setSerCollo(refMtbColt.getSerCollo()) - .setGestione(refMtbColt.getGestione()); - } - createdMtbColr.setRefMtbColr(refMtbColr); - } + refMtbColr.setNumCollo(refMtbColt.getNumCollo()) + .setDataCollo(refMtbColt.getDataColloS()) + .setSerCollo(refMtbColt.getSerCollo()) + .setGestione(refMtbColt.getGestione()); + } + createdMtbColr.setRefMtbColr(refMtbColr); + } - //Chiamato removeListFilter perché cosi mi cancella tutti i dati di pick temporanei - if (removeFilters) - resetMatchedRows(); - else - //Refresh della lista forzato - this.mPickingList.postValue(this.mPickingList.getValue()); + //Chiamato removeListFilter perché cosi mi cancella tutti i dati di pick temporanei + if (removeFilters) + resetMatchedRows(); + else + //Refresh della lista forzato + this.mPickingList.postValue(this.mPickingList.getValue()); - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); - if (shouldCloseLU) requestCloseLU(shouldPrint); - - }, this::sendError))); + if (shouldCloseLU) { + requestCloseLU(shouldPrint); + if (nextUlBarcode != null) { + processBarcodeDTO(nextUlBarcode); + } + } } - private void executeDepositChangeIfNeeded(MtbColt refMtbColt, Runnable onComplete) { + private void executeDepositChangeIfNeeded(MtbColt refMtbColt) throws Exception { //Considero solo la prima UDC scansionata boolean shouldChangeCodMdep = refMtbColt != null && !refMtbColt.getCodMdep().equalsIgnoreCase(mCurrentMtbColt.getCodMdep()) && mCurrentMtbColt.getMtbColr().isEmpty(); String newCodMdep = shouldChangeCodMdep ? refMtbColt.getCodMdep() : null; if (shouldChangeCodMdep) { - mColliMagazzinoRESTConsumer.spostaUL(mCurrentMtbColt, newCodMdep, null, false, () -> { - mCurrentMtbColt.setCodMdep(newCodMdep); - onComplete.run(); - }, this::sendError); - } else onComplete.run(); + mColliMagazzinoRESTConsumer.spostaUlSynchronized(mCurrentMtbColt, newCodMdep, null, false); + mCurrentMtbColt.setCodMdep(newCodMdep); + } } - private void executeTipoUlChangeIfNeeded(MtbColt refMtbColt, Runnable onComplete) { + private void executeTipoUlChangeIfNeeded(MtbColt refMtbColt) throws Exception { boolean shouldChangeCodTcol = refMtbColt != null && refMtbColt.getCodTcol() != null && !refMtbColt.getCodTcol().equalsIgnoreCase(mCurrentMtbColt.getCodTcol()) && mCurrentMtbColt.getMtbColr().isEmpty(); String newTipoUL = shouldChangeCodTcol ? refMtbColt.getCodTcol() : null; - ObservableMtbTcol newMtbTcol = SettingsManager.iDB().getInternalImballi().stream().filter(x -> x.getCodTcol().equalsIgnoreCase(newTipoUL)) + ObservableMtbTcol newMtbTcol = SettingsManager.iDB().getInternalImballi().stream() + .filter(x -> x.getCodTcol().equalsIgnoreCase(newTipoUL)) .findFirst() .orElse(null); if (!UtilityString.isNullOrEmpty(newTipoUL) && newMtbTcol == null) { - this.sendError(new Exception("Impossibile riconoscere il tipo UL " + newTipoUL)); - onComplete.run(); - return; + throw new Exception("Impossibile riconoscere il tipo UL " + newTipoUL); } if (shouldChangeCodTcol && newMtbTcol != null) { - updateTipoUl(newMtbTcol, onComplete); - } else onComplete.run(); + mColliMagazzinoRESTConsumer.updateTipoULSynchronized(mCurrentMtbColt, newMtbTcol.getCodTcol()); + mCurrentMtbColt.setCodTcol(newMtbTcol.getCodTcol()); + } } public void updateTipoUl(ObservableMtbTcol newTipoUL, Runnable onComplete) { @@ -1547,8 +1636,7 @@ public class SpedizioneViewModel { }, this::sendError); } - private void saveEditedRow(MtbColr mtbColrToUpdate, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) { - + private void saveEditedRow(MtbColr mtbColrToUpdate, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) throws Exception { this.sendOnLoadingStarted(); MtbColr mtbColrClone = (MtbColr) mtbColrToUpdate.clone(); @@ -1561,121 +1649,109 @@ public class SpedizioneViewModel { .setNewQtaCnf(qtaCnf) .setNewQtaTot(qtaTot); - this.mColliScaricoRESTConsumer.editUDSRow(editUDSRowRequest, savedMtbColr -> { - mtbColrToUpdate.setNumCnf(savedMtbColr.getNumCnf()) - .setQtaCnf(savedMtbColr.getQtaCnf()) - .setQtaCol(savedMtbColr.getQtaCol()); + var savedMtbColr = this.mColliScaricoRESTConsumer.editUDSRowSynchronized(editUDSRowRequest); - Optional pickingObjectDTO = this.mPickingList.getValue().stream() - .filter(x -> x.getWithdrawMtbColrs().stream() - .anyMatch(y -> y == mtbColrToUpdate)) - .findFirst(); + mtbColrToUpdate.setNumCnf(savedMtbColr.getNumCnf()) + .setQtaCnf(savedMtbColr.getQtaCnf()) + .setQtaCol(savedMtbColr.getQtaCol()); - if (pickingObjectDTO.isPresent()) { - pickingObjectDTO.get().getWithdrawMtbColrs().remove(mtbColrToUpdate); - pickingObjectDTO.get().getWithdrawMtbColrs().add(mtbColrToUpdate); - } + Optional pickingObjectDTO = this.mPickingList.getValue().stream() + .filter(x -> x.getWithdrawMtbColrs().stream() + .anyMatch(y -> y == mtbColrToUpdate)) + .findFirst(); - this.mCurrentMtbColt.getMtbColr().remove(mtbColrToUpdate); - this.mCurrentMtbColt.getMtbColr().add(mtbColrToUpdate); + if (pickingObjectDTO.isPresent()) { + pickingObjectDTO.get().getWithdrawMtbColrs().remove(mtbColrToUpdate); + pickingObjectDTO.get().getWithdrawMtbColrs().add(mtbColrToUpdate); + } - this.resetMatchedRows(); - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); - }, this::sendError); + this.mCurrentMtbColt.getMtbColr().remove(mtbColrToUpdate); + this.mCurrentMtbColt.getMtbColr().add(mtbColrToUpdate); + + this.resetMatchedRows(); + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); } - public void requestDeleteRow(MtbColr mtbColrToDelete) { - this.sendMtbColrDeleteRequest(canDelete -> { - if (!canDelete) - return; + public void requestDeleteRow(MtbColr mtbColrToDelete) throws Exception { + var canDelete = this.sendMtbColrDeleteRequest(); + if (!canDelete) + return; - this.sendOnLoadingStarted(); + this.sendOnLoadingStarted(); - var deleteUDSRowRequestoDTO = new DeleteUDSRowRequestDTO() - .setMtbColrToDelete(mtbColrToDelete); + var deleteUDSRowRequestoDTO = new DeleteUDSRowRequestDTO() + .setMtbColrToDelete(mtbColrToDelete); - this.mColliScaricoRESTConsumer.deleteUDSRow(deleteUDSRowRequestoDTO, () -> { - Optional pickingObjectDTO = this.mPickingList.getValue().stream() - .filter(x -> x.getWithdrawMtbColrs().stream().anyMatch(y -> y == mtbColrToDelete)) - .findFirst(); + this.mColliScaricoRESTConsumer.deleteUDSRowSynchronized(deleteUDSRowRequestoDTO); - if (pickingObjectDTO.isPresent()) { - pickingObjectDTO.get().getWithdrawMtbColrs().remove(mtbColrToDelete); - } + Optional pickingObjectDTO = this.mPickingList.getValue().stream() + .filter(x -> x.getWithdrawMtbColrs().stream().anyMatch(y -> y == mtbColrToDelete)) + .findFirst(); - this.mCurrentMtbColt.getMtbColr().remove(mtbColrToDelete); + if (pickingObjectDTO.isPresent()) { + pickingObjectDTO.get().getWithdrawMtbColrs().remove(mtbColrToDelete); + } - this.resetMatchedRows(); - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); - }, this::sendError); + this.mCurrentMtbColt.getMtbColr().remove(mtbColrToDelete); - }); + this.resetMatchedRows(); + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); } - public void requestCloseLU(boolean shouldPrint) { + public void requestCloseLU(boolean shouldPrint) throws Exception { if (mCurrentMtbColt == null) return; this.sendOnLoadingStarted(); - this.checkIfShouldBeDeleted(() -> { - deleteLU(() -> { - this.mCurrentMtbColt = null; + var shouldBeDeleted = this.shouldUlBeDeleted(); + if (shouldBeDeleted) { + deleteLU(); - if (mMtbColtSessionID != null) - this.mColliDataRecoverService.closeSession(mMtbColtSessionID); + this.mCurrentMtbColt = null; - this.mIsNewLU = false; - this.sendLUClosed(); - this.sendOnLoadingEnded(); - }); + if (mMtbColtSessionID != null) + this.mColliDataRecoverService.closeSession(mMtbColtSessionID); - }, () -> { - this.askPeso(() -> { + this.mIsNewLU = false; + this.sendLUClosed(); + this.sendOnLoadingEnded(); - this.askInfoAggiuntive(() -> { + } else { - this.closeLU(generatedMtbColts -> { + this.askPeso(); + this.askInfoAggiuntive(); + var generatedMtbColts = this.closeLU(); - this.validateTheUdsToBeDuplicated(generatedMtbColts, duplicatedMtbColts -> { + var duplicatedMtbColts = this.validateTheUdsToBeDuplicated(generatedMtbColts); - if (duplicatedMtbColts != null) { - generatedMtbColts.addAll(duplicatedMtbColts); - } + if (duplicatedMtbColts != null) { + generatedMtbColts.addAll(duplicatedMtbColts); + } - this.mColliMagazzinoRESTConsumer.fillMtbAartsOfMtbColts(generatedMtbColts, filledMtbColts -> { + var filledMtbColts = this.mColliMagazzinoRESTConsumer.fillMtbAartsOfMtbColtsSynchronized(generatedMtbColts); - this.askPositionChange( - filledMtbColts, - positionedMtbColts -> { + var positionedMtbColts = this.askPositionChange(filledMtbColts); - this.askPrint((shouldPrint && SettingsManager.iDB().isFlagPrintEtichetteOnLUClose()), positionedMtbColts, () -> { - positionedMtbColts.stream() - .filter(x -> !this.mColliRegistrati.contains(x)) - .forEach(x -> this.mColliRegistrati.add(x)); - postCloseOperations(positionedMtbColts); + this.askPrint((shouldPrint && SettingsManager.iDB().isFlagPrintEtichetteOnLUClose()), positionedMtbColts); - this.mIsNewLU = false; + positionedMtbColts.stream() + .filter(x -> !this.mColliRegistrati.contains(x)) + .forEach(x -> this.mColliRegistrati.add(x)); - this.resetMatchedRows(); - this.sendLUClosed(); - this.sendOnLoadingEnded(); - }); + postCloseOperations(positionedMtbColts); - }); + this.mIsNewLU = false; - }, this::sendError); - }); - }); - }); - }); - }); + this.resetMatchedRows(); + this.sendLUClosed(); + this.sendOnLoadingEnded(); + } } - - private void closeLU(RunnableArgs> onComplete) { + private List closeLU() throws Exception { var clonedLuToClose = (MtbColt) this.mCurrentMtbColt.clone(); clonedLuToClose.setMtbColr(null); @@ -1705,12 +1781,11 @@ public class SpedizioneViewModel { } - this.mColliScaricoRESTConsumer.closeUDS(closeUDSRequestDto, closeResponse -> { - onComplete.run(closeResponse.getGeneratedMtbColts()); - }, this::sendError); + var closeResponse = this.mColliScaricoRESTConsumer.closeUDSSynchronized(closeUDSRequestDto); + return closeResponse.getGeneratedMtbColts(); } - private void validateTheUdsToBeDuplicated(List mtbColtList, RunnableArgs> onComplete) { + private List validateTheUdsToBeDuplicated(List mtbColtList) throws Exception { var clonedLu = (MtbColt) this.mCurrentMtbColt.clone(); boolean noReference = clonedLu.getMtbColr().stream() @@ -1722,8 +1797,7 @@ public class SpedizioneViewModel { ); if (mtbColtList.size() > 1 || !noReference || !SettingsManager.iDB().isFlagAskDuplicateUDSSpedizione()) { - onComplete.run(new ArrayList<>()); - return; + return new ArrayList<>(); } var savedMtbColt = mtbColtList.get(0); @@ -1745,88 +1819,91 @@ public class SpedizioneViewModel { BigDecimal qtaEvasa = Objects.requireNonNull(groupedByCodMart.get(codMart)).stream().map(MtbColr::getNumCnf).reduce(BigDecimal.ZERO, BigDecimal::add); - sendInputDuplicate(qtaTot, qtaEvasa, inputNumber -> { - duplicateUDS(savedMtbColt, inputNumber, onComplete); - }, () -> onComplete.run(null)); + var inputNumber = sendInputDuplicate(qtaTot, qtaEvasa); + return duplicateUDS(savedMtbColt, inputNumber); } } } } else { - sendInputDuplicate(inputNumber -> { - duplicateUDS(savedMtbColt, inputNumber, onComplete); - }, () -> onComplete.run(null)); + var inputNumber = sendInputDuplicate(); + return duplicateUDS(savedMtbColt, inputNumber); } + + return null; } - private void duplicateUDS(MtbColt savedMtbColt, Integer inputNumber, RunnableArgs> onComplete) { + private List duplicateUDS(MtbColt savedMtbColt, Integer inputNumber) throws Exception { var duplicateUDSRequestDTO = new DuplicateUDSRequestDTO() .setMtbColt(savedMtbColt) .setNumOfDuplicates(inputNumber); - this.mColliSpedizioneRESTConsumer.duplicateUDS(duplicateUDSRequestDTO, data -> { - Map> groupedByCodMart = data.getMtbColtList() - .stream() - .flatMap(x -> x.getMtbColr().stream()) - .filter(x -> x.getCodMart() != null) - .collect(Collectors.groupingBy(MtbColr::getCodMart)); + var data = this.mColliSpedizioneRESTConsumer.duplicateUDSSynchronized(duplicateUDSRequestDTO); - for (PickingObjectDTO pickingObjectDTO : Objects.requireNonNull(this.mPickingList.getValue())) { - if (pickingObjectDTO.getMtbAart() != null) { - String codMart = pickingObjectDTO.getMtbAart().getCodMart(); - if (groupedByCodMart.containsKey(codMart)) { - pickingObjectDTO.getWithdrawMtbColrs() - .addAll(Objects.requireNonNull(groupedByCodMart.get(codMart))); - } + Map> groupedByCodMart = data.getMtbColtList() + .stream() + .flatMap(x -> x.getMtbColr().stream()) + .filter(x -> x.getCodMart() != null) + .collect(Collectors.groupingBy(MtbColr::getCodMart)); + + for (PickingObjectDTO pickingObjectDTO : Objects.requireNonNull(this.mPickingList.getValue())) { + if (pickingObjectDTO.getMtbAart() != null) { + String codMart = pickingObjectDTO.getMtbAart().getCodMart(); + if (groupedByCodMart.containsKey(codMart)) { + pickingObjectDTO.getWithdrawMtbColrs() + .addAll(Objects.requireNonNull(groupedByCodMart.get(codMart))); } } - onComplete.run(data.getMtbColtList()); - }, this::sendError); + } + + return data.getMtbColtList(); } - private void checkIfShouldBeDeleted(Runnable onDeleted, Runnable onContinue) { + private boolean shouldUlBeDeleted() throws Exception { + var shouldBeDeleted = this.mColliMagazzinoRESTConsumer.canULBeDeletedSynchronized(this.mCurrentMtbColt); - this.mColliMagazzinoRESTConsumer.canULBeDeleted(this.mCurrentMtbColt, - canBeDeleted -> { - if (canBeDeleted == null || !canBeDeleted) - onContinue.run(); - - else onDeleted.run(); - - }, this::sendError); + return shouldBeDeleted != null && shouldBeDeleted; } - private void deleteLU(Runnable onComplete) { - this.mColliMagazzinoRESTConsumer.deleteUL( + private void deleteLU() throws Exception { + this.mColliMagazzinoRESTConsumer.deleteULSynchronized( new DeleteULRequestDTO() - .setMtbColt(this.mCurrentMtbColt), - onComplete, this::sendError); + .setMtbColt(this.mCurrentMtbColt)); } - private void askPeso(Runnable onComplete) { - + private void askPeso() { if (mDefaultSegnoCol != -1 || !mShouldAskPesoLU) { - onComplete.run(); return; } - this.sendLUPesoRequired(mCurrentMtbColt.getCodTcol(), mCurrentMtbColt.getPesoNettoKg(), mCurrentMtbColt.getPesoKg(), (newCodTcol, newNetWeight, newGrossWeight) -> { + final CountDownLatch latch = new CountDownLatch(1); - mCurrentMtbColt.setCodTcol(newCodTcol); - mCurrentMtbColt.setPesoNettoKg(newNetWeight); - mCurrentMtbColt.setPesoKg(newGrossWeight); + this.sendLUPesoRequired(mCurrentMtbColt.getCodTcol(), mCurrentMtbColt.getPesoNettoKg(), mCurrentMtbColt.getPesoKg(), + (newCodTcol, newNetWeight, newGrossWeight) -> { - onComplete.run(); - }); + + if (newCodTcol != null) mCurrentMtbColt.setCodTcol(newCodTcol); + if (newNetWeight != null) mCurrentMtbColt.setPesoNettoKg(newNetWeight); + if (newGrossWeight != null) mCurrentMtbColt.setPesoKg(newGrossWeight); + + latch.countDown(); + }); + + try { + latch.await(); // Attende che il dialog venga chiuso + } catch (InterruptedException e) { + this.sendError(e); + } } - private void askInfoAggiuntive(Runnable onComplete) { + private void askInfoAggiuntive() { if (mDefaultSegnoCol != -1 || !SettingsManager.iDB().isFlagAskInfoAggiuntiveSpedizione()) { - onComplete.run(); return; } + final CountDownLatch latch = new CountDownLatch(1); + this.mListener.onInfoAggiuntiveRequired(mCurrentMtbColt, (note, mtbTcol) -> { mCurrentMtbColt.setAnnotazioni(note); @@ -1838,67 +1915,57 @@ public class SpedizioneViewModel { mCurrentMtbColt.setCodTcol(null); } - onComplete.run(); + latch.countDown(); }); + + try { + latch.await(); // Attende che il dialog venga chiuso + } catch (InterruptedException e) { + this.sendError(e); + } } - private void askPositionChange(List mtbColtsToMove, RunnableArgs> onComplete) { + private List askPositionChange(List mtbColtsToMove) throws Exception { if (mDefaultGestioneOfUL != GestioneEnum.LAVORAZIONE || mDefaultSegnoCol != 1 || !this.mIsNewLU) { - onComplete.run(mtbColtsToMove); - return; + return mtbColtsToMove; } - this.sendLUPositionChangeRequest((shouldChangePosition, mtbDepoPosizione) -> { + var response = this.sendLUPositionChangeRequest(); - if (!shouldChangePosition) { - onComplete.run(mtbColtsToMove); - return; - } + if (response == null || !response.first) { + return mtbColtsToMove; + } - if (mtbDepoPosizione == null) { - //Nessuna posizione trovata con questo barcode - this.sendError(new ScannedPositionNotExistException()); - return; - } + var mtbDepoPosizione = response.second; + if (mtbDepoPosizione == null) { + //Nessuna posizione trovata con questo barcode + throw new ScannedPositionNotExistException(); + } - if (!mtbDepoPosizione.isFlagMonoCollo()) { - //La posizione non è Mono-UL - this.sendError(new CurrentMonoLUPositionIsNotCorrectException()); - return; - } + if (!mtbDepoPosizione.isFlagMonoCollo()) { + //La posizione non è Mono-UL + throw new CurrentMonoLUPositionIsNotCorrectException(); + } - this.mPosizioneRESTConsumer.getBancaliInPosizione(mtbDepoPosizione, destMtbColtList -> { + var destMtbColtList = this.mPosizioneRESTConsumer.getBancaliInPosizioneSynchronized(mtbDepoPosizione); - if (destMtbColtList == null || destMtbColtList.size() != 1) { - //Nessuna UL trovata oppure più UL nella stessa posizione - this.sendError(new NoLUFoundException()); - return; + if (destMtbColtList == null || destMtbColtList.size() != 1) { + //Nessuna UL trovata oppure più UL nella stessa posizione + throw new NoLUFoundException(); + } - } + if (destMtbColtList.get(0).getSegno() != mDefaultSegnoCol) { + throw new InvalidLUException(); - if (destMtbColtList.get(0).getSegno() != mDefaultSegnoCol) { - this.sendError(new InvalidLUException()); - return; - - } - - moveLUtoLU(mtbColtsToMove, destMtbColtList.get(0), savedMtbColt -> { - ArrayList savedMtbColtList = new ArrayList<>(); - savedMtbColtList.add(savedMtbColt); - onComplete.run(savedMtbColtList); - }); - - - }, this::sendError); - - - }); + } + var savedMtbColt = moveLUtoLU(mtbColtsToMove, destMtbColtList.get(0)); + return savedMtbColt; } - private void askPrint(boolean canPrint, List mtbColtsToPrint, Runnable onComplete) { + private void askPrint(boolean canPrint, List mtbColtsToPrint) { if (mDefaultGestioneOfUL != GestioneEnum.VENDITA || mDefaultSegnoCol != -1 || @@ -1906,36 +1973,51 @@ public class SpedizioneViewModel { mtbColtsToPrint.isEmpty() || !canPrint) { - onComplete.run(); return; } + final CountDownLatch latch = new CountDownLatch(1); + this.sendLUPrintRequest(shouldPrint -> { if (!shouldPrint) { - onComplete.run(); + latch.countDown(); return; } var printUDSRequestDto = new PrintULRequestDTO() .setMtbColts(mtbColtsToPrint); - this.mColliMagazzinoRESTConsumer.printUL(printUDSRequestDto, onComplete, - ex -> this.sendLUPrintError(ex, onComplete)); + this.mColliMagazzinoRESTConsumer + .printUL(printUDSRequestDto, + latch::countDown, + ex -> this.sendLUPrintError(ex, latch::countDown)); }); + try { + latch.await(); // Attende che il dialog venga chiuso + } catch (InterruptedException e) { + this.sendError(e); + } + + } - private void moveLUtoLU(List sourceMtbColts, MtbColt destMtbColt, RunnableArgs onComplete) { + private List moveLUtoLU(List sourceMtbColts, MtbColt destMtbColt) throws Exception { destMtbColt.setMtbColr(new ObservableArrayList<>()); for (MtbColt sourceMtbColt : sourceMtbColts) { for (MtbColr sourceMtbColr : sourceMtbColt.getMtbColr()) { MtbColr cloneMtbColr = (MtbColr) sourceMtbColr.clone(); - cloneMtbColr.setRiga(null).setNumCollo(null).setGestione((String) null).setDataCollo((String) null).setSerCollo(null).setCausale(MtbColr.Causale.VERSAMENTO); + cloneMtbColr.setRiga(null) + .setNumCollo(null) + .setGestione((String) null) + .setDataCollo((String) null) + .setSerCollo(null) + .setCausale(MtbColr.Causale.VERSAMENTO); cloneMtbColr.setOperation(CommonModelConsts.OPERATION.INSERT); destMtbColt.getMtbColr().add(cloneMtbColr); @@ -1948,9 +2030,8 @@ public class SpedizioneViewModel { destMtbColt.setOperation(CommonModelConsts.OPERATION.INSERT_OR_UPDATE); sourceMtbColts.add(destMtbColt); - this.mColliMagazzinoRESTConsumer.saveColli(sourceMtbColts, data -> { - onComplete.run(destMtbColt); - }, this::sendError); + var data = this.mColliMagazzinoRESTConsumer.saveColliSynchronized(sourceMtbColts); + return data; } @@ -2038,18 +2119,19 @@ public class SpedizioneViewModel { public void closeOrder() { if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose() || SettingsManager.iDB().isFlagPrintPackingListOnOrderClose()) { - this.sendOnCloseOrderPrintRequest(this::onCloseOrderPrintRequest); - } else { - this.onOrderClosedPrintingDone(); + var printRequestResult = this.sendOnCloseOrderPrintRequest(); + this.onCloseOrderPrintRequest(printRequestResult); } + + this.onOrderClosedPrintingDone(); } private void onCloseOrderPrintRequest(PrintOrderCloseDTO dto) { if (!dto.isFlagPrintPackingList() && !dto.isFlagPrintSSCC()) { - onOrderClosedPrintingDone(); return; } - List closedOrders = this.mTestateOrdini.stream() + + List closedOrders = this.mTestateOrdini.parallelStream() .map(ord -> new DtbOrdt() .setDataOrd(ord.getDataOrdS()) .setNumOrd(ord.getNumOrd()) @@ -2059,11 +2141,18 @@ public class SpedizioneViewModel { .collect(Collectors.toList()); dto.setPrintList(closedOrders); - printClosedOrders(dto, this::onOrderClosedPrintingDone, ex -> this.sendLUPrintError(ex, this::sendOnLoadingEnded)); + + try { + printClosedOrders(dto); + } catch (Exception e) { + this.sendLUPrintError(e, () -> { + }); + } + } - private void printClosedOrders(PrintOrderCloseDTO dto, Runnable onSuccess, RunnableArgs onAbort) { - this.mPrinterRESTConsumer.printClosedOrders(dto, SettingsManager.i().getUserSession().getDepo().getCodMdep(), onSuccess, onAbort); + private void printClosedOrders(PrintOrderCloseDTO dto) throws Exception { + this.mPrinterRESTConsumer.printClosedOrdersSynchronized(dto, SettingsManager.i().getUserSession().getDepo().getCodMdep()); } @@ -2127,14 +2216,28 @@ public class SpedizioneViewModel { this.mDocumentRESTConsumer.createDocFromColli(loadCollidto, doc -> this.sendOnOrderClosed(), this::sendError); } - private void sendInputDuplicate(BigDecimal qtaTot, BigDecimal qtaEvasa, RunnableArgs onComplete, Runnable onNegativeClick) { - if (this.mListener != null) - mListener.onInputDuplicate(qtaTot, qtaEvasa, onComplete, onNegativeClick); + private Integer sendInputDuplicate() { + return sendInputDuplicate(null, null); } - private void sendInputDuplicate(RunnableArgs onComplete, Runnable onNegativeClick) { - if (this.mListener != null) - mListener.onInputDuplicate(null, null, onComplete, onNegativeClick); + private Integer sendInputDuplicate(BigDecimal qtaTot, BigDecimal qtaEvasa) { + + final CountDownLatch latch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + + mListener.onInputDuplicate(qtaTot, qtaEvasa, data -> { + result.set(data); + latch.countDown(); + }, latch::countDown); + + try { + latch.await(); // Attende che il dialog venga chiuso + return result.get(); + } catch (InterruptedException e) { + this.sendError(e); + } + + return null; } public SpedizioneViewModel setListeners(Listener listener) { @@ -2152,7 +2255,7 @@ public class SpedizioneViewModel { void onError(Exception ex, boolean useSnackbar); - void onFullItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canBatchLotBeChanged, RunnableArgss onComplete); + void onFullItemDispatched(PickingObjectDTO pickingObjectDTO, MtbAart mtbAart, BigDecimal initialNumCnf, BigDecimal initialQtaCnf, BigDecimal initialQtaTot, BigDecimal totalQtaOrd, BigDecimal totalNumCnfOrd, BigDecimal qtaCnfOrd, BigDecimal totalQtaToBeTaken, BigDecimal totalNumCnfToBeTaken, BigDecimal qtaCnfToBeTaken, BigDecimal totalQtaAvailable, BigDecimal totalNumCnfAvailable, BigDecimal qtaCnfAvailable, String partitaMag, LocalDate dataScad, boolean canOverflowOrderQuantity, boolean canBatchLotBeChanged, RunnableArgs onComplete, Runnable onAbort); void onInfoAggiuntiveRequired(MtbColt currentMtbColt, RunnableArgss onComplete); @@ -2160,13 +2263,13 @@ public class SpedizioneViewModel { void onBatchLotSelectionRequest(List availableBatchLots, RunnableArgs onComplete); - void onCloseOrderPrintRequest(RunnableArgs onComplete); + PrintOrderCloseDTO onCloseOrderPrintRequest(); void onCreateDocsRequest(); void onChooseArtRequest(List artsList, RunnableArgs onComplete); - void onChooseArtsRequest(List artsList, RunnableArgs> onComplete); + void onChooseArtsRequest(List artsList, RunnableArgs> onComplete, Runnable onAbort); void onOrderClosed(); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/print_sscc_list/DialogPrintOrderSSCCListView.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/print_sscc_list/DialogPrintOrderSSCCListView.java index 773d9daf..48ffb931 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/print_sscc_list/DialogPrintOrderSSCCListView.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/print_sscc_list/DialogPrintOrderSSCCListView.java @@ -35,17 +35,18 @@ public class DialogPrintOrderSSCCListView extends BaseDialogFragment { private Context mContext; private DialogPrintOrderSsccListBinding mBindings; private final PrintOrderCloseDTO printOrderCloseDTO; - private final RunnableArgs onDialogClose; + private final Result result = new Result(); + private final RunnableArgs onDialogClose; public static DialogPrintOrderSSCCListView newInstance( PrintOrderCloseDTO printOrderCloseDTO, - RunnableArgs onDismiss + RunnableArgs onDismiss ) { return new DialogPrintOrderSSCCListView(printOrderCloseDTO, onDismiss); } - public DialogPrintOrderSSCCListView(@NotNull PrintOrderCloseDTO printOrderCloseDTO, @NotNull RunnableArgs onDismiss) { + public DialogPrintOrderSSCCListView(@NotNull PrintOrderCloseDTO printOrderCloseDTO, @NotNull RunnableArgs onDismiss) { this.printOrderCloseDTO = printOrderCloseDTO; this.onDialogClose = onDismiss; } @@ -71,22 +72,22 @@ public class DialogPrintOrderSSCCListView extends BaseDialogFragment { } public void onCheckChange(RadioGroup radioGroup, int id) { - this.printOrderCloseDTO.setFlagSkipPrintedSSCC(id == mBindings.printOnlyNew.getId()); + this.result.setFlagSkipPrintedSSCC(id == mBindings.printOnlyNew.getId()); } public void onPositiveClick() { - this.printOrderCloseDTO.setFlagPrintSSCC(true); + this.result.setFlagPrintSSCC(true); this.dismiss(); } public void onNegativeClick() { - this.printOrderCloseDTO.setFlagPrintSSCC(false); + this.result.setFlagPrintSSCC(false); this.dismiss(); } @Override public void onDismiss(@NonNull DialogInterface dialog) { - this.onDialogClose.run(this.printOrderCloseDTO); + this.onDialogClose.run(this.result); super.onDismiss(dialog); } @@ -112,4 +113,26 @@ public class DialogPrintOrderSSCCListView extends BaseDialogFragment { UtilityExceptions.defaultException(this.mContext, ex); dismiss(); } + + + public class Result { + private boolean flagPrintSSCC = false; + private boolean flagSkipPrintedSSCC = true; + + public boolean isFlagPrintSSCC() { + return flagPrintSSCC; + } + + private void setFlagPrintSSCC(boolean flagPrintSSCC) { + this.flagPrintSSCC = flagPrintSSCC; + } + + public boolean isFlagSkipPrintedSSCC() { + return flagSkipPrintedSSCC; + } + + private void setFlagSkipPrintedSSCC(boolean flagSkipPrintedSSCC) { + this.flagSkipPrintedSSCC = flagSkipPrintedSSCC; + } + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/row_info/info_situazione_articolo/DialogInfoSituazioneArticoloView.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/row_info/info_situazione_articolo/DialogInfoSituazioneArticoloView.java index 827c02e6..267e15b9 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/row_info/info_situazione_articolo/DialogInfoSituazioneArticoloView.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/dialogs/row_info/info_situazione_articolo/DialogInfoSituazioneArticoloView.java @@ -4,6 +4,7 @@ import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; +import android.os.Handler; import android.view.LayoutInflater; import android.view.View; @@ -18,6 +19,7 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Inject; @@ -42,6 +44,12 @@ public class DialogInfoSituazioneArticoloView extends BaseDialogRowInfoView { @Inject GiacenzaRESTConsumer giacenzaRESTConsumer; + @Inject + ExecutorService executorService; + + @Inject + Handler handler; + private DialogInfoSituazioneArticoloBinding mBindings; private Context mContext; @@ -86,24 +94,33 @@ public class DialogInfoSituazioneArticoloView extends BaseDialogRowInfoView { String partitaMag = getSpedizioneListModel().getOriginalModel().getSitArtOrdDTO().getPartitaMag(); String codJcom = getSpedizioneListModel().getOriginalModel().getSitArtOrdDTO().getCodJcom(); - giacenzaRESTConsumer.getInstantItemSituation( - codMdep, - codMart, - partitaMag, - codJcom, - result -> { - this.initIncomingItemsList(result.getIncomingItems()); - this.initAvailableItemsList(result.getAvailableItems()); + this.onLoadingStarted(); + executorService.execute(() -> { + try { + var result = giacenzaRESTConsumer.getInstantItemSituationSynchronized(codMdep, codMart, partitaMag, codJcom); - this.onLoadingEnded(); - }, this::onError); + + handler.post(() -> { + try { + if(result != null && result.getIncomingItems() != null) this.initIncomingItemsList(result.getIncomingItems()); + if(result != null && result.getAvailableItems() != null) this.initAvailableItemsList(result.getAvailableItems()); + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } + }); + + } catch (Exception e) { + onError(e); + } + }); } private void initIncomingItemsList(List incomingItems) { mBindings.incomingLabel.setVisibility(incomingItems == null || incomingItems.isEmpty() ? View.GONE : View.VISIBLE); - if(incomingItems == null || incomingItems.isEmpty()) + if (incomingItems == null || incomingItems.isEmpty()) return; new LiveAdapter(incomingItems, BR.item) @@ -115,14 +132,14 @@ public class DialogInfoSituazioneArticoloView extends BaseDialogRowInfoView { private void initAvailableItemsList(List availableItems) { mBindings.availableLabel.setVisibility(availableItems == null || availableItems.isEmpty() ? View.GONE : View.VISIBLE); - if(availableItems == null) + if (availableItems == null) availableItems = new ArrayList<>(); availableItems = Stream.of(availableItems) .filter(x -> x.getDataScad() == null || UtilityDate.isAfterToday(x.getDataScad())) .toList(); - if(availableItems.isEmpty()) + if (availableItems.isEmpty()) return; var preferedCodJcom = getSpedizioneListModel().getOriginalModel().getSitArtOrdDTO().getCodJcom(); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/model/PickedQuantityDTO.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/model/PickedQuantityDTO.java index d41e3ed6..6e6c6b98 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/model/PickedQuantityDTO.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/model/PickedQuantityDTO.java @@ -3,6 +3,8 @@ package it.integry.integrywmsnative.gest.spedizione.model; import java.math.BigDecimal; import java.time.LocalDate; +import it.integry.barcode_base_android_library.model.BarcodeScanDTO; + public class PickedQuantityDTO { private String partitaMag; @@ -12,6 +14,9 @@ public class PickedQuantityDTO { private BigDecimal qtaCnf; private BigDecimal qtaTot; + private BarcodeScanDTO nextUlBarcode; + private boolean shouldCloseLu; + public String getPartitaMag() { return partitaMag; } @@ -56,4 +61,22 @@ public class PickedQuantityDTO { this.qtaTot = qtaTot; return this; } + + public BarcodeScanDTO getNextUlBarcode() { + return nextUlBarcode; + } + + public PickedQuantityDTO setNextUlBarcode(BarcodeScanDTO nextUlBarcode) { + this.nextUlBarcode = nextUlBarcode; + return this; + } + + public boolean isShouldCloseLu() { + return shouldCloseLu; + } + + public PickedQuantityDTO setShouldCloseLu(boolean shouldCloseLu) { + this.shouldCloseLu = shouldCloseLu; + return this; + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/UltimeConsegneClienteFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/UltimeConsegneClienteFragment.java index 8b6fde24..46c7c765 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/UltimeConsegneClienteFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/UltimeConsegneClienteFragment.java @@ -47,7 +47,7 @@ public class UltimeConsegneClienteFragment extends BaseFragment implements Ultim private final List mOnPreDestroyList = new ArrayList<>(); private ElevatedToolbar mToolbar; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private final ObservableArrayList mDocumentiMutableData = new ObservableArrayList<>(); @@ -112,10 +112,14 @@ public class UltimeConsegneClienteFragment extends BaseFragment implements Ultim public void openFilterDialog() { this.mViewModel.loadCodAnagClienti(gtbAnags -> { - DialogUltimeConsegneFiltroAvanzato.make(getActivity(), gtbAnags, mAppliedFilterViewModel, (filter) -> { - mAppliedFilterViewModel = filter; - refreshItems(); - }).show(); + handler.post(() -> { + + DialogUltimeConsegneFiltroAvanzato.make(getActivity(), gtbAnags, mAppliedFilterViewModel, (filter) -> { + mAppliedFilterViewModel = filter; + refreshItems(); + }).show(); + + }); }); } @@ -132,24 +136,24 @@ public class UltimeConsegneClienteFragment extends BaseFragment implements Ultim // mBindings.fastscroll.setRecyclerView(mBindings.recyclerView); - if(mToolbar != null) + if (mToolbar != null) mToolbar.setRecyclerView(mBindings.recyclerView); } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); this.mViewModel.processBarcodeDTO(data, () -> { - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }); }; diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/dialog/DialogUltimeConsegneFiltroAvanzato.java b/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/dialog/DialogUltimeConsegneFiltroAvanzato.java index b072fe8f..96f1a7e6 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/dialog/DialogUltimeConsegneFiltroAvanzato.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ultime_consegne_cliente/dialog/DialogUltimeConsegneFiltroAvanzato.java @@ -9,7 +9,6 @@ import android.view.WindowManager; import android.widget.ArrayAdapter; import androidx.appcompat.app.AlertDialog; -import androidx.databinding.DataBindingUtil; import com.annimon.stream.Stream; import com.annimon.stream.function.Predicate; @@ -65,7 +64,7 @@ public class DialogUltimeConsegneFiltroAvanzato { DialogUltimeConsegneFiltroAvanzatoViewModel viewModel = baseViewModel != null ? baseViewModel : new DialogUltimeConsegneFiltroAvanzatoViewModel(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - DialogUltimeConsegneFiltroAvanzatoBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_ultime_consegne_filtro_avanzato, null, false); + DialogUltimeConsegneFiltroAvanzatoBinding binding = DialogUltimeConsegneFiltroAvanzatoBinding.inflate(inflater, null, false); final AlertDialog.Builder dialog = new AlertDialog.Builder(context) .setView(binding.getRoot()); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/UltimiArriviFornitoreFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/UltimiArriviFornitoreFragment.java index 239deef7..65f3d3a2 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/UltimiArriviFornitoreFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/UltimiArriviFornitoreFragment.java @@ -54,7 +54,7 @@ public class UltimiArriviFornitoreFragment extends BaseFragment implements ITitl private final List mOnPreDestroyList = new ArrayList<>(); private ElevatedToolbar mToolbar; - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; private final ObservableArrayList mDocumentiMutableData = new ObservableArrayList<>(); @@ -117,10 +117,12 @@ public class UltimiArriviFornitoreFragment extends BaseFragment implements ITitl public void openFilterDialog() { this.mViewModel.loadCodAnagFornitori(gtbAnags -> { - DialogUltimiArriviFornitoreFiltroAvanzato.make(getActivity(), gtbAnags, mAppliedFilterViewModel, (filter) -> { - mAppliedFilterViewModel = filter; - filterItems(null); - }).show(); + handler.post(() -> { + DialogUltimiArriviFornitoreFiltroAvanzato.make(getActivity(), gtbAnags, mAppliedFilterViewModel, (filter) -> { + mAppliedFilterViewModel = filter; + filterItems(null); + }).show(); + }); }); } @@ -142,18 +144,18 @@ public class UltimiArriviFornitoreFragment extends BaseFragment implements ITitl } private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); this.mViewModel.processBarcodeDTO(data, () -> { - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }); }; @@ -222,7 +224,7 @@ public class UltimiArriviFornitoreFragment extends BaseFragment implements ITitl @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); for (Runnable onPreDestroy : mOnPreDestroyList) { onPreDestroy.run(); @@ -259,7 +261,7 @@ public class UltimiArriviFornitoreFragment extends BaseFragment implements ITitl .newInstance(scannedMtbColt.getMtbColr(), items -> { List mtbAarts = new ArrayList<>(); - if(items != null && !items.isEmpty()) { + if (items != null && !items.isEmpty()) { mtbAarts = Stream.of(items) .map(MtbColr::getMtbAart) .toList(); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/dialog/DialogUltimiArriviFornitoreFiltroAvanzato.java b/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/dialog/DialogUltimiArriviFornitoreFiltroAvanzato.java index 824079d7..6d7b94b1 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/dialog/DialogUltimiArriviFornitoreFiltroAvanzato.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/dialog/DialogUltimiArriviFornitoreFiltroAvanzato.java @@ -9,7 +9,6 @@ import android.view.WindowManager; import android.widget.ArrayAdapter; import androidx.appcompat.app.AlertDialog; -import androidx.databinding.DataBindingUtil; import com.annimon.stream.Stream; import com.annimon.stream.function.Predicate; @@ -63,7 +62,7 @@ public class DialogUltimiArriviFornitoreFiltroAvanzato { DialogUltimiArriviFiltroAvanzatoViewModel viewModel = baseViewModel != null ? baseViewModel : new DialogUltimiArriviFiltroAvanzatoViewModel(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - DialogUltimiArriviFornitoreFiltroAvanzatoBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_ultimi_arrivi_fornitore_filtro_avanzato, null, false); + DialogUltimiArriviFornitoreFiltroAvanzatoBinding binding = DialogUltimiArriviFornitoreFiltroAvanzatoBinding.inflate(inflater,null, false); final AlertDialog.Builder dialog = new AlertDialog.Builder(context) .setView(binding.getRoot()); diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceFragment.java index b4f5cf7f..f9afe54a 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceFragment.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceFragment.java @@ -59,7 +59,7 @@ public class VersamentoMerceFragment extends BaseFragment implements ITitledFrag private final List mOnPreDestroyList = new ArrayList<>(); - private int barcodeScannerIstanceID = -1; + private int mBarcodeScannerInstanceID = -1; public static VersamentoMerceFragment newInstance() { @@ -98,7 +98,7 @@ public class VersamentoMerceFragment extends BaseFragment implements ITitledFrag @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); for (Runnable onPreDestroy : mOnPreDestroyList) { onPreDestroy.run(); @@ -126,11 +126,11 @@ public class VersamentoMerceFragment extends BaseFragment implements ITitledFrag private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private final RunnableArgs onScanSuccessful = data -> { @@ -216,7 +216,12 @@ public class VersamentoMerceFragment extends BaseFragment implements ITitledFrag this.requireActivity().runOnUiThread(() -> { mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) - .setOnComplete((resultDTO, shouldCloseLU) -> { + .setOnComplete(resultDTO -> { + + if(resultDTO == null || resultDTO.isAborted()) { + this.onLoadingEnded(); + return; + } PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) diff --git a/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceViewModel.java index 82389768..62d37e55 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/versamento_merce/VersamentoMerceViewModel.java @@ -14,7 +14,7 @@ import java.util.List; import javax.inject.Inject; import it.integry.barcode_base_android_library.model.BarcodeScanDTO; -import it.integry.integrywmsnative.core.exception.InvalidCodMdepLUException; +import it.integry.integrywmsnative.core.exception.InvalidCodMdepException; import it.integry.integrywmsnative.core.exception.InvalidLUGestioneException; import it.integry.integrywmsnative.core.exception.NoArtsInLUException; import it.integry.integrywmsnative.core.exception.NoLUFoundException; @@ -141,7 +141,7 @@ public class VersamentoMerceViewModel { if (codMdepIsValid) { pickMerceULtoUL(mtbColt, onComplete); - } else this.sendError(new InvalidCodMdepLUException()); + } else this.sendError(new InvalidCodMdepException()); }, this::sendError); } else { @@ -198,7 +198,7 @@ public class VersamentoMerceViewModel { if (codMdepIsValid) { pickMerceULtoUL(mtbColt, onComplete); - } else this.sendError(new InvalidCodMdepLUException()); + } else this.sendError(new InvalidCodMdepException()); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentListAdapter.java b/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentListAdapter.java index 201e6f69..30fb1104 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentListAdapter.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentListAdapter.java @@ -1,6 +1,8 @@ package it.integry.integrywmsnative.view.bottom_sheet__lu_content; import android.content.Context; +import android.os.Handler; +import android.os.Looper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -48,10 +50,12 @@ public class BottomSheetFragmentLUContentListAdapter extends RecyclerView.Adapte this.mContext = context; this.mDataset = mtbColrs != null ? mtbColrs : new ArrayList<>(); + Handler handler = new Handler(Looper.getMainLooper()); + mtbColrs.addOnListChangedCallback(new OnListGeneralChangedCallback() { @Override public void onChanged(ObservableList sender) { - notifyDataSetChanged(); + handler.post(() -> notifyDataSetChanged()); } }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentView.java b/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentView.java index ab0b3697..7c4aa05d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/bottom_sheet__lu_content/BottomSheetFragmentLUContentView.java @@ -1,6 +1,8 @@ package it.integry.integrywmsnative.view.bottom_sheet__lu_content; import android.content.Context; +import android.os.Handler; +import android.os.Looper; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; @@ -76,25 +78,31 @@ public class BottomSheetFragmentLUContentView extends BottomSheetFragmentBaseVie } private void initCallbacks() { + Handler handler = new Handler(Looper.getMainLooper()); this.mViewModel.getObservableMtbColt().addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() { @Override public void onPropertyChanged(Observable sender, int propertyId) { - var mtbColt = mViewModel.getObservableMtbColt().get(); + handler.post(() -> { - if (mtbColt != null) { - initAdapter(); + var mtbColt = mViewModel.getObservableMtbColt().get(); - onMtbColrItemChanged(); + if (mtbColt != null) { + initAdapter(); - mtbColt.getMtbColr().addOnListChangedCallback(new OnListGeneralChangedCallback() { - @Override - public void onChanged(ObservableList sender) { - onMtbColrItemChanged(); - } - }); - } else { - mBinding.mtbColrRecyclerView.setAdapter(null); - } + onMtbColrItemChanged(); + + mtbColt.getMtbColr().addOnListChangedCallback(new OnListGeneralChangedCallback() { + @Override + public void onChanged(ObservableList sender) { + handler.post(() -> { + onMtbColrItemChanged(); + }); + } + }); + } else { + mBinding.mtbColrRecyclerView.setAdapter(null); + } + }); } }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_cliente/viewmodel/DialogAskCliente_Page1ViewModel.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_cliente/viewmodel/DialogAskCliente_Page1ViewModel.java index 943e5464..c97a3ef7 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_cliente/viewmodel/DialogAskCliente_Page1ViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_cliente/viewmodel/DialogAskCliente_Page1ViewModel.java @@ -61,7 +61,7 @@ public class DialogAskCliente_Page1ViewModel implements IDialogAskClienteViewMod mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(mContext, ex, false))); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); this.mBinding.buttonYes.setOnClickListener(v -> { if (validateCliente()) { @@ -91,7 +91,7 @@ public class DialogAskCliente_Page1ViewModel implements IDialogAskClienteViewMod private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); String barcode = data.getStringValue(); @@ -118,7 +118,7 @@ public class DialogAskCliente_Page1ViewModel implements IDialogAskClienteViewMod } } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }; diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_commessa/DialogAskCommessaView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_commessa/DialogAskCommessaView.java index 6224038c..432d57a9 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_commessa/DialogAskCommessaView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_commessa/DialogAskCommessaView.java @@ -44,7 +44,7 @@ public class DialogAskCommessaView extends BaseDialogFragment implements DialogA private DialogAskCommessaBinding mBindings; private Context mContext; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private JtbComt selectedJtbComt; @@ -113,7 +113,7 @@ public class DialogAskCommessaView extends BaseDialogFragment implements DialogA public void onDismiss(@NonNull DialogInterface dialog) { super.onDismiss(dialog); - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); } @Override @@ -125,15 +125,15 @@ public class DialogAskCommessaView extends BaseDialogFragment implements DialogA } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); // this.mViewModel.processBarcodeDTO(data, BarcodeManager::enable); }; diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_deposito/DialogAskDepositoViewModel.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_deposito/DialogAskDepositoViewModel.java index 79e79f35..9f06c527 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_deposito/DialogAskDepositoViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_deposito/DialogAskDepositoViewModel.java @@ -9,6 +9,8 @@ import it.integry.barcode_base_android_library.model.BarcodeScanDTO; import it.integry.integrywmsnative.core.exception.InvalidCodMdepBarcodeException; import it.integry.integrywmsnative.core.exception.NoResultFromBarcodeException; import it.integry.integrywmsnative.core.rest.consumers.BarcodeRESTConsumer; +import it.integry.integrywmsnative.core.rest.model.AvailableCodMdepsDTO; +import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.utility.UtilityBarcode; import it.integry.integrywmsnative.core.utility.UtilityString; @@ -17,7 +19,7 @@ public class DialogAskDepositoViewModel { Handler handler; BarcodeRESTConsumer barcodeRESTConsumer; - private MutableLiveData codMdep = new MutableLiveData<>(); + private final MutableLiveData codMdep = new MutableLiveData<>(); private Listener listener; public DialogAskDepositoViewModel(Handler handler, BarcodeRESTConsumer barcodeRESTConsumer) { @@ -45,14 +47,14 @@ public class DialogAskDepositoViewModel { throw new InvalidCodMdepBarcodeException(barcodeScanDTO.getStringValue()); } -// AvailableCodMdepsDTO availableCodMdepsDTO = SettingsManager.iDB().getAvailableCodMdep().stream() -// .filter(x -> x.getCodMdep().equalsIgnoreCase(ean128Model.Internal4)) -// .findFirst() -// .orElse(null); -// -// if (availableCodMdepsDTO == null) { -// throw new InvalidCodMdepBarcodeException(barcodeScanDTO.getStringValue()); -// } + AvailableCodMdepsDTO availableCodMdepsDTO = SettingsManager.iDB().getAvailableCodMdep().stream() + .filter(x -> x.getCodMdep().equalsIgnoreCase(ean128Model.Internal4)) + .findFirst() + .orElse(null); + + if (availableCodMdepsDTO == null) { + throw new InvalidCodMdepBarcodeException(ean128Model.Internal4); + } handler.post(() -> { this.codMdep.setValue(ean128Model.Internal4); diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_linea_prod/DialogAskLineaProdView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_linea_prod/DialogAskLineaProdView.java index 2b0709b0..268d7632 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_linea_prod/DialogAskLineaProdView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_linea_prod/DialogAskLineaProdView.java @@ -35,7 +35,7 @@ public class DialogAskLineaProdView extends BaseDialogFragment implements Dialog private Context mContext; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; //Pass here all external parameters public static DialogAskLineaProdView newInstance(RunnableArgs onComplete, Runnable onAbort) { @@ -89,16 +89,16 @@ public class DialogAskLineaProdView extends BaseDialogFragment implements Dialog } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); - this.mViewModel.processBarcodeDTO(data, BarcodeManager::enable); + BarcodeManager.disable(mBarcodeScannerInstanceID); + this.mViewModel.processBarcodeDTO(data, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)); }; @Override @@ -110,7 +110,7 @@ public class DialogAskLineaProdView extends BaseDialogFragment implements Dialog @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onDismiss(dialog); } } \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_position_of_lu/DialogAskPositionOfLUView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_position_of_lu/DialogAskPositionOfLUView.java index ee0f31c6..43dd4ff9 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_position_of_lu/DialogAskPositionOfLUView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_position_of_lu/DialogAskPositionOfLUView.java @@ -4,6 +4,7 @@ import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; +import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; @@ -43,6 +44,10 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { @Inject DialogAskPositionOfLUViewModel mViewModel; + @Inject + Handler handler; + + private DialogAskPositionOfLuBinding mBindings; private DialogAskPositionOfLUAdapter viewpagerAdapter; private Context mContext; @@ -167,8 +172,6 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); - - BarcodeManager.enable(); } @Override @@ -180,7 +183,7 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { private final RunnableArgs onScanSuccessfull = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); if (!isOnLivelloPage()) { @@ -191,11 +194,10 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { if (!mCheckForLineaProd && !currentMtbDepoPosizione.isFlagLineaProduzione() && UtilityPosizione.isPosizioneWithLivello(foundPosizione)) { askLivello(); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } else { completedFlow = true; - BarcodeManager.enable(); if (onComplete != null) onComplete.run(DialogConsts.Results.YES, foundPosizione); @@ -203,14 +205,19 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { } } else { - BarcodeManager.enable(); - Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) - .show(); + BarcodeManager.enable(mBarcodeScannerInstanceID); + + handler.post(() -> { + Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) + .show(); + }); } } else { - Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) - .show(); - BarcodeManager.enable(); + handler.post(() -> { + Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) + .show(); + }); + BarcodeManager.enable(mBarcodeScannerInstanceID); } }; diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_unknown_barcode_notes/DialogAskUnknownBarcodeNotesView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_unknown_barcode_notes/DialogAskUnknownBarcodeNotesView.java index ce6b0ece..f0296cc9 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_unknown_barcode_notes/DialogAskUnknownBarcodeNotesView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/ask_unknown_barcode_notes/DialogAskUnknownBarcodeNotesView.java @@ -37,7 +37,7 @@ public class DialogAskUnknownBarcodeNotesView extends BaseDialogFragment { private final Runnable onAbort; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; //Pass here all external parameters public static DialogAskUnknownBarcodeNotesView newInstance(String unknownBarcode, RunnableArgs onComplete, Runnable onAbort) { @@ -108,17 +108,17 @@ public class DialogAskUnknownBarcodeNotesView extends BaseDialogFragment { @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); - BarcodeManager.enable(); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); + BarcodeManager.enable(mBarcodeScannerInstanceID); super.onDismiss(dialog); } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); setBarcodeListener(true); } @@ -137,6 +137,6 @@ public class DialogAskUnknownBarcodeNotesView extends BaseDialogFragment { @Override public void onError(Exception ex) { super.onError(ex); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } } \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/base/DialogSimpleMessageView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/base/DialogSimpleMessageView.java index 69bde96f..c4ede104 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/base/DialogSimpleMessageView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/base/DialogSimpleMessageView.java @@ -107,12 +107,13 @@ public class DialogSimpleMessageView extends BaseDialogFragment { mBindings.setView(this); mBindings.setLifecycleOwner(this); + setCancelable(false); this.initContent(); var alertDialogBuilder = new MaterialAlertDialogBuilder(requireContext()) .setView(mBindings.getRoot()) - .setCancelable(false); + .setCancelable(isCancelable()); if (isPositiveVisible()) alertDialogBuilder.setPositiveButton(getPositiveButtonText(), (dialog, which) -> { @@ -130,7 +131,7 @@ public class DialogSimpleMessageView extends BaseDialogFragment { }); var alertDialog = alertDialogBuilder.create(); - alertDialog.setCanceledOnTouchOutside(false); + alertDialog.setCanceledOnTouchOutside(isCancelable()); return alertDialog; } @@ -188,6 +189,8 @@ public class DialogSimpleMessageView extends BaseDialogFragment { } + + public boolean isPositiveVisible() { return mOnPositiveClick != null || (!isNeutralVisible() && !isNegativeVisible()); } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/bind_product_barcode_with_package/DialogBindProductBarcodeWithPackageView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/bind_product_barcode_with_package/DialogBindProductBarcodeWithPackageView.java index 129eb719..ff0c457f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/bind_product_barcode_with_package/DialogBindProductBarcodeWithPackageView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/bind_product_barcode_with_package/DialogBindProductBarcodeWithPackageView.java @@ -35,7 +35,7 @@ public class DialogBindProductBarcodeWithPackageView extends BaseDialogFragment private final Runnable onAbort; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; //Pass here all external parameters public static DialogBindProductBarcodeWithPackageView newInstance(String unknownBarcode,Runnable onAbort) { @@ -85,8 +85,8 @@ public class DialogBindProductBarcodeWithPackageView extends BaseDialogFragment @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); - BarcodeManager.enable(); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); + BarcodeManager.enable(mBarcodeScannerInstanceID); super.onDismiss(dialog); } @@ -94,10 +94,10 @@ public class DialogBindProductBarcodeWithPackageView extends BaseDialogFragment private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); setBarcodeListener(true); } @@ -116,6 +116,6 @@ public class DialogBindProductBarcodeWithPackageView extends BaseDialogFragment @Override public void onError(Exception ex) { super.onError(ex); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } } \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsAdapter.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsAdapter.java deleted file mode 100644 index c522e3eb..00000000 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsAdapter.java +++ /dev/null @@ -1,77 +0,0 @@ -package it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.ViewGroup; - -import androidx.databinding.DataBindingUtil; -import androidx.recyclerview.widget.RecyclerView; - -import java.util.List; - -import it.integry.integrywmsnative.R; -import it.integry.integrywmsnative.core.interfaces.IRecyclerItemClicked; -import it.integry.integrywmsnative.core.model.MtbAart; -import it.integry.integrywmsnative.databinding.DialogChooseArtFromListaArtItemModelBinding; - -public class DialogChooseArtFromListaArtsAdapter extends RecyclerView.Adapter { - - protected Context mContext; - - private List mDataset; - private final IRecyclerItemClicked mOnItemClickListener; - - public static class ViewHolder extends RecyclerView.ViewHolder { - protected DialogChooseArtFromListaArtItemModelBinding mViewDataBinding; - - - public ViewHolder(DialogChooseArtFromListaArtItemModelBinding v) { - super(v.getRoot()); - mViewDataBinding = v; - } - - public void bind(MtbAart mtbAart) { - mViewDataBinding.setItem(mtbAart); - mViewDataBinding.executePendingBindings(); - } - } - - public DialogChooseArtFromListaArtsAdapter(Context context, List myDataset, IRecyclerItemClicked onItemClickListener) { - mContext = context; - mDataset = myDataset; - mOnItemClickListener = onItemClickListener; - } - - @Override - public DialogChooseArtFromListaArtsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - // create a new view - DialogChooseArtFromListaArtItemModelBinding viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.dialog_choose_art_from_lista_art__item_model, parent, false); - - return new ViewHolder(viewDataBinding); - } - - @Override - public void onBindViewHolder(DialogChooseArtFromListaArtsAdapter.ViewHolder holder, int position) { - MtbAart item = mDataset.get(position); - holder.bind(item); - - holder.mViewDataBinding.getRoot().setOnClickListener(x -> { - if(mOnItemClickListener != null) { - mOnItemClickListener.onItemClick(item, position); - } - }); - } - - @Override - public void onViewRecycled(DialogChooseArtFromListaArtsAdapter.ViewHolder holder) { - super.onViewRecycled(holder); - } - - @Override - public int getItemCount() { - return mDataset.size(); - } - - - -} diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsComponent.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsComponent.java new file mode 100644 index 00000000..e972c960 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsComponent.java @@ -0,0 +1,14 @@ +package it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts; + +import dagger.Subcomponent; + +@Subcomponent +public interface DialogChooseArtFromListaArtsComponent { + + @Subcomponent.Factory + interface Factory { + DialogChooseArtFromListaArtsComponent create(); + } + + void inject(DialogChooseArtFromListaArtsView dialogChooseArtFromListaArtsView); +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsModule.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsModule.java new file mode 100644 index 00000000..c38d4ccd --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsModule.java @@ -0,0 +1,14 @@ +package it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts; + +import dagger.Module; +import dagger.Provides; + +@Module(subcomponents = DialogChooseArtFromListaArtsComponent.class) +public class DialogChooseArtFromListaArtsModule { + + @Provides + DialogChooseArtFromListaArtsViewModel providesDialogChooseArtFromListaArtsViewModel() { + return new DialogChooseArtFromListaArtsViewModel(); + } + +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsView.java index eed2e817..5b2b1319 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsView.java @@ -1,6 +1,8 @@ package it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts; import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; @@ -10,76 +12,116 @@ import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.material.dialog.MaterialAlertDialogBuilder; +import com.ravikoradiya.liveadapter.LiveAdapter; +import com.ravikoradiya.liveadapter.Type; import java.util.List; +import java.util.Objects; +import javax.inject.Inject; + +import it.integry.integrywmsnative.BR; +import it.integry.integrywmsnative.MainApplication; import it.integry.integrywmsnative.R; import it.integry.integrywmsnative.core.expansion.BaseDialogFragment; import it.integry.integrywmsnative.core.expansion.RunnableArgs; -import it.integry.integrywmsnative.core.interfaces.IRecyclerItemClicked; import it.integry.integrywmsnative.core.model.MtbAart; -import it.integry.integrywmsnative.databinding.DialogChooseArtFromListaArtBinding; +import it.integry.integrywmsnative.databinding.DialogChooseArtFromListaArtItemModelBinding; +import it.integry.integrywmsnative.databinding.DialogChooseArtFromListaArtsBinding; import it.integry.integrywmsnative.ui.SimpleDividerItemDecoration; +import kotlin.Unit; public class DialogChooseArtFromListaArtsView extends BaseDialogFragment { + @Inject + DialogChooseArtFromListaArtsViewModel mViewModel; - + private DialogChooseArtFromListaArtsBinding mBindings; + private Context mContext; + private final RunnableArgs onComplete; private final boolean mEnableSelection; private final List mListaArts; - private final RunnableArgs mOnItemChoosed; + //Pass here all external parameters + public static DialogChooseArtFromListaArtsView newInstance(boolean enableSelection, List listaArts, RunnableArgs onComplete) { + return new DialogChooseArtFromListaArtsView(enableSelection, listaArts, onComplete); + } - public DialogChooseArtFromListaArtsView(boolean enableSelection, List listaArts, RunnableArgs onItemChoosed) { + private DialogChooseArtFromListaArtsView(boolean enableSelection, List listaArts, RunnableArgs onComplete) { super(); - + this.onComplete = onComplete; this.mEnableSelection = enableSelection; this.mListaArts = listaArts; - this.mOnItemChoosed = onItemChoosed; + + MainApplication.appComponent + .dialogChooseArtFromListaArtsComponent() + .create() + .inject(this); } @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { - var binding = DialogChooseArtFromListaArtBinding.inflate(LayoutInflater.from(requireContext())); + this.mContext = requireContext(); - binding.titleText.setText(this.mEnableSelection ? R.string.dialog_choose_art_from_lista_art : + mBindings = DialogChooseArtFromListaArtsBinding.inflate(LayoutInflater.from(this.mContext), null, false); + mBindings.setLifecycleOwner(this); + + mBindings.titleText.setText(this.mEnableSelection ? R.string.dialog_choose_art_from_lista_art : R.string.articoli_disponibili); - initRecyclerView(binding, mListaArts); + initRecyclerView(mBindings, mListaArts); - setCancelable(false); + setCancelable(true); - var alertDialog = new MaterialAlertDialogBuilder(requireContext()) - .setView(binding.getRoot()) + var alertDialog = new MaterialAlertDialogBuilder(this.mContext) + .setView(mBindings.getRoot()) .setCancelable(isCancelable()) .create(); alertDialog.setCanceledOnTouchOutside(isCancelable()); alertDialog.setOnShowListener(this); + alertDialog.setOnDismissListener(this); return alertDialog; } - private void initRecyclerView(DialogChooseArtFromListaArtBinding binding, List dataset) { + @Override + public void dismiss() { + dismiss(null); + } + + @Override + public void onDismiss(@NonNull DialogInterface dialog) { + dismiss(); + } + + public void dismiss(MtbAart item) { + if (getDialog() != null) getDialog().dismiss(); + onComplete.run(item); + } + + private void initRecyclerView(DialogChooseArtFromListaArtsBinding binding, List dataset) { binding.itemsList.setNestedScrollingEnabled(false); binding.itemsList.setHasFixedSize(true); binding.itemsList.setLayoutManager(new LinearLayoutManager(requireContext())); SimpleDividerItemDecoration itemDecorator = new SimpleDividerItemDecoration(requireContext(), SimpleDividerItemDecoration.VERTICAL); - itemDecorator.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.divider)); + itemDecorator.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(requireContext(), R.drawable.divider))); binding.itemsList.addItemDecoration(itemDecorator); - IRecyclerItemClicked onItemClickListener = (item, position) -> { - if (mOnItemChoosed != null) { - mOnItemChoosed.run(item); - } + var itemType = new Type(R.layout.dialog_choose_art_from_lista_art__item_model, BR.item); - dismiss(); - }; + itemType.onClick(x -> { + dismiss(x.getBinding().getItem()); + return null; + }); - DialogChooseArtFromListaArtsAdapter mCurrentAdapter = new DialogChooseArtFromListaArtsAdapter( - requireContext(), dataset, this.mEnableSelection ? onItemClickListener : null); - binding.itemsList.setAdapter(mCurrentAdapter); + new LiveAdapter(dataset, BR.item) + .map(MtbAart.class, itemType) + .onNoData(noData -> { +// mBindings.emptyView.setVisibility(noData ? View.VISIBLE : View.GONE); + return Unit.INSTANCE; + }) + .into(this.mBindings.itemsList); } - -} +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsViewModel.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsViewModel.java new file mode 100644 index 00000000..1580e077 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_art_from_lista_arts/DialogChooseArtFromListaArtsViewModel.java @@ -0,0 +1,5 @@ +package it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts; + +public class DialogChooseArtFromListaArtsViewModel { + +} \ No newline at end of file diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_arts_from_mtbcolr_list/DialogChooseArtsFromMtbColrList.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_arts_from_mtbcolr_list/DialogChooseArtsFromMtbColrList.java index 1f241c6f..1d6a124f 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_arts_from_mtbcolr_list/DialogChooseArtsFromMtbColrList.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/choose_arts_from_mtbcolr_list/DialogChooseArtsFromMtbColrList.java @@ -50,7 +50,7 @@ public class DialogChooseArtsFromMtbColrList extends BaseDialogFragment implemen ArticoloRESTConsumer articoloRESTConsumer; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private final List inputMtbColrList; private MtbAart selectedArt; private final RunnableArgs> onConfirmed; @@ -231,9 +231,9 @@ public class DialogChooseArtsFromMtbColrList extends BaseDialogFragment implemen } private void setupBarcode() { - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(ex -> UtilityExceptions.defaultException(mContext, ex, false))); } @@ -241,7 +241,7 @@ public class DialogChooseArtsFromMtbColrList extends BaseDialogFragment implemen @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); this.onAbort.run(); super.onDismiss(dialog); } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/create_new_art/DialogCreateNewArtView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/create_new_art/DialogCreateNewArtView.java index 24e5b708..9ddc7412 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/create_new_art/DialogCreateNewArtView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/create_new_art/DialogCreateNewArtView.java @@ -53,7 +53,7 @@ public class DialogCreateNewArtView extends BaseDialogFragment implements Dialog private Context mContext; public final BarcodeScanDTO mScannedBarcode; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private final String initialPosizione; private final RunnableArgs onArticleCreated; @@ -187,7 +187,7 @@ public class DialogCreateNewArtView extends BaseDialogFragment implements Dialog } private void initBarcodeReader() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(data -> { requireActivity().runOnUiThread(() -> { @@ -205,7 +205,7 @@ public class DialogCreateNewArtView extends BaseDialogFragment implements Dialog @Override public void onDismiss(@NonNull DialogInterface dialog) { super.onDismiss(dialog); - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); } private void initObservable() { diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_peso_lu/DialogInputPesoLUView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_peso_lu/DialogInputPesoLUView.java index 015e0263..6ee8a97d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_peso_lu/DialogInputPesoLUView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_peso_lu/DialogInputPesoLUView.java @@ -20,6 +20,7 @@ import javax.inject.Inject; import it.integry.integrywmsnative.MainApplication; import it.integry.integrywmsnative.R; +import it.integry.integrywmsnative.core.di.BindableBigDecimal; import it.integry.integrywmsnative.core.di.BindableString; import it.integry.integrywmsnative.core.expansion.BaseDialogFragment; import it.integry.integrywmsnative.core.expansion.RunnableArgsss; @@ -27,7 +28,6 @@ import it.integry.integrywmsnative.core.model.MtbTCol; import it.integry.integrywmsnative.core.model.observable.ObservableMtbTcol; import it.integry.integrywmsnative.core.rest.consumers.ImballiRESTConsumer; import it.integry.integrywmsnative.core.settings.SettingsManager; -import it.integry.integrywmsnative.core.utility.UtilityNumber; import it.integry.integrywmsnative.databinding.DialogInputPesoLuBinding; public class DialogInputPesoLUView extends BaseDialogFragment { @@ -44,8 +44,8 @@ public class DialogInputPesoLUView extends BaseDialogFragment { private RunnableArgsss onDialogDismiss; public BindableString codTcol = new BindableString(); - public BindableString netWeight = new BindableString(); - public BindableString grossWeight = new BindableString(); + public BindableBigDecimal netWeight = new BindableBigDecimal(); + public BindableBigDecimal grossWeight = new BindableBigDecimal(); private List codTcolList = null; @@ -62,8 +62,8 @@ public class DialogInputPesoLUView extends BaseDialogFragment { this.onDialogDismiss = onDialogDismiss; this.codTcol.set(codTcol); - this.netWeight.set(UtilityNumber.decimalToString(netWeight)); - this.grossWeight.set(UtilityNumber.decimalToString(grossWeight)); + this.netWeight.set(netWeight); + this.grossWeight.set(grossWeight); } @@ -88,6 +88,12 @@ public class DialogInputPesoLUView extends BaseDialogFragment { var alertDialog = new MaterialAlertDialogBuilder(this.mContext) .setView(mBindings.getRoot()) .setCancelable(isCancelable()) + .setPositiveButton(R.string.confirm, (dialogInterface, i) -> { + onDialogDismiss.run(codTcol.get(), netWeight.get(), grossWeight.get()); + }) + .setNegativeButton(R.string.abort, ((dialogInterface, i) -> { + onDialogDismiss.run(null, null, null); + })) .create(); alertDialog.setCanceledOnTouchOutside(isCancelable()); diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2DTO.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2DTO.java index 84547c37..fb0c386b 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2DTO.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2DTO.java @@ -20,7 +20,7 @@ public class DialogInputQuantityV2DTO { private BigDecimal totalQtaOrd; private BigDecimal totalNumCnfOrd; - private BigDecimal qtaCnfOrd; + private BigDecimal totalQtaCnfOrd; private BigDecimal totalQtaInWarehouse; private BigDecimal totalNumCnfInWarehouse; @@ -47,6 +47,7 @@ public class DialogInputQuantityV2DTO { private boolean notifyProductLotStatus = false; private boolean disableTracciabilitaCheck = false; private boolean warnOnQuantityOverflow = false; + private boolean enableSSCCRead = false; private StatoArticoloDTO statoPartitaMag; @@ -115,12 +116,12 @@ public class DialogInputQuantityV2DTO { return this; } - public BigDecimal getQtaCnfOrd() { - return UtilityBigDecimal.round(qtaCnfOrd); + public BigDecimal getTotalQtaCnfOrd() { + return UtilityBigDecimal.round(totalQtaCnfOrd); } - public DialogInputQuantityV2DTO setQtaCnfOrd(BigDecimal qtaCnfOrd) { - this.qtaCnfOrd = qtaCnfOrd; + public DialogInputQuantityV2DTO setTotalQtaCnfOrd(BigDecimal totalQtaCnfOrd) { + this.totalQtaCnfOrd = totalQtaCnfOrd; return this; } @@ -385,6 +386,15 @@ public class DialogInputQuantityV2DTO { return this; } + public boolean isEnableSSCCRead() { + return enableSSCCRead; + } + + public DialogInputQuantityV2DTO setEnableSSCCRead(boolean enableSSCCRead) { + this.enableSSCCRead = enableSSCCRead; + return this; + } + public List getMtbPartitaMagList() { return mtbPartitaMagList; } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2Module.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2Module.java index 25b321db..bcb79b0a 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2Module.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2Module.java @@ -1,5 +1,7 @@ package it.integry.integrywmsnative.view.dialogs.input_quantity_v2; +import java.util.concurrent.ExecutorService; + import dagger.Module; import dagger.Provides; import it.integry.integrywmsnative.core.rest.consumers.BarcodeRESTConsumer; @@ -9,8 +11,8 @@ import it.integry.integrywmsnative.core.rest.consumers.MagazzinoRESTConsumer; public class DialogInputQuantityV2Module { @Provides - DialogInputQuantityV2ViewModel providesDialogInputQuantityV2ViewModel(BarcodeRESTConsumer barcodeRESTConsumer, MagazzinoRESTConsumer magazzinoRESTConsumer) { - return new DialogInputQuantityV2ViewModel(barcodeRESTConsumer, magazzinoRESTConsumer); + DialogInputQuantityV2ViewModel providesDialogInputQuantityV2ViewModel(ExecutorService executorService, BarcodeRESTConsumer barcodeRESTConsumer, MagazzinoRESTConsumer magazzinoRESTConsumer) { + return new DialogInputQuantityV2ViewModel(executorService, barcodeRESTConsumer, magazzinoRESTConsumer); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResponseViewModel.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResponseViewModel.java new file mode 100644 index 00000000..7ea9e7c6 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResponseViewModel.java @@ -0,0 +1,25 @@ +package it.integry.integrywmsnative.view.dialogs.input_quantity_v2; + +import androidx.lifecycle.LiveData; +import androidx.lifecycle.MutableLiveData; +import androidx.lifecycle.ViewModel; + +public class DialogInputQuantityV2ResponseViewModel extends ViewModel { + + + private MutableLiveData result = new MutableLiveData<>(); + + public LiveData getResult() { + return result; + } + + public DialogInputQuantityV2ResponseViewModel setResult(MutableLiveData result) { + this.result = result; + return this; + } + + public DialogInputQuantityV2ResponseViewModel setResultValue(DialogInputQuantityV2ResultDTO result) { + this.result.postValue(result); + return this; + } +} diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResultDTO.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResultDTO.java index 53a7ed8f..63c407bf 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResultDTO.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResultDTO.java @@ -3,6 +3,8 @@ package it.integry.integrywmsnative.view.dialogs.input_quantity_v2; import java.math.BigDecimal; import java.time.LocalDate; +import it.integry.barcode_base_android_library.model.BarcodeScanDTO; + public class DialogInputQuantityV2ResultDTO { private String partitaMag; @@ -13,6 +15,12 @@ public class DialogInputQuantityV2ResultDTO { private BigDecimal qtaCnf; private BigDecimal qtaTot; + private BarcodeScanDTO nextUlBarcode; + + private boolean shouldCloseLu = false; + private boolean aborted = true; + + public String getPartitaMag() { return partitaMag; } @@ -66,4 +74,31 @@ public class DialogInputQuantityV2ResultDTO { this.qtaTot = qtaTot; return this; } + + public BarcodeScanDTO getNextUlBarcode() { + return nextUlBarcode; + } + + public DialogInputQuantityV2ResultDTO setNextUlBarcode(BarcodeScanDTO nextUlBarcode) { + this.nextUlBarcode = nextUlBarcode; + return this; + } + + public boolean isShouldCloseLu() { + return shouldCloseLu; + } + + public DialogInputQuantityV2ResultDTO setShouldCloseLu(boolean shouldCloseLu) { + this.shouldCloseLu = shouldCloseLu; + return this; + } + + public boolean isAborted() { + return aborted; + } + + public DialogInputQuantityV2ResultDTO setAborted(boolean aborted) { + this.aborted = aborted; + return this; + } } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2View.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2View.java index d6216d92..96d64cfc 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2View.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2View.java @@ -39,7 +39,6 @@ import it.integry.integrywmsnative.core.barcode_reader.BarcodeCallbackDTO; import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager; import it.integry.integrywmsnative.core.expansion.BaseDialogFragment; import it.integry.integrywmsnative.core.expansion.RunnableArgs; -import it.integry.integrywmsnative.core.expansion.RunnableArgss; import it.integry.integrywmsnative.core.model.MtbAart; import it.integry.integrywmsnative.core.model.MtbUntMis; import it.integry.integrywmsnative.core.settings.SettingsManager; @@ -58,8 +57,12 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia @Inject DialogInputQuantityV2ViewModel mViewModel; + @Inject + Handler handler; + private DialogInputQuantityV2DTO mDialogInputQuantityV2DTO; - private RunnableArgss mOnComplete; + //1: Result / 2: ShouldCloseLu / 3: Aborted + private RunnableArgs mOnComplete; private Runnable mOnAbort; public ObservableField currentTextNumCnfToTake = new ObservableField<>(0); @@ -88,15 +91,13 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia public ObservableField enabledLUCloseButton = new ObservableField<>(true); public ObservableField showProductLotStatus = new ObservableField<>(false); - private final Handler mHandler = new Handler(); - private Context context; private DialogInputQuantityV2Binding mBindings; private boolean mEnableDataCallback = true; private boolean mObservablesInitated = false; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private boolean mAbort = true; @@ -105,7 +106,7 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia return this; } - public DialogInputQuantityV2View setOnComplete(RunnableArgss mOnComplete) { + public DialogInputQuantityV2View setOnComplete(RunnableArgs mOnComplete) { this.mOnComplete = mOnComplete; return this; } @@ -130,7 +131,6 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme_NewMaterial_Dialog_FullscreenDialog); this.initBarcode(); - } @NonNull @@ -162,7 +162,7 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia .setTotalNumCnfCommitted(mDialogInputQuantityV2DTO.getTotalNumCnfCommitted()) .setTotalNumCnfOrd(mDialogInputQuantityV2DTO.getTotalNumCnfOrd()) .setTotalQtaOrd(mDialogInputQuantityV2DTO.getTotalQtaOrd()) - .setQtaCnfOrd(mDialogInputQuantityV2DTO.getQtaCnfOrd()) + .setQtaCnfOrd(mDialogInputQuantityV2DTO.getTotalQtaCnfOrd()) .setTotalNumCnfToBeTaken(mDialogInputQuantityV2DTO.getTotalNumCnfToBeTaken()) .setTotalQtaToBeTaken(mDialogInputQuantityV2DTO.getTotalQtaToBeTaken()) .setQtaCnfToBeTaken(mDialogInputQuantityV2DTO.getQtaCnfToBeTaken()) @@ -178,8 +178,9 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia .setSuggestPartitaMagRunnable(mDialogInputQuantityV2DTO.getSuggestPartitaMag()) .setDataScad(mDialogInputQuantityV2DTO.getDataScad()) .setDisableTracciabilitaCheck(mDialogInputQuantityV2DTO.isDisableTracciabilitaCheck()) - .setmPartitaMagList(mDialogInputQuantityV2DTO.getMtbPartitaMagList()) - .setStatoArt(mDialogInputQuantityV2DTO.getStatoPartitaMag() != null ? mDialogInputQuantityV2DTO.getStatoPartitaMag().getStatoArt() : null); + .setPartitaMagList(mDialogInputQuantityV2DTO.getMtbPartitaMagList()) + .setStatoArt(mDialogInputQuantityV2DTO.getStatoPartitaMag() != null ? mDialogInputQuantityV2DTO.getStatoPartitaMag().getStatoArt() : null) + .setEnableSSCCRead(mDialogInputQuantityV2DTO.isEnableSSCCRead()); mBindings.setView(this); mBindings.setViewmodel(this.mViewModel); @@ -241,12 +242,14 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia public void onDestroyView() { super.onDestroyView(); - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + mViewModel.destroy(); + + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); if (mAbort && this.mOnAbort != null) this.mOnAbort.run(); } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessful) .setOnScanFailed(ex -> UtilityExceptions.defaultException(this.context, ex, false))); } @@ -254,7 +257,14 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia private final RunnableArgs onScanSuccessful = data -> { this.onLoadingStarted(); - this.mViewModel.processBarcodeDTO(data, this::onLoadingEnded); + executorService.execute(() -> { + try { + this.mViewModel.processBarcodeDTO(data); + this.onLoadingEnded(); + } catch (Exception ex) { + onError(ex); + } + }); }; public void save() { @@ -262,12 +272,14 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia this.mViewModel.validate(validated -> { - requireActivity().runOnUiThread(() -> { + handler.post(() -> { this.onLoadingEnded(); if (validated) { - this.mAbort = false; - dismiss(this.mViewModel.getResult(), false); + var result = this.mViewModel.getResult() + .setAborted(false) + .setShouldCloseLu(false); + dismiss(result); } }); }); @@ -276,27 +288,30 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia public void saveAndCloseLU() { this.mViewModel.validate(validated -> { if (validated) { - this.mAbort = false; - dismiss(this.mViewModel.getResult(), true); - } else { - this.onLoadingEnded(); + var result = this.mViewModel.getResult() + .setAborted(false) + .setShouldCloseLu(true); + + dismiss(result); } }); } @Override public void dismiss() { - dismiss(null, false); + dismiss(null); } - private void dismiss(DialogInputQuantityV2ResultDTO result, boolean shouldCloseLu) { + private void dismiss(DialogInputQuantityV2ResultDTO result) { super.dismiss(); + if (this.mOnComplete != null) { - if(result == null) { - mOnAbort.run(); - } else { - this.mOnComplete.run(result, shouldCloseLu); + if (result == null) { + result = new DialogInputQuantityV2ResultDTO() + .setAborted(true); } + + this.mOnComplete.run(result); } } @@ -495,10 +510,10 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia this.enabledLUCloseButton.set(this.mDialogInputQuantityV2DTO.isCanLUBeClosed()); this.currentTaraArticolo.set(this.mViewModel.getMtbAart().getTaraKg() != null ? this.mViewModel.getMtbAart().getTaraKg() : BigDecimal.ZERO); - if (this.mDialogInputQuantityV2DTO.getMtbAart().isFlagQtaCnfFissaBoolean() && this.mDialogInputQuantityV2DTO.getTotalQtaOrd() != null && !this.mDialogInputQuantityV2DTO.getTotalQtaOrd().equals(BigDecimal.ZERO) && !(this.mDialogInputQuantityV2DTO.getQtaCnfOrd().compareTo(BigDecimal.ZERO) == 0)) { - int numCnftoTake = this.mDialogInputQuantityV2DTO.getTotalQtaOrd().divide(this.mDialogInputQuantityV2DTO.getQtaCnfOrd(), 0, RoundingMode.DOWN).intValue(); + if (this.mDialogInputQuantityV2DTO.getMtbAart().isFlagQtaCnfFissaBoolean() && this.mDialogInputQuantityV2DTO.getTotalQtaOrd() != null && !this.mDialogInputQuantityV2DTO.getTotalQtaOrd().equals(BigDecimal.ZERO) && !(this.mDialogInputQuantityV2DTO.getTotalQtaCnfOrd().compareTo(BigDecimal.ZERO) == 0)) { + int numCnftoTake = this.mDialogInputQuantityV2DTO.getTotalQtaOrd().divide(this.mDialogInputQuantityV2DTO.getTotalQtaCnfOrd(), 0, RoundingMode.DOWN).intValue(); this.currentTextNumCnfToTake.set(numCnftoTake); - int qtaText = this.mDialogInputQuantityV2DTO.getTotalQtaOrd().remainder(this.mDialogInputQuantityV2DTO.getQtaCnfOrd()).intValue(); + int qtaText = this.mDialogInputQuantityV2DTO.getTotalQtaOrd().remainder(this.mDialogInputQuantityV2DTO.getTotalQtaCnfOrd()).intValue(); this.currentTextNumPezziToTake.set(qtaText); } else { this.currentTextNumCnfToTake.set(0); @@ -552,10 +567,18 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia @Override public void onWarning(String text, RunnableArgs result) { - DialogSimpleMessageView.makeWarningDialog(new SpannableString(Html.fromHtml(text)), - null, - () -> result.run(true), - () -> result.run(false) - ).show(requireActivity().getSupportFragmentManager(), "tag"); + handler.post(() -> { + + DialogSimpleMessageView.makeWarningDialog(new SpannableString(Html.fromHtml(text)), + null, + () -> result.run(true), + () -> result.run(false) + ).show(requireActivity().getSupportFragmentManager(), "tag"); + }); + } + + @Override + public void onULCloseRequested() { + saveAndCloseLU(); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ViewModel.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ViewModel.java index a348c09f..fe276b85 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ViewModel.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ViewModel.java @@ -1,13 +1,12 @@ package it.integry.integrywmsnative.view.dialogs.input_quantity_v2; -import android.text.SpannableString; - import androidx.databinding.ObservableField; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import java.util.Optional; +import java.util.concurrent.ExecutorService; import java.util.concurrent.FutureTask; import java.util.concurrent.atomic.AtomicBoolean; @@ -18,12 +17,12 @@ import it.integry.integrywmsnative.R; import it.integry.integrywmsnative.core.di.BindableString; import it.integry.integrywmsnative.core.expansion.RunnableArgs; import it.integry.integrywmsnative.core.expansion.RunnableArgsWithReturn; +import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener; import it.integry.integrywmsnative.core.model.MtbAart; import it.integry.integrywmsnative.core.model.MtbPartitaMag; import it.integry.integrywmsnative.core.model.secondary.StatoPartitaMag; import it.integry.integrywmsnative.core.rest.consumers.BarcodeRESTConsumer; import it.integry.integrywmsnative.core.rest.consumers.MagazzinoRESTConsumer; -import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener; import it.integry.integrywmsnative.core.rest.model.Ean13PesoModel; import it.integry.integrywmsnative.core.settings.SettingsManager; import it.integry.integrywmsnative.core.utility.UtilityBarcode; @@ -31,8 +30,6 @@ import it.integry.integrywmsnative.core.utility.UtilityBigDecimal; import it.integry.integrywmsnative.core.utility.UtilityDate; import it.integry.integrywmsnative.core.utility.UtilityResources; import it.integry.integrywmsnative.core.utility.UtilityString; -import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView; -import it.integry.integrywmsnative.view.dialogs.exception.InactiveBatchLotException; import it.integry.integrywmsnative.view.dialogs.exception.InvalidBatchLotException; import it.integry.integrywmsnative.view.dialogs.exception.InvalidExpireDateException; import it.integry.integrywmsnative.view.dialogs.exception.InvalidNotesException; @@ -88,6 +85,8 @@ public class DialogInputQuantityV2ViewModel { private String internalNote; private LocalDate internalDataScad; + private BarcodeScanDTO internalNextUlBarcode; + private RunnableArgsWithReturn suggestPartitaMagRunnable; private boolean canInputZeroQuantity; @@ -97,9 +96,11 @@ public class DialogInputQuantityV2ViewModel { private int onQtaTotInputChanged; private boolean disableTracciabilitaCheck; private boolean warnOnQuantityOverflow; + private boolean enableSSCCRead; private Listener mListener; + private final ExecutorService executorService; private final BarcodeRESTConsumer mBarcodeRESTConsumer; private final MagazzinoRESTConsumer mMagazzinoRESTConsumer; @@ -108,7 +109,8 @@ public class DialogInputQuantityV2ViewModel { private List mPartitaMagList; @Inject - public DialogInputQuantityV2ViewModel(BarcodeRESTConsumer barcodeRESTConsumer, MagazzinoRESTConsumer magazzinoRESTConsumer) { + public DialogInputQuantityV2ViewModel(ExecutorService executorService, BarcodeRESTConsumer barcodeRESTConsumer, MagazzinoRESTConsumer magazzinoRESTConsumer) { + this.executorService = executorService; this.mBarcodeRESTConsumer = barcodeRESTConsumer; this.mMagazzinoRESTConsumer = magazzinoRESTConsumer; } @@ -150,17 +152,16 @@ public class DialogInputQuantityV2ViewModel { this.mListener.onDataChanged(); } - public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO, Runnable onComplete) { - if (UtilityBarcode.isEanPeso(barcodeScanDTO)) { - Ean13PesoModel ean13PesoModel; + public void destroy() { + this.internalPartitaMag = null; + this.internalNote = null; + this.internalDataScad = null; + this.internalNextUlBarcode = null; + } - try { - ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue()); - } catch (Exception ex) { - this.mListener.onError(ex); - onComplete.run(); - return; - } + public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO) throws Exception { + if (UtilityBarcode.isEanPeso(barcodeScanDTO)) { + Ean13PesoModel ean13PesoModel = Ean13PesoModel.fromBarcode(barcodeScanDTO.getStringValue()); if (this.mtbAart.get() != null && this.mtbAart.get().getBarCode() != null && @@ -178,57 +179,50 @@ public class DialogInputQuantityV2ViewModel { this.unlockQtaCnf(); } - onComplete.run(); } else if (UtilityBarcode.isEtichetta128(barcodeScanDTO)) { - this.mBarcodeRESTConsumer.decodeEan128(barcodeScanDTO, ean128Model -> { + var ean128Model = this.mBarcodeRESTConsumer.decodeEan128Synchronized(barcodeScanDTO); - if (ean128Model == null) { - onComplete.run(); - return; + if (ean128Model == null) { + return; + } + + if (canPartitaMagBeChanged) { + if (!UtilityString.isNullOrEmpty(ean128Model.BatchLot)) { + this.setPartitaMag(ean128Model.BatchLot); } - if (canPartitaMagBeChanged) { + if (!UtilityString.isNullOrEmpty(ean128Model.BestBefore)) { + this.setDataScad(UtilityDate.recognizeLocalDate(ean128Model.BestBefore)); + } else if (!UtilityString.isNullOrEmpty(ean128Model.Expiry)) { + this.setDataScad(UtilityDate.recognizeLocalDate(ean128Model.Expiry)); + } + } - if (!UtilityString.isNullOrEmpty(ean128Model.BatchLot)) { - this.setPartitaMag(ean128Model.BatchLot); - } + if (ean128Model.Count != null && ean128Model.Count > 0) { + this.setNumCnf(BigDecimal.valueOf(ean128Model.Count)); + } else if (ean128Model.NetWeightKg != null && ean128Model.NetWeightKg > 0) { + this.setQtaTot(BigDecimal.valueOf(ean128Model.NetWeightKg)); + this.setNumCnf(UtilityBigDecimal.divideAndRoundToInteger(this.getQtaTot(), this.mtbAart.get().getQtaCnf())); - try { - if (!UtilityString.isNullOrEmpty(ean128Model.BestBefore)) { - this.setDataScad(UtilityDate.recognizeLocalDate(ean128Model.BestBefore)); - } else if (!UtilityString.isNullOrEmpty(ean128Model.Expiry)) { - this.setDataScad(UtilityDate.recognizeLocalDate(ean128Model.Expiry)); - } - } catch (Exception ex) { - this.mListener.onError(ex); - } + if (!this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + if (UtilityBigDecimal.equalsTo(this.getNumCnf(), BigDecimal.ZERO)) + this.setNumCnf(BigDecimal.ONE); + this.setQtaCnf(UtilityBigDecimal.divide(this.getQtaTot(), this.getNumCnf())); } - if (ean128Model.Count != null && ean128Model.Count > 0) { - this.setNumCnf(BigDecimal.valueOf(ean128Model.Count)); - } else if (ean128Model.NetWeightKg != null && ean128Model.NetWeightKg > 0) { - this.setQtaTot(BigDecimal.valueOf(ean128Model.NetWeightKg)); - this.setNumCnf(UtilityBigDecimal.divideAndRoundToInteger(this.getQtaTot(), this.mtbAart.get().getQtaCnf())); - - if (!this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - if (UtilityBigDecimal.equalsTo(this.getNumCnf(), BigDecimal.ZERO)) - this.setNumCnf(BigDecimal.ONE); - this.setQtaCnf(UtilityBigDecimal.divide(this.getQtaTot(), this.getNumCnf())); - } - - this.unlockNumCnf(); - this.unlockQtaCnf(); + this.unlockNumCnf(); + this.unlockQtaCnf(); + } else if (ean128Model.Sscc != null) { + //Close current UDS and open another one with new SSCC + if (enableSSCCRead) { + this.internalNextUlBarcode = barcodeScanDTO; + this.sendOnULCloseRequested(); } + return; + } - this.mListener.onDataChanged(); - onComplete.run(); + this.mListener.onDataChanged(); - }, ex -> { - this.mListener.onError(ex); - onComplete.run(); - }); - } else { - onComplete.run(); } } @@ -361,7 +355,7 @@ public class DialogInputQuantityV2ViewModel { return this; } - public DialogInputQuantityV2ViewModel setmPartitaMagList(List mPartitaMagList) { + public DialogInputQuantityV2ViewModel setPartitaMagList(List mPartitaMagList) { this.mPartitaMagList = mPartitaMagList; return this; } @@ -381,6 +375,11 @@ public class DialogInputQuantityV2ViewModel { return this; } + public DialogInputQuantityV2ViewModel setEnableSSCCRead(boolean enableSSCCRead) { + this.enableSSCCRead = enableSSCCRead; + return this; + } + public boolean canPartitaMagBeChanged() { return canPartitaMagBeChanged; } @@ -527,7 +526,9 @@ public class DialogInputQuantityV2ViewModel { } public void validate(RunnableArgs onValidated) { - new Thread(() -> { + executorService.execute(() -> { + + if (this.internalQtaCnf == null || UtilityBigDecimal.equalsTo(this.internalQtaCnf, BigDecimal.ZERO)) { this.sendError(new InvalidQtaCnfQuantityException()); @@ -664,7 +665,8 @@ public class DialogInputQuantityV2ViewModel { } onValidated.run(true); - }).start(); + + }); } private boolean runWarningDialogSyncronized(String text) { @@ -696,7 +698,8 @@ public class DialogInputQuantityV2ViewModel { .setNumCnf(this.internalNumCnf) .setQtaCnf(this.internalQtaCnf) .setNote(this.internalNote) - .setQtaTot(this.internalQtaTot); + .setQtaTot(this.internalQtaTot) + .setNextUlBarcode(this.internalNextUlBarcode); } public void setListener(Listener listener) { @@ -738,11 +741,17 @@ public class DialogInputQuantityV2ViewModel { if (this.mListener != null) mListener.onLoadingEnded(); } + private void sendOnULCloseRequested() { + if (this.mListener != null) mListener.onULCloseRequested(); + } + public interface Listener extends ILoadingListener { void onDataChanged(); void onError(Exception ex); void onWarning(String text, RunnableArgs result); + + void onULCloseRequested(); } } diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_art/DialogScanArtView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_art/DialogScanArtView.java index 8058efc9..3a1a6f89 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_art/DialogScanArtView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_art/DialogScanArtView.java @@ -44,7 +44,7 @@ public class DialogScanArtView extends BaseDialogFragment implements DialogScanA private DialogScanArtBinding mBindings; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private RunnableArgssss onPickingCompleted = null; private RunnableArgs onMagazzinoAutomaticoPickingRequest = null; @@ -106,13 +106,13 @@ public class DialogScanArtView extends BaseDialogFragment implements DialogScanA @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); super.onDismiss(dialog); } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); setBarcodeListener(true); diff --git a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_or_create_lu/DialogScanOrCreateLUView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_or_create_lu/DialogScanOrCreateLUView.java index 15ac4692..8a62ca10 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_or_create_lu/DialogScanOrCreateLUView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/scan_or_create_lu/DialogScanOrCreateLUView.java @@ -138,7 +138,6 @@ public class DialogScanOrCreateLUView extends BaseDialogFragment implements Dial mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); setBarcodeListener(true); } diff --git a/app/src/main/res/layout/dialog_choose_art_from_lista_arts.xml b/app/src/main/res/layout/dialog_choose_art_from_lista_arts.xml new file mode 100644 index 00000000..4ff53faf --- /dev/null +++ b/app/src/main/res/layout/dialog_choose_art_from_lista_arts.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_main_ordini_uscita__list_group_model.xml b/app/src/main/res/layout/fragment_main_ordini_uscita__list_group_model.xml index 2d522cb1..e68142ea 100644 --- a/app/src/main/res/layout/fragment_main_ordini_uscita__list_group_model.xml +++ b/app/src/main/res/layout/fragment_main_ordini_uscita__list_group_model.xml @@ -1,101 +1,95 @@ - - - - - + - - + android:paddingStart="4dp" + android:paddingEnd="12dp" + android:paddingVertical="4dp" + android:background="@color/full_white"> + + android:layout_width="0dp" + android:layout_height="0dp" + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toTopOf="parent" + app:layout_constraintBottom_toBottomOf="parent" + app:layout_constraintWidth="8dp"/> - + + app:checked="@{selected}" + app:layout_constraintStart_toEndOf="@id/empty_view" + app:layout_constraintTop_toTopOf="parent" + app:layout_constraintBottom_toBottomOf="parent" /> + + - + + - - - - - - - - - - - - - - - + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_main_ordini_uscita__list_model.xml b/app/src/main/res/layout/fragment_main_ordini_uscita__list_model.xml index bf46c73f..89ca2ac9 100644 --- a/app/src/main/res/layout/fragment_main_ordini_uscita__list_model.xml +++ b/app/src/main/res/layout/fragment_main_ordini_uscita__list_model.xml @@ -1,5 +1,5 @@ - - - +