From 243ab13abbcac34d875cee552c8300eb5568c50a Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 5 Apr 2024 17:56:17 +0200 Subject: [PATCH] ... --- .../Services/UserDataServiceMobile.cs | 34 +++++- TIAMSharedUI/Pages/Formula1.razor | 100 +++++++++++++----- .../Client/Services/UserDataServiceWeb.cs | 37 ++++++- .../Server/Controllers/UserAPIController.cs | 71 ++++++++++++- .../Shared/Interfaces/IUserDataService.cs | 1 + TIAMWebApp/Shared/Models/APIUrls.cs | 3 + .../UI/WizardModels/TransferWizardModel.cs | 4 +- .../Models/PageModels/RegistrationModel.cs | 19 ++++ 8 files changed, 236 insertions(+), 33 deletions(-) diff --git a/TIAMMobileApp/Services/UserDataServiceMobile.cs b/TIAMMobileApp/Services/UserDataServiceMobile.cs index 67c15f46..5e6dd506 100644 --- a/TIAMMobileApp/Services/UserDataServiceMobile.cs +++ b/TIAMMobileApp/Services/UserDataServiceMobile.cs @@ -119,6 +119,34 @@ namespace TIAMMobileApp.Services return (isSuccess, result); } + public async Task<(bool isSuccess, UserModelDto? user)> CreateGuestUser(RegistrationModel regModel) + { + + bool isSuccess = false; + string result = string.Empty; + UserModelDto? user; + var url = $"{Setting.ApiBaseUrl}/{APIUrls.CreateGuestUser}"; + + var response = await http.PostAsJsonAsync(url, regModel); + + + if (response.IsSuccessStatusCode) + { + isSuccess = true; + result = await response.Content.ReadAsStringAsync(); + user = JsonConvert.DeserializeObject(result); + } + else + { + isSuccess = false; + result = await response.Content.ReadAsStringAsync(); + user = null; + } + + + return (isSuccess, user); + } + public async Task?> GetUsersAsync() { return await http.GetFromJsonAsync>(APIUrls.GetUsers); @@ -126,7 +154,11 @@ namespace TIAMMobileApp.Services public async Task GetUserByEmailAsync(string email) { - return await http.GetFromJsonAsync(APIUrls.GetUserByEmail); + var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserByEmail}"; + var response = await http.PostAsJsonAsync(url, email); + var result = await response.Content.ReadAsStringAsync(); + var user = JsonConvert.DeserializeObject(result); + return user; } public async Task GetUserByIdAsync(Guid id) { diff --git a/TIAMSharedUI/Pages/Formula1.razor b/TIAMSharedUI/Pages/Formula1.razor index f080f5c4..0259c667 100644 --- a/TIAMSharedUI/Pages/Formula1.razor +++ b/TIAMSharedUI/Pages/Formula1.razor @@ -2,12 +2,14 @@ @using AyCode.Interfaces.StorageHandlers; @using BlazorAnimation @using Newtonsoft.Json; +@using TIAM.Entities.Transfers @using TIAMSharedUI.Shared.Components @using TIAMWebApp.Shared.Application.Interfaces @using TIAMWebApp.Shared.Application.Models.ClientSide; @using AyCode.Blazor.Components; @using TIAMWebApp.Shared.Application.Models; @using TIAMWebApp.Shared.Application.Models.ClientSide.UI +@using TIAMWebApp.Shared.Application.Models.PageModels @using TIAMWebApp.Shared.Application.Utility; @using System.IdentityModel.Tokens.Jwt; @using TIAMSharedUI.Pages.Components; @@ -322,7 +324,7 @@ CssClass="text-white"> - + @@ -398,35 +400,51 @@ new HeroSliderItem public async Task SubmitForm(object result) { var orderModel = result as TransferWizardModel; - List TransferList = new List(); - foreach (var date in OrderDates) + //check if user exists + if (sessionService.IsAuthenticated) { - - TransferWizardModel transfer = orderModel.Clone(); - transfer.TripDate = new DateTime(2024, 07, date); //Basic settings - if (sessionService.IsAuthenticated) - { - transfer.UserId = sessionService.User.UserModelDto.Id; - transfer.ProductId = sessionService.User.UserModelDto.Products.FirstOrDefault().Id; - } - transfer.Price = null; - - // Outbound trip - transfer.PickupAddress = OrderLocation; - transfer.Destination = "Hungaroring"; - TransferList.Add(transfer); - - // Return trip - transfer = orderModel.Clone(); - transfer.TripDate = new DateTime(2024, 07, date); - transfer.PickupAddress = "Hungaroring"; - transfer.Destination = OrderLocation; - TransferList.Add(transfer); + orderModel.UserId = sessionService.User.UserModelDto.Id; + orderModel.ProductId = sessionService.User.UserModelDto.Products.FirstOrDefault().Id; } - - var transferResult = await transferDataService.CreateTransfers(TransferList); - logToBrowserConsole.LogToBC($"Submitted nested form: {transferResult.GetType().FullName}, {transferResult.Count}"); + else + { + //cherck if user exists + var user = await UserDataService.GetUserByEmailAsync(orderModel.EmailAddress); + + if (user.Id == Guid.Empty) + user = null; + + if (user != null) + { + orderModel.UserId = user.Id; + + orderModel.ProductId = user.Products.FirstOrDefault()?.Id; + } + else + { + //if not, create user + + Random random = new Random(); + string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + string password = new string(Enumerable.Repeat(chars, 10) + .Select(s => s[random.Next(s.Length)]).ToArray()); + + RegistrationModel regModel = new RegistrationModel + { + PhoneNumber = orderModel.PhoneNumber, + Email = orderModel.EmailAddress, + Password = password, + ReferralId = Guid.Empty + }; + + var bleh = await UserDataService.CreateGuestUser(regModel); + orderModel.UserId = bleh.user.Id; + + } + } + + await ProcessTransfers(orderModel); } protected override void OnInitialized() @@ -450,6 +468,34 @@ new HeroSliderItem OrderLocation = location; showWizard = true; } + + public async Task> ProcessTransfers(TransferWizardModel orderModel) + { + List TransferList = new List(); + foreach (var date in OrderDates) + { + + TransferWizardModel transfer = orderModel.Clone(); + transfer.TripDate = new DateTime(2024, 07, date); + + + // Outbound trip + transfer.PickupAddress = OrderLocation; + transfer.Destination = "Hungaroring"; + TransferList.Add(transfer); + + // Return trip + transfer = orderModel.Clone(); + transfer.TripDate = new DateTime(2024, 07, date); + transfer.PickupAddress = "Hungaroring"; + transfer.Destination = OrderLocation; + TransferList.Add(transfer); + } + + var transferResult = await transferDataService.CreateTransfers(TransferList); + logToBrowserConsole.LogToBC($"Submitted nested form: {transferResult.GetType().FullName}, {transferResult.Count}"); + return transferResult; + } } diff --git a/TIAMWebApp/Client/Services/UserDataServiceWeb.cs b/TIAMWebApp/Client/Services/UserDataServiceWeb.cs index a0e3c983..572aa292 100644 --- a/TIAMWebApp/Client/Services/UserDataServiceWeb.cs +++ b/TIAMWebApp/Client/Services/UserDataServiceWeb.cs @@ -12,6 +12,7 @@ using TIAMWebApp.Shared.Application.Utility; using AyCode.Interfaces.StorageHandlers; using AyCode.Core.Logger; using TIAM.Models.Dtos.Users; +using Azure; namespace TIAMWebApp.Client.Services @@ -125,6 +126,36 @@ namespace TIAMWebApp.Client.Services return (isSuccess, result); } + public async Task<(bool isSuccess, UserModelDto? user)> CreateGuestUser(RegistrationModel regModel) + { + + bool isSuccess = false; + string result = string.Empty; + UserModelDto? user = new UserModelDto(); + var url = $"{Setting.ApiBaseUrl}/{APIUrls.CreateGuestUser}"; + logToBrowserConsole.LogToBC("CreateGuestUser url: " + url); + var response = await http.PostAsJsonAsync(url, regModel); + + + if (response.IsSuccessStatusCode) + { + isSuccess = true; + result = await response.Content.ReadAsStringAsync(); + logToBrowserConsole.LogToBC("CreateGuestUser result: " + result); + user = JsonConvert.DeserializeObject(result); + } + else + { + isSuccess = false; + result = await response.Content.ReadAsStringAsync(); + user = null; + } + + + return (isSuccess, user); + } + + public async Task?> GetUsersAsync() { return await http.GetFromJsonAsync>(APIUrls.GetUsers); @@ -133,7 +164,11 @@ namespace TIAMWebApp.Client.Services public async Task GetUserByEmailAsync(string email) { var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserByEmail}"; - return await http.GetFromJsonAsync(url); + logToBrowserConsole.LogToBC("GetUserByEmailAsync url: " + url + ", " + email); + var response = await http.PostAsJsonAsync(url, email); + var result = await response.Content.ReadAsStringAsync(); + var user = JsonConvert.DeserializeObject(result); + return user; } public async Task GetUserByIdAsync(Guid id) diff --git a/TIAMWebApp/Server/Controllers/UserAPIController.cs b/TIAMWebApp/Server/Controllers/UserAPIController.cs index e8481d29..d519d094 100644 --- a/TIAMWebApp/Server/Controllers/UserAPIController.cs +++ b/TIAMWebApp/Server/Controllers/UserAPIController.cs @@ -23,6 +23,10 @@ using TIAM.Entities.Users; using TIAM.Models.Dtos.Users; using TIAMWebApp.Server.ModelsTIAMWebApp.Shared.Application.Models; using TIAMWebApp.Shared.Application.Utility; +using TIAM.Database.DataLayers.Admins; +using System; +using TIAM.Entities.Profiles; +using TIAM.Entities.Addresses; namespace TIAMWebApp.Server.Controllers { @@ -32,6 +36,7 @@ namespace TIAMWebApp.Server.Controllers public class UserAPIController : ControllerBase { private UserDal _userDal; + private AdminDal _adminDal; private readonly IConfiguration _configuration; private readonly IWebHostEnvironment _webHostEnvironment; readonly PasswordHasher _hasher = new(); @@ -46,12 +51,13 @@ namespace TIAMWebApp.Server.Controllers private readonly ILogger _logger; - public UserAPIController(ILogger logger, IConfiguration configuration, IWebHostEnvironment webHostEnvironment, UserDal userDal) + public UserAPIController(ILogger logger, IConfiguration configuration, IWebHostEnvironment webHostEnvironment, UserDal userDal, AdminDal adminDal) { _logger = logger; _configuration = configuration; _webHostEnvironment = webHostEnvironment; _userDal = userDal; + _adminDal = adminDal; } @@ -304,6 +310,65 @@ namespace TIAMWebApp.Server.Controllers } } + [AllowAnonymous] + [HttpPost] + [Route(APIUrls.CreateGuestUserRouteName)] + public async Task CreateGuestUser([FromBody] JsonElement SerializedRegistrationModel) + { + Console.WriteLine("CreateGuestUser called"); + bool result = false; + UserModelDtoDetail? guestUser = null; + + if (string.IsNullOrEmpty(SerializedRegistrationModel.GetRawText())) + { + return BadRequest("SerializedLoginModel is required"); + } + else + { + var user = JObject.Parse(SerializedRegistrationModel.GetRawText()).ToObject(); + + if (user != null) + { + Random random = new Random(); + string chars = "1234567890"; + string nameExtension = new string(Enumerable.Repeat(chars, 10) + .Select(s => s[random.Next(s.Length)]).ToArray()); + + + var userId = Guid.NewGuid(); + var email = user?.Email; + var phoneNumber = user?.PhoneNumber; + var password = user?.Password; + Guid? referralId = user?.ReferralId; + + if (email is null || phoneNumber is null || password is null) + { + return BadRequest("Invalid request"); + } + else + { + Console.WriteLine($"User to be created: {userId}"); + Console.WriteLine($"User to be created: {email}"); + Console.WriteLine($"User to be created: {phoneNumber}"); + Console.WriteLine($"User to be created: {password}"); + User userToCreate = new(userId, email, phoneNumber, password); + userToCreate.Profile = new Profile(); + userToCreate.Profile.Name = "Guest-" + nameExtension; + userToCreate.RefferalId = referralId; + Random rnd = new Random(); + userToCreate.Profile.Address = new Address(); + userToCreate.Profile.Address.AddressText = "NAN"; + userToCreate.Profile.Address.Latitude = Math.Round(90 + rnd.NextDouble(), 8); + userToCreate.Profile.Address.Longitude = Math.Round(180 + rnd.NextDouble(), 8); + result = await _adminDal.AddUser(userToCreate); + guestUser = await _userDal.GetUserModelDtoDetailByIdAsync(userId); + } + } + + return Ok(guestUser); + } + } + [HttpPost] [Route("Test1")] public async Task TestEndpoint([FromBody] int testParam) @@ -331,10 +396,12 @@ namespace TIAMWebApp.Server.Controllers } [AllowAnonymous] - [HttpGet] + [HttpPost] [Route("GetUserByEmail")] public Task GetUserByEmail(string email) { + Logger.Info($"GetUserByEmail called with email: {email}"); + Console.WriteLine($"GetUserByEmail called with email: {email}"); return _userDal.GetUserModelDtoByEmailAsync(email); } diff --git a/TIAMWebApp/Shared/Interfaces/IUserDataService.cs b/TIAMWebApp/Shared/Interfaces/IUserDataService.cs index ca4bf60c..a0ef4e87 100644 --- a/TIAMWebApp/Shared/Interfaces/IUserDataService.cs +++ b/TIAMWebApp/Shared/Interfaces/IUserDataService.cs @@ -18,6 +18,7 @@ namespace TIAMWebApp.Shared.Application.Interfaces public Task AuthenticateUser(LoginModel loginModel); public Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel); + public Task<(bool isSuccess, UserModelDto? user)> CreateGuestUser(RegistrationModel regModel); public Task TestUserApi(int Param); //public Task> GetUserRolesAsync(UserModel userModel); diff --git a/TIAMWebApp/Shared/Models/APIUrls.cs b/TIAMWebApp/Shared/Models/APIUrls.cs index 31582e87..05ff6d0e 100644 --- a/TIAMWebApp/Shared/Models/APIUrls.cs +++ b/TIAMWebApp/Shared/Models/APIUrls.cs @@ -37,6 +37,9 @@ namespace TIAMWebApp.Shared.Application.Models public const string CreateUserRouteName = "CreateUser"; public const string CreateUser = UserAPI + CreateUserRouteName; + public const string CreateGuestUserRouteName = "CreateGuestUser"; + public const string CreateGuestUser = UserAPI + CreateGuestUserRouteName; + public const string RefreshTokenRouteName = "RefreshToken"; public const string RefreshToken = UserAPI + RefreshTokenRouteName; diff --git a/TIAMWebApp/Shared/Models/ClientSide/UI/WizardModels/TransferWizardModel.cs b/TIAMWebApp/Shared/Models/ClientSide/UI/WizardModels/TransferWizardModel.cs index 940f8bb1..ce87d9f7 100644 --- a/TIAMWebApp/Shared/Models/ClientSide/UI/WizardModels/TransferWizardModel.cs +++ b/TIAMWebApp/Shared/Models/ClientSide/UI/WizardModels/TransferWizardModel.cs @@ -16,12 +16,12 @@ namespace TIAMWebApp.Shared.Application.Models.ClientSide.UI.WizardModels { public Guid Id { get; set; } public Guid UserId { get; set; } - public Guid ProductId { get; set; } + public Guid? ProductId { get; set; } public Guid UserProductMappingId { get; set; } public Guid UserProductToCarId { get; set; } - public Guid ReferralId { get; set; } + public Guid? ReferralId { get; set; } public string ? Comment { get; set; } diff --git a/TIAMWebApp/Shared/Models/PageModels/RegistrationModel.cs b/TIAMWebApp/Shared/Models/PageModels/RegistrationModel.cs index 255dd946..db401aba 100644 --- a/TIAMWebApp/Shared/Models/PageModels/RegistrationModel.cs +++ b/TIAMWebApp/Shared/Models/PageModels/RegistrationModel.cs @@ -15,6 +15,25 @@ namespace TIAMWebApp.Shared.Application.Models.PageModels public string? Password { get; set; } public string? PhoneNumber { get; set; } + + public Guid? ReferralId { get; set; } + + public RegistrationModel() { } + + public RegistrationModel(string email, string password, string phoneNumber, Guid referralId) + { + Email = email; + Password = password; + PhoneNumber = phoneNumber; + ReferralId = referralId; + } + + public RegistrationModel(string email, string password, string phoneNumber) + { + Email = email; + Password = password; + PhoneNumber = phoneNumber; + } } }