This commit is contained in:
Adam 2024-09-01 09:24:14 +02:00
commit 7a88cdd21f
35 changed files with 730 additions and 743 deletions

View File

@ -148,10 +148,11 @@ namespace TIAM.Database.DataLayers.Admins
#region TransferDestination #region TransferDestination
public List<TransferDestination> GetTransferDestinations() => Session(ctx => ctx.GetTransferDestinations().ToList()); public Task<List<TransferDestination>> GetTransferDestinationsAsync() => SessionAsync(ctx => ctx.GetTransferDestinations().ToList());
public TransferDestination? GetTransferDestinationById(Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationById(transferDestinationId)); public TransferDestination? GetTransferDestinationById(Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationById(transferDestinationId));
public Task<TransferDestination?> GetTransferDestinationByIdAsync(Guid transferDestinationId) => SessionAsync(ctx => ctx.GetTransferDestinationById(transferDestinationId)); public Task<TransferDestination?> GetTransferDestinationByIdAsync(Guid transferDestinationId) => SessionAsync(ctx => ctx.GetTransferDestinationById(transferDestinationId));
public string? GetTransferDestinationJsonById(Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationById(transferDestinationId)?.ToJson()); public Task<List<TransferDestination>> GetPublicTransferDestinationsAsync(Guid productId) => SessionAsync(ctx => ctx.GetTransferDestinations().Where(x => !x.ProductId.HasValue || x.ProductId == productId).ToList());
public Task<bool> AddTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.AddTransferDestination(transferDestination)); public Task<bool> AddTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.AddTransferDestination(transferDestination));
public Task<bool> UpdateTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.UpdateTransferDestination(transferDestination)); public Task<bool> UpdateTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.UpdateTransferDestination(transferDestination));

View File

@ -16,6 +16,7 @@ namespace TIAM.Entities.Transfers
[ForeignKey(nameof(AddressId))] [ForeignKey(nameof(AddressId))]
public virtual Address Address { get; set; } public virtual Address Address { get; set; }
public Guid? ProductId { get; set; }
//public virtual List<Product> Products { get; set; } //public virtual List<Product> Products { get; set; }
//public virtual List<TransferDestinationToProduct> TransferDestinationToProducts { get; set; } //public virtual List<TransferDestinationToProduct> TransferDestinationToProducts { get; set; }

View File

@ -1,5 +1,9 @@
namespace TIAM.Services.Interfaces; using TIAM.Entities.Transfers;
public interface ITransferApiControllerClient : IUserApiControllerCommon namespace TIAM.Services.Interfaces;
public interface ITransferApiControllerClient : ITransferApiControllerCommon
{ {
Task GetTransferDestinationsAsync(List<TransferDestination> intoDestinationList, Action? callback = null);
Task GetPublicTransferDestinationsAsync(List<TransferDestination> intoDestinationList, Guid includeProductId, Action? callback = null);
} }

View File

@ -26,7 +26,8 @@ public interface ITransferApiControllerCommon
#endregion Drivers #endregion Drivers
#region TransferDestination #region TransferDestination
public List<TransferDestination> GetTransferDestinations(); public Task<List<TransferDestination>> GetTransferDestinations();
public Task<List<TransferDestination>> GetPublicTransferDestinations(Guid includeProductId);
public Task<TransferDestination?> GetTransferDestinationById(Guid transferDestinationId); public Task<TransferDestination?> GetTransferDestinationById(Guid transferDestinationId);
public Task<TransferDestination?> CreateTransferDestination(TransferDestination transferDestination); public Task<TransferDestination?> CreateTransferDestination(TransferDestination transferDestination);
public Task<TransferDestination?> UpdateTransferDestination(TransferDestination transferDestination); public Task<TransferDestination?> UpdateTransferDestination(TransferDestination transferDestination);

View File

@ -100,9 +100,10 @@ public class SignalRTags : AcSignalRTags
public const int GetTransferDestinationById = 80; public const int GetTransferDestinationById = 80;
public const int GetAllTransferDestinations = 81; public const int GetAllTransferDestinations = 81;
public const int CreateTransferDestination = 82; public const int GetAllTransferDestinationsByProductId = 82;
public const int UpdateTransferDestination = 83; public const int CreateTransferDestination = 83;
public const int RemoveTransferDestination = 84; //set permissions to 0 public const int UpdateTransferDestination = 84;
public const int RemoveTransferDestination = 85; //set permissions to 0
public const int CreateTransferDestinationToProduct = 90; public const int CreateTransferDestinationToProduct = 90;
public const int UpdateTransferDestinationToProduct = 91; public const int UpdateTransferDestinationToProduct = 91;
@ -113,8 +114,13 @@ public class SignalRTags : AcSignalRTags
public const int GetTransferDestinationToProductsByTransferDestinationId = 96; public const int GetTransferDestinationToProductsByTransferDestinationId = 96;
public const int GetAllUsers = 120; public const int GetAllUsers = 120;
public const int GetAllUserModelDtoDetails = 121; public const int GetAllUserModelDto = 121;
public const int GetAllUserModelDtoEmails = 125; public const int GetAllUserModelDtoDetails = 122;
public const int GetAllUserModelDtoEmails = 123;
public const int GetUserModelDtoById = 126;
public const int GetUserModelDtoByEmail = 127;
public const int GetUserModelDtoDetailById = 128;
public const int GetUserModelDtoDetailByEmail = 129;
public const int AddUser = 130; public const int AddUser = 130;
public const int AddUserModelDtoDetail = 131; public const int AddUserModelDtoDetail = 131;
public const int UpdateUser = 135; public const int UpdateUser = 135;
@ -125,5 +131,6 @@ public class SignalRTags : AcSignalRTags
public const int GuestUpdateTransfer = 150; public const int GuestUpdateTransfer = 150;
public const int DriverUpdateTransfer = 151; public const int DriverUpdateTransfer = 151;
public const int AuthenticateUser = 160;
public const int GetAllLogItemsByFilterText = 1000; public const int GetAllLogItemsByFilterText = 1000;
} }

View File

@ -17,7 +17,7 @@ using TIAMWebApp.Shared.Application.Utility;
namespace TIAMMobileApp.Services namespace TIAMMobileApp.Services
{ {
public class UserDataServiceMobile(HttpClient http, ISessionService sessionService, ISecureStorageHandler secureStorageHandler, IServiceProviderDataService serviceProviderDataService, IEnumerable<IAcLogWriterClientBase> logWriters) public class UserDataServiceMobile(HttpClient http, AdminSignalRClient adminSignalRClient, ISessionService sessionService, ISecureStorageHandler secureStorageHandler, IServiceProviderDataService serviceProviderDataService, IEnumerable<IAcLogWriterClientBase> logWriters)
: UserDataServiceClientBase(http, sessionService, secureStorageHandler, serviceProviderDataService, logWriters); : UserDataServiceClientBase(http, adminSignalRClient, sessionService, secureStorageHandler, serviceProviderDataService, logWriters);
} }

View File

@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Text.Json; using System.Text.Json;
using AyCode.Core.Extensions;
using AyCode.Core.Helpers; using AyCode.Core.Helpers;
using TIAMWebApp.Shared.Application.Models.ClientSide; using TIAMWebApp.Shared.Application.Models.ClientSide;
using TIAMWebApp.Shared.Application.Models; using TIAMWebApp.Shared.Application.Models;
@ -64,80 +65,79 @@ namespace TIAMSharedUI.Pages
{ {
_currentStep = 1; _currentStep = 1;
BrowserConsoleLogWriter.Info("Login started: " + "Email: " + _loginModel.Email + ", Password: " + _loginModel.Password); BrowserConsoleLogWriter.Info("Login started: " + "Email: " + _loginModel.Email + ", Password: " + _loginModel.Password);
var response = await userDataService.AuthenticateUser(_loginModel);
var mainResponse = await userDataService.AuthenticateUser(_loginModel);
//var response = await UserDataservice.TestUserApi(30); //var response = await UserDataservice.TestUserApi(30);
BrowserConsoleLogWriter.Info("Login started"); BrowserConsoleLogWriter.Info("Login started");
BrowserConsoleLogWriter.Info(response); //BrowserConsoleLogWriter.Info(response);
if (!string.IsNullOrEmpty(response)) //if (!string.IsNullOrEmpty(response))
if (mainResponse != null)
{ {
//get token and save to local storage //get token and save to local storage
//parse to Mainresponse from json string //parse to Mainresponse from json string
//var Mainresponse = JsonSerializer.Deserialize<MainResponse>(response); //var Mainresponse = JsonSerializer.Deserialize<MainResponse>(response);
var mainResponse = JsonSerializer.Deserialize<MainResponse>(response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); //var mainResponse = JsonSerializer.Deserialize<MainResponse>(response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (mainResponse != null) if (!mainResponse.IsSuccess)
{ {
//await App.Current.MainPage.DisplayAlert("Error", "Invalid credentials", "Ok");
//display error message via jsinterop
BrowserConsoleLogWriter.Info("Invalid credentials");
messageClass = "text-danger";
resultMessage = "Invalid credentials";
await InvokeAsync(StateHasChanged);
//navManager.NavigateTo("login");
}
else
{
string authResponseJson = mainResponse.Content.ToJson(); //JsonSerializer.Serialize(mainResponse.Content);
if (!mainResponse.IsSuccess) var authResponse = authResponseJson.JsonTo<AuthenticationResponse>(); //JsonSerializer.Deserialize<AuthenticationResponse>(authResponseJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
string accessToken = authResponse.AccessToken;
var token = ProcessToken(accessToken);
string userId = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value;
string email = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
var myId = Guid.Parse(userId);
//userDataService.User.Email = _email;
var userBasicDetails = new UserBasicDetails(userId, email, authResponse.AccessToken, authResponse.RefreshToken);
string userBasicDetailsJson = JsonSerializer.Serialize(userBasicDetails);
//save to local storage
await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userBasicDetailsJson);
await AuthStateProvider.GetAuthenticationStateAsync();
//await App.Current.MainPage.DisplayAlert("Success", "Successful login", "Ok");
//display success message via jsinterop
BrowserConsoleLogWriter.Info("Successful login");
var user = await userDataService.IsLoggedInAsync(myId);
_adminSignalRClient.GetByIdAsync<SiteViewModel>(SignalRTags.GetSiteViewModelByUserId, signalResponseMessage =>
{ {
//await App.Current.MainPage.DisplayAlert("Error", "Invalid credentials", "Ok"); sessionService.SiteViewModel.Initialize(signalResponseMessage.ResponseData!);
//display error message via jsinterop BrowserConsoleLogWriter.Debug($"UnreadMessages: {sessionService.SiteViewModel.UnreadMessages.Count}");
BrowserConsoleLogWriter.Info("Invalid credentials");
messageClass = "text-danger";
resultMessage = "Invalid credentials";
await InvokeAsync(StateHasChanged);
//navManager.NavigateTo("login");
}
else
{
string authResponseJson = JsonSerializer.Serialize(mainResponse.Content);
var authResponse = JsonSerializer.Deserialize<AuthenticationResponse>(authResponseJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); componentUpdateService.CallRequestRefreshAll();
return Task.CompletedTask;
}, user.UserId).Forget();
string accessToken = authResponse.AccessToken; messageClass = "text-success";
resultMessage = "Successful login";
var token = ProcessToken(accessToken); SaveToSessionInfo(user).Forget();
navManager.NavigateTo("/");
string userId = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value;
string email = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
var myId = Guid.Parse(userId);
//userDataService.User.Email = _email;
var userBasicDetails = new UserBasicDetails(userId, email, authResponse.AccessToken, authResponse.RefreshToken);
string userBasicDetailsJson = JsonSerializer.Serialize(userBasicDetails);
//save to local storage
await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userBasicDetailsJson);
await AuthStateProvider.GetAuthenticationStateAsync();
//await App.Current.MainPage.DisplayAlert("Success", "Successful login", "Ok");
//display success message via jsinterop
BrowserConsoleLogWriter.Info("Successful login");
var user = await userDataService.IsLoggedInAsync(myId);
_adminSignalRClient.GetByIdAsync<SiteViewModel>(SignalRTags.GetSiteViewModelByUserId, signalResponseMessage =>
{
sessionService.SiteViewModel.Initialize(signalResponseMessage.ResponseData!);
BrowserConsoleLogWriter.Debug($"UnreadMessages: {sessionService.SiteViewModel.UnreadMessages.Count}");
componentUpdateService.CallRequestRefreshAll();
return Task.CompletedTask;
}, user.UserId).Forget();
messageClass = "text-success";
resultMessage = "Successful login";
SaveToSessionInfo(user).Forget();
navManager.NavigateTo("/");
}
} }
} }
else else
@ -145,10 +145,9 @@ namespace TIAMSharedUI.Pages
//api error //api error
//await App.Current.MainPage.DisplayAlert("Error", "An error occured while trying to login", "Ok"); //await App.Current.MainPage.DisplayAlert("Error", "An error occured while trying to login", "Ok");
//display error message via jsinterop //display error message via jsinterop
BrowserConsoleLogWriter.Info("An error occured while trying to login"); BrowserConsoleLogWriter.Warning("An error occured while trying to login");
navManager.NavigateTo("login"); navManager.NavigateTo("login");
} }
} }
protected override void OnInitialized() protected override void OnInitialized()

View File

@ -11,22 +11,24 @@
@using TIAMWebApp.Shared.Application.Models.ClientSide.UI @using TIAMWebApp.Shared.Application.Models.ClientSide.UI
@using TIAMWebApp.Shared.Application.Models.ClientSide.UI.WizardModels @using TIAMWebApp.Shared.Application.Models.ClientSide.UI.WizardModels
@using AyCode.Services.Loggers @using AyCode.Services.Loggers
@using TIAMSharedUI.Pages.User.Hotels
@using TIAMWebApp.Shared.Application.Models.PageModels @using TIAMWebApp.Shared.Application.Models.PageModels
@using TIAMWebApp.Shared.Application.Services @using TIAMWebApp.Shared.Application.Services
@using TIAMWebApp.Shared.Application.Utility
@inherits BasePageComponent @inherits BasePageComponent
@inject NavigationManager navManager @inject NavigationManager navManager
@inject IAcLogWriterClientBase BrowserConsoleLogWriter @inject IEnumerable<IAcLogWriterClientBase> LogWriters
@inject IWizardProcessor WizardProcessor @inject IWizardProcessor WizardProcessor
@inject IUserDataService UserDataService @inject IUserDataService UserDataService
@inject AdminSignalRClient _adminSignalRClient @inject AdminSignalRClient _adminSignalRClient
<PageTitle>Transfer</PageTitle> <PageTitle>Transfer</PageTitle>
<HeroSlider SliderItems="sliders" Height="30vh"></HeroSlider> <HeroSlider SliderItems="_sliders" Height="30vh"></HeroSlider>
<div class="container-fluid" style="position: relative; z-index: 2;"> <div class="container-fluid" style="position: relative; z-index: 2;">
<div class="row d-flex justify-content-center"> <div class="row d-flex justify-content-center">
@{ @{
if (displayHelp) if (_displayHelp)
{ {
<div class="col-md-6 col-12 px-5"> <div class="col-md-6 col-12 px-5">
<!-- Step 1 --> <!-- Step 1 -->
@ -164,18 +166,18 @@
<DxToolbarItem Alignment="ToolbarItemAlignment.Right" Text="Help" RenderStyle="ButtonRenderStyle.Secondary" IconCssClass="grid-icon-column-chooser" Click="ShowHelp_Click" /> <DxToolbarItem Alignment="ToolbarItemAlignment.Right" Text="Help" RenderStyle="ButtonRenderStyle.Secondary" IconCssClass="grid-icon-column-chooser" Click="ShowHelp_Click" />
</Items> </Items>
</DxToolbar> </DxToolbar>
<DxTabs> <DxTabs>
<DxTabPage TabIconCssClass="fa-solid fa-plane-departure" Click="ToAirport" Text="To the Airport"> <DxTabPage TabIconCssClass="fa-solid fa-plane-departure" Click="ToAirport" Text="To the Airport">
<DynamicEditForm Data="myModel" TitleString="@($"To: {myModel.Destination}")" isEditing="true" IgnoreReflection="TransferIgnorList1" OnSubmit="SubmitForm"></DynamicEditForm> <DynamicEditForm Data="_myModel" TitleString="@($"To: {_myModel.Destination}")" isEditing="true" IgnoreReflection="_transferIgnorList1" OnSubmit="SubmitForm"></DynamicEditForm>
</DxTabPage> </DxTabPage>
<DxTabPage TabIconCssClass="fa-solid fa-plane-arrival" Click="FromAirport" Text="From the Airport"> <DxTabPage TabIconCssClass="fa-solid fa-plane-arrival" Click="FromAirport" Text="From the Airport">
<DynamicEditForm Data="myModel" TitleString="@($"From: {myModel.Destination}")" isEditing="true" IgnoreReflection="TransferIgnorList2" OnSubmit="SubmitForm"></DynamicEditForm> <DynamicEditForm Data="_myModel" TitleString="@($"From: {_myModel.Destination}")" isEditing="true" IgnoreReflection="_transferIgnorList2" OnSubmit="SubmitForm"></DynamicEditForm>
</DxTabPage> </DxTabPage>
</DxTabs> </DxTabs>
@ -187,8 +189,8 @@
SubtitleResourceString="TransferSubtitle"></InputWizard> *@ SubtitleResourceString="TransferSubtitle"></InputWizard> *@
</div> </div>
</div> </div>
@ -234,83 +236,88 @@
@code { @code {
public TransferWizardModel myModel = new TransferWizardModel(); private LoggerClient<TransferPage> _logger;
public List<HeroSliderItem> sliders = new List<HeroSliderItem> private readonly TransferWizardModel _myModel = new TransferWizardModel();
{
new HeroSliderItem
{
Title = "Welcome to TIAM",
ImageUrl = "_content/TIAMSharedUI/images/f1_1.png"
},
new HeroSliderItem
{
Title = "Welcome to TIAM",
ImageUrl = "_content/TIAMSharedUI/images/f1_2.png"
},
new HeroSliderItem
{
Title = "Welcome to TIAM",
ImageUrl = "_content/TIAMSharedUI/images/f1_3.png"
},
};
public List<string> TransferIgnorList1 = new List<string> private readonly List<HeroSliderItem> _sliders =
{ [
"Id", new HeroSliderItem
"Destination", {
"UserId", Title = "Welcome to TIAM",
"ProductId", ImageUrl = "_content/TIAMSharedUI/images/f1_1.png"
"PaymentId", },
"TripDate",
"FirstName",
"LastName",
"UserProductMappingId",
"UserProductToCarId",
"ReferralId",
"Price"
};
public List<string> TransferIgnorList2 = new List<string> new HeroSliderItem
{ {
"Id", Title = "Welcome to TIAM",
"PickupAddress", ImageUrl = "_content/TIAMSharedUI/images/f1_2.png"
"UserId", },
"ProductId",
"PaymentId", new HeroSliderItem
"TripDate", {
"FirstName", Title = "Welcome to TIAM",
"LastName", ImageUrl = "_content/TIAMSharedUI/images/f1_3.png"
"UserProductMappingId", }
"UserProductToCarId", ];
"ReferralId",
"Price" private readonly List<string> _transferIgnorList1 =
}; [
"Id",
"Destination",
"UserId",
"ProductId",
"PaymentId",
"TripDate",
"FirstName",
"LastName",
"UserProductMappingId",
"UserProductToCarId",
"ReferralId",
"Price"
];
private readonly List<string> _transferIgnorList2 =
[
"Id",
"PickupAddress",
"UserId",
"ProductId",
"PaymentId",
"TripDate",
"FirstName",
"LastName",
"UserProductMappingId",
"UserProductToCarId",
"ReferralId",
"Price"
];
/*protected override void OnAfterRender(bool isFirst) /*protected override void OnAfterRender(bool isFirst)
{ {
message = " Target destination is " + slider.SliderElementId.ToString(); message = " Target destination is " + slider.SliderElementId.ToString();
}*/ }*/
private bool toAirport = true; private bool _toAirport = true;
private bool displayHelp = false; private bool _displayHelp = false;
public void ToAirport() public void ToAirport()
{ {
toAirport = true; _toAirport = true;
myModel.Destination = "Budapest, 1185"; _myModel.Destination = "Budapest, 1185";
} }
public void FromAirport() public void FromAirport()
{ {
toAirport = false; _toAirport = false;
myModel.PickupAddress = "Budapest, 1185"; _myModel.PickupAddress = "Budapest, 1185";
} }
public async Task SubmitForm(object Result) public async Task SubmitForm(object result)
{ {
TransferWizardModel resModel = (TransferWizardModel)Result; var resModel = (TransferWizardModel)result;
//let's check if user exists with this email //let's check if user exists with this email
var user = await UserDataService.GetUserByEmailAsync(resModel.EmailAddress!); var user = await UserDataService.GetUserByEmailAsync(resModel.EmailAddress!);
if (user != null && user.Id != Guid.Empty) if (user != null && user.Id != Guid.Empty)
@ -371,7 +378,8 @@ new HeroSliderItem
if (createdUserDetail != null) if (createdUserDetail != null)
{ {
createdUserDetail.UserDto.RefferalId = userDetail.UserDto.RefferalId; createdUserDetail.UserDto.RefferalId = userDetail.UserDto.RefferalId;
var updatedNewUser = await _adminSignalRClient.PostDataAsync<UserModelDtoDetail>(SignalRTags.UpdateUserModelDtoDetail, userDetail);
var updatedNewUser = await _adminSignalRClient.UpdateUserModelDtoDetail(userDetail);
if (updatedNewUser != null) if (updatedNewUser != null)
{ {
//referral set //referral set
@ -381,6 +389,7 @@ new HeroSliderItem
//something wrong //something wrong
} }
} }
resModel.ReferralId = userDetail.UserDto.RefferalId; resModel.ReferralId = userDetail.UserDto.RefferalId;
} }
@ -393,20 +402,23 @@ new HeroSliderItem
} }
} }
} }
var transfer = await WizardProcessor.ProcessWizardAsync<TransferWizardModel>(Result.GetType(), Result);
BrowserConsoleLogWriter.Info($"Submitted nested form: {Result.GetType().FullName}"); var transfer = await WizardProcessor.ProcessWizardAsync<TransferWizardModel>(result.GetType(), result);
_logger.Info($"Submitted nested form: {result.GetType().FullName}");
navManager.NavigateTo($"/transfer2/{resModel.Id}"); navManager.NavigateTo($"/transfer2/{resModel.Id}");
} }
protected override Task OnInitializedAsync() protected override Task OnInitializedAsync()
{ {
_logger = new LoggerClient<TransferPage>(LogWriters.ToArray());
ToAirport(); ToAirport();
return base.OnInitializedAsync(); return base.OnInitializedAsync();
} }
private void ShowHelp_Click() private void ShowHelp_Click()
{ {
displayHelp = !displayHelp; _displayHelp = !_displayHelp;
} }
} }

View File

@ -1,4 +1,5 @@
@using BlazorAnimation @using AyCode.Core.Helpers
@using BlazorAnimation
@using TIAM.Core.Enums @using TIAM.Core.Enums
@using TIAM.Entities.Addresses @using TIAM.Entities.Addresses
@using TIAM.Entities.Products @using TIAM.Entities.Products
@ -42,7 +43,7 @@
<div class="row"> <div class="row">
<div class="col-12 col-md-3"> <div class="col-12 col-md-3">
<h4>Information</h4> <h4>Information</h4>
@RenderDetailsItem("fa-solid fa-user", "Contact Name", productProfile.FullName) @RenderDetailsItem("fa-solid fa-user", "Contact Name", _productProfile.FullName)
@RenderDetailsItem("fa-solid fa-circle-info", "Description", Context.Description) @RenderDetailsItem("fa-solid fa-circle-info", "Description", Context.Description)
</div> </div>
@ -79,16 +80,16 @@
</div> </div>
<div class="col-4"> <div class="col-4">
@{ @{
if (!isAddressTransferDestination) if (!_isAddressTransferDestination)
{ {
<DxButton Click="() => SaveAsDestination(productProfile.Address, Context)" Text="Save as destination" RenderStyle="ButtonRenderStyle.Primary" /> <DxButton Click="() => SaveAsDestination(_productProfile.Address, Context)" Text="Save as destination" RenderStyle="ButtonRenderStyle.Primary" />
} }
} }
</div> </div>
<div class="col-4"></div> <div class="col-4"></div>
</div> </div>
</div> </div>
<p>@msg</p> <p>@_msg</p>
</div> </div>
</div> </div>
@ -120,11 +121,11 @@
AccordionExpandMode ExpandMode { get; set; } = AccordionExpandMode.SingleOrNone; AccordionExpandMode ExpandMode { get; set; } = AccordionExpandMode.SingleOrNone;
AccordionExpandCollapseAction ExpandCollapseAction { get; set; } = AccordionExpandCollapseAction.HeaderClick; AccordionExpandCollapseAction ExpandCollapseAction { get; set; } = AccordionExpandCollapseAction.HeaderClick;
private Profile productProfile = new Profile(); private Profile _productProfile = new Profile();
private List<TransferDestination> destinations = new List<TransferDestination>(); private readonly List<TransferDestination> _destinations = [];
string msg; string _msg;
private bool isSaveActive = false; private bool _isSaveActive = false;
private bool isAddressTransferDestination = false; private bool _isAddressTransferDestination = false;
private async Task CopyUrl(string url) private async Task CopyUrl(string url)
{ {
@ -139,19 +140,20 @@
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
var productOwner = await AdminSignalRClient.GetByIdAsync<List<Company>>(SignalRTags.GetCompaniesById, Context.ServiceProviderId); var productOwner = await AdminSignalRClient.GetByIdAsync<List<Company>>(SignalRTags.GetCompaniesById, Context.ServiceProviderId);
var ProductProfiles = await AdminSignalRClient.GetByIdAsync<List<Profile>>(SignalRTags.GetProfileById, Context.ProfileId); var productProfiles = await AdminSignalRClient.GetByIdAsync<List<Profile>>(SignalRTags.GetProfileById, Context.ProfileId);
await AdminSignalRClient.GetAllIntoAsync<TransferDestination>(destinations, SignalRTags.GetAllTransferDestinations);
if (productOwner != null) if (productOwner != null)
{ {
ImageSource = await ServiceProviderDataService.GetQRCodeByProductIdAndOwnerAffiliateIdAsync(new Guid[] { productOwner[0].AffiliateId, Context.Id }); ImageSource = await ServiceProviderDataService.GetQRCodeByProductIdAndOwnerAffiliateIdAsync([productOwner[0].AffiliateId, Context.Id]);
}
if (ProductProfiles != null)
{
productProfile = ProductProfiles[0];
var AddressId = productProfile.AddressId;
isAddressTransferDestination = CheckDestinations(AddressId);
} }
if (productProfiles != null)
{
_productProfile = productProfiles[0];
_isAddressTransferDestination = CheckDestinations(_productProfile.AddressId);
}
AdminSignalRClient.GetTransferDestinationsAsync(_destinations).Forget();
await base.OnInitializedAsync(); await base.OnInitializedAsync();
} }
@ -163,40 +165,27 @@
RenderFragment RenderDetailsItem(string iconCssClass, string caption, string value) RenderFragment RenderDetailsItem(string iconCssClass, string caption, string value)
{ {
return @<div class="d-flex m-1 align-items-center"> return @<div class="d-flex m-1 align-items-center">
<div class="icon-container flex-shrink-0"> <div class="icon-container flex-shrink-0">
<span class="dxbl-image m-1 @iconCssClass"></span> <span class="dxbl-image m-1 @iconCssClass"></span>
</div> </div>
<div class="text-container m-1 flex-grow-1 ms-2"> <div class="text-container m-1 flex-grow-1 ms-2">
<label>@caption:</label> <label>@caption:</label>
<div>@value</div> <div>@value</div>
</div> </div>
</div>; </div>;
} }
private bool CheckDestinations(Guid addressId) private bool CheckDestinations(Guid addressId)
{ {
if (destinations != null) return _destinations.Any(d => d.AddressId == addressId);
{
if (destinations.Any(d => d.AddressId == addressId))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
} }
private async Task SaveAsDestination(Address address, Product product) private async Task SaveAsDestination(Address address, Product product)
{ {
TransferDestination transferDestination = new TransferDestination(); var transferDestination = new TransferDestination();
transferDestination.Id = Guid.NewGuid(); transferDestination.Id = Guid.NewGuid();
transferDestination.Name = product.Name; transferDestination.Name = product.Name;
if (!string.IsNullOrEmpty(product.Profile.Description)) if (!string.IsNullOrEmpty(product.Profile.Description))
{ {
transferDestination.Description = product.Profile.Description; transferDestination.Description = product.Profile.Description;
@ -205,8 +194,10 @@
{ {
transferDestination.Description = "No description available"; transferDestination.Description = "No description available";
} }
transferDestination.AddressId = address.Id; transferDestination.AddressId = address.Id;
transferDestination.AddressString = address.AddressText; transferDestination.AddressString = address.AddressText;
var result = await AdminSignalRClient.PostDataAsync<TransferDestination>(SignalRTags.CreateTransferDestination, transferDestination); var result = await AdminSignalRClient.PostDataAsync<TransferDestination>(SignalRTags.CreateTransferDestination, transferDestination);
await InvokeAsync(StateHasChanged); await InvokeAsync(StateHasChanged);
} }

View File

@ -109,10 +109,10 @@
@RenderDetailsItem("fa-solid fa-hashtag", "Comment", Context.Comment) @RenderDetailsItem("fa-solid fa-hashtag", "Comment", Context.Comment)
</div> </div>
<div class="col-12 col-md-6"> <div class="col-12 col-md-6">
@RenderDetailsItem("fa-solid fa-list-check", "Status", AllStatuses.FirstOrDefault(x => x.StatusValue == (byte)Context.TransferStatusType).StatusName) @RenderDetailsItem("fa-solid fa-list-check", "Status", TransferStatusModel.GetStatusModel(Context.TransferStatusType).StatusName)
</div> </div>
<div class="col-9 col-md-5"> <div class="col-9 col-md-5">
<DxComboBox Data="@Statuses" <DxComboBox Data="@DriverStatuses"
@bind-Value="@CurrentStatusType" @bind-Value="@CurrentStatusType"
NullText="Select new status" NullText="Select new status"
CssClass="form-field" CssClass="form-field"
@ -182,27 +182,18 @@
private static readonly IEnumerable<TransferStatusModel> Statuses = new[] private static readonly IEnumerable<TransferStatusModel> DriverStatuses = TransferStatusModel.AllStatuses.Values.Where(x => x.StatusValue is TransferStatusType.DriverConfirmed or
{ TransferStatusType.DriverEnRoute or TransferStatusType.PassengerPickup or TransferStatusType.Finished or TransferStatusType.UserCanceled);
new TransferStatusModel(Convert.ToByte(TransferStatusType.DriverConfirmed), "Driver confirmed"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.DriverEnRoute), "Driver enroute"), // private static readonly IEnumerable<TransferStatusModel> Statuses = new[]
new TransferStatusModel(Convert.ToByte(TransferStatusType.PassengerPickup), "Passenger in car"), // {
new TransferStatusModel(Convert.ToByte(TransferStatusType.Finished), "Finished"), // new TransferStatusModel(TransferStatusType.DriverConfirmed, "Driver confirmed"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.UserCanceled), "User cancelled"), // new TransferStatusModel(TransferStatusType.DriverEnRoute, "Driver enroute"),
}; // new TransferStatusModel(TransferStatusType.PassengerPickup, "Passenger in car"),
// new TransferStatusModel(TransferStatusType.Finished, "Finished"),
// new TransferStatusModel(TransferStatusType.UserCanceled, "User cancelled"),
// };
private static readonly List<TransferStatusModel> AllStatuses = new()
{
new TransferStatusModel(Convert.ToByte(TransferStatusType.OrderSubmitted), "Order submitted"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.OrderConfirmed), "Order confirmed"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.AssignedToDriver), "Assigned to driver"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.DriverConfirmed), "Driver confirmed"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.DriverEnRoute), "Driver enroute"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.PassengerPickup), "Passenger in car"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.Finished), "Finished"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.UserCanceled), "User cancelled"),
new TransferStatusModel(Convert.ToByte(TransferStatusType.AdminDenied), "Admin cancelled")
};
private TransferStatusModel _currentStatusType; private TransferStatusModel _currentStatusType;
public TransferStatusModel CurrentStatusType public TransferStatusModel CurrentStatusType
@ -245,7 +236,7 @@
var result = await AdminSignalRClient.PostDataAsync<Transfer>(SignalRTags.UpdateTransfer, Context); var result = await AdminSignalRClient.PostDataAsync<Transfer>(SignalRTags.UpdateTransfer, Context);
if (result != null) if (result != null)
{ {
if (AllStatuses.FirstOrDefault(x => x.StatusValue == (byte)result.TransferStatusType) == CurrentStatusType) if (TransferStatusModel.GetStatusModel(result.TransferStatusType) == CurrentStatusType)
{ {
msg = $"Stataus saved"; msg = $"Stataus saved";
StateHasChanged(); StateHasChanged();
@ -282,13 +273,14 @@
{ {
_logger = new LoggerClient<TransferCardComponent>(LogWriters.ToArray()); _logger = new LoggerClient<TransferCardComponent>(LogWriters.ToArray());
sysAdmins = await AdminSignalRClient.GetByIdAsync<List<UserModelDtoDetail>>(SignalRTags.GetAllUserModelDtoDetails, TiamConstClient.SysAdmins[0]); sysAdmins = await AdminSignalRClient.GetByIdAsync<List<UserModelDtoDetail>>(SignalRTags.GetAllUserModelDtoDetails, TiamConstClient.SysAdmins[0]);
await base.OnInitializedAsync(); await base.OnInitializedAsync();
} }
protected override Task OnParametersSetAsync() protected override Task OnParametersSetAsync()
{ {
CurrentStatusType = AllStatuses.FirstOrDefault(x => x.StatusValue == (byte)Context.TransferStatusType); CurrentStatusType = TransferStatusModel.GetStatusModel(Context.TransferStatusType);
return base.OnParametersSetAsync(); return base.OnParametersSetAsync();
} }

View File

@ -227,19 +227,6 @@
"ContextId", "ContextId",
]; ];
private static readonly List<TransferStatusModel> Statuses =
[
new(Convert.ToByte(TransferStatusType.OrderSubmitted), "Order submitted"),
new(Convert.ToByte(TransferStatusType.OrderConfirmed), "Order confirmed"),
new(Convert.ToByte(TransferStatusType.AssignedToDriver), "Assigned to driver"),
new(Convert.ToByte(TransferStatusType.DriverConfirmed), "Driver confirmed"),
new(Convert.ToByte(TransferStatusType.DriverEnRoute), "Driver enroute"),
new(Convert.ToByte(TransferStatusType.PassengerPickup), "Passenger in car"),
new(Convert.ToByte(TransferStatusType.Finished), "Finished"),
new(Convert.ToByte(TransferStatusType.UserCanceled), "User cancelled"),
new(Convert.ToByte(TransferStatusType.AdminDenied), "Admin cancelled")
];
void Grid_CustomizeElement(GridCustomizeElementEventArgs e) void Grid_CustomizeElement(GridCustomizeElementEventArgs e)
{ {
try try

View File

@ -8,6 +8,7 @@
@using TIAMSharedUI.Pages.Components.EditComponents @using TIAMSharedUI.Pages.Components.EditComponents
@using TIAMSharedUI.Shared @using TIAMSharedUI.Shared
@using AyCode.Services.Loggers @using AyCode.Services.Loggers
@using TIAM.Core.Enums
@using TIAMWebApp.Shared.Application.Interfaces; @using TIAMWebApp.Shared.Application.Interfaces;
@using TIAMWebApp.Shared.Application.Models.ClientSide.UI.WizardModels @using TIAMWebApp.Shared.Application.Models.ClientSide.UI.WizardModels
@using TIAMWebApp.Shared.Application.Models.PageModels @using TIAMWebApp.Shared.Application.Models.PageModels
@ -38,7 +39,7 @@
<h3>Selected Hotel:</h3> <h3>Selected Hotel:</h3>
<DxComboBox Data="@Hotels" <DxComboBox Data="@_hotels"
@bind-Value="@SelectedHotel" @bind-Value="@SelectedHotel"
SearchMode="@ListSearchMode.AutoSearch" SearchMode="@ListSearchMode.AutoSearch"
SearchFilterCondition="@ListSearchFilterCondition.Contains" SearchFilterCondition="@ListSearchFilterCondition.Contains"
@ -50,12 +51,12 @@
<div class="row py-3"> <div class="row py-3">
<DynamicEditForm Data="Data" CurrentProduct="@SelectedHotel" isEditing="true" IgnoreReflection="TransferIgnorList" OnSubmit="SubmitForm"></DynamicEditForm> <DynamicEditForm Data="_data" CurrentProduct="@SelectedHotel" isEditing="true" IgnoreReflection="TransferIgnorList" OnSubmit="SubmitForm"></DynamicEditForm>
</div> </div>
<div class="row py-3"> <div class="row py-3">
<DxButton RenderStyle="ButtonRenderStyle.Primary" Click="@Reload" Visible="@isReloadVisible">Reload</DxButton> <DxButton RenderStyle="ButtonRenderStyle.Primary" Click="@Reload" Visible="@_isReloadVisible">Reload</DxButton>
</div> </div>
</div> </div>
@ -66,67 +67,68 @@
@code { @code {
private LoggerClient<CreateAndManageTransfer> _logger; private LoggerClient<CreateAndManageTransfer> _logger;
private TransferWizardModel Data = new(); private TransferWizardModel _data = new();
private List<Product> Hotels = new List<Product>(); private List<Product> _hotels = [];
private Product selectedHotel { get; set; }
public Product SelectedHotel private static Product? _selectedHotel;
public Product? SelectedHotel
{ {
get get => _selectedHotel;
{
return selectedHotel;
}
set set
{ {
selectedHotel = value; if (_selectedHotel == value) return;
_selectedHotel = value;
StateHasChanged(); StateHasChanged();
} }
} }
public List<string> TransferIgnorList = new List<string> public List<string> TransferIgnorList =
{ [
nameof(TransferWizardModel.Id), nameof(TransferWizardModel.Id),
nameof(TransferWizardModel.UserId), nameof(TransferWizardModel.UserId),
nameof(TransferWizardModel.ProductId), nameof(TransferWizardModel.ProductId),
nameof(TransferWizardModel.FirstName), nameof(TransferWizardModel.FirstName),
nameof(TransferWizardModel.LastName), nameof(TransferWizardModel.LastName),
nameof(TransferWizardModel.UserProductMappingId), nameof(TransferWizardModel.UserProductMappingId),
nameof(TransferWizardModel.UserProductToCarId), nameof(TransferWizardModel.UserProductToCarId),
nameof(TransferWizardModel.ReferralId), nameof(TransferWizardModel.ReferralId),
nameof(TransferWizardModel.Price) nameof(TransferWizardModel.Price)
}; ];
private bool isReloadVisible = false;
private bool SelectedHotelInitialized = false; private bool _isReloadVisible = false;
protected override void OnInitialized() protected override void OnInitialized()
{ {
_logger = new LoggerClient<CreateAndManageTransfer>(LogWriters.ToArray()); _logger = new LoggerClient<CreateAndManageTransfer>(LogWriters.ToArray());
if (_sessionService.User != null) if (_sessionService.User != null)
{ {
if (_sessionService.User.UserModelDto.Products.Any())
if (_sessionService.User.UserModelDto.Products.Count() > 0)
{ {
if (_sessionService.User.UserModelDto.Products.Any(x => x.ProductType == TIAM.Core.Enums.ProductType.Hotel)) if (_sessionService.User.UserModelDto.Products.Any(x => x.ProductType == ProductType.Hotel))
{ {
Hotels = _sessionService.GetHotels(); _hotels = _sessionService.GetHotels();
if (!SelectedHotelInitialized) SelectedHotel = _hotels.FirstOrDefault(x => x.Id == _selectedHotel?.Id) ?? _hotels[0];
{
SelectedHotel = Hotels[0];
SelectedHotelInitialized = true;
}
} }
} }
} }
Data = new TransferWizardModel();
base.OnInitialized(); base.OnInitialized();
} }
public async Task SubmitForm(object result) public async Task SubmitForm(object result)
{ {
if (_selectedHotel == null)
{
_logger.Error($"_selectedHotel == null");
return;
}
var valami = ((TransferWizardModel)result).CopyToTransfer(); var valami = ((TransferWizardModel)result).CopyToTransfer();
valami.Id = Guid.NewGuid(); valami.Id = Guid.NewGuid();
valami.ProductId = SelectedHotel.Id; valami.ProductId = _selectedHotel.Id;
var user = await UserDataService.GetUserByEmailAsync(valami.ContactEmail); var user = await UserDataService.GetUserByEmailAsync(valami.ContactEmail);
if (user != null && user.Id != Guid.Empty) if (user != null && user.Id != Guid.Empty)
{ {
@ -152,7 +154,7 @@
registration.PhoneNumber = valami.ContactPhone; registration.PhoneNumber = valami.ContactPhone;
registration.Password = password; registration.Password = password;
//get list with one member! //get list with one member!
var productOwner = await _adminSignalRClient.GetByIdAsync<List<Company>>(SignalRTags.GetCompaniesById, SelectedHotel.ServiceProviderId); var productOwner = await _adminSignalRClient.GetByIdAsync<List<Company>>(SignalRTags.GetCompaniesById, _selectedHotel.ServiceProviderId);
registration.ReferralId = productOwner[0].AffiliateId; registration.ReferralId = productOwner[0].AffiliateId;
@ -166,18 +168,19 @@
} }
_logger.Info("New user created added"); _logger.Info("New user created added");
} }
//valami.ProductId = SessionService.User.UserId; //TODO ProductID! //valami.ProductId = SessionService.User.UserId; //TODO ProductID!
// await WizardProcessor.ProcessWizardAsync<TransferDestinationWizardModel>(result.GetType(), result); // await WizardProcessor.ProcessWizardAsync<TransferDestinationWizardModel>(result.GetType(), result);
var saveResult = await _adminSignalRClient.PostDataAsync<Transfer>(SignalRTags.AddTransfer, valami); var saveResult = await _adminSignalRClient.PostDataAsync<Transfer>(SignalRTags.AddTransfer, valami);
_logger.Info($"Submitted form: {result.GetType().FullName}, {valami.ToAddress}, {valami.FromAddress}, {valami.ProductId}"); _logger.Info($"Submitted form: {result.GetType().FullName}, {valami.ToAddress}, {valami.FromAddress}, {valami.ProductId}");
isReloadVisible = true; _isReloadVisible = true;
} }
public void Reload() public void Reload()
{ {
Data = new TransferWizardModel(); _data = new TransferWizardModel();
isReloadVisible = false; _isReloadVisible = false;
StateHasChanged(); StateHasChanged();
} }

View File

@ -44,9 +44,9 @@
</div> </div>
<div class="d-flex flex-column mb-4 pb-2"> <div class="d-flex flex-column mb-4 pb-2">
<h4> Hotel name: <span class="small text-muted"> @hotelName </span></h4> <h4> Hotel name: <span class="small text-muted"> @_hotelName </span></h4>
<h4> Address: <span class="small text-muted"> @hotelAddress </span></h4> <h4> Address: <span class="small text-muted"> @_hotelAddress </span></h4>
<h4> Contact name: <span class="small text-muted"> @hotelContactName</span></h4> <h4> Contact name: <span class="small text-muted"> @_hotelContactName</span></h4>
</div> </div>
</div> </div>
<div class="card-footer py-2 px-4"> <div class="card-footer py-2 px-4">
@ -71,7 +71,7 @@
</div> </div>
<div> <div>
<h6 class="mb-0"> <a href="/user/transfers/@productId">All transfers</a> </h6> <h6 class="mb-0"> <a href="/user/transfers/@ProductId">All transfers</a> </h6>
</div> </div>
</div> </div>
</div> </div>
@ -79,7 +79,7 @@
<div class="d-flex flex-row mb-4 pb-2"> <div class="d-flex flex-row mb-4 pb-2">
<TransferGrid Logger="_logger" <TransferGrid Logger="_logger"
SignalRClient="adminSignalRClient" SignalRClient="AdminSignalRClient"
ContextIds="@(Id.IsNullOrEmpty() ? null : [Id])" ContextIds="@(Id.IsNullOrEmpty() ? null : [Id])"
GetAllMessageTag="@SignalRTags.GetTransfersByOrderingProductId" GetAllMessageTag="@SignalRTags.GetTransfersByOrderingProductId"
CustomizeElement="Grid_CustomizeElement" CustomizeElement="Grid_CustomizeElement"
@ -175,7 +175,7 @@
</Animation> </Animation>
</div> </div>
<div class="col-12 col-lg-3" hidden="@accessDenied"> <div class="col-12 col-lg-3" hidden="@_accessDenied">
<Animation Effect="@Effect.FadeIn" Speed="@Speed.Fast" Delay="@TimeSpan.FromMilliseconds(250)"> <Animation Effect="@Effect.FadeIn" Speed="@Speed.Fast" Delay="@TimeSpan.FromMilliseconds(250)">
<div class="card card-admin" style="border-radius: 16px;"> <div class="card card-admin" style="border-radius: 16px;">
<div class="card-header py-2 px-4"> <div class="card-header py-2 px-4">
@ -192,7 +192,7 @@
<div class="card-body card-admin-body py-2 px-4"> <div class="card-body card-admin-body py-2 px-4">
<div class="d-flex flex-row mb-4 pb-2"> <div class="d-flex flex-row mb-4 pb-2">
<TransferGrid Logger="_logger" <TransferGrid Logger="_logger"
SignalRClient="adminSignalRClient" SignalRClient="AdminSignalRClient"
ContextIds="@(Id.IsNullOrEmpty() ? null : [Id])" ContextIds="@(Id.IsNullOrEmpty() ? null : [Id])"
GetAllMessageTag="@SignalRTags.GetTransfersByOrderingProductId" GetAllMessageTag="@SignalRTags.GetTransfersByOrderingProductId"
ColumnResizeMode="GridColumnResizeMode.NextColumn" ColumnResizeMode="GridColumnResizeMode.NextColumn"
@ -270,7 +270,7 @@
} }
</style> </style>
<DxGrid Data="@Data"> <DxGrid Data="@_data">
<Columns> <Columns>
<DxGridDataColumn FieldName="CompanyName" AllowSort="true" /> <DxGridDataColumn FieldName="CompanyName" AllowSort="true" />
<DxGridDataColumn FieldName="ContactName" /> <DxGridDataColumn FieldName="ContactName" />

View File

@ -5,6 +5,7 @@ using System.ComponentModel.DataAnnotations;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using AyCode.Utils.Extensions;
using TIAM.Core.Enums; using TIAM.Core.Enums;
using TIAM.Entities.Products; using TIAM.Entities.Products;
using TIAM.Entities.ServiceProviders; using TIAM.Entities.ServiceProviders;
@ -20,52 +21,45 @@ namespace TIAMSharedUI.Pages.User.Hotels
public partial class HotelComponent : ComponentBase public partial class HotelComponent : ComponentBase
{ {
[Parameter] [Parameter] public Guid Id { get; set; }
public Guid Id { get; set; }
[Parameter] public bool ShowSeriesPointMarkers { get; set; } [Parameter] public bool ShowSeriesPointMarkers { get; set; }
[Parameter] public bool ShowSeriesLabels { get; set; } [Parameter] public bool ShowSeriesLabels { get; set; }
[Inject] [Inject] ISupplierService SupplierService { get; set; }
ISupplierService SupplierService { get; set; }
[Inject] [Inject] IUserDataService UserDataService { get; set; }
IUserDataService UserDataService { get; set; }
[Inject] [Inject] IServiceProviderDataService ServiceProviderDataService { get; set; }
IServiceProviderDataService ServiceProviderDataService { get; set; }
[Inject] [Inject] AdminSignalRClient AdminSignalRClient { get; set; }
AdminSignalRClient adminSignalRClient { get; set; }
[Inject] [Inject] IEnumerable<IAcLogWriterClientBase> LogWriters { get; set; }
IEnumerable<IAcLogWriterClientBase> LogWriters { get; set; }
[Inject] [Inject] ISessionService SessionService { get; set; }
ISessionService SessionService { get; set; }
private LoggerClient<HotelComponent> _logger; private LoggerClient<HotelComponent> _logger;
object? OrderData { get; set; } private object? _orderData;
object? AffiliateData { get; set; } private object? _affiliateData;
object? Data { get; set; } private object? _data;
public string ImageSource { get; set; } = ""; public string ImageSource { get; set; } = "";
public Guid productId { get; set; } public Guid ProductId { get; set; }
private Product? hotel; private Product? _hotel;
private string hotelName; private string _hotelName = string.Empty;
private string hotelAddress = "No address set"; private string _hotelAddress = "No address set";
private string hotelContactName = "No contact name set yet"; private string _hotelContactName = "No contact name set yet";
private bool isProductAdmin; private bool _isProductAdmin;
private bool accessDenied = true; private bool _accessDenied = true;
protected override void OnParametersSet() protected override void OnParametersSet()
{ {
productId = Id; ProductId = Id;
base.OnParametersSet(); base.OnParametersSet();
} }
@ -73,130 +67,103 @@ namespace TIAMSharedUI.Pages.User.Hotels
{ {
_logger = new LoggerClient<HotelComponent>(LogWriters.ToArray()); _logger = new LoggerClient<HotelComponent>(LogWriters.ToArray());
hotel = await adminSignalRClient.GetByIdAsync<Product>(SignalRTags.GetProductById, Id); _hotel = await AdminSignalRClient.GetByIdAsync<Product>(SignalRTags.GetProductById, Id);
if (hotel != null) if (_hotel != null)
{ {
if (hotel.Name != null) if (!_hotel.Name.IsNullOrWhiteSpace()) _hotelName = _hotel.Name;
{
hotelName = hotel.Name;
}
if (hotel.Profile != null)
{
if (hotel.Profile.Address != null)
{
if (string.IsNullOrEmpty(hotel.Profile.Address.AddressText))
{
hotelAddress = hotel.Profile.Address.AddressText;
} _hotelAddress = !_hotel.Profile.Address.AddressText.IsNullOrWhiteSpace() ? _hotel.Profile.Address.AddressText : "Address is empty";
else _hotelContactName = !_hotel.Profile.FullName.IsNullOrWhiteSpace() ? _hotel.Profile.FullName : "No contact name has been set yet";
{
hotelAddress = "Address is empty";
}
}
else
{
hotelAddress = "No address found";
}
if (hotel.Profile.FullName != null)
{
hotelContactName = hotel.Profile.FullName;
}
else
{
hotelContactName = "No contact name has been set yet";
}
}
else
{
hotelAddress = "No profile found";
}
} }
//TEMPORARY //TEMPORARY
isProductAdmin = SessionService.User.UserModelDto.UserProductMappings.Any(m => m.ProductId == Id && m.Permissions == 1); _isProductAdmin = SessionService.User?.UserModelDto.UserProductMappings.Any(m => m.ProductId == Id && m.Permissions == 1) ?? false;
accessDenied = !isProductAdmin; _accessDenied = !_isProductAdmin;
_logger.Debug($"{hotel.Name}, {isProductAdmin}"); _logger.Debug($"{_hotel?.Name}, {_isProductAdmin}");
base.OnInitialized(); base.OnInitialized();
OrderData = new object[] _orderData = new object[]
{ {
new { new
Date = DateTime.Now.AddDays(3), {
Income = "$5", Date = DateTime.Now.AddDays(3),
TransactionId = "POX987532582", Income = "$5",
Status = "Finished" TransactionId = "POX987532582",
}, Status = "Finished"
new { },
Date = DateTime.Today.AddDays(-2), new
Income = "$5", {
TransactionId = "POX645646382", Date = DateTime.Today.AddDays(-2),
Status = "Finished" Income = "$5",
}, TransactionId = "POX645646382",
new { Status = "Finished"
Date = DateTime.Today.AddDays(-6), },
Income = "$8", new
TransactionId = "POX645766311", {
Status = "Finished" Date = DateTime.Today.AddDays(-6),
}, Income = "$8",
TransactionId = "POX645766311",
Status = "Finished"
},
}; };
AffiliateData = new object[] _affiliateData = new object[]
{ {
new { new
AffiliateId = 1, {
IncomeThisMonth = "$5", AffiliateId = 1,
IncomeAlltime = "9425", IncomeThisMonth = "$5",
CompanyName = "Upgen Ltd.", IncomeAlltime = "9425",
Status = "Active" CompanyName = "Upgen Ltd.",
}, Status = "Active"
new { },
AffiliateId = 2, new
IncomeThisMonth = "$538", {
IncomeAlltime = "13425", AffiliateId = 2,
CompanyName = "Kovacs hotel Ltd.", IncomeThisMonth = "$538",
Status = "Active" IncomeAlltime = "13425",
}, CompanyName = "Kovacs hotel Ltd.",
new { Status = "Active"
AffiliateId = 3, },
IncomeThisMonth = "$0", new
IncomeAlltime = "134200", {
CompanyName = "Innosaurus Ltd.", AffiliateId = 3,
Status = "Passive" IncomeThisMonth = "$0",
}, IncomeAlltime = "134200",
CompanyName = "Innosaurus Ltd.",
Status = "Passive"
},
}; };
var suppliers = await SupplierService.GetSuppliersAsync(); var suppliers = await SupplierService.GetSuppliersAsync();
Data = suppliers.Select(s => _data = suppliers.Select(s => new
{ {
return new s.CompanyName,
{ s.ContactName,
s.CompanyName, s.ContactTitle,
s.ContactName, s.Country,
s.ContactTitle, s.City,
s.Country, s.Address,
s.City, s.Phone
s.Address,
s.Phone
};
}); });
var productOwner = await adminSignalRClient.GetByIdAsync<List<Company>>(SignalRTags.GetCompaniesById, hotel.ServiceProviderId);
if(productOwner!=null) var productOwner = await AdminSignalRClient.GetByIdAsync<List<Company>>(SignalRTags.GetCompaniesById, _hotel.ServiceProviderId);
if (productOwner != null)
{ {
ImageSource = await ServiceProviderDataService.GetQRCodeByProductIdAsync(productOwner[0].AffiliateId); ImageSource = await ServiceProviderDataService.GetQRCodeByProductIdAsync(productOwner[0].AffiliateId);
} }
else else
{ {
int width = 128; const int width = 128;
int height = 128; const int height = 128;
string base64String = ""; var base64String = "";
// Create a new bitmap // Create a new bitmap
using (Bitmap bitmap = new Bitmap(width, height)) using (var bitmap = new Bitmap(width, height))
{ {
// Set all pixels to black // Set all pixels to black
using (Graphics gfx = Graphics.FromImage(bitmap)) using (var gfx = Graphics.FromImage(bitmap))
{ {
gfx.Clear(Color.Black); gfx.Clear(Color.Black);
} }
@ -209,18 +176,18 @@ namespace TIAMSharedUI.Pages.User.Hotels
ImageSource = base64String; ImageSource = base64String;
} }
//SKBitmap bitmap = await ServiceProviderDataService.GetQRCodeByProductIdAsync(Guid.NewGuid()); //SKBitmap bitmap = await ServiceProviderDataService.GetQRCodeByProductIdAsync(Guid.NewGuid());
} }
private string BitmapToBase64(Bitmap bitmap) private string BitmapToBase64(Bitmap bitmap)
{ {
using (MemoryStream memoryStream = new MemoryStream()) using (var memoryStream = new MemoryStream())
{ {
// Save bitmap to memory stream // Save bitmap to memory stream
bitmap.Save(memoryStream, ImageFormat.Png); bitmap.Save(memoryStream, ImageFormat.Png);
// Convert memory stream to Base64 string // Convert memory stream to Base64 string
byte[] imageBytes = memoryStream.ToArray(); var imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes); return Convert.ToBase64String(imageBytes);
} }
} }
@ -263,19 +230,5 @@ namespace TIAMSharedUI.Pages.User.Hotels
_logger.Error($"Grid_CustomizeElement; {ex.Message}", ex); _logger.Error($"Grid_CustomizeElement; {ex.Message}", ex);
} }
} }
private static readonly List<TransferStatusModel> Statuses =
[
new(Convert.ToByte(TransferStatusType.OrderSubmitted), "Order submitted"),
new(Convert.ToByte(TransferStatusType.OrderConfirmed), "Order confirmed"),
new(Convert.ToByte(TransferStatusType.AssignedToDriver), "Assigned to driver"),
new(Convert.ToByte(TransferStatusType.DriverConfirmed), "Driver confirmed"),
new(Convert.ToByte(TransferStatusType.DriverEnRoute), "Driver enroute"),
new(Convert.ToByte(TransferStatusType.PassengerPickup), "Passenger in car"),
new(Convert.ToByte(TransferStatusType.Finished), "Finished"),
new(Convert.ToByte(TransferStatusType.UserCanceled), "User cancelled"),
new(Convert.ToByte(TransferStatusType.AdminDenied), "Admin cancelled")
];
} }
} }

View File

@ -134,7 +134,7 @@
<CellDisplayTemplate> <CellDisplayTemplate>
@{ @{
TransferStatusModel keyField = Statuses.FirstOrDefault(x => x.StatusValue == (byte)context.Value)!; TransferStatusModel keyField = TransferStatusModel.GetStatusModel((TransferStatusType)context.Value);
string transferStatusText = keyField.StatusName; string transferStatusText = keyField.StatusName;
<text>@transferStatusText</text> <text>@transferStatusText</text>
} }
@ -200,7 +200,7 @@
<ToolbarTemplate> <ToolbarTemplate>
<div> <div>
<DxTagBox Data="@Statuses" Values="@_selectedCategories" @ref="_filterTag" <DxTagBox Data="@TransferStatusModel.AllStatuses.Values" Values="@_selectedCategories" @ref="_filterTag"
ValuesChanged="(IEnumerable<TransferStatusModel> values) => TagBox_ValuesChanged(values)" ValuesChanged="(IEnumerable<TransferStatusModel> values) => TagBox_ValuesChanged(values)"
ValueFieldName="StatusValue" TextFieldName="StatusName" NullText="Select status type..." ValueFieldName="StatusValue" TextFieldName="StatusName" NullText="Select status type..."
ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto" aria-label="Select status type" /> ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto" aria-label="Select status type" />
@ -249,30 +249,17 @@
public List<string> IgnoreList = public List<string> IgnoreList =
[ [
"ReceiverEmailAddress", "ReceiverEmailAddress",
"ReceiverFullName", "ReceiverFullName",
"ReceiverId", "ReceiverId",
"SenderEmailAddress", "SenderEmailAddress",
"SenderFullName", "SenderFullName",
"SenderId", "SenderId",
"ContextId", "ContextId",
"ContextType" "ContextType"
]; ];
private static readonly List<TransferStatusModel> Statuses = private static List<TransferStatusModel> _selectedCategories = TransferStatusModel.AllStatuses.Values.Where(x => x.StatusValue != TransferStatusType.Finished && x.StatusValue != TransferStatusType.UserCanceled && x.StatusValue != TransferStatusType.AdminDenied).ToList();
[ private string _filterText = GetFilterText(_selectedCategories.Select(x => x.StatusValue).ToList());
new(Convert.ToByte(TransferStatusType.OrderSubmitted), "Order submitted"),
new(Convert.ToByte(TransferStatusType.OrderConfirmed), "Order confirmed"),
new(Convert.ToByte(TransferStatusType.AssignedToDriver), "Assigned to driver"),
new(Convert.ToByte(TransferStatusType.DriverConfirmed), "Driver confirmed"),
new(Convert.ToByte(TransferStatusType.DriverEnRoute), "Driver enroute"),
new(Convert.ToByte(TransferStatusType.PassengerPickup), "Passenger in car"),
new(Convert.ToByte(TransferStatusType.Finished), "Finished"),
new(Convert.ToByte(TransferStatusType.UserCanceled), "User cancelled"),
new(Convert.ToByte(TransferStatusType.AdminDenied), "Admin cancelled")
];
private static List<TransferStatusModel> _selectedCategories = Statuses.Where(x => /* x.StatusValue != (byte)TransferStatusType.OrderSubmitted && */ x.StatusValue != (byte)TransferStatusType.Finished && x.StatusValue != (byte)TransferStatusType.UserCanceled && x.StatusValue != (byte)TransferStatusType.AdminDenied).ToList();
private string _filterText = GetFilterText(_selectedCategories.Select(x => (TransferStatusType)x.StatusValue).ToList());
private MessageWizardModel _messageWizardModel = new(); private MessageWizardModel _messageWizardModel = new();
@ -319,7 +306,7 @@
public async Task SubmitForm(object result) public async Task SubmitForm(object result)
{ {
var messageModel = (result as MessageWizardModel)!; var messageModel = (result as MessageWizardModel)!;
_logger.Info(messageModel.Content); _logger.Info(messageModel.Content);
var email = await wizardProcessor.ProcessWizardAsync<MessageWizardModel>(result.GetType(), messageModel); var email = await wizardProcessor.ProcessWizardAsync<MessageWizardModel>(result.GetType(), messageModel);
_logger.Info($"Submitted nested form: {result.GetType().FullName}"); _logger.Info($"Submitted nested form: {result.GetType().FullName}");
@ -466,23 +453,23 @@
} }
_dataStorage = new DxSchedulerDataStorage _dataStorage = new DxSchedulerDataStorage
{
AppointmentMappings = new DxSchedulerAppointmentMappings()
{ {
AppointmentMappings = new DxSchedulerAppointmentMappings() Type = "AppointmentType",
{ Start = "StartDate",
Type = "AppointmentType", End = "EndDate",
Start = "StartDate", Subject = "Caption",
End = "EndDate", AllDay = "AllDay",
Subject = "Caption", Location = "Location",
AllDay = "AllDay", Description = "Description",
Location = "Location", LabelId = "Label",
Description = "Description", StatusId = "Status",
LabelId = "Label", RecurrenceInfo = "Recurrence"
StatusId = "Status", },
RecurrenceInfo = "Recurrence"
},
AppointmentsSource = AppointmentModels AppointmentsSource = AppointmentModels
}; };
} }
public AppointmentModel CreateAppointmentModel(Transfer transfer) public AppointmentModel CreateAppointmentModel(Transfer transfer)
@ -503,4 +490,5 @@
//_gridTransfer.ExpandDetailRow(0); //_gridTransfer.ExpandDetailRow(0);
} }
} }
} }

View File

@ -143,7 +143,7 @@
[Parameter] public GridDetailExpandButtonDisplayMode DetailExpandButtonDisplayMode { get; set; } = GridDetailExpandButtonDisplayMode.Never; [Parameter] public GridDetailExpandButtonDisplayMode DetailExpandButtonDisplayMode { get; set; } = GridDetailExpandButtonDisplayMode.Never;
[Parameter] public bool ShowManageButtons { get; set; } = false; [Parameter] public bool ShowManageButtons { get; set; } = false;
private List<TransferDestination> destinations = []; private List<TransferDestination> _destinations = [];
private ProductDetailGrid _productGrid = null!; private ProductDetailGrid _productGrid = null!;
private LoggerClient<ProductDetailGridComponent> _logger = null!; private LoggerClient<ProductDetailGridComponent> _logger = null!;
@ -157,7 +157,8 @@
protected override void OnInitialized() protected override void OnInitialized()
{ {
_logger = new LoggerClient<ProductDetailGridComponent>(LogWriters.ToArray()); _logger = new LoggerClient<ProductDetailGridComponent>(LogWriters.ToArray());
AdminSignalRClient.GetAllIntoAsync<TransferDestination>(destinations, SignalRTags.GetAllTransferDestinations).Forget();
AdminSignalRClient.GetTransferDestinationsAsync(_destinations).Forget();
//DataSource = new List<Address>(); //DataSource = new List<Address>();
} }
@ -166,9 +167,9 @@
{ {
if(destinations!=null) if(_destinations!=null)
{ {
if (destinations.Any(d => d.AddressId == addressId)) if (_destinations.Any(d => d.AddressId == addressId))
{ {
return true; return true;
} }

View File

@ -144,7 +144,7 @@
[Parameter] public EventCallback<GridEditModelSavingEventArgs> OnGridEditModelSaving { get; set; } [Parameter] public EventCallback<GridEditModelSavingEventArgs> OnGridEditModelSaving { get; set; }
[Parameter] public GridDetailExpandButtonDisplayMode DetailExpandButtonDisplayMode { get; set; } = GridDetailExpandButtonDisplayMode.Never; [Parameter] public GridDetailExpandButtonDisplayMode DetailExpandButtonDisplayMode { get; set; } = GridDetailExpandButtonDisplayMode.Never;
private List<TransferDestination> destinations = []; private List<TransferDestination> _destinations = [];
private ProductGrid _productGrid = null!; private ProductGrid _productGrid = null!;
private LoggerClient<ProductGridComponent> _logger = null!; private LoggerClient<ProductGridComponent> _logger = null!;
@ -159,16 +159,17 @@
protected override void OnInitialized() protected override void OnInitialized()
{ {
_logger = new LoggerClient<ProductGridComponent>(LogWriters.ToArray()); _logger = new LoggerClient<ProductGridComponent>(LogWriters.ToArray());
AdminSignalRClient.GetAllIntoAsync<TransferDestination>(destinations, SignalRTags.GetAllTransferDestinations).Forget();
AdminSignalRClient.GetTransferDestinationsAsync(_destinations).Forget();
} }
private bool CheckDestinations(Guid addressId) private bool CheckDestinations(Guid addressId)
{ {
if (destinations != null) if (_destinations != null)
{ {
if (destinations.Any(d => d.AddressId == addressId)) if (_destinations.Any(d => d.AddressId == addressId))
{ {
return true; return true;
} }

View File

@ -36,10 +36,10 @@
<DxGridDataColumn FieldName="ProductId" Caption="ServiceId"> <DxGridDataColumn FieldName="ProductId" Caption="ServiceId">
<CellEditTemplate> <CellEditTemplate>
@{ @{
var TransferDestinationToProductEditModel = (TransferDestinationToProduct)context.EditModel; var transferDestinationToProductEditModel = (TransferDestinationToProduct)context.EditModel;
} }
<DxComboBox Data="@_products" TextFieldName="Name" ValueFieldName="Id" @bind-Value="TransferDestinationToProductEditModel.ProductId" ReadOnly="@ProductIdReadOnly" <DxComboBox Data="@_products" TextFieldName="Name" ValueFieldName="Id" @bind-Value="transferDestinationToProductEditModel.ProductId" ReadOnly="@_productIdReadOnly"
SearchFilterCondition="ListSearchFilterCondition.Contains" SearchMode="ListSearchMode.AutoSearch"> SearchFilterCondition="ListSearchFilterCondition.Contains" SearchMode="ListSearchMode.AutoSearch">
</DxComboBox> </DxComboBox>
</CellEditTemplate> </CellEditTemplate>
@ -47,10 +47,10 @@
<DxGridDataColumn FieldName="TransferDestinationId"> <DxGridDataColumn FieldName="TransferDestinationId">
<CellEditTemplate> <CellEditTemplate>
@{ @{
var TransferDestinationToProductEditModel = (TransferDestinationToProduct)context.EditModel; var transferDestinationToProductEditModel = (TransferDestinationToProduct)context.EditModel;
} }
<DxComboBox Data="@_transferDestinations" TextFieldName="Name" ValueFieldName="Id" @bind-Value="TransferDestinationToProductEditModel.TransferDestinationId" ReadOnly="@DestinationIdReadOnly" <DxComboBox Data="@_destinations" TextFieldName="Name" ValueFieldName="Id" @bind-Value="transferDestinationToProductEditModel.TransferDestinationId" ReadOnly="@_destinationIdReadOnly"
SearchFilterCondition="ListSearchFilterCondition.Contains" SearchMode="ListSearchMode.AutoSearch"> SearchFilterCondition="ListSearchFilterCondition.Contains" SearchMode="ListSearchMode.AutoSearch">
</DxComboBox> </DxComboBox>
</CellEditTemplate> </CellEditTemplate>
@ -111,11 +111,11 @@
[Parameter] public bool IsProductIdReadonly { get; set; } = false; [Parameter] public bool IsProductIdReadonly { get; set; } = false;
[Parameter] public bool IsDestinationIdReadonly { get; set; } = false; [Parameter] public bool IsDestinationIdReadonly { get; set; } = false;
private bool ProductIdReadOnly = false; private bool _productIdReadOnly = false;
private bool DestinationIdReadOnly = false; private bool _destinationIdReadOnly = false;
//private bool? _isNewState = null; //private bool? _isNewState = null;
private List<TransferDestination> _transferDestinations = []; private List<TransferDestination> _destinations = [];
private List<Product> _products = []; private List<Product> _products = [];
private LoggerClient<TransferDestinationToProductGridComponent> _logger = null!; private LoggerClient<TransferDestinationToProductGridComponent> _logger = null!;
@ -123,8 +123,10 @@
protected override void OnInitialized() protected override void OnInitialized()
{ {
_logger = new LoggerClient<TransferDestinationToProductGridComponent>(LogWriters.ToArray()); _logger = new LoggerClient<TransferDestinationToProductGridComponent>(LogWriters.ToArray());
AdminSignalRClient.GetAllIntoAsync(_transferDestinations, SignalRTags.GetAllTransferDestinations).Forget();
AdminSignalRClient.GetTransferDestinationsAsync(_destinations).Forget();
AdminSignalRClient.GetAllIntoAsync(_products, SignalRTags.GetAllProducts).Forget(); AdminSignalRClient.GetAllIntoAsync(_products, SignalRTags.GetAllProducts).Forget();
base.OnInitialized(); base.OnInitialized();
} }
@ -132,9 +134,9 @@
{ {
if (!e.IsNew) if (!e.IsNew)
{ {
DestinationIdReadOnly = true; _destinationIdReadOnly = true;
ProductIdReadOnly = true; _productIdReadOnly = true;
} }
else else
@ -143,12 +145,12 @@
{ {
((TransferDestinationToProduct)(e.EditModel)).TransferDestinationId = (Guid)ContextIds[0]; ((TransferDestinationToProduct)(e.EditModel)).TransferDestinationId = (Guid)ContextIds[0];
} }
DestinationIdReadOnly = IsDestinationIdReadonly; _destinationIdReadOnly = IsDestinationIdReadonly;
if (IsProductIdReadonly) if (IsProductIdReadonly)
{ {
((TransferDestinationToProduct)(e.EditModel)).ProductId = (Guid)ContextIds[0]; ((TransferDestinationToProduct)(e.EditModel)).ProductId = (Guid)ContextIds[0];
} }
ProductIdReadOnly = IsProductIdReadonly; _productIdReadOnly = IsProductIdReadonly;
} }
if (!e.IsNew) return; if (!e.IsNew) return;
@ -157,14 +159,14 @@
private void OnGridEditModelSaving(GridEditModelSavingEventArgs e) private void OnGridEditModelSaving(GridEditModelSavingEventArgs e)
{ {
DestinationIdReadOnly = false; _destinationIdReadOnly = false;
ProductIdReadOnly = false; _productIdReadOnly = false;
} }
private void EditCanceling(GridEditCancelingEventArgs e) private void EditCanceling(GridEditCancelingEventArgs e)
{ {
DestinationIdReadOnly = false; _destinationIdReadOnly = false;
ProductIdReadOnly = false; _productIdReadOnly = false;
} }

View File

@ -47,7 +47,7 @@
var TransferDestinationToProductEditModel = (TransferDestinationToProduct)context.EditModel; var TransferDestinationToProductEditModel = (TransferDestinationToProduct)context.EditModel;
} }
<DxComboBox Data="@_transferDestinations" TextFieldName="Name" ValueFieldName="Id" @bind-Value="TransferDestinationToProductEditModel.TransferDestinationId" ReadOnly="@(!_isNewState!.Value)" <DxComboBox Data="@_destinations" TextFieldName="Name" ValueFieldName="Id" @bind-Value="TransferDestinationToProductEditModel.TransferDestinationId" ReadOnly="@(!_isNewState!.Value)"
SearchFilterCondition="ListSearchFilterCondition.Contains" SearchMode="ListSearchMode.AutoSearch"> SearchFilterCondition="ListSearchFilterCondition.Contains" SearchMode="ListSearchMode.AutoSearch">
</DxComboBox> </DxComboBox>
</CellEditTemplate> </CellEditTemplate>
@ -101,15 +101,17 @@
private LoggerClient<TransferDestinationToProductGridComponent> _logger = null!; private LoggerClient<TransferDestinationToProductGridComponent> _logger = null!;
private bool? _isNewState = null; private bool? _isNewState = null;
private List<TransferDestination> _transferDestinations = []; private List<TransferDestination> _destinations = [];
private List<Product> _products = []; private List<Product> _products = [];
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
_logger = new LoggerClient<TransferDestinationToProductGridComponent>(LogWriters.ToArray()); _logger = new LoggerClient<TransferDestinationToProductGridComponent>(LogWriters.ToArray());
AdminSignalRClient.GetAllIntoAsync(_transferDestinations, SignalRTags.GetAllTransferDestinations).Forget();
AdminSignalRClient.GetTransferDestinationsAsync(_destinations).Forget();
AdminSignalRClient.GetAllIntoAsync(_products, SignalRTags.GetAllProducts).Forget(); AdminSignalRClient.GetAllIntoAsync(_products, SignalRTags.GetAllProducts).Forget();
await base.OnInitializedAsync(); await base.OnInitializedAsync();
} }

View File

@ -218,19 +218,6 @@
"ContextId", "ContextId",
]; ];
private static readonly List<TransferStatusModel> Statuses =
[
new(Convert.ToByte(TransferStatusType.OrderSubmitted), "Order submitted"),
new(Convert.ToByte(TransferStatusType.OrderConfirmed), "Order confirmed"),
new(Convert.ToByte(TransferStatusType.AssignedToDriver), "Assigned to driver"),
new(Convert.ToByte(TransferStatusType.DriverConfirmed), "Driver confirmed"),
new(Convert.ToByte(TransferStatusType.DriverEnRoute), "Driver enroute"),
new(Convert.ToByte(TransferStatusType.PassengerPickup), "Passenger in car"),
new(Convert.ToByte(TransferStatusType.Finished), "Finished"),
new(Convert.ToByte(TransferStatusType.UserCanceled), "User cancelled"),
new(Convert.ToByte(TransferStatusType.AdminDenied), "Admin cancelled")
];
void Grid_CustomizeElement(GridCustomizeElementEventArgs e) void Grid_CustomizeElement(GridCustomizeElementEventArgs e)
{ {
try try

View File

@ -1,7 +1,9 @@
@using System.Linq.Expressions @using System.Linq.Expressions
@using AyCode.Core.Extensions @using AyCode.Core.Extensions
@using AyCode.Core.Helpers
@using AyCode.Core.Loggers @using AyCode.Core.Loggers
@using AyCode.Services.Loggers @using AyCode.Services.Loggers
@using AyCode.Services.SignalRs
@using TIAM.Core.Loggers @using TIAM.Core.Loggers
@using TIAM.Entities.Products @using TIAM.Entities.Products
@using TIAM.Entities.Transfers @using TIAM.Entities.Transfers
@ -23,7 +25,7 @@
<DxTabPage Text="Preset addresses"> <DxTabPage Text="Preset addresses">
<DxComboBox Data="@Data" <DxComboBox Data="@_destinations"
CssClass="p-3" CssClass="p-3"
InputCssClass="@CssClass" InputCssClass="@CssClass"
@bind-Value="@SelectedDestination" @bind-Value="@SelectedDestination"
@ -54,7 +56,7 @@
</DxTabPage> </DxTabPage>
</DxTabs> </DxTabs>
<p>Selected address: @Address</p> <p>Selected address: @_address</p>
@* <p class="demo-text cw-480 mt-3"> @* <p class="demo-text cw-480 mt-3">
@ -79,30 +81,27 @@
[Parameter] public Guid? ProductId { get; set; } [Parameter] public Guid? ProductId { get; set; }
public List<TransferDestination> Destinations = new List<TransferDestination>();
public DxTextBox TextField; public DxTextBox TextField;
TransferDestination Result; TransferDestination Result;
ILogger _logger; ILogger _logger;
IEnumerable<TransferDestination> Data { get; set; } readonly List<TransferDestination> _destinations = [];
private string Address { get; set; } private string _address = string.Empty;
private string ValidationMessage { get; set; } private string _validationMessage = string.Empty;
private TransferDestination _selectedDestination; private TransferDestination? _selectedDestination;
public TransferDestination SelectedDestination public TransferDestination? SelectedDestination
{ {
get => _selectedDestination; get => _selectedDestination;
set set
{ {
if (_selectedDestination != value) if (_selectedDestination == value) return;
{
_selectedDestination = value; _selectedDestination = value;
SetNewDestination(value.AddressString!); SetNewDestination(value?.AddressString ?? string.Empty);
}
} }
} }
@ -111,35 +110,21 @@
// StateHasChanged(); // StateHasChanged();
} }
protected override async Task OnInitializedAsync() protected override Task OnInitializedAsync()
{ {
_logger = new LoggerClient<ComboboxItemSelector>(LogWriters.ToArray()); _logger = new LoggerClient<ComboboxItemSelector>(LogWriters.ToArray());
Data = await _adminSignalRClient.GetAllAsync<List<TransferDestination>>(SignalRTags.GetAllTransferDestinations); if (ProductId.IsNullOrEmpty()) _adminSignalRClient.GetTransferDestinationsAsync(_destinations, GetTransferDestinationsCallback()).Forget();
else _adminSignalRClient.GetPublicTransferDestinationsAsync(_destinations, ProductId.Value, GetTransferDestinationsCallback()).Forget();
Guid? productAddressId = Guid.Empty; return Task.CompletedTask;
if (!ProductId.IsNullOrEmpty())
{
var currentProduct = await _adminSignalRClient.GetByIdAsync<Product>(SignalRTags.GetProductById, ProductId);
if (currentProduct != null)
{
if (!currentProduct.Profile.AddressId.IsNullOrEmpty())
{
productAddressId = currentProduct.Profile.AddressId;
}
}
}
_logger.Debug($"List length: {Data.Count().ToString()}"); Action GetTransferDestinationsCallback()
if (Data.Any(x => x.AddressId == (Guid)productAddressId))
{ {
SelectedDestination = Data.Where(x => x.AddressId == (Guid)productAddressId).FirstOrDefault()!; return () => { SelectedDestination = ProductId.IsNullOrEmpty() ? _destinations.FirstOrDefault() : _destinations.FirstOrDefault(x => x.ProductId == ProductId); };
}
else
{
SelectedDestination = Data.FirstOrDefault();
} }
} }
// RenderFragment GetSelectedItemDescription() // RenderFragment GetSelectedItemDescription()
// { // {
// if (SelectedDestination != null) // if (SelectedDestination != null)
@ -159,13 +144,13 @@
public void OnSelectedAddressChanged(string address) public void OnSelectedAddressChanged(string address)
{ {
Address = address; _address = address;
OnSliderChanged.InvokeAsync(address); OnSliderChanged.InvokeAsync(address);
} }
public void SetNewDestination(string address) public void SetNewDestination(string address)
{ {
Address = address; _address = address;
OnSliderChanged.InvokeAsync(address); OnSliderChanged.InvokeAsync(address);
} }

View File

@ -47,9 +47,16 @@ namespace TIAMSharedUI.Shared.Components.BaseComponents
protected override void OnInitialized() protected override void OnInitialized()
{ {
Initialize();
base.OnInitialized(); base.OnInitialized();
}
private void Initialize()
{
_logger = new LoggerClient<BasePageComponent>(_logWriters.ToArray()); _logger = new LoggerClient<BasePageComponent>(_logWriters.ToArray());
var currentUrl = _navManager.ToBaseRelativePath(_navManager.Uri); var currentUrl = _navManager.ToBaseRelativePath(_navManager.Uri);
_pageState.AddPageToHistory(currentUrl); _pageState.AddPageToHistory(currentUrl);
_logger.Debug(_pageState.GetGoBackPage()); _logger.Debug(_pageState.GetGoBackPage());
} }

View File

@ -17,20 +17,20 @@ namespace TIAMSharedUI.Shared.Components.BaseComponents
{ {
[Authorize] [Authorize]
public class UserBasePageComponent : BasePageComponent public class UserBasePageComponent : BasePageComponent
{ {
private LoggerClient<UserBasePageComponent> _logger = null!; private LoggerClient<UserBasePageComponent> _logger = null!;
public UserBasePageComponent() public UserBasePageComponent()
{ {
} }
protected override void OnInitialized() protected override void OnInitialized()
{ {
base.OnInitialized();
_logger = new LoggerClient<UserBasePageComponent>(_logWriters.ToArray()); _logger = new LoggerClient<UserBasePageComponent>(_logWriters.ToArray());
base.OnInitialized();
} }
} }
} }

View File

@ -24,17 +24,17 @@
protected override void OnInitialized() protected override void OnInitialized()
{ {
if(pageHistoryState.CanGoBack()) if (pageHistoryState.CanGoBack())
{ {
isBackVisible = true; isBackVisible = true;
} }
} }
private void GoBack() private void GoBack()
{ {
@if (pageHistoryState.CanGoBack()) @if (pageHistoryState.CanGoBack())
{ {
NavManager.NavigateTo(pageHistoryState.GetGoBackPage()); NavManager.NavigateTo(pageHistoryState.GetGoBackPage()!);
} }
} }
} }

View File

@ -19,7 +19,7 @@ using TIAMWebApp.Shared.Application.Services;
namespace TIAMWebApp.Client.Services namespace TIAMWebApp.Client.Services
{ {
public class UserDataServiceWeb(HttpClient http, ISessionService sessionService, ISecureStorageHandler secureStorageHandler, IServiceProviderDataService serviceProviderDataService, IEnumerable<IAcLogWriterClientBase> logWriters) public class UserDataServiceWeb(HttpClient http, AdminSignalRClient adminSignalRClient, ISessionService sessionService, ISecureStorageHandler secureStorageHandler, IServiceProviderDataService serviceProviderDataService, IEnumerable<IAcLogWriterClientBase> logWriters)
: UserDataServiceClientBase(http, sessionService, secureStorageHandler, serviceProviderDataService, logWriters); : UserDataServiceClientBase(http, adminSignalRClient, sessionService, secureStorageHandler, serviceProviderDataService, logWriters);
} }

View File

@ -497,64 +497,69 @@ namespace TIAMWebApp.Server.Controllers
[Tags("In-Progress", "Product")] [Tags("In-Progress", "Product")]
public async Task<IActionResult> GetQRCodeByProductId([FromBody] Guid productId) public async Task<IActionResult> GetQRCodeByProductId([FromBody] Guid productId)
{ {
_logger.Info(@"GetQRCode called"); _logger.Info($"GetQRCode called; productId: {productId}");
if (productId == Guid.Empty) return BadRequest("OBSOLATE");
{ if (productId.IsNullOrEmpty()) return BadRequest("Product is required");
return BadRequest("Product is required");
}
else
{
//var result = _serviceProviderDal.GetQRCodeAsync(productId);
var qrGenerator = new QRCodeGenerator(); //var result = _serviceProviderDal.GetQRCodeAsync(productId);
var qrCodeData = qrGenerator.CreateQrCode($"https://touriam.com/{productId}", QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCode(qrCodeData); var qrGenerator = new QRCodeGenerator();
//Bitmap qrCodeImage = qrCode.GetGraphic(20); var qrCodeData = qrGenerator.CreateQrCode($"https://touriam.com/{productId}", QRCodeGenerator.ECCLevel.Q);
//var rootpath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "assets"); var qrCode = new QRCode(qrCodeData);
var rootpath = System.IO.Path.Combine(env.WebRootPath, "assets");
var qrCodeImage = qrCode.GetGraphic(20, Color.DarkMagenta, Color.White, (Bitmap)Bitmap.FromFile(rootpath + "/myimage.png")); //Bitmap qrCodeImage = qrCode.GetGraphic(20);
_logger.Info($@"qrCodeLogo: {rootpath}/myimage.png"); //var rootpath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "assets");
var ms = new MemoryStream(); var rootpath = Path.Combine(env.WebRootPath, "assets");
var qrCodeImage = qrCode.GetGraphic(20, Color.DarkMagenta, Color.White, (Bitmap)Bitmap.FromFile(rootpath + "/myimage.png"));
_logger.Debug($@"qrCodeLogo: {rootpath}/myimage.png");
byte[] byteImage;
using (var ms = new MemoryStream())
{
qrCodeImage.Save(ms, ImageFormat.Jpeg); qrCodeImage.Save(ms, ImageFormat.Jpeg);
var byteImage = ms.ToArray(); byteImage = ms.ToArray();
var sigBase64 = Convert.ToBase64String(byteImage); // Get Base64
return Ok(sigBase64);
} }
var sigBase64 = Convert.ToBase64String(byteImage); // Get Base64
return Ok(sigBase64);
} }
[AllowAnonymous] [AllowAnonymous]
[HttpPost] [HttpPost]
[Route(APIUrls.GetQrCodeByProductIdAndOwnerAffiliateIdRouteName)] [Route(APIUrls.GetQrCodeByProductIdAndOwnerAffiliateIdRouteName)]
public async Task<IActionResult> GetQrCodeByProductIdAndOwnerAffiliateId([FromBody] Guid[] Ids) public async Task<IActionResult> GetQrCodeByProductIdAndOwnerAffiliateId([FromBody] Guid[] ids)
{ {
_logger.Info(@"GetQRCode called"); _logger.Info(@"GetQRCode called");
if (Ids[0].IsNullOrEmpty() || Ids[1].IsNullOrEmpty()) if (ids[0].IsNullOrEmpty() || ids[1].IsNullOrEmpty())
{ {
return BadRequest("Product is required"); return BadRequest("Product is required");
} }
else
var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode($"{Setting.BaseUrl}/public/transfer/{ids[0]}/{ids[1]}", QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCode(qrCodeData);
//Bitmap qrCodeImage = qrCode.GetGraphic(20);
//var rootpath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "assets");
var rootpath = Path.Combine(env.WebRootPath, "assets");
var qrCodeImage = qrCode.GetGraphic(20, Color.DarkMagenta, Color.White, (Bitmap)Bitmap.FromFile(rootpath + "/myimage.png"));
_logger.Info($@"qrCodeLogo: {rootpath}/myimage.png");
byte[] byteImage;
using (var ms = new MemoryStream())
{ {
var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode($"{Setting.BaseUrl}/public/transfer/{Ids[0]}/{Ids[1]}", QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCode(qrCodeData);
//Bitmap qrCodeImage = qrCode.GetGraphic(20);
//var rootpath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "assets");
var rootpath = System.IO.Path.Combine(env.WebRootPath, "assets");
var qrCodeImage = qrCode.GetGraphic(20, Color.DarkMagenta, Color.White, (Bitmap)Bitmap.FromFile(rootpath + "/myimage.png"));
_logger.Info($@"qrCodeLogo: {rootpath}/myimage.png");
var ms = new MemoryStream();
qrCodeImage.Save(ms, ImageFormat.Jpeg); qrCodeImage.Save(ms, ImageFormat.Jpeg);
var byteImage = ms.ToArray(); byteImage = ms.ToArray();
var sigBase64 = Convert.ToBase64String(byteImage); // Get Base64
return Ok(sigBase64);
} }
var sigBase64 = Convert.ToBase64String(byteImage); // Get Base64
return Ok(sigBase64);
} }
} }
} }

View File

@ -77,9 +77,16 @@ namespace TIAMWebApp.Server.Controllers
[HttpGet] [HttpGet]
[Route(APIUrls.GetTransferDestinationsRouteName)] [Route(APIUrls.GetTransferDestinationsRouteName)]
[SignalR(SignalRTags.GetAllTransferDestinations)] [SignalR(SignalRTags.GetAllTransferDestinations)]
public List<TransferDestination> GetTransferDestinations() public async Task<List<TransferDestination>> GetTransferDestinations()
{ {
return _adminDal.GetTransferDestinations(); return await _adminDal.GetTransferDestinationsAsync();
}
[NonAction]
[SignalR(SignalRTags.GetAllTransferDestinationsByProductId)]
public async Task<List<TransferDestination>> GetPublicTransferDestinations(Guid includeProductId)
{
return await _adminDal.GetPublicTransferDestinationsAsync(includeProductId);
} }
//[Authorize] //[Authorize]

View File

@ -96,28 +96,40 @@ namespace TIAMWebApp.Server.Controllers
if (authenticateUser == null) throw new NullReferenceException("authenticateUser == null"); if (authenticateUser == null) throw new NullReferenceException("authenticateUser == null");
_logger.Info(authenticateUser.Email); var response = await AuthenticateUser(authenticateUser);
var loggedInModel = _loginService.Login(authenticateUser.Email, authenticateUser.Password); if (response != null) return Ok(response);
if (loggedInModel.IsLoggedIn)
return Unauthorized();
}
[NonAction]
[SignalR(SignalRTags.AuthenticateUser)]
public async Task<MainResponse?> AuthenticateUser(LoginModel authenticateUser)
{
_logger.Info($"AuthenticateUser; {authenticateUser.Email}");
var loggedInModel = await _loginService.LoginAsync(authenticateUser.Email, authenticateUser.Password);
if (!loggedInModel.IsLoggedIn)
{ {
var response = new MainResponse _logger.Warning(@"User not valid! errorCode: " + loggedInModel.LoginErrorCode);
{ return null;
Content = new AuthenticationResponse
{
RefreshToken = loggedInModel.LoggedInUser.RefreshToken,
AccessToken = loggedInModel.AccessToken
},
IsSuccess = true,
ErrorMessage = ""
};
return Ok(response);
} }
_logger.Warning(@"User not valid! errorCode: " + loggedInModel.LoginErrorCode); var response = new MainResponse
return Unauthorized(); {
Content = new AuthenticationResponse
{
RefreshToken = loggedInModel.LoggedInUser.RefreshToken,
AccessToken = loggedInModel.AccessToken
},
IsSuccess = true,
ErrorMessage = ""
};
return response;
} }
[AllowAnonymous] [AllowAnonymous]
@ -199,7 +211,7 @@ namespace TIAMWebApp.Server.Controllers
else else
{ {
var user = JObject.Parse(serializedRegistrationModel.GetRawText()).ToObject<RegistrationModel>(); var user = JObject.Parse(serializedRegistrationModel.GetRawText()).ToObject<RegistrationModel>();
bool result = false; var result = false;
if (user != null) if (user != null)
{ {
//add userModel to users array //add userModel to users array
@ -297,6 +309,7 @@ namespace TIAMWebApp.Server.Controllers
[AllowAnonymous] [AllowAnonymous]
[HttpGet] [HttpGet]
[Route("GetUsers")] [Route("GetUsers")]
[SignalR(SignalRTags.GetAllUserModelDto)]
public async Task<List<UserModelDto>> GetUsers() public async Task<List<UserModelDto>> GetUsers()
{ {
//var users = await _userDal.Ctx.Users.ToListAsync();//.GetUsersAsync(); //var users = await _userDal.Ctx.Users.ToListAsync();//.GetUsersAsync();
@ -412,34 +425,35 @@ namespace TIAMWebApp.Server.Controllers
[AllowAnonymous] [AllowAnonymous]
[HttpGet] [HttpGet]
[Route(APIUrls.GetUserByEmailRouteName + "/{email}")] [Route(APIUrls.GetUserByEmailRouteName + "/{email}")]
public async Task<UserModelDto>? GetUserByEmail(string email) [SignalR(SignalRTags.GetUserModelDtoByEmail)]
public async Task<UserModelDto?> GetUserByEmail(string email)
{ {
_logger.Info($"GetUserByEmail called with email: {email}"); _logger.Info($"GetUserByEmail called with email: {email}");
var result = await userDal.GetUserModelDtoByEmailAsync<UserModelDto>(email, false);
if (result == null)
{
UserModelDto resultDto = new UserModelDto();
return resultDto;
}
else
{
return result;
}
return await userDal.GetUserModelDtoByEmailAsync<UserModelDto>(email, false);
//var result = await userDal.GetUserModelDtoByEmailAsync<UserModelDto>(email, false);
//if (result != null) return result;
//var resultDto = new UserModelDto();
//return resultDto;
} }
[AllowAnonymous] [AllowAnonymous]
[HttpPost] [HttpPost]
[Route(APIUrls.GetUserByIdRouteName)] [Route(APIUrls.GetUserByIdRouteName)]
[SignalR(SignalRTags.GetUserModelDtoById)]
public async Task<UserModelDto?> GetUserById([FromBody] Guid id) public async Task<UserModelDto?> GetUserById([FromBody] Guid id)
{ {
_logger.Info($"GetUserById called with id: {id}"); _logger.Info($"GetUserById called with id: {id}");
return await userDal.GetUserModelDtoByIdAsync<UserModelDto>(id, true); return await userDal.GetUserModelDtoByIdAsync<UserModelDto>(id, true);
} }
[AllowAnonymous] [AllowAnonymous]
[HttpPost] [HttpPost]
[Route(APIUrls.GetUserDetailByIdRouteName)] [Route(APIUrls.GetUserDetailByIdRouteName)]
[SignalR(SignalRTags.GetUserModelDtoDetailById)]
public async Task<UserModelDtoDetail?> GetUserDetailById([FromBody] Guid id) public async Task<UserModelDtoDetail?> GetUserDetailById([FromBody] Guid id)
{ {
_logger.Info($"GetUserDetailById called with id: {id}"); _logger.Info($"GetUserDetailById called with id: {id}");

View File

@ -8,14 +8,14 @@ namespace TIAMWebApp.Shared.Application.Interfaces
{ {
public Task<UserSessionModel> IsLoggedInAsync(Guid id); public Task<UserSessionModel> IsLoggedInAsync(Guid id);
public Task<string> AuthenticateUser(LoginModel loginModel); public Task<MainResponse?> AuthenticateUser(LoginModel loginModel);
public Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel); public Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel);
public Task<(bool isSuccess, UserModelDto? user)> CreateGuestUser(RegistrationModel regModel); public Task<(bool isSuccess, UserModelDto? user)> CreateGuestUser(RegistrationModel regModel);
public Task<string> TestUserApi(int Param); public Task<string> TestUserApi(int Param);
//public Task<Dictionary<int, string>> GetUserRolesAsync(UserModel userModel); //public Task<Dictionary<int, string>> GetUserRolesAsync(UserModel userModel);
public Task<List<UserModelDto>?> GetUsersAsync(); public Task<List<UserModelDto>> GetUsersAsync();
public Task<List<UserModelDtoDetail>> GetUsersWithDetailsAsync(); public Task<List<UserModelDtoDetail>> GetUsersWithDetailsAsync();

View File

@ -1,14 +1,46 @@
namespace TIAMWebApp.Shared.Application.Models.ClientSide.UI using TIAM.Core.Enums;
{
namespace TIAMWebApp.Shared.Application.Models.ClientSide.UI
{
public class TransferStatusModel public class TransferStatusModel
{ {
public byte StatusValue { get; set; } public TransferStatusType StatusValue { get; set; }
public string StatusName { get; set; } public string StatusName { get; set; }
public TransferStatusModel(byte statusValue, string statusName) public TransferStatusModel(TransferStatusType statusValue, string statusName)
{ {
StatusValue = statusValue; StatusValue = statusValue;
StatusName = statusName; StatusName = statusName;
} }
public static TransferStatusModel GetStatusModel(TransferStatusType transferStatusType)
=> AllStatuses[transferStatusType];
//TODO: ez nem igazán a TransferStatusModel-re való... - J.
public static readonly Dictionary<TransferStatusType, TransferStatusModel> AllStatuses = new()
{
[TransferStatusType.OrderSubmitted] = new TransferStatusModel(TransferStatusType.OrderSubmitted, "Order submitted"),
[TransferStatusType.OrderConfirmed] = new TransferStatusModel(TransferStatusType.OrderConfirmed, "Order confirmed"),
[TransferStatusType.AssignedToDriver] = new TransferStatusModel(TransferStatusType.AssignedToDriver, "Assigned to driver"),
[TransferStatusType.DriverConfirmed] = new TransferStatusModel(TransferStatusType.DriverConfirmed, "Driver confirmed"),
[TransferStatusType.DriverEnRoute] = new TransferStatusModel(TransferStatusType.DriverEnRoute, "Driver enroute"),
[TransferStatusType.PassengerPickup] = new TransferStatusModel(TransferStatusType.PassengerPickup, "Passenger in car"),
[TransferStatusType.Finished] = new TransferStatusModel(TransferStatusType.Finished, "Finished"),
[TransferStatusType.UserCanceled] = new TransferStatusModel(TransferStatusType.UserCanceled, "User cancelled"),
[TransferStatusType.AdminDenied] = new TransferStatusModel(TransferStatusType.AdminDenied, "Admin cancelled"),
};
//public static readonly Dictionary<TransferStatusType, TransferStatusModel> AllStatuses =
//[
// new(TransferStatusType.OrderSubmitted, "Order submitted"),
// new(TransferStatusType.OrderConfirmed, "Order confirmed"),
// new(TransferStatusType.AssignedToDriver, "Assigned to driver"),
// new(TransferStatusType.DriverConfirmed, "Driver confirmed"),
// new(TransferStatusType.DriverEnRoute, "Driver enroute"),
// new(TransferStatusType.PassengerPickup, "Passenger in car"),
// new(TransferStatusType.Finished, "Finished"),
// new(TransferStatusType.UserCanceled, "User cancelled"),
// new(TransferStatusType.AdminDenied, "Admin cancelled")
//];
} }
} }

View File

@ -2,7 +2,6 @@
using AyCode.Core.Consts; using AyCode.Core.Consts;
using AyCode.Core.Helpers; using AyCode.Core.Helpers;
using AyCode.Services.Loggers; using AyCode.Services.Loggers;
using AyCode.Services.SignalRs;
using TIAM.Entities.Drivers; using TIAM.Entities.Drivers;
using TIAM.Entities.Transfers; using TIAM.Entities.Transfers;
using TIAM.Entities.Users; using TIAM.Entities.Users;
@ -58,19 +57,7 @@ namespace TIAMWebApp.Shared.Application.Services
{ {
Logger.Detail($"GetAllCarsByProductIdAsync client called; productId: {productId}"); Logger.Detail($"GetAllCarsByProductIdAsync client called; productId: {productId}");
//TODO: AdminSignalRClient.GetAllIntoAsync<Car>(_cars, SignalRTags.GetAllCarsByProductId, [productId]) - J. return GetAllIntoAsync(intoCars, SignalRTags.GetAllCarsByProductId, [productId], callback);
return GetAllAsync<List<Car>>(SignalRTags.GetAllCarsByProductId, response =>
{
if (response is { Status: SignalResponseStatus.Success, ResponseData: not null })
{
intoCars.Clear();
intoCars.AddRange(response.ResponseData);
}
callback?.Invoke();
return Task.CompletedTask;
}, [productId]);
} }
#endregion ICompanyApiController #endregion ICompanyApiController
@ -137,10 +124,18 @@ namespace TIAMWebApp.Shared.Application.Services
throw new NotImplementedException(); throw new NotImplementedException();
} }
public List<TransferDestination> GetTransferDestinations() public async Task<List<TransferDestination>> GetTransferDestinations()
{ => await GetAllAsync<List<TransferDestination>>(SignalRTags.GetAllTransferDestinations) ?? [];
throw new NotImplementedException();
}
public Task GetTransferDestinationsAsync(List<TransferDestination> intoDestinationList, Action? callback = null)
=> GetAllIntoAsync(intoDestinationList, SignalRTags.GetAllTransferDestinations, null, callback);
public async Task<List<TransferDestination>> GetPublicTransferDestinations(Guid includeProductId)
=> await GetAllAsync<List<TransferDestination>>(SignalRTags.GetAllTransferDestinationsByProductId, [includeProductId]) ?? [];
public Task GetPublicTransferDestinationsAsync(List<TransferDestination> intoDestinationList, Guid includeProductId, Action? callback = null)
=> GetAllIntoAsync(intoDestinationList, SignalRTags.GetAllTransferDestinationsByProductId, [includeProductId], callback);
public async Task<TransferDestination?> GetTransferDestinationById(Guid transferDestinationId) public async Task<TransferDestination?> GetTransferDestinationById(Guid transferDestinationId)
{ {

View File

@ -199,8 +199,6 @@ namespace TIAMWebApp.Shared.Application.Services
public async Task<string> GetQRCodeByProductIdAsync(Guid productId) public async Task<string> GetQRCodeByProductIdAsync(Guid productId)
{ {
var url = APIUrls.GetQrCodeByProductId; var url = APIUrls.GetQrCodeByProductId;
var response = await http.PostAsJsonAsync(url, productId); var response = await http.PostAsJsonAsync(url, productId);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
@ -215,11 +213,10 @@ namespace TIAMWebApp.Shared.Application.Services
} }
} }
public async Task<string> GetQRCodeByProductIdAndOwnerAffiliateIdAsync(Guid[] Ids) public async Task<string> GetQRCodeByProductIdAndOwnerAffiliateIdAsync(Guid[] ids)
{ {
var url = APIUrls.GetQrCodeByProductIdAndOwnerAffiliateId; var url = APIUrls.GetQrCodeByProductIdAndOwnerAffiliateId;
var response = await http.PostAsJsonAsync(url, Ids); var response = await http.PostAsJsonAsync(url, ids);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();

View File

@ -1,4 +1,5 @@
using System.Net; using System.Net;
using TIAM.Core.Enums;
using TIAM.Entities.Products; using TIAM.Entities.Products;
using TIAM.Models; using TIAM.Models;
using TIAMWebApp.Shared.Application.Interfaces; using TIAMWebApp.Shared.Application.Interfaces;
@ -23,12 +24,7 @@ public abstract class SessionServiceClientBase : ISessionService
public virtual List<Product> GetHotels() public virtual List<Product> GetHotels()
{ {
if (User != null) return User != null ? User.UserModelDto.Products.Where(x => x.ProductType == ProductType.Hotel).ToList() : [];
{
return User.UserModelDto.Products.Count > 0 ? User.UserModelDto.Products.Where(x => x.ProductType == TIAM.Core.Enums.ProductType.Hotel).ToList() : [];
}
return [];
} }
public virtual void ClearAll() public virtual void ClearAll()

View File

@ -5,6 +5,7 @@ using AyCode.Interfaces.StorageHandlers;
using AyCode.Services.Loggers; using AyCode.Services.Loggers;
using Newtonsoft.Json; using Newtonsoft.Json;
using TIAM.Models.Dtos.Users; using TIAM.Models.Dtos.Users;
using TIAM.Services;
using TIAMWebApp.Shared.Application.Interfaces; using TIAMWebApp.Shared.Application.Interfaces;
using TIAMWebApp.Shared.Application.Models; using TIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Models.ClientSide; using TIAMWebApp.Shared.Application.Models.ClientSide;
@ -17,18 +18,21 @@ public abstract class UserDataServiceClientBase : IUserDataService
{ {
protected readonly HttpClient Http; protected readonly HttpClient Http;
protected readonly LoggerClient Logger; protected readonly LoggerClient Logger;
protected readonly AdminSignalRClient AdminSignalRClient;
protected readonly ISessionService SessionService; protected readonly ISessionService SessionService;
protected readonly ISecureStorageHandler SecureStorageHandler; protected readonly ISecureStorageHandler SecureStorageHandler;
protected readonly IServiceProviderDataService ServiceProviderDataService; protected readonly IServiceProviderDataService ServiceProviderDataService;
protected UserDataServiceClientBase(HttpClient http, ISessionService sessionService, ISecureStorageHandler secureStorageHandler, IServiceProviderDataService serviceProviderDataService, IEnumerable<IAcLogWriterClientBase> logWriters) protected UserDataServiceClientBase(HttpClient http, AdminSignalRClient adminSignalRClient, ISessionService sessionService, ISecureStorageHandler secureStorageHandler, IServiceProviderDataService serviceProviderDataService, IEnumerable<IAcLogWriterClientBase> logWriters)
{ {
Http = http; Http = http;
AdminSignalRClient = adminSignalRClient;
SessionService = sessionService; SessionService = sessionService;
SecureStorageHandler = secureStorageHandler; SecureStorageHandler = secureStorageHandler;
ServiceProviderDataService = serviceProviderDataService; ServiceProviderDataService = serviceProviderDataService;
Logger = new LoggerClient(this.GetType().Name, logWriters.ToArray()); Logger = new LoggerClient(this.GetType().Name, logWriters.ToArray());
} }
@ -71,34 +75,37 @@ public abstract class UserDataServiceClientBase : IUserDataService
return result; return result;
} }
public async Task<string> AuthenticateUser(LoginModel loginModel) public async Task<MainResponse?> AuthenticateUser(LoginModel loginModel)
{ {
var result = string.Empty; Logger.Debug($"AuthenticateUser; email: {loginModel.Email}");
var url = $"{Setting.ApiBaseUrl}/{APIUrls.AuthenticateUser}";
var response = await Http.PostAsJsonAsync(url, loginModel); return await AdminSignalRClient.PostDataAsync<LoginModel, MainResponse>(SignalRTags.AuthenticateUser, loginModel);
//try //var result = string.Empty;
//var url = $"{Setting.ApiBaseUrl}/{APIUrls.AuthenticateUser}";
//var response = await Http.PostAsJsonAsync(url, loginModel);
////try
////{
//// Logger.Detail("Login started: " + "Email: " + loginModel.Email + ", Password: " + loginModel.Password);
////}
////catch (Exception ex)
////{
//// _logger.Error(ex.Message, ex);
////}
//if (response.IsSuccessStatusCode)
//{ //{
// Logger.Detail("Login started: " + "Email: " + loginModel.Email + ", Password: " + loginModel.Password); // result = await response.Content.ReadAsStringAsync();
//} //}
//catch (Exception ex) //else
//{ //{
// _logger.Error(ex.Message, ex); // result = await response.Content.ReadAsStringAsync();
//} //}
if (response.IsSuccessStatusCode) ////result = await response.Content.ReadAsStringAsync();
{ //return result;
result = await response.Content.ReadAsStringAsync();
}
else
{
result = await response.Content.ReadAsStringAsync();
}
//result = await response.Content.ReadAsStringAsync();
return result;
} }
public async Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel) public async Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel)
@ -107,7 +114,7 @@ public abstract class UserDataServiceClientBase : IUserDataService
var result = string.Empty; var result = string.Empty;
var url = $"{Setting.ApiBaseUrl}/{APIUrls.CreateUser}"; var url = $"{Setting.ApiBaseUrl}/{APIUrls.CreateUser}";
Logger.Info("CreateUser url: " + url); Logger.Debug("CreateUser url: " + url);
var response = await Http.PostAsJsonAsync(url, regModel); var response = await Http.PostAsJsonAsync(url, regModel);
result = await response.Content.ReadAsStringAsync(); result = await response.Content.ReadAsStringAsync();
@ -133,7 +140,7 @@ public abstract class UserDataServiceClientBase : IUserDataService
var user = new UserModelDto(); var user = new UserModelDto();
var url = $"{Setting.ApiBaseUrl}/{APIUrls.CreateGuestUser}"; var url = $"{Setting.ApiBaseUrl}/{APIUrls.CreateGuestUser}";
Logger.Info("CreateGuestUser url: " + url); Logger.Debug("CreateGuestUser url: " + url);
var response = await Http.PostAsJsonAsync(url, regModel); var response = await Http.PostAsJsonAsync(url, regModel);
@ -141,7 +148,7 @@ public abstract class UserDataServiceClientBase : IUserDataService
{ {
isSuccess = true; isSuccess = true;
result = await response.Content.ReadAsStringAsync(); result = await response.Content.ReadAsStringAsync();
Logger.Info("CreateGuestUser result: " + result); Logger.Debug("CreateGuestUser result: " + result);
user = JsonConvert.DeserializeObject<UserModelDto>(result); user = JsonConvert.DeserializeObject<UserModelDto>(result);
} }
else else
@ -155,89 +162,107 @@ public abstract class UserDataServiceClientBase : IUserDataService
} }
public async Task<List<UserModelDto>?> GetUsersAsync() public async Task<List<UserModelDto>> GetUsersAsync()
{ {
return await Http.GetFromJsonAsync<List<UserModelDto>>(APIUrls.GetUsers); Logger.Debug($"GetUsersAsync");
return await AdminSignalRClient.GetAllAsync<List<UserModelDto>>(SignalRTags.GetAllUserModelDto) ?? [];
//return await Http.GetFromJsonAsync<List<UserModelDto>>(APIUrls.GetUsers);
} }
public async Task<List<UserModelDtoDetail>> GetUsersWithDetailsAsync() public async Task<List<UserModelDtoDetail>> GetUsersWithDetailsAsync()
{ {
var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUsersWithDetails}"; Logger.Debug($"GetUsersWithDetailsAsync");
Logger.Info("GetUserByEmailAsync url: " + url + "!"); return await AdminSignalRClient.GetAllAsync<List<UserModelDtoDetail>>(SignalRTags.GetAllUserModelDtoDetails) ?? [];
var response = await Http.GetFromJsonAsync<List<UserModelDtoDetail>>(APIUrls.GetUsersWithDetails);
//var result = await response.Content.ReadAsStringAsync(); ////var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUsersWithDetails}";
//var user = JsonConvert.DeserializeObject<UserModelDto>(result);
////Logger.Info("GetUserByEmailAsync url: " + url + "!");
////var response = await Http.GetFromJsonAsync<List<UserModelDtoDetail>>(APIUrls.GetUsersWithDetails);
//////var result = await response.Content.ReadAsStringAsync();
//////var user = JsonConvert.DeserializeObject<UserModelDto>(result);
return response ?? []; ////return response ?? [];
} }
public async Task<UserModelDto?> GetUserByEmailAsync(string email) public async Task<UserModelDto?> GetUserByEmailAsync(string email)
{ {
try Logger.Debug($"GetUserByEmailAsync; email: {email}");
{
var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserByEmail}/{email}";
Logger.Info("GetUserByEmailAsync url: " + url + ", " + email);
var response = await Http.GetAsync(url); return await AdminSignalRClient.GetByIdAsync<UserModelDto>(SignalRTags.GetUserModelDtoByEmail, email);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode) //try
{ //{
var jsonResponse = await response.Content.ReadAsStringAsync(); // var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserByEmail}/{email}";
var user = System.Text.Json.JsonSerializer.Deserialize<UserModelDto>(jsonResponse, new JsonSerializerOptions // Logger.Info("GetUserByEmailAsync url: " + url + ", " + email);
{
PropertyNameCaseInsensitive = true
});
return user;
}
return null; // var response = await Http.GetAsync(url);
} // response.EnsureSuccessStatusCode();
catch (HttpRequestException httpRequestException)
{ // if (response.IsSuccessStatusCode)
// Handle specific HTTP request exceptions // {
Logger.DebugConditional($"Request error: {httpRequestException.Message}"); // var jsonResponse = await response.Content.ReadAsStringAsync();
throw; // var user = System.Text.Json.JsonSerializer.Deserialize<UserModelDto>(jsonResponse, new JsonSerializerOptions
} // {
catch (Exception ex) // PropertyNameCaseInsensitive = true
{ // });
// Handle other possible exceptions // return user;
Logger.DebugConditional($"An error occurred: {ex.Message}"); // }
throw;
} // return null;
//}
//catch (HttpRequestException httpRequestException)
//{
// // Handle specific HTTP request exceptions
// Logger.DebugConditional($"Request error: {httpRequestException.Message}");
// throw;
//}
//catch (Exception ex)
//{
// // Handle other possible exceptions
// Logger.DebugConditional($"An error occurred: {ex.Message}");
// throw;
//}
} }
public async Task<UserModelDto?> GetUserByIdAsync(Guid id) public async Task<UserModelDto?> GetUserByIdAsync(Guid id)
{ {
var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserById}"; Logger.Debug($"GetUserByIdAsync; id: {id}");
Logger.Info("GetUserByIdAsync url: " + url + ", " + id.ToString());
var response = await Http.PostAsJsonAsync(url, id); return await AdminSignalRClient.GetByIdAsync<UserModelDto>(SignalRTags.GetUserModelDtoById, id);
var result = await response.Content.ReadAsStringAsync();
var user = JsonConvert.DeserializeObject<UserModelDto>(result);
return user; //var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserById}";
//Logger.Debug("GetUserByIdAsync url: " + url + ", " + id.ToString());
//var response = await Http.PostAsJsonAsync(url, id);
//var result = await response.Content.ReadAsStringAsync();
//var user = JsonConvert.DeserializeObject<UserModelDto>(result);
//return user;
} }
public async Task<UserModelDtoDetail?> GetUserDetailByIdAsync(Guid id) public async Task<UserModelDtoDetail?> GetUserDetailByIdAsync(Guid id)
{ {
Logger.Info("GetUserDetailByIdAsync", "GLOBAL_LOGGER"); Logger.Debug($"GetUserDetailByIdAsync; id: {id}");
var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserDetailById}"; return await AdminSignalRClient.GetByIdAsync<UserModelDtoDetail>(SignalRTags.GetUserModelDtoDetailById, id);
Logger.Info("GetUserDetailByIdAsync url: " + url + ", " + id.ToString());
var response = await Http.PostAsJsonAsync(url, id); //var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetUserDetailById}";
//var result = await response.Content.ReadAsStringAsync(); //Logger.Info("GetUserDetailByIdAsync url: " + url + ", " + id.ToString());
var result = await response.Content.ReadFromJsonAsync<UserModelDtoDetail>();
//var user = JsonConvert.DeserializeObject<UserModelDtoDetail>(result);
return result; //var response = await Http.PostAsJsonAsync(url, id);
////var result = await response.Content.ReadAsStringAsync();
//var result = await response.Content.ReadFromJsonAsync<UserModelDtoDetail>();
////var user = JsonConvert.DeserializeObject<UserModelDtoDetail>(result);
//return result;
} }
public async Task<bool> RefreshToken() public async Task<bool> RefreshToken()
{ {
Logger.Info("RefreshToken() called"); Logger.Debug("RefreshToken() called");
var isTokenRefreshed = false; var isTokenRefreshed = false;
var url = $"{Setting.ApiBaseUrl}/{APIUrls.RefreshToken}"; var url = $"{Setting.ApiBaseUrl}/{APIUrls.RefreshToken}";
@ -251,7 +276,7 @@ public abstract class UserDataServiceClientBase : IUserDataService
try try
{ {
Logger.Info("Refreshtoken url: " + url); Logger.Debug("Refreshtoken url: " + url);
var response = await Http.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json")); var response = await Http.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {

View File

@ -8,32 +8,24 @@ namespace TIAMWebApp.Shared.Application.Utility
{ {
public class PageHistoryState public class PageHistoryState
{ {
private List<string> previousPages; private readonly List<string> _previousPages = [];
public PageHistoryState() public PageHistoryState()
{ }
public void AddPageToHistory(string pageUrl)
{ {
previousPages = new List<string>(); _previousPages.Add(pageUrl);
}
public void AddPageToHistory(string pageName)
{
previousPages.Add(pageName);
} }
public string GetGoBackPage() public string GetGoBackPage()
{ {
if (previousPages.Count > 1) return _previousPages.Count > 1 ? _previousPages[^2] : _previousPages.FirstOrDefault() ?? string.Empty;
{
// You add a page on initialization, so you need to return the 2nd from the last
return previousPages.ElementAt(previousPages.Count - 2);
}
// Can't go back because you didn't navigate enough
return previousPages.FirstOrDefault();
} }
public bool CanGoBack() public bool CanGoBack()
{ {
return previousPages.Count > 1; return _previousPages.Count > 1;
} }
} }
} }