using Comal.Classes; using InABox.Core; using InABox.Database; namespace PRS.Shared.Database_Update_Scripts; public class Update_7_66 : DatabaseUpdateScript { public override VersionNumber Version => new VersionNumber(7, 66); public override bool Update() { Logger.Send(LogType.Information, "", $"Updating Stocktake History"); var _holdings = DbFactory.NewProvider(Logger.Main).Query( new Filter().All(), Columns.None().Add(x => x.ID) .Add(x => x.Location.ID) .Add(x => x.LastStockTake) ).ToObjects() .GroupBy(x=>x.Location.ID).ToArray(); var _locations = DbFactory.NewProvider(Logger.Main).Query( new Filter().All(), Columns.None().Add(x => x.ID) .Add(x => x.LastStocktake) .Add(x => x.CurrentStocktake) .Add(x => x.StocktakeFrequency) .Add(x => x.NextStocktake) ).ToArray(); List _updates = new List(); int _updateCount = 0; foreach (var _location in _locations) { var _group = _holdings.FirstOrDefault(x => x.Key == _location.ID); if (_group != null) { if (_group.Any(x => x.LastStockTake.IsEmpty())) { _location.CurrentStocktake = _group.Where(x => !x.LastStockTake.IsEmpty()) .MinBy(x => x.LastStockTake)? .LastStockTake ?? DateTime.MinValue; _location.LastStocktake = DateTime.MinValue; } else { _location.CurrentStocktake = DateTime.MinValue; _location.LastStocktake = _group.MaxBy(x => x.LastStockTake)? .LastStockTake ?? DateTime.MinValue; } } else { _location.CurrentStocktake = DateTime.MinValue; _location.LastStocktake = DateTime.MinValue; } _location.StocktakeFrequency = StockTakeFrequency.Yearly; _updates.Add(_location); if (_updates.Count >= 500) { _updateCount += 500; Logger.Send(LogType.Information, "", $"- Saving {_updateCount} Locations"); DbFactory.NewProvider(Logger.Main).Save(_updates); _updates.Clear(); } } if (_updates.Any()) { _updateCount += _updates.Count; Logger.Send(LogType.Information, "", $"- Saving {_updateCount} Locations"); DbFactory.NewProvider(Logger.Main).Save(_updates); } return true; } }