Commission számítás, egyéb apró javítások, google autocomplete, google address validation, google route planning alapok

This commit is contained in:
Adam 2024-07-31 12:08:15 +02:00
parent 874315ad80
commit a7bee0bd1d
21 changed files with 608 additions and 160 deletions

View File

@ -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<string> 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<GooglePlacesResponse>(requestUri);
return response?.Candidates?.Length > 0 ? "Valid address" : "Invalid address";
}
public async Task<string> 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<GoogleDirectionsResponse>(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<List<string>> GetPlacePredictionsAsync(string input)
{
var requestUri = $"https://maps.googleapis.com/maps/api/place/autocomplete/json?input={input}&key={_apiKey}";
var response = await _httpClient.GetFromJsonAsync<GooglePlacesAutocompleteResponse>(requestUri);
var predictions = new List<string>();
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; }
}
}

View File

@ -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<string> 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<SmartyStreetsResponse[]>(requestUri);
return response?.Length > 0 ? "Valid address" : "Invalid address";
}
}
public class SmartyStreetsResponse
{
public string DeliveryLine1 { get; set; }
public string LastLine { get; set; }
}
}

View File

@ -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;
}
}
}

View File

@ -70,6 +70,8 @@ namespace TIAMMobileApp
builder.Services.AddSingleton<SumupService>();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();
builder.Services.AddScoped<ExchangeRateService>();
builder.Services.AddScoped<SmartyStreetsService>();
builder.Services.AddScoped<GooglePlacesService>();
builder.Services.AddAuthorizationCore();
builder.Services.Configure<AnimationOptions>(Guid.NewGuid().ToString(), c => { });
return builder.Build();

View File

@ -0,0 +1,56 @@
@using AyCode.Blazor.Components.Components
@using TIAMWebApp.Shared.Application.Services
@inject GooglePlacesService GooglePlacesService
<h4>
@NullText
</h4>
<DxTextBox @bind-Text="Address"
@oninput="OnInputChanged"
BindValueMode="BindValueMode.OnDelayedInput"
InputDelay="500">
</DxTextBox>
@if (Predictions.Count > 0)
{
<DxComboBox Data="@Predictions"
ValueFieldName="Description"
TextFieldName="Description"
@bind-Value="SelectedPrediction">
</DxComboBox>
}
@code {
[Parameter] public string NullText { get; set; }
[Parameter] public EventCallback<string> AddressChanged { get; set; }
private string Address { get; set; }
private List<PredictionItem> 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; }
}
}

View File

@ -24,8 +24,8 @@
<PageTitle>Create transfer</PageTitle>
<div class="text-center m-5">
<h1>Drivers</h1>
<h2 style="font-size:small">Manage drivers here!</h2>
<h1>Create transfer</h1>
<h2 style="font-size:small">Order a new transfer here!</h2>
</div>
<!--We need to check if the user is owner of a swerviceprovider-->

View File

@ -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;
}
}

View File

@ -55,19 +55,36 @@
</NavLink>
</li>
<li>
<NavLink href="@($"mytransfers/{Guid.Parse("108E5A63-AA9E-47BE-ACFA-00306FFC5215")}")">
My transfers
</NavLink>
</li>
<li>
<NavLink href="exchange-rate">
Exchange Rate
</NavLink>
</li>
<li>
<NavLink href="route-calculation">
Google route calculation
</NavLink>
</li>
<li>
<NavLink href="google-address-validation">
Google address validation
</NavLink>
</li>
<li>
<NavLink href="smarty-address-validation">
Smarty address validation
</NavLink>
</li>
<li>
<NavLink href="address-autocomplete">
Google autocomplete
</NavLink>
</li>
<li></li>
</ul>

View File

@ -0,0 +1,14 @@
@page "/address-autocomplete"
@using DevExpress.Blazor
@using TIAMSharedUI.Pages.Components
<AddressSearchAndSelectComponent AddressChanged="@OnSelectedAddressChanged" NullText="Search for an address"></AddressSearchAndSelectComponent>
<p>@resultAddress</p>
@code {
private string resultAddress = "";
private void OnSelectedAddressChanged(string address) {
resultAddress = address;
}
}

View File

@ -0,0 +1,28 @@
@page "/google-address-validation"
@using DevExpress.Blazor
@using TIAMWebApp.Shared.Application.Services
@inject GooglePlacesService GooglePlacesService
<DxFormLayout>
<DxFormLayoutGroup Caption="Address Validation">
<DxFormLayoutItem Caption="Address">
<DxTextBox @bind-Text="Address" />
</DxFormLayoutItem>
<DxFormLayoutItem>
<DxButton Context="ButtonContext" Click="ValidateAddress">Validate Address</DxButton>
</DxFormLayoutItem>
<DxFormLayoutItem>
<p>@ValidationMessage</p>
</DxFormLayoutItem>
</DxFormLayoutGroup>
</DxFormLayout>
@code {
private string Address { get; set; }
private string ValidationMessage { get; set; }
private async Task ValidateAddress()
{
ValidationMessage = await GooglePlacesService.ValidateAddressAsync(Address);
}
}

View File

@ -0,0 +1,41 @@
@page "/route-calculation"
@using DevExpress.Blazor
@using TIAMWebApp.Shared.Application.Services
@inject GooglePlacesService GooglePlacesService
<DxFormLayout>
<DxFormLayoutGroup Context="LayoutGroupContext" Caption="Route Calculation">
<DxFormLayoutItem Caption="Origin Address">
<DxTextBox @bind-Text="OriginAddress" />
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Destination Address">
<DxTextBox @bind-Text="DestinationAddress" />
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Travel Date">
<DxDateEdit @bind-Date="TravelDate" />
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Travel Time">
<DxTimeEdit @bind-Time="TravelTime" />
</DxFormLayoutItem>
<DxFormLayoutItem>
<DxButton Context="ButtonContext" Click="CalculateRoute">Calculate Route</DxButton>
</DxFormLayoutItem>
<DxFormLayoutItem>
<p>@RouteMessage</p>
</DxFormLayoutItem>
</DxFormLayoutGroup>
</DxFormLayout>
@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);
}
}

View File

@ -0,0 +1,29 @@
@page "/smarty-address-validation"
@using DevExpress.Blazor
@using TIAMWebApp.Shared.Application.Services
@inject SmartyStreetsService SmartyStreetsService
<DxFormLayout>
<DxFormLayoutGroup Caption="Address Validation">
<DxFormLayoutItem Caption="Address">
<DxTextBox @bind-Text="Address" />
</DxFormLayoutItem>
<DxFormLayoutItem>
<DxButton Context="ButtonContext" Click="ValidateAddress">Validate Address</DxButton>
</DxFormLayoutItem>
<DxFormLayoutItem>
<p>@ValidationMessage</p>
</DxFormLayoutItem>
</DxFormLayoutGroup>
</DxFormLayout>
@code {
private string Address { get; set; }
private string ValidationMessage { get; set; }
private async Task ValidateAddress()
{
ValidationMessage = await SmartyStreetsService.ValidateAddressAsync(Address);
}
}

View File

@ -47,6 +47,8 @@ builder.Services.AddSingleton<SumupService>();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<ExchangeRateService>();
builder.Services.AddScoped<SmartyStreetsService>();
builder.Services.AddScoped<GooglePlacesService>();
//builder.Services.AddScoped<BrowserConsoleLogWriter>();
//WebSpecific end

View File

@ -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<SupplierAPIController> _logger;
private readonly GooglePlacesService _googlePlacesService;
public GoogleAPIController(ILogger<SupplierAPIController> logger)
public GoogleAPIController(ILogger<SupplierAPIController> logger, GooglePlacesService googlePlacesService)
{
_logger = logger;
_googlePlacesService = googlePlacesService;
}
[HttpPost]
[Route("GetAddressForCoordinates")]
public async Task<string?> GetAddressForCoordinates(TripInfo myTrip)
{
//[HttpPost]
//[Route("GetAddressForCoordinates")]
//public async Task<string?> 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<string> ValidateAddress(string address)
[Route(APIUrls.GoogleValidateAddressRouteName)]
public async Task<string> ValidateAddress([FromBody] string address)
{
var request = new AddressValidationRequest
{
Key = _apiKey,
Address = new PostalAddress
{
AddressLines = new List<string>
{
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<string> GetTravelTimeWithGoogleMatrix()
[HttpPost]
[Route(APIUrls.GoogleCalculateRouteRouteName)]
public async Task<string> 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<string> 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();
}
}

View File

@ -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<IAcLogWriterBase> logWriters) : ControllerBase
{
private readonly TIAM.Core.Loggers.Logger<SmartyStreetsAPIController> _logger = new(logWriters.ToArray());
[AllowAnonymous]
[HttpPost]
[Route(APIUrls.SmartyValidateAddress)]
//[SignalR(SignalRTags.GetProfileById)]
public async Task<IActionResult> Set([FromBody] string address)
{
_logger.Info($@"GetServiceProviderById called with rate: {address}");
var result = await _service.ValidateAddressAsync(address);
return Ok(result);
}
}
}

View File

@ -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;
}
}

View File

@ -48,6 +48,8 @@ builder.Services.AddScoped<MessageAPIController>();
builder.Services.AddScoped<ProfileAPIController>();
builder.Services.AddScoped<LoggerApiController>();
builder.Services.AddSingleton<ExchangeRateService>();
builder.Services.AddScoped<SmartyStreetsService>();
builder.Services.AddScoped<GooglePlacesService>();
builder.Services.AddSignalR(options => options.MaximumReceiveMessageSize = 102400 * 1024);//.AddMessagePackProtocol(options => options.SerializerOptions = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData));

View File

@ -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;
}
}

View File

@ -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; }
}
}

View File

@ -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<IAcLogWriterClientBase> logWriters)
{
_httpClient = httpClient;
_logger = new LoggerClient<TransferDataService>(logWriters.ToArray());
}
public async Task<string> 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<UserModelDto>(result);
return result;
}
public async Task<string> 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<UserModelDto>(result);
return result;
}
public async Task<List<string>> GetPlacePredictionsAsync(string input)
{
var url = $"{Setting.ApiBaseUrl}/{APIUrls.GoogleAutoComplete}";
var response = await _httpClient.PostAsJsonAsync(url, input);
var result = await response.Content.ReadFromJsonAsync(typeof(List<string>));
//var user = JsonConvert.DeserializeObject<UserModelDto>(result);
_logger.Debug($"result: {result.GetType().FullName}");
return (List<string>)result;
}
}
}

View File

@ -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<string> ValidateAddressAsync(string address)
{
var url = $"{Setting.ApiBaseUrl}/{APIUrls.SmartyValidateAddress}";
return await _httpClient.GetFromJsonAsync<string>(url);
}
public async Task SetExchangeRateAsync(ExchangeRate rate)
{
var url = $"{Setting.ApiBaseUrl}/{APIUrls.UpdateExchangeRate}";
await _httpClient.PostAsJsonAsync(url, rate);
}
}
}