Esempio n. 1
0
        public GetAchievementsResponse GetAchievements(GetKpiAchievementsConfigurationRequest request)
        {
            PeriodeType periodeType = (PeriodeType)Enum.Parse(typeof(PeriodeType), request.PeriodeType);
            var         response    = new GetAchievementsResponse();

            try
            {
                var kpiAchievement = DataContext.KpiAchievements.Include(x => x.Kpi).Where(x => x.PeriodeType == periodeType && x.Periode.Year == request.Year && x.Periode.Month == request.Month).ToList();
                if (kpiAchievement.Count > 0)
                {
                    foreach (var item in kpiAchievement)
                    {
                        response.KpiAchievements.Add(item.MapTo <GetKpiAchievementResponse>());
                    }
                }
                response.IsSuccess = true;
            }
            catch (InvalidOperationException invalidOperationException)
            {
                response.IsSuccess = false;
                response.Message   = invalidOperationException.Message;
            }
            catch (ArgumentNullException argumentNullException)
            {
                response.IsSuccess = false;
                response.Message   = argumentNullException.Message;
            }
            return(response);
        }
Esempio n. 2
0
        public GetKpiTargetsResponse GetKpiTargets(int[] kpiIds, DateTime?start, DateTime?end, string periodeType)
        {
            PeriodeType pType    = (PeriodeType)Enum.Parse(typeof(PeriodeType), periodeType);
            var         response = new GetKpiTargetsResponse();

            try
            {
                var kpiTarget = DataContext.KpiTargets
                                .Include(x => x.Kpi.Measurement)
                                .OrderBy(x => x.Kpi.Order)
                                .Where(x => kpiIds.Contains(x.Kpi.Id) && x.PeriodeType == pType && x.Periode >= start.Value && x.Periode <= end.Value)
                                .ToList();
                if (kpiTarget.Count > 0)
                {
                    foreach (var item in kpiTarget)
                    {
                        response.KpiTargets.Add(item.MapTo <GetKpiTargetsResponse.KpiTarget>());
                    }
                }
                response.IsSuccess = true;
            }
            catch (InvalidOperationException invalidOperationException)
            {
                response.IsSuccess = false;
                response.Message   = invalidOperationException.Message;
            }
            catch (ArgumentNullException argumentNullException)
            {
                response.IsSuccess = false;
                response.Message   = argumentNullException.Message;
            }
            return(response);
        }
Esempio n. 3
0
        public ActionResult ConfigurationPartial(ConfigurationParamViewModel paramViewModel)
        {
            int         roleGroupId = paramViewModel.Id;
            PeriodeType pType       = string.IsNullOrEmpty(paramViewModel.PeriodeType)
                                    ? PeriodeType.Yearly
                                    : (PeriodeType)Enum.Parse(typeof(PeriodeType), paramViewModel.PeriodeType);

            var request = new GetKpiAchievementsConfigurationRequest();

            request.PeriodeType = pType.ToString();
            request.RoleGroupId = roleGroupId;
            request.Year        = paramViewModel.Year;
            request.Month       = paramViewModel.Month;
            var response = _kpiAchievementService.GetKpiAchievementsConfiguration(request);

            if (response.IsSuccess)
            {
                var viewModel = response.MapTo <ConfigurationKpiAchievementsViewModel>();
                viewModel.Year        = request.Year;
                viewModel.Month       = request.Month;
                viewModel.Years       = _dropdownService.GetYears().MapTo <SelectListItem>();
                viewModel.Months      = _dropdownService.GetMonths().MapTo <SelectListItem>();
                viewModel.PeriodeType = pType.ToString();
                viewModel.FileName    = this._ExportToExcel(viewModel);
                return(PartialView("Configuration/_" + pType.ToString(), viewModel));
            }

            return(base.ErrorPage(response.Message));
        }
Esempio n. 4
0
        public BaseResponse DeleteKpiAchievement(int kpiId, DateTime periode, PeriodeType periodeType)
        {
            var response = new BaseResponse();

            try
            {
                var achievements = DataContext.KpiAchievements.Where(
                    x => x.Kpi.Id == kpiId && x.Periode == periode && x.PeriodeType == periodeType).ToList();
                foreach (var achievement in achievements)
                {
                    DataContext.KpiAchievements.Remove(achievement);
                }
                DataContext.SaveChanges();
                response.IsSuccess = true;
            }
            catch (InvalidOperationException invalidOperationException)
            {
                response.Message       = invalidOperationException.Message;
                response.ExceptionType = typeof(InvalidOperationException);
            }
            catch (ArgumentNullException argumentNullException)
            {
                response.Message       = argumentNullException.Message;
                response.ExceptionType = typeof(ArgumentNullException);
            }

            return(response);
        }
Esempio n. 5
0
        public GetKpiAchievementResponse GetKpiAchievementByValue(GetKpiAchievementRequestByValue request)
        {
            PeriodeType periodeType = (PeriodeType)Enum.Parse(typeof(PeriodeType), request.PeriodeType);
            var         response    = new GetKpiAchievementResponse();

            response.PeriodeType = periodeType;
            try
            {
                var kpiAchievement = DataContext.KpiAchievements.Include(x => x.Kpi).Single(x => x.Kpi.Id == request.KpiId && x.PeriodeType == periodeType && x.Periode == request.Periode);
                response           = kpiAchievement.MapTo <GetKpiAchievementResponse>();
                response.IsSuccess = true;
            }
            catch (InvalidOperationException invalidOperationException)
            {
                response.IsSuccess     = false;
                response.Message       = invalidOperationException.Message;
                response.ExceptionType = typeof(InvalidOperationException);
            }
            catch (ArgumentNullException argumentNullException)
            {
                response.IsSuccess = false;
                response.Message   = argumentNullException.Message;
            }
            return(response);
        }
Esempio n. 6
0
        public UpdateKpiAchievementsResponse UpdateKpiAchievements(UpdateKpiAchievementsRequest request)
        {
            PeriodeType periodeType = (PeriodeType)Enum.Parse(typeof(PeriodeType), request.PeriodeType);
            var         response    = new UpdateKpiAchievementsResponse();

            response.PeriodeType = periodeType;

            try
            {
                foreach (var pillar in request.Pillars)
                {
                    foreach (var kpi in pillar.Kpis)
                    {
                        foreach (var kpiAchievement in kpi.KpiAchievements)
                        {
                            if (kpiAchievement.Id == 0)
                            {
                                var kpiAchievementNew = new KpiAchievement();
                                kpiAchievementNew.Value       = kpiAchievement.Value;
                                kpiAchievementNew.Kpi         = DataContext.Kpis.Single(x => x.Id == kpi.Id);
                                kpiAchievementNew.PeriodeType = periodeType;
                                kpiAchievementNew.Periode     = kpiAchievement.Periode;
                                kpiAchievementNew.IsActive    = true;
                                kpiAchievementNew.Remark      = kpiAchievement.Remark;
                                kpiAchievementNew.CreatedDate = DateTime.Now;
                                kpiAchievementNew.UpdatedDate = DateTime.Now;
                                DataContext.KpiAchievements.Add(kpiAchievementNew);
                            }
                            else
                            {
                                var kpiAchievementNew = new KpiAchievement();
                                kpiAchievementNew.Id          = kpiAchievement.Id;
                                kpiAchievementNew.Value       = kpiAchievement.Value;
                                kpiAchievementNew.Kpi         = DataContext.Kpis.Single(x => x.Id == kpi.Id);
                                kpiAchievementNew.PeriodeType = periodeType;
                                kpiAchievementNew.Periode     = kpiAchievement.Periode;
                                kpiAchievementNew.IsActive    = true;
                                kpiAchievementNew.Remark      = kpiAchievement.Remark;
                                kpiAchievementNew.UpdatedDate = DateTime.Now;
                                DataContext.KpiAchievements.Attach(kpiAchievementNew);
                                DataContext.Entry(kpiAchievementNew).State = EntityState.Modified;
                            }
                        }
                    }
                }
                response.IsSuccess = true;
                response.Message   = "KPI Achievements has been updated successfully";
                DataContext.SaveChanges();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                response.Message = invalidOperationException.Message;
            }

            return(response);
        }
Esempio n. 7
0
        public GetKpiAchievementResponse GetKpiAchievement(int kpiId, DateTime date, PeriodeType periodeType)
        {
            var response = new GetKpiAchievementResponse();

            try
            {
                var kpi    = DataContext.Kpis.Include(x => x.Measurement).Single(x => x.Id == kpiId);
                var data   = DataContext.KpiAchievements.Include(x => x.Kpi).Where(x => x.Kpi.Id == kpiId && x.Periode == date).AsQueryable();
                var result = new KpiAchievement();
                switch (periodeType)
                {
                case PeriodeType.Daily:
                {
                    result = data.FirstOrDefault(x => x.PeriodeType == periodeType);
                    break;
                }
                }

                var kpiResponse = new GetKpiAchievementResponse.KpiResponse
                {
                    Id          = kpi.Id,
                    Measurement = kpi.Measurement.Name,
                    Name        = kpi.Name,
                    Remark      = kpi.Remark,
                };

                return(new GetKpiAchievementResponse
                {
                    Value = (result != null) ? result.Value : null,
                    Mtd = (result != null) ? result.Mtd : null,
                    Ytd = (result != null) ? result.Ytd : null,
                    Itd = (result != null) ? result.Itd : null,
                    Remark = (result != null) ? result.Remark : null,
                    Kpi = kpiResponse,
                    Deviation = (result != null) ? result.Deviation : null,
                    IsSuccess = true
                });
            }
            catch (Exception exception)
            {
                response.Message = exception.Message;
            }


            return(response);
        }
        private OperationDataConfigurationViewModel ConfigurationViewModel(OperationDataParamConfigurationViewModel paramViewModel, bool?isIncludeGroup)
        {
            PeriodeType pType = string.IsNullOrEmpty(paramViewModel.PeriodeType)
                                    ? PeriodeType.Yearly
                                    : (PeriodeType)Enum.Parse(typeof(PeriodeType), paramViewModel.PeriodeType);

            var request = paramViewModel.MapTo <GetOperationDataConfigurationRequest>();

            request.PeriodeType = pType;
            request.IsPartial   = isIncludeGroup.HasValue && isIncludeGroup.Value;
            var response  = _operationDataService.GetOperationDataConfiguration(request);
            var viewModel = response.MapTo <OperationDataConfigurationViewModel>();

            viewModel.Years       = _dropdownService.GetYearsForOperationData().MapTo <SelectListItem>();
            viewModel.PeriodeType = pType.ToString();
            viewModel.Year        = request.Year;
            viewModel.ConfigType  = ConfigType.OperationData.ToString();
            return(viewModel);
        }
        public ActionResult DownloadTemplateForAllGroup(OperationDataParamConfigurationViewModel paramViewModel)
        {
            PeriodeType pType = string.IsNullOrEmpty(paramViewModel.PeriodeType)
                                   ? PeriodeType.Yearly
                                   : (PeriodeType)Enum.Parse(typeof(PeriodeType), paramViewModel.PeriodeType);

            var request = paramViewModel.MapTo <GetOperationDataConfigurationRequest>();

            request.PeriodeType = pType;
            request.IsPartial   = false;
            var response  = _operationDataService.GetOperationDataConfigurationForAllGroup(request);
            var viewModel = response.MapTo <OperationDataConfigurationViewModel>();

            viewModel.Years       = _dropdownService.GetYearsForOperationData().MapTo <SelectListItem>();
            viewModel.PeriodeType = pType.ToString();
            viewModel.Year        = request.Year;
            viewModel.ConfigType  = ConfigType.OperationData.ToString();
            return(ConvertToExcelFile(paramViewModel, viewModel));
        }
Esempio n. 10
0
        public ActionResult Update(int id, string periodeType)
        {
            int         pmsSummaryId = id;
            PeriodeType pType        = string.IsNullOrEmpty(periodeType)
                            ? PeriodeType.Yearly
                            : (PeriodeType)Enum.Parse(typeof(PeriodeType), periodeType);
            var request = new GetKpiAchievementsRequest {
                PeriodeType = pType, PmsSummaryId = pmsSummaryId
            };
            var response = _kpiAchievementService.GetKpiAchievements(request);

            if (response.IsSuccess)
            {
                var viewModel = response.MapTo <UpdateKpiAchievementsViewModel>();
                viewModel.PmsSummaryId = pmsSummaryId;
                viewModel.PeriodeType  = pType.ToString();
                viewModel.PeriodeTypes = _dropdownService.GetPeriodeTypesForKpiTargetAndAchievement().MapTo <SelectListItem>();
                return(View("Update", viewModel));
            }
            return(base.ErrorPage(response.Message));
        }
Esempio n. 11
0
        public ActionResult UpdatePartial(int id, string periodeType)
        {
            int         pmsSummaryId = id;
            PeriodeType pType        = (PeriodeType)Enum.Parse(typeof(PeriodeType), periodeType);

            var request = new GetKpiAchievementsRequest {
                PeriodeType = pType, PmsSummaryId = pmsSummaryId
            };
            var    response = _kpiAchievementService.GetKpiAchievements(request);
            string view     = pType == PeriodeType.Yearly ? "_yearly" : "_monthly";

            if (response.IsSuccess)
            {
                var viewModel = response.MapTo <UpdateKpiAchievementsViewModel>();
                viewModel.PeriodeType  = pType.ToString();
                viewModel.PmsSummaryId = pmsSummaryId;
                return(PartialView(view, viewModel));
            }

            return(Content(response.Message));
        }
Esempio n. 12
0
        public GetKpiTargetItemResponse GetKpiTarget(int kpiId, DateTime date, PeriodeType periodeType)
        {
            var response = new GetKpiTargetItemResponse();

            var kpiTarget = DataContext.KpiTargets
                            .Include(x => x.Kpi)
                            .Where(x => x.PeriodeType == periodeType &&
                                   x.Periode == date && x.Kpi.Id == kpiId).FirstOrDefault();

            if (kpiTarget != null)
            {
                response.Kpi = new GetKpiTargetItemResponse.KpiResponse
                {
                    Id   = kpiTarget.Kpi.Id,
                    Name = kpiTarget.Kpi.Name
                };
                response.Value       = kpiTarget.Value;
                response.Periode     = kpiTarget.Periode;
                response.PeriodeType = kpiTarget.PeriodeType;
            }

            return(response);
        }
Esempio n. 13
0
        private IList<GetCartesianChartDataResponse.SeriesResponse> _getKpiEconomicSeries(IList<GetCartesianChartDataRequest.SeriesRequest> configSeries, PeriodeType periodeType, IList<DateTime> dateTimePeriodes, string seriesType, RangeFilter rangeFilter, string graphicType, out string newTimeInformation, out IList<DateTime> newDatetimePeriodes, bool comparison = false, bool asNetbackChart = false)
        {
            var seriesResponse = new List<GetCartesianChartDataResponse.SeriesResponse>();
            var start = rangeFilter == RangeFilter.AllExistingYears ? DateTime.Now : dateTimePeriodes[0];
            var end = rangeFilter == RangeFilter.AllExistingYears ? DateTime.Now : dateTimePeriodes[dateTimePeriodes.Count - 1];
            var scenarioId = 0;
            var scenario = DataContext.Scenarios.FirstOrDefault(x => x.IsDashboard == true);
            if (scenario != null)
            {
                scenarioId = scenario.Id;
            }
            newTimeInformation = null;
            newDatetimePeriodes = new List<DateTime>();
            foreach (var series in configSeries)
            {

                if (series.Stacks.Count == 0)
                {
                    IList<KeyOperationData> kpiEconomics = new List<KeyOperationData>();
                    if (rangeFilter == RangeFilter.AllExistingYears)
                    {
                        kpiEconomics = DataContext.KeyOperationDatas.Where(x => x.PeriodeType == periodeType &&
                            x.Kpi.Id == series.KpiId && x.Scenario.Id == scenarioId)
                    .OrderBy(x => x.Periode).ToList();
                    }
                    else
                    {
                        kpiEconomics = DataContext.KeyOperationDatas.Where(x => x.PeriodeType == periodeType &&
                          x.Periode >= start && x.Periode <= end && x.Kpi.Id == series.KpiId && x.Scenario.Id == scenarioId)
                          .OrderBy(x => x.Periode).ToList();
                    }

                    if ((periodeType == PeriodeType.Hourly && rangeFilter == RangeFilter.CurrentHour) ||
                        (periodeType == PeriodeType.Daily && rangeFilter == RangeFilter.CurrentDay) ||
                        (periodeType == PeriodeType.Monthly && rangeFilter == RangeFilter.CurrentMonth) ||
                        (periodeType == PeriodeType.Yearly && rangeFilter == RangeFilter.CurrentYear))
                    {
                        var kpiEconomic = DataContext.KeyOperationDatas.Where(x => x.PeriodeType == periodeType &&
                      x.Periode <= end && x.Kpi.Id == series.KpiId && (x.Value != null && x.Value.Value != 0) && x.Scenario.Id == scenarioId)
                      .OrderByDescending(x => x.Periode).FirstOrDefault();
                        if (kpiEconomic != null)
                        {
                            kpiEconomics = new List<KeyOperationData> { kpiEconomic };
                            switch (periodeType)
                            {
                                case PeriodeType.Hourly:
                                    newTimeInformation = kpiEconomic.Periode.ToString(DateFormat.Hourly, CultureInfo.InvariantCulture);
                                    break;
                                case PeriodeType.Daily:
                                    newTimeInformation = kpiEconomic.Periode.ToString("dd MMM yy", CultureInfo.InvariantCulture);
                                    break;
                                case PeriodeType.Monthly:
                                    newTimeInformation = kpiEconomic.Periode.ToString("MMM yy", CultureInfo.InvariantCulture);
                                    break;
                                case PeriodeType.Yearly:
                                    newTimeInformation = kpiEconomic.Periode.ToString(DateFormat.Yearly, CultureInfo.InvariantCulture);
                                    break;
                            }
                            dateTimePeriodes = new List<DateTime> { kpiEconomic.Periode };
                            newDatetimePeriodes = dateTimePeriodes;
                        }

                    }

                    if (seriesType == "multi-stacks-grouped")
                    {
                        var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = series.Label,
                            Stack = series.Label,
                            Color = series.Color,
                            Order = series.Order
                        };
                        if (asNetbackChart)
                        {
                            var sumValue = kpiEconomics.Sum(x => x.Value);
                            aSeries.BorderColor = "transparent";
                            aSeries.Data.Add(sumValue);
                            if (newTimeInformation == null && newDatetimePeriodes.Count == 0)
                            {
                                if (rangeFilter == RangeFilter.AllExistingYears)
                                {
                                    newTimeInformation = "2011 - 2030";
                                    newDatetimePeriodes = new List<DateTime> { new DateTime(2011, 1, 1, 0, 0, 0), new DateTime(2030, 1, 1, 0, 0, 0) };
                                }
                                else
                                {
                                    switch (periodeType)
                                    {
                                        case PeriodeType.Hourly:
                                            newTimeInformation = start.ToString(DateFormat.Hourly, CultureInfo.InvariantCulture) + " - " + end.ToString(DateFormat.Hourly, CultureInfo.InvariantCulture);
                                            break;
                                        case PeriodeType.Daily:
                                            newTimeInformation = start.ToString("dd MMM yy", CultureInfo.InvariantCulture) + " - " + end.ToString("dd MMM yy", CultureInfo.InvariantCulture);
                                            break;
                                        case PeriodeType.Monthly:
                                            newTimeInformation = start.ToString("MMM yy", CultureInfo.InvariantCulture) + " - " + end.ToString("MMM yy", CultureInfo.InvariantCulture);
                                            break;
                                        case PeriodeType.Yearly:
                                            newTimeInformation = start.ToString(DateFormat.Yearly, CultureInfo.InvariantCulture) + " - " + end.ToString(DateFormat.Yearly, CultureInfo.InvariantCulture);
                                            break;
                                    }
                                    dateTimePeriodes = new List<DateTime> { start, end };
                                    newDatetimePeriodes = dateTimePeriodes;
                                }
                            }

                        }
                        else if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                        {

                            foreach (var periode in dateTimePeriodes)
                            {
                                var economicValue = kpiEconomics.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                if (economicValue == null || !economicValue.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(economicValue.Value);
                                }
                            }

                        }
                        else
                        {
                            foreach (var periode in dateTimePeriodes)
                            {
                                var target = kpiEconomics.Where(x => x.Periode == periode).FirstOrDefault();
                                if (target == null || !target.Value.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(target.Value.Value);
                                }
                            }
                        }

                        if (graphicType == "baraccumulative")
                        {
                            var previousSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = "Previous Accumulation",
                                Color = string.IsNullOrEmpty(series.PreviousColor) ? "#004071" : series.PreviousColor,
                                Stack = series.Label,
                                Order = series.Order
                            };
                            for (var i = 0; i < aSeries.Data.Count; i++)
                            {
                                double data = 0;
                                for (var j = 0; j < i; j++)
                                {
                                    data += aSeries.Data[j].HasValue ? aSeries.Data[j].Value : 0;
                                }
                                previousSeries.Data.Add(data);
                            }
                            seriesResponse.Add(previousSeries);
                        }
                        seriesResponse.Add(aSeries);
                        if (asNetbackChart && seriesResponse.Count > 1)
                        {
                            var invicibleSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = "invisible_" + series.Label,
                                Stack = series.Label,
                                Color = "transparent",
                                BorderColor = "transparent",
                                ShowInLegend = false
                            };
                            invicibleSeries.Data.Add(seriesResponse[seriesResponse.Count - 2].Data[0] - seriesResponse[seriesResponse.Count - 1].Data[0]);
                            seriesResponse.Add(invicibleSeries);
                        }
                    }
                    else
                    {
                        var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = series.Label,
                            Color = series.Color,
                            Order = series.Order
                        };
                        if (comparison)
                        {
                            aSeries.Stack = "KpiTarget";
                        }
                        if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                        {

                            foreach (var periode in dateTimePeriodes)
                            {
                                var targetValue = kpiEconomics.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                if (targetValue == null || !targetValue.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(targetValue.Value);
                                }
                            }
                        }
                        else
                        {
                            foreach (var periode in dateTimePeriodes)
                            {
                                var target = kpiEconomics.Where(x => x.Periode == periode).FirstOrDefault();
                                if (target == null || !target.Value.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(target.Value.Value);
                                }
                            }
                        }

                        if (graphicType == "baraccumulative")
                        {
                            var previousSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = "Previous Accumulation",
                                Color = string.IsNullOrEmpty(series.PreviousColor) ? "#004071" : series.PreviousColor,
                                Order = series.Order
                            };
                            if (comparison)
                            {
                                previousSeries.Stack = "KpiTarget";
                            }
                            for (var i = 0; i < aSeries.Data.Count; i++)
                            {
                                double data = 0;
                                for (var j = 0; j < i; j++)
                                {
                                    data += aSeries.Data[j].HasValue ? aSeries.Data[j].Value : 0;
                                }
                                previousSeries.Data.Add(data);
                            }
                            seriesResponse.Add(previousSeries);
                        }
                        seriesResponse.Add(aSeries);
                    }

                }
                else
                {
                    foreach (var stack in series.Stacks)
                    {
                        var kpiEconomics = DataContext.KeyOperationDatas.Where(x => x.PeriodeType == periodeType &&
                        x.Periode >= start && x.Periode <= end && x.Kpi.Id == stack.KpiId && x.Scenario.Id == scenarioId)
                        .OrderBy(x => x.Periode).ToList();

                        if ((periodeType == PeriodeType.Hourly && rangeFilter == RangeFilter.CurrentHour) ||
                        (periodeType == PeriodeType.Daily && rangeFilter == RangeFilter.CurrentDay) ||
                        (periodeType == PeriodeType.Monthly && rangeFilter == RangeFilter.CurrentMonth) ||
                        (periodeType == PeriodeType.Yearly && rangeFilter == RangeFilter.CurrentYear))
                        {
                            var kpiEconomic = DataContext.KeyOperationDatas.Where(x => x.PeriodeType == periodeType &&
                          x.Periode <= end && x.Kpi.Id == stack.KpiId && (x.Value != null && x.Value.Value != 0))
                          .OrderByDescending(x => x.Periode).FirstOrDefault();
                            if (kpiEconomic != null)
                            {
                                kpiEconomics = new List<KeyOperationData> { kpiEconomic };
                                switch (periodeType)
                                {
                                    case PeriodeType.Hourly:
                                        newTimeInformation = kpiEconomic.Periode.ToString(DateFormat.Hourly, CultureInfo.InvariantCulture);
                                        break;
                                    case PeriodeType.Daily:
                                        newTimeInformation = kpiEconomic.Periode.ToString("dd MMM yy", CultureInfo.InvariantCulture);
                                        break;
                                    case PeriodeType.Monthly:
                                        newTimeInformation = kpiEconomic.Periode.ToString("MMM yy", CultureInfo.InvariantCulture);
                                        break;
                                    case PeriodeType.Yearly:
                                        newTimeInformation = kpiEconomic.Periode.ToString(DateFormat.Yearly, CultureInfo.InvariantCulture);
                                        break;
                                }
                                dateTimePeriodes = new List<DateTime> { kpiEconomic.Periode };
                                newDatetimePeriodes = dateTimePeriodes;
                            }

                        }

                        if (seriesType == "multi-stacks-grouped")
                        {
                            var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = stack.Label,
                                Stack = series.Label,
                                Color = stack.Color,
                                Order = series.Order
                            };
                            if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                            {

                                foreach (var periode in dateTimePeriodes)
                                {
                                    var economicValue = kpiEconomics.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                        .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                    if (economicValue == null || !economicValue.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(economicValue.Value);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var periode in dateTimePeriodes)
                                {
                                    var economic = kpiEconomics.Where(x => x.Periode == periode).FirstOrDefault();
                                    if (economic == null || !economic.Value.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(economic.Value.Value);
                                    }
                                }
                            }
                            seriesResponse.Add(aSeries);
                        }
                        else
                        {

                            var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = stack.Label,
                                Color = stack.Color,
                                Order = series.Order
                            };
                            if (comparison)
                            {
                                aSeries.Stack = "KpiTarget";
                            }
                            if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                            {

                                foreach (var periode in dateTimePeriodes)
                                {
                                    var economicValue = kpiEconomics.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                        .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                    if (economicValue == null || !economicValue.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(economicValue.Value);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var periode in dateTimePeriodes)
                                {
                                    var economic = kpiEconomics.Where(x => x.Periode == periode).FirstOrDefault();
                                    if (economic == null || !economic.Value.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(economic.Value.Value);
                                    }
                                }
                            }
                            seriesResponse.Add(aSeries);
                        }
                    }
                }
            }
            return seriesResponse;
        }
Esempio n. 14
0
        private ReadExcelFileModel _ReadExcelFile(string filename)
        {
            var      listPrev = new List <UpdateKpiAchievementsViewModel.KpiAchievementItem>();
            var      response = new ReadExcelFileModel();
            var      file     = Server.MapPath(filename);
            Workbook workbook = new Workbook();

            using (FileStream stream = new FileStream(file, FileMode.Open))
            {
                workbook.LoadDocument(stream, DocumentFormat.OpenXml);
                foreach (var worksheet in workbook.Worksheets)
                {
                    string[] name = worksheet.Name.Split('_');
                    //if (name.Count() > 0 && name[0] != "Sheet1" && (name[0] == PeriodeType.Daily.ToString() || name[0] == PeriodeType.Hourly.ToString() || name[0] == PeriodeType.Monthly.ToString() || name[0] == PeriodeType.Weekly.ToString() || name[0] == PeriodeType.Yearly.ToString()))
                    if (name[0] == "Daily" || name[0] == "Monthly" || name[0] == "Yearly")
                    {
                        string      periodType = name[0];
                        PeriodeType pType      = string.IsNullOrEmpty(periodType)
                            ? PeriodeType.Yearly
                            : (PeriodeType)Enum.Parse(typeof(PeriodeType), periodType);
                        string   period = name[name.Count() - 1];
                        string[] periodes = null;
                        int      tahun, bulan;
                        //validate and switch value by periodType
                        if (periodType != period && !string.IsNullOrEmpty(period))
                        {
                            switch (periodType)
                            {
                            case "Daily":
                                periodes = period.Split('-');
                                tahun    = int.Parse(periodes[0]);
                                bulan    = int.Parse(periodes[periodes.Count() - 1]);
                                break;

                            case "Monthly":
                                tahun = int.Parse(period);
                                break;

                            case "Yearly":
                            default:
                                break;
                            }
                        }

                        //coba baca value
                        workbook.Worksheets.ActiveWorksheet = worksheet;
                        //get row

                        Range    range      = worksheet.GetUsedRange();
                        int      rows       = range.RowCount;
                        int      column     = range.ColumnCount - 2;
                        int      Kpi_Id     = 0;
                        DateTime periodData = new DateTime();
                        double?  nilai      = null;
                        for (int i = 1; i < rows; i++)
                        {
                            //get rows
                            for (int j = 0; j < column; j++)
                            {
                                var prepareDataContainer = new UpdateKpiAchievementsViewModel.KpiAchievementItem();
                                //get rows header and period
                                if (j == 0)
                                {
                                    if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                    {
                                        Kpi_Id = int.Parse(worksheet.Cells[i, j].Value.ToString());
                                    }
                                }
                                else if (j > 1)
                                {
                                    if (worksheet.Cells[0, j].Value.Type == CellValueType.DateTime)
                                    {
                                        periodData = DateTime.Parse(worksheet.Cells[0, j].Value.ToString());
                                    }
                                    if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                    {
                                        nilai = double.Parse(worksheet.Cells[i, j].Value.ToString());
                                    }
                                    else
                                    {
                                        nilai = null;
                                    }

                                    if (nilai != null)
                                    {
                                        prepareDataContainer.Value       = nilai;
                                        prepareDataContainer.KpiId       = Kpi_Id;
                                        prepareDataContainer.Periode     = periodData;
                                        prepareDataContainer.PeriodeType = pType;
                                        var oldKpiAchievement = _kpiAchievementService.GetKpiAchievementByValue(new GetKpiAchievementRequestByValue {
                                            Kpi_Id = Kpi_Id, periode = periodData, PeriodeType = periodType
                                        });
                                        if (oldKpiAchievement.IsSuccess)
                                        {
                                            prepareDataContainer.Id = oldKpiAchievement.Id;
                                        }
                                        var request = prepareDataContainer.MapTo <UpdateKpiAchievementItemRequest>();
                                        _kpiAchievementService.UpdateKpiAchievementItem(request);
                                    }
                                    //listPrev.Add(prepareDataContainer);
                                }
                            }
                        }
                        //DataTable dataTable = worksheet.CreateDataTable(range, true);
                        //for (int col = 0; col < range.ColumnCount; col++)
                        //{
                        //    //CellValueType cellType = range[0, col].Value.Type;
                        //    for (int r = 1; r < range.RowCount; r++)
                        //    {
                        //        //if (cellType != range[r, col].Value.Type)
                        //        //{
                        //        //    dataTable.Columns[col].DataType = typeof(string);
                        //        //    break;
                        //        //}
                        //    }
                        //}

                        response.isSuccess = true;
                    }
                    else
                    {
                        response.isSuccess = false;
                        response.Message   = "File Not Valid";
                        break;
                    }
                }
            }
            return(response);
        }
        private ReadExcelFileModel _ReadExcelFile(string filename)
        {
            var response = new ReadExcelFileModel();

            try
            {
                int inserted = 0;
                int skipped  = 0;
                int rejected = 0;
                var listPrev = new List <UpdateKpiAchievementsViewModel.KpiAchievementItem>();

                var      file     = Server.MapPath(filename);
                var      userId   = UserProfile().UserId;
                Workbook workbook = new Workbook();
                using (FileStream stream = new FileStream(file, FileMode.Open))
                {
                    workbook.LoadDocument(stream, DevExpress.Spreadsheet.DocumentFormat.OpenXml);
                    foreach (var worksheet in workbook.Worksheets)
                    {
                        string[] name = worksheet.Name.Split('_');
                        //if (name.Count() > 0 && name[0] != "Sheet1" && (name[0] == PeriodeType.Daily.ToString() || name[0] == PeriodeType.Hourly.ToString() || name[0] == PeriodeType.Monthly.ToString() || name[0] == PeriodeType.Weekly.ToString() || name[0] == PeriodeType.Yearly.ToString()))
                        if (name[0] == "Daily" || name[0] == "Monthly" || name[0] == "Yearly")
                        {
                            string      periodType = name[0];
                            PeriodeType pType      = string.IsNullOrEmpty(periodType)
                                                    ? PeriodeType.Yearly
                                                    : (PeriodeType)Enum.Parse(typeof(PeriodeType), periodType);
                            string   period = name[name.Count() - 1];
                            string[] periodes = null;
                            int      tahun, bulan;
                            //validate and switch value by periodType
                            if (periodType != period && !string.IsNullOrEmpty(period))
                            {
                                switch (periodType)
                                {
                                case "Daily":
                                    periodes = period.Split('-');
                                    tahun    = int.Parse(periodes[0]);
                                    bulan    = int.Parse(periodes[periodes.Count() - 1]);
                                    break;

                                case "Monthly":
                                    tahun = int.Parse(period);
                                    break;

                                case "Yearly":
                                default:
                                    break;
                                }
                            }

                            //coba baca value
                            workbook.Worksheets.ActiveWorksheet = worksheet;
                            //get row

                            Range    range      = worksheet.GetUsedRange();
                            int      rows       = range.RowCount;
                            int      column     = range.ColumnCount - 2;
                            int      kpiId      = 0;
                            DateTime periodData = new DateTime();
                            double?  nilai      = null;
                            for (int i = 1; i < rows; i++)
                            {
                                //get rows
                                for (int j = 0; j < column; j++)
                                {
                                    bool fromExistedToNull    = false;
                                    var  prepareDataContainer = new UpdateKpiAchievementsViewModel.KpiAchievementItem();
                                    //get rows header and period
                                    if (j == 0)
                                    {
                                        if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                        {
                                            kpiId = int.Parse(worksheet.Cells[i, j].Value.ToString());
                                        }
                                    }
                                    else if (j > 1)
                                    {
                                        if (worksheet.Cells[0, j].Value.Type == CellValueType.DateTime)
                                        {
                                            periodData = DateTime.Parse(worksheet.Cells[0, j].Value.ToString());
                                        }

                                        if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                        {
                                            nilai = double.Parse(worksheet.Cells[i, j].Value.ToString());
                                        }
                                        else if (worksheet.Cells[i, j].Value.Type == CellValueType.Text)
                                        {
                                            fromExistedToNull = true;
                                            nilai             = null;
                                        }
                                        else
                                        {
                                            nilai = null;
                                        }

                                        bool isValidKpi = false;
                                        if (!this.UserProfile().IsSuperAdmin)
                                        {
                                            skipped++;
                                            isValidKpi =
                                                _kpiService.IsValidKpi(new Services.Requests.Kpi.GetKpiByRole
                                            {
                                                RoleId = this.UserProfile().RoleId
                                            });
                                        }
                                        else
                                        {
                                            isValidKpi = true;
                                        }

                                        if (isValidKpi && (nilai != null || fromExistedToNull))
                                        {
                                            prepareDataContainer.Value       = nilai.ToString();
                                            prepareDataContainer.KpiId       = kpiId;
                                            prepareDataContainer.Periode     = periodData;
                                            prepareDataContainer.PeriodeType = pType;
                                            var oldKpiAchievement =
                                                _kpiAchievementService.GetKpiAchievementByValue(
                                                    new GetKpiAchievementRequestByValue
                                            {
                                                KpiId       = kpiId,
                                                Periode     = periodData,
                                                PeriodeType = periodType
                                            });
                                            if (oldKpiAchievement.IsSuccess)
                                            {
                                                prepareDataContainer.Id = oldKpiAchievement.Id;
                                            }
                                            else
                                            {
                                                var fixedError = false;
                                                if (oldKpiAchievement.ExceptionType != null &&
                                                    oldKpiAchievement.ExceptionType ==
                                                    typeof(InvalidOperationException))
                                                {
                                                    //var delete = _kpiAchievementService.DeleteKpiAchievement(kpiId, periodData, pType);
                                                    var delete = _kpiAchievementService.DeleteKpiAchievement(new DeleteKpiAchievementRequest {
                                                        kpiId          = kpiId,
                                                        periode        = periodData,
                                                        periodeType    = pType,
                                                        ControllerName = "KPI Achievement",
                                                        ActionName     = "Read Excel File",
                                                        UserId         = UserProfile().UserId
                                                    });
                                                    fixedError = delete.IsSuccess;
                                                }

                                                if (!fixedError)
                                                {
                                                    throw new Exception(string.Format(@"KPI with id {0} and periode {1} and periode type {2} can't be inserted", kpiId, periodData.ToShortDateString(), pType.ToString()));
                                                }
                                            }
                                            var request = prepareDataContainer.MapTo <UpdateKpiAchievementItemRequest>();
                                            request.UserId     = userId;
                                            request.UpdateFrom = "KPIAchievementForm";
                                            var insert = _kpiAchievementService.UpdateKpiAchievementItem(request);
                                            if (insert.IsSuccess)
                                            {
                                                inserted++;
                                            }
                                            else
                                            {
                                                rejected++;
                                            }
                                        }
                                    }
                                }
                            }

                            response.isSuccess = true;
                            response.Message   = "Success :" + inserted + "\r\n";
                            response.Message  += "Skipped :" + skipped + "\r\n";
                            response.Message  += "Rejected :" + rejected + "\r\n";
                        }
                        else
                        {
                            response.isSuccess = false;
                            response.Message   = "File Not Valid";
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                response.Message   = exception.Message;
                response.isSuccess = false;
            }

            return(response);
        }
        private BaseResponse _ReadExcelFile(string filename, int scenarioId, string configType)
        {
            var         response = new BaseResponse();
            string      periodType = string.Empty;
            PeriodeType pType = PeriodeType.Yearly;
            int         tahun = DateTime.Now.Year, bulan = DateTime.Now.Month;
            List <OperationDataConfigurationViewModel.Item> list_data = new List <OperationDataConfigurationViewModel.Item>();

            if (filename != Path.GetFullPath(filename))
            {
                filename = Server.MapPath(filename);
            }

            /*
             * cek file exist and return immediatelly if not exist
             */
            if (!System.IO.File.Exists(filename))
            {
                response.IsSuccess = false;
                response.Message   = "File Not Found";
                return(response);
            }
            Workbook workbook = new Workbook();

            using (FileStream stream = new FileStream(filename, FileMode.Open))
            {
                workbook.LoadDocument(stream, DevExpress.Spreadsheet.DocumentFormat.OpenXml);
                #region foreach
                foreach (var worksheet in workbook.Worksheets)
                {
                    string[] name = worksheet.Name.Split('_');
                    if (name[0] == "Daily" || name[0] == "Monthly" || name[0] == "Yearly")
                    {
                        periodType = name[0];
                        pType      = string.IsNullOrEmpty(periodType)
                            ? PeriodeType.Yearly
                            : (PeriodeType)Enum.Parse(typeof(PeriodeType), periodType);
                        string   period   = name[name.Count() - 1];
                        string[] periodes = null;
                        //validate and switch value by periodType
                        if (periodType != period && !string.IsNullOrEmpty(period))
                        {
                            switch (periodType)
                            {
                            case "Daily":
                                periodes = period.Split('-');
                                tahun    = int.Parse(periodes[0]);
                                bulan    = int.Parse(periodes[periodes.Count() - 1]);
                                break;

                            case "Monthly":
                                tahun = int.Parse(period);
                                break;

                            case "Yearly":
                            default:
                                break;
                            }
                        }

                        workbook.Worksheets.ActiveWorksheet = worksheet;
                        //get row

                        Range      range      = worksheet.GetUsedRange();
                        int        rows       = range.RowCount;
                        int        column     = range.ColumnCount - 2;
                        int        Kpi_Id     = 0;
                        DateTime   periodData = new DateTime();
                        double?    nilai      = null;
                        List <int> list_Kpi   = new List <int>();

                        for (int i = 1; i < rows; i++)
                        {
                            for (int j = 0; j < column; j++)
                            {
                                if (j == 0)
                                {
                                    if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                    {
                                        int Kpis_Id = int.Parse(worksheet.Cells[i, j].Value.ToString());
                                        list_Kpi.Add(Kpis_Id);
                                    }
                                }
                            }
                        }
                        var operationsId = _operationConfigService.GetOperationIn(new GetOperationsInRequest {
                            KpiIds = list_Kpi
                        });

                        //get rows
                        for (int i = 1; i < rows; i++)
                        {
                            for (int j = 0; j < column; j++)
                            {
                                bool fromExistedToNull = false;
                                if (j == 0)
                                {
                                    if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                    {
                                        Kpi_Id = int.Parse(worksheet.Cells[i, j].Value.ToString());
                                    }
                                }
                                else if (j > 1)
                                {
                                    var operationId = 0;
                                    var operation   = operationsId.KeyOperations.FirstOrDefault(x => x.KpiId == Kpi_Id);
                                    if (operation != null)
                                    {
                                        operationId = operation.Id;
                                    }

                                    if (worksheet.Cells[0, j].Value.Type == CellValueType.DateTime)
                                    {
                                        periodData = DateTime.Parse(worksheet.Cells[0, j].Value.ToString());
                                    }
                                    if (worksheet.Cells[i, j].Value.Type == CellValueType.Numeric)
                                    {
                                        nilai = double.Parse(worksheet.Cells[i, j].Value.ToString());
                                    }
                                    else if (worksheet.Cells[i, j].Value.Type == CellValueType.Text)
                                    {
                                        fromExistedToNull = true;
                                        nilai             = null;
                                    }
                                    else
                                    {
                                        nilai = null;
                                    }



                                    if (nilai != null || fromExistedToNull)
                                    {
                                        // try to cacth and update
                                        var data = new OperationDataConfigurationViewModel.Item()
                                        {
                                            Value = nilai, KpiId = Kpi_Id, Periode = periodData, PeriodeType = pType, ScenarioId = scenarioId, OperationId = operationId
                                        };
                                        list_data.Add(data);
                                        //switch (configType)
                                        //{
                                        //    case "KpiTarget":
                                        //        response = this._UpdateKpiTarget(data);
                                        //        break;
                                        //    case "KpiAchievement":
                                        //        response = this._UpdateKpiAchievement(data);
                                        //        break;
                                        //    case "Economic":
                                        //        response = this._UpdateEconomic(data);
                                        //        break;
                                        //    default:
                                        //        response.IsSuccess = false;
                                        //        response.Message = "No Table Selected";
                                        //        break;
                                        //}
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        response.IsSuccess = false;
                        response.Message   = "File Not Valid";
                        break;
                    }
                    switch (configType)
                    {
                    //case "KpiTarget":
                    //    response = this._UpdateKpiTarget(list_data);
                    //    break;
                    //case "KpiAchievement":
                    //    response = this._UpdateKpiAchievement(list_data, pType.ToString(), tahun, bulan);
                    //    break;
                    case "Economic":
                        response = this._UpdateEconomic(list_data);
                        break;

                    default:
                        response.IsSuccess = false;
                        response.Message   = "No Table Selected";
                        break;
                    }
                }
                #endregion
            }

            //here to read excel fileController
            return(response);
        }
Esempio n. 17
0
        public FileResult DownloadTemplate(DownloadTemplateViewModel vModel)
        {
            ConfigType config = string.IsNullOrEmpty(vModel.ConfigType) ? ConfigType.KpiTarget
                                    : (ConfigType)Enum.Parse(typeof(ConfigType), vModel.ConfigType);

            #region Get Data
            PeriodeType pType = string.IsNullOrEmpty(vModel.PeriodeType) ? PeriodeType.Yearly
                            : (PeriodeType)Enum.Parse(typeof(PeriodeType), vModel.PeriodeType);

            var viewModel = new ConfigurationViewModel();
            switch (config)
            {
            case ConfigType.KpiTarget:
            {
                var request = new GetKpiTargetsConfigurationRequest()
                {
                    PeriodeType = vModel.PeriodeType,
                    Year        = vModel.Year,
                    Month       = vModel.Month,
                    RoleGroupId = vModel.RoleGroupId
                };
                var target = _kpiTargetService.GetKpiTargetsConfiguration(request);
                viewModel = target.MapTo <ConfigurationViewModel>();
                break;
            }

            case ConfigType.KpiAchievement:
            {
                var request = new GetKpiAchievementsConfigurationRequest()
                {
                    PeriodeType = vModel.PeriodeType,
                    Year        = vModel.Year,
                    Month       = vModel.Month,
                    RoleGroupId = vModel.RoleGroupId
                };
                var achievement = _kpiAchievementService.GetKpiAchievementsConfiguration(request);
                viewModel = achievement.MapTo <ConfigurationViewModel>();
                break;
            }

            case ConfigType.OperationData:
            {
                var request = vModel.MapTo <GetOperationDataConfigurationRequest>();
                request.PeriodeType = pType;
                request.IsPartial   = false;
                var operationData = _operationDataService.GetOperationDataConfiguration(request);
                viewModel = operationData.MapTo <ConfigurationViewModel>();
                //return new FileContentResult(null, "application/octet-stream") { FileDownloadName = "as" };
                break;
            }

            default:
                break;
            }
            #endregion

            /*
             * Find and Create Directory
             */
            var resultPath = Server.MapPath(string.Format("{0}{1}/", TemplateDirectory, vModel.ConfigType));
            if (!Directory.Exists(resultPath))
            {
                Directory.CreateDirectory(resultPath);
            }


            #region parsing data to excel
            string dateFormat    = string.Empty;
            string workSheetName = new StringBuilder(vModel.PeriodeType).ToString();
            switch (vModel.PeriodeType)
            {
            case "Yearly":
                dateFormat = "yyyy";
                break;

            case "Monthly":
                dateFormat    = "mmm-yy";
                workSheetName = string.Format("{0}_{1}", workSheetName, vModel.Year);
                break;

            default:
                dateFormat    = "dd-mmm-yy";
                workSheetName = string.Format("{0}_{1}-{2}", workSheetName, vModel.Year, vModel.Month.ToString().PadLeft(2, '0'));
                break;
            }

            string fileName = string.Format(@"{0}_{1}_{2}.xlsx", vModel.ConfigType, vModel.PeriodeType, DateTime.Now.ToString("yyyymmddMMss"));

            IWorkbook workbook  = new Workbook();
            Worksheet worksheet = workbook.Worksheets[0];

            worksheet.Name = workSheetName;
            workbook.Worksheets.ActiveWorksheet = worksheet;
            RowCollection    rows    = workbook.Worksheets[0].Rows;
            ColumnCollection columns = workbook.Worksheets[0].Columns;

            Row headerRow = rows[0];
            headerRow.FillColor            = Color.DarkGray;
            headerRow.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
            headerRow.Alignment.Vertical   = SpreadsheetVerticalAlignment.Center;
            Column kpiIdColumn   = columns[0];
            Column kpiNameColumn = columns[1];
            kpiIdColumn.Visible = false;

            headerRow.Worksheet.Cells[headerRow.Index, kpiIdColumn.Index].Value   = "KPI ID";
            headerRow.Worksheet.Cells[headerRow.Index, kpiNameColumn.Index].Value = "KPI Name";
            int i = 1; //i for row
            #region inserting from models
            foreach (var kpi in viewModel.Kpis)
            {
                worksheet.Cells[i, kpiIdColumn.Index].Value   = kpi.Id;
                worksheet.Cells[i, kpiNameColumn.Index].Value = string.Format("{0} ({1})", kpi.Name, kpi.Measurement);
                int j     = 2; // for column
                var items = new List <ConfigurationViewModel.Item>();
                switch (vModel.ConfigType)
                {
                case "KpiTarget":
                {
                    foreach (var target in kpi.KpiTargets)
                    {
                        var item = new ConfigurationViewModel.Item
                        {
                            Id          = target.Id,
                            KpiId       = kpi.Id,
                            Periode     = target.Periode,
                            Remark      = target.Remark,
                            Value       = target.Value.HasValue ? target.Value.ToString() : string.Empty,
                            PeriodeType = pType
                        };
                        items.Add(item);
                    }
                    break;
                }

                case "KpiAchievement":
                {
                    foreach (var achievement in kpi.KpiAchievements)
                    {
                        var item = new ConfigurationViewModel.Item()
                        {
                            Id          = achievement.Id,
                            KpiId       = kpi.Id,
                            Periode     = achievement.Periode,
                            Remark      = achievement.Remark,
                            Value       = achievement.Value.HasValue ? achievement.Value.ToString() : string.Empty,
                            PeriodeType = pType
                        };
                        items.Add(item);
                    }
                    break;
                }

                case "OperationData":
                {
                    //items = kpi.OperationData.MapTo<ConfigurationViewModel.Item>();
                    foreach (var operationData in kpi.OperationData)
                    {
                        var item = new ConfigurationViewModel.Item()
                        {
                            Id          = operationData.Id,
                            KpiId       = kpi.Id,
                            Periode     = operationData.Periode,
                            Remark      = operationData.Remark,
                            Value       = operationData.Value.HasValue ? operationData.Value.ToString() : string.Empty,
                            PeriodeType = pType
                        };
                        items.Add(item);
                    }
                    break;
                }
                }

                foreach (var item in items)
                {
                    worksheet.Cells[headerRow.Index, j].Value        = item.Periode;
                    worksheet.Cells[headerRow.Index, j].NumberFormat = dateFormat;
                    worksheet.Cells[headerRow.Index, j].AutoFitColumns();

                    worksheet.Cells[i, j].Value        = item.RealValue;
                    worksheet.Cells[i, j].NumberFormat = "#,0.#0";
                    worksheet.Columns[j].AutoFitColumns();
                    j++;
                }

                Column totalValueColumn = worksheet.Columns[j];
                if (i == headerRow.Index + 1)
                {
                    worksheet.Cells[headerRow.Index, totalValueColumn.Index].Value     = "Average";
                    worksheet.Cells[headerRow.Index, totalValueColumn.Index + 1].Value = "SUM";
                    Range r1 = worksheet.Range.FromLTRB(kpiNameColumn.Index + 1, i, j - 1, i);
                    worksheet.Cells[i, j].Formula     = string.Format("=AVERAGE({0})", r1.GetReferenceA1());
                    worksheet.Cells[i, j + 1].Formula = string.Format("=SUM({0})", r1.GetReferenceA1());
                }
                else
                {
                    // add formula
                    Range r2 = worksheet.Range.FromLTRB(kpiNameColumn.Index + 1, i, j - 1, i);
                    worksheet.Cells[i, j].Formula     = string.Format("=AVERAGE({0})", r2.GetReferenceA1());
                    worksheet.Cells[i, j + 1].Formula = string.Format("=SUM({0})", r2.GetReferenceA1());
                }
                i++;
            }
            #endregion
            kpiNameColumn.AutoFitColumns();
            worksheet.FreezePanes(headerRow.Index, kpiNameColumn.Index);

            string resultFilePath = string.Format("{0},{1}", resultPath, fileName);
            //System.Web.HttpContext.Current.Request.MapPath(resultPath + fileName);
            //System.Web.HttpContext.Current.Response.Clear();
            //System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //System.Web.HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}", fileName));

            using (FileStream stream = new FileStream(resultFilePath, FileMode.Create, FileAccess.ReadWrite))
            {
                workbook.SaveDocument(stream, DevExpress.Spreadsheet.DocumentFormat.Xlsx);
                stream.Close();
            }
            //System.Web.HttpContext.Current.Response.End();
            //workbook.SaveDocument(resultFilePath, DocumentFormat.OpenXml);
            //workbook.Dispose();
            #endregion

            string namafile  = Path.GetFileName(resultFilePath);
            byte[] fileBytes = System.IO.File.ReadAllBytes(resultFilePath);
            var    response  = new FileContentResult(fileBytes, "application/octet-stream")
            {
                FileDownloadName = fileName
            };
            return(response);
        }
Esempio n. 18
0
        private IList<GetCartesianChartDataResponse.SeriesResponse> _getKpiActualSeries(IList<GetCartesianChartDataRequest.SeriesRequest> configSeries, PeriodeType periodeType, IList<DateTime> dateTimePeriodes, string seriesType, RangeFilter rangeFilter, string graphicType,out string newTimeInformation, out IList<DateTime> newDatetimePeriodes, bool comparison = false)
        {
            var seriesResponse = new List<GetCartesianChartDataResponse.SeriesResponse>();
            var start = dateTimePeriodes[0];
            var end = dateTimePeriodes[dateTimePeriodes.Count - 1];
            newTimeInformation = null;
            newDatetimePeriodes = new List<DateTime>();
            foreach (var series in configSeries)
            {

                if (series.Stacks.Count == 0)
                {
                    var kpiActuals = DataContext.KpiAchievements.Where(x => x.PeriodeType == periodeType &&
                      x.Periode >= start && x.Periode <= end && x.Kpi.Id == series.KpiId)
                      .OrderBy(x => x.Periode).ToList();

                    if ((periodeType == PeriodeType.Hourly && rangeFilter == RangeFilter.CurrentHour) ||
                       (periodeType == PeriodeType.Daily && rangeFilter == RangeFilter.CurrentDay) ||
                       (periodeType == PeriodeType.Monthly && rangeFilter == RangeFilter.CurrentMonth) ||
                       (periodeType == PeriodeType.Yearly && rangeFilter == RangeFilter.CurrentYear))
                    {
                        var kpiActual = DataContext.KpiAchievements.Where(x => x.PeriodeType == periodeType &&
                      x.Periode <= end && x.Kpi.Id == series.KpiId && (x.Value != null && x.Value.Value != 0))
                      .OrderByDescending(x => x.Periode).FirstOrDefault();
                        if (kpiActual != null)
                        {
                            kpiActuals = new List<KpiAchievement> { kpiActual };
                            switch (periodeType)
                            {
                                case PeriodeType.Hourly:
                                    newTimeInformation = kpiActual.Periode.ToString("dd/MMM/yyyy hh tt", CultureInfo.InvariantCulture);
                                    break;
                                case PeriodeType.Daily:
                                    newTimeInformation = kpiActual.Periode.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                                    break;
                                case PeriodeType.Monthly:
                                    newTimeInformation = kpiActual.Periode.ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                                    break;
                                case PeriodeType.Yearly:
                                    newTimeInformation = kpiActual.Periode.ToString("yyyy", CultureInfo.InvariantCulture);
                                    break;
                            }
                            dateTimePeriodes = new List<DateTime> { kpiActual.Periode };
                            newDatetimePeriodes = dateTimePeriodes;

                        }
                    }

                    if (seriesType == "multi-stacks-grouped" && graphicType == "baraccumulative")
                    {
                        var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = series.Label,
                            Stack = series.Label,
                            Color = series.Color
                        };
                        if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                        {

                            foreach (var periode in dateTimePeriodes)
                            {
                                var targetValue = kpiActuals.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                if (targetValue == null || !targetValue.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(targetValue.Value);
                                }
                            }
                        }
                        else
                        {
                            foreach (var periode in dateTimePeriodes)
                            {
                                var target = kpiActuals.Where(x => x.Periode == periode).FirstOrDefault();
                                if (target == null || !target.Value.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(target.Value.Value);
                                }
                            }
                        }

                        var previousSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = "Previous Accumulation",
                            Color = string.IsNullOrEmpty(series.PreviousColor) ? "#004071" : series.PreviousColor,
                            Stack = series.Label
                        };
                        for (var i = 0; i < aSeries.Data.Count; i++)
                        {
                            double data = 0;
                            for (var j = 0; j < i; j++)
                            {
                                data += aSeries.Data[j].HasValue ? aSeries.Data[j].Value : 0;
                            }
                            previousSeries.Data.Add(data);
                        }
                        seriesResponse.Add(previousSeries);
                        seriesResponse.Add(aSeries);
                    }
                    else if (seriesType == "multi-stacks" && graphicType == "baraccumulative")
                    {
                        var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = series.Label,
                            Color = series.Color
                        };
                        if (comparison)
                        {
                            aSeries.Stack = "KpiActual";
                        }
                        if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                        {

                            foreach (var periode in dateTimePeriodes)
                            {
                                var targetValue = kpiActuals.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                if (targetValue == null || !targetValue.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(targetValue.Value);
                                }
                            }
                        }
                        else
                        {
                            foreach (var periode in dateTimePeriodes)
                            {
                                var target = kpiActuals.Where(x => x.Periode == periode).FirstOrDefault();
                                if (target == null || !target.Value.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(target.Value.Value);
                                }
                            }
                        }

                        var previousSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = "Previous Accumulation",
                            Color = string.IsNullOrEmpty(series.PreviousColor) ? "#004071" : series.PreviousColor,
                        };
                        if (comparison)
                        {
                            previousSeries.Stack = "KpiActual";
                        }
                        for (var i = 0; i < aSeries.Data.Count; i++)
                        {
                            double data = 0;
                            for (var j = 0; j < i; j++)
                            {
                                data += aSeries.Data[j].HasValue ? aSeries.Data[j].Value : 0;
                            }
                            previousSeries.Data.Add(data);
                        }
                        seriesResponse.Add(previousSeries);
                        seriesResponse.Add(aSeries);
                    }
                    else if ((seriesType == "multi-stacks" || seriesType == "multi-stacks-grouped") && graphicType == "barachievement")
                    {
                        var kpiTargets = DataContext.KpiTargets.Where(x => x.PeriodeType == periodeType &&
                            x.Periode >= start && x.Periode <= end && x.Kpi.Id == series.KpiId)
                            .OrderBy(x => x.Periode).ToList();
                        if ((periodeType == PeriodeType.Hourly && rangeFilter == RangeFilter.CurrentHour) ||
                      (periodeType == PeriodeType.Daily && rangeFilter == RangeFilter.CurrentDay) ||
                      (periodeType == PeriodeType.Monthly && rangeFilter == RangeFilter.CurrentMonth) ||
                      (periodeType == PeriodeType.Yearly && rangeFilter == RangeFilter.CurrentYear))
                        {
                            if (kpiActuals.Count > 0)
                            {
                                var periode = kpiActuals.First().Periode;
                                kpiTargets = DataContext.KpiTargets.Where(x => x.PeriodeType == periodeType &&
                              x.Periode == periode && x.Kpi.Id == series.KpiId)
                              .OrderBy(x => x.Periode).ToList();
                            }

                        }
                        var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = series.Label,
                            Color = string.IsNullOrEmpty(series.Color) ? "blue" : series.Color
                        };
                        if (comparison)
                        {
                            aSeries.Stack = "KpiActual";
                        }
                        var remainSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = "Remain",
                            Color = "red"
                        };
                        if (comparison)
                        {
                            remainSeries.Stack = "KpiActual";
                        }
                        var exceedSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = "Exceed",
                            Color = "green"
                        };
                        if (seriesType == "multi-stacks-grouped")
                        {
                            aSeries.Stack = series.Label;
                            remainSeries.Stack = series.Label;
                            exceedSeries.Stack = series.Label;
                        }
                        if (comparison)
                        {
                            exceedSeries.Stack = "KpiActual";
                        }
                        foreach (var periode in dateTimePeriodes)
                        {
                            if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                            {
                                var actual = kpiActuals.Where(x => x.Periode <= periode)
                                    .GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                var target = kpiTargets.Where(x => x.Periode <= periode)
                                    .GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();

                                if (!actual.HasValue)
                                {
                                    if (!target.HasValue)
                                    {
                                        exceedSeries.Data.Add(0);
                                        remainSeries.Data.Add(0);
                                        aSeries.Data.Add(0);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(0);
                                        remainSeries.Data.Add(target.Value);
                                        exceedSeries.Data.Add(0);
                                    }
                                }
                                else
                                {
                                    if (!target.HasValue)
                                    {
                                        aSeries.Data.Add(target.Value);
                                        remainSeries.Data.Add(0);
                                        exceedSeries.Data.Add(actual.Value);
                                    }
                                    else
                                    {

                                        var remain = target.Value - actual.Value;
                                        if (remain > 0)
                                        {
                                            aSeries.Data.Add(actual.Value);
                                            remainSeries.Data.Add(remain);
                                            exceedSeries.Data.Add(0);
                                        }
                                        else
                                        {
                                            aSeries.Data.Add(target.Value);
                                            exceedSeries.Data.Add(-remain);
                                            remainSeries.Data.Add(0);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var actual = kpiActuals.Where(x => x.Periode == periode).FirstOrDefault();
                                var target = kpiTargets.Where(x => x.Periode == periode).FirstOrDefault();
                                if (actual == null || !actual.Value.HasValue)
                                {
                                    if (target == null || !target.Value.HasValue)
                                    {
                                        exceedSeries.Data.Add(0);
                                        remainSeries.Data.Add(0);
                                        aSeries.Data.Add(0);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(0);
                                        remainSeries.Data.Add(target.Value.Value);
                                        exceedSeries.Data.Add(0);
                                    }
                                }
                                else
                                {
                                    if (target == null || !target.Value.HasValue)
                                    {
                                        aSeries.Data.Add(target.Value.Value);
                                        remainSeries.Data.Add(0);
                                        exceedSeries.Data.Add(actual.Value.Value);
                                    }
                                    else
                                    {

                                        var remain = target.Value.Value - actual.Value.Value;
                                        if (remain > 0)
                                        {
                                            aSeries.Data.Add(actual.Value.Value);
                                            remainSeries.Data.Add(remain);
                                            exceedSeries.Data.Add(0);
                                        }
                                        else
                                        {
                                            aSeries.Data.Add(target.Value.Value);
                                            exceedSeries.Data.Add(-remain);
                                            remainSeries.Data.Add(0);
                                        }
                                    }
                                }
                            }

                        }
                        seriesResponse.Add(remainSeries);
                        seriesResponse.Add(exceedSeries);
                        seriesResponse.Add(aSeries);
                    }
                    else
                    {
                        //var kpiTargets = DataContext.KpiAchievements.Where(x => x.PeriodeType == periodeType &&
                        //     x.Periode >= start && x.Periode <= end && x.Kpi.Id == series.KpiId)
                        //     .OrderBy(x => x.Periode).ToList();
                        var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                        {
                            Name = series.Label,
                            Color = series.Color
                        };
                        if (comparison)
                        {
                            aSeries.Stack = "KpiActual";
                        }
                        if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                        {

                            foreach (var periode in dateTimePeriodes)
                            {
                                var targetValue = kpiActuals.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                    .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                if (targetValue == null || !targetValue.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(targetValue.Value);
                                }
                            }
                        }
                        else
                        {
                            foreach (var periode in dateTimePeriodes)
                            {
                                var target = kpiActuals.Where(x => x.Periode == periode).FirstOrDefault();
                                if (target == null || !target.Value.HasValue)
                                {
                                    aSeries.Data.Add(null);
                                }
                                else
                                {
                                    aSeries.Data.Add(target.Value.Value);
                                }
                            }
                        }

                        if (graphicType == "baraccumulative")
                        {
                            var previousSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = "Previous Accumulation",
                                Color = string.IsNullOrEmpty(series.PreviousColor) ? "#004071" : series.PreviousColor,
                            };
                            if (comparison)
                            {
                                previousSeries.Stack = "KpiActual";
                            }
                            for (var i = 0; i < aSeries.Data.Count; i++)
                            {
                                double data = 0;
                                for (var j = 0; j < i; j++)
                                {
                                    data += aSeries.Data[j].HasValue ? aSeries.Data[j].Value : 0;
                                }
                                previousSeries.Data.Add(data);
                            }
                            seriesResponse.Add(previousSeries);
                        }
                        seriesResponse.Add(aSeries);
                    }
                }
                else
                {
                    foreach (var stack in series.Stacks)
                    {
                        var kpiActuals = DataContext.KpiAchievements.Where(x => x.PeriodeType == periodeType &&
                        x.Periode >= start && x.Periode <= end && x.Kpi.Id == stack.KpiId)
                        .OrderBy(x => x.Periode).ToList();

                        if ((periodeType == PeriodeType.Hourly && rangeFilter == RangeFilter.CurrentHour) ||
                     (periodeType == PeriodeType.Daily && rangeFilter == RangeFilter.CurrentDay) ||
                     (periodeType == PeriodeType.Monthly && rangeFilter == RangeFilter.CurrentMonth) ||
                     (periodeType == PeriodeType.Yearly && rangeFilter == RangeFilter.CurrentYear))
                        {
                            var kpiActual = DataContext.KpiAchievements.Where(x => x.PeriodeType == periodeType &&
                          x.Periode <= end && x.Kpi.Id == stack.KpiId && (x.Value != null && x.Value.Value != 0))
                          .OrderByDescending(x => x.Periode).FirstOrDefault();
                            if (kpiActual != null)
                            {
                                kpiActuals = new List<KpiAchievement> { kpiActual };
                                switch (periodeType)
                                {
                                    case PeriodeType.Hourly:
                                        newTimeInformation = kpiActual.Periode.ToString("dd/MMM/yyyy hh tt", CultureInfo.InvariantCulture);
                                        break;
                                    case PeriodeType.Daily:
                                        newTimeInformation = kpiActual.Periode.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                                        break;
                                    case PeriodeType.Monthly:
                                        newTimeInformation = kpiActual.Periode.ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                                        break;
                                    case PeriodeType.Yearly:
                                        newTimeInformation = kpiActual.Periode.ToString("yyyy", CultureInfo.InvariantCulture);
                                        break;
                                }
                                dateTimePeriodes = new List<DateTime> { kpiActual.Periode };
                                newDatetimePeriodes = dateTimePeriodes;
                            }
                        }

                        if (seriesType == "multi-stacks-grouped")
                        {
                            var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = stack.Label,
                                Stack = series.Label,
                                Color = stack.Color
                            };
                            if (comparison)
                            {
                                aSeries.Stack = "KpiActual";
                            }
                            if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                            {

                                foreach (var periode in dateTimePeriodes)
                                {
                                    var targetValue = kpiActuals.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                        .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                    if (targetValue == null || !targetValue.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(targetValue.Value);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var periode in dateTimePeriodes)
                                {
                                    var target = kpiActuals.Where(x => x.Periode == periode).FirstOrDefault();
                                    if (target == null || !target.Value.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(target.Value.Value);
                                    }
                                }
                            }
                            seriesResponse.Add(aSeries);
                        }
                        else
                        {

                            var aSeries = new GetCartesianChartDataResponse.SeriesResponse
                            {
                                Name = stack.Label,
                                Color = stack.Color
                            };
                            if (comparison)
                            {
                                aSeries.Stack = "KpiActual";
                            }
                            if (rangeFilter == RangeFilter.YTD || rangeFilter == RangeFilter.DTD || rangeFilter == RangeFilter.MTD)
                            {

                                foreach (var periode in dateTimePeriodes)
                                {
                                    var targetValue = kpiActuals.Where(x => x.Periode <= periode).GroupBy(x => x.Kpi)
                                        .Select(x => x.Sum(y => y.Value)).FirstOrDefault();
                                    if (targetValue == null || !targetValue.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(targetValue.Value);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var periode in dateTimePeriodes)
                                {
                                    var target = kpiActuals.Where(x => x.Periode == periode).FirstOrDefault();
                                    if (target == null || !target.Value.HasValue)
                                    {
                                        aSeries.Data.Add(null);
                                    }
                                    else
                                    {
                                        aSeries.Data.Add(target.Value.Value);
                                    }
                                }
                            }
                            seriesResponse.Add(aSeries);
                        }
                    }
                }
            }
            return seriesResponse;
        }
Esempio n. 19
0
        //, out string timeInformation
        private string[] _getPeriodes(PeriodeType periodeType, RangeFilter rangeFilter, DateTime? Start, DateTime? End, out IList<DateTime> dateTimePeriodes, out string timeInformation)
        {
            //var ci = new CultureInfo("en-GB");
            var periodes = new List<string>();
            dateTimePeriodes = new List<DateTime>();
            switch (periodeType)
            {
                case PeriodeType.Hourly:
                    var hourlyFormat = "hh tt";
                    switch (rangeFilter)
                    {
                        case RangeFilter.CurrentHour:
                            {
                                var currentHour = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0);
                                dateTimePeriodes.Add(currentHour);
                                periodes.Add(currentHour.ToString(hourlyFormat));
                                timeInformation = currentHour.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        case RangeFilter.CurrentDay:
                            {
                                var startHour = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                                periodes.Add(startHour.ToString(hourlyFormat));
                                dateTimePeriodes.Add(startHour);
                                for (double i = 1; i < 24; i++)
                                {
                                    startHour = startHour.AddHours(1);
                                    periodes.Add(startHour.ToString(hourlyFormat));
                                    dateTimePeriodes.Add(startHour);
                                }
                                timeInformation = startHour.AddHours(-1).ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        case RangeFilter.DTD:
                            {
                                //var currentDay = DateTime.Now.Day;
                                var startHour = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                                var currentHour = DateTime.Now.Hour;
                                timeInformation = startHour.ToString("dd/MMM/yyyy hh tt", CultureInfo.InvariantCulture);
                                while (startHour.Hour <= currentHour)
                                {
                                    periodes.Add(startHour.ToString(hourlyFormat));
                                    dateTimePeriodes.Add(startHour);
                                    startHour = startHour.AddHours(1);
                                }
                                timeInformation += " - " + startHour.AddHours(-1).ToString("dd/MMM/yyyy hh tt", CultureInfo.InvariantCulture);
                            }
                            break;
                        default:
                            timeInformation = Start.Value.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture) + " - " + End.Value.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                            while (Start.Value <= End.Value)
                            {
                                periodes.Add(Start.Value.ToString(hourlyFormat));
                                dateTimePeriodes.Add(Start.Value);
                                Start = Start.Value.AddHours(1);
                            }
                            break;
                    }
                    break;
                case PeriodeType.Daily:
                    var dailyFormat = "dd";
                    switch (rangeFilter)
                    {
                        case RangeFilter.CurrentDay:
                            {
                                var currentDay = DateTime.Now.Date;
                                periodes.Add(currentDay.ToString(dailyFormat));
                                dateTimePeriodes.Add(currentDay);
                                timeInformation = currentDay.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        case RangeFilter.CurrentMonth:
                            {
                                var currentMonth = DateTime.Now.Month;
                                var startDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                                while (currentMonth == startDay.Month)
                                {
                                    periodes.Add(startDay.ToString(dailyFormat));
                                    dateTimePeriodes.Add(startDay);
                                    startDay = startDay.AddDays(1);
                                }
                                timeInformation = startDay.AddDays(-1).ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        case RangeFilter.MTD:
                            {
                                var currentMonth = DateTime.Now.Month;
                                var startDay = new DateTime(DateTime.Now.Year, currentMonth, 1);
                                var currentDay = DateTime.Now.Day;
                                timeInformation = startDay.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                                while (startDay.Day <= currentDay)
                                {
                                    periodes.Add(startDay.ToString(dailyFormat));
                                    dateTimePeriodes.Add(startDay);
                                    startDay = startDay.AddDays(1);
                                }
                                timeInformation += " - " + startDay.AddDays(-1).ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        default:
                            timeInformation = Start.Value.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture) + " - " + End.Value.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
                            while (Start.Value <= End.Value)
                            {
                                periodes.Add(Start.Value.ToString(dailyFormat));
                                dateTimePeriodes.Add(Start.Value);
                                Start = Start.Value.AddDays(1);
                            }
                            break;

                    }
                    break;
                case PeriodeType.Monthly:
                    var monthlyFormat = "MMM";
                    switch (rangeFilter)
                    {
                        case RangeFilter.CurrentMonth:
                            {
                                var currentMonth = DateTime.Now.Date;
                                dateTimePeriodes.Add(currentMonth);
                                periodes.Add(currentMonth.ToString(monthlyFormat, CultureInfo.InvariantCulture));
                                timeInformation = currentMonth.ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        case RangeFilter.CurrentYear:
                            {
                                var currentYear = DateTime.Now.Year;
                                var startMonth = new DateTime(DateTime.Now.Year, 1, 1);
                                timeInformation = currentYear.ToString();
                                while (currentYear == startMonth.Year)
                                {
                                    periodes.Add(startMonth.ToString(monthlyFormat));
                                    dateTimePeriodes.Add(startMonth);
                                    startMonth = startMonth.AddMonths(1);
                                }
                            }
                            break;
                        case RangeFilter.YTD:
                            {
                                var currentYear = DateTime.Now.Year;
                                var startMonth = new DateTime(DateTime.Now.Year, 1, 1);
                                var currentMont = DateTime.Now.Month;
                                timeInformation = startMonth.ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                                while (startMonth.Month <= currentMont)
                                {
                                    periodes.Add(startMonth.ToString(monthlyFormat));
                                    dateTimePeriodes.Add(startMonth);
                                    startMonth = startMonth.AddMonths(1);
                                }
                                timeInformation += " - " + startMonth.AddMonths(-1).ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                            }
                            break;
                        default:
                            timeInformation = Start.Value.ToString("MMM/yyyy", CultureInfo.InvariantCulture) + " - " + End.Value.ToString("MMM/yyyy", CultureInfo.InvariantCulture);
                            while (Start.Value <= End.Value)
                            {
                                dateTimePeriodes.Add(Start.Value);
                                periodes.Add(Start.Value.ToString(monthlyFormat));
                                Start = Start.Value.AddMonths(1);
                            }
                            break;
                    }
                    break;
                default:
                    var yearlyFormat = "yyyy";
                    switch (rangeFilter)
                    {
                        case RangeFilter.CurrentYear:
                            periodes.Add(DateTime.Now.Year.ToString());
                            dateTimePeriodes.Add(new DateTime(DateTime.Now.Year, 1, 1));
                            timeInformation = DateTime.Now.Year.ToString();
                            break;
                        default:
                            timeInformation = Start.Value.ToString("yyyy", CultureInfo.InvariantCulture) + " - " + End.Value.ToString("yyyy", CultureInfo.InvariantCulture);
                            while (Start.Value <= End.Value)
                            {
                                periodes.Add(Start.Value.ToString(yearlyFormat));
                                dateTimePeriodes.Add(Start.Value);
                                Start = Start.Value.AddYears(1);
                            }
                            break;
                    }
                    break;
            }

            return periodes.ToArray();
        }
Esempio n. 20
0
 private double? SumSeries(ArtifactValueInformation valueInformation, PeriodeType periodEType, DateTime start, DateTime end, int kpiId)
 {
     switch (valueInformation) {
         case ArtifactValueInformation.Ytd:
             return
                 DataContext.KpiAchievements.Where(x => x.PeriodeType == periodEType
                         && x.Periode >= start && x.Periode <= end && x.Kpi.Id == kpiId)
                         .GroupBy(x => x.Kpi.Id)
                         .Select(x => x.Sum(y => (double?)y.Ytd ?? 0)).FirstOrDefault();
         case ArtifactValueInformation.Mtd:
             return
                 DataContext.KpiAchievements.Where(x => x.PeriodeType == periodEType
                         && x.Periode >= start && x.Periode <= end && x.Kpi.Id == kpiId)
                         .GroupBy(x => x.Kpi.Id)
                         .Select(x => x.Sum(y => (double?)y.Mtd ?? 0)).FirstOrDefault();
         default:
             return DataContext.KpiAchievements.Where(x => x.PeriodeType == periodEType
                         && x.Periode >= start && x.Periode <= end && x.Kpi.Id == kpiId)
                         .GroupBy(x => x.Kpi.Id)
                         .Select(x => x.Sum(y => (double?)y.Value ?? 0)).FirstOrDefault();
     }
 }
Esempio n. 21
0
        private DisplayKpiInformationViewModel GetGeneralDerKpiInformations(int numberOfKpi, GetDerLayoutitemResponse layout, DateTime date, PeriodeType periodeType)
        {
            var viewModel = new DisplayKpiInformationViewModel();

            for (int i = 0; i < numberOfKpi; i++)
            {
                var kpiInformationVm = new DisplayKpiInformationViewModel.KpiInformationViewModel { Position = i };
                var item = layout.KpiInformations.FirstOrDefault(x => x.Position == i) ??
                           new GetDerLayoutitemResponse.KpiInformationResponse { Position = i };
                if (item.Kpi != null)
                {
                    kpiInformationVm = item.MapTo<DisplayKpiInformationViewModel.KpiInformationViewModel>();
                    //var achievement = _kpiAchievementService.GetKpiAchievement(item.Kpi.Id, date, periodeType);
                    //kpiInformationVm.DerItemValue = achievement.MapTo<DerItemValueViewModel>();
                    if (item.ConfigType.Equals(ConfigType.KpiAchievement))
                    {
                        var achievement = new Services.Responses.KpiAchievement.GetKpiAchievementResponse();
                        if (item.Kpi.Id == 62)
                        {
                            achievement = _kpiAchievementService.GetKpiAchievement(item.Kpi.Id, new DateTime(date.Year, date.Month, 1), PeriodeType.Monthly);
                        }
                        else if (item.Kpi.Id == 385)
                        {
                            var prevMonth = date.AddMonths(-1);
                            achievement = _kpiAchievementService.GetKpiAchievement(item.Kpi.Id, new DateTime(prevMonth.Year, prevMonth.Month, 1), PeriodeType.Monthly);
                        }
                        else
                        {
                            achievement = _kpiAchievementService.GetKpiAchievement(item.Kpi.Id, date, periodeType);
                        }
                        kpiInformationVm.DerItemValue = achievement.MapTo<DerItemValueViewModel>();
                    }
                    else if (item.ConfigType.Equals(ConfigType.KpiTarget))
                    {
                        var target = _kpiTargetService.GetKpiTargetByValue(new GetKpiTargetRequestByValue { Kpi_Id = item.Kpi.Id, periode = date, PeriodeType = periodeType.ToString() });
                        kpiInformationVm.DerItemValue = target.MapTo<DerItemValueViewModel>();
                    }
                }

                viewModel.KpiInformationViewModels.Add(kpiInformationVm);
            }

            return viewModel;
        }
Esempio n. 22
0
        public BaseResponse DeleteKpiAchievement(int kpiId, DateTime periode, PeriodeType periodeType)
        {
            var response = new BaseResponse();
            try
            {
                var achievements = DataContext.KpiAchievements.Where(
                x => x.Kpi.Id == kpiId && x.Periode == periode && x.PeriodeType == periodeType).ToList();
                foreach (var achievement in achievements)
                {
                    DataContext.KpiAchievements.Remove(achievement);
                }
                DataContext.SaveChanges();
                response.IsSuccess = true;
            }
            catch (InvalidOperationException invalidOperationException)
            {
                response.Message = invalidOperationException.Message;
                response.ExceptionType = typeof (InvalidOperationException);
            }
            catch (ArgumentNullException argumentNullException)
            {
                response.Message = argumentNullException.Message;
                response.ExceptionType = typeof(ArgumentNullException);
            }

            return response;
        }