StocktakeModule.xaml.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using InABox.Mobile;
  13. using Syncfusion.SfImageEditor.XForms;
  14. using Xamarin.CommunityToolkit.Extensions;
  15. using Xamarin.CommunityToolkit.UI.Views;
  16. using Xamarin.Essentials;
  17. using Xamarin.Forms;
  18. using Xamarin.Forms.Xaml;
  19. using XF.Material.Forms.UI.Dialogs;
  20. using Location = InABox.Core.Location;
  21. using LogType = InABox.Core.LogType;
  22. using TextAlignment = Xamarin.Forms.TextAlignment;
  23. namespace PRS.Mobile
  24. {
  25. public class StockLocationStatusConverter : AbstractConverter<StockLocationShell, string>
  26. {
  27. protected override string? Convert(StockLocationShell? value, object? parameter = null)
  28. {
  29. return value != null
  30. ? $"{value.LocationType}, {(value.Active ? "Active" : "Inactive")}"
  31. : "";
  32. }
  33. }
  34. public class StockHoldingShellColorConverter : AbstractConverter<StockHoldingShell, Color>
  35. {
  36. public DateTime CurrentStockTake { get; set; } = DateTime.MinValue;
  37. protected override Color Convert(StockHoldingShell? value, object? parameter = null)
  38. {
  39. var count = value?.Transactions.Aggregate(0, (agg, trans) => agg += 1) ?? 0;
  40. var prevcounted = !CurrentStockTake.IsEmpty() && (value?.LastStocktake ?? DateTime.MinValue) >= CurrentStockTake;
  41. return count > 0 || prevcounted
  42. ? Color.LightGreen
  43. : Color.Orange;
  44. }
  45. }
  46. public class StockHoldingShellAdjustmentConverter : AbstractConverter<StockHoldingShell, String>
  47. {
  48. public DateTime CurrentStockTake { get; set; } = DateTime.MinValue;
  49. protected override String Convert(StockHoldingShell? value, object? parameter = null)
  50. {
  51. var basevalue = value?.Units ?? 0.0d;
  52. var count = value?.Transactions.Aggregate(0, (agg, trans) => agg += 1) ?? 0;
  53. var quantity = value?.Transactions.Aggregate(0.0d, (agg, trans) => agg += trans.Quantity) ?? 0.0d;
  54. var prevcounted = !CurrentStockTake.IsEmpty() && (value?.LastStocktake ?? DateTime.MinValue) >= CurrentStockTake;
  55. return count == 0
  56. ? prevcounted
  57. ? "ALREADY\nCOUNTED"
  58. : "NOT\nCHECKED"
  59. : quantity.IsEffectivelyEqual(basevalue)
  60. ? "CORRECT\nQUANTITY"
  61. : quantity < basevalue
  62. ? $"{basevalue-quantity:F2}\nSHORT"
  63. : $"{quantity-basevalue:F2}\nOVER";
  64. }
  65. }
  66. public class StockHoldingShellBalanceConverter : AbstractConverter<StockHoldingShell, String>
  67. {
  68. protected override String Convert(StockHoldingShell? value, object? parameter = null)
  69. {
  70. var basevalue = value?.Units ?? 0.0d;
  71. var count = value?.Transactions.Aggregate(0, (agg, trans) => agg += 1) ?? 0;
  72. var quantity = value?.Transactions.Aggregate(0.0d, (agg, trans) => agg += trans.Quantity) ?? 0.0d;
  73. return count == 0 || quantity.IsEffectivelyEqual(basevalue)
  74. ? $"{basevalue:F2}"
  75. : $"{quantity:F2}";
  76. }
  77. }
  78. [XamlCompilation(XamlCompilationOptions.Compile)]
  79. public partial class StocktakeModule : MobilePage
  80. {
  81. private bool _isNewStockTake = true;
  82. public StocktakeModule(Guid locationid)
  83. {
  84. InitializeComponent();
  85. if (locationid != Guid.Empty)
  86. {
  87. App.Data.StockLocations.Refresh(false);
  88. var location = App.Data.StockLocations.FirstOrDefault(x => x.ID == locationid);
  89. ViewModel.Location = location ?? new StockLocationShell();
  90. Title = $"Stock Take: {ViewModel.Location.Description}";
  91. }
  92. else
  93. ViewModel.Location = new StockLocationShell();
  94. _isNewStockTake = ViewModel.Location.CurrentStocktake.IsEmpty();
  95. _stockHoldingShellColorConverter.CurrentStockTake = ViewModel.Location.CurrentStocktake;
  96. _stockHoldingShellAdjustmentConverter.CurrentStockTake = ViewModel.Location.CurrentStocktake;
  97. }
  98. protected override async Task<bool> OnBackButtonClicked()
  99. {
  100. bool result = true;
  101. if (ViewModel.Location.ID != Guid.Empty && ViewModel.Transactions.Any())
  102. result = await DisplayAlert("Stocktake in progress",
  103. "This Stocktake is not complete.\nAre you sure you wish to close it?", "No", "Yes") == false;
  104. if (result && _isNewStockTake && !ViewModel.Location.CurrentStocktake.IsEmpty())
  105. {
  106. ViewModel.Location.CurrentStocktake = DateTime.MinValue;
  107. ViewModel.Location.Save("Stocktake cancelled by user");
  108. }
  109. return result;
  110. }
  111. private void Holding_Clicked(object sender, EventArgs e)
  112. {
  113. if (ViewModel.Location.ID == Guid.Empty)
  114. {
  115. DisplayAlert("ERROR", "Please select a Location!", "OK");
  116. return;
  117. }
  118. if ((sender as MobileCard)?.BindingContext is StockHoldingShell shell)
  119. {
  120. var transaction = ViewModel.Transactions.FirstOrDefault(x => x.Source.Shell == shell);
  121. if (transaction == null)
  122. {
  123. transaction = new StockTransaction(StockTransactionType.StockTake, shell, shell);
  124. transaction.Allocations = shell.Allocations.Select(x => new StockTransactionAllocation()
  125. {
  126. ID = x.ID,
  127. Description = x.Description,
  128. Quantity = x.Quantity,
  129. Maximum = double.MaxValue
  130. }
  131. ).ToArray();
  132. }
  133. var popup = new StockTakeEdit(transaction);
  134. popup.TransactionSaved += (o,e) =>
  135. {
  136. if (ViewModel.Location.CurrentStocktake.IsEmpty())
  137. {
  138. ViewModel.Location.CurrentStocktake = DateTime.Now;
  139. ViewModel.Location.Save("Stocktake marked as started on mobile device");
  140. }
  141. if (shell.Parent.Transactions != null && !shell.Parent.Transactions.Contains(transaction))
  142. shell.Parent.Transactions?.Add(transaction);
  143. shell.ProductID = transaction.ProductID;
  144. shell.ProductCode = transaction.ProductCode;
  145. shell.ProductName = transaction.ProductName;
  146. var imageid = transaction.ImageID;
  147. if (imageid != Guid.Empty)
  148. shell.Parent.Images[imageid] = transaction.Image;
  149. shell.ImageID = imageid;
  150. shell.DimensionsUnitID = transaction.DimensionsUnitID;
  151. shell.DimensionsHeight = transaction.DimensionsHeight;
  152. shell.DimensionsWidth = transaction.DimensionsWidth;
  153. shell.DimensionsLength = transaction.DimensionsLength;
  154. shell.DimensionsQuantity = transaction.DimensionsQuantity;
  155. shell.DimensionsValue = transaction.DimensionsValue;
  156. shell.DimensionsUnitSize = transaction.DimensionsUnitSize;
  157. _holdings.ItemsSource = null;
  158. _holdings.ItemsSource = ViewModel.Holdings.Items;
  159. };
  160. Navigation.PushAsync(popup);
  161. }
  162. }
  163. private async void TakePhoto_Clicked(object sender, EventArgs args)
  164. {
  165. try
  166. {
  167. MobileDocument file = await MobileDocument.From(PhotoUtils.CreateCameraOptions());
  168. if (file?.Data?.Any() == true)
  169. ViewModel.Images.Add(
  170. new StockTransactionImage(
  171. file,
  172. MobileUtils.ImageTools.CreateThumbnail(file.Data, 256, 256)
  173. )
  174. );
  175. }
  176. catch (Exception e)
  177. {
  178. await MaterialDialog.Instance.AlertAsync(e.Message, "ERROR");
  179. }
  180. }
  181. private async void PickPhoto_Clicked(object sender, EventArgs args)
  182. {
  183. try
  184. {
  185. MobileDocument file = await MobileDocument.From(PhotoUtils.CreatePhotoLibraryOptions());
  186. if (file?.Data?.Any() == true)
  187. ViewModel.Images.Add(
  188. new StockTransactionImage(
  189. file,
  190. MobileUtils.ImageTools.CreateThumbnail(file.Data, 256, 256)
  191. )
  192. );
  193. }
  194. catch (Exception e)
  195. {
  196. await MaterialDialog.Instance.AlertAsync(e.Message, "ERROR");
  197. }
  198. }
  199. private void Image_Clicked(object sender, EventArgs e)
  200. {
  201. if ((sender as MobileCard)?.BindingContext is StockTransactionImage image)
  202. {
  203. ShowPopup(() =>
  204. {
  205. var editor = new SfImageEditor()
  206. {
  207. Source = ImageSource.FromStream(() => new MemoryStream(image.Document.Data)),
  208. BackgroundColor = Color.Transparent,
  209. };
  210. editor.ToolbarSettings.HeaderToolbarHeight = 0;
  211. editor.ImageEdited += (o, args) =>
  212. {
  213. // Trigger the Dispatcher to allow the edit to complete before saving
  214. // Otherwise the autosaved image is one edit behind the editor itself
  215. Dispatcher.BeginInvokeOnMainThread(() => editor.Save());
  216. };
  217. editor.ImageSaving += (o, args) =>
  218. {
  219. using (var ms = new MemoryStream())
  220. {
  221. args.Stream.CopyTo(ms);
  222. image.Document.Data = ms.GetBuffer();
  223. image.Thumbnail = MobileUtils.ImageTools.CreateThumbnail(image.Document.Data, 256, 256);
  224. }
  225. args.Cancel = true;
  226. };
  227. return editor;
  228. });
  229. }
  230. }
  231. private async void Save_Clicked(object sender, MobileMenuButtonClickedEventArgs args)
  232. {
  233. if (!ViewModel.Holdings.Any() && !ViewModel.Transactions.Any() &&
  234. ViewModel.Location.LocationType == StockLocationType.Transient)
  235. {
  236. if (await MaterialDialog.Instance.ConfirmAsync("This location is empty!\nMark it as Inactive?",
  237. "Empty Location") == true)
  238. {
  239. using(var dialog = await MaterialDialog.Instance.LoadingDialogAsync(message: "Closing Location"))
  240. {
  241. ViewModel.Location.Active = false;
  242. ViewModel.Location.Save("Closed by Mobile Device");
  243. Navigation.PopAsync();
  244. return;
  245. }
  246. }
  247. }
  248. if (ViewModel.Holdings.Any()
  249. && !ViewModel.Transactions.Any())
  250. {
  251. await DisplayAlert("Error", "There are no transactions to save!", "OK");
  252. return;
  253. }
  254. if (ViewModel.Holdings.Any()
  255. && !ViewModel.Images.Any())
  256. {
  257. await DisplayAlert("Error", "Please provide at least one photo.", "OK");
  258. return;
  259. }
  260. if (await DisplayAlert("Confirm", "Save StockTake Batch?", "OK", "CANCEL") == true)
  261. {
  262. using(var dialog = await MaterialDialog.Instance.LoadingDialogAsync(message: "Saving Data"))
  263. {
  264. Progress<String> progress = new Progress<string>((s) => dialog.MessageText = s);
  265. await ViewModel.Save(progress);
  266. }
  267. Navigation.PopAsync();
  268. }
  269. }
  270. private async void AddHolding_Clicked(object sender, MobileMenuButtonClickedEventArgs args)
  271. {
  272. if (ViewModel.Location.ID == Guid.Empty)
  273. {
  274. DisplayAlert("ERROR", "Please select a Location!", "OK");
  275. return;
  276. }
  277. var holding = ViewModel.Holdings.CreateItem();
  278. holding.LocationID = ViewModel.Location.ID;
  279. holding.LocationCode = ViewModel.Location.Code;
  280. holding.LocationDescription = ViewModel.Location.Description;
  281. var transaction = new StockTransaction(StockTransactionType.StockTake, holding, holding);
  282. transaction.Allocations = new StockTransactionAllocation[]
  283. {
  284. new StockTransactionAllocation()
  285. {
  286. ID = Guid.Empty,
  287. Description = "General Stock",
  288. Quantity = 0.0F,
  289. Maximum = double.MaxValue
  290. }
  291. };
  292. var popup = new StockTakeEdit(transaction);
  293. popup.TransactionSaved += (o,e) =>
  294. {
  295. transaction.Source.JobID = transaction.Target.JobID;
  296. transaction.Source.JobNumber = transaction.Target.JobNumber;
  297. transaction.Source.JobName = transaction.Target.JobName;
  298. transaction.Source.StyleID = transaction.Target.StyleID;
  299. transaction.Source.StyleCode = transaction.Target.StyleCode;
  300. transaction.Source.StyleDescription = transaction.Target.StyleDescription;
  301. transaction.Source.Units = transaction.Target.Units;
  302. ViewModel.Transactions.Add(transaction);
  303. _holdings.ItemsSource = null;
  304. _holdings.ItemsSource = ViewModel.Holdings.Items;
  305. };
  306. Navigation.PushAsync(popup);
  307. }
  308. private void ChangeArea_Clicked(object sender, MobileButtonClickEventArgs args)
  309. {
  310. ShowPopup(
  311. () => SelectionView.Execute<StockAreaShell>(
  312. (columns) =>
  313. {
  314. columns.Add(new MobileGridTextColumn<StockAreaShell>()
  315. {
  316. Column = x => x.Code,
  317. Width = GridLength.Auto,
  318. Caption = "Code",
  319. Alignment = TextAlignment.Start
  320. });
  321. columns.Add(new MobileGridTextColumn<StockAreaShell>()
  322. {
  323. Column = x => x.Description, Width = GridLength.Star, Caption = "Description",
  324. Alignment = TextAlignment.Start
  325. });
  326. },
  327. (refresh) =>
  328. {
  329. App.Data.StockAreas.Refresh(true);
  330. return App.Data.StockAreas.Where(x => x.Active);
  331. },
  332. (areas) =>
  333. {
  334. ViewModel.Location.AreaID = areas?.FirstOrDefault()?.ID ?? Guid.Empty;
  335. ViewModel.Location.AreaCode = areas?.FirstOrDefault()?.Code ?? string.Empty;
  336. ViewModel.Location.AreaDescription = areas?.FirstOrDefault()?.Description ?? string.Empty;
  337. ViewModel.Location.WarehouseID = areas?.FirstOrDefault()?.WarehouseID ?? Guid.Empty;
  338. ViewModel.Location.WarehouseCode = areas?.FirstOrDefault()?.WarehouseCode ?? string.Empty;
  339. ViewModel.Location.WarehouseDescription = areas?.FirstOrDefault()?.WarehouseDescription ?? string.Empty;
  340. DismissPopup();
  341. }
  342. )
  343. );
  344. }
  345. private void ToggleActive_Clicked(object sender, MobileButtonClickEventArgs args)
  346. {
  347. ViewModel.Location.Active = !ViewModel.Location.Active;
  348. }
  349. }
  350. }