StockLocationStore.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Linq;
  3. using Comal.Classes;
  4. using InABox.Core;
  5. namespace Comal.Stores
  6. {
  7. public class StockLocationStore : BaseStore<StockLocation>
  8. {
  9. protected override void BeforeSave(StockLocation entity)
  10. {
  11. base.BeforeSave(entity);
  12. // If the Warehouse is not set, use the default one
  13. if (!entity.Warehouse.IsValid())
  14. {
  15. var warehouseid = Provider.Query(
  16. new Filter<StockWarehouse>(x => x.Default).IsEqualTo(true),
  17. new Columns<StockWarehouse>(x => x.ID)
  18. ).Rows.Select(r => r.Get<StockWarehouse, Guid>(c => c.ID)).FirstOrDefault();
  19. entity.Warehouse.ID = warehouseid;
  20. }
  21. // Try to make sure that there is one and one only default location for the warehouse
  22. var otherdefaults = Provider.Query(
  23. new Filter<StockLocation>(x => x.ID).IsNotEqualTo(entity.ID).And(x => x.Warehouse.ID).IsEqualTo(entity.Warehouse.ID)
  24. .And(x => x.Default)
  25. .IsEqualTo(true),
  26. new Columns<StockLocation>(x => x.ID, x => x.Default)
  27. ).Rows.Select(x => x.ToObject<StockLocation>()).ToArray();
  28. if (!entity.Default)
  29. if (!otherdefaults.Any())
  30. entity.Default = true;
  31. if (entity.Default)
  32. {
  33. entity.Active = true;
  34. foreach (var otherdefault in otherdefaults)
  35. otherdefault.Default = false;
  36. Provider.Save(otherdefaults);
  37. }
  38. }
  39. }
  40. }