public DistributionWindow(DistributionViewModel dvm)
 {
     this.dvm    = dvm;
     DataContext = this.dvm;
     InitializeComponent();
     this.dvm.UpdateData += Dvm_UpdateData;
 }
Exemple #2
0
        public ActionResult DistributionReportViewerExportTo(DistributionViewModel distributionViewModel)
        {
            //DRMFSS.Web.Reports.MasterReportBound rep = GetDistributionReport();
            MasterReportBound report = GetDistributionReportPivot(distributionViewModel);

            return(DevExpress.Web.Mvc.ReportViewerExtension.ExportTo(report));
        }
 private void InitializeViews()
 {
     BasesViewModel = new BasesViewModel(db);
     BasesView      = new BasesView {
         DataContext = BasesViewModel
     };
     PlatformViewModel = new PlatformViewModel(db);
     PlatformView      = new PlatformView {
         DataContext = PlatformViewModel
     };
     ActionsViewModel = new ActionsViewModel(db);
     ActionsView      = new ActionsView {
         DataContext = ActionsViewModel
     };
     DistributionViewModel = new DistributionViewModel(db);
     DistributionView      = new DistributionView {
         DataContext = DistributionViewModel
     };
     HomeViewModel = new HomeViewModel(db);
     HomeView      = new HomeView {
         DataContext = HomeViewModel
     };
     TelegramViewModel = new TelegramViewModel(db);
     TelegramView      = new TelegramView {
         DataContext = TelegramViewModel
     };
 }
        /// <summary>
        ///   Gets an array containing all distributions that can be dynamically build by
        ///   this application by inspecting Accord.NET assemblies using reflection.
        /// </summary>
        ///
        public static DistributionViewModel[] GetDistributions(MainViewModel owner)
        {
            // This function iterates the Accord.Statistics assembly looking for
            // classes that are concrete (not abstract) and that implement the
            // IUnivariateDistribution interface. Then, it attempts to create a
            // DistributionViewModel from the distribution's type by using the
            // DistributionViewModel.TryParse method.

            var baseType = typeof(IUnivariateDistribution);

            var assembly = Assembly.GetAssembly(baseType);

            // Prepare and leave Accord.NET documentation parsed
            var doc = GetDocumentation(assembly);

            // Get all univariate distributions in Accord.NET:
            var distributions = assembly.GetTypes()
                                .Where(p => baseType.IsAssignableFrom(p) && !p.IsAbstract && !p.IsInterface);

            // Get only those that can be dynamically built:
            var buildable = new List <DistributionViewModel>();

            foreach (Type type in distributions)
            {
                DistributionViewModel distribution;
                if (DistributionViewModel.TryParse(owner, type, doc, out distribution))
                {
                    buildable.Add(distribution);
                }
            }

            buildable.Sort((a, b) => a.Name.CompareTo(b.Name));

            return(buildable.ToArray());
        }
Exemple #5
0
        public ActionResult DistributionReportViewerExportTo(DistributionViewModel distributionViewModel)
        {
            //Cats.Web.Hub.Reports.MasterReportBound rep = GetDistributionReport();
            MasterReportBound report = GetDistributionReportPivot(distributionViewModel);

            //TODO:Install DevexpressV11  return DevExpress.Web.Mvc.ReportViewerExtension.ExportTo(report);
            return(View());
        }
Exemple #6
0
 public ActionResult DistributionCompleted(DistributionViewModel distribution)
 {
     if (string.IsNullOrEmpty(distribution.Title))
     {
         distribution.Title = "No Title!";
     }
     return(View(distribution));
 }
Exemple #7
0
        private void DistributeButon_Click(object sender, RoutedEventArgs e)
        {
            DistributionViewModel dvm = mwvm.StartDistribute();

            DistributionWindow distribute = new DistributionWindow(dvm);

            distribute.ShowDialog();
        }
        public IList <DistributionViewModel> MapDistributionsToViewModels(IList <IDistribution> distributions)
        {
            var viewModels = new DistributionViewModel[distributions.Count];

            for (int cnt = 0; cnt < distributions.Count; cnt++)
            {
                viewModels[cnt] = MapDistributionToViewModel(distributions[cnt]);
            }
            return(viewModels);
        }
Exemple #9
0
        public static async Task <DistributionViewModel> RunAsync(DistributionViewModel vm, string url)
        {
            try
            {
                var distribution = await GetDistributionAsync(url);

                return(distribution);
            }
            catch (Exception ex)
            {
                _client.CancelPendingRequests();
                throw new Exception("RunAsync caused an error: " + ex.Message, ex);
            }
        }
Exemple #10
0
        public void DistributionAsync(string graphId, string distId)
        {
            var vm            = new DistributionViewModel();
            var webApiBaseUrl = ConfigurationManager.AppSettings["DataCatalogWebApiUrl"];
            var url           = webApiBaseUrl + $"/GetDistribution?graphId={graphId}&distributionId={distId}";

            AsyncManager.OutstandingOperations.Increment();

            Task.Factory.StartNew(() =>
            {
                DistributionViewModel result            = DataStoreSrv.RunAsync(vm, url).Result;
                AsyncManager.Parameters["distribution"] = result;
                AsyncManager.OutstandingOperations.Decrement();
            }
                                  );
        }
        public ActionResult DistributePackage(DistributionViewModel distributionViewModel)
        {
            AutoMapper.Mapper.CreateMap <DistributionViewModel, Distribution>();
            var distribute = AutoMapper.Mapper.Map <Distribution>(distributionViewModel);

            var id = distributionsContracts.Add(distribute, User.Identity.GetUserName(), distributionViewModel.BarcodeId);

            if (id > 0)
            {
                TempData["Success"] = "Distributed packages";
                return(RedirectToAction("DistributePackage"));
            }
            else
            {
                TempData["Fail"] = "Failed to send";
                return(View("Distribute"));
            }
        }
Exemple #12
0
        public MasterReportBound GetDistributionReportPivot(DistributionViewModel distributionViewModel)
        {
            List <DRMFSS.BLL.ViewModels.Report.Data.DistributionReport> reports = new List <BLL.ViewModels.Report.Data.DistributionReport>();

            DRMFSS.BLL.ViewModels.Report.Data.DistributionReport distribution = new BLL.ViewModels.Report.Data.DistributionReport();
            BLL.UserProfile user = _userProfileService.GetUser(User.Identity.Name);

            distribution.PreparedBy  = user.GetFullName();
            distribution.HubName     = user.DefaultHub.HubNameWithOwner;
            distribution.ReportCode  = DateTime.Now.ToString();
            distribution.ReportDate  = DateTime.Now;
            distribution.ReportName  = "DistributionReport";
            distribution.ReportTitle = "Distribution Report";
            distribution.Rows        = new List <DistributionRows>();

            distribution.Rows = _transactionService.GetDistributionReport(user.DefaultHub.HubID, distributionViewModel);
            //   new List<DistributionRows>();
            //for (int i = 1; i < 5; i++)
            //{
            //    DistributionRows r = new DistributionRows();
            //    r.BudgetYear = DateTime.Now.Year;
            //    r.Region = (i % 2 == 0) ? "Amhara" : "Benshangul";
            //    r.Program = "Program " + i.ToString();
            //    r.DistributedAmount = i * decimal.Parse("2340.43674") * 45;
            //    int month = i;
            //    if (month == 0)
            //        month++;
            //    r.Month = month.ToString();
            //    r.Quarter = (i % 3 > 0) ? (i / 3) + 1 : i / 3;
            //    distribution.Rows.Add(r);
            //}

            reports.Add(distribution);

            DRMFSS.Web.Reports.DistributionReportPivot rpt = new Web.Reports.DistributionReportPivot();
            rpt.xrPivotGrid1.DataSource = reports[0].Rows;
            MasterReportBound report = new MasterReportBound()
            {
                Name = "Distribution Report - " + DateTime.Now.ToShortDateString(), DataSource = reports
            };

            report.rptSubReport.ReportSource = rpt;
            return(report);
        }
Exemple #13
0
        public ActionResult DistributionReport()
        {
            DistributionViewModel newDistributionViewModel = new DistributionViewModel();

            newDistributionViewModel.PeriodId = (DateTime.Now.Month - 1 / 3) + 1;// current quarter by default
            MasterReportBound report = GetDistributionReportPivot(newDistributionViewModel);
            UserProfile       user   = _userProfileService.GetUser(User.Identity.Name);
            var codes          = ConstantsService.GetAllCodes();
            var commodityTypes = _commodityTypeService.GetAllCommodityTypeForReprot();
            var programs       = _programService.GetAllProgramsForReport();
            var stores         = _hubService.GetAllStoreByUser(user);
            var areas          = _adminUnitService.GetAllAreasForReport();
            var bidRefs        = _dispatchAllocationService.GetAllBidRefsForReport();
            var viewModel      = new DistributionViewModel(codes, commodityTypes, programs, stores, areas, bidRefs);

            ViewBag.Filters = viewModel;

            return(View(report));
        }
Exemple #14
0
        private static async Task <DistributionViewModel> GetDistributionAsync(string url)
        {
            DistributionViewModel vm       = null;
            HttpResponseMessage   response = await _client.GetAsync(url, HttpCompletionOption.ResponseContentRead);

            if (response.IsSuccessStatusCode)
            {
                try
                {
                    var json = response.Content.ReadAsStringAsync().Result;
                    vm = Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(DistributionViewModel)) as DistributionViewModel;
                }
                catch (Exception ex)
                {
                    _client.CancelPendingRequests();
                    throw new Exception("GetDistributionAsync caused an error: " + ex.Message, ex);
                }
            }
            return(vm);
        }
        private bool MakeLink(string folderPath, DistributionViewModel data, int year, int quarter, string regions)
        {
            bool check = false;

            try
            {
                check = WriteReportHelper.MakLinkDistributionQuarter(data, folderPath,
                                                                     $"_PP{year.ToString().Substring(0,2)}{quarter.ToString().PadLeft(2,'0')}", year, quarter, regions);
            }
            catch (Exception ex)
            {
                check = false;
                pcloader.Invoke(new MethodInvoker(delegate
                {
                    pcloader.Visible = false;
                }));
                MessageBox.Show(ex.ToString());
            }
            return(check);
        }
        private DistributionViewModel MapDistributionToViewModel(IDistribution distribution)
        {
            var viewModel = new DistributionViewModel();

            viewModel.Id = distribution.Id;

            viewModel.Minimum = distribution.Minimum;
            viewModel.Worst   = distribution.Worst;
            viewModel.Likely  = distribution.Likely;
            viewModel.Best    = distribution.Best;
            viewModel.Maximum = distribution.Maximum;

            viewModel.HeightWorst  = distribution.HeightWorst;
            viewModel.HeightLikely = distribution.HeightLikely;
            viewModel.HeightBest   = distribution.HeightBest;

            viewModel.Mean  = distribution.Mean;
            viewModel.Stdev = distribution.Stdev;
            viewModel.Skew  = distribution.Skew;
            viewModel.Kurt  = distribution.Kurt;

            return(viewModel);
        }
Exemple #17
0
        public ActionResult DistributionReport()
        {
            DistributionViewModel newDistributionViewModel = new DistributionViewModel();
            newDistributionViewModel.PeriodId = (DateTime.Now.Month - 1/3) + 1;// current quarter by default
            MasterReportBound report = GetDistributionReportPivot(newDistributionViewModel);
            UserProfile user = _userProfileService.GetUser(User.Identity.Name);
            var codes=ConstantsService.GetAllCodes();
            var commodityTypes=_commodityTypeService.GetAllCommodityTypeForReprot();
            var programs=_programService.GetAllProgramsForReport();
            var stores=_hubService.GetAllStoreByUser(user);
            var areas=_adminUnitService.GetAllAreasForReport();
            var bidRefs=_dispatchAllocationService.GetAllBidRefsForReport();
            var viewModel = new DistributionViewModel(codes,commodityTypes,programs,stores,areas,bidRefs);
            ViewBag.Filters = viewModel;

            return View(report);
        }
Exemple #18
0
 public ActionResult DistributionReportViewerExportTo(DistributionViewModel distributionViewModel)
 {
     //Cats.Web.Hub.Reports.MasterReportBound rep = GetDistributionReport();
     MasterReportBound report = GetDistributionReportPivot(distributionViewModel);
     //TODO:Install DevexpressV11  return DevExpress.Web.Mvc.ReportViewerExtension.ExportTo(report);
     return View();
 }
Exemple #19
0
        public MasterReportBound GetDistributionReportPivot(DistributionViewModel distributionViewModel)
        {
            List<Cats.Models.Hub.ViewModels.Report.Data.DistributionReport> reports = new List<Cats.Models.Hub.ViewModels.Report.Data.DistributionReport>();
            Cats.Models.Hub.ViewModels.Report.Data.DistributionReport distribution = new Cats.Models.Hub.ViewModels.Report.Data.DistributionReport();
            UserProfile user = _userProfileService.GetUser(User.Identity.Name);

            distribution.PreparedBy = user.GetFullName();
            distribution.HubName = user.DefaultHub.HubNameWithOwner;
            distribution.ReportCode = DateTime.Now.ToString();
            distribution.ReportDate = DateTime.Now;
            distribution.ReportName = "DistributionReport";
            distribution.ReportTitle = "Distribution Report";
            distribution.Rows = new List<DistributionRows>();

            distribution.Rows = _transactionService.GetDistributionReport(user.DefaultHub.HubID, distributionViewModel);
             //   new List<DistributionRows>();
            //for (int i = 1; i < 5; i++)
            //{
            //    DistributionRows r = new DistributionRows();
            //    r.BudgetYear = DateTime.Now.Year;
            //    r.Region = (i % 2 == 0) ? "Amhara" : "Benshangul";
            //    r.Program = "Program " + i.ToString();
            //    r.DistributedAmount = i * decimal.Parse("2340.43674") * 45;
            //    int month = i;
            //    if (month == 0)
            //        month++;
            //    r.Month = month.ToString();
            //    r.Quarter = (i % 3 > 0) ? (i / 3) + 1 : i / 3;
            //    distribution.Rows.Add(r);
            //}

            reports.Add(distribution);

            Cats.Web.Hub.Reports.DistributionReportPivot rpt = new Cats.Web.Hub.Reports.DistributionReportPivot();
            rpt.xrPivotGrid1.DataSource = reports[0].Rows;
            MasterReportBound report = new MasterReportBound() { Name = "Distribution Report - " + DateTime.Now.ToShortDateString(), DataSource = reports };
            report.rptSubReport.ReportSource = rpt;
            return report;
        }
 public DistributionView()
 {
     InitializeComponent();
     DataContext = new DistributionViewModel();
 }
Exemple #21
0
 public ActionResult DistributionReportPartial(DistributionViewModel distributionViewModel)
 {
     MasterReportBound report = GetDistributionReportPivot(distributionViewModel);
     return PartialView("DistributionReportPartial", report);
 }
 public ActionResult Create(DistributionViewModel distributionViewModel)
 {
     return(View());
 }
Exemple #23
0
 public AddCommand(DistributionViewModel distribution)
 {
     Distribution = distribution;
 }
 private void LoadDataDetail(string intNo, int year, int quarter)
 {
     try
     {
         isLoadDetail = true;
         DateTime startTime = DateTime.Now;
         //countDetail = 0;
         foreach (var item in dataMaster.Items)
         {
             item.Items.Clear();
         }
         #region Read file
         ExcelHelper excelHelper = new ExcelHelper();
         dataMaster = excelHelper.ReadExcelImportDistributionQuaterDetail(dataMaster);
         if (dataMaster != null)
         {
             dataMaster.Items = dataMaster.Items.OrderBy(p => p.SerialNo).ToList();
             dataImport       = dataMaster.Items;
         }
         #endregion
         //dataImport = JsonHelper.JsonToPreclaim(path, year, month);
         if (dataImport != null && dataImport.Count > 0)
         {
             countMaster = dataImport.Count;
             statusMain.Invoke(new MethodInvoker(delegate
             {
                 lbInfo.Text = $"Total detail records loading: {1}";
             }));
             dgvMaster.Invoke(new MethodInvoker(delegate
             {
                 dgvMaster.DataSource = dataImport;
             }));
             for (int i = 0; i < dgvMaster.Rows.Count; i++)
             {
                 if (dgvMaster.Rows[i].Cells["Pathx"].Value.ToString() == string.Empty ||
                     (bool)dgvMaster.Rows[i].Cells["IsLoadDetail"].Value == false)
                 {
                     dgvMaster.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
                 }
             }
         }
         else
         {
             statusMain.Invoke(new MethodInvoker(delegate
             {
                 lbInfo.Text = "Load detail data from excel file be error!";
             }));
         }
         DateTime endTime = DateTime.Now;
         lbInfoImport.Invoke(new MethodInvoker(delegate
         {
             lbInfoImport.Text  = $"Time load(second(s)): {(endTime - startTime).TotalSeconds.ToString("##0.##")}, ";
             lbInfoImport.Text += $"total detail record(s): {countMaster}";
         }));
         isLoadDetail = false;
     }
     catch (Exception)
     {
         isLoadDetail = false;
         pcloader.Invoke(new MethodInvoker(delegate
         {
             pcloader.Visible = false;
         }));
     }
 }
        private void btnLoadMasterList_Click(object sender, EventArgs e)
        {
            try
            {
                if (isLoadMaster)
                {
                    statusMain.Invoke(new MethodInvoker(delegate
                    {
                        lbOperation.Text = "Waiting load master...";
                    }));
                }
                if (isLoadDetail)
                {
                    statusMain.Invoke(new MethodInvoker(delegate
                    {
                        lbOperation.Text = "Waiting load detail...";
                    }));
                }
                if (isSync)
                {
                    statusMain.Invoke(new MethodInvoker(delegate
                    {
                        lbOperation.Text = "Waiting sync data...";
                    }));
                }
                pathMaster = "";
                if (txtPath.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("input master file path!");
                    return;
                }
                if (txtPath1.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("input detail folder path!");
                    return;
                }
                if (dataMaster != null)
                {
                    if (dataMaster.Items != null)
                    {
                        dataMaster.Items.Clear();
                        dataMaster.Items = null;
                    }
                    dataMaster = null;
                    GC.Collect();
                    dataMaster           = new DistributionViewModel();
                    dgvMaster.DataSource = dataMaster.Items;
                    dgvMaster.Invalidate();
                    dgvDetail.DataSource = new List <DistributionDetails>();
                    dgvDetail.Invalidate();
                }
                pathMaster = txtPath.Text;
                pathDetail = txtPath1.Text;
                year       = (int)numYear.Value;
                quarter    = cboQuater.SelectedIndex + 1;
                regions    = cboRegons.Text;

                strPP            = $"PP{year}{quarter.ToString().PadLeft(2,'0')}";
                isLoadMasterType = true;
                Operation        = OperationType.LoadExcel;
                pcloader.Visible = true;
                pcloader.Dock    = DockStyle.Fill;
                backgroundWorker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public override async Task <int> HandleCommand(AddLocationCommand request, CancellationToken cancellationToken)
        {
            if (request.Location == null || request.Location.Address == null || request.Location.Contact == null)
            {
                throw new BusinessException("AddWrongInformation");
            }

            if (request.LoginSession.Roles.FirstOrDefault(r => r == "Administrator") == null)
            {
                var retailer = await retailerQueries.GetByUserId(request.LoginSession.Id);

                if (retailer == null)
                {
                    throw new BusinessException("Retailer.NotExisted");
                }
                request.Location.RetailerId = retailer.Id;
            }
            else
            {
                if (request.Location.RetailerId == 0)
                {
                    throw new BusinessException("AddWrongInformation");
                }
                else
                {
                    var retailer = await retailerQueries.Get(request.Location.RetailerId);

                    if (retailer == null)
                    {
                        throw new BusinessException("Retailer.NotExisted");
                    }
                }
            }

            if (request.Location.ImageData?.Length > Constant.MaxImageLength)
            {
                throw new BusinessException("Image.OutOfLength");
            }
            //With ImageData < 100byte. This is a link image. With Image > 100byte, It can a real imageData.
            if (request.Location.ImageData?.Length > 200)
            {
                string type = CommonHelper.GetImageType(System.Text.Encoding.ASCII.GetBytes(request.Location.ImageData));
                if (!CommonHelper.IsImageType(type))
                {
                    throw new BusinessException("Image.WrongType");
                }
                string Base64StringData = request.Location.ImageData.Substring(request.Location.ImageData.IndexOf(",") + 1);
                string fileName         = Guid.NewGuid().ToString().Replace("-", "");
                request.Location.ImageURL = CommonHelper.SaveImage($"{GlobalConfiguration.RetailerImagePath}/{DateTime.Now.ToString("yyyyMM")}/", fileName, type, Base64StringData);
            }

            var distributions = await WebHelper.HttpGet <IEnumerable <DistributionViewModel> >(GlobalConfiguration.APIGateWayURI, AppUrl.GetDistributions, request.LoginSession.AccessToken);

            double minDistance              = double.MaxValue;
            bool   isInDisRadius            = false;
            DistributionViewModel chooseDis = null;

            foreach (var dis in distributions)
            {
                var distance = 1000 * CommonHelper.DistanceBetween2Points(dis.Address.Latitude, dis.Address.Longitude, request.Location.Address.Latitude, request.Location.Address.Longitude);
                if (isInDisRadius)
                {
                    if (distance < minDistance && distance <= dis.Radius)
                    {
                        minDistance = distance;
                        chooseDis   = dis;
                    }
                }
                else
                {
                    if (distance < minDistance)
                    {
                        minDistance = distance;
                        chooseDis   = dis;
                    }
                    if (distance <= dis.Radius)
                    {
                        isInDisRadius = true;
                    }
                }
            }
            if (chooseDis != null)
            {
                request.Location.DistributionId = chooseDis.Id;
            }

            var rs = -1;

            using (var conn = DALHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        retailerRepository.JoinTransaction(conn, trans);
                        retailerQueries.JoinTransaction(conn, trans);
                        locationRepository.JoinTransaction(conn, trans);

                        request.Location.GLN = await retailerQueries.GenarateLocationCode();

                        request.Location    = CreateBuild(request.Location, request.LoginSession);
                        request.Location.Id = await retailerRepository.AddLocation(request.Location);

                        request.Location.Address.Id         = 0;
                        request.Location.Address.ObjectType = LocationOjectType.R.ToString();
                        request.Location.Address.ObjectId   = request.Location.RetailerId;
                        request.Location.Address.IsUsed     = true;
                        request.Location.Address            = CreateBuild(request.Location.Address, request.LoginSession);
                        var addressId = await locationRepository.AddOrUpdateAddress(request.Location.Address);

                        request.Location.Contact.Id         = 0;
                        request.Location.Contact.ObjectType = LocationOjectType.R.ToString();
                        request.Location.Contact.ObjectId   = request.Location.RetailerId;
                        request.Location.Contact.IsUsed     = true;
                        request.Location.Contact            = CreateBuild(request.Location.Contact, request.LoginSession);
                        var contactId = await locationRepository.AddOrUpdateContact(request.Location.Contact);

                        request.Location.AddressId = addressId;
                        request.Location.ContactId = contactId;

                        rs = await retailerRepository.UpdateLocation(request.Location);
                    }
                    finally
                    {
                        if (rs == 0)
                        {
                            trans.Commit();
                        }
                        else
                        {
                            try
                            {
                                trans.Commit();
                            }
                            catch { }
                            CommonHelper.DeleteImage(request.Location.ImageURL);
                        }
                    }
                }
            };

            return(rs);
        }
        public ActionResult Distribution(Guid groupId, string firstName, string lastName)
        {
            DistributionViewModel vm = new DistributionViewModel();

            ApplicationDbContext context = new ApplicationDbContext();

            var group = context.Groups.Include("Members").FirstOrDefault(x => x.Id == groupId);

            vm.Budget    = group.Budget;
            vm.GroupName = group.Name;
            var members = group.Members.ToList();

            firstName = firstName.Trim().ToLower();
            lastName  = lastName.Trim().ToLower();

            var person = members.FirstOrDefault(x => x.FirstName.ToLower() == firstName && x.LastName.ToLower() == lastName);

            Member member;

            //Person exists
            if (person != null)
            {
                vm.PersonExists = true;

                //Person should be assigned
                if (person.Receiver == null)
                {
                    member = members.FirstOrDefault(
                        //Already got present
                        x => !x.HasGotPresent &&
                        //You can't give to yourself
                        x.Id != person.Id &&
                        //You can't give to someone has given to you
                        x.Receiver != person.Id
                        //You can't give to someone who has already given something
                        && x.Receiver == null);
                    if (member == null)
                    {
                        member = members.FirstOrDefault(
                            //Already got present
                            x => !x.HasGotPresent &&
                            //You can't give to yourself
                            x.Id != person.Id &&
                            //You can't give to someone has given to you
                            x.Receiver != person.Id);
                        if (member == null)
                        {
                            member = members.FirstOrDefault(x => !x.HasGotPresent && x.Id != person.Id);
                        }
                    }
                    member.HasGotPresent = true;
                    person.Receiver      = member.Id;
                }//Already assigned
                else
                {
                    vm.AlreadyAssigned = true;
                    member             = members.FirstOrDefault(x => x.Id == person.Receiver.Value);
                }
                vm.Name = member.FirstName + " " + member.LastName;
            }
            else
            {
                vm.PersonExists = false;
            }

            context.SaveChanges();

            return(View("Distribution", vm));
        }
Exemple #28
0
        public ActionResult DistributionReportPartial(DistributionViewModel distributionViewModel)
        {
            MasterReportBound report = GetDistributionReportPivot(distributionViewModel);

            return(PartialView("DistributionReportPartial", report));
        }
        public void MapNodesToViewModelsOnSuccessReturnsViewModels()
        {
            //arrange
            var distribution = new Mock <IDistribution>();
            IList <IDistribution> distributions = new[] { distribution.Object };
            var statistics = new Mock <IStatistic>();
            var parentMock = new Mock <INode>();

            parentMock.Setup(n => n.Id).Returns(1);
            parentMock.Setup(n => n.Name).Returns("name");
            parentMock.Setup(n => n.NetworkName).Returns("networkname");
            parentMock.Setup(n => n.NetworkUrl).Returns("networkurl");
            parentMock.Setup(n => n.InitialPrice).Returns(2);
            parentMock.Setup(n => n.InitialInvestment).Returns(3);
            parentMock.Setup(n => n.PortfolioWeight).Returns(4);
            parentMock.Setup(n => n.IsPortfolioComponent).Returns(true);
            parentMock.Setup(n => n.Distributions).Returns(distributions);
            parentMock.Setup(n => n.Statistics).Returns(statistics.Object);
            parentMock.Setup(n => n.Histogram).Returns(new List <HistogramDatum>());

            var childMock = new Mock <INode>();

            childMock.Setup(n => n.Id).Returns(2);
            childMock.Setup(n => n.Parent).Returns(parentMock.Object);
            childMock.Setup(n => n.Distributions).Returns(distributions);
            childMock.Setup(n => n.Statistics).Returns(statistics.Object);

            var parent = parentMock.Object;
            var child  = childMock.Object;
            IDictionary <int, INode> nodes = new Dictionary <int, INode> {
                { parent.Id, parent },
                { child.Id, child }
            };

            var distributionViewModel  = new DistributionViewModel();
            var distributionViewModels = new[] { distributionViewModel };
            var distributionMapper     = new Mock <IDistributionMapper>();

            distributionMapper.Setup(m => m.MapDistributionsToViewModels(
                                         It.Is <IList <IDistribution> >(list => list == distributions)))
            .Returns(distributionViewModels);

            var statisticsViewModel = new StatisticViewModel();
            var statisticsMapper    = new Mock <IStatisticMapper>();

            statisticsMapper.Setup(m => m.MapStatisticToViewModel(
                                       It.Is <IStatistic>(s => s == statistics.Object)))
            .Returns(statisticsViewModel);

            var nodeMapper = new NodeMapper(null, null, distributionMapper.Object, statisticsMapper.Object);

            //act
            var results      = nodeMapper.MapNodesToViewModels(nodes);
            var parentResult = results[parent.Id];
            var childResult  = results[child.Id];

            //assert
            Assert.AreEqual(parent.Id, parentResult.Id);
            Assert.AreEqual(parent.Name, parentResult.Name);
            Assert.AreEqual(parent.Url, parentResult.Url);
            Assert.AreEqual(parent.NetworkName, parentResult.NetworkName);
            Assert.AreEqual(parent.NetworkUrl, parentResult.NetworkUrl);
            Assert.AreEqual(parent.InitialPrice, parentResult.InitialPrice);
            Assert.AreEqual(parent.InitialInvestment, parentResult.InitialInvestment);
            Assert.AreEqual(parent.PortfolioWeight, parentResult.PortfolioWeight);
            Assert.IsTrue(parentResult.IsPortfolioComponent);
            Assert.AreSame(distributionViewModels, parentResult.Distributions);
            Assert.AreSame(statisticsViewModel, parentResult.Statistics);
            Assert.AreSame(parent.Histogram, parentResult.Histogram);

            Assert.AreEqual(child.Id, childResult.Id);
            Assert.AreEqual(parent.Id, childResult.Parent.Id);
        }
Exemple #30
0
 public UpdateCommand(DistributionViewModel distribution)
 {
     Distribution = distribution;
 }
Exemple #31
0
        public async Task <DistributionViewModel> GetByCode(string code)
        {
            DistributionViewModel result = null;
            string cmd = $@"SELECT * FROM `distribution` d
                            LEFT JOIN `address` a ON a.id = d.address_id AND a.is_used = 1 AND a.is_deleted = 0
                            LEFT JOIN `contact` cc ON cc.id = d.contact_id AND cc.is_used = 1 AND cc.is_deleted = 0
                            WHERE d.code = '{code}' and d.is_deleted = 0";

            if (DbConnection != null)
            {
                var rd = await DbConnection.QueryMultipleAsync(cmd, transaction : DbTransaction);

                rd.Read <Distribution, Address, Contact, DistributionViewModel>(
                    (dRs, aRs, cdRs) =>
                {
                    if (result == null)
                    {
                        result = CommonHelper.Mapper <Distribution, DistributionViewModel>(dRs);
                    }

                    if (result.Address == null)
                    {
                        result.Address = aRs;
                    }

                    if (result.Contact == null)
                    {
                        result.Contact = cdRs;
                    }

                    return(result);
                }
                    );

                return(result);
            }
            else
            {
                using (var conn = DALHelper.GetConnection())
                {
                    var rd = await conn.QueryMultipleAsync(cmd);

                    rd.Read <Distribution, Address, Contact, DistributionViewModel>(
                        (dRs, aRs, cdRs) =>
                    {
                        if (result == null)
                        {
                            result = CommonHelper.Mapper <Distribution, DistributionViewModel>(dRs);
                        }

                        if (result.Address == null)
                        {
                            result.Address = aRs;
                        }

                        if (result.Contact == null)
                        {
                            result.Contact = cdRs;
                        }

                        return(result);
                    }
                        );

                    return(result);
                }
            }
        }
        private void LoadDataMaster(int year, int quarter)
        {
            try
            {
                if (pathMaster == string.Empty || pathDetail == string.Empty)
                {
                    return;
                }
                DateTime startTime = DateTime.Now;
                countMaster = 0;
                if (dataImport != null)
                {
                    dataImport.Clear();
                }
                if (dataMaster != null)
                {
                    dataMaster.Items.Clear();
                }
                #region Read file
                ExcelHelper excelHelper = new ExcelHelper();
                dataMaster = excelHelper.ReadExcelImportDistributionQuaterMaster(year, quarter, pathMaster);
                if (dataMaster != null)
                {
                    dataMaster.Items = dataMaster.Items.OrderBy(p => p.SerialNo).ToList();
                    dataImport       = dataMaster.Items;
                }
                #endregion

                //dataImport = JsonHelper.JsonToPreclaim(path, year, month);
                if (dataImport != null && dataImport.Count > 0)
                {
                    countMaster = dataImport.Count;
                    statusMain.Invoke(new MethodInvoker(delegate
                    {
                        lbInfo.Text = $"Total master records loading: {1}";
                    }));
                    #region lay file detail
                    string[] files = Directory.GetFiles(pathDetail);
                    foreach (var item in files)
                    {
                        string[] list_name = item.Split('\\');
                        string   name      = "";
                        if (list_name.Length > 0)
                        {
                            name = list_name.Last().Split('.')[0];
                            string[] arrayStr = name.Split(' ');
                            if (arrayStr.Length > 0)
                            {
                                string intNo = arrayStr[arrayStr.Length - 1];
                                var    data  = dataImport.Where(p => p.IntNo == intNo).FirstOrDefault();
                                if (data != null)
                                {
                                    if (data.Path != string.Empty)
                                    {
                                        data.Path += ";";
                                    }
                                    data.Path    += item;
                                    data.NameFile = name;
                                }
                            }
                        }
                    }
                    #endregion
                    dgvMaster.Invoke(new MethodInvoker(delegate
                    {
                        dgvMaster.DataSource = dataImport;
                    }));
                    for (int i = 0; i < dgvMaster.Rows.Count; i++)
                    {
                        if (dgvMaster.Rows[i].Cells["Pathx"].Value.ToString() == string.Empty)
                        {
                            dgvMaster.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
                        }
                    }
                }
                else
                {
                    statusMain.Invoke(new MethodInvoker(delegate
                    {
                        lbInfo.Text = "Load master data from excel file be error!";
                    }));
                }
                DateTime endTime = DateTime.Now;
                lbInfoImport.Invoke(new MethodInvoker(delegate
                {
                    lbInfoImport.Text  = $"Time load(second(s)): {(endTime - startTime).TotalSeconds.ToString("##0.##")}, ";
                    lbInfoImport.Text += $"total master record(s): {countMaster}";
                }));

                #region load detail
                LoadDataDetail(intNo, year, quarter);
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.None,
                                MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000);           // MB_TOPMOST
                pcloader.Invoke(new MethodInvoker(delegate
                {
                    pcloader.Visible = false;
                }));
            }
        }