diff --git a/TIAM.Services.Server/GooglePlacesService.cs b/TIAM.Services.Server/GooglePlacesService.cs new file mode 100644 index 00000000..32d67837 --- /dev/null +++ b/TIAM.Services.Server/GooglePlacesService.cs @@ -0,0 +1,104 @@ +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; + +namespace TIAM.Services.Server +{ + public class GooglePlacesService + { + private readonly HttpClient _httpClient; + private readonly string _apiKey = "AIzaSyAyEYJkpt2KDa3SJ34UNWO4-dNOJKmUtF8"; + + public GooglePlacesService(HttpClient httpClient) + { + _httpClient = httpClient; + } + + public async Task ValidateAddressAsync(string address) + { + var requestUri = $"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={address}&inputtype=textquery&fields=formatted_address,name&key={_apiKey}"; + + var response = await _httpClient.GetFromJsonAsync(requestUri); + + return response?.Candidates?.Length > 0 ? "Valid address" : "Invalid address"; + } + + public async Task CalculateRouteAsync(string origin, string destination, DateTime travelTime) + { + // Convert the travel time to Unix time + long unixTime = ((DateTimeOffset)travelTime).ToUnixTimeSeconds(); + var requestUri = $"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&departure_time={unixTime}&key={_apiKey}"; + + var response = await _httpClient.GetFromJsonAsync(requestUri); + + if (response?.Routes?.Length > 0) + { + var route = response.Routes[0]; + return $"Distance: {route.Legs[0].Distance.Text}, Duration: {route.Legs[0].Duration.Text} (with traffic: {route.Legs[0].DurationInTraffic?.Text})"; + } + + return "Route not found"; + } + + public async Task> GetPlacePredictionsAsync(string input) + { + var requestUri = $"https://maps.googleapis.com/maps/api/place/autocomplete/json?input={input}&key={_apiKey}"; + + var response = await _httpClient.GetFromJsonAsync(requestUri); + + var predictions = new List(); + if (response?.Predictions != null) + { + foreach (var prediction in response.Predictions) + { + predictions.Add(prediction.Description); + } + } + + return predictions; + } + } + + public class GooglePlacesAutocompleteResponse + { + public Prediction[] Predictions { get; set; } + } + + public class Prediction + { + public string Description { get; set; } + } + + public class GooglePlacesResponse + { + public Candidate[]? Candidates { get; set; } + } + + public class Candidate + { + public string? Formatted_Address { get; set; } + public string? Name { get; set; } + } + + public class GoogleDirectionsResponse + { + public Route[]? Routes { get; set; } + } + + public class Route + { + public Leg[]? Legs { get; set; } + } + + public class Leg + { + public TextValue? Distance { get; set; } + public TextValue? Duration { get; set; } + public TextValue? DurationInTraffic { get; set; } + } + + public class TextValue + { + public string Text { get; set; } + } +} \ No newline at end of file diff --git a/TIAM.Services.Server/SmartyStreetService.cs b/TIAM.Services.Server/SmartyStreetService.cs new file mode 100644 index 00000000..82eb504a --- /dev/null +++ b/TIAM.Services.Server/SmartyStreetService.cs @@ -0,0 +1,33 @@ +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; + +namespace TIAM.Services.Server +{ + public class SmartyStreetsService + { + private readonly HttpClient _httpClient; + private readonly string _authId = "YourAuthID"; + private readonly string _authToken = "YourAuthToken"; + + public SmartyStreetsService(HttpClient httpClient) + { + _httpClient = httpClient; + } + + public async Task ValidateAddressAsync(string address) + { + var requestUri = $"https://us-street.api.smartystreets.com/street-address?auth-id={_authId}&auth-token={_authToken}&street={address}"; + + var response = await _httpClient.GetFromJsonAsync(requestUri); + + return response?.Length > 0 ? "Valid address" : "Invalid address"; + } + } + + public class SmartyStreetsResponse + { + public string DeliveryLine1 { get; set; } + public string LastLine { get; set; } + } +} diff --git a/TIAM.Services.Server/TransferBackendService.cs b/TIAM.Services.Server/TransferBackendService.cs index ef82c262..2ff08010 100644 --- a/TIAM.Services.Server/TransferBackendService.cs +++ b/TIAM.Services.Server/TransferBackendService.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using TIAM.Core.Enums; using TIAM.Database.DataLayers.Admins; using TIAM.Entities.Products; @@ -58,5 +59,44 @@ namespace TIAM.Services.Server }; } + public double GetCommission(Guid productId, double Price, TransferDestination to) + { + //check if Destination has a custom commissionRate by productId + double commissionRate = 0; + double commission = 0; + var transferDestinationToProduct = adminDal.GetTransferDestinationToProduct(productId, to.Id); + if (transferDestinationToProduct != null) + { + commissionRate = transferDestinationToProduct.ProductCommis; + } + else + { + if (to.ProductCommis > 0) + { + commissionRate = to.ProductCommis; + } + + else + { + var product = adminDal.GetProductById(productId); + if (product != null) + { + if(product.ServiceProvider != null) + { + commissionRate = product.ServiceProvider.CommissionPercent; + } + } + + } + } + commission = GetCommission(Price, commissionRate); + return commission; + } + + public double GetCommission(double price, double commissionrate) + { + return price * commissionrate / 100; + } + } } diff --git a/TIAMMobileApp/MauiProgram.cs b/TIAMMobileApp/MauiProgram.cs index 685946ea..e6d42c4e 100644 --- a/TIAMMobileApp/MauiProgram.cs +++ b/TIAMMobileApp/MauiProgram.cs @@ -70,6 +70,8 @@ namespace TIAMMobileApp builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddAuthorizationCore(); builder.Services.Configure(Guid.NewGuid().ToString(), c => { }); return builder.Build(); diff --git a/TIAMSharedUI/Pages/Components/AddressSearchAndSelectComponent.razor b/TIAMSharedUI/Pages/Components/AddressSearchAndSelectComponent.razor new file mode 100644 index 00000000..1bbc65f4 --- /dev/null +++ b/TIAMSharedUI/Pages/Components/AddressSearchAndSelectComponent.razor @@ -0,0 +1,56 @@ +@using AyCode.Blazor.Components.Components +@using TIAMWebApp.Shared.Application.Services +@inject GooglePlacesService GooglePlacesService + +

+ @NullText +

+ + + + + + @if (Predictions.Count > 0) + { + + + } + + +@code { + + [Parameter] public string NullText { get; set; } + + [Parameter] public EventCallback AddressChanged { get; set; } + + private string Address { get; set; } + private List Predictions { get; set; } = new(); + private PredictionItem SelectedPrediction { get; set; } + + private async Task OnInputChanged(ChangeEventArgs e) + { + var input = Address; + if (!string.IsNullOrWhiteSpace(input)) + { + var predictions = await GooglePlacesService.GetPlacePredictionsAsync(input); + Predictions = predictions.ConvertAll(p => new PredictionItem { Description = p }); + SelectedPrediction = Predictions[0]; + } + else + { + Predictions.Clear(); + } + } + + private class PredictionItem + { + public string Description { get; set; } + } + +} diff --git a/TIAMSharedUI/Pages/User/Hotels/CreateAndManageTransfer.razor b/TIAMSharedUI/Pages/User/Hotels/CreateAndManageTransfer.razor index 5843717a..ce04cf22 100644 --- a/TIAMSharedUI/Pages/User/Hotels/CreateAndManageTransfer.razor +++ b/TIAMSharedUI/Pages/User/Hotels/CreateAndManageTransfer.razor @@ -24,8 +24,8 @@ Create transfer
-

Drivers

-

Manage drivers here!

+

Create transfer

+

Order a new transfer here!

diff --git a/TIAMSharedUI/Pages/User/Hotels/ManageIncome.razor b/TIAMSharedUI/Pages/User/Hotels/ManageIncome.razor index 0190d5da..4901880b 100644 --- a/TIAMSharedUI/Pages/User/Hotels/ManageIncome.razor +++ b/TIAMSharedUI/Pages/User/Hotels/ManageIncome.razor @@ -166,7 +166,7 @@ if (e.FieldName == "Appointment") { - string displayText = $"Month: {((DateTime)e.Value).Year.ToString()}.{((DateTime)e.Value).Month.ToString()}"; + string displayText = $"{((DateTime)e.Value).Year.ToString()}.{((DateTime)e.Value).Month.ToString()}"; e.DisplayText = displayText; } } diff --git a/TIAMSharedUI/Pages/Utility/ChatPage.razor b/TIAMSharedUI/Pages/Utility/ChatPage.razor index 3f977dfe..57045fb7 100644 --- a/TIAMSharedUI/Pages/Utility/ChatPage.razor +++ b/TIAMSharedUI/Pages/Utility/ChatPage.razor @@ -55,19 +55,36 @@
  • - - My transfers
  • - - Exchange Rate
  • +
  • + + Google route calculation + +
  • +
  • + + Google address validation + +
  • +
  • + + Smarty address validation + +
  • +
  • + + Google autocomplete + +
  • +
  • diff --git a/TIAMSharedUI/Pages/Utility/GoogleAddressAutoCompleteTest.razor b/TIAMSharedUI/Pages/Utility/GoogleAddressAutoCompleteTest.razor new file mode 100644 index 00000000..20d9d00a --- /dev/null +++ b/TIAMSharedUI/Pages/Utility/GoogleAddressAutoCompleteTest.razor @@ -0,0 +1,14 @@ +@page "/address-autocomplete" +@using DevExpress.Blazor +@using TIAMSharedUI.Pages.Components + + + +

    @resultAddress

    +@code { + private string resultAddress = ""; + + private void OnSelectedAddressChanged(string address) { + resultAddress = address; + } +} diff --git a/TIAMSharedUI/Pages/Utility/GoogleAddressValidatortest.razor b/TIAMSharedUI/Pages/Utility/GoogleAddressValidatortest.razor new file mode 100644 index 00000000..0bf17f15 --- /dev/null +++ b/TIAMSharedUI/Pages/Utility/GoogleAddressValidatortest.razor @@ -0,0 +1,28 @@ +@page "/google-address-validation" +@using DevExpress.Blazor +@using TIAMWebApp.Shared.Application.Services +@inject GooglePlacesService GooglePlacesService + + + + + + + + Validate Address + + +

    @ValidationMessage

    +
    +
    +
    + +@code { + private string Address { get; set; } + private string ValidationMessage { get; set; } + + private async Task ValidateAddress() + { + ValidationMessage = await GooglePlacesService.ValidateAddressAsync(Address); + } +} \ No newline at end of file diff --git a/TIAMSharedUI/Pages/Utility/GoogleRouteCalculationTest.razor b/TIAMSharedUI/Pages/Utility/GoogleRouteCalculationTest.razor new file mode 100644 index 00000000..60a26172 --- /dev/null +++ b/TIAMSharedUI/Pages/Utility/GoogleRouteCalculationTest.razor @@ -0,0 +1,41 @@ +@page "/route-calculation" +@using DevExpress.Blazor +@using TIAMWebApp.Shared.Application.Services +@inject GooglePlacesService GooglePlacesService + + + + + + + + + + + + + + + + + Calculate Route + + +

    @RouteMessage

    +
    +
    +
    + +@code { + private string OriginAddress { get; set; } + private string DestinationAddress { get; set; } + private DateTime TravelDate { get; set; } = DateTime.Today; + private TimeSpan TravelTime { get; set; } = DateTime.Now.TimeOfDay; + private string RouteMessage { get; set; } + + private async Task CalculateRoute() + { + var travelDateTime = TravelDate.Add(TravelTime); + RouteMessage = await GooglePlacesService.CalculateRouteAsync(OriginAddress, DestinationAddress, travelDateTime); + } +} \ No newline at end of file diff --git a/TIAMSharedUI/Pages/Utility/SmartyAddressValidatortest.razor b/TIAMSharedUI/Pages/Utility/SmartyAddressValidatortest.razor new file mode 100644 index 00000000..306950fc --- /dev/null +++ b/TIAMSharedUI/Pages/Utility/SmartyAddressValidatortest.razor @@ -0,0 +1,29 @@ +@page "/smarty-address-validation" +@using DevExpress.Blazor +@using TIAMWebApp.Shared.Application.Services +@inject SmartyStreetsService SmartyStreetsService + + + + + + + + Validate Address + + +

    @ValidationMessage

    +
    +
    +
    + +@code { + private string Address { get; set; } + private string ValidationMessage { get; set; } + + private async Task ValidateAddress() + { + ValidationMessage = await SmartyStreetsService.ValidateAddressAsync(Address); + } +} + diff --git a/TIAMWebApp/Client/Program.cs b/TIAMWebApp/Client/Program.cs index 490d4b60..083371ee 100644 --- a/TIAMWebApp/Client/Program.cs +++ b/TIAMWebApp/Client/Program.cs @@ -47,6 +47,8 @@ builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddAuthorizationCore(); builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); //builder.Services.AddScoped(); //WebSpecific end diff --git a/TIAMWebApp/Server/Controllers/GoogleAPIController .cs b/TIAMWebApp/Server/Controllers/GoogleAPIController .cs index b607a4d0..982edb38 100644 --- a/TIAMWebApp/Server/Controllers/GoogleAPIController .cs +++ b/TIAMWebApp/Server/Controllers/GoogleAPIController .cs @@ -1,3 +1,4 @@ +using AyCode.Core.Extensions; using AyCode.Core.Server.Loggers; using GoogleApi; using GoogleApi.Entities.Common; @@ -10,7 +11,10 @@ using GoogleApi.Entities.Maps.DistanceMatrix.Response; using GoogleApi.Entities.Maps.Geocoding.Location.Request; using Microsoft.AspNetCore.Mvc; using System.Net; +using TIAM.Services.Server; using TIAMWebApp.Shared.Application.Models; +using TIAMWebApp.Shared.Application.Models.PageModels; + namespace TIAMWebApp.Server.Controllers { @@ -18,176 +22,82 @@ namespace TIAMWebApp.Server.Controllers [Route("api/v1/[controller]")] public class GoogleAPIController : ControllerBase { - - private string _apiKey = "AIzaSyAyEYJkpt2KDa3SJ34UNWO4-dNOJKmUtF8"; - private static readonly TripInfo[] Trips = new TripInfo[] - { - - new TripInfo(47.511887f, 19.031920f, 47.510769f, 19.081422f ), - - - }; + private readonly ILogger _logger; + private readonly GooglePlacesService _googlePlacesService; - - public GoogleAPIController(ILogger logger) + public GoogleAPIController(ILogger logger, GooglePlacesService googlePlacesService) { _logger = logger; - + _googlePlacesService = googlePlacesService; } - [HttpPost] - [Route("GetAddressForCoordinates")] - public async Task GetAddressForCoordinates(TripInfo myTrip) - { + //[HttpPost] + //[Route("GetAddressForCoordinates")] + //public async Task GetAddressForCoordinates(TripInfo myTrip) + //{ - var latitude = myTrip.StartLatitude; // Example latitude + // var latitude = myTrip.StartLatitude; // Example latitude - var longitude = myTrip.StartLongitude; // Example longitude - GlobalLogger.Info(latitude.ToString()); - GlobalLogger.Info(longitude.ToString()); - var booo = new Coordinate(latitude, longitude); + // var longitude = myTrip.StartLongitude; // Example longitude + // GlobalLogger.Info(latitude.ToString()); + // GlobalLogger.Info(longitude.ToString()); + // var booo = new Coordinate(latitude, longitude); - var request = new LocationGeocodeRequest - { - Key = _apiKey, - Location = booo - }; + // var request = new LocationGeocodeRequest + // { + // Key = _apiKey, + // Location = booo + // }; - try - { - var response = await GoogleMaps.Geocode.LocationGeocode.QueryAsync(request); - if (response.Status == Status.Ok) - { - return response.RawJson; - } + // try + // { + // var response = await GoogleMaps.Geocode.LocationGeocode.QueryAsync(request); + // if (response.Status == Status.Ok) + // { + // return response.RawJson; + // } - else - { - return "Something wrong"; - } - } - catch (Exception ex) - { - return ex + "Error occurred while calling GoogleMaps.Geocode.LocationGeocode.QueryAsync"; - } + // else + // { + // return "Something wrong"; + // } + // } + // catch (Exception ex) + // { + // return ex + "Error occurred while calling GoogleMaps.Geocode.LocationGeocode.QueryAsync"; + // } - } + //} //google api call to get coordinates from address [HttpPost] - [Route("ValidateAddress")] - public async Task ValidateAddress(string address) + [Route(APIUrls.GoogleValidateAddressRouteName)] + public async Task ValidateAddress([FromBody] string address) { - - var request = new AddressValidationRequest - { - Key = _apiKey, - Address = new PostalAddress - { - AddressLines = new List - { - address - } - } - }; - - - var response = await GoogleMaps.AddressValidation.QueryAsync(request); - if (response.Status == Status.Ok) - { - return response.Result.Address.FormattedAddress; - } - else if (response.Status == Status.ZeroResults) - { - return "No results found for the given address."; - } - else - { - return "Something went wrong."; - } - + _logger.LogDebug($"ValidateAddress Called {address}"); + var result = await _googlePlacesService.ValidateAddressAsync(address); + return result; } - [HttpGet] - [Route("GetTravelTime")] - //public string GetTravelTime(TripInfo) - public async Task GetTravelTimeWithGoogleMatrix() + [HttpPost] + [Route(APIUrls.GoogleCalculateRouteRouteName)] + public async Task CalculateRouteAsync(RouteCalculationModel routeCalculationModel) { - var latitude1 = Trips[0].StartLatitude; // Example latitude - - var longitude1 = Trips[0].StartLongitude; // Example longitude - - var latitude2 = Trips[0].EndLatitude; // Example latitude - - var longitude2 = Trips[0].EndLongitude; // Example longitude - - GlobalLogger.Info(latitude1.ToString()); - GlobalLogger.Info(longitude1.ToString()); - GlobalLogger.Info(latitude2.ToString()); - GlobalLogger.Info(longitude2.ToString()); - - try - { - - var origin1 = new Address("Margit utca 35, Budapest, Budapest, Magyarország"); - var origin2 = new Address("Nefelejcs utca 18, Budapest, Budapest, Magyarország"); - var destination1 = new Address("Százados utca 30/a, Budapest, Budapest, Magyarország"); - var destination2 = new Address("Novoszadek utca 53, Pilisszántó, Pest, Magyarország"); - DistanceMatrixResponse? response = null; - - //var response = await GoogleMaps.DistanceMatrix.QueryAsync(request); - try - { - var request = new DistanceMatrixRequest - { - Key = _apiKey, - Origins = new[] - { - new LocationEx(origin1), - new LocationEx(origin2) - }, - Destinations = new[] - { - new LocationEx(destination1), - new LocationEx(destination2) - }, - TravelMode = TravelMode.DRIVING, - }; - - response = await GoogleApi.GoogleMaps.DistanceMatrix.QueryAsync(request); - return response.RawJson; - - } - catch (Exception e) - { - GlobalLogger.Error($"Errorcode: {response?.Status}, {e.Message}", e); - } - - - return ""; - - } - catch (WebException ex) - { - GlobalLogger.Error($"Google Maps API Error {ex.Message}", ex); - return "Google Maps API Error {0}" + ex.Message; - } - - + + var result = await _googlePlacesService.CalculateRouteAsync(routeCalculationModel.Origin, routeCalculationModel.Destination, routeCalculationModel.TravelTime); + return result; } - public class GoogleMapsResponse + [HttpPost] + [Route(APIUrls.GoogleAutoCompleteRouteName)] + public async Task GoogleAutoComplete([FromBody] string address) { - public string Status { get; set; } - public Result[] Results { get; set; } - } - - public class Result - { - public string FormattedAddress { get; set; } + _logger.LogDebug($"ValidateAddress Called {address}"); + var result = await _googlePlacesService.GetPlacePredictionsAsync(address); + return result.ToJson(); } } diff --git a/TIAMWebApp/Server/Controllers/SmartyStreetsAPIController.cs b/TIAMWebApp/Server/Controllers/SmartyStreetsAPIController.cs new file mode 100644 index 00000000..3593e20b --- /dev/null +++ b/TIAMWebApp/Server/Controllers/SmartyStreetsAPIController.cs @@ -0,0 +1,47 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using QRCoder; +using System.Drawing; +using System.Drawing.Imaging; +using AyCode.Core.Enums; +using AyCode.Core.Extensions; +using TIAM.Database.DataLayers.Admins; +using TIAM.Entities.ServiceProviders; +using TIAM.Entities.Users; +using TIAMWebApp.Shared.Application.Models; +using Product = TIAM.Entities.Products.Product; +using TIAM.Entities.Addresses; +using TIAM.Entities.Profiles; +using AyCode.Core.Loggers; +using AyCode.Entities; +using AyCode.Services.SignalRs; +using AyCode.Utils.Extensions; +using TIAM.Entities.Drivers; +using TIAM.Services; +using TIAMWebApp.Server.Services; +using GoogleApi.Entities.Search.Video.Common; +using TIAM.Services.Server; + +namespace TIAMWebApp.Server.Controllers +{ + [ApiController] + [Route("api/v1/[controller]")] + public class SmartyStreetsAPIController(SmartyStreetsService _service,IEnumerable logWriters) : ControllerBase + { + + private readonly TIAM.Core.Loggers.Logger _logger = new(logWriters.ToArray()); + + + [AllowAnonymous] + [HttpPost] + [Route(APIUrls.SmartyValidateAddress)] + //[SignalR(SignalRTags.GetProfileById)] + public async Task Set([FromBody] string address) + { + _logger.Info($@"GetServiceProviderById called with rate: {address}"); + var result = await _service.ValidateAddressAsync(address); + return Ok(result); + } + } + +} \ No newline at end of file diff --git a/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs b/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs index 974576ee..5b329735 100644 --- a/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs +++ b/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs @@ -513,17 +513,14 @@ namespace TIAMWebApp.Server.Controllers { product = await _adminDal.GetProductByIdAsync((Guid)transfer.ProductId); transfer.Price = _transferBackendService.GetTransferPrice(transfer.ProductId.Value, from, to, transfer.PassengerCount); - } - if(transfer.Price != null && transfer.Price > 0 && product != null) - { - if(product.ServiceProvider.CommissionPercent!=null) - { - transfer.Revenue = transfer.Price * product.ServiceProvider.CommissionPercent / 100; + if (transfer.Price != null && transfer.Price > 0) + { + transfer.Revenue = _transferBackendService.GetCommission((Guid)transfer.ProductId, (double)transfer.Price, to); } else { - transfer.Revenue=0; + transfer.Revenue = 0; } } diff --git a/TIAMWebApp/Server/Program.cs b/TIAMWebApp/Server/Program.cs index c9fa98c8..a810b381 100644 --- a/TIAMWebApp/Server/Program.cs +++ b/TIAMWebApp/Server/Program.cs @@ -48,6 +48,8 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddSignalR(options => options.MaximumReceiveMessageSize = 102400 * 1024);//.AddMessagePackProtocol(options => options.SerializerOptions = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData)); diff --git a/TIAMWebApp/Shared/Models/APIUrls.cs b/TIAMWebApp/Shared/Models/APIUrls.cs index 0c18917d..17415c75 100644 --- a/TIAMWebApp/Shared/Models/APIUrls.cs +++ b/TIAMWebApp/Shared/Models/APIUrls.cs @@ -20,6 +20,8 @@ namespace TIAMWebApp.Shared.Application.Models public const string MessageAPI = BaseUrlWithSlashAndVersion + "MessageAPI/"; public const string PaymentAPI = BaseUrlWithSlashAndVersion + "PaymentAPI/"; public const string ExchangeRateAPI = BaseUrlWithSlashAndVersion + "ExchangeRateAPI/"; + public const string SmartyStreetsAPI = BaseUrlWithSlashAndVersion + "SmartyStreetsAPI/"; + public const string GoogleAPI = BaseUrlWithSlashAndVersion + "GoogleAPI/"; public const string AddLogItemRouteName = "AddLogItem"; public const string AddLogItem = LoggerApi + AddLogItemRouteName; @@ -274,5 +276,17 @@ namespace TIAMWebApp.Shared.Application.Models public const string GetExchangeRateRouteName = "GetExchangeRate"; public const string GetExchangeRate = ExchangeRateAPI + GetExchangeRateRouteName; + public const string SmartyValidateAddressRouteName = "SmartyValidateAddress"; + public const string SmartyValidateAddress = SmartyStreetsAPI + SmartyValidateAddressRouteName; + + public const string GoogleValidateAddressRouteName = "GoogleValidateAddress"; + public const string GoogleValidateAddress = GoogleAPI + GoogleValidateAddressRouteName; + + public const string GoogleCalculateRouteRouteName = "GoogleCalculateRoute"; + public const string GoogleCalculateRoute = GoogleAPI + GoogleCalculateRouteRouteName; + + public const string GoogleAutoCompleteRouteName = "GoogleAutoComplete"; + public const string GoogleAutoComplete = GoogleAPI + GoogleAutoCompleteRouteName; + } } diff --git a/TIAMWebApp/Shared/Models/PageModels/RouteCalculationModel.cs b/TIAMWebApp/Shared/Models/PageModels/RouteCalculationModel.cs new file mode 100644 index 00000000..ce7d27b1 --- /dev/null +++ b/TIAMWebApp/Shared/Models/PageModels/RouteCalculationModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TIAMWebApp.Shared.Application.Models.PageModels +{ + public class RouteCalculationModel + { + public string Origin { get; set; } + public string Destination { get; set; } + public DateTime TravelTime { get; set; } + + } +} diff --git a/TIAMWebApp/Shared/Services/GooglePlacesService.cs b/TIAMWebApp/Shared/Services/GooglePlacesService.cs new file mode 100644 index 00000000..f68ca366 --- /dev/null +++ b/TIAMWebApp/Shared/Services/GooglePlacesService.cs @@ -0,0 +1,61 @@ +using AyCode.Services.Loggers; +using DevExpress.Office; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +using TIAM.Core.Loggers; +using TIAMWebApp.Shared.Application.Models; +using TIAMWebApp.Shared.Application.Models.ClientSide; +using TIAMWebApp.Shared.Application.Models.PageModels; +using TIAMWebApp.Shared.Application.Utility; + +namespace TIAMWebApp.Shared.Application.Services +{ + public class GooglePlacesService + { + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public GooglePlacesService(HttpClient httpClient, IEnumerable logWriters) + { + _httpClient = httpClient; + _logger = new LoggerClient(logWriters.ToArray()); + } + + public async Task ValidateAddressAsync(string address) + { + + var url = $"{Setting.ApiBaseUrl}/{APIUrls.GoogleValidateAddress}"; + var response = await _httpClient.PostAsJsonAsync(url, address); + var result = await response.Content.ReadAsStringAsync(); + //var user = JsonConvert.DeserializeObject(result); + return result; + } + + public async Task CalculateRouteAsync(string origin, string destination, DateTime travelTime) + { + var url = $"{Setting.ApiBaseUrl}/{APIUrls.GoogleCalculateRoute}"; + + RouteCalculationModel routeCalculationModel = new RouteCalculationModel(); + routeCalculationModel.Origin = origin ; + routeCalculationModel.Destination = destination ; + routeCalculationModel.TravelTime = travelTime ; + var response = await _httpClient.PostAsJsonAsync(url, routeCalculationModel); + var result = await response.Content.ReadAsStringAsync(); + //var user = JsonConvert.DeserializeObject(result); + return result; + } + public async Task> GetPlacePredictionsAsync(string input) + { + var url = $"{Setting.ApiBaseUrl}/{APIUrls.GoogleAutoComplete}"; + var response = await _httpClient.PostAsJsonAsync(url, input); + var result = await response.Content.ReadFromJsonAsync(typeof(List)); + //var user = JsonConvert.DeserializeObject(result); + _logger.Debug($"result: {result.GetType().FullName}"); + return (List)result; + } + } +} + + + diff --git a/TIAMWebApp/Shared/Services/SmartystreetsService.cs b/TIAMWebApp/Shared/Services/SmartystreetsService.cs new file mode 100644 index 00000000..db256fbd --- /dev/null +++ b/TIAMWebApp/Shared/Services/SmartystreetsService.cs @@ -0,0 +1,35 @@ +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; + +using TIAMWebApp.Shared.Application.Models; +using TIAMWebApp.Shared.Application.Models.ClientSide; + +namespace TIAMWebApp.Shared.Application.Services +{ + public class SmartyStreetsService + { + private readonly HttpClient _httpClient; + + public SmartyStreetsService(HttpClient httpClient) + { + _httpClient = httpClient; + } + + public async Task ValidateAddressAsync(string address) + { + + var url = $"{Setting.ApiBaseUrl}/{APIUrls.SmartyValidateAddress}"; + return await _httpClient.GetFromJsonAsync(url); + } + + public async Task SetExchangeRateAsync(ExchangeRate rate) + { + var url = $"{Setting.ApiBaseUrl}/{APIUrls.UpdateExchangeRate}"; + await _httpClient.PostAsJsonAsync(url, rate); + } + } +} + + +