protected void LoadEntityContacts(MasterEntity entity)
 {
     _entity = entity;
     using (var c = NestedContainer)
     {
         ContactsList.Clear();
         var contacts = Using<IContactRepository>(c).GetByContactsOwnerId(entity.Id, ShowInactive)
             .Where(n => (n.Firstname.ToLower().Contains(SearchText.ToLower()) ||
                          n.Lastname.ToLower().Contains(SearchText.ToLower()) ||
                          n.MobilePhone.ToLower().Contains(SearchText.ToLower()))
             );
         _pagedList = new PagenatedList<Contact>(contacts.AsQueryable(), CurrentPage, ItemsPerPage, contacts.Count());
         _pagedList.ToList().ForEach(
             n => ContactsList.Add(new VMContactItem { Contact = n, IsDirty = false, IsNew = false }));
         UpdatePagenationControl();
     }
 }
        private void LoadProductsToImport()
        {
           if(!FileUtility.ValidateFile(SelectedPath))return;
            using (var c=NestedContainer)
            {

                try
                {
                    ImportItems = Using<IProductImportService>(c).Import(SelectedPath);

                    var productImports = ImportItems as List<ProductImport> ?? ImportItems.ToList();
                    if (productImports.Any())
                    {
                        var items = productImports.Select((n, i) => new ProductImportItem()
                                                                        {
                                                                            SequenceNo = i + 1,
                                                                            BrandCode = n.BrandCode,
                                                                            Description = n.Description,
                                                                            DiscountGroup = n.DiscountGroup,
                                                                            ExFactoryPrice = n.ExFactoryPrice,
                                                                            PackagingCode = n.PackagingCode,
                                                                            PackagingTypeCode = n.PackagingTypeCode,
                                                                            ProductCode = n.ProductCode,
                                                                            ProductFlavourCode = n.ProductFlavourCode,
                                                                            ProductTypeCode = n.ProductTypeCode,
                                                                            VATClass = n.VATClass,
                                                                            CustomerDiscount = n.CustomerDiscount,
                                                                            IsChecked = false
                                                                        }).AsQueryable();
                        
                        PagedList = new PagenatedList<ProductImportItem>(items, CurrentPage, ItemsPerPage,items.Count());
                        
                            ProductImportList.Clear();
                        PagedList.ToList().ForEach(ProductImportList.Add);

                        UpdatePagenationControl();

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error getting data from file\nDetails=>" + ex.Message);

                }
            }
        }
        protected override void Reload()
        {
            if (!FileUtility.ValidateFile(SelectedPath)) return;
             using (var c = NestedContainer)
             {

                 MainWindowViewModel.GlobalStatus = string.Format("Loading: {0}", LoadedImportItem);
                 try
                 {

                     ImportItems = Using<IDistributorSalesmanImportService>(c).Import(SelectedPath);
                     var imports = ImportItems as List<DistributorSalesmanImport> ?? ImportItems.ToList();
                     if (imports.Any())
                     {
                         var importready = imports.Select((n, i) => new DistributorSalesmanImportItem()
                                                                        {
                                                                            SequenceNo = i + 1,
                                                                            DistributorCode = n.DistributorCode,
                                                                            Name = n.Name,
                                                                            PayRollNumber = n.PayRollNumber,
                                                                            IsChecked = false,
                                                                            SalesmanCode = n.SalesmanCode,
                                                                          //  SalesmanPhoneNumber = n.SalesmanPhoneNumber
                                                                        }).ToList();
                         SalesmanImportList.Clear();
                        PagedList = new PagenatedList<DistributorSalesmanImportItem>(importready.AsQueryable(),
                                                                                            CurrentPage,
                                                                                            ItemsPerPage,
                                                                                            importready.Count());
                         PagedList.ToList().ForEach(SalesmanImportList.Add);

                         UpdatePagenationControl();
                         MainWindowViewModel.GlobalStatus = string.Format("Loaded:{0}", LoadedImportItem);
                     }
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("Error getting data from file\nDetails=>" + ex.Message);
                     MainWindowViewModel.GlobalStatus = string.Format("Error loading {0}", LoadedImportItem);
                 }
             }

        }
        protected override void Reload()
        {
            if (!FileUtility.ValidateFile(SelectedPath)) return;
            using (var c = NestedContainer)
            {
                try
                {
                    ImportItems = Using<IPricingImportService>(c).Import(SelectedPath);
                    var imports = ImportItems as List<PricingImport> ?? ImportItems.ToList();
                    if (imports.Any())
                    {
                        var importready = imports.Select((n, i) => new PricingImportItem()
                                                                       {
                                                                           SequenceNo = i + 1,
                                                                           IsChecked = false,
                                                                           ProductCode = n.ProductCode,
                                                                           SellingPrice = n.SellingPrice,
                                                                           ExFactoryRate = n.ExFactoryRate,
                                                                           PricingTireCode = n.PricingTireCode

                                                                       }).AsQueryable();

                        PagedList = new PagenatedList<PricingImportItem>(importready.AsQueryable(),
                                                                                               CurrentPage,
                                                                                               ItemsPerPage,
                                                                                               importready.Count());
                        PricingImportList.Clear();
                        PagedList.ToList().ForEach(PricingImportList.Add);
                       
                        UpdatePagenationControl();
                        
                        
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error getting data from file\nDetails=>" + ex.Message);

                }
            }
        }
        protected override void Reload()
        {
            if (!FileUtility.ValidateFile(SelectedPath)) return;
            using (var c = NestedContainer)
            {
                try
                {
                    ImportItems = Using<IShipToAddressImportService>(c).Import(SelectedPath);
                    var imports = ImportItems as List<ShipToAddressImport> ?? ImportItems.ToList();
                    if (imports.Any())
                    {
                        var importready = imports.Select((n, i) => new ShipToAddressImportItem()
                                                                       {
                                                                           SequenceNo = i + 1,
                                                                           IsChecked = false,
                                                                           Name = n.Code,
                                                                           Description = n.Description,
                                                                           OutletCode = n.OutletCode,
                                                                           PhysicalAddress = n.PhysicalAddress,
                                                                           PostalAddress = n.PostalAddress,
                                                                           Latitude = n.Latitude,
                                                                           Longitude = n.Longitude
                                                                       }).ToList();
                        ShipToAddressesImportList.Clear();
                        PagedList = new PagenatedList<ShipToAddressImportItem>(importready.AsQueryable(),
                                                                                             CurrentPage,
                                                                                             ItemsPerPage,
                                                                                             importready.Count());
                        PagedList.ToList().ForEach(ShipToAddressesImportList.Add);

                        UpdatePagenationControl();
                       
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error getting data from file\nDetails=>" + ex.Message);

                }
            }
        }
       private void LoadDiscountGroupsToImport()
       {
           if (!FileUtility.ValidateFile(SelectedPath)) return;
           using (var c = NestedContainer)
           {
               try
               {
                   ImportItems = Using<IProductDiscountGroupImportService>(c).Import(SelectedPath);
                   var imports = ImportItems as List<ProductDiscountGroupImport> ?? ImportItems.ToList();
                   if (imports.Any())
                   {
                       var importready = imports.Select((n, i) => new DiscountGroupImportItem()
                       {
                           SequenceNo = i + 1,
                           IsChecked = false,
                           ProductCode = n.ProductCode,
                           DiscontGroupCode = n.DiscontGroupCode,
                           DiscountValue = n.DiscountValue

                       }).AsQueryable();

                       PagedList = new PagenatedList<DiscountGroupImportItem>(importready.AsQueryable(),
                                                                                              CurrentPage,
                                                                                              ItemsPerPage,
                                                                                              importready.Count());
                       DiscountGroupImportList.Clear();
                       PagedList.ToList().ForEach(DiscountGroupImportList.Add);

                       UpdatePagenationControl();


                   }
               }
               catch (Exception ex)
               {
                   MessageBox.Show("Error getting data from file\nDetails=>" + ex.Message);

               }
           }
       }
 private void LoadList()
 {
     Application.Current.Dispatcher.BeginInvoke(
         new Action(
             delegate
                 {
                     using (var c = NestedContainer)
                     {
                         _pagenatedCommSuppList = Using<ICommoditySupplierRepository>(c).GetAll(CurrentPage,
                                                                                                ItemsPerPage,
                                                                                                SearchText,
                                                                                                ShowInactive);
                         CommoditySupplierList.Clear();
                         _pagenatedCommSuppList.Select((n, i) => Map(n as CommoditySupplier, i)).ToList().ForEach
                             (CommoditySupplierList.Add);
                         UpdatePagenationControl();
                     }
                 }));
 }
        internal void LoadConfirmedOrders()
       {
           Application.Current.Dispatcher.BeginInvoke(
               new Action(
                   () =>
                       {
                           using (var c = NestedContainer)
                           {
                               var orders = Using<IMainOrderRepository>(c)
                                   .PagedDocumentList(CurrentPage, ItemsPerPage, StartDate, EndDate,
                                                      OrderType.OutletToDistributor, DocumentStatus.Confirmed,
                                                      SearchText);
                                 
                               
                               var items = orders
                                   .Select((n, i) => new OrderItemSummary()
                                                         {
                                                             SequenceNo = i + 1,
                                                             OrderId = n.OrderId,
                                                             TotalVat = n.TotalVat,
                                                             GrossAmount = n.GrossAmount,
                                                             NetAmount = n.NetAmount,
                                                             Required = n.Required,
                                                             OutstandingAmount =
                                                                 FormatOutstandingAmount(n.OutstandingAmount),
                                                             OrderReference = n.OrderReference,
                                                             PaidAmount = n.PaidAmount,
                                                             Status = n.Status,
                                                             Salesman = n.Salesman,
                                                             ShippingAddress = GetShippingAddress(n.OrderId),
                                                             IsChecked = false
                                                             
                                                         }).AsQueryable();

                               _pagedItemSummaries = new PagenatedList<OrderItemSummary>(items, CurrentPage, ItemsPerPage,
                                                                                                  items.Count());
                               OrdersSummaryList.Clear();
                              
                               _pagedItemSummaries.ToList().ForEach(OrdersSummaryList.Add);

                               UpdatePagenationControl();
                           }
                       }));
       }
        private void LoadAgiUsers()
        {
            Application.Current.Dispatcher.BeginInvoke(
                new Action(
                    delegate
                        {
                            using (StructureMap.IContainer c = NestedContainer)
                            {
                                UsersList.Clear();
                                var userList = Using<IUserRepository>(c).GetAll(ShowInactive);
                                if (SelectedUserType == UserType.None)
                                    userList = userList.Where(n =>
                                                              (n.UserType == UserType.AgriHQAdmin ||
                                                               n.UserType == UserType.HubManager ||
                                                               n.UserType == UserType.Clerk ||
                                                               n.UserType == UserType.PurchasingClerk ||
                                                               n.UserType == UserType.Driver)
                                                              && n.Username.ToLower().Contains(SearchText.ToLower())
                                        );
                                else
                                    userList = userList.Where(n => n.UserType == SelectedUserType);
                                userList = userList.OrderBy(n => n.CostCentre)
                                    .ThenBy(n => n.Username);

                                _pagenatedUserList = new PagenatedList<User>(userList.AsQueryable(), CurrentPage,
                                                                             (int) ItemsPerPage,
                                                                             userList.Count());
                                var mappedUserItems = _pagenatedUserList.Select(MapUser);

                                foreach (var user in mappedUserItems)
                                {
                                    if (user.EntityStatus == (int) EntityStatus.Active)
                                        user.HlkDeactivateContent = GetLocalText("sl.users.grid.col.deactivate");
                                            //Deactivate
                                    else if (user.EntityStatus == (int) EntityStatus.Inactive)
                                        user.HlkDeactivateContent = GetLocalText("sl.users.grid.col.activate");
                                    UsersList.Add(user);
                                }
                                UpdatePagenationControl();
                            }
                        }), null);
        }
       protected async virtual void ListOrders()
       {

          await Task.Factory.StartNew(() =>
                                     {
                                         Application.Current.Dispatcher.BeginInvoke(
                                             new Action(delegate
                                                            {
                                                                if (SelectedOrderStatus != DocumentStatus.Confirmed)
                                                                    ShowApproveSelectedButton = Visibility.Collapsed;
                                                                using (var container = NestedContainer)
                                                                {
                                                                    OrdersSummaryList.Clear();
                                                                    if (isUnconfirmedTab)
                                                                    {
                                                                        var orderSaveAndContinueService =
                                                                            Using<IOrderSaveAndContinueService>(
                                                                                container);
                                                                        var item =orderSaveAndContinueService.Query(
                                                                                StartDate, EndDate, SelectedOrderType);
                                                                        IPagenatedList<OrderSaveAndContinueLater> ItemList =
                                                                               new PagenatedList<OrderSaveAndContinueLater>(
                                                                                   item.AsQueryable(), CurrentPage,
                                                                                   ItemsPerPage, item.Count());
                                                                        ItemList.Select(Map).ToList().
                                                                            ForEach(
                                                                                OrdersSummaryList.Add);
                                                                    }
                                                                    else
                                                                    {


                                                                        //var orders = Using<IMainOrderRepository>(
                                                                        //    container)
                                                                        //    .GetMainOrderSummariyList(StartDate, EndDate,
                                                                        //                              SelectedOrderType,
                                                                        //                              SelectedOrderStatus,
                                                                        //                              SearchText);
                                                                        var orders =
                                                                            Using<IMainOrderRepository>(container).
                                                                                PagedDocumentList(CurrentPage,
                                                                                                  ItemsPerPage,
                                                                                                  StartDate, EndDate,
                                                                                                  SelectedOrderType,
                                                                                                  SelectedOrderStatus,
                                                                                                  SearchText);

                                                                     
                                                                        if (orders != null && orders.Any())
                                                                        {
                                                                            PagedDocumentList =
                                                                                new PagenatedList<MainOrderSummary>(
                                                                                    orders.AsQueryable(), CurrentPage,
                                                                                    ItemsPerPage, orders.TotalItemCount,true);
                                                                            PagedDocumentList.Select(Map).ToList().
                                                                                ForEach(
                                                                                    OrdersSummaryList.Add);

                                                                            UpdatePagenationControl();

                                                                        }
                                                                    }
                                                                   

                                                                }
                                                            }));
                                     });


       }
        private void LoadGRNs()
        {
            Application.Current.Dispatcher.BeginInvoke(
                new Action(delegate
                               {
                                   using (var c = NestedContainer)
                                   {
                                       var irns =
                                           Using<IInventoryReceivedNoteRepository>(c).GetAll().OrderByDescending(p=>p.DocumentDateIssued).ToList();
                                       if (!string.IsNullOrEmpty(SearchText))
                                       {
                                           irns =
                                               irns.Where(
                                                   p =>
                                                   (p.OrderReferences != null &&
                                                    p.OrderReferences.ToLower().Contains(SearchText.ToLower()))
                                                   || p.DocumentReference.ToLower().Contains(SearchText.ToLower())
                                                   ||
                                                   p.DocumentIssuerUser != null &&
                                                   p.DocumentIssuerUser.Username.ToLower().Contains(
                                                       SearchText.ToLower())
                                                   ).ToList();
                                       }

                                       if (irns.Any())
                                       {
                                           PagedDocumentList = new PagenatedList<InventoryReceivedNote>(
                                               irns.AsQueryable(), CurrentPage,
                                               ItemsPerPage, irns.Count());

                                           UpdatePagenationControl();
                                           Map(PagedDocumentList);
                                       }
                                   }
                               }));

        }
        private void Load(IEnumerable<ApprovedOrderImport> imports)
        {
            using (var c = NestedContainer)
            {
                var importsAuditRepository = Using<IExportImportAuditRepository>(c);
                var validImportsItems =
                    imports.Where(
                        approvedOrderImport => !importsAuditRepository.IsImported(approvedOrderImport.OrderReference)).
                        ToList();
               
                var items = validImportsItems.Select((n, i) => new ImportOrderItemSummary()
                                                         {
                                                             SequenceNo = i + 1,
                                                             DistributrCode =string.IsNullOrEmpty(n.DistributrCode)?GetDistributorCode(n.OrderReference):"",
                                                             OrderReference = n.OrderReference,
                                                             OutletCode = n.OutletCode,
                                                             ProductCode = n.ProductCode,
                                                             OrderDate=n.OrderDate,
                                                            SalesmanCode = n.SalesmanCode,
                                                             ApprovedQuantity = n.ApprovedQuantity
                                                         }).AsQueryable();

                PagedList = new PagenatedList<ImportOrderItemSummary>(items, CurrentPage, ItemsPerPage,
                                                                      items.Count());

                PagedList.ToList().ForEach(ImportOrderItemsSummaryList.Add);

                UpdatePagenationControl();
                
                if (!validImportsItems.Any())
                    UploadStatusMessage = "All orders in file already imported";
            }

        }
 private void LoadShipToAddress()
 {
    ShippingAddresses.Clear();
     DeletedAddresses.Clear();
      if(outlet !=null)
      {
          var addresses = outlet.ShipToAddresses.Where(n => n._Status != EntityStatus.Deleted).ToList();
          if(!string.IsNullOrEmpty(SearchText))
          {
              SearchText = SearchText.ToLower();
              addresses =
                  addresses.Where(
                      p =>
                      p.Code != null && p.Code.ToLower().Contains(SearchText) ||
                      p.Name != null && p.Name.ToLower().Contains(SearchText)).ToList();
          }
          
          if(addresses.Count>10)
          {
              PagedList=new PagenatedList<Core.Domain.Master.CostCentreEntities.ShipToAddress>(addresses.AsQueryable(),20,20,addresses.Count);
              PagedList.ToList().ForEach(n=>ShippingAddresses.Add(MapShippingAddress(n)));
          }
          else
          {
              addresses.ForEach(n=>ShippingAddresses.Add(MapShippingAddress(n)));
              
          }
      }
 }
        void LoadPagedRoutes()
        {
            using (StructureMap.IContainer c = NestedContainer)
            {
                _pagedroutes = Using<IRouteRepository>(c).GetAll(CurrentPage, (int) ItemsPerPage, SearchText, ShowInactive);
                var pagedRouteItems = _pagedroutes.Select(Map).ToList();

                Routes.Clear();
                foreach (var item in pagedRouteItems)
                {
                    if (item.EntityStatus == (int)EntityStatus.Active)
                        item.HlkDeactivateContent = GetLocalText("sl.users.grid.col.deactivate"); //Deactivate
                    else if (item.EntityStatus == (int)EntityStatus.Inactive)
                        item.HlkDeactivateContent = GetLocalText("sl.users.grid.col.activate"); //Activate
                    Routes.Add(item);
                    double percent = ((double)Routes.Count * 100) / (double)_pagedroutes.Count();
                    LoadingStatus = "Loading Routes ..." + (int)percent + "%\nPlease wait";
                }
                Loading = false;
            }
        }
        void DoLoadReturns()
        {
            using (var container = NestedContainer)
            {
                var _returnsNoteService = Using<IReturnsNoteRepository>(container);

                Logging.Log("Loading Returns", LOGLEVEL.INFO);
                List<ReturnsNote> returns =
                    _returnsNoteService.GetAll()
                        .OfType<ReturnsNote>()
                        .Where(n => n.ReturnsNoteType == ReturnsNoteType.SalesmanToDistributor)
                        .ToList();


                returns = returns.Where(n => n.Status == SelectedDocumentStatus).ToList();
                             

                PagenatedReturnsList = new PagenatedList<ReturnsNote>(returns.AsQueryable(), CurrentPage,
                                                                      ItemsPerPage,
                                                                      returns.Count());
                ReturnsList.Clear();
                if (PagenatedReturnsList != null && PagenatedReturnsList.Count > 0)
                {
                    var items = PagenatedReturnsList
                        .Select(n => new ListRNItemsViewModel
                                         {
                                             Id = n.Id,
                                             ReturnsDate =
                                                 n.DocumentDateIssued.ToString(
                                                     "dd-MMM-yyyy hh:mm:ss.sss tt"),
                                             SalesMan = n.DocumentIssuerUser.Username
                                         }).ToList();
                    items.ForEach(ReturnsList.Add);

                    UpdatePagenationControl();
                }
               
            }
        }
        void LoadUsers()
        {
            using (StructureMap.IContainer c = NestedContainer)
            {
                Users.Clear();
                var myCostCentreId = Using<IConfigService>(c).Load().CostCentreId;
                var ccs = Using<ICostCentreRepository>(c).GetAll().Where(n => n.ParentCostCentre != null);
                ccs=ccs.Where(n => n.ParentCostCentre.Id == myCostCentreId).ToList();
                List<Guid> ccIds = ccs.Select(n => n.Id).ToList();
                ccIds.Add(myCostCentreId);

                var userRepository = Using<IUserRepository>(c);
             
                var users = ccIds.ToList().SelectMany(n => userRepository.GetByCostCentre(n, ShowInactive)).OrderByDescending(p => p.Username);

              PagedList=new PagenatedList<User>(users.AsQueryable(),CurrentPage,ItemsPerPage,users.Count());
                PagedList.Select(MapUser).ToList().ForEach(n => Users.Add(n));
                UpdatePagenationControl();

            }
        }
        void LoadContactsFromLocalDb()
        {
           

            using (StructureMap.IContainer c = NestedContainer)
            {
                var contactRepository = Using<IContactRepository>(c);

                var contacts = contactRepository.Query(new QueryStandard()).Data.ToList();
                if (SelectedContactOwner != null)
                {
                    contacts =
                   Using<IContactRepository>(c).GetByContactsOwnerId(SelectedContactOwner.Id, ShowInactive).ToList();
                

                    foreach (var item in contacts)
                    {

                        Contacts.Add(Map(item));

                   } }
                PagedList = new PagenatedList<Contact>(contacts, CurrentPage, ItemsPerPage, contacts.Count());
                Contacts.Clear();
                PagedList.Select(Map).ToList().ForEach(n => Contacts.Add(n));
                UpdatePagenationControl();
            }

        }