public async Task <PriceDto> CalculatePriceAsync(CalculatePriceDto calculatePriceDto) { var pickUpAddress = calculatePriceDto.PickUpLocation.Address; var dropOffAddress = calculatePriceDto.DropOffLocation.Address; var key = $"{pickUpAddress}|{dropOffAddress}"; var pricing = await _pricingRepository.GetPricingAsync(key); if (pricing == null) { var response = await MakeRequest(pickUpAddress, dropOffAddress); if (response.IsSuccessStatusCode) { var responseString = await response.Content.ReadAsStringAsync(); var metrix = JsonConvert.DeserializeObject <DistanceMetrixDto>(responseString); if (metrix.Status.ToUpper() != HttpStatusCode.OK.ToString()) { throw new PricingDomainException(metrix.ErrorMessage); } var row = metrix.Rows.FirstOrDefault(); if (row == null) { throw new PricingDomainException("Please try again with different address"); } var element = row.Elements.FirstOrDefault(); if (element == null) { throw new PricingDomainException("Please try again with different address"); } var distanceKilometers = element.Distance.Value / 1000; //to kilometers var durationMinutes = element.Duration.Value / 60; //to minutes var calculatedPrice = distanceKilometers + durationMinutes / 10 + calculatePriceDto.Weight / 10; // simple price calculation formula pricing = new Model.Pricing { Price = calculatedPrice, Distance = distanceKilometers, Duration = durationMinutes }; await _pricingRepository.InsertPricingAsync(key, pricing); } else { throw new PricingDomainException(await response.Content.ReadAsStringAsync()); } } return(MapToPriceDto(pricing)); }
public async Task <IActionResult> CalculatePriceAsync(CalculatePriceDto calculatePriceDto) { return(Ok(await _pricingService.CalculatePriceAsync(calculatePriceDto))); }