-
Notifications
You must be signed in to change notification settings - Fork 21
/
SalesConfigActivityFragment.java
1482 lines (1315 loc) · 69.3 KB
/
SalesConfigActivityFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018 Kaushik N. Sanji
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kaushiknsanji.storeapp.ui.inventory.config;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.recyclerview.extensions.ListAdapter;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.kaushiknsanji.storeapp.R;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductAttribute;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductImage;
import com.example.kaushiknsanji.storeapp.data.local.models.ProductSupplierSales;
import com.example.kaushiknsanji.storeapp.ui.BasePresenter;
import com.example.kaushiknsanji.storeapp.ui.BaseView;
import com.example.kaushiknsanji.storeapp.ui.common.ProgressDialogFragment;
import com.example.kaushiknsanji.storeapp.ui.products.config.ProductConfigContract;
import com.example.kaushiknsanji.storeapp.ui.suppliers.config.SupplierConfigActivity;
import com.example.kaushiknsanji.storeapp.utils.OrientationUtility;
import com.example.kaushiknsanji.storeapp.utils.SnackbarUtility;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
/**
* Content Fragment of {@link SalesConfigActivity} that inflates the layout 'R.layout.fragment_sales_config'
* to display the configuration details of the Product and its Suppliers with their Sales inventory.
* The Sales Inventory of the Product can be updated across its listed Suppliers and
* procurement request can also be placed with any Supplier listed. This implements the
* {@link SalesConfigContract.View} on the lines of Model-View-Presenter architecture.
*
* @author Kaushik N Sanji
*/
public class SalesConfigActivityFragment extends Fragment implements SalesConfigContract.View, View.OnClickListener {
//Constant used for logs
private static final String LOG_TAG = SalesConfigActivityFragment.class.getSimpleName();
//The Bundle argument constant of this Fragment
private static final String ARGUMENT_INT_PRODUCT_ID = "argument.PRODUCT_ID";
//Bundle constants for persisting the data throughout System config changes
private static final String BUNDLE_PRODUCT_NAME_KEY = "SalesConfig.ProductName";
private static final String BUNDLE_PRODUCT_SKU_KEY = "SalesConfig.ProductSku";
private static final String BUNDLE_PRODUCT_DESCRIPTION_KEY = "SalesConfig.ProductDescription";
private static final String BUNDLE_PRODUCT_CATEGORY_KEY = "SalesConfig.ProductCategory";
private static final String BUNDLE_PRODUCT_ORIGINAL_TOTAL_AVAIL_QTY_INT_KEY = "SalesConfig.OriginalTotalAvailableQuantity";
private static final String BUNDLE_PRODUCT_IMAGES_LIST_KEY = "SalesConfig.ProductImages";
private static final String BUNDLE_PRODUCT_ATTRS_LIST_KEY = "SalesConfig.ProductAttributes";
private static final String BUNDLE_PRODUCT_SUPPLIERS_LIST_KEY = "SalesConfig.ProductSuppliers";
private static final String BUNDLE_PRODUCT_RESTORED_BOOL_KEY = "SalesConfig.IsProductRestored";
private static final String BUNDLE_SUPPLIERS_RESTORED_BOOL_KEY = "SalesConfig.AreSuppliersRestored";
//The Presenter for this View
private SalesConfigContract.Presenter mPresenter;
//Stores the instance of the View components required
private TextView mTextViewProductName;
private TextView mTextViewProductSku;
private TextView mTextViewProductDesc;
private TextView mTextViewProductCategory;
private TextView mTextViewProductAvailableQuantity;
private TableLayout mTableLayoutProductAttrs;
private RecyclerView mRecyclerViewProductSuppliers;
//RecyclerView Adapter for Product's Suppliers
private ProductSuppliersAdapter mProductSuppliersAdapter;
//Stores the Product ID, retrieved from Bundle arguments passed
private int mProductId;
//Stores the Product Attributes list of the Product
private ArrayList<ProductAttribute> mProductAttributes;
//Stores the URI details of the Product Images
private ArrayList<ProductImage> mProductImages;
//Stores the state of Product details restored,
//to prevent updating the fields every time during System config change
private boolean mIsProductRestored;
//Stores the state of Supplier details restored,
//to prevent updating the fields every time during System config change
private boolean mAreSuppliersRestored;
//Stores the value of the Original Total Available Quantity of the Product
private int mOldTotalAvailableQuantity;
/**
* The {@link AlertDialog} Click Listener for the Product Delete Menu.
*/
private DialogInterface.OnClickListener mProductDeleteDialogOnClickListener = new DialogInterface.OnClickListener() {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog the dialog that received the click
* @param which the button that was clicked (ex.
* {@link DialogInterface#BUTTON_POSITIVE}) or the position
*/
@Override
public void onClick(DialogInterface dialog, int which) {
//Taking action based on the button clicked
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//For "Yes" Button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
//Dispatch to the Presenter to delete the Product
mPresenter.deleteProduct();
break;
case DialogInterface.BUTTON_NEGATIVE:
//For "No" Button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
break;
}
}
};
/**
* The {@link AlertDialog} Click Listener for the Unsaved changes dialog
*/
private DialogInterface.OnClickListener mUnsavedDialogOnClickListener = new DialogInterface.OnClickListener() {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog the dialog that received the click
* @param which the button that was clicked (ex.
* {@link DialogInterface#BUTTON_POSITIVE}) or the position
*/
@Override
public void onClick(DialogInterface dialog, int which) {
//Taking action based on the button clicked
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//For "Save" button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
//Start saving the Product Sales
saveProductSales();
break;
case DialogInterface.BUTTON_NEGATIVE:
//For "Discard" button
//Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
//Dispatch to the Presenter to finish the Activity without saving changes
mPresenter.finishActivity();
break;
case DialogInterface.BUTTON_NEUTRAL:
//For "Keep Editing" button
//Just Dismiss the dialog
dialog.dismiss();
//Unlock orientation
OrientationUtility.unlockScreenOrientation(requireActivity());
break;
}
}
};
/**
* Mandatory Empty Constructor of {@link SalesConfigActivityFragment}
* This is required by the {@link android.support.v4.app.FragmentManager} to instantiate
* the fragment (e.g. upon screen orientation changes).
*/
public SalesConfigActivityFragment() {
}
/**
* Static Factory Constructor that creates an instance of {@link SalesConfigActivityFragment}
* using the provided {@code productId}
*
* @param productId The integer value of the Product Id of an existing Product;
* @return Instance of {@link SalesConfigActivityFragment}
*/
public static SalesConfigActivityFragment newInstance(int productId) {
//Saving the arguments passed, in a Bundle
Bundle args = new Bundle(1);
args.putInt(ARGUMENT_INT_PRODUCT_ID, productId);
//Instantiating the Fragment
SalesConfigActivityFragment fragment = new SalesConfigActivityFragment();
//Passing the Bundle as Arguments to this Fragment
fragment.setArguments(args);
//Returning the fragment instance
return fragment;
}
/**
* Called to do initial creation of a fragment.
*
* @param savedInstanceState If the fragment is being re-created from
* a previous saved state, this is the state.
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Indicating that this fragment has menu options to show
setHasOptionsMenu(true);
}
/**
* Called to have the fragment instantiate its user interface view.
* This is optional, and non-graphical fragments can return null (which
* is the default implementation). This will be called between
* {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
* <p>
* <p>If you return a View from here, you will later be called in
* {@link #onDestroyView} when the view is being released.
*
* @param inflater The LayoutInflater object that can be used to inflate
* any views in the fragment,
* @param container If non-null, this is the parent view that the fragment's
* UI should be attached to. The fragment should not add the view itself,
* but this can be used to generate the LayoutParams of the view.
* @param savedInstanceState If non-null, this fragment is being re-constructed
* from a previous saved state as given here.
* @return Returns the View for the fragment's UI ('R.layout.fragment_sales_config')
*/
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout 'R.layout.fragment_sales_config' for this fragment
//Passing false as we are attaching the layout ourselves
View rootView = inflater.inflate(R.layout.fragment_sales_config, container, false);
//Finding the views to initialize
mTextViewProductName = rootView.findViewById(R.id.text_sales_config_product_name);
mTextViewProductSku = rootView.findViewById(R.id.text_sales_config_product_sku);
mTextViewProductDesc = rootView.findViewById(R.id.text_sales_config_product_desc);
mTextViewProductCategory = rootView.findViewById(R.id.text_sales_config_product_category);
mTextViewProductAvailableQuantity = rootView.findViewById(R.id.text_sales_config_total_available_quantity);
mTableLayoutProductAttrs = rootView.findViewById(R.id.tablelayout_sales_config_product_attrs);
mRecyclerViewProductSuppliers = rootView.findViewById(R.id.recyclerview_sales_config_suppliers);
//Registering Click listener on Product Edit Image Button
rootView.findViewById(R.id.imgbtn_sales_config_product_edit).setOnClickListener(this);
//Retrieving the Product Id and Supplier Id from the Bundle
Bundle arguments = getArguments();
if (arguments != null) {
mProductId = arguments.getInt(ARGUMENT_INT_PRODUCT_ID, ProductConfigContract.NEW_PRODUCT_INT);
}
//Initialize RecyclerView for Product's Suppliers
setupProductSuppliersRecyclerView();
//Returning the prepared layout
return rootView;
}
/**
* Called when the fragment is visible to the user and actively running.
* This is generally
* tied to {@link android.support.v4.app.FragmentActivity#onResume() Activity.onResume} of the containing
* Activity's lifecycle.
*/
@Override
public void onResume() {
super.onResume();
if (mProductId == ProductConfigContract.NEW_PRODUCT_INT) {
//When the Product Id is not an existing Id, then finish the Activity
mPresenter.doCancel();
} else {
//When the Product Id is valid, start downloading the required data
mPresenter.start();
}
}
/**
* Called when the fragment's activity has been created and this
* fragment's view hierarchy instantiated. It can be used to do final
* initialization once these pieces are in place, such as retrieving
* views or restoring state. It is also useful for fragments that use
* {@link #setRetainInstance(boolean)} to retain their instance,
* as this callback tells the fragment when it is fully associated with
* the new activity instance. This is called after {@link #onCreateView}
* and before {@link #onViewStateRestored(Bundle)}.
*
* @param savedInstanceState If the fragment is being re-created from
* a previous saved state, this is the state.
*/
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//On Subsequent launch
//Restoring Product Name
mPresenter.updateProductName(savedInstanceState.getString(BUNDLE_PRODUCT_NAME_KEY));
//Restoring Product SKU
mPresenter.updateProductSku(savedInstanceState.getString(BUNDLE_PRODUCT_SKU_KEY));
//Restoring Product Description
mPresenter.updateProductDescription(savedInstanceState.getString(BUNDLE_PRODUCT_DESCRIPTION_KEY));
//Restoring Product Category
mPresenter.updateProductCategory(savedInstanceState.getString(BUNDLE_PRODUCT_CATEGORY_KEY));
//Restoring Product Images
mPresenter.updateProductImage(savedInstanceState.getParcelableArrayList(BUNDLE_PRODUCT_IMAGES_LIST_KEY));
//Restoring Product Attributes
mPresenter.updateProductAttributes(savedInstanceState.getParcelableArrayList(BUNDLE_PRODUCT_ATTRS_LIST_KEY));
//Restoring Product's Suppliers and Sales information
mPresenter.updateProductSupplierSalesList(savedInstanceState.getParcelableArrayList(BUNDLE_PRODUCT_SUPPLIERS_LIST_KEY));
//Restoring the Original Total Available Quantity after loading the Sales information
//to overwrite with the corrected value
mPresenter.updateAndSyncOldTotalAvailability(savedInstanceState.getInt(BUNDLE_PRODUCT_ORIGINAL_TOTAL_AVAIL_QTY_INT_KEY));
//Restoring the state of Product data restored
mPresenter.updateAndSyncProductState(savedInstanceState.getBoolean(BUNDLE_PRODUCT_RESTORED_BOOL_KEY, false));
//Restoring the state of Suppliers data restored
mPresenter.updateAndSyncSuppliersState(savedInstanceState.getBoolean(BUNDLE_SUPPLIERS_RESTORED_BOOL_KEY, false));
}
}
/**
* Called to ask the fragment to save its current dynamic state, so it
* can later be reconstructed in a new instance of its process is
* restarted. If a new instance of the fragment later needs to be
* created, the data you place in the Bundle here will be available
* in the Bundle given to {@link #onCreate(Bundle)},
* {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and
* {@link #onActivityCreated(Bundle)}.
* <p>
* <p>This corresponds to {@link android.support.v4.app.FragmentActivity#onSaveInstanceState(Bundle)
* Activity.onSaveInstanceState(Bundle)} and most of the discussion there
* applies here as well.
*
* @param outState Bundle in which to place your saved state.
*/
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
//Trigger Focus Loss to capture any value partially entered
mPresenter.triggerFocusLost();
//Saving the state
outState.putString(BUNDLE_PRODUCT_NAME_KEY, mTextViewProductName.getText().toString());
outState.putString(BUNDLE_PRODUCT_SKU_KEY, mTextViewProductSku.getText().toString());
outState.putString(BUNDLE_PRODUCT_DESCRIPTION_KEY, mTextViewProductDesc.getText().toString());
outState.putString(BUNDLE_PRODUCT_CATEGORY_KEY, mTextViewProductCategory.getText().toString());
outState.putInt(BUNDLE_PRODUCT_ORIGINAL_TOTAL_AVAIL_QTY_INT_KEY, mOldTotalAvailableQuantity);
outState.putParcelableArrayList(BUNDLE_PRODUCT_IMAGES_LIST_KEY, mProductImages);
outState.putParcelableArrayList(BUNDLE_PRODUCT_ATTRS_LIST_KEY, mProductAttributes);
outState.putParcelableArrayList(BUNDLE_PRODUCT_SUPPLIERS_LIST_KEY, mProductSuppliersAdapter.getProductSupplierSalesList());
outState.putBoolean(BUNDLE_PRODUCT_RESTORED_BOOL_KEY, mIsProductRestored);
outState.putBoolean(BUNDLE_SUPPLIERS_RESTORED_BOOL_KEY, mAreSuppliersRestored);
}
/**
* Method that registers the Presenter {@code presenter} with the View implementing {@link BaseView}
*
* @param presenter Presenter instance implementing the {@link BasePresenter}
*/
@Override
public void setPresenter(SalesConfigContract.Presenter presenter) {
mPresenter = presenter;
}
/**
* Initialize the contents of the Fragment host's standard options menu. You
* should place your menu items in to <var>menu</var>.
*
* @param menu The options menu in which you place your items.
* @param inflater The LayoutInflater object that can be used to inflate the Menu options
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Inflating the Menu options from 'R.menu.menu_fragment_sales_config'
inflater.inflate(R.menu.menu_fragment_sales_config, menu);
}
/**
* This hook is called whenever an item in your options menu is selected.
* The default implementation simply returns false to have the normal
* processing happen.
*
* @param item The menu item that was selected.
* @return boolean Return false to allow normal menu processing to
* proceed, true to consume it here.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handling based on the Menu item selected
switch (item.getItemId()) {
case R.id.action_delete:
//On Click of Delete Menu
//Delegating to the Presenter to show the re-confirmation dialog
mPresenter.showDeleteProductDialog();
return true;
case R.id.action_save:
//On Click of Save Menu
//Saving the Product Sales information
saveProductSales();
return true;
default:
//On other cases, do the default menu handling
return super.onOptionsItemSelected(item);
}
}
/**
* Method that grabs the data from the Views and dispatches to the Presenter
* to initiate the Save process.
*/
private void saveProductSales() {
//Delegating to the Presenter to trigger focus loss on listener registered Views,
//in order to persist their data
mPresenter.triggerFocusLost();
//Delegating to the Presenter to initiate the Save process
mPresenter.onSave(mProductSuppliersAdapter.getProductSupplierSalesList());
}
/**
* Method that initializes the RecyclerView 'R.id.recyclerview_sales_config_suppliers' and its Adapter.
*/
private void setupProductSuppliersRecyclerView() {
//Creating a Vertical Linear Layout Manager with default layout order
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext(),
LinearLayoutManager.VERTICAL, false);
//Setting the Layout Manager to use
mRecyclerViewProductSuppliers.setLayoutManager(linearLayoutManager);
//Initializing the Adapter
mProductSuppliersAdapter = new ProductSuppliersAdapter(new ProductSupplierItemUserActionsListener());
//Setting the Adapter on RecyclerView
mRecyclerViewProductSuppliers.setAdapter(mProductSuppliersAdapter);
//Attaching the ItemTouchHelper for Swipe delete
mProductSuppliersAdapter.getItemTouchHelper().attachToRecyclerView(mRecyclerViewProductSuppliers);
}
/**
* Method invoked to keep the state of "Product details restored", in sync with the Presenter.
*
* @param isProductRestored Boolean that indicates the state of Product data restored.
* <b>TRUE</b> if it had been restored; <b>FALSE</b> otherwise.
*/
@Override
public void syncProductState(boolean isProductRestored) {
//Saving the state
mIsProductRestored = isProductRestored;
}
/**
* Method invoked to keep the state of "Suppliers data restored", in sync with the Presenter.
*
* @param areSuppliersRestored Boolean that indicates the state of Suppliers data restored.
* <b>TRUE</b> if it had been restored; <b>FALSE</b> otherwise.
*/
@Override
public void syncSuppliersState(boolean areSuppliersRestored) {
//Saving the state
mAreSuppliersRestored = areSuppliersRestored;
}
/**
* Method invoked to keep the original Total available quantity of the Product,
* in sync with the Presenter.
*
* @param oldTotalAvailableQuantity Integer value of the original Total available
* quantity of the Product.
*/
@Override
public void syncOldTotalAvailability(int oldTotalAvailableQuantity) {
//Saving the original Total available quantity
mOldTotalAvailableQuantity = oldTotalAvailableQuantity;
}
/**
* Method that displays the Progress indicator
*
* @param statusTextId String resource for the status of the Progress to be shown.
*/
@Override
public void showProgressIndicator(int statusTextId) {
ProgressDialogFragment.showDialog(getChildFragmentManager(), getString(statusTextId));
}
/**
* Method that hides the Progress indicator
*/
@Override
public void hideProgressIndicator() {
ProgressDialogFragment.dismissDialog(getChildFragmentManager());
}
/**
* Method invoked when an error is encountered during Product/Suppliers information
* retrieval or save process.
*
* @param messageId String Resource of the error Message to be displayed
* @param args Variable number of arguments to replace the format specifiers
*/
@Override
public void showError(int messageId, @Nullable Object... args) {
if (getView() != null) {
//When we have the root view
//Evaluating the message to be shown
String messageToBeShown;
if (args != null && args.length > 0) {
//For the String Resource with args
messageToBeShown = getString(messageId, args);
} else {
//For the String Resource without args
messageToBeShown = getString(messageId);
}
if (!TextUtils.isEmpty(messageToBeShown)) {
//Displaying the Snackbar message of indefinite time length
//when we have the error message to be shown
new SnackbarUtility(Snackbar.make(getView(), messageToBeShown, Snackbar.LENGTH_INDEFINITE))
.revealCompleteMessage() //Removes the limit on max lines
.setDismissAction(R.string.snackbar_action_ok) //For the Dismiss "OK" action
.showSnack();
}
}
}
/**
* Method that updates the Product Name {@code productName} to the View.
*
* @param productName The Product Name of the Product.
*/
@Override
public void updateProductName(String productName) {
//Setting the Product Name
mTextViewProductName.setText(productName);
}
/**
* Method that updates the Product SKU {@code productSku} to the View.
*
* @param productSku The Product SKU of the Product.
*/
@Override
public void updateProductSku(String productSku) {
//Setting the Product SKU
mTextViewProductSku.setText(productSku);
//Setting Barcode typeface for the SKU
mTextViewProductSku.setTypeface(ResourcesCompat.getFont(requireContext(), R.font.libre_barcode_128_text_regular));
}
/**
* Method that updates the Product Category {@code productCategory} to the View.
*
* @param productCategory The Product Category of the Product.
*/
@Override
public void updateProductCategory(String productCategory) {
mTextViewProductCategory.setText(productCategory);
}
/**
* Method that updates the Product Description {@code description} to the View.
*
* @param description The description of the Product.
*/
@Override
public void updateProductDescription(String description) {
mTextViewProductDesc.setText(description);
}
/**
* Method that updates the List of Product Images {@code productImages} to the View
*
* @param productImages The List of {@link ProductImage} of a Product.
*/
@Override
public void updateProductImages(ArrayList<ProductImage> productImages) {
//Saving the list of ProductImages
mProductImages = productImages;
}
/**
* Method that updates the List of Product Attributes {@code productAttributes} to the View.
*
* @param productAttributes The List of {@link ProductAttribute} of a Product.
*/
@Override
public void updateProductAttributes(ArrayList<ProductAttribute> productAttributes) {
//Saving the Product Attributes data
mProductAttributes = productAttributes;
//Set Stretch all Table Columns
mTableLayoutProductAttrs.setStretchAllColumns(true);
//Removing all the Child Views if any
mTableLayoutProductAttrs.removeAllViewsInLayout();
//Retrieving the Number of Product Attributes
int noOfProductAttrs = mProductAttributes.size();
//Iterating over the list to build a Table for Product Attributes to be shown
for (int index = 0; index < noOfProductAttrs; index++) {
//Retrieving the current Product Attribute at the index
ProductAttribute productAttribute = mProductAttributes.get(index);
//Creating a new TableRow to show the entry
TableRow tableRow = new TableRow(requireContext());
//Setting TableRow LayoutParams
TableLayout.LayoutParams tableRowLayoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
//Adding the New Row to the TableLayout
mTableLayoutProductAttrs.addView(tableRow, tableRowLayoutParams);
//Setting background for the table row with different color shape for odd and even rows
if (index % 2 == 0) {
//When even
tableRow.setBackgroundResource(R.drawable.shape_sales_config_product_attrs_table_bg_even_row);
} else {
//When odd
tableRow.setBackgroundResource(R.drawable.shape_sales_config_product_attrs_table_bg_odd_row);
}
//Setting the LayoutParams for Table Cell TextView
TableRow.LayoutParams textViewCellLayoutParams = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT);
//Inflating a TextView with Style to hold the Attribute Name
TextView textViewAttrName = (TextView) LayoutInflater.from(requireContext()).inflate(R.layout.layout_sales_config_product_attrs_table_cell_name, tableRow, false);
//Setting the Attribute Name on TextView
textViewAttrName.setText(productAttribute.getAttributeName());
//Adding Attribute Name TextView to the TableRow
tableRow.addView(textViewAttrName, textViewCellLayoutParams);
//Inflating a TextView with Style to hold the Attribute Value
TextView textViewAttrValue = (TextView) LayoutInflater.from(requireContext()).inflate(R.layout.layout_sales_config_product_attrs_table_cell_value, tableRow, false);
//Setting the Attribute Value on TextView
textViewAttrValue.setText(productAttribute.getAttributeValue());
//Adding Attribute Value TextView to the TableRow
tableRow.addView(textViewAttrValue, textViewCellLayoutParams);
}
}
/**
* Method that updates the Adapter of the RecyclerView List of Product's Suppliers with
* Sales information.
*
* @param productSupplierSalesList List of {@link ProductSupplierSales} containing
* the Product's Suppliers with Sales information.
*/
@Override
public void loadProductSuppliersData(ArrayList<ProductSupplierSales> productSupplierSalesList) {
mProductSuppliersAdapter.submitList(productSupplierSalesList);
}
/**
* Method invoked when the total available quantity of the Product has been recalculated.
*
* @param totalAvailableQuantity Integer value of the Total Available quantity of the Product.
*/
@Override
public void updateAvailability(int totalAvailableQuantity) {
//Set the total available quantity value
mTextViewProductAvailableQuantity.setText(String.valueOf(totalAvailableQuantity));
//Set the Text Color
mTextViewProductAvailableQuantity.setTextColor(ContextCompat.getColor(requireContext(), android.R.color.holo_green_dark));
}
/**
* Method invoked to show the "Out Of Stock!" alert when the Total Available quantity
* of the Product is 0.
*/
@Override
public void showOutOfStockAlert() {
//Set the Out of Stock message
mTextViewProductAvailableQuantity.setText(getString(R.string.sales_list_item_out_of_stock));
//Set the Text Color
mTextViewProductAvailableQuantity.setTextColor(ContextCompat.getColor(requireContext(), R.color.salesListItemOutOfStockColor));
}
/**
* Method invoked when the user swipes left/right any Item View of the Product's Suppliers
* in order to remove it from the list. This should show a Snackbar with Action UNDO.
*
* @param supplierCode The Supplier Code of the Supplier being swiped out/unlinked.
*/
@Override
public void showProductSupplierSwiped(String supplierCode) {
if (getView() != null) {
new SnackbarUtility(Snackbar.make(getView(),
getString(R.string.sales_config_supplier_swipe_action_success,
supplierCode), Snackbar.LENGTH_LONG))
.revealCompleteMessage()
.setAction(R.string.snackbar_action_undo, (view) -> {
//Try and Restore the Adapter data when UNDO is clicked
if (mProductSuppliersAdapter.restoreLastRemovedProductSupplierSales()) {
//On Success, show a Snackbar message
Snackbar.make(getView(),
getString(R.string.sales_config_supplier_swipe_action_undo_success, supplierCode),
Snackbar.LENGTH_LONG).show();
}
})
.showSnack();
}
}
/**
* Method that displays a message on Success of Updating a Product.
*
* @param productSku String containing the SKU of the Product that was updated successfully.
*/
@Override
public void showUpdateProductSuccess(String productSku) {
if (getView() != null) {
Snackbar.make(getView(), getString(R.string.product_list_item_update_success, productSku), Snackbar.LENGTH_LONG).show();
}
}
/**
* Method that displays a message on Success of updating an Existing Supplier.
*
* @param supplierCode String containing the code of the Supplier that was updated successfully.
*/
@Override
public void showUpdateSupplierSuccess(String supplierCode) {
if (getView() != null) {
Snackbar.make(getView(), getString(R.string.supplier_list_item_update_success, supplierCode), Snackbar.LENGTH_LONG).show();
}
}
/**
* Method that displays a message on Success of Deleting an Existing Supplier.
*
* @param supplierCode String containing the code of the Supplier that was deleted successfully.
*/
@Override
public void showDeleteSupplierSuccess(String supplierCode) {
if (getView() != null) {
Snackbar.make(getView(), getString(R.string.supplier_list_item_delete_success, supplierCode), Snackbar.LENGTH_LONG).show();
}
}
/**
* Method invoked before save operation or screen orientation change to persist
* any data held by the view that had focus and its listener registered.
* This clears the focus held by the view to trigger the listener, causing to persist any unsaved data.
*/
@Override
public void triggerFocusLost() {
//Clearing focus in the last registered view in Product Suppliers Adapter
if (mProductSuppliersAdapter != null) {
mProductSuppliersAdapter.triggerFocusLost();
}
}
/**
* Method invoked by the Presenter to display the Discard dialog,
* requesting the User whether to keep editing/discard the changes
*/
@Override
public void showDiscardDialog() {
//Creating an AlertDialog with a message, and listeners for the positive, neutral and negative buttons
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
//Set the Message
builder.setMessage(R.string.sales_config_unsaved_changes_dialog_message);
//Set the Positive Button and its listener
builder.setPositiveButton(R.string.sales_config_unsaved_changes_dialog_positive_text, mUnsavedDialogOnClickListener);
//Set the Negative Button and its listener
builder.setNegativeButton(R.string.sales_config_unsaved_changes_dialog_negative_text, mUnsavedDialogOnClickListener);
//Set the Neutral Button and its listener
builder.setNeutralButton(R.string.sales_config_unsaved_changes_dialog_neutral_text, mUnsavedDialogOnClickListener);
//Lock the Orientation
OrientationUtility.lockCurrentScreenOrientation(requireActivity());
//Create and display the AlertDialog
builder.create().show();
}
/**
* Method invoked when the user clicks on the Delete Menu Action to delete the Product.
* This should launch a Dialog for the user to reconfirm the request before proceeding
* with the Delete Action.
*/
@Override
public void showDeleteProductDialog() {
//Creating an AlertDialog with a message, and listeners for the positive and negative buttons
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
//Set the Message
builder.setMessage(R.string.sales_config_delete_product_confirm_dialog_message);
//Set the Positive Button and its listener
builder.setPositiveButton(android.R.string.yes, mProductDeleteDialogOnClickListener);
//Set the Negative Button and its listener
builder.setNegativeButton(android.R.string.no, mProductDeleteDialogOnClickListener);
//Lock the Orientation
OrientationUtility.lockCurrentScreenOrientation(requireActivity());
//Create and display the AlertDialog
builder.create().show();
}
/**
* Called when a view has been clicked.
*
* @param view The view that was clicked.
*/
@Override
public void onClick(View view) {
//Taking action based on the Id of the View clicked
switch (view.getId()) {
case R.id.imgbtn_sales_config_product_edit:
//For the Product Edit ImageButton
//Delegating to the Presenter to launch the ProductConfigActivity to edit the Product
mPresenter.editProduct(mProductId);
break;
}
}
/**
* {@link ListAdapter} class for the RecyclerView to load the list of Suppliers with their
* Selling Price and Product Availability {@link ProductSupplierSales} to be displayed.
*/
private static class ProductSuppliersAdapter extends ListAdapter<ProductSupplierSales, ProductSuppliersAdapter.ViewHolder> {
/**
* {@link DiffUtil.ItemCallback} for calculating the difference between two
* {@link ProductSupplierSales} objects.
*/
private static DiffUtil.ItemCallback<ProductSupplierSales> DIFF_SUPPLIERS
= new DiffUtil.ItemCallback<ProductSupplierSales>() {
/**
* Called to check whether two objects represent the same item.
* <p>
* For example, if your items have unique ids, this method should check their id equality.
*
* @param oldItem The item in the old list.
* @param newItem The item in the new list.
* @return True if the two items represent the same object or false if they are different.
*
* @see DiffUtil.Callback#areItemsTheSame(int, int)
*/
@Override
public boolean areItemsTheSame(ProductSupplierSales oldItem, ProductSupplierSales newItem) {
//Returning the comparison of Product and Supplier's Id
return (oldItem.getItemId() == newItem.getItemId()) && (oldItem.getSupplierId() == newItem.getSupplierId());
}
/**
* Called to check whether two items have the same data.
* <p>
* This information is used to detect if the contents of an item have changed.
* <p>
* This method to check equality instead of {@link Object#equals(Object)} so that you can
* change its behavior depending on your UI.
* <p>
* For example, if you are using DiffUtil with a
* {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter}, you should
* return whether the items' visual representations are the same.
* <p>
* This method is called only if {@link #areItemsTheSame(ProductSupplierSales, ProductSupplierSales)} returns {@code true} for
* these items.
*
* @param oldItem The item in the old list.
* @param newItem The item in the new list.
* @return True if the contents of the items are the same or false if they are different.
*
* @see DiffUtil.Callback#areContentsTheSame(int, int)
*/
@Override
public boolean areContentsTheSame(ProductSupplierSales oldItem, ProductSupplierSales newItem) {
//Returning the result of equals
return oldItem.equals(newItem);
}
};
//The Data of this Adapter that stores the Supplier details with Selling Price
//and Product Availability
private ArrayList<ProductSupplierSales> mProductSupplierSalesList;
//Stores the EditText View that had last acquired focus
private View mLastFocusedView;
//Stores last removed data if needs to be undone
private ProductSupplierSales mLastRemovedProductSupplierSales;
//Listener for User Actions on Product's List of Suppliers
private ProductSuppliersUserActionsListener mActionsListener;
/**
* Constructor of {@link ProductSuppliersAdapter}
*
* @param userActionsListener Instance of {@link ProductSuppliersUserActionsListener}
* to receive event callbacks for User Actions on Item Views
*/
ProductSuppliersAdapter(ProductSuppliersUserActionsListener userActionsListener) {
super(DIFF_SUPPLIERS);
//Registering the User Actions Listener
mActionsListener = userActionsListener;
}
/**
* Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
* an item.
*
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
* @return A new ViewHolder that holds a View of the given view type.
*/
@NonNull
@Override
public ProductSuppliersAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//Inflating the item layout 'R.layout.item_sales_config_supplier'
//Passing False since we are attaching the layout ourselves
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sales_config_supplier, parent, false);
//Returning the Instance of ViewHolder for the inflated Item View
return new ViewHolder(itemView);
}
/**
* Called by RecyclerView to display the data at the specified position. This method should
* update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
* position.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(@NonNull ProductSuppliersAdapter.ViewHolder holder, int position) {
//Get the data at the position
ProductSupplierSales productSupplierSales = getItem(position);
//Binding the data at the position
holder.bind(productSupplierSales);
}
/**
* Submits a new list to be diffed, and displayed.
* <p>
* If a list is already being displayed, a diff will be computed on a background thread, which
* will dispatch Adapter.notifyItem events on the main thread.
*
* @param submittedList The new list to be displayed.
*/
@Override
public void submitList(List<ProductSupplierSales> submittedList) {
//Restoring the quantities from the current list if present
if (mProductSupplierSalesList != null && mProductSupplierSalesList.size() > 0) {
//When we had some data
//Creating a SparseArray of Supplier Id with their Quantities for lookup
SparseIntArray suppliersQuantityArray = new SparseIntArray();