Update_7_66.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.Database;
  4. namespace PRS.Shared.Database_Update_Scripts;
  5. public class Update_7_66 : DatabaseUpdateScript
  6. {
  7. public override VersionNumber Version => new VersionNumber(7, 66);
  8. public override bool Update()
  9. {
  10. Logger.Send(LogType.Information, "", $"Updating Stocktake History");
  11. var _holdings = DbFactory.NewProvider(Logger.Main).Query(
  12. new Filter<StockHolding>().All(),
  13. Columns.None<StockHolding>().Add(x => x.ID)
  14. .Add(x => x.Location.ID)
  15. .Add(x => x.LastStockTake)
  16. ).ToObjects<StockHolding>()
  17. .GroupBy(x=>x.Location.ID).ToArray();
  18. var _locations = DbFactory.NewProvider(Logger.Main).Query(
  19. new Filter<StockLocation>().All(),
  20. Columns.None<StockLocation>().Add(x => x.ID)
  21. .Add(x => x.LastStocktake)
  22. .Add(x => x.CurrentStocktake)
  23. .Add(x => x.StocktakeFrequency)
  24. .Add(x => x.NextStocktake)
  25. ).ToArray<StockLocation>();
  26. List<StockLocation> _updates = new List<StockLocation>();
  27. int _updateCount = 0;
  28. foreach (var _location in _locations)
  29. {
  30. var _group = _holdings.FirstOrDefault(x => x.Key == _location.ID);
  31. if (_group != null)
  32. {
  33. if (_group.Any(x => x.LastStockTake.IsEmpty()))
  34. {
  35. _location.CurrentStocktake =
  36. _group.Where(x => !x.LastStockTake.IsEmpty())
  37. .MinBy(x => x.LastStockTake)?
  38. .LastStockTake
  39. ?? DateTime.MinValue;
  40. _location.LastStocktake = DateTime.MinValue;
  41. }
  42. else
  43. {
  44. _location.CurrentStocktake = DateTime.MinValue;
  45. _location.LastStocktake =
  46. _group.MaxBy(x => x.LastStockTake)?
  47. .LastStockTake
  48. ?? DateTime.MinValue;
  49. }
  50. }
  51. else
  52. {
  53. _location.CurrentStocktake = DateTime.MinValue;
  54. _location.LastStocktake = DateTime.MinValue;
  55. }
  56. _location.StocktakeFrequency = StockTakeFrequency.Yearly;
  57. _updates.Add(_location);
  58. if (_updates.Count >= 500)
  59. {
  60. _updateCount += 500;
  61. Logger.Send(LogType.Information, "", $"- Saving {_updateCount} Locations");
  62. DbFactory.NewProvider(Logger.Main).Save(_updates);
  63. _updates.Clear();
  64. }
  65. }
  66. if (_updates.Any())
  67. {
  68. _updateCount += _updates.Count;
  69. Logger.Send(LogType.Information, "", $"- Saving {_updateCount} Locations");
  70. DbFactory.NewProvider(Logger.Main).Save(_updates);
  71. }
  72. return true;
  73. }
  74. }