public async Task <List <CostUsageResponse> > GetCurrentMonthCost(CostUsageRequest costUsageRequest)
        {
            costUsageRequest.StartDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            costUsageRequest.EndDate     = costUsageRequest.StartDate.AddMonths(1).AddDays(-1);
            costUsageRequest.Granularity = "MONTHLY";
            var mapRequest = mapper.Map <GetCostAndUsageRequest>(costUsageRequest);
            var response   = await costExplorerRepository.GetCostAndUsage(mapRequest);

            var totalDays          = DateTime.DaysInMonth(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1).Year, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1).Month);
            var currentDay         = DateTime.Now.Day;
            var lastMonthTotalCost = await GetLastMonthCost(costUsageRequest);

            var lastMonthsAvg = lastMonthTotalCost / totalDays;
            var lastMonthAverageofDesiredDays = lastMonthsAvg * currentDay;
            var mapResponse = response.ResultsByTime.SelectMany(x => x.Groups).Select(amt => Convert.ToDecimal(amt.Metrics[costUsageRequest.Metrics].Amount)).Sum();
            var currentMonthPercentageChange = ((lastMonthAverageofDesiredDays - mapResponse) / mapResponse) * 100;

            return(new List <CostUsageResponse>()
            {
                new CostUsageResponse()
                {
                    Name = DateTime.Now.ToString("MMMM") + "-" + DateTime.Now.Year.ToString(),
                    Amount = mapResponse,
                    Custom = Convert.ToString(Math.Round(currentMonthPercentageChange, 2))
                }
            });
        }
        public async Task <List <CostUsageResponse> > GetCostByMonth(CostUsageRequest costUsageRequest)
        {
            var cacheKey = CacheHelpers.GenerateCostByMonthCacheItemKey(costUsageRequest);

            return(await cache.GetOrCreateAsync(cacheKey, async entry =>
            {
                entry.AbsoluteExpirationRelativeToNow = CacheHelpers.absoluteExpirationRelativeToNow;
                return await costExplorerOperations.GetCostByMonth(costUsageRequest);
            }));
        }
Exemple #3
0
        public async Task <IActionResult> GetMonthlyCostPrediction([FromBody] CostUsageRequest costUsageRequest)
        {
            if (!ValidationHelper.IsValidCostUsageRequest(costUsageRequest, out string message))
            {
                return(BadRequest(new { Message = message }));
            }
            var response = await costExplorerOperations.GetCostForecast(costUsageRequest);

            return(Ok(response));
        }
        public async Task <List <CostUsageResponse> > GetCostByMonth(CostUsageRequest costUsageRequest)
        {
            var mapRequest = mapper.Map <GetCostAndUsageRequest>(costUsageRequest);
            var response   = await costExplorerRepository.GetCostAndUsage(mapRequest);

            var mapResponse = response.ResultsByTime.Select(x => new { x.Groups, x.TimePeriod }).Select(z => new CostUsageResponse()
            {
                Name   = Convert.ToDateTime(z.TimePeriod.Start).ToString("MMMM") + "-" + Convert.ToDateTime(z.TimePeriod.Start).Year.ToString(),
                Amount = z.Groups.Sum(s => Convert.ToDecimal(s.Metrics[costUsageRequest.Metrics].Amount))
            });

            return(mapResponse.ToList());
        }
        public async Task <decimal> GetLastMonthCost(CostUsageRequest costUsageRequest)
        {
            costUsageRequest.StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
            costUsageRequest.EndDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);

            costUsageRequest.Granularity = "MONTHLY";
            var mapRequest = mapper.Map <GetCostAndUsageRequest>(costUsageRequest);
            var response   = await costExplorerRepository.GetCostAndUsage(mapRequest);

            var mapResponse = response.ResultsByTime.SelectMany(x => x.Groups).Select(amt => Convert.ToDecimal(amt.Metrics[costUsageRequest.Metrics].Amount)).Sum();

            return(mapResponse);
        }
        public async Task <List <CostUsageResponse> > GetForecastForCurrentMonth(CostUsageRequest costUsageRequest)
        {
            var mapRequest = mapper.Map <GetCostForecastRequest>(costUsageRequest);

            mapRequest.Granularity = Granularity.MONTHLY;
            mapRequest.Metric      = Amazon.CostExplorer.Metric.UNBLENDED_COST;
            string startDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");                                             //DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
            string endDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).ToString("yyyy-MM-dd"); //new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");

            if (endDate.Equals(startDate))
            {
            }
            mapRequest.TimePeriod = new DateInterval()
            {
                Start = startDate,
                End   = endDate
            };
            GetCostForecastResponse response = new GetCostForecastResponse();

            try
            {
                response = await costExplorerRepository.GetCostForecast(mapRequest);
            }
            catch (DataUnavailableException ex)
            {
                return(new List <CostUsageResponse>()
                {
                    new CostUsageResponse()
                    {
                        Name = "Current Month Cost:",
                        Amount = 0.00M,
                        Custom = "0",
                        Date = DateTime.Now
                    }
                });
            }
            var currentMonthCost = response.Total.Amount;
            var lastMonthCost    = await GetLastMonthCost(costUsageRequest);

            var mapResponse = response.ForecastResultsByTime.Select(x => new CostUsageResponse()
            {
                Name   = "Current Month Cost:",
                Amount = Convert.ToDecimal(currentMonthCost),
                Custom = Convert.ToString(Math.Round((Convert.ToDecimal(currentMonthCost) - Convert.ToDecimal(lastMonthCost)) / Convert.ToDecimal(currentMonthCost) * 100, 2))
            });

            return(mapResponse.ToList());
        }
        public async Task <List <CostUsageResponse> > GetCurrentYearCost(CostUsageRequest costUsageRequest)
        {
            costUsageRequest.StartDate   = new DateTime(DateTime.Now.Year, 1, 1);
            costUsageRequest.EndDate     = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);
            costUsageRequest.Granularity = "MONTHLY";
            var mapRequest = mapper.Map <GetCostAndUsageRequest>(costUsageRequest);
            var response   = await costExplorerRepository.GetCostAndUsage(mapRequest);

            var mapResponse = response.ResultsByTime.SelectMany(x => x.Groups).Select(amt => Convert.ToDecimal(amt.Metrics[costUsageRequest.Metrics].Amount)).Sum();

            return(new List <CostUsageResponse>()
            {
                new CostUsageResponse()
                {
                    Name = DateTime.Now.Year.ToString(),
                    Amount = mapResponse
                }
            });
        }
        public async Task <List <CostUsageResponse> > GetCostUsage(CostUsageRequest costUsageRequest)
        {
            var mapRequest = mapper.Map <GetCostAndUsageRequest>(costUsageRequest);
            var response   = await costExplorerRepository.GetCostAndUsage(mapRequest);

            var mapResponse = response.ResultsByTime.SelectMany(x => x.Groups).GroupBy(x => x.Keys[response.GroupDefinitions.Count - 1])
                              .Select(z => new CostUsageResponse
            {
                Name   = z.Key,
                Amount = z.Sum(c => Convert.ToDecimal(c.Metrics[costUsageRequest.Metrics].Amount))
            }
                                      );

            if (costUsageRequest.Limit.HasValue && costUsageRequest.Limit != -1)
            {
                return(mapResponse.OrderByDescending(x => x.Amount).Take(costUsageRequest.Limit.Value).ToList());
            }
            return(mapResponse.ToList());
        }
Exemple #9
0
        public static bool IsValidCostUsageRequest(CostUsageRequest costUsageRequest, out string message)
        {
            DateTime temp;

            if (!DateTime.TryParse(costUsageRequest.StartDate.ToString(), out temp))
            {
                message = $"Invalid Start Date:{costUsageRequest.StartDate.ToString()}";
                return(false);
            }
            if (!DateTime.TryParse(costUsageRequest.EndDate.ToString(), out temp))
            {
                message = $"Invalid End Date:{costUsageRequest.EndDate.ToString()}";
                return(false);
            }
            if (!CostUsageConstants.granularity.Any(x => x.Equals(costUsageRequest.Granularity)))
            {
                message = $"Granularity is invalid:{costUsageRequest.Granularity.ToString()}, Please provide a proper Granularity. Either MONTHLY or DAILY";
                return(false);
            }
            if (!costUsageRequest.GroupBy.Any(x => CostUsageConstants.GroupBy.Any(y => y.Equals(x.Key))))
            //(!CostUsageConstants.GroupBy.Any(x=> x.Equals(costUsageRequest.GroupBy.FirstOrDefault().Key)))
            {
                message = $"Invalid GroupBy key value:{String.Join(",",costUsageRequest.GroupBy.Select(x=> x.Key))}, it should be { String.Join(",", CostUsageConstants.GroupBy)}";
                return(false);
            }
            if (!CostUsageConstants.Filter.Any(x => x.Equals(costUsageRequest.Filters.Key)))
            {
                message = $"Invalid Filter key value:{costUsageRequest.Filters.Key}, it should be {String.Join(",", CostUsageConstants.Filter)}";
                return(false);
            }
            if (!CostUsageConstants.Metrics.Any(x => x.Equals(costUsageRequest.Metrics)))
            {
                message = $"Invalid Metrics value:{costUsageRequest.Metrics}, it should be {String.Join(",", CostUsageConstants.Metrics)}";
                return(false);
            }
            message = "The request is valid";
            return(true);
        }
        //getForecastForCurrentMonth
        public async Task <List <CostUsageResponse> > GetCostForecast(CostUsageRequest costUsageRequest)
        {
            try
            {
                var mapRequest = mapper.Map <GetCostForecastRequest>(costUsageRequest);
                mapRequest.Granularity = Granularity.MONTHLY;
                mapRequest.Metric      = Amazon.CostExplorer.Metric.UNBLENDED_COST;
                string startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");
                string endDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddYears(1).AddDays(-1).ToString("yyyy-MM-dd");
                mapRequest.TimePeriod = new DateInterval()
                {
                    Start = startDate,
                    End   = endDate
                };
                var response = await costExplorerRepository.GetCostForecast(mapRequest);

                var mapResponse = response.ForecastResultsByTime.Select(x => new CostUsageResponse()
                {
                    Name   = Convert.ToDateTime(x.TimePeriod.Start).ToString("MMMM") + "-" + Convert.ToDateTime(x.TimePeriod.Start).Year,
                    Amount = Convert.ToDecimal(x.MeanValue),
                    Date   = Convert.ToDateTime(x.TimePeriod.Start)
                });
                return(mapResponse.ToList());
            }
            catch (DataUnavailableException ex)
            {
                return(new List <CostUsageResponse>()
                {
                    new CostUsageResponse()
                    {
                        Name = DateTime.Now.ToString("MMMM") + "-" + DateTime.Now.Year.ToString(),
                        Amount = 0,
                        Date = DateTime.Now
                    }
                });
            }
        }
        public async Task <List <CostUsageResponse> > GetForecastForCurrentMonth(CostUsageRequest costUsageRequest)
        {
            var response = await costExplorerOperations.GetForecastForCurrentMonth(costUsageRequest);

            return(response);
        }
 public static string GenerateCacheItemKeyForMonth(CostUsageRequest costUsageRequest)
 {
     return(string.Format(_monthItemsKeyTemplate, DateTime.Now.ToString("yyyyMMdd"), costUsageRequest.StartDate.ToString("yyyyMMdd"), costUsageRequest.EndDate.ToString("yyyyMMdd"), String.Join("-", costUsageRequest?.Filters?.Values)));
 }
 public static string GenerateCostByMonthCacheItemKey(CostUsageRequest costUsageRequest)
 {
     return(string.Format(_costByMonthItemsKeyTemplate, DateTime.Now.ToString("yyyyMMdd"), costUsageRequest.StartDate.ToString("yyyyMMdd"), costUsageRequest.EndDate.ToString("yyyyMMdd"), String.Join("-", costUsageRequest.GroupBy.Select(x => x.Key)), costUsageRequest.Granularity, String.Join("-", costUsageRequest?.Filters?.Values)));
 }