private CommodityProducerViewModel LoadUnassignedCenters(Guid producerId,CommodityProducerViewModel vm)
 {
     var unassignedCenters = _centreRepository.GetAll().ToList();
     var assignedAllocations = _masterDataAllocationRepository.GetByAllocationType(MasterDataAllocationType.CommodityProducerCentreAllocation, producerId);
     var assignedCenters = new List<Centre>();
     foreach (var assignedAllocation in assignedAllocations)
     {
        var center = _centreRepository.GetById(assignedAllocation.EntityBId);
         if(center!=null)
         {
             assignedCenters.Add(center);
             if (unassignedCenters.Any(l => l == center))
             {
                 unassignedCenters.Remove(center);
             } 
         }
     }
     vm.AssignedFarmCentres.Clear();
     vm.AssignedFarmCentres = assignedCenters;
     ViewBag.UnassignedCenters = unassignedCenters.Select(r => new { r.Id, r.Name }).ToDictionary(d => d.Id, d => d.Name);
     return vm;
 }
        public ActionResult AssignCentre(CommodityProducerViewModel vm)
        {
            try
            {
                var center = _centreRepository.GetById(vm.SelectedCentreId);
                vm.AssignedFarmCentres=new List<Centre>(){center};
                CommodityProducerViewModel pvm = _commodityProducerViewModelBuilder.AssignCentre(vm);
                LoadUnassignedCenters(vm.Id,vm);
                var msg = "Route successfully added";
                return RedirectToAction("EditCommodityProducer", new { commoditySupplierId = pvm.CommoditySupplierId, id = pvm.Id, msg });
            }
            catch(DomainValidationException ve)
            {
                ValidationSummary.DomainValidationErrors(ve, ModelState);
                
                var existing = _commodityProducerViewModelBuilder.Get(vm.Id);
                if (existing == null)
                    return View("CreateCommodityProducer", vm);

                return View("EditCommodityProducer", vm);
                
            }catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                _log.Debug("Failed to create centres " + ex.Message);

                var existing = _commodityProducerViewModelBuilder.Get(vm.Id);
                if (existing == null)
                    return View("CreateCommodityProducer", vm);

                return View("EditCommodityProducer", vm);
            }
        }
        public ActionResult CreateCommodityProducer(Guid CommoditySupplierId, CommodityProducerViewModel vm)
        {
            try
            {
                vm.Id = Guid.NewGuid();
                vm.CommoditySupplierId = CommoditySupplierId;
                _commodityProducerViewModelBuilder.Save(vm);

                TempData["msg"] = "Farm Successfully Created";

                return RedirectToAction("ListCommodityProducers", new { CommoditySupplierId = CommoditySupplierId });
            }
            catch (DomainValidationException ve)
            {
                TempData["msg"] = ve.Message;
                ValidationSummary.DomainValidationErrors(ve, ModelState);
                _log.Debug("Failed to create commodity producers " + ve.Message);
                _log.Error("Failed to create commodity producers" + ve.ToString());

                _commodityProducerViewModelBuilder.SetUp(vm);
                return View(vm);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                _log.Debug("Failed to create Commodity producers " + ex.Message);
                _log.Error("Failed to create Commodity producers" + ex.ToString());

                _commodityProducerViewModelBuilder.SetUp(vm);
                return View(vm);
            }

        }
        public ActionResult CreateCommodityProducer(Guid CommoditySupplierId)
        {
            var model = new CommodityProducerViewModel();
            model.CommoditySupplierId = CommoditySupplierId;
            _commodityProducerViewModelBuilder.SetUp(model);

            return View(model);
        }
        public ActionResult EditCommodityProducer(Guid commoditySupplierId, CommodityProducerViewModel vm)
        {
            var path = Request.Path;
            if (path.Split('/').LastOrDefault() == "AssignCentre")
            {
                return AssignCentre(vm);
            }

            vm.CommoditySupplierId = commoditySupplierId;
            _commodityProducerViewModelBuilder.SetUp(vm);
            try
            {
                _commodityProducerViewModelBuilder.Save(vm);
                TempData["msg"] = "Commodity producer Successfully Edited";
                return RedirectToAction("ListCommodityProducers", new { CommoditySupplierId = commoditySupplierId });
            }
            catch (DomainValidationException ve)
            {
                ValidationSummary.DomainValidationErrors(ve, ModelState);
                _log.Debug("Failed to edit Commodity producer " + ve.Message);
                _log.Error("Failed to edit Commodity producer" + ve.ToString());

                _commodityProducerViewModelBuilder.SetUp(vm);
                return View();
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                _log.Debug("Failed to edit Commodity producer " + ex.Message);
                _log.Error("Failed to edit Commodity producer" + ex.ToString());
                _commodityProducerViewModelBuilder.SetUp(vm);
                return View();
            }
        }
        public ActionResult CreateCommoditySupplier(CommoditySupplierViewModel vm)
        {
            
            ViewBag.CommoditySupplierTypeList = _commoditySupplierViewModelBuilder.CommoditySupplierType();
            ViewBag.ParentCostCentreList = _commoditySupplierViewModelBuilder.ParentCostCentre();
            ViewBag.Banks = _commoditySupplierViewModelBuilder.GetBanks();
            ViewBag.GenderList = _commodityOwnerViewModelBuilder.Gender();
            ViewBag.MaritalStatusList = _commodityOwnerViewModelBuilder.MaritalStatus();
            ViewBag.CommodityOwnerTypeList = _commodityOwnerViewModelBuilder.CommodityOwnerType();
            ViewBag.UnassignedCentresList = _centreRepository.GetAll().Select(r => new { r.Id, r.Name }).ToDictionary(d => d.Id, d => d.Name);
            LoadBranches(vm.BankId);

            if (!ModelState.IsValid)
            {
                return View(vm);
            }

            var allocatedCenter = _centreRepository.GetById(vm.SelectedCentreId);
            try
            {
                using (var tran = new TransactionScope())
                {
                    var commoditySupplierDto = new CommoditySupplierDTO
                    {
                            MasterId = vm.CommoditySupplierId,
                            Name = vm.Name,
                            AccountName = vm.AccountName,
                            AccountNo = vm.AccountNo,
                            PinNo = vm.PinNo,
                            BankId = vm.BankId,
                            BankBranchId = vm.BankBranchId,
                            CommoditySupplierTypeId = vm.CommoditySupplierType,
                            CostCentreCode = vm.CostCentreCode,
                            ParentCostCentreId = vm.ParentCostCentreId,
                        
                        };
                    _commoditySupplierViewModelBuilder.Save(commoditySupplierDto);
                    var commodityOwnerViewModel = new CommodityOwnerViewModel
                        {
                            Id=vm.CommodityOwnerId,
                            Code=vm.OwnerCode,
                            CommodityOwnerType=vm.CommodityOwnerType,
                            DateOfBirth=vm.DateOfBirth,
                            BusinessNumber=vm.BusinessNumber,
                            Description=vm.Description,
                            Email=vm.Email,
                            FaxNumber=vm.FaxNumber,
                            FirstName=vm.FirstName,
                            LastName=vm.LastName,
                            Surname=vm.Surname,
                            Gender=vm.Gender,
                            IdNo=vm.IdNo,
                            MaritalStatus=vm.MaritalStatus,
                            OfficeNumber=vm.OfficeNumber,
                            PhoneNumber=vm.PhoneNumber,
                            PhysicalAddress=vm.PhysicalAddress,
                            PinNo=vm.OwnerPinNo,
                            PostalAddress=vm.PostalAddress,
                            CommoditySupplier=vm.CommoditySupplierId
                        };

                    _commodityOwnerViewModelBuilder.Save(commodityOwnerViewModel);
                    var commodityProducerViewModel = new CommodityProducerViewModel
                        {
                            Id=vm.CommodityProducerId,
                            Code=vm.FarmCode,
                            Acrage=vm.Acrage,
                            Name=vm.FarmName,
                            RegNo=vm.RegNo,
                            PhysicalAddress=vm.FarmPhysicalAddress,
                            Description=vm.FarmDescription,
                            CommoditySupplierId=vm.CommoditySupplierId,
                            AssignedFarmCentres = new List<Centre>(){allocatedCenter},

                        };
                    _commodityProducerViewModelBuilder.Save(commodityProducerViewModel);

                    AssignCenter(vm.SelectedCentreId, vm.CommodityProducerId);

                    TempData["msg"] = "Commodity supplier Successfully Created";
                    tran.Complete();
                }


                return RedirectToAction("ListCommoditySuppliers");
            }
            catch (DomainValidationException ve)
            {
                ValidationSummary.DomainValidationErrors(ve, ModelState);
                _log.Debug("Failed to create commodity suppliers " + ve.Message);
                _log.Error("Failed to create commodity suppliers" + ve.ToString());

                return View(vm);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                _log.Debug("Failed to create Commodity suppliers " + ex.Message);
                _log.Error("Failed to create Commodity suppliers" + ex.ToString());

                return View(vm);
            }

        }