From 2d48f6687c19821eb51dac1b08658d202c15cf8b Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 24 Feb 2025 12:05:39 +0100 Subject: [PATCH 01/19] =?UTF-8?q?Aggiunta=20logica=20di=20fast=20picking?= =?UTF-8?q?=20in=20spedizione,=20scansionando=20un=20barcode=20di=20una=20?= =?UTF-8?q?UL=20all'interno=20di=20DialogInputQuantity=20verr=C3=A0=20auto?= =?UTF-8?q?maticamente=20chiusa=20l'ul=20attuale=20e=20riavviato=20il=20pr?= =?UTF-8?q?ocesso=20di=20scansione=20del=20barcode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/build.gradle | 6 +- .../MainApplicationModule.java | 37 +- .../barcode_reader/BarcodeCallbackDTO.java | 10 + .../core/barcode_reader/BarcodeManager.java | 51 +- .../integrywmsnative/core/di/Converters.java | 72 +- .../core/expansion/BaseActivity.java | 7 +- .../core/expansion/BaseDialog.java | 2 +- .../core/expansion/BaseDialogFragment.java | 11 +- .../core/expansion/BaseFragment.java | 5 +- .../view/ExtendedSectionedRecyclerView.java | 18 +- .../integrywmsnative/core/model/MtbAart.java | 99 ++ .../integrywmsnative/core/model/MtbColr.java | 52 + .../integrywmsnative/core/model/MtbColt.java | 20 +- .../core/model/MtbPartitaMag.java | 64 +- .../core/model/MtbUntMis.java | 12 + .../core/rest/HttpInterceptor.java | 2 +- .../rest/consumers/ArticoloRESTConsumer.java | 88 +- .../rest/consumers/BarcodeRESTConsumer.java | 4 + .../ColliLavorazioneRESTConsumer.java | 149 +- .../consumers/ColliMagazzinoRESTConsumer.java | 302 ++-- .../ColliSpedizioneRESTConsumer.java | 174 +- .../rest/consumers/EntityRESTConsumer.java | 74 +- .../MagazzinoAutomaticoRESTConsumer.java | 33 +- .../rest/consumers/OrdiniRESTConsumer.java | 42 +- .../rest/consumers/PosizioniRESTConsumer.java | 24 +- .../rest/consumers/SystemRESTConsumer.java | 53 +- .../ColliScaricoRESTConsumerInterface.java | 10 + .../MutableLiveDataDeserializer.java | 21 + .../serializer/MutableLiveDataSerializer.java | 16 + .../core/utility/UtilityDialog.java | 1 + .../core/utility/UtilityGson.java | 6 + .../AccettazioneBollaPickingActivity.java | 21 +- .../AccettazioneBollaPickingViewModel.java | 14 +- .../AccettazioneOrdiniPickingActivity.java | 29 +- .../edit_form/DocInterniEditFormActivity.java | 16 +- .../inventario/ElencoInventariFragment.java | 2 +- .../picking/PickingInventarioActivity.java | 18 +- .../picking_libero/PickingLiberoFragment.java | 25 +- .../picking_resi/PickingResiActivity.java | 19 +- .../ProdDettaglioLineaActivity.java | 34 +- .../ProdDettaglioLineaViewModel.java | 5 +- .../dialogs/DialogRecoverUl.java | 8 +- .../dialogs/DialogStartProduction.java | 8 +- .../ProdLineeProduzioneFragment.java | 12 +- .../ProdLineeProduzioneViewModel.java | 4 +- .../ProdRecuperoMaterialeFragment.java | 17 +- .../ProdRientroMerceFragment.java | 4 +- .../ProdRientroMerceOrderListFragment.java | 2 +- .../ProdRiposizionamentoDaProdFragment.java | 10 +- .../ProdVersamentoMaterialeFragment.java | 15 +- .../PVOrdineAcquistoEditActivity.java | 18 +- .../PVOrdineAcquistoEditViewModel.java | 4 +- .../edit_articolo/DialogEditArticoloView.java | 8 +- .../PVOrdiniAcquistoGrigliaFragment.java | 2 +- .../DialogScanGrigliaAcquistoView.java | 14 +- .../RettificaGiacenzeFragment.java | 14 +- .../gest/spedizione/SpedizioneActivity.java | 329 ++-- .../gest/spedizione/SpedizioneModule.java | 8 +- .../gest/spedizione/SpedizioneViewModel.java | 1405 +++++++++-------- .../spedizione/model/PickedQuantityDTO.java | 23 + .../UltimeConsegneClienteFragment.java | 10 +- .../UltimiArriviFornitoreFragment.java | 12 +- .../VersamentoMerceFragment.java | 15 +- ...ttomSheetFragmentLUContentListAdapter.java | 6 +- .../BottomSheetFragmentLUContentView.java | 34 +- .../DialogAskCliente_Page1ViewModel.java | 6 +- .../ask_commessa/DialogAskCommessaView.java | 10 +- .../DialogAskLineaProdView.java | 12 +- .../DialogAskPositionOfLUView.java | 18 +- .../DialogAskUnknownBarcodeNotesView.java | 12 +- ...alogBindProductBarcodeWithPackageView.java | 12 +- .../DialogChooseArtsFromMtbColrList.java | 8 +- .../DialogCreateNewArtView.java | 6 +- ...ialogInputQuantityV2ResponseViewModel.java | 25 + .../DialogInputQuantityV2ResultDTO.java | 35 + .../DialogInputQuantityV2View.java | 66 +- .../DialogInputQuantityV2ViewModel.java | 327 ++-- .../dialogs/scan_art/DialogScanArtView.java | 12 +- .../DialogScanOrCreateLUView.java | 10 +- ...t_main_ordini_uscita__list_group_model.xml | 8 +- 80 files changed, 2538 insertions(+), 1659 deletions(-) create mode 100644 app/src/main/java/it/integry/integrywmsnative/core/rest/deserializer/MutableLiveDataDeserializer.java create mode 100644 app/src/main/java/it/integry/integrywmsnative/core/rest/serializer/MutableLiveDataSerializer.java create mode 100644 app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2ResponseViewModel.java diff --git a/app/build.gradle b/app/build.gradle index 5289fbff..0c903c52 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -110,7 +110,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 +121,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 +140,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/MainApplicationModule.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java index 52eb0626..60b404d9 100644 --- a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java @@ -150,8 +150,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 @@ -162,8 +162,8 @@ public class MainApplicationModule { @Provides @Singleton - ArticoloRESTConsumer provideArticoloRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer) { - return new ArticoloRESTConsumer(restBuilder, systemRESTConsumer); + ArticoloRESTConsumer provideArticoloRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, SystemRESTConsumer systemRESTConsumer) { + return new ArticoloRESTConsumer(restBuilder, executorService, systemRESTConsumer); } @Provides @@ -198,18 +198,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 @@ -238,8 +239,8 @@ public class MainApplicationModule { @Provides @Singleton - SystemRESTConsumer provideSystemRESTConsumer(RESTBuilder restBuilder) { - return new SystemRESTConsumer(restBuilder); + SystemRESTConsumer provideSystemRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService) { + return new SystemRESTConsumer(restBuilder, executorService); } @Provides @@ -250,8 +251,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 @@ -310,20 +311,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/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/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/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 b3b79372..4f7c671d 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 @@ -65,14 +65,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(); // }); @@ -82,7 +82,6 @@ public abstract class BaseFragment extends Fragment { requireActivity().runOnUiThread(() -> { this.closeProgress(); UtilityExceptions.defaultException(getActivity(), ex); - BarcodeManager.enable(); }); } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java index e07b7bff..da2c4b51 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java @@ -6,28 +6,19 @@ import androidx.databinding.ObservableArrayList; import androidx.databinding.ObservableList; import androidx.recyclerview.widget.RecyclerView; -import com.zhukic.sectionedrecyclerview.SectionedRecyclerViewAdapter; - -import java.util.ArrayList; - import it.integry.integrywmsnative.core.expansion.OnListGeneralChangedCallback; public abstract class ExtendedSectionedRecyclerView extends SectionedRecyclerViewAdapter { - protected ArrayList mDataset = new ArrayList<>(); private View mEmptyView; public ExtendedSectionedRecyclerView(ObservableArrayList myDataset) { - mDataset.addAll(myDataset); + super(); myDataset.addOnListChangedCallback(new OnListGeneralChangedCallback() { @Override public void onChanged(ObservableList sender) { - mDataset.clear(); - mDataset.addAll(sender); - notifyDataChanged(); - notifyDataSetChanged(); checkIfEmpty(); } }); @@ -41,14 +32,11 @@ public abstract class ExtendedSectionedRecyclerView(); + 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..3c482f8d 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,7 @@ public class MtbColt extends EntityBase { private BigDecimal altezzaCm; private String codJcom; - private final ObservableField mtbTCol = new ObservableField<>(); + private final transient MutableLiveData mtbTCol = new MutableLiveData<>(); private Boolean disablePrint; private String ragSocCliente; @@ -261,7 +261,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() @@ -545,15 +545,15 @@ public class MtbColt extends EntityBase { } public ObservableMtbTcol getMtbTCol() { - return mtbTCol.get(); + return mtbTCol.getValue(); } public MtbColt setMtbTCol(ObservableMtbTcol mtbTCol) { - this.mtbTCol.set(mtbTCol); + this.mtbTCol.postValue(mtbTCol); return this; } - public ObservableField mtbTcolProperty() { + public MutableLiveData mtbTcolProperty() { return mtbTCol; } @@ -632,7 +632,13 @@ public class MtbColt extends EntityBase { @Override public EntityBase clone() { MtbColt mtbColt = (MtbColt) super.clone(); - mtbColt.setMtbColr((ObservableArrayList) mtbColt.getMtbColr().clone()); + mtbColt.setMtbColr(new ObservableArrayList<>()); + + 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 3f1cf2a4..fa024ef8 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 @@ -10,6 +10,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -26,7 +27,6 @@ import it.integry.integrywmsnative.core.rest.model.articolo.RetrieveArticoloByCo import it.integry.integrywmsnative.core.rest.model.articolo.SaveArticoloRequestDTO; import it.integry.integrywmsnative.core.rest.model.articolo.SaveArticoloResponseDTO; import it.integry.integrywmsnative.core.rest.model.articolo.SearchArticoloByBarcodeRequestDTO; -import it.integry.integrywmsnative.core.rest.model.articolo.SearchArticoloByBarcodeResponseDTO; import it.integry.integrywmsnative.core.rest.model.articolo.UpdateBarcodeImballoRequestDTO; import it.integry.integrywmsnative.core.utility.UtilityQuery; import retrofit2.Call; @@ -36,10 +36,12 @@ import retrofit2.Response; public class ArticoloRESTConsumer extends _BaseRESTConsumer { private final RESTBuilder restBuilder; + private final ExecutorService executorService; private final SystemRESTConsumer systemRESTConsumer; - public ArticoloRESTConsumer(RESTBuilder restBuilder, SystemRESTConsumer systemRESTConsumer) { + public ArticoloRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, SystemRESTConsumer systemRESTConsumer) { this.restBuilder = restBuilder; + this.executorService = executorService; this.systemRESTConsumer = systemRESTConsumer; } @@ -78,28 +80,30 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { }); } - public void searchByBarcode(String barcodeProd, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List searchByBarcodeSynchronized(String barcodeProd) throws Exception { ArticoloRESTConsumerService articoloRESTConsumerService = restBuilder.getService(ArticoloRESTConsumerService.class); var request = new SearchArticoloByBarcodeRequestDTO() .setBarcode(barcodeProd) .setOnlyActive(true); - articoloRESTConsumerService + var response = articoloRESTConsumerService .searchByBarcode(request) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "searchByBarcode", (m) -> { - onComplete.run(response.body().getDto().getArts()); - }, onFailed); - } + .execute(); - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + analyzeAnswer(response, "searchByBarcode"); + return response.body().getDto().getArts(); + } + + public void searchByBarcode(String barcodeProd, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var mtbAarts = searchByBarcodeSynchronized(barcodeProd); + if (onComplete != null) onComplete.run(mtbAarts); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } public void findIfIsKit(MtbAart mtbAart, RunnableArgs onComplete, RunnableArgs onFailed){ @@ -122,45 +126,47 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { }); } - public void getByCodMarts(List codMartToFind, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List getByCodMartsSynchronized(List codMartToFind) throws Exception { var codMarts = Stream.of(codMartToFind) .withoutNulls() .distinct().toList(); - ArticoloRESTConsumerService articoloRESTConsumer = restBuilder.getService(ArticoloRESTConsumerService.class); - articoloRESTConsumer + var response = articoloRESTConsumer .getByCodMart(new RetrieveArticoloByCodMartRequestDTO() .setCodMarts(codMarts)) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "getByCodMart", onComplete, onFailed); - } + .execute(); + return analyzeAnswer(response, "getByCodMart"); + } - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + public void getByCodMarts(List codMartToFind, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var mtbAarts = getByCodMartsSynchronized(codMartToFind); + if (onComplete != null) onComplete.run(mtbAarts); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); + } + public List getStatoPartitaSynchronized(String codMart, String partitaMag) throws Exception { + ArticoloRESTConsumerService articoloRESTConsumer = restBuilder.getService(ArticoloRESTConsumerService.class); + var response = articoloRESTConsumer.getStatoPartita(codMart, partitaMag).execute(); + + var data = analyzeAnswer(response, "getStatoPartita"); + return data; } public void getStatoPartita(String codMart, String partitaMag, RunnableArgs> onComplete, RunnableArgs onFailed) { - - ArticoloRESTConsumerService articoloRESTConsumer = restBuilder.getService(ArticoloRESTConsumerService.class); - articoloRESTConsumer.getStatoPartita(codMart, partitaMag).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "getStatoPartita", onComplete, onFailed); - } - - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - onFailed.run(e); + executorService.execute(() -> { + try { + var response = getStatoPartitaSynchronized(codMart, partitaMag); + if (onComplete != null) onComplete.run(response); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } }); - } diff --git a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/BarcodeRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/BarcodeRESTConsumer.java index 51474031..cb781a56 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/BarcodeRESTConsumer.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/BarcodeRESTConsumer.java @@ -16,6 +16,10 @@ public class BarcodeRESTConsumer extends _BaseRESTConsumer { this.ean128Service = ean128Service; } + public Ean128Model decodeEan128Synchronized(BarcodeScanDTO barcodeScanDTO) throws Exception { + return this.ean128Service.decode(barcodeScanDTO); + } + public void decodeEan128(BarcodeScanDTO barcodeObj, RunnableArgs onComplete, RunnableArgs onFailed) { try { onComplete.run(this.ean128Service.decode(barcodeObj)); 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 d869846f..7b79318f 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 @@ -16,6 +16,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.stream.Collectors; import javax.inject.Singleton; @@ -58,8 +60,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) { @@ -68,6 +71,7 @@ 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) { @@ -75,14 +79,10 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { 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<>() { @@ -99,6 +99,19 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } + public List saveColliSynchronized(List mtbColtsToSave) throws Exception { + + for (MtbColt mtbColt : mtbColtsToSave) { + for (int i = 0; i < mtbColt.getMtbColr().size(); i++) { + mtbColt.getMtbColr().get(i) + .setMtbAart(null) + .setMtbPartitaMag(null); + } + } + + return this.mEntityRESTConsumer.processEntityListSynchronized(mtbColtsToSave, true, MtbColt.class); + } + public void saveColli(List mtbColtsToSave, RunnableArgs> onComplete, RunnableArgs onFailed) { for (MtbColt mtbColt : mtbColtsToSave) { @@ -210,7 +223,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } -// if (sourceMtbColt.getMtbColr().size() != 1) { +// if (sourceMtbColt.getMtbColr().getValue().size() != 1) { // onFailed.run(new Exception()); // return; // } @@ -286,69 +299,82 @@ 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 fillMtbAartsOfMtbColts(List mtbColts, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List fillMtbAartsOfMtbColtsSynchronized(List mtbColts) throws Exception { List codMarts = new ArrayList<>(); for (MtbColt mtbColt : mtbColts) { - codMarts.addAll(Stream.of(mtbColt.getMtbColr()) + codMarts.addAll(mtbColt.getMtbColr().stream() .map(MtbColr::getCodMart) - .withoutNulls() + .filter(x -> !UtilityString.isNullOrEmpty(x)) .distinct() - .toList()); + .collect(Collectors.toList())); } + List mtbAarts = mArticoloRESTConsumer.getByCodMartsSynchronized(codMarts); - mArticoloRESTConsumer.getByCodMarts(codMarts, arts -> { + for (MtbColt mtbColt : mtbColts) { + for (MtbColr mtbColr : mtbColt.getMtbColr()) { - if (arts != null && !arts.isEmpty()) { - for (MtbColt mtbColt : mtbColts) { - for (MtbColr mtbColr : mtbColt.getMtbColr()) { + if (mtbAarts != null && !mtbAarts.isEmpty()) { + MtbAart foundMtbAart = null; - MtbAart foundMtbAart = null; + List mtbAartStream = mtbAarts.parallelStream() + .filter(x -> x.getCodMart().equalsIgnoreCase(mtbColr.getCodMart())) + .collect(Collectors.toList()); - List mtbAartStream = Stream.of(arts) - .filter(x -> x.getCodMart().equalsIgnoreCase(mtbColr.getCodMart())).toList(); - - if (mtbAartStream != null && !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()); + if (!mtbAartStream.isEmpty()) { + foundMtbAart = mtbAartStream.get(0); } - } - } - onComplete.run(mtbColts); - }, onFailed); + mtbColr.setMtbAart(foundMtbAart); + } + + mtbColr.setGestione(mtbColt.getGestione()); + mtbColr.setSerCollo(mtbColt.getSerCollo()); + mtbColr.setNumCollo(mtbColt.getNumCollo()); + mtbColr.setDataCollo(mtbColt.getDataColloS()); + } + } + + return mtbColts; + } + + public void fillMtbAartsOfMtbColts(List mtbColts, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + List returnedMtbColts = fillMtbAartsOfMtbColtsSynchronized(mtbColts); + if (onComplete != null) onComplete.run(returnedMtbColts); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); + } + }); } public void getMultipleByTestate(List testate, boolean onlyResiduo, RunnableArgs> onComplete, RunnableArgs onFailed) { @@ -369,6 +395,15 @@ 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) @@ -379,36 +414,36 @@ 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()) { + List mtbColtList = new ArrayList<>(); + mtbColtList.add(mtbColt); + var mtbColts = fillMtbAartsOfMtbColtsSynchronized(mtbColtList); + 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++) { @@ -424,21 +459,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) { @@ -449,7 +486,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<>()); @@ -459,22 +496,23 @@ 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 updateDataFine(MtbColt mtbColt, Runnable onComplete, RunnableArgs onFailed) { @@ -538,7 +576,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { } public void spostaArtsTraUL(MtbColt sourceMtbColt, MtbColt destMtbColt, boolean flagForceUseRefs, RunnableArgs> onComplete, RunnableArgs onFailed) { - new Thread(() -> { + executorService.execute(() -> { MtbColt mtbColtToMoveClone = (MtbColt) sourceMtbColt.clone(); MtbColt mtbColtDestClone = (MtbColt) destMtbColt.clone(); @@ -569,7 +607,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { if (onFailed != null) onFailed.run(e); } }); - }).start(); + }); } public void assegnaLottoSuColloScarico(MtbColt sourceMtbColt, Runnable onComplete, RunnableArgs onFailed) { @@ -698,42 +736,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/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/EntityRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/EntityRESTConsumer.java index 964043b2..00e1abeb 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,9 +27,11 @@ 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 void processEntity(T entityToSave, final ISimpleOperationCallback callback, Class type) { @@ -73,53 +76,48 @@ public class EntityRESTConsumer extends _BaseRESTConsumer { } - 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); - }; - + public List processEntityListSynchronized(List entitiesToSave, boolean singleTransaction, Class type) throws Exception { 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()) { + var response = service.processEntityList(singleTransaction, entitiesToSave) + .execute(); - if (response.body() != null) { + if (response.isSuccessful()) { - ArrayList responseList = new ArrayList<>(); - Gson gson = UtilityGson.createObject(); -// Type typeOfObjectsList = new TypeToken() {}.getType(); + if (response.body() != null) { - for (ServiceRESTResponse jsonSingleObject : response.body()) { + ArrayList responseList = new ArrayList<>(); + Gson gson = UtilityGson.createObject(); - 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())); + for (ServiceRESTResponse jsonSingleObject : response.body()) { - return; - } - } - - onComplete.run(responseList); + if (jsonSingleObject.getEsito() == EsitoType.OK) { + String jsonText = gson.toJson(jsonSingleObject.getEntity()); + responseList.add(gson.fromJson(jsonText, type)); } else { - Log.e("EntityRESTConsumer", response.message()); - tmpFailed.run(new Exception(response.message())); + Log.e("EntityRESTConsumer", jsonSingleObject.getErrorMessage()); + throw new Exception(jsonSingleObject.getErrorMessage()); } - } 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); + 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) { + 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/MagazzinoAutomaticoRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/MagazzinoAutomaticoRESTConsumer.java index c938a532..fcd79249 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 pickItemsSynchronous(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 { + pickItemsSynchronous(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/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..eceb8263 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 @@ -7,6 +7,7 @@ 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; @@ -25,10 +26,12 @@ 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) { @@ -50,8 +53,7 @@ public class PosizioniRESTConsumer extends _BaseRESTConsumer { }); } - - 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 +63,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/SystemRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/SystemRESTConsumer.java index 6267f717..0f6eda07 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 @@ -13,6 +13,7 @@ import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Type; import java.util.List; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -37,9 +38,11 @@ import retrofit2.Response; public class SystemRESTConsumer extends _BaseRESTConsumer { private final RESTBuilder restBuilder; + private final ExecutorService executorService; - public SystemRESTConsumer(RESTBuilder restBuilder) { + public SystemRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService) { this.restBuilder = restBuilder; + this.executorService = executorService; } public void retrieveUpdatesInfo(final RunnableArgs onSuccess, final RunnableArgs onFailed) { @@ -48,7 +51,7 @@ public class SystemRESTConsumer extends _BaseRESTConsumer { .enqueue(new ManagedErrorCallback<>() { @Override public void onResponse(Call call, Response response) { - if(response.code() == 404) { + if (response.code() == 404) { onSuccess.run(null); return; } @@ -84,35 +87,37 @@ public class SystemRESTConsumer extends _BaseRESTConsumer { } - public void processSql(String nativeSql, final Type clazz, final RunnableArgs onComplete, final RunnableArgs onFailed) { + public T processSqlSynchronized(String nativeSql, final Type clazz) throws Exception { NativeSqlRequestDTO nativeSqlDTO = new NativeSqlRequestDTO() .setNativeSql(nativeSql); SystemRESTConsumerService service = restBuilder.getService(SystemRESTConsumerService.class); - service + var response = service .processSql(nativeSqlDTO) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - analyzeAnswer(response, "ProcessSql", o -> { - Gson gson = UtilityGson.createObject(); + .execute(); + + var data = analyzeAnswer(response, "processSql"); + + Gson gson = UtilityGson.createObject(); + String json = gson.toJson(data); + + InputStream ims = new ByteArrayInputStream(json.getBytes()); + Reader reader = new InputStreamReader(ims); + T gsonObj = gson.fromJson(reader, clazz); + + return gsonObj; + } - String json = gson.toJson(o); - - InputStream ims = new ByteArrayInputStream(json.getBytes()); - Reader reader = new InputStreamReader(ims); - T gsonObj = gson.fromJson(reader, clazz); - - onComplete.run(gsonObj); - }, onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - onFailed.run(e); - } - }); + public void processSql(String nativeSql, final Type clazz, final RunnableArgs onComplete, final RunnableArgs onFailed) { + executorService.execute(() -> { + try { + T result = processSqlSynchronized(nativeSql, clazz); + 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/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/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/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/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 4d222ef8..68b9b03a 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 @@ -98,7 +98,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; @@ -182,10 +182,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(); } } @@ -199,7 +199,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))); } @@ -590,7 +590,7 @@ public class AccettazioneBollaPickingActivity extends BaseActivity implements Ac UtilityExceptions.defaultException(this, ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @Override @@ -600,7 +600,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) @@ -625,14 +625,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 3de5f89c..76e2ee06 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 @@ -594,14 +594,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( @@ -694,7 +694,9 @@ public class AccettazioneBollaPickingViewModel { mtbColrToEdit.getPartitaMag(), mtbColrToEdit.getDataScadPartita(), true, - (pickedQuantityDTO, shouldCloseLU) -> { + pickedQuantityDTO -> { + if(pickedQuantityDTO == null) + return; this.saveEditedRow(mtbColrToEdit, pickedQuantityDTO.getNumCnf(), @@ -702,7 +704,7 @@ public class AccettazioneBollaPickingViewModel { pickedQuantityDTO.getQtaTot(), pickedQuantityDTO.getPartitaMag(), pickedQuantityDTO.getDataScad(), - shouldCloseLU); + pickedQuantityDTO.isShouldCloseLu()); }); } @@ -982,7 +984,7 @@ public class AccettazioneBollaPickingViewModel { String partitaMag, LocalDate dataScad, boolean canPartitaMagBeChanged, - RunnableArgss onComplete) { + RunnableArgs onComplete) { if (this.mListener != null) mListener.onItemDispatched(pickingObjectDTO, mtbAart, initialNumCnf, @@ -1065,7 +1067,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 e8c9e98b..c188c0c4 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 @@ -103,7 +103,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; @@ -306,10 +306,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(); } } @@ -340,7 +340,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() { @@ -753,7 +753,7 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A UtilityExceptions.defaultException(this, ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @Override @@ -771,17 +771,24 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A 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); 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 public void onRowSaved() { runOnUiThread(() -> { 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(); }); } @@ -828,7 +835,7 @@ public class AccettazioneOrdiniPickingActivity extends BaseActivity implements A runOnUiThread(() -> { noLUPresent.set(false); 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(); this.mBottomSheetFragmentLUContentViewModel.setMtbColt(mtbColt); 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 948a3540..ab05401b 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 7f65b7a4..aebc883a 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, InventarioRoomDTO inventarioRoomDTO, 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/picking_libero/PickingLiberoFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoFragment.java index 0c36446b..ac6fcb84 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 @@ -87,7 +87,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 +171,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,11 +206,11 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); this.onLoadingStarted(); this.mViewModel.processBarcodeDTO(data, () -> { - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); this.onLoadingEnded(); }); }; @@ -294,7 +294,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme UtilityExceptions.defaultException(getActivity(), ex); } - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); }); } @@ -321,7 +321,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()); } @@ -365,7 +365,12 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme 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()) @@ -374,7 +379,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme .setDataScad(resultDTO.getDataScad()); this.onLoadingStarted(); - onComplete.run(pickedQuantityDTO, shouldCloseLU); + onComplete.run(pickedQuantityDTO, resultDTO.isShouldCloseLu()); }) .setOnAbort(this::onLoadingEnded) .show(requireActivity().getSupportFragmentManager(), "tag"); @@ -402,7 +407,7 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme @Override public void onPreDestroy(Runnable onComplete) { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); if (thereIsAnOpenedUL.get()) mViewModel.closeLU(onComplete); else onComplete.run(); } 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 6c6c50ef..8f7e2ebb 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 fda72b03..a73843a7 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 @@ -75,7 +75,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,11 +193,11 @@ public class ProdVersamentoMaterialeFragment extends BaseFragment implements Pro private void initBarcodeReader() { - barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(mViewModel::processBarcodeDTO) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } // private void openLU() { @@ -383,7 +383,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 +397,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/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/rettifica_giacenze/RettificaGiacenzeFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/rettifica_giacenze/RettificaGiacenzeFragment.java index 4c467954..f71df24c 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 @@ -84,7 +84,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 +165,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))); } @@ -370,7 +370,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()); @@ -425,7 +425,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()) @@ -433,7 +435,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"); }, () -> { @@ -555,7 +557,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/spedizione/SpedizioneActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneActivity.java index 534b0086..5e9067fe 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 @@ -5,6 +5,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; +import android.os.Handler; import android.text.Html; import android.text.SpannableString; import android.view.Gravity; @@ -13,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; @@ -96,21 +98,23 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Inject DialogInputQuantityV2View mDialogInputQuantityV2View; + @Inject + Handler handler; + private BottomSheetFragmentLUContentViewModel mBottomSheetFragmentLUContentViewModel; 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; @@ -239,31 +243,36 @@ 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); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); 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); } @@ -320,13 +329,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); @@ -709,36 +724,64 @@ 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() { - DialogScanArtView - .newInstance(!mEnableFakeGiacenza, (status, mtbAart, ean128Model, mtbColr) -> { - if (status == DialogConsts.Results.YES) { - this.mViewmodel.dispatchExtraItem(mtbAart, ean128Model, mtbColr); - } - }, pickMagazzinoAutomaticoPosizione -> { - this.onLoadingStarted(); - this.mViewmodel.executeEmptyMagazzinoAutomaticoRequest(pickMagazzinoAutomaticoPosizione, this::onLoadingEnded); - }) - .show(getSupportFragmentManager(), "tag"); + handler.post(() -> { + DialogScanArtView + .newInstance(!mEnableFakeGiacenza, (status, mtbAart, ean128Model, mtbColr) -> { + if (status == DialogConsts.Results.YES) { + + executorService.execute(() -> { + try { + this.mViewmodel.dispatchExtraItem(mtbAart, ean128Model, mtbColr); + } catch (Exception e) { + onError(e); + } + }); + + } + }, pickMagazzinoAutomaticoPosizione -> { + this.onLoadingStarted(); + + executorService.execute(() -> { + try { + this.mViewmodel.executeEmptyMagazzinoAutomaticoRequest(pickMagazzinoAutomaticoPosizione); + } catch (Exception e) { + onError(e); + } + this.onLoadingEnded(); + }); + }) + .show(getSupportFragmentManager(), "tag"); + }); } public void startManualSearch() { - BarcodeManager.disable(); - DialogSimpleInputHelper.makeInputDialog(this, "Inserisci il codice a barre", codice -> { + handler.post(() -> { + BarcodeManager.disable(mBarcodeScannerInstanceID); + DialogSimpleInputHelper.makeInputDialog(this, "Inserisci il codice a barre", codice -> { - this.onScanSuccessful.run(new BarcodeScanDTO().setStringValue(codice).setType(BarcodeType.CODE128)); - BarcodeManager.enable(); + this.onScanSuccessful.run(new BarcodeScanDTO().setStringValue(codice).setType(BarcodeType.CODE128)); + BarcodeManager.enable(mBarcodeScannerInstanceID); - }, BarcodeManager::enable).show(); + }, () -> BarcodeManager.enable(mBarcodeScannerInstanceID)).show(); + }); } public void removeListFilter() { - this.mViewmodel.resetMatchedRows(); + handler.post(() -> { + this.mViewmodel.resetMatchedRows(); + }); } @@ -747,88 +790,109 @@ 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); + } }); } public void trackPackaging() { - this.fabPopupMenu.dismiss(); + handler.post(() -> { + this.fabPopupMenu.dismiss(); - DialogTracciamentoImballiView.newInstance(imballiData -> { + DialogTracciamentoImballiView.newInstance(imballiData -> { - if (imballiData != null && !imballiData.isEmpty()) { - DialogAskVettoreView.newInstance(mViewmodel.getDefaultVettore(), vettoreData -> { - mViewmodel.registraImballi(vettoreData, imballiData); - }) - .show(getSupportFragmentManager(), DialogAskVettoreView.class.getName()); - } - }).show(getSupportFragmentManager(), DialogTracciamentoImballiView.class.getName()); + if (imballiData != null && !imballiData.isEmpty()) { + DialogAskVettoreView.newInstance(mViewmodel.getDefaultVettore(), vettoreData -> { + mViewmodel.registraImballi(vettoreData, imballiData); + }) + .show(getSupportFragmentManager(), DialogAskVettoreView.class.getName()); + } + }).show(getSupportFragmentManager(), DialogTracciamentoImballiView.class.getName()); + }); } public void showCreatedUL() { - this.fabPopupMenu.dismiss(); + handler.post(() -> { + this.fabPopupMenu.dismiss(); - ArrayList createdMtbColts = this.mViewmodel.getCreatedMtbColts(); + ArrayList createdMtbColts = this.mViewmodel.getCreatedMtbColts(); - Intent myIntent = ListaBancaliActivity.createIntent(this, createdMtbColts, true, false); - this.startActivityForResult(myIntent, PICK_UL_REQUEST); + Intent myIntent = ListaBancaliActivity.createIntent(this, createdMtbColts, true, false); + this.startActivityForResult(myIntent, PICK_UL_REQUEST); + }); } public void closeOrder() { - this.fabPopupMenu.dismiss(); + handler.post(() -> { + this.fabPopupMenu.dismiss(); - this.mViewmodel.closeOrder(); + this.mViewmodel.closeOrder(); + }); } @Override public void onLUOpened(MtbColt mtbColt) { - this.addExtraItemsEnabled.set(SettingsManager.iDB().isFlagCanAddExtraItemSpedizione()); - noLUPresent.set(false); + handler.post(() -> { + this.addExtraItemsEnabled.set(SettingsManager.iDB().isFlagCanAddExtraItemSpedizione()); + noLUPresent.postValue(false); - Snackbar.make(mBindings.getRoot(), R.string.data_saved, Snackbar.LENGTH_SHORT) - .setBackgroundTint(getResources().getColor(R. color. green_500)) - .show(); + Snackbar.make(mBindings.getRoot(), R.string.data_saved, Snackbar.LENGTH_SHORT) + .setBackgroundTint(getResources().getColor(R.color.green_500)) + .show(); - this.mBottomSheetFragmentLUContentViewModel.setMtbColt(mtbColt); + this.mBottomSheetFragmentLUContentViewModel.setMtbColt(mtbColt); + }); } @Override public void onLUClosed() { - this.addExtraItemsEnabled.set(false); - noLUPresent.set(true); - this.mBottomSheetFragmentLUContentViewModel.setMtbColt(null); + handler.post(() -> { + this.addExtraItemsEnabled.set(false); + noLUPresent.postValue(true); + this.mBottomSheetFragmentLUContentViewModel.setMtbColt(null); - if (this.mShouldCloseActivity) super.onBackPressed(); + if (this.mShouldCloseActivity) super.onBackPressed(); + }); } @Override public void onLUPesoRequired(String codTcol, BigDecimal netWeightKG, BigDecimal grossWeightKG, RunnableArgsss onComplete) { - DialogInputPesoLUView.newInstance(null, new BigDecimal(50), new BigDecimal(55), (newCodTcol, newNetWeight, newGrossWeight) -> { - onComplete.run(newCodTcol, netWeightKG, grossWeightKG); - }) - .show(getSupportFragmentManager(), "tag"); + handler.post(() -> { + DialogInputPesoLUView.newInstance(null, new BigDecimal(50), new BigDecimal(55), (newCodTcol, newNetWeight, newGrossWeight) -> { + onComplete.run(newCodTcol, netWeightKG, grossWeightKG); + }) + .show(getSupportFragmentManager(), "tag"); + }); } @Override public void onLUSuccessullyPrinted() { - Resources res = getResources(); - String errorMessage = res.getText(R.string.alert_print_completed_message).toString(); - DialogSimpleMessageView - .makeSuccessDialog(res.getText(R.string.completed).toString(), new SpannableString(errorMessage), null, null) - .show(getSupportFragmentManager(), "tag"); + handler.post(() -> { + Resources res = getResources(); + String errorMessage = res.getText(R.string.alert_print_completed_message).toString(); + DialogSimpleMessageView + .makeSuccessDialog(res.getText(R.string.completed).toString(), new SpannableString(errorMessage), null, null) + .show(getSupportFragmentManager(), "tag"); + }); } @Override public void onLUPrintRequest(RunnableArgs onComplete) { - DialogYesNoView.newInstance(getString(R.string.action_print), - String.format(getString(R.string.message_print_packing_list), "Packing List"), - result -> { - onComplete.run(result == DialogConsts.Results.YES); - }) - .show(getSupportFragmentManager(), "dialog-print"); + handler.post(() -> { + DialogYesNoView.newInstance(getString(R.string.action_print), + String.format(getString(R.string.message_print_packing_list), "Packing List"), + result -> { + onComplete.run(result == DialogConsts.Results.YES); + }) + .show(getSupportFragmentManager(), "dialog-print"); + }); } @Override @@ -845,41 +909,52 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Override public void onFilterApplied(String newValue) { - this.mBindings.filteredArtsInListExpandableLayout.expand(true); - this.mBindings.descriptionFilterText.setText(!UtilityString.isNullOrEmpty(newValue) ? newValue : ""); + handler.post(() -> { + this.mBindings.filteredArtsInListExpandableLayout.expand(true); + this.mBindings.descriptionFilterText.setText(!UtilityString.isNullOrEmpty(newValue) ? newValue : ""); + }); } @Override public void onFilterRemoved() { - this.mBindings.filteredArtsInListExpandableLayout.collapse(true); - this.mBindings.descriptionFilterText.setText(""); + handler.post(() -> { + this.mBindings.filteredArtsInListExpandableLayout.collapse(true); + this.mBindings.descriptionFilterText.setText(""); + }); } @Override public void onMtbColrDeleteRequest(RunnableArgs onComplete) { - String text = getResources().getString(R.string.alert_delete_mtb_colr); - DialogSimpleMessageView.makeWarningDialog(new SpannableString(text), - null, - () -> onComplete.run(true), - () -> onComplete.run(false) - ) - .show(getSupportFragmentManager(), "tag"); + handler.post(() -> { + String text = getResources().getString(R.string.alert_delete_mtb_colr); + DialogSimpleMessageView.makeWarningDialog(new SpannableString(text), + null, + () -> onComplete.run(true), + () -> onComplete.run(false) + ) + .show(getSupportFragmentManager(), "tag"); + }); } @Override public void onError(Exception ex, boolean useSnackbar) { - this.onLoadingEnded(); - if (ex instanceof InvalidPesoKGException) { - UtilityToast.showToast(ex.getMessage()); - } else { - if(useSnackbar) - Snackbar.make(mBindings.getRoot(), Objects.requireNonNull(ex.getMessage()), Snackbar.LENGTH_LONG).show(); - else - UtilityExceptions.defaultException(this, ex); - } + handler.post(() -> { - BarcodeManager.enable(); + this.onLoadingEnded(); + + if (ex instanceof InvalidPesoKGException) { + UtilityToast.showToast(ex.getMessage()); + } else { + if (useSnackbar) + Snackbar.make(mBindings.getRoot(), Objects.requireNonNull(ex.getMessage()), Snackbar.LENGTH_LONG).show(); + else + UtilityExceptions.defaultException(this, ex); + } + + BarcodeManager.enable(mBarcodeScannerInstanceID); + + }); } @Override @@ -901,7 +976,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(); @@ -935,20 +1011,23 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo 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(); } @@ -1043,8 +1122,8 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo } @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"); } @@ -1057,7 +1136,7 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo @Override public void onRowSaved() { 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(); } @@ -1073,17 +1152,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/SpedizioneModule.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneModule.java index e2f150e2..2c0b9f60 100644 --- a/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneModule.java @@ -1,5 +1,7 @@ package it.integry.integrywmsnative.gest.spedizione; +import java.util.concurrent.ExecutorService; + import dagger.Module; import dagger.Provides; import it.integry.integrywmsnative.core.data_recover.ColliDataRecoverService; @@ -38,7 +40,8 @@ public class SpedizioneModule { ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer, MagazzinoAutomaticoRESTConsumer magazzinoAutomaticoRESTConsumer, ImballiRESTConsumer imballiRESTConsumer, - MagazzinoRESTConsumer magazzinoRESTConsumer) { + MagazzinoRESTConsumer magazzinoRESTConsumer, + ExecutorService executorService) { return new SpedizioneViewModel(articoloRESTConsumer, barcodeRESTConsumer, colliDataRecoverService, @@ -51,7 +54,8 @@ public class SpedizioneModule { colliLavorazioneRESTConsumer, magazzinoAutomaticoRESTConsumer, imballiRESTConsumer, - magazzinoRESTConsumer); + magazzinoRESTConsumer, + executorService); } } 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 e1bc5ec4..1a82be96 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,5 +1,9 @@ package it.integry.integrywmsnative.gest.spedizione; +import android.os.Handler; +import android.os.Looper; +import android.util.Pair; + import androidx.databinding.ObservableArrayList; import androidx.lifecycle.MutableLiveData; @@ -14,6 +18,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; @@ -140,9 +147,13 @@ public class SpedizioneViewModel { private final MagazzinoAutomaticoRESTConsumer mMagazzinoAutomaticoRESTConsumer; private final ImballiRESTConsumer mImballiRESTConsumer; + private final ExecutorService executorService; + private ColliScaricoRESTConsumerInterface mColliScaricoRESTConsumer; private MagazzinoRESTConsumer magazzinoRESTConsumer; + private Handler handler = new Handler(Looper.getMainLooper()); + @Inject public SpedizioneViewModel(ArticoloRESTConsumer articoloRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, @@ -156,7 +167,8 @@ public class SpedizioneViewModel { ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer, MagazzinoAutomaticoRESTConsumer mMagazzinoAutomaticoRESTConsumer, ImballiRESTConsumer imballiRESTConsumer, - MagazzinoRESTConsumer magazzinoRESTConsumer) { + MagazzinoRESTConsumer magazzinoRESTConsumer, + ExecutorService executorService) { this.mArticoloRESTConsumer = articoloRESTConsumer; this.mBarcodeRESTConsumer = barcodeRESTConsumer; this.mColliDataRecoverService = colliDataRecoverService; @@ -170,6 +182,7 @@ public class SpedizioneViewModel { this.mMagazzinoAutomaticoRESTConsumer = mMagazzinoAutomaticoRESTConsumer; this.mImballiRESTConsumer = imballiRESTConsumer; this.magazzinoRESTConsumer = magazzinoRESTConsumer; + this.executorService = executorService; } @@ -353,8 +366,23 @@ public class SpedizioneViewModel { if (this.mListener != null) mListener.onChooseArtRequest(mtbAarts, onComplete); } - 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() { @@ -402,39 +430,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) { @@ -442,282 +518,252 @@ 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) { - //Se non c'è una UL aperta - if (mCurrentMtbColt == null) { + //Se è un'etichetta anonima + if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { + //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); - //Se è un'etichetta anonima - if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { - //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); + } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)/* && mDefaultSegnoCol == 1*/) { + this.processBarcodePosizioneNotOpenedLU(barcodeScanDTO); - } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)/* && mDefaultSegnoCol == 1*/) { - this.processBarcodePosizioneNotOpenedLU(barcodeScanDTO, onComplete); + } else { + this.processBarcodeNotOpenedLU(barcodeScanDTO); + } } else { - this.processBarcodeNotOpenedLU(barcodeScanDTO, onComplete); + if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { + //Cerco gli articoli presenti nell'ul dell'etichetta anonima + this.executeEtichettaLU(barcodeScanDTO.getStringValue()); + + } else { + this.processBarcodeAlreadyOpenedLU(barcodeScanDTO); + } } - } else { - if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { - //Cerco gli articoli presenti nell'ul dell'etichetta anonima - this.executeEtichettaLU(barcodeScanDTO.getStringValue(), onComplete); - - } else { - this.processBarcodeAlreadyOpenedLU(barcodeScanDTO, onComplete); - } - } } - 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 InvalidCodMdepException()); - + 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 InvalidCodMdepException()); + 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 InvalidCodMdepException()); - - } 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 codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() + .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); + + if (codMdepIsValid) { + 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 { + this.sendChooseArtRequest(mtbAartList, art -> { + try { + this.searchArtFromAnag(art, pickData); + } catch (Exception e) { + this.sendError(e); + } + }); + } + } 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() @@ -730,45 +776,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.pickItemsSynchronous(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()))) @@ -779,11 +825,10 @@ public class SpedizioneViewModel { .setDefaultGestioneOfNewUDS(mDefaultGestioneOfUL.getText()) .setOrdersOfNewUDS(orders); - mMagazzinoAutomaticoRESTConsumer.pickItems(mtbDepoPosizione, - magazzinoAutomaticoPickRequest, onComplete, this::sendError); + mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronous(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<>(); @@ -821,7 +866,7 @@ 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() @@ -841,11 +886,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() @@ -861,13 +905,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); @@ -881,6 +924,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); @@ -907,7 +951,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) { @@ -965,7 +1009,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); + } } }); @@ -978,7 +1026,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(); @@ -1108,38 +1156,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)); @@ -1238,15 +1303,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)) @@ -1260,114 +1333,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; @@ -1388,19 +1462,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 @@ -1444,89 +1517,97 @@ 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 { + executeDepositChangeIfNeeded(refMtbColt); + executeTipoUlChangeIfNeeded(refMtbColt); - 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; + if (!UtilityString.isNullOrEmpty(newTipoUL) && newMtbTcol == null) { + 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) { @@ -1536,8 +1617,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(); @@ -1550,121 +1630,195 @@ 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(); +// +// var shouldBeDeleted = this.shouldUlBeDeleted(); +// if (shouldBeDeleted) { +// deleteLU(); +// +// this.mCurrentMtbColt = null; +// +// if (mMtbColtSessionID != null) +// this.mColliDataRecoverService.closeSession(mMtbColtSessionID); +// +// this.mIsNewLU = false; +// this.sendLUClosed(); +// this.sendOnLoadingEnded(); +// +// } else { +// var askInfoAggiuntiveFuture = Futures.transformAsync( +// askPeso(), +// voidResult -> askInfoAggiuntive(), +// executorService +// ); +// +// var closeLuFuture = Futures.transformAsync( +// askInfoAggiuntiveFuture, +// voidResult -> closeLU(), +// executorService +// ); +// +// var duplicateUlFuture = Futures.transformAsync( +// closeLuFuture, +// generatedMtbColts -> validateTheUdsToBeDuplicated(generatedMtbColts), +// executorService +// ); +// +// var filledMtbColtFuture = Futures.transformAsync( +// duplicateUlFuture, +// duplicatedMtbColts -> { +// SettableFuture> future = SettableFuture.create(); +// this.mColliMagazzinoRESTConsumer.fillMtbAartsOfMtbColts(duplicatedMtbColts, +// future::set, +// future::setException); +// +// return future; +// }, +// executorService +// ); +// +// var askPosizioneFuture = Futures.transformAsync(filledMtbColtFuture, +// this::askPositionChange, +// executorService); +// +// var askPrintFuture = Futures.transformAsync(askPosizioneFuture, +// mtbColts -> askPrint(shouldPrint && SettingsManager.iDB().isFlagPrintEtichetteOnLUClose(), mtbColts), +// executorService); +// +// +// Futures.addCallback(askPrintFuture, new FutureCallback<>() { +// +// @Override +// public void onSuccess(List result) { +// handler.post(() -> { +// result.stream() +// .filter(x -> !mColliRegistrati.contains(x)) +// .forEach(x -> mColliRegistrati.add(x)); +// +// postCloseOperations(result); +// +// mIsNewLU = false; +// +// resetMatchedRows(); +// sendLUClosed(); +// sendOnLoadingEnded(); +// }); +// } +// +// @Override +// public void onFailure(Throwable throwable) { +// sendError(new Exception(throwable)); +// } +// }, executorService); +// +// } +// } + + 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); @@ -1694,12 +1848,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() @@ -1711,8 +1864,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); @@ -1734,88 +1886,90 @@ 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(); - }); + mCurrentMtbColt.setCodTcol(newCodTcol); + mCurrentMtbColt.setPesoNettoKg(newNetWeight); + 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); @@ -1827,67 +1981,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 || @@ -1895,36 +2039,50 @@ public class SpedizioneViewModel { mtbColtsToPrint.isEmpty() || !canPrint) { - onComplete.run(); return; } + final CountDownLatch latch = new CountDownLatch(1); + this.sendLUPrintRequest(shouldPrint -> { if (!shouldPrint) { - onComplete.run(); 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); @@ -1937,9 +2095,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; } @@ -2115,14 +2272,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) { @@ -2140,7 +2311,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); @@ -2154,7 +2325,7 @@ public class SpedizioneViewModel { 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/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..a5124ead 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<>(); @@ -138,18 +138,18 @@ public class UltimeConsegneClienteFragment extends BaseFragment implements Ultim } 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/ultimi_arrivi_fornitore/UltimiArriviFornitoreFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/ultimi_arrivi_fornitore/UltimiArriviFornitoreFragment.java index 239deef7..718f3b3c 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<>(); @@ -142,18 +142,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 +222,7 @@ public class UltimiArriviFornitoreFragment extends BaseFragment implements ITitl @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); for (Runnable onPreDestroy : mOnPreDestroyList) { onPreDestroy.run(); 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 f1f335a4..06fea57a 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 @@ -55,7 +55,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() { @@ -94,7 +94,7 @@ public class VersamentoMerceFragment extends BaseFragment implements ITitledFrag @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); for (Runnable onPreDestroy : mOnPreDestroyList) { onPreDestroy.run(); @@ -122,11 +122,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 -> { @@ -211,7 +211,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/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_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 d6d538d5..c5493af8 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 @@ -37,7 +37,7 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment implements Dia private DialogAskPositionOfLuBinding mBindings; private DialogAskPositionOfLUAdapter viewpagerAdapter; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private boolean mCheckForLineaProd; @@ -142,23 +142,23 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment implements Dia } private void initBarcode() { - mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() + mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); if (!completedFlow) onComplete.run(DialogConsts.Results.ABORT, null); super.onDismiss(dialog); } private final RunnableArgs onScanSuccessfull = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); if (!isOnLivelloPage()) { @@ -169,11 +169,11 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment implements Dia if (!mCheckForLineaProd && !currentMtbDepoPosizione.isFlagLineaProduzione() && UtilityPosizione.isPosizioneWithLivello(foundPosizione)) { askLivello(); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } else { completedFlow = true; - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); if (onComplete != null) onComplete.run(DialogConsts.Results.YES, foundPosizione); @@ -181,14 +181,14 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment implements Dia } } else { - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) .show(); } } else { Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) .show(); - BarcodeManager.enable(); + 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/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_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_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 fe40362f..daa9b4df 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 @@ -4,7 +4,6 @@ import android.app.Dialog; import android.content.Context; import android.content.res.ColorStateList; import android.os.Bundle; -import android.os.Handler; import android.text.Html; import android.text.InputType; import android.text.SpannableString; @@ -39,7 +38,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; @@ -59,7 +57,8 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia DialogInputQuantityV2ViewModel mViewModel; 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 +87,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 +102,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 +127,6 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme_NewMaterial_Dialog_FullscreenDialog); this.initBarcode(); - } @NonNull @@ -241,12 +237,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 +252,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() { @@ -266,9 +271,10 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia this.onLoadingEnded(); if (validated) { - this.mAbort = false; - dismiss(); - this.mOnComplete.run(this.mViewModel.getResult(), false); + var result = this.mViewModel.getResult() + .setAborted(false) + .setShouldCloseLu(false); + dismiss(result); } }); }); @@ -277,15 +283,32 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia public void saveAndCloseLU() { this.mViewModel.validate(validated -> { if (validated) { - this.mAbort = false; - dismiss(); - this.mOnComplete.run(this.mViewModel.getResult(), true); - } else { - this.onLoadingEnded(); + var result = this.mViewModel.getResult() + .setAborted(false) + .setShouldCloseLu(true); + + dismiss(result); } }); } + @Override + public void dismiss() { + dismiss(null); + } + + private void dismiss(DialogInputQuantityV2ResultDTO result) { + if (this.mOnComplete != null) { + if(result == null) { + result = new DialogInputQuantityV2ResultDTO() + .setAborted(true); + } + + this.mOnComplete.run(result); + } + super.dismiss(); + } + @Override public void onStart() { super.onStart(); @@ -544,4 +567,9 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia () -> 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..02c8edd3 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,7 +1,5 @@ package it.integry.integrywmsnative.view.dialogs.input_quantity_v2; -import android.text.SpannableString; - import androidx.databinding.ObservableField; import java.math.BigDecimal; @@ -18,12 +16,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 +29,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 +84,8 @@ public class DialogInputQuantityV2ViewModel { private String internalNote; private LocalDate internalDataScad; + private BarcodeScanDTO internalNextUlBarcode; + private RunnableArgsWithReturn suggestPartitaMagRunnable; private boolean canInputZeroQuantity; @@ -150,17 +148,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 +175,48 @@ 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())); + this.unlockNumCnf(); + this.unlockQtaCnf(); + } else if (ean128Model.Sscc != null) { + //Close current UDS and open another one with new SSCC + this.internalNextUlBarcode = barcodeScanDTO; + this.sendOnULCloseRequested(); + return; + } - 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.mListener.onDataChanged(); - this.unlockNumCnf(); - this.unlockQtaCnf(); - } - - this.mListener.onDataChanged(); - onComplete.run(); - - }, ex -> { - this.mListener.onError(ex); - onComplete.run(); - }); - } else { - onComplete.run(); } } @@ -527,144 +515,142 @@ public class DialogInputQuantityV2ViewModel { } public void validate(RunnableArgs onValidated) { - new Thread(() -> { - if (this.internalQtaCnf == null || UtilityBigDecimal.equalsTo(this.internalQtaCnf, BigDecimal.ZERO)) { + if (this.internalQtaCnf == null || UtilityBigDecimal.equalsTo(this.internalQtaCnf, BigDecimal.ZERO)) { - this.sendError(new InvalidQtaCnfQuantityException()); - onValidated.run(false); - return; - } + this.sendError(new InvalidQtaCnfQuantityException()); + onValidated.run(false); + return; + } - if (!disableTracciabilitaCheck && mtbAart.get().isFlagTracciabilitaBoolean()) { - if (UtilityString.isNullOrEmpty(internalPartitaMag)) { - if (suggestPartitaMagRunnable != null) { - internalPartitaMag = suggestPartitaMagRunnable.run(this); - if (internalPartitaMag == null) { - this.sendError(new InvalidBatchLotException()); - onValidated.run(false); - return; - } - } else { + if (!disableTracciabilitaCheck && mtbAart.get().isFlagTracciabilitaBoolean()) { + if (UtilityString.isNullOrEmpty(internalPartitaMag)) { + if (suggestPartitaMagRunnable != null) { + internalPartitaMag = suggestPartitaMagRunnable.run(this); + if (internalPartitaMag == null) { this.sendError(new InvalidBatchLotException()); onValidated.run(false); return; } } else { - if (SettingsManager.iDB().isFlagWarningNewPartitaMag()) { - MtbPartitaMag mtbPartitaMag = null; - try { - mtbPartitaMag = retrievePartitaMag(internalPartitaMag, this.getMtbAart().getCodMart()); - } catch (Exception e) { - this.sendError(e); + this.sendError(new InvalidBatchLotException()); + onValidated.run(false); + return; + } + } else { + if (SettingsManager.iDB().isFlagWarningNewPartitaMag()) { + MtbPartitaMag mtbPartitaMag = null; + try { + mtbPartitaMag = retrievePartitaMag(internalPartitaMag, this.getMtbAart().getCodMart()); + } catch (Exception e) { + this.sendError(e); + onValidated.run(false); + return; + } + + if (mtbPartitaMag == null) { + boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.batch_lot_inexistent_error_message)); + if (!result) { onValidated.run(false); return; } - - if (mtbPartitaMag == null) { - boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.batch_lot_inexistent_error_message)); - if (!result) { - onValidated.run(false); - return; - } - } } } } + } - if (this.statoArt == StatoPartitaMag.DISATTIVO) { - boolean result = runWarningDialogSyncronized(String.format(UtilityResources.getString(R.string.batch_lot_not_enabled), internalPartitaMag)); - if (!result) { - onValidated.run(false); - return; - } - } - - if (this.shouldAskDataScad && UtilityString.isNullOrEmpty(internalPartitaMag)) { - - this.sendError(new InvalidBatchLotException()); + if (this.statoArt == StatoPartitaMag.DISATTIVO) { + boolean result = runWarningDialogSyncronized(String.format(UtilityResources.getString(R.string.batch_lot_not_enabled), internalPartitaMag)); + if (!result) { onValidated.run(false); return; } + } - if (this.shouldAskDataScad && this.internalDataScad == null) { + if (this.shouldAskDataScad && UtilityString.isNullOrEmpty(internalPartitaMag)) { - this.sendError(new InvalidExpireDateException()); + this.sendError(new InvalidBatchLotException()); + onValidated.run(false); + return; + } + + if (this.shouldAskDataScad && this.internalDataScad == null) { + + this.sendError(new InvalidExpireDateException()); + onValidated.run(false); + return; + } + + if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && + this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + this.sendError(new OverflowQtaTotOrderedQuantityException()); + onValidated.run(false); + return; + } + + if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && + !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + this.sendError(new OverflowNumCnfOrderedQuantityException()); + onValidated.run(false); + return; + } + + if (UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaAvailable)) { + + this.sendError(new OverflowQtaTotAvailableQuantityException()); + onValidated.run(false); + return; + } + + if (UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfAvailable) && + !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + this.sendError(new OverflowNumCnfAvailableQuantityException()); + onValidated.run(false); + return; + } + + if (!this.canInputZeroQuantity && (this.internalNumCnf == null || this.internalQtaCnf == null || this.internalQtaTot == null || + UtilityBigDecimal.equalsOrLowerThan(this.internalNumCnf, BigDecimal.ZERO) || + UtilityBigDecimal.equalsOrLowerThan(this.internalQtaCnf, BigDecimal.ZERO) || + UtilityBigDecimal.equalsOrLowerThan(this.internalQtaTot, BigDecimal.ZERO))) { + + this.sendError(new InvalidQuantityException()); + onValidated.run(false); + return; + } + + if (this.isNoteMandatory() && (this.internalNote == null || this.internalNote.length() <= 0)) { + this.sendError(new InvalidNotesException()); + onValidated.run(false); + return; + } + + if (!UtilityString.isNullOrEmpty(this.internalPartitaMag)) + this.internalPartitaMag = this.internalPartitaMag.toUpperCase(); + + if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && + this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_quantity_overflow_error_message)); + if (!result) { onValidated.run(false); return; } + } - if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && - this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && + !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - this.sendError(new OverflowQtaTotOrderedQuantityException()); + boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_num_cnf_overflow_error_message)); + if (!result) { onValidated.run(false); return; } + } - if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && - !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - this.sendError(new OverflowNumCnfOrderedQuantityException()); - onValidated.run(false); - return; - } - - if (UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaAvailable)) { - - this.sendError(new OverflowQtaTotAvailableQuantityException()); - onValidated.run(false); - return; - } - - if (UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfAvailable) && - !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - this.sendError(new OverflowNumCnfAvailableQuantityException()); - onValidated.run(false); - return; - } - - if (!this.canInputZeroQuantity && (this.internalNumCnf == null || this.internalQtaCnf == null || this.internalQtaTot == null || - UtilityBigDecimal.equalsOrLowerThan(this.internalNumCnf, BigDecimal.ZERO) || - UtilityBigDecimal.equalsOrLowerThan(this.internalQtaCnf, BigDecimal.ZERO) || - UtilityBigDecimal.equalsOrLowerThan(this.internalQtaTot, BigDecimal.ZERO))) { - - this.sendError(new InvalidQuantityException()); - onValidated.run(false); - return; - } - - if (this.isNoteMandatory() && (this.internalNote == null || this.internalNote.length() <= 0)) { - this.sendError(new InvalidNotesException()); - onValidated.run(false); - return; - } - - if (!UtilityString.isNullOrEmpty(this.internalPartitaMag)) - this.internalPartitaMag = this.internalPartitaMag.toUpperCase(); - - if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && - this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_quantity_overflow_error_message)); - if (!result) { - onValidated.run(false); - return; - } - } - - if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && - !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_num_cnf_overflow_error_message)); - if (!result) { - onValidated.run(false); - return; - } - } - - onValidated.run(true); - }).start(); + onValidated.run(true); } private boolean runWarningDialogSyncronized(String text) { @@ -696,7 +682,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 +725,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 6938c66d..a5f09312 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 @@ -41,7 +41,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; @@ -89,17 +89,17 @@ public class DialogScanArtView extends BaseDialogFragment implements DialogScanA @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); } @@ -145,6 +145,6 @@ public class DialogScanArtView extends BaseDialogFragment implements DialogScanA @Override public void onError(Exception ex) { super.onError(ex); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } } 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 ffd5aae7..5a47ae4a 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 @@ -35,7 +35,7 @@ public class DialogScanOrCreateLUView extends BaseDialogFragment implements Dial DialogScanOrCreateLUViewModel mViewModel; private DialogScanOrCreateLuBinding mBindings; - private int mBarcodeScannerIstanceID; + private int mBarcodeScannerInstanceID; private final RunnableArgss mOnComplete; private MtbColt openedMtbColt; @@ -116,8 +116,8 @@ public class DialogScanOrCreateLUView extends BaseDialogFragment implements Dial @Override public void onDismiss(@NonNull DialogInterface dialog) { - BarcodeManager.removeCallback(mBarcodeScannerIstanceID); - BarcodeManager.enable(); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); + BarcodeManager.enable(mBarcodeScannerInstanceID); if (openedMtbColt == null) { mOnComplete.run(null, false); } @@ -126,10 +126,10 @@ public class DialogScanOrCreateLUView extends BaseDialogFragment implements Dial 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); } 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..38792a6d 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 @@ -11,7 +11,7 @@ - - - + - + \ No newline at end of file From 706878b1e4926c046c5713d03ca552edb2171255 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 24 Feb 2025 18:35:17 +0100 Subject: [PATCH 02/19] Migliorato adapter avantielenco ordini di uscita --- app/build.gradle | 3 + .../MainApplicationModule.java | 8 +- .../view/ExtendedSectionedRecyclerView.java | 18 +- .../ExtendedSectionedRecyclerViewNew.java | 44 +++ .../expansion/view/RecyclerViewProfiler.java | 218 +++++++++++ .../view/SectionedRecyclerViewAdapter.java | 350 ++++++++++++++++++ .../rest/consumers/ArticoloRESTConsumer.java | 15 +- .../rest/consumers/CommessaRESTConsumer.java | 33 +- .../rest/consumers/DepositoRESTConsumer.java | 12 +- .../OrdiniUscitaElencoFragment.java | 195 +++++----- .../OrdiniUscitaElencoViewModel.java | 48 +-- .../OrdiniUscitaElencoFiltroViewModel.java | 4 +- .../ui/OrdiniUscitaElencoAdapter.java | 86 +++-- ...t_main_ordini_uscita__list_group_model.xml | 149 ++++---- ...ragment_main_ordini_uscita__list_model.xml | 6 +- 15 files changed, 932 insertions(+), 257 deletions(-) create mode 100644 app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerViewNew.java create mode 100644 app/src/main/java/it/integry/integrywmsnative/core/expansion/view/RecyclerViewProfiler.java create mode 100644 app/src/main/java/it/integry/integrywmsnative/core/expansion/view/SectionedRecyclerViewAdapter.java diff --git a/app/build.gradle b/app/build.gradle index 30255e9b..8d6f1b99 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -62,6 +62,9 @@ android { android.buildFeatures.dataBinding true android.buildFeatures.buildConfig true + android.dataBinding.enabledForTests true + android.dataBinding.addKtx true + compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 diff --git a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java index 60b404d9..c42eab43 100644 --- a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java @@ -168,14 +168,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 diff --git a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java index da2c4b51..e07b7bff 100644 --- a/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/ExtendedSectionedRecyclerView.java @@ -6,19 +6,28 @@ import androidx.databinding.ObservableArrayList; import androidx.databinding.ObservableList; import androidx.recyclerview.widget.RecyclerView; +import com.zhukic.sectionedrecyclerview.SectionedRecyclerViewAdapter; + +import java.util.ArrayList; + import it.integry.integrywmsnative.core.expansion.OnListGeneralChangedCallback; public abstract class ExtendedSectionedRecyclerView extends SectionedRecyclerViewAdapter { + protected ArrayList mDataset = new ArrayList<>(); private View mEmptyView; public ExtendedSectionedRecyclerView(ObservableArrayList myDataset) { - super(); + mDataset.addAll(myDataset); myDataset.addOnListChangedCallback(new OnListGeneralChangedCallback() { @Override public void onChanged(ObservableList sender) { + mDataset.clear(); + mDataset.addAll(sender); + notifyDataChanged(); + notifyDataSetChanged(); checkIfEmpty(); } }); @@ -32,11 +41,14 @@ public abstract class ExtendedSectionedRecyclerView + 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..6b43eb10 --- /dev/null +++ b/app/src/main/java/it/integry/integrywmsnative/core/expansion/view/SectionedRecyclerViewAdapter.java @@ -0,0 +1,350 @@ +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; + +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, 50); + sharedPool.setMaxRecycledViews(TYPE_ITEM, 200); + } + + @Override + public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { + super.onAttachedToRecyclerView(recyclerView); + profiler = new RecyclerViewProfiler(recyclerView); + profiler.enableProfiling(false); + + 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(50); + } + +// recyclerView.post(() -> { + // Precarica alcuni ViewHolder +// for (int i = 0; i < 25; i++) { +// sharedPool.putRecycledView( +// createViewHolder(recyclerView, TYPE_HEADER)); +// } +// for (int i = 0; i < 50; i++) { +// sharedPool.putRecycledView( +// createViewHolder(recyclerView, TYPE_ITEM)); +// } +// }); + } + + 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/rest/consumers/ArticoloRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/ArticoloRESTConsumer.java index fa024ef8..12bc1577 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 @@ -178,7 +178,7 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { } - public void getArtsGroups(List groupsToFind, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List getArtsGroupsSynchronized(List groupsToFind) throws Exception { var whereCondMap = Stream.of(groupsToFind) .map(x -> { HashMap vars = new HashMap<>(); @@ -192,7 +192,18 @@ public class ArticoloRESTConsumer extends _BaseRESTConsumer { Type typeOfObjectsList = new TypeToken>() { }.getType(); - this.systemRESTConsumer.processSql("SELECT * FROM mtb_grup " + whereCond, typeOfObjectsList, onComplete, onFailed); + return this.systemRESTConsumer.processSqlSynchronized("SELECT * FROM mtb_grup " + whereCond, typeOfObjectsList); + } + + public void getArtsGroups(List groupsToFind, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var data = getArtsGroupsSynchronized(groupsToFind); + 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/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java index f60e7674..b145c9df 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,6 +2,7 @@ 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.view.LayoutInflater; import android.view.View; @@ -93,6 +94,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 +111,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; @@ -175,18 +179,43 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF @Override public void onStart() { super.onStart(); - this.onLoadingStarted(); - this.initMtbDepoCache(() -> { - String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); - mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol); + this.mViewModel.getOrderList().observe(getViewLifecycleOwner(), data -> { + executorService.execute(() -> { + try { + this.onLoadingStarted(); + this.initMtbGrupsCache(); + this.initJtbComtCache(); + + + mAppliedFilterViewModel.init(data); + + this.refreshList(data, null); + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } + }); }); + this.onLoadingStarted(); + executorService.execute(() -> { + try { + this.initMtbDepoCache(); + + String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); + mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol); + + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } + }); } @Override public void onDestroy() { - BarcodeManager.removeCallback(barcodeScannerIstanceID); + BarcodeManager.removeCallback(mBarcodeScannerInstanceID); for (Runnable onPreDestroy : mOnPreDestroyList) { onPreDestroy.run(); @@ -198,71 +227,70 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF private void initRecyclerView() { + this.onLoadingStarted(); + + boolean canSelectMultipleOrdini = SettingsManager.iDB().isFlagSpedizioneCanSelectMultipleOrders(); boolean canSelectMultipleClienti = SettingsManager.iDB().isFlagMultiClienteOrdV(); - this.mViewModel.getOrderList().observe(getViewLifecycleOwner(), v -> { - this.onLoadingStarted(); - this.initMtbGrupsCache(() -> { - this.initJtbComtCache(this::onLoadingEnded); - }); + executorService.execute(() -> { - mAppliedFilterViewModel.init(mViewModel.getOrderList().getValue()); - this.refreshList(null); + OrdiniUscitaElencoAdapter ordiniUscitaElencoAdapter = + new OrdiniUscitaElencoAdapter(getActivity(), mOrdiniInevasiMutableData) + .setOnGroupItemClicked(x -> { + if (!canSelectMultipleClienti) { + Stream.of(mOrdiniInevasiMutableData) + .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x) && y.getSelectedObservable().get()) + .forEach(y -> y.getSelectedObservable().set(false)); + } + + boolean allSelected = Stream.of(mOrdiniInevasiMutableData) + .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) + .allMatch(y -> y.getSelectedObservable().get()); + + Stream.of(mOrdiniInevasiMutableData) + .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) + .forEach(y -> y.getSelectedObservable().set(!allSelected)); + }) + .setOnItemChecked(x -> { + if (!canSelectMultipleClienti && x.getSelectedObservable().get()) { + Stream.of(mOrdiniInevasiMutableData) + .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x.getGroupTitle()) && y.getSelectedObservable().get()) + .forEach(y -> y.getSelectedObservable().set(false)); + } + + fabVisible.set(Stream.of(mOrdiniInevasiMutableData) + .anyMatch(y -> y.getSelectedObservable().get())); + }); + + ordiniUscitaElencoAdapter + .setEmptyView(this.mBindings.ordiniVenditaEmptyView); + + this.mBindings.venditaMainList.setLayoutManager(new LinearLayoutManager(getActivity())); + this.mBindings.venditaMainList.setItemViewCacheSize(20); + this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter); + }); - - OrdiniUscitaElencoAdapter ordiniUscitaElencoAdapter = - new OrdiniUscitaElencoAdapter(getActivity(), mOrdiniInevasiMutableData) - .setOnGroupItemClicked(x -> { - if (!canSelectMultipleClienti) { - Stream.of(mOrdiniInevasiMutableData) - .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x) && y.getSelectedObservable().get()) - .forEach(y -> y.getSelectedObservable().set(false)); - } - - boolean allSelected = Stream.of(mOrdiniInevasiMutableData) - .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) - .allMatch(y -> y.getSelectedObservable().get()); - - Stream.of(mOrdiniInevasiMutableData) - .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) - .forEach(y -> y.getSelectedObservable().set(!allSelected)); - }) - .setOnItemChecked(x -> { - if (!canSelectMultipleClienti && x.getSelectedObservable().get()) { - Stream.of(mOrdiniInevasiMutableData) - .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x.getGroupTitle()) && y.getSelectedObservable().get()) - .forEach(y -> y.getSelectedObservable().set(false)); - } - - fabVisible.set(Stream.of(mOrdiniInevasiMutableData) - .anyMatch(y -> y.getSelectedObservable().get())); - }); - - ordiniUscitaElencoAdapter - .setEmptyView(this.mBindings.ordiniVenditaEmptyView); - - this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter); - this.mBindings.venditaMainList.setLayoutManager(new LinearLayoutManager(getActivity())); + this.onLoadingEnded(); // 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,21 +742,21 @@ 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); + handler.post(() -> { this.mOrdiniInevasiMutableData.clear(); this.mOrdiniInevasiMutableData.addAll(list); @@ -744,7 +772,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.parallelStream() .filter(x -> !x.isHidden()) .sorted(comparator) .map(x -> { @@ -774,7 +802,7 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF return listModel; }) - .toList(); + .collect(Collectors.toList()); return notHiddenElements; } @@ -814,7 +842,7 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF @Override public void onOrderFiltered(List filteredOrders) { - refreshList(filteredOrders); + refreshList(mViewModel.getOrderList().getValue(), filteredOrders); } @Override @@ -874,38 +902,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 +939,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/OrdiniUscitaElencoViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoViewModel.java index b9a491b9..3854c793 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,8 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; import javax.inject.Inject; @@ -57,39 +59,37 @@ 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) throws Exception { this.mCurrentCodMdep = currentCodMdep; this.mCurrentGestioneOrd = gestioneOrd; this.mCurrentGestioneCol = gestioneCol; this.mCurrentSegnoCol = segnoCol; - this.sendOnLoadingStarted(); +// Date loadingStartDate = new Date(); - Date loadingStartDate = new Date(); + var ordiniLavorazione = this.mOrdiniRESTConsumer.getOrdiniInevasiSynchronized(this.mCurrentCodMdep, mCurrentGestioneOrd); - 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()); - - long forcedDelaySecs = (new Date().getTime() - loadingStartDate.getTime()) / 1000; - - if (2 - forcedDelaySecs > 0) { - try { - Thread.sleep((2 - forcedDelaySecs) * 1000); - } catch (Exception ignored) { - } + var orderList = ordiniLavorazione.parallelStream() + .map(x -> { + try { + return OrdiniUscitaElencoDTO.fromParent(x); + } catch (Exception ex) { + return null; } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); - this.sendOnLoadingEnded(); - }, this::sendError); + this.mOrderList.postValue(orderList); + +// long forcedDelaySecs = (new Date().getTime() - loadingStartDate.getTime()) / 1000; +// +// if (2 - forcedDelaySecs > 0) { +// try { +// Thread.sleep((2 - forcedDelaySecs) * 1000); +// } catch (Exception ignored) { +// } +// } } 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..9d71487e 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 @@ -44,7 +44,7 @@ public class OrdiniUscitaElencoFiltroViewModel { public void init(List initialList) { this.initialOrderList = initialList; - this.currentFilteredOrderList.setValue(this.initialOrderList); + this.currentFilteredOrderList.postValue(this.initialOrderList); } public MutableLiveData> getMutableFilteredOrderList() { @@ -192,7 +192,7 @@ public class OrdiniUscitaElencoFiltroViewModel { returnList = tmpStream.toList(); } - this.currentFilteredOrderList.setValue(returnList); + this.currentFilteredOrderList.postValue(returnList); } public ObservableField> getCurrentDepositoPredicate() { 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..8c608194 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,34 @@ 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; + + static class SubheaderHolder extends RecyclerView.ViewHolder { FragmentMainOrdiniUscitaListModelBinding mBinding; @@ -50,6 +60,22 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerView mutableDataSet) { super(mutableDataSet); mContext = context; + layoutInflater = LayoutInflater.from(mContext); +// 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); + + setSections(Arrays.asList(keyArray), collect); + } + }); } public OrdiniUscitaElencoAdapter setOnGroupItemClicked(RunnableArgs onGroupItemClicked) { @@ -64,58 +90,60 @@ 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/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 38792a6d..4ca47ca2 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,94 @@ - - - - - + - - + 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_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 @@ - - - + From ce3dfca6e03e046f93d704f79066fb4ea8109e2d Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 24 Feb 2025 18:55:45 +0100 Subject: [PATCH 03/19] Rimosso parametro inutilizzato in build.gradle --- app/build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/app/build.gradle b/app/build.gradle index 8d6f1b99..1963e4d4 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -63,7 +63,6 @@ android { android.buildFeatures.buildConfig true android.dataBinding.enabledForTests true - android.dataBinding.addKtx true compileOptions { sourceCompatibility JavaVersion.VERSION_17 From 6c621d5ca86f4cd641ee8bb90c8a60dad387a6a7 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 26 Feb 2025 13:06:56 +0100 Subject: [PATCH 04/19] Migliorie sul caricamento della lista di ordini di uscita --- .../view/SectionedRecyclerViewAdapter.java | 16 +-- .../OrdiniUscitaElencoFragment.java | 114 +++++++++--------- .../OrdiniUscitaElencoModule.java | 8 +- .../OrdiniUscitaElencoViewModel.java | 55 +++++---- .../OrdiniUscitaElencoFiltroViewModel.java | 11 +- .../ui/OrdiniUscitaElencoAdapter.java | 54 +++++---- .../ui/OrdiniUscitaElencoListModel.java | 28 +++++ .../view/dialogs/DialogProgressView.java | 16 ++- 8 files changed, 178 insertions(+), 124 deletions(-) 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 index 6b43eb10..53a9a699 100644 --- 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 @@ -41,15 +41,15 @@ public abstract class SectionedRecyclerViewAdapter { +// recyclerView.postDelayed(() -> { // Precarica alcuni ViewHolder -// for (int i = 0; i < 25; i++) { +// for (int i = 0; i < 100; i++) { // sharedPool.putRecycledView( // createViewHolder(recyclerView, TYPE_HEADER)); // } -// for (int i = 0; i < 50; i++) { +// for (int i = 0; i < 100; i++) { // sharedPool.putRecycledView( // createViewHolder(recyclerView, TYPE_ITEM)); // } -// }); +// }, 50); } protected static class Section { 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 b145c9df..41912bdb 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 @@ -4,6 +4,7 @@ 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; @@ -69,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; @@ -168,11 +169,11 @@ 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(); } @@ -180,37 +181,41 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF public void onStart() { super.onStart(); + 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); + }); - mAppliedFilterViewModel.init(data); - - this.refreshList(data, null); this.onLoadingEnded(); } catch (Exception e) { onError(e); } }); + }); + this.onLoadingStarted(); - executorService.execute(() -> { - try { - this.initMtbDepoCache(); - String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); - mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol); + this.initRecyclerView(); + this.initFilters(); - this.onLoadingEnded(); - } catch (Exception e) { - onError(e); - } + String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep(); + mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol, () -> { + this.onLoadingEnded(); }); + + Log.d("onStart", "Ended"); } @Override @@ -227,52 +232,45 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF private void initRecyclerView() { - this.onLoadingStarted(); - - boolean canSelectMultipleOrdini = SettingsManager.iDB().isFlagSpedizioneCanSelectMultipleOrders(); boolean canSelectMultipleClienti = SettingsManager.iDB().isFlagMultiClienteOrdV(); - executorService.execute(() -> { - - - OrdiniUscitaElencoAdapter ordiniUscitaElencoAdapter = - new OrdiniUscitaElencoAdapter(getActivity(), mOrdiniInevasiMutableData) - .setOnGroupItemClicked(x -> { - if (!canSelectMultipleClienti) { - Stream.of(mOrdiniInevasiMutableData) - .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x) && y.getSelectedObservable().get()) - .forEach(y -> y.getSelectedObservable().set(false)); - } - - boolean allSelected = Stream.of(mOrdiniInevasiMutableData) - .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) - .allMatch(y -> y.getSelectedObservable().get()); + OrdiniUscitaElencoAdapter ordiniUscitaElencoAdapter = + new OrdiniUscitaElencoAdapter(getActivity(), mOrdiniInevasiMutableData) + .setOnGroupItemClicked(x -> { + if (!canSelectMultipleClienti) { Stream.of(mOrdiniInevasiMutableData) - .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) - .forEach(y -> y.getSelectedObservable().set(!allSelected)); - }) - .setOnItemChecked(x -> { - if (!canSelectMultipleClienti && x.getSelectedObservable().get()) { - Stream.of(mOrdiniInevasiMutableData) - .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x.getGroupTitle()) && y.getSelectedObservable().get()) - .forEach(y -> y.getSelectedObservable().set(false)); - } + .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x) && y.getSelectedObservable().get()) + .forEach(y -> y.getSelectedObservable().set(false)); + } - fabVisible.set(Stream.of(mOrdiniInevasiMutableData) - .anyMatch(y -> y.getSelectedObservable().get())); - }); + boolean allSelected = Stream.of(mOrdiniInevasiMutableData) + .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) + .allMatch(y -> y.getSelectedObservable().get()); - ordiniUscitaElencoAdapter - .setEmptyView(this.mBindings.ordiniVenditaEmptyView); + Stream.of(mOrdiniInevasiMutableData) + .filter(y -> y.getGroupTitle().equalsIgnoreCase(x)) + .forEach(y -> y.getSelectedObservable().set(!allSelected)); + }) + .setOnItemChecked(x -> { + if (!canSelectMultipleClienti && x.getSelectedObservable().get()) { + Stream.of(mOrdiniInevasiMutableData) + .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x.getGroupTitle()) && y.getSelectedObservable().get()) + .forEach(y -> y.getSelectedObservable().set(false)); + } - this.mBindings.venditaMainList.setLayoutManager(new LinearLayoutManager(getActivity())); - this.mBindings.venditaMainList.setItemViewCacheSize(20); - this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter); + fabVisible.set(Stream.of(mOrdiniInevasiMutableData) + .anyMatch(y -> y.getSelectedObservable().get())); + }); + + ordiniUscitaElencoAdapter + .setEmptyView(this.mBindings.ordiniVenditaEmptyView); + + this.mBindings.venditaMainList.setLayoutManager(new LinearLayoutManager(getActivity())); + this.mBindings.venditaMainList.setItemViewCacheSize(20); + this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter); - }); - this.onLoadingEnded(); // if (mToolbar != null) // mToolbar.setRecyclerView(this.mBindings.venditaMainList); @@ -756,13 +754,11 @@ public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledF var list = convertDataModelToListModel(tmpList); - handler.post(() -> { - 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) { 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 3854c793..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 @@ -9,6 +9,7 @@ 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; @@ -39,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; @@ -51,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; @@ -59,37 +69,36 @@ public class OrdiniUscitaElencoViewModel { } - public void init(String currentCodMdep, GestioneEnum gestioneOrd, GestioneEnum gestioneCol, int segnoCol) throws Exception { + 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; -// Date loadingStartDate = new Date(); - var ordiniLavorazione = this.mOrdiniRESTConsumer.getOrdiniInevasiSynchronized(this.mCurrentCodMdep, mCurrentGestioneOrd); + executorService.execute(() -> { - var orderList = ordiniLavorazione.parallelStream() - .map(x -> { - try { - return OrdiniUscitaElencoDTO.fromParent(x); - } catch (Exception ex) { - return null; - } - }) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + List ordiniLavorazione = null; + try { + ordiniLavorazione = this.mOrdiniRESTConsumer.getOrdiniInevasiSynchronized(this.mCurrentCodMdep, mCurrentGestioneOrd); - this.mOrderList.postValue(orderList); + var orderList = ordiniLavorazione.parallelStream() + .map(x -> { + try { + return OrdiniUscitaElencoDTO.fromParent(x); + } catch (Exception ex) { + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); -// long forcedDelaySecs = (new Date().getTime() - loadingStartDate.getTime()) / 1000; -// -// if (2 - forcedDelaySecs > 0) { -// try { -// Thread.sleep((2 - forcedDelaySecs) * 1000); -// } catch (Exception ignored) { -// } -// } + 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/OrdiniUscitaElencoFiltroViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/filters/OrdiniUscitaElencoFiltroViewModel.java index 9d71487e..22127813 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; @@ -44,7 +46,7 @@ public class OrdiniUscitaElencoFiltroViewModel { public void init(List initialList) { this.initialOrderList = initialList; - this.currentFilteredOrderList.postValue(this.initialOrderList); + this.currentFilteredOrderList.setValue(this.initialOrderList); } public MutableLiveData> getMutableFilteredOrderList() { @@ -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 8c608194..7a0ae725 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 @@ -34,6 +34,29 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerViewNew< 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); + + setSections(Arrays.asList(keyArray), collect); + } + }); + } static class SubheaderHolder extends RecyclerView.ViewHolder { @@ -57,27 +80,6 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerViewNew< } } - public OrdiniUscitaElencoAdapter(Context context, ObservableArrayList mutableDataSet) { - super(mutableDataSet); - mContext = context; - layoutInflater = LayoutInflater.from(mContext); -// 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); - - setSections(Arrays.asList(keyArray), collect); - } - }); - } - public OrdiniUscitaElencoAdapter setOnGroupItemClicked(RunnableArgs onGroupItemClicked) { this.mOnGroupItemClicked = onGroupItemClicked; return this; @@ -126,25 +128,25 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerViewNew< if (listModel.getEtichettaColor() != null) holder.mBinding.emptyView.setBackgroundColor(listModel.getEtichettaColor()); else - holder.mBinding.emptyView.setBackgroundColor(ResourcesCompat.getColor(mContext.getResources(), android.R.color.transparent, null)); + holder.mBinding.emptyView.setBackgroundColor(transparentColor); if (!UtilityString.isNullOrEmpty(listModel.getDescription())) { - holder.mBinding.descrizione.setText(Html.fromHtml(listModel.getDescription())); + holder.mBinding.descrizione.setText(listModel.getDescriptionSpanned()); holder.mBinding.descrizione.setVisibility(View.VISIBLE); } else holder.mBinding.descrizione.setVisibility(View.GONE); if (!UtilityString.isNullOrEmpty(listModel.getSubDescription())) { - holder.mBinding.subDescrizione.setText(Html.fromHtml(listModel.getSubDescription())); + holder.mBinding.subDescrizione.setText(listModel.getSubDescriptionSpanned()); holder.mBinding.subDescrizione.setVisibility(View.VISIBLE); } else holder.mBinding.subDescrizione.setVisibility(View.GONE); if (!UtilityString.isNullOrEmpty(listModel.getRightDescription())) { - holder.mBinding.rightDescrizione.setText(Html.fromHtml(listModel.getRightDescription())); + holder.mBinding.rightDescrizione.setText(listModel.getRightDescriptionSpanned()); holder.mBinding.rightDescrizione.setVisibility(View.VISIBLE); } else holder.mBinding.rightDescrizione.setVisibility(View.GONE); if (!UtilityString.isNullOrEmpty(listModel.getRightSubDescription())) { - holder.mBinding.rightSubDescrizione.setText(Html.fromHtml(listModel.getRightSubDescription())); + holder.mBinding.rightSubDescrizione.setText(listModel.getRightSubDescriptionSpanned()); holder.mBinding.rightSubDescrizione.setVisibility(View.VISIBLE); } else holder.mBinding.rightSubDescrizione.setVisibility(View.GONE); 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/view/dialogs/DialogProgressView.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/DialogProgressView.java index 4c456019..dc04761d 100644 --- a/app/src/main/java/it/integry/integrywmsnative/view/dialogs/DialogProgressView.java +++ b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/DialogProgressView.java @@ -74,7 +74,12 @@ public class DialogProgressView extends DialogFragment { try { if (!manager.isDestroyed() && !isAdded()) { - //manager.executePendingTransactions(); + try { + manager.executePendingTransactions(); + } catch (IllegalStateException e) { + //ignore + String a = ""; + } showNow(manager, "loading-dialog"); mBindings.progressBar.setIndeterminate(isIndeterminateProgress()); @@ -91,7 +96,16 @@ public class DialogProgressView extends DialogFragment { handler.post(() -> { if (isAdded()) { dismissAllowingStateLoss(); + if (!getParentFragmentManager().isDestroyed()) { + try { + getParentFragmentManager().executePendingTransactions(); + } catch (IllegalStateException e) { + //ignore + String a = ""; + } + } } + }); } From 1988fae4f928fe8e655ffc70b3af2a65cd5e8ace Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 26 Feb 2025 13:12:00 +0100 Subject: [PATCH 05/19] Aggiunto profiler recyclerview solo in caso di debug --- .../core/expansion/view/SectionedRecyclerViewAdapter.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 index 53a9a699..80ccea3e 100644 --- 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 @@ -12,6 +12,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import it.integry.integrywmsnative.BuildConfig; + public abstract class SectionedRecyclerViewAdapter extends RecyclerView.Adapter { @@ -49,7 +51,7 @@ public abstract class SectionedRecyclerViewAdapter Date: Wed, 26 Feb 2025 13:50:20 +0100 Subject: [PATCH 06/19] Fix su filtri ordini uscita --- .../OrdiniUscitaElencoFragment.java | 6 +++--- .../filters/FilterClienteLayoutView.java | 14 +++++++------- .../filters/OrdiniUscitaElencoFiltroViewModel.java | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) 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 41912bdb..a5695e63 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 @@ -827,11 +827,11 @@ 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); }); } 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 22127813..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 @@ -194,7 +194,7 @@ public class OrdiniUscitaElencoFiltroViewModel { returnList = tmpStream.toList(); } - this.currentFilteredOrderList.postValue(returnList); + this.currentFilteredOrderList.setValue(returnList); } public ObservableField> getCurrentDepositoPredicate() { From 9d48fec426545dbe3ca5cf60964d37d702ea2e7b Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 26 Feb 2025 18:36:17 +0100 Subject: [PATCH 07/19] Aggiunto controllo su deposito in fase di picking uscita --- .../integrywmsnative/gest/spedizione/SpedizioneViewModel.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 1a82be96..23f77437 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 @@ -690,10 +690,11 @@ public class SpedizioneViewModel { if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { if (mtbColt.getSegno() != -1) { + boolean codMdepMatchPreviousPick = mCurrentMtbColt != null && (mtbColt.getMtbColr().isEmpty() || mCurrentMtbColt.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); - if (codMdepIsValid) { + if (codMdepIsValid && codMdepMatchPreviousPick) { searchArtFromUL(mtbColt); } else throw new InvalidCodMdepException(); From 0312f972bcf04391f08004beb0ffed269123b614 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 26 Feb 2025 19:01:04 +0100 Subject: [PATCH 08/19] Refactor: Update weight input dialog and LU closing logic - Changed `DialogInputPesoLUView` to use `BindableBigDecimal` for weight fields. - Updated `DialogInputPesoLUView` to invoke onComplete only after user confirmation - Refactored `SpedizioneViewModel` to correctly set values coming from the weight input dialog - Removed commented-out code in `SpedizioneViewModel` - Added handling for null values in weight fields. - `SpedizioneActivity` changed to pass current values to `DialogInputPesoLUView` - Fixed recovery mode UI not collapsing --- .../gest/main/MainFragment.java | 7 +- .../gest/spedizione/SpedizioneActivity.java | 4 +- .../gest/spedizione/SpedizioneViewModel.java | 94 +------------------ .../input_peso_lu/DialogInputPesoLUView.java | 16 +++- 4 files changed, 23 insertions(+), 98 deletions(-) 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..039296a5 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; @@ -70,6 +71,8 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab @Inject ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer; + @Inject + Handler handler; @Inject MenuService menuService; @@ -267,7 +270,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/spedizione/SpedizioneActivity.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneActivity.java index 5e9067fe..3f184b63 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 @@ -865,9 +865,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"); }); } 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 1a82be96..52b13d29 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 @@ -1682,92 +1682,6 @@ public class SpedizioneViewModel { this.sendOnLoadingEnded(); } -// public void requestCloseLU(boolean shouldPrint) throws Exception { -// if (mCurrentMtbColt == null) return; -// this.sendOnLoadingStarted(); -// -// var shouldBeDeleted = this.shouldUlBeDeleted(); -// if (shouldBeDeleted) { -// deleteLU(); -// -// this.mCurrentMtbColt = null; -// -// if (mMtbColtSessionID != null) -// this.mColliDataRecoverService.closeSession(mMtbColtSessionID); -// -// this.mIsNewLU = false; -// this.sendLUClosed(); -// this.sendOnLoadingEnded(); -// -// } else { -// var askInfoAggiuntiveFuture = Futures.transformAsync( -// askPeso(), -// voidResult -> askInfoAggiuntive(), -// executorService -// ); -// -// var closeLuFuture = Futures.transformAsync( -// askInfoAggiuntiveFuture, -// voidResult -> closeLU(), -// executorService -// ); -// -// var duplicateUlFuture = Futures.transformAsync( -// closeLuFuture, -// generatedMtbColts -> validateTheUdsToBeDuplicated(generatedMtbColts), -// executorService -// ); -// -// var filledMtbColtFuture = Futures.transformAsync( -// duplicateUlFuture, -// duplicatedMtbColts -> { -// SettableFuture> future = SettableFuture.create(); -// this.mColliMagazzinoRESTConsumer.fillMtbAartsOfMtbColts(duplicatedMtbColts, -// future::set, -// future::setException); -// -// return future; -// }, -// executorService -// ); -// -// var askPosizioneFuture = Futures.transformAsync(filledMtbColtFuture, -// this::askPositionChange, -// executorService); -// -// var askPrintFuture = Futures.transformAsync(askPosizioneFuture, -// mtbColts -> askPrint(shouldPrint && SettingsManager.iDB().isFlagPrintEtichetteOnLUClose(), mtbColts), -// executorService); -// -// -// Futures.addCallback(askPrintFuture, new FutureCallback<>() { -// -// @Override -// public void onSuccess(List result) { -// handler.post(() -> { -// result.stream() -// .filter(x -> !mColliRegistrati.contains(x)) -// .forEach(x -> mColliRegistrati.add(x)); -// -// postCloseOperations(result); -// -// mIsNewLU = false; -// -// resetMatchedRows(); -// sendLUClosed(); -// sendOnLoadingEnded(); -// }); -// } -// -// @Override -// public void onFailure(Throwable throwable) { -// sendError(new Exception(throwable)); -// } -// }, executorService); -// -// } -// } - public void requestCloseLU(boolean shouldPrint) throws Exception { if (mCurrentMtbColt == null) return; this.sendOnLoadingStarted(); @@ -1948,9 +1862,10 @@ public class SpedizioneViewModel { this.sendLUPesoRequired(mCurrentMtbColt.getCodTcol(), mCurrentMtbColt.getPesoNettoKg(), mCurrentMtbColt.getPesoKg(), (newCodTcol, newNetWeight, newGrossWeight) -> { - mCurrentMtbColt.setCodTcol(newCodTcol); - mCurrentMtbColt.setPesoNettoKg(newNetWeight); - mCurrentMtbColt.setPesoKg(newGrossWeight); + + if(newCodTcol != null) mCurrentMtbColt.setCodTcol(newCodTcol); + if(newNetWeight != null) mCurrentMtbColt.setPesoNettoKg(newNetWeight); + if(newGrossWeight != null) mCurrentMtbColt.setPesoKg(newGrossWeight); latch.countDown(); }); @@ -2047,6 +1962,7 @@ public class SpedizioneViewModel { this.sendLUPrintRequest(shouldPrint -> { if (!shouldPrint) { + latch.countDown(); return; } 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()); From e75121b0bdf80355e450925830aa4679fd412539 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 26 Feb 2025 19:10:30 +0100 Subject: [PATCH 09/19] Refactor: Improve data recovery in MainFragment - Replaced the previous data recovery mechanism with an ExecutorService-based approach. - This allows for concurrent recovery operations, improving overall efficiency. - Improved error handling by removing unnecessary callbacks and handling exceptions directly. - Replaced cyclic recursion with a simpler iterative loop for session recovery. --- .../gest/main/MainFragment.java | 86 ++++++++----------- 1 file changed, 37 insertions(+), 49 deletions(-) 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 039296a5..7fa9f314 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 @@ -21,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; @@ -32,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; @@ -44,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; @@ -71,6 +68,9 @@ public class MainFragment extends Fragment implements ITitledFragment, IScrollab @Inject ColliLavorazioneRESTConsumer colliLavorazioneRESTConsumer; + @Inject + ExecutorService executorService; + @Inject Handler handler; @@ -173,46 +173,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(); @@ -221,8 +206,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(); } @@ -231,26 +216,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); } } From 5694d8bd1c838010f5d4d0753c25e7e1f36a2897 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Fri, 28 Feb 2025 15:26:02 +0100 Subject: [PATCH 10/19] Migliorata gestione callback e chiamate in background per Picking Libero --- .../MainApplicationModule.java | 4 +- .../consumers/ColliMagazzinoRESTConsumer.java | 145 +-- .../rest/consumers/EntityRESTConsumer.java | 64 +- .../rest/consumers/GiacenzaRESTConsumer.java | 71 +- .../MagazzinoAutomaticoRESTConsumer.java | 4 +- .../picking_libero/PickingLiberoFragment.java | 86 +- .../picking_libero/PickingLiberoModule.java | 4 + .../PickingLiberoViewModel.java | 951 +++++++++--------- .../gest/spedizione/SpedizioneViewModel.java | 4 +- .../DialogInputQuantityV2View.java | 3 +- 10 files changed, 689 insertions(+), 647 deletions(-) diff --git a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java index ae78d4e7..cabc6fac 100644 --- a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java @@ -269,8 +269,8 @@ public class MainApplicationModule { @Provides @Singleton - GiacenzaRESTConsumer provideGiacenzaRESTConsumer(RESTBuilder restBuilder, ArticoloRESTConsumer articoloRESTConsumer) { - return new GiacenzaRESTConsumer(restBuilder, articoloRESTConsumer); + GiacenzaRESTConsumer provideGiacenzaRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, ArticoloRESTConsumer articoloRESTConsumer) { + return new GiacenzaRESTConsumer(restBuilder, executorService, articoloRESTConsumer); } @Provides 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 8314164e..e09577b9 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 @@ -16,8 +16,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.concurrent.ExecutorService; import java.util.Objects; +import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; import javax.inject.Singleton; @@ -37,7 +37,6 @@ 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.UpdateTipoULRequestDTO; import it.integry.integrywmsnative.core.rest.model.VersamentoAutomaticoULResponseDTO; @@ -75,7 +74,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { 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); @@ -86,17 +85,18 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { .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); + }); } @@ -327,6 +327,36 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { }); } + public List fillMtbAartsOfMtbColrsSynchronized(List mtbColrs) throws Exception { + + List codMarts = new ArrayList<>(mtbColrs.stream() + .map(MtbColr::getCodMart) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toUnmodifiableList())); + + var arts = mArticoloRESTConsumer.getByCodMartsSynchronized(codMarts); + + + 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<>(); @@ -405,6 +435,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { 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) @@ -424,9 +455,7 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { .execute(); var mtbColt = analyzeAnswer(response, "getColloInGiac"); if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { - List mtbColtList = new ArrayList<>(); - mtbColtList.add(mtbColt); - var mtbColts = fillMtbAartsOfMtbColtsSynchronized(mtbColtList); + var mtbColts = fillMtbAartsOfMtbColtsSynchronized(Collections.singletonList(mtbColt)); return mtbColts.get(0); } @@ -576,44 +605,45 @@ public class ColliMagazzinoRESTConsumer extends _BaseRESTConsumer { }); } + 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); + } + + mtbColtDestClone.setMtbColr(null); + + SpostaArtsTraULRequestDTO spostaArtsTraULRequestDTO = new SpostaArtsTraULRequestDTO() + .setSourceMtbColt(mtbColtToMoveClone) + .setDestinationMtbColt(mtbColtDestClone) + .setFlagForceUseRefs(flagForceUseRefs); + + ColliMagazzinoRESTConsumerService colliMagazzinoRESTConsumerService = restBuilder.getService(ColliMagazzinoRESTConsumerService.class); + var response = colliMagazzinoRESTConsumerService.spostaArtsTraUL(spostaArtsTraULRequestDTO) + .execute(); + + var data = analyzeAnswer(response, "spostaArtsTraUL"); + var mtbColrs = fillMtbAartsOfMtbColrsSynchronized(data.getGeneratedMtbColr()); + + return mtbColrs; + } + public void spostaArtsTraUL(MtbColt sourceMtbColt, MtbColt destMtbColt, boolean flagForceUseRefs, RunnableArgs> onComplete, RunnableArgs onFailed) { executorService.execute(() -> { - 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); + try { + var result = spostaArtsTraULSynchronized(sourceMtbColt, destMtbColt, flagForceUseRefs); + if (onComplete != null) onComplete.run(result); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } - - mtbColtDestClone.setMtbColr(null); - - 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 -> { - - fillMtbAartsOfMtbColrs(data.getGeneratedMtbColr(), onComplete, onFailed); - - }, onFailed); - } - - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - if (onFailed != null) onFailed.run(e); - } - }); }); } - public void assegnaLottoSuColloScarico(MtbColt sourceMtbColt, Runnable onComplete, RunnableArgs onFailed) { + public MtbColt assegnaLottoSuColloScaricoSynchronized(MtbColt sourceMtbColt) throws Exception { MtbColt sourceMtbColtClone = (MtbColt) sourceMtbColt.clone(); for (int i = 0; i < sourceMtbColtClone.getMtbColr().size(); i++) { @@ -623,17 +653,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); } }); } 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 00e1abeb..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 @@ -34,45 +34,41 @@ public class EntityRESTConsumer extends _BaseRESTConsumer { this.executorService = executorService; } - public void processEntity(T entityToSave, final ISimpleOperationCallback callback, Class type) { - - RunnableArgs tmpFailed = ex -> { - if (callback != null) callback.onFailed(ex); - }; - + public T processEntitySynchronized(T entityToSave, Class type) throws Exception { EntityRESTConsumerService service = restBuilder.getService(EntityRESTConsumerService.class); - service + var response = service .processEntity(entityToSave) - .enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call> call, Response> response) { - if (response.isSuccessful()) { + .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()) { + if (response.body() != null) { + if (response.body().getEsito() == EsitoType.OK) { + Gson gson = UtilityGson.createObject(); - 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())); - } - } + 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()); + } + } - @Override - public void onFailure(Call> call, @NonNull final Exception e) { - tmpFailed.run(e); - } - }); + 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); + } + }); } 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 8754f409..83506ee8 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 @@ -7,6 +7,8 @@ import com.annimon.stream.Stream; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.stream.Collectors; import javax.inject.Singleton; @@ -28,52 +30,55 @@ import retrofit2.Response; public class GiacenzaRESTConsumer extends _BaseRESTConsumer { private final RESTBuilder restBuilder; + private final ExecutorService executorService; private final ArticoloRESTConsumer mArticoloRESTConsumer; - public GiacenzaRESTConsumer(RESTBuilder restBuilder, ArticoloRESTConsumer articoloRESTConsumer) { + public GiacenzaRESTConsumer(RESTBuilder restBuilder, ExecutorService executorService, ArticoloRESTConsumer articoloRESTConsumer) { this.restBuilder = restBuilder; + this.executorService = executorService; this.mArticoloRESTConsumer = articoloRESTConsumer; } - public void getGiacenzeInPosizione(MtbDepoPosizione posizione, RunnableArgs> onComplete, RunnableArgs onFailed) { + public List getGiacenzeInPosizioneSynchronized(MtbDepoPosizione posizione) throws Exception { GiacenzaRESTConsumerService giacenzaRESTConsumerService = restBuilder.getService(GiacenzaRESTConsumerService.class); - giacenzaRESTConsumerService.retrieveAvailableItems(posizione.getPosizione()).enqueue(new ManagedErrorCallback<>() { - @Override - public void onResponse(Call>> call, Response>> response) { - analyzeAnswer(response, "getGiacenzeInPosizione", inventarioList -> { + var response = giacenzaRESTConsumerService.retrieveAvailableItems(posizione.getPosizione()) + .execute(); - if(inventarioList != null && !inventarioList.isEmpty()){ - List codMarts = Stream.of(inventarioList) - .map(x -> x.getCodMart().trim()) - .toList(); + var inventarioList = analyzeAnswer(response, "getGiacenzeInPosizione"); - mArticoloRESTConsumer.getByCodMarts(codMarts, mtbAarts -> { - for (var row : inventarioList) { + if (inventarioList != null && !inventarioList.isEmpty()) { + List codMarts = inventarioList.stream() + .map(x -> x.getCodMart().trim()) + .collect(Collectors.toList()); - MtbAart foundMtbAart = null; - Optional mtbAartOpt = Stream.of(mtbAarts) - .filter(x -> x.getCodMart().equalsIgnoreCase(row.getCodMart())) - .findFirst(); + var mtbAarts = mArticoloRESTConsumer.getByCodMartsSynchronized(codMarts); + for (var row : inventarioList) { + MtbAart foundMtbAart = null; + Optional mtbAartOpt = Stream.of(mtbAarts) + .filter(x -> x.getCodMart().equalsIgnoreCase(row.getCodMart())) + .findFirst(); - if (mtbAartOpt.isPresent()) { - foundMtbAart = mtbAartOpt.get(); - } + if (mtbAartOpt.isPresent()) { + foundMtbAart = mtbAartOpt.get(); + } - row.setMtbAart(foundMtbAart); - } - - onComplete.run(inventarioList); - }, onFailed); - }else{ - onComplete.run(new ArrayList<>()); - } - }, onFailed); + row.setMtbAart(foundMtbAart); } - @Override - public void onFailure(Call>> call, @NonNull final Exception e) { - onFailed.run(e); + return inventarioList; + } + + return new ArrayList<>(); + } + + public void getGiacenzeInPosizione(MtbDepoPosizione posizione, RunnableArgs> onComplete, RunnableArgs onFailed) { + executorService.execute(() -> { + try { + var result = getGiacenzeInPosizioneSynchronized(posizione); + if (onComplete != null) onComplete.run(result); + } catch (Exception ex) { + if (onFailed != null) onFailed.run(ex); } }); } @@ -92,8 +97,8 @@ public class GiacenzaRESTConsumer extends _BaseRESTConsumer { mArticoloRESTConsumer.getByCodMarts(codMarts, mtbAarts -> { for (var articoli : inventarioList) { List mvwSitArtUdcDetInventario = articoli.getMvwSitArtUdcDetInventarioDTO(); - if (mvwSitArtUdcDetInventario != null && !mvwSitArtUdcDetInventario.isEmpty()){ - for (var row : mvwSitArtUdcDetInventario){ + if (mvwSitArtUdcDetInventario != null && !mvwSitArtUdcDetInventario.isEmpty()) { + for (var row : mvwSitArtUdcDetInventario) { MtbAart foundMtbAart = null; Optional mtbAartOpt = Stream.of(mtbAarts) .filter(x -> x.getCodMart().equalsIgnoreCase(row.getCodMart())) 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 fcd79249..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 @@ -28,7 +28,7 @@ public class MagazzinoAutomaticoRESTConsumer extends _BaseRESTConsumer { this.restBuilder = restBuilder; } - public void pickItemsSynchronous(MtbDepoPosizione posizione, MagazzinoAutomaticoPickItemsRequestDTO magazzinoAutomaticoPickItemsRequestDTO) throws Exception { + public void pickItemsSynchronized(MtbDepoPosizione posizione, MagazzinoAutomaticoPickItemsRequestDTO magazzinoAutomaticoPickItemsRequestDTO) throws Exception { MagazzinoAutomaticoRESTConsumerService magazzinoAutomaticoRESTConsumerService = restBuilder.getService(MagazzinoAutomaticoRESTConsumerService.class); var response = magazzinoAutomaticoRESTConsumerService.pickItems(posizione.getPosizione(), magazzinoAutomaticoPickItemsRequestDTO) .execute(); @@ -39,7 +39,7 @@ public class MagazzinoAutomaticoRESTConsumer extends _BaseRESTConsumer { public void pickItems(MtbDepoPosizione posizione, MagazzinoAutomaticoPickItemsRequestDTO magazzinoAutomaticoPickItemsRequestDTO, Runnable onComplete, RunnableArgs onFailed) { executorService.execute(() -> { try { - pickItemsSynchronous(posizione, magazzinoAutomaticoPickItemsRequestDTO); + 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/gest/picking_libero/PickingLiberoFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoFragment.java index ee48c0e9..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); @@ -206,23 +210,41 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme } private final RunnableArgs onScanSuccessful = data -> { - BarcodeManager.disable(mBarcodeScannerInstanceID); this.onLoadingStarted(); - this.mViewModel.processBarcodeDTO(data, () -> { - BarcodeManager.enable(mBarcodeScannerInstanceID); - 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) { @@ -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) @@ -366,8 +388,8 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme if (!mDialogInputQuantityV2View.isVisible()) mDialogInputQuantityV2View.setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) .setOnComplete(resultDTO -> { - if(resultDTO == null || resultDTO.isAborted()) { - onComplete.run(null, false); + if (resultDTO == null || resultDTO.isAborted()) { + onComplete.run(null); return; } @@ -378,19 +400,16 @@ public class PickingLiberoFragment extends BaseFragment implements ITitledFragme .setPartitaMag(resultDTO.getPartitaMag()) .setDataScad(resultDTO.getDataScad()); - onComplete.run(pickedQuantityDTO, resultDTO.isShouldCloseLu()); - }) - .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(); }); } @@ -398,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(mBarcodeScannerInstanceID); - if (thereIsAnOpenedUL.get()) mViewModel.closeLU(onComplete); - else onComplete.run(); + 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 0c71ad4b..e675d333 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; @@ -71,6 +74,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 +100,7 @@ public class PickingLiberoViewModel { @Inject - public PickingLiberoViewModel(ExecutorService executorService, + public PickingLiberoViewModel(ExecutorService executorService, Handler handler, ArticoloRESTConsumer articoloRESTConsumer, ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer, BarcodeRESTConsumer barcodeRESTConsumer, @@ -107,6 +111,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 +138,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 +180,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 InvalidCodMdepException()); - - }, 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 InvalidCodMdepException()); - - } 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 +393,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 +434,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 +482,7 @@ public class PickingLiberoViewModel { } - this.sendOnItemDispatched( + var pickedQuantityDTO = this.sendOnItemDispatched( pickingObjectDTO, pickingObjectDTO.getMtbAart(), initialNumCnf, @@ -549,86 +498,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 +584,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,35 +600,25 @@ 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(); - + public void saveNewRow(PickingObjectDTO pickingObjectDTO, BigDecimal numCnf, BigDecimal qtaCnf, BigDecimal qtaTot, String partitaMag, LocalDate dataScad, boolean shouldCloseLU) throws Exception { final MtbColr mtbColr = new MtbColr() .setCodMart(pickingObjectDTO.getMtbAart().getCodMart()) .setPartitaMag(partitaMag) @@ -722,28 +643,26 @@ public class PickingLiberoViewModel { 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 value = mColliMagazzinoRESTConsumer.saveColloSynchronized(cloneMtbColt); - mCurrentMtbColt.getMtbColr().add(mtbColr); + 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()); - this.sendOnRowSaved(); - this.sendOnLoadingEnded(); + mCurrentMtbColt.getMtbColr().add(mtbColr); - if (shouldCloseLU) closeLU(null); - }, this::sendError); + this.sendOnRowSaved(); + if (shouldCloseLU) closeLU(); } - private void loadRifULFromMtbColr(MtbColr mtbColr, RunnableArgs 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()) && @@ -751,103 +670,99 @@ 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); - } + if (pickedQuantityDTO == null) { + return; + } - 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); - }); - - - }); + this.sendOnLoadingStarted(); + this.saveEditedRow(mtbColrToUpdate, + pickedQuantityDTO.getNumCnf(), + pickedQuantityDTO.getQtaCnf(), + pickedQuantityDTO.getQtaTot(), + pickedQuantityDTO.getPartitaMag(), + pickedQuantityDTO.getDataScad(), + pickedQuantityDTO.isShouldCloseLu()); + this.sendOnLoadingEnded(); } - 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(); @@ -871,110 +786,105 @@ public class PickingLiberoViewModel { mtbColt.getMtbColr().add(mtbColr); - this.mColliMagazzinoRESTConsumer.saveCollo(mtbColt, (value) -> { + var value = this.mColliMagazzinoRESTConsumer.saveColloSynchronized(mtbColt); - mtbColr.setNumCnf(numCnf) - .setQtaCnf(qtaCnf) - .setQtaCol(qtaTot); + mtbColr.setNumCnf(numCnf) + .setQtaCnf(qtaCnf) + .setQtaCol(qtaTot); + handler.post(() -> { this.mCurrentMtbColt.getMtbColr().remove(mtbColrToUpdate); this.mCurrentMtbColt.getMtbColr().add(mtbColr); + }); + + this.sendOnRowSaved(); + this.sendOnLoadingEnded(); + } + + + public void deleteRow(MtbColr mtbColrToDelete) throws Exception { + var shouldDelete = this.sendMtbColrDeleteRequest(); + 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); + + var value = this.mColliMagazzinoRESTConsumer.saveColloSynchronized(mtbColt); + + handler.post(() -> { + this.mCurrentMtbColt.getMtbColr().remove(mtbColrToDelete); + }); 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) { + public void closeLU() throws Exception { if (mCurrentMtbColt == null) { - if (onComplete != null) onComplete.run(); return; } - this.sendOnLoadingStarted(); this.mDefaultCommessa = null; - mColliMagazzinoRESTConsumer.canULBeDeleted(mCurrentMtbColt, canBeDeleted -> { - if (canBeDeleted) { - deleteLU(() -> { - if (mMtbColtSessionID != null) - this.mColliDataRecoverService.closeSession(mMtbColtSessionID); + var canBeDeleted = mColliMagazzinoRESTConsumer.canULBeDeletedSynchronized(mCurrentMtbColt); - this.sendLUClosed(); - this.sendOnLoadingEnded(); + if (canBeDeleted) { + deleteLU(); - this.mCurrentMtbColt = null; - if (onComplete != null) onComplete.run(); - }); - } else { + if (mMtbColtSessionID != null) + this.mColliDataRecoverService.closeSession(mMtbColtSessionID); - this.mColliMagazzinoRESTConsumer.assegnaLottoSuColloScarico(mCurrentMtbColt, () -> { + this.sendLUClosed(); + this.sendOnLoadingEnded(); - var closeUDSRequest = new CloseUDSRequestDTO() - .setMtbColt(mCurrentMtbColt); - - if (this.mDefaultGestione == GestioneEnum.LAVORAZIONE) { - 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); - } - - private void deleteLU(Runnable onComplete) { - DeleteULRequestDTO deleteULRequestDTO = new DeleteULRequestDTO() - .setMtbColt(mCurrentMtbColt); - mColliMagazzinoRESTConsumer.deleteUL(deleteULRequestDTO, () -> { 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) { + 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; } @@ -998,20 +908,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 { @@ -1026,28 +977,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, @@ -1065,7 +1018,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() { @@ -1105,7 +1068,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/spedizione/SpedizioneViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneViewModel.java index f80a8460..c5c24e76 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 @@ -812,7 +812,7 @@ public class SpedizioneViewModel { .setOrdersOfNewUDS(orders) .setItemsToPick(magazzinoAutomaticoPickItemRequestDTOList); - mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronous(mtbDepoPosizione, magazzinoAutomaticoPickRequest); + mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronized(mtbDepoPosizione, magazzinoAutomaticoPickRequest); } public void executeEmptyMagazzinoAutomaticoRequest(MtbDepoPosizione mtbDepoPosizione) throws Exception { @@ -826,7 +826,7 @@ public class SpedizioneViewModel { .setDefaultGestioneOfNewUDS(mDefaultGestioneOfUL.getText()) .setOrdersOfNewUDS(orders); - mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronous(mtbDepoPosizione, magazzinoAutomaticoPickRequest); + mMagazzinoAutomaticoRESTConsumer.pickItemsSynchronized(mtbDepoPosizione, magazzinoAutomaticoPickRequest); } private void searchArtFromUL(MtbColt scannedUL) throws Exception { 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 daa9b4df..81694f1e 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 @@ -298,6 +298,8 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia } private void dismiss(DialogInputQuantityV2ResultDTO result) { + super.dismiss(); + if (this.mOnComplete != null) { if(result == null) { result = new DialogInputQuantityV2ResultDTO() @@ -306,7 +308,6 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia this.mOnComplete.run(result); } - super.dismiss(); } @Override From 326a3a00b253b60d77a489f143711dbbd9940b7a Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 3 Mar 2025 13:30:43 +0100 Subject: [PATCH 11/19] Fix check deposito --- .../integrywmsnative/gest/spedizione/SpedizioneViewModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 c5c24e76..e4afc58a 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 @@ -690,7 +690,7 @@ public class SpedizioneViewModel { if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { if (mtbColt.getSegno() != -1) { - boolean codMdepMatchPreviousPick = mCurrentMtbColt != null && (mtbColt.getMtbColr().isEmpty() || mCurrentMtbColt.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); + boolean codMdepMatchPreviousPick = mCurrentMtbColt == null || mtbColt.getMtbColr().isEmpty() || mCurrentMtbColt.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep()); boolean codMdepIsValid = SettingsManager.iDB().getAvailableCodMdep().stream() .anyMatch(x -> x.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep())); From 7c35e19ed475d70195d4ce1d1093cc8e970c1380 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 3 Mar 2025 17:50:18 +0100 Subject: [PATCH 12/19] Fix vari --- .../gest/picking_libero/PickingLiberoViewModel.java | 12 ++++++++++-- .../gest/spedizione/SpedizioneViewModel.java | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) 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 e675d333..277f26b9 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 @@ -859,11 +859,19 @@ public class PickingLiberoViewModel { var closeUDSRequest = new CloseUDSRequestDTO() .setMtbColt(mCurrentMtbColt); - if (this.mDefaultGestione == GestioneEnum.LAVORAZIONE) { + 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()); + .setDocumentCodAnag(SettingsManager.iDB().getInternalCodAnags().stream() + .filter(InternalCodAnagsDTO::isFornitore) + .findFirst() + .get() + .getCodAnag()); } var response = this.mColliScaricoRESTConsumer.closeUDSSynchronized(closeUDSRequest); 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 e4afc58a..8ae521ce 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 @@ -690,7 +690,7 @@ public class SpedizioneViewModel { if (mtbColt != null && mtbColt.getMtbColr() != null && !mtbColt.getMtbColr().isEmpty()) { if (mtbColt.getSegno() != -1) { - boolean codMdepMatchPreviousPick = mCurrentMtbColt == null || mtbColt.getMtbColr().isEmpty() || mCurrentMtbColt.getCodMdep().equalsIgnoreCase(mtbColt.getCodMdep()); + 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())); From 044bcbd852c9e178e4298b005cd52226ce5695e0 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Tue, 4 Mar 2025 11:01:38 +0100 Subject: [PATCH 13/19] Fix after merge --- .../ask_position_of_lu/DialogAskPositionOfLUView.java | 11 ++++------- .../scan_or_create_lu/DialogScanOrCreateLUView.java | 1 - 2 files changed, 4 insertions(+), 8 deletions(-) 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..48f2b2b8 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 @@ -167,8 +167,6 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { mBarcodeScannerInstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO() .setOnScanSuccessful(onScanSuccessfull) .setOnScanFailed(this::onError)); - - BarcodeManager.enable(); } @Override @@ -180,7 +178,7 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { private final RunnableArgs onScanSuccessfull = data -> { - BarcodeManager.disable(); + BarcodeManager.disable(mBarcodeScannerInstanceID); if (!isOnLivelloPage()) { @@ -191,11 +189,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 +200,14 @@ public class DialogAskPositionOfLUView extends BaseDialogFragment { } } else { - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) .show(); } } else { Toast.makeText(requireContext(), "Barcode non riconosciuto", Toast.LENGTH_SHORT) .show(); - BarcodeManager.enable(); + BarcodeManager.enable(mBarcodeScannerInstanceID); } }; 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); } From cd89ce917ebb25ee06c6c145289ad6bb8b08cbaa Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 12 Mar 2025 18:11:53 +0100 Subject: [PATCH 14/19] Fix vari su Synchronized e MainThread --- .../rest/consumers/ArticoloRESTConsumer.java | 41 ++--- .../rest/consumers/GiacenzaRESTConsumer.java | 77 +++++----- .../rest/consumers/PrinterRESTConsumer.java | 17 +- .../OrdiniUscitaElencoFragment.java | 2 +- .../ui/OrdiniUscitaElencoAdapter.java | 4 +- .../gest/spedizione/SpedizioneActivity.java | 145 ++++++++++++------ .../gest/spedizione/SpedizioneViewModel.java | 83 +++++----- .../DialogPrintOrderSSCCListView.java | 37 ++++- .../DialogInfoSituazioneArticoloView.java | 43 ++++-- ...t_main_ordini_uscita__list_group_model.xml | 1 + 10 files changed, 276 insertions(+), 174 deletions(-) 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 12bc1577..c25f2672 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 @@ -10,7 +10,9 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Objects; import java.util.concurrent.ExecutorService; +import java.util.stream.Collectors; import javax.inject.Singleton; @@ -106,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 @@ -207,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()) { @@ -237,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/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/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/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java b/app/src/main/java/it/integry/integrywmsnative/gest/ordini_uscita_elenco/OrdiniUscitaElencoFragment.java index a5695e63..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 @@ -768,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 = dataList.parallelStream() + List notHiddenElements = dataList.stream() .filter(x -> !x.isHidden()) .sorted(comparator) .map(x -> { 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 7a0ae725..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 @@ -53,7 +53,9 @@ public class OrdiniUscitaElencoAdapter extends ExtendedSectionedRecyclerViewNew< String[] keyArray = new String[collect.keySet().size()]; collect.keySet().toArray(keyArray); - setSections(Arrays.asList(keyArray), collect); + var keyList = Arrays.asList(keyArray); + keyList.sort(String::compareTo); + setSections(keyList, collect); } }); } 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 be11478c..d20a7c5a 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 @@ -26,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; @@ -257,7 +259,9 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo }); } else { BarcodeManager.removeCallback(mBarcodeScannerInstanceID); - super.onBackPressed(); + handler.post(() -> { + super.onBackPressed(); + }); } } @@ -830,10 +834,16 @@ public class SpedizioneActivity extends BaseActivity implements SpedizioneViewMo public void closeOrder() { - handler.post(() -> { - this.fabPopupMenu.dismiss(); + this.fabPopupMenu.dismiss(); + this.onLoadingStarted(); - this.mViewmodel.closeOrder(); + executorService.execute(() -> { + try { + this.mViewmodel.closeOrder(); + this.onLoadingEnded(); + } catch (Exception e) { + onError(e); + } }); } @@ -1051,66 +1061,113 @@ 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 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 8ae521ce..fd3398bc 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 @@ -354,8 +354,12 @@ 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() { @@ -519,33 +523,33 @@ public class SpedizioneViewModel { } public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO) throws Exception { - //Se non c'è una UL aperta - if (mCurrentMtbColt == null) { + //Se non c'è una UL aperta + if (mCurrentMtbColt == null) { - //Se è un'etichetta anonima - if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { - //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); + //Se è un'etichetta anonima + if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { + //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); - } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)/* && mDefaultSegnoCol == 1*/) { - this.processBarcodePosizioneNotOpenedLU(barcodeScanDTO); - - } else { - this.processBarcodeNotOpenedLU(barcodeScanDTO); - } + } else if (UtilityBarcode.isEtichettaPosizione(barcodeScanDTO)/* && mDefaultSegnoCol == 1*/) { + this.processBarcodePosizioneNotOpenedLU(barcodeScanDTO); } else { - if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { - //Cerco gli articoli presenti nell'ul dell'etichetta anonima - this.executeEtichettaLU(barcodeScanDTO.getStringValue()); - - } else { - this.processBarcodeAlreadyOpenedLU(barcodeScanDTO); - } + this.processBarcodeNotOpenedLU(barcodeScanDTO); } + } else { + if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO)) { + //Cerco gli articoli presenti nell'ul dell'etichetta anonima + this.executeEtichettaLU(barcodeScanDTO.getStringValue()); + + } else { + this.processBarcodeAlreadyOpenedLU(barcodeScanDTO); + } + } + } private void processBarcodePosizioneNotOpenedLU(BarcodeScanDTO barcodeScanDTO) throws Exception { @@ -1864,9 +1868,9 @@ public class SpedizioneViewModel { (newCodTcol, newNetWeight, newGrossWeight) -> { - if(newCodTcol != null) mCurrentMtbColt.setCodTcol(newCodTcol); - if(newNetWeight != null) mCurrentMtbColt.setPesoNettoKg(newNetWeight); - if(newGrossWeight != null) mCurrentMtbColt.setPesoKg(newGrossWeight); + if (newCodTcol != null) mCurrentMtbColt.setCodTcol(newCodTcol); + if (newNetWeight != null) mCurrentMtbColt.setPesoNettoKg(newNetWeight); + if (newGrossWeight != null) mCurrentMtbColt.setPesoKg(newGrossWeight); latch.countDown(); }); @@ -2098,20 +2102,21 @@ public class SpedizioneViewModel { } public void closeOrder() { - this.sendOnLoadingStarted(); + 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()) @@ -2121,11 +2126,17 @@ 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()); } @@ -2236,7 +2247,7 @@ public class SpedizioneViewModel { void onBatchLotSelectionRequest(List availableBatchLots, RunnableArgs onComplete); - void onCloseOrderPrintRequest(RunnableArgs onComplete); + PrintOrderCloseDTO onCloseOrderPrintRequest(); void onCreateDocsRequest(); 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/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 4ca47ca2..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 @@ -25,6 +25,7 @@ android:layout_height="0dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" + app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintWidth="8dp"/> From 18937a33153ec50b29bd94285b53015c44b1b823 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Wed, 12 Mar 2025 19:26:45 +0100 Subject: [PATCH 15/19] Fix vari su Synchronized e MainThread --- .../MainApplicationModule.java | 4 +- .../core/context/MainContext.java | 17 +++- .../RettificaGiacenzeFragment.java | 97 +++++++++++-------- .../gest/spedizione/SpedizioneViewModel.java | 8 +- 4 files changed, 73 insertions(+), 53 deletions(-) diff --git a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java index cabc6fac..cd3919db 100644 --- a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java +++ b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java @@ -99,8 +99,8 @@ public class MainApplicationModule { @Provides @Singleton - MainContext providesMainContextNew(MenuService menuService, AppDatabase appDatabase, SystemRESTConsumer systemRESTConsumer, AuthenticationRESTConsumer authenticationRESTConsumer) { - return new MainContext(mApplication.getApplicationContext(), menuService, appDatabase, systemRESTConsumer, authenticationRESTConsumer); + MainContext providesMainContextNew(MenuService menuService, AppDatabase appDatabase, SystemRESTConsumer systemRESTConsumer, AuthenticationRESTConsumer authenticationRESTConsumer, ExecutorService executorService, Handler handler) { + return new MainContext(mApplication.getApplicationContext(), menuService, appDatabase, systemRESTConsumer, authenticationRESTConsumer, executorService, handler); } @Provides 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 36812bd0..2de28edb 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,6 +10,7 @@ import android.text.SpannedString; import com.google.firebase.installations.FirebaseInstallations; import java.net.ConnectException; +import java.util.concurrent.ExecutorService; import javax.inject.Singleton; @@ -18,7 +20,6 @@ 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 @@ -29,15 +30,19 @@ public class MainContext { private final AppDatabase appDatabase; private final SystemRESTConsumer systemRESTConsumer; private final AuthenticationRESTConsumer authenticationRESTConsumer; + private final ExecutorService executorService; + private final Handler handler; private Listener mListener; - public MainContext(Context applicationContext, MenuService menuService, AppDatabase appDatabase, SystemRESTConsumer systemRESTConsumer, AuthenticationRESTConsumer authenticationRESTConsumer) { + public MainContext(Context applicationContext, MenuService menuService, AppDatabase appDatabase, SystemRESTConsumer systemRESTConsumer, AuthenticationRESTConsumer authenticationRESTConsumer, ExecutorService executorService, Handler handler) { this.applicationContext = applicationContext; this.menuService = menuService; this.appDatabase = appDatabase; this.systemRESTConsumer = systemRESTConsumer; this.authenticationRESTConsumer = authenticationRESTConsumer; + this.executorService = executorService; + this.handler = handler; } public void init() { @@ -105,14 +110,16 @@ 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() { 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 43aad056..bc1002d7 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); @@ -268,46 +272,49 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr @Override public void onFornitoriLoaded(ArrayList fornitoriList) { - AutoCompleteFornitoreAdapter autoCompleteFornitoreAdapter = new AutoCompleteFornitoreAdapter(getActivity(), fornitoriList); - mBinding.autoCompleteFornitori.setAdapter(autoCompleteFornitoreAdapter); - mBinding.autoCompleteFornitori.setDropDownWidth(getActivity().getResources().getDisplayMetrics().widthPixels); + handler.post(() -> { - mBinding.inputCodArtDescrForn.setOnEditorActionListener((v, actionId, event) -> { - if (actionId == EditorInfo.IME_ACTION_DONE) { - resetAllError(); + AutoCompleteFornitoreAdapter autoCompleteFornitoreAdapter = new AutoCompleteFornitoreAdapter(getActivity(), fornitoriList); + mBinding.autoCompleteFornitori.setAdapter(autoCompleteFornitoreAdapter); + mBinding.autoCompleteFornitori.setDropDownWidth(getActivity().getResources().getDisplayMetrics().widthPixels); - if (UtilityString.isNullOrEmpty(mBinding.autoCompleteFornitori.getText().toString())) { - setError(mBinding.autoCompleteFornitoriLayout, getActivity().getResources().getText(R.string.error).toString()); + mBinding.inputCodArtDescrForn.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + resetAllError(); + + if (UtilityString.isNullOrEmpty(mBinding.autoCompleteFornitori.getText().toString())) { + setError(mBinding.autoCompleteFornitoriLayout, getActivity().getResources().getText(R.string.error).toString()); + return true; + } + + if (UtilityString.isNullOrEmpty(mBinding.inputCodArtDescrForn.getText().toString())) { + setError(mBinding.layoutCodArtDescrForn, getActivity().getResources().getText(R.string.error).toString()); + return true; + } + + mViewModel.searchArtFor( + mBinding.autoCompleteFornitori.getText().toString(), + mBinding.inputCodArtDescrForn.getText().toString()); return true; } + return false; + }); - if (UtilityString.isNullOrEmpty(mBinding.inputCodArtDescrForn.getText().toString())) { - setError(mBinding.layoutCodArtDescrForn, getActivity().getResources().getText(R.string.error).toString()); + + mBinding.inputCodArtDescrInt.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + resetAllError(); + + if (UtilityString.isNullOrEmpty(mBinding.inputCodArtDescrInt.getText().toString())) { + setError(mBinding.layoutCodArtDescrInt, getActivity().getResources().getText(R.string.error).toString()); + return true; + } + + mViewModel.searchArtInt(mBinding.inputCodArtDescrInt.getText().toString(), null, null); return true; } - - mViewModel.searchArtFor( - mBinding.autoCompleteFornitori.getText().toString(), - mBinding.inputCodArtDescrForn.getText().toString()); - return true; - } - return false; - }); - - - mBinding.inputCodArtDescrInt.setOnEditorActionListener((v, actionId, event) -> { - if (actionId == EditorInfo.IME_ACTION_DONE) { - resetAllError(); - - if (UtilityString.isNullOrEmpty(mBinding.inputCodArtDescrInt.getText().toString())) { - setError(mBinding.layoutCodArtDescrInt, getActivity().getResources().getText(R.string.error).toString()); - return true; - } - - mViewModel.searchArtInt(mBinding.inputCodArtDescrInt.getText().toString(), null, null); - return true; - } - return false; + return false; + }); }); } @@ -339,21 +346,25 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr @Override public void onLUOpened(MtbColt mtbColt) { - initAdapter(); + handler.post(() -> { + initAdapter(); - this.currentMtbColtObs.set(mtbColt); - thereIsAnOpenedUL.set(true); + this.currentMtbColtObs.set(mtbColt); + thereIsAnOpenedUL.set(true); + }); } @Override public void onLUClosed() { - destroyAdapter(); + handler.post(() -> { + destroyAdapter(); - this.currentMtbColtObs.set(null); - thereIsAnOpenedUL.set(false); + this.currentMtbColtObs.set(null); + thereIsAnOpenedUL.set(false); - this.mViewModel.requestLU(); - /*if (getActivity() != null) ((IPoppableActivity) getActivity()).pop();*/ + this.mViewModel.requestLU(); + /*if (getActivity() != null) ((IPoppableActivity) getActivity()).pop();*/ + }); } @Override @@ -426,7 +437,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr mDialogInputQuantityV2View .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO) .setOnComplete(resultDTO -> { - if(resultDTO == null || resultDTO.isAborted()) return; + if (resultDTO == null || resultDTO.isAborted()) return; PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO() .setNumCnf(resultDTO.getNumCnf()) @@ -458,7 +469,7 @@ public class RettificaGiacenzeFragment extends BaseFragment implements ITitledFr @Override public void onRowSaved() { Snackbar.make(getView(), R.string.data_saved, Snackbar.LENGTH_SHORT) - .setBackgroundTint(getResources().getColor(R. color. green_500)) + .setBackgroundTint(getResources().getColor(R.color.green_500)) .show(); } 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 fd3398bc..1da4cfb8 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 @@ -1524,8 +1524,9 @@ public class SpedizioneViewModel { MtbColr createdMtbColr = null; try { - executeDepositChangeIfNeeded(refMtbColt); - executeTipoUlChangeIfNeeded(refMtbColt); + MtbColt sourceMtbColt = pickingObjectDTO.getTempPickData() != null ? pickingObjectDTO.getTempPickData().getSourceMtbColt() : null; + executeDepositChangeIfNeeded(sourceMtbColt); + executeTipoUlChangeIfNeeded(sourceMtbColt); createdMtbColr = this.mColliScaricoRESTConsumer.insertUDSRowSynchronized(insertUDSRowRequestDto); } catch (Exception ex) { @@ -2130,7 +2131,8 @@ public class SpedizioneViewModel { try { printClosedOrders(dto); } catch (Exception e) { - this.sendLUPrintError(e, () -> {}); + this.sendLUPrintError(e, () -> { + }); } } From 71f077a617143be83e3a791b459a0d7193e7978a Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Fri, 14 Mar 2025 13:25:40 +0100 Subject: [PATCH 16/19] Fix after merge --- .idea/AndroidProjectSystem.xml | 6 ++++++ ...dMdepLUException.java => InvalidCodMdepException.java} | 6 +++--- .../gest/picking_libero/PickingLiberoViewModel.java | 6 +++--- .../ProdVersamentoMaterialeViewModel.java | 6 +++--- .../pv_verifica_giacenze/VerificaGiacenzeFragment.java | 2 +- .../gest/spedizione/SpedizioneViewModel.java | 8 ++++---- .../gest/versamento_merce/VersamentoMerceViewModel.java | 6 +++--- 7 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 .idea/AndroidProjectSystem.xml rename app/src/main/java/it/integry/integrywmsnative/core/exception/{InvalidCodMdepLUException.java => InvalidCodMdepException.java} (69%) diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 00000000..4a53bee8 --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file 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/gest/picking_libero/PickingLiberoViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/picking_libero/PickingLiberoViewModel.java index da4fe77a..277f26b9 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 @@ -20,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; @@ -245,7 +245,7 @@ public class PickingLiberoViewModel { if (codMdepIsValid) { pickMerceULtoUL(mtbColt, articolo); - } else throw new InvalidCodMdepLUException(); + } else throw new InvalidCodMdepException(); } else { @@ -271,7 +271,7 @@ public class PickingLiberoViewModel { if (codMdepIsValid) { pickMerceULtoUL(mtbColtScanned); - } else throw new InvalidCodMdepLUException(); + } else throw new InvalidCodMdepException(); } else { throw new NoLUFoundException(); 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..b4484c1a 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 @@ -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.NoLUFoundException; import it.integry.integrywmsnative.core.exception.NoResultFromBarcodeException; import it.integry.integrywmsnative.core.exception.TooManyLUFoundInMonoLUPositionException; @@ -116,7 +116,7 @@ public class ProdVersamentoMaterialeViewModel { if (codMdepIsValid) { this.onLUOpened(mtbColt); - } else this.sendError(new InvalidCodMdepLUException()); + } else this.sendError(new InvalidCodMdepException()); }, this::sendError); } else { @@ -135,7 +135,7 @@ public class ProdVersamentoMaterialeViewModel { if (codMdepIsValid) { this.onLUOpened(mtbColt); - } else this.sendError(new InvalidCodMdepLUException()); + } else this.sendError(new InvalidCodMdepException()); }, this::sendError); } 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 0a1562ec..40aec6ff 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 @@ -284,7 +284,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/spedizione/SpedizioneViewModel.java b/app/src/main/java/it/integry/integrywmsnative/gest/spedizione/SpedizioneViewModel.java index f1057b4b..50c5120f 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 @@ -29,7 +29,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; @@ -640,7 +640,7 @@ public class SpedizioneViewModel { if (codMdepIsValid) { this.createNewLU(null, null); searchArtFromUL(mtbColt); - } else throw new InvalidCodMdepLUException(); + } else throw new InvalidCodMdepException(); } } @@ -681,7 +681,7 @@ public class SpedizioneViewModel { if (codMdepIsValid) { this.searchArtFromUL(mtbColt); - } else throw new InvalidCodMdepLUException(); + } else throw new InvalidCodMdepException(); } else { throw new EmptyLUException(); @@ -700,7 +700,7 @@ public class SpedizioneViewModel { if (codMdepIsValid && codMdepMatchPreviousPick) { searchArtFromUL(mtbColt); - } else throw new InvalidCodMdepLUException(); + } else throw new InvalidCodMdepException(); } else { throw new InvalidLUException(); 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()); } } From ce5ab1cfc27fe09dddecd514c4b954a62faffe5e Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 17 Mar 2025 18:31:45 +0100 Subject: [PATCH 17/19] Resa synchronized l'init iniziale dell'app --- .../MainApplicationModule.java | 11 +- .../integrywmsnative/SplashActivity.java | 20 +- .../core/context/MainContext.java | 82 +++---- .../core/menu/MenuRESTConsumer.java | 22 +- .../core/menu/MenuService.java | 23 +- .../rest/consumers/AziendaRESTConsumer.java | 22 +- .../rest/consumers/GestSetupRESTConsumer.java | 34 +-- .../rest/consumers/PosizioniRESTConsumer.java | 24 +- .../rest/consumers/SystemRESTConsumer.java | 5 + .../rest/watcher/ServerStatusChecker.java | 53 ++-- .../core/settings/SettingsManager.java | 208 +++++++--------- .../core/utility/UtilityExceptions.java | 10 +- .../gest/main/MainActivity.java | 5 +- .../gest/main/MainFragment.java | 5 +- .../dialogs/base/DialogSimpleMessageView.java | 7 +- .../DialogInputQuantityV2Module.java | 6 +- .../DialogInputQuantityV2View.java | 25 +- .../DialogInputQuantityV2ViewModel.java | 226 +++++++++--------- 18 files changed, 366 insertions(+), 422 deletions(-) diff --git a/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java b/app/src/main/java/it/integry/integrywmsnative/MainApplicationModule.java index 4473d541..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, ExecutorService executorService, Handler handler) { - return new MainContext(mApplication.getApplicationContext(), menuService, appDatabase, systemRESTConsumer, authenticationRESTConsumer, executorService, handler); + 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 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/context/MainContext.java b/app/src/main/java/it/integry/integrywmsnative/core/context/MainContext.java index e2b61c24..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 @@ -17,7 +17,6 @@ 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.gest.login.rest.AuthenticationRESTConsumer; @@ -28,21 +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, ExecutorService executorService, Handler handler) { + 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() { @@ -53,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 -> { @@ -122,40 +118,16 @@ public class MainContext { }); } - 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/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/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/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/PosizioniRESTConsumer.java b/app/src/main/java/it/integry/integrywmsnative/core/rest/consumers/PosizioniRESTConsumer.java index eceb8263..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,7 +1,5 @@ package it.integry.integrywmsnative.core.rest.consumers; -import androidx.annotation.NonNull; - import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; @@ -15,11 +13,7 @@ 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 { @@ -34,23 +28,15 @@ public class PosizioniRESTConsumer extends _BaseRESTConsumer { 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 ArrayList getBancaliInPosizioneSynchronized(MtbDepoPosizione mtbDepoPosizione) throws Exception { 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/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/SettingsManager.java b/app/src/main/java/it/integry/integrywmsnative/core/settings/SettingsManager.java index f0850073..f1dc75bc 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<>(); @@ -648,34 +623,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/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/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 7fa9f314..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 @@ -80,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<>(); @@ -144,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()) { 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/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/DialogInputQuantityV2View.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2View.java index 81694f1e..3b5f4744 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 @@ -4,6 +4,7 @@ import android.app.Dialog; import android.content.Context; import android.content.res.ColorStateList; import android.os.Bundle; +import android.os.Handler; import android.text.Html; import android.text.InputType; import android.text.SpannableString; @@ -56,6 +57,9 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia @Inject DialogInputQuantityV2ViewModel mViewModel; + @Inject + Handler handler; + private DialogInputQuantityV2DTO mDialogInputQuantityV2DTO; //1: Result / 2: ShouldCloseLu / 3: Aborted private RunnableArgs mOnComplete; @@ -267,13 +271,13 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia this.mViewModel.validate(validated -> { - requireActivity().runOnUiThread(() -> { + handler.post(() -> { this.onLoadingEnded(); if (validated) { var result = this.mViewModel.getResult() - .setAborted(false) - .setShouldCloseLu(false); + .setAborted(false) + .setShouldCloseLu(false); dismiss(result); } }); @@ -301,7 +305,7 @@ public class DialogInputQuantityV2View extends BaseDialogFragment implements Dia super.dismiss(); if (this.mOnComplete != null) { - if(result == null) { + if (result == null) { result = new DialogInputQuantityV2ResultDTO() .setAborted(true); } @@ -562,11 +566,14 @@ 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 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 02c8edd3..ae2e3ef8 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 @@ -6,6 +6,7 @@ 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; @@ -98,6 +99,7 @@ public class DialogInputQuantityV2ViewModel { private Listener mListener; + private final ExecutorService executorService; private final BarcodeRESTConsumer mBarcodeRESTConsumer; private final MagazzinoRESTConsumer mMagazzinoRESTConsumer; @@ -106,7 +108,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; } @@ -515,142 +518,147 @@ public class DialogInputQuantityV2ViewModel { } public void validate(RunnableArgs onValidated) { - if (this.internalQtaCnf == null || UtilityBigDecimal.equalsTo(this.internalQtaCnf, BigDecimal.ZERO)) { + executorService.execute(() -> { - this.sendError(new InvalidQtaCnfQuantityException()); - onValidated.run(false); - return; - } - if (!disableTracciabilitaCheck && mtbAart.get().isFlagTracciabilitaBoolean()) { - if (UtilityString.isNullOrEmpty(internalPartitaMag)) { - if (suggestPartitaMagRunnable != null) { - internalPartitaMag = suggestPartitaMagRunnable.run(this); - if (internalPartitaMag == null) { + if (this.internalQtaCnf == null || UtilityBigDecimal.equalsTo(this.internalQtaCnf, BigDecimal.ZERO)) { + + this.sendError(new InvalidQtaCnfQuantityException()); + onValidated.run(false); + return; + } + + if (!disableTracciabilitaCheck && mtbAart.get().isFlagTracciabilitaBoolean()) { + if (UtilityString.isNullOrEmpty(internalPartitaMag)) { + if (suggestPartitaMagRunnable != null) { + internalPartitaMag = suggestPartitaMagRunnable.run(this); + if (internalPartitaMag == null) { + this.sendError(new InvalidBatchLotException()); + onValidated.run(false); + return; + } + } else { this.sendError(new InvalidBatchLotException()); onValidated.run(false); return; } } else { - this.sendError(new InvalidBatchLotException()); - onValidated.run(false); - return; - } - } else { - if (SettingsManager.iDB().isFlagWarningNewPartitaMag()) { - MtbPartitaMag mtbPartitaMag = null; - try { - mtbPartitaMag = retrievePartitaMag(internalPartitaMag, this.getMtbAart().getCodMart()); - } catch (Exception e) { - this.sendError(e); - onValidated.run(false); - return; - } - - if (mtbPartitaMag == null) { - boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.batch_lot_inexistent_error_message)); - if (!result) { + if (SettingsManager.iDB().isFlagWarningNewPartitaMag()) { + MtbPartitaMag mtbPartitaMag = null; + try { + mtbPartitaMag = retrievePartitaMag(internalPartitaMag, this.getMtbAart().getCodMart()); + } catch (Exception e) { + this.sendError(e); onValidated.run(false); return; } + + if (mtbPartitaMag == null) { + boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.batch_lot_inexistent_error_message)); + if (!result) { + onValidated.run(false); + return; + } + } } } } - } - if (this.statoArt == StatoPartitaMag.DISATTIVO) { - boolean result = runWarningDialogSyncronized(String.format(UtilityResources.getString(R.string.batch_lot_not_enabled), internalPartitaMag)); - if (!result) { + if (this.statoArt == StatoPartitaMag.DISATTIVO) { + boolean result = runWarningDialogSyncronized(String.format(UtilityResources.getString(R.string.batch_lot_not_enabled), internalPartitaMag)); + if (!result) { + onValidated.run(false); + return; + } + } + + if (this.shouldAskDataScad && UtilityString.isNullOrEmpty(internalPartitaMag)) { + + this.sendError(new InvalidBatchLotException()); onValidated.run(false); return; } - } - if (this.shouldAskDataScad && UtilityString.isNullOrEmpty(internalPartitaMag)) { + if (this.shouldAskDataScad && this.internalDataScad == null) { - this.sendError(new InvalidBatchLotException()); - onValidated.run(false); - return; - } - - if (this.shouldAskDataScad && this.internalDataScad == null) { - - this.sendError(new InvalidExpireDateException()); - onValidated.run(false); - return; - } - - if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && - this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - this.sendError(new OverflowQtaTotOrderedQuantityException()); - onValidated.run(false); - return; - } - - if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && - !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - this.sendError(new OverflowNumCnfOrderedQuantityException()); - onValidated.run(false); - return; - } - - if (UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaAvailable)) { - - this.sendError(new OverflowQtaTotAvailableQuantityException()); - onValidated.run(false); - return; - } - - if (UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfAvailable) && - !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - this.sendError(new OverflowNumCnfAvailableQuantityException()); - onValidated.run(false); - return; - } - - if (!this.canInputZeroQuantity && (this.internalNumCnf == null || this.internalQtaCnf == null || this.internalQtaTot == null || - UtilityBigDecimal.equalsOrLowerThan(this.internalNumCnf, BigDecimal.ZERO) || - UtilityBigDecimal.equalsOrLowerThan(this.internalQtaCnf, BigDecimal.ZERO) || - UtilityBigDecimal.equalsOrLowerThan(this.internalQtaTot, BigDecimal.ZERO))) { - - this.sendError(new InvalidQuantityException()); - onValidated.run(false); - return; - } - - if (this.isNoteMandatory() && (this.internalNote == null || this.internalNote.length() <= 0)) { - this.sendError(new InvalidNotesException()); - onValidated.run(false); - return; - } - - if (!UtilityString.isNullOrEmpty(this.internalPartitaMag)) - this.internalPartitaMag = this.internalPartitaMag.toUpperCase(); - - if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && - this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - - boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_quantity_overflow_error_message)); - if (!result) { + this.sendError(new InvalidExpireDateException()); onValidated.run(false); return; } - } - if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && - !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && + this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { - boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_num_cnf_overflow_error_message)); - if (!result) { + this.sendError(new OverflowQtaTotOrderedQuantityException()); onValidated.run(false); return; } - } - onValidated.run(true); + if (!this.canOverflowOrderQuantity && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && + !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + this.sendError(new OverflowNumCnfOrderedQuantityException()); + onValidated.run(false); + return; + } + + if (UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaAvailable)) { + + this.sendError(new OverflowQtaTotAvailableQuantityException()); + onValidated.run(false); + return; + } + + if (UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfAvailable) && + !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + this.sendError(new OverflowNumCnfAvailableQuantityException()); + onValidated.run(false); + return; + } + + if (!this.canInputZeroQuantity && (this.internalNumCnf == null || this.internalQtaCnf == null || this.internalQtaTot == null || + UtilityBigDecimal.equalsOrLowerThan(this.internalNumCnf, BigDecimal.ZERO) || + UtilityBigDecimal.equalsOrLowerThan(this.internalQtaCnf, BigDecimal.ZERO) || + UtilityBigDecimal.equalsOrLowerThan(this.internalQtaTot, BigDecimal.ZERO))) { + + this.sendError(new InvalidQuantityException()); + onValidated.run(false); + return; + } + + if (this.isNoteMandatory() && (this.internalNote == null || this.internalNote.length() <= 0)) { + this.sendError(new InvalidNotesException()); + onValidated.run(false); + return; + } + + if (!UtilityString.isNullOrEmpty(this.internalPartitaMag)) + this.internalPartitaMag = this.internalPartitaMag.toUpperCase(); + + if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalQtaTot, this.totalQtaOrd) && + this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_quantity_overflow_error_message)); + if (!result) { + onValidated.run(false); + return; + } + } + + if (this.warnOnQuantityOverflow && UtilityBigDecimal.greaterThan(this.internalNumCnf, this.totalNumCnfOrd) && + !this.mtbAart.get().isFlagQtaCnfFissaBoolean()) { + + boolean result = runWarningDialogSyncronized(UtilityResources.getString(R.string.confirm_ordered_num_cnf_overflow_error_message)); + if (!result) { + onValidated.run(false); + return; + } + } + + onValidated.run(true); + + }); } private boolean runWarningDialogSyncronized(String text) { From 1b4df1ecd1a0315f161311691f702bee6244b9ac Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 17 Mar 2025 18:59:47 +0100 Subject: [PATCH 18/19] Implementato flag che abilita/disabilita il fast-picking --- .../core/settings/DBSettingsModel.java | 9 +++++++++ .../core/settings/SettingsManager.java | 6 ++++++ .../gest/spedizione/SpedizioneActivity.java | 3 ++- .../DialogInputQuantityV2DTO.java | 10 ++++++++++ .../DialogInputQuantityV2View.java | 5 +++-- .../DialogInputQuantityV2ViewModel.java | 14 +++++++++++--- 6 files changed, 41 insertions(+), 6 deletions(-) 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 f1dc75bc..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 @@ -558,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") 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 d20a7c5a..1f4e7de6 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 @@ -1014,7 +1014,8 @@ 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 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..640a29ce 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 @@ -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; @@ -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/DialogInputQuantityV2View.java b/app/src/main/java/it/integry/integrywmsnative/view/dialogs/input_quantity_v2/DialogInputQuantityV2View.java index 3b5f4744..b387510e 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 @@ -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); 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 ae2e3ef8..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 @@ -96,6 +96,7 @@ public class DialogInputQuantityV2ViewModel { private int onQtaTotInputChanged; private boolean disableTracciabilitaCheck; private boolean warnOnQuantityOverflow; + private boolean enableSSCCRead; private Listener mListener; @@ -213,8 +214,10 @@ public class DialogInputQuantityV2ViewModel { this.unlockQtaCnf(); } else if (ean128Model.Sscc != null) { //Close current UDS and open another one with new SSCC - this.internalNextUlBarcode = barcodeScanDTO; - this.sendOnULCloseRequested(); + if (enableSSCCRead) { + this.internalNextUlBarcode = barcodeScanDTO; + this.sendOnULCloseRequested(); + } return; } @@ -352,7 +355,7 @@ public class DialogInputQuantityV2ViewModel { return this; } - public DialogInputQuantityV2ViewModel setmPartitaMagList(List mPartitaMagList) { + public DialogInputQuantityV2ViewModel setPartitaMagList(List mPartitaMagList) { this.mPartitaMagList = mPartitaMagList; return this; } @@ -372,6 +375,11 @@ public class DialogInputQuantityV2ViewModel { return this; } + public DialogInputQuantityV2ViewModel setEnableSSCCRead(boolean enableSSCCRead) { + this.enableSSCCRead = enableSSCCRead; + return this; + } + public boolean canPartitaMagBeChanged() { return canPartitaMagBeChanged; } From 296675f0b01d4afa5f30d998b1f6b11188a8cce4 Mon Sep 17 00:00:00 2001 From: GiuseppeS Date: Mon, 31 Mar 2025 10:35:39 +0200 Subject: [PATCH 19/19] -> v1.46.00 (488) --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 44908fdd..c6a8c555 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,8 +10,8 @@ apply plugin: 'com.google.gms.google-services' android { - def appVersionCode = 487 - def appVersionName = '1.45.05' + def appVersionCode = 488 + def appVersionName = '1.46.00' signingConfigs { release {