LockService, RequestId, ConnectionId, BidButtonDisabled; improvements, fixes, etc...

This commit is contained in:
Loretta 2024-12-12 08:55:37 +01:00
parent 8a7a8d5722
commit a58cf9ce9b
9 changed files with 169 additions and 92 deletions

View File

@ -1,4 +1,5 @@
using AyCode.Core.Extensions;
using AyCode.Utils.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Nop.Core;
@ -16,54 +17,62 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Components
{
[ViewComponent(Name = "LiveAnnouncement")]
public class LiveAnnouncementViewComponent(ILogger logger, IWorkContext workContext, IWidgetPluginManager widgetPluginManager, AuctionService auctionService, IHubContext<AuctionHub> auctionHubContext)
public class LiveAnnouncementViewComponent(ILogger logger, ILockService lockService, IWorkContext workContext, IWidgetPluginManager widgetPluginManager, AuctionService auctionService, IHubContext<AuctionHub> auctionHubContext)
: NopViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string widgetZone, object additionalData)
{
//await logger.InformationAsync("LiveAnnouncementViewComponent.InvokeAsync called");
var customer = await workContext.GetCurrentCustomerAsync();
//lock... - J.
var auctions = await auctionService.GetAllCurrentAutoOpenAndClosedAuctionsAsync();
if (auctions.Count > 0)
await logger.InformationAsync($"LiveAnnouncementViewComponent.InvokeAsync(); Before lock; widgetZone: {widgetZone}", null, customer);
using (await lockService.SemaphoreSlim.UseWaitAsync())
{
await logger.InformationAsync($"LiveAnnouncementViewComponent.InvokeAsync auctions.Count > 0; count: {auctions.Count}; names: {string.Join("; ", auctions.Select(x => x.AuctionName))}");
await logger.InformationAsync($"LiveAnnouncementViewComponent.InvokeAsync(); Enter lock; widgetZone: {widgetZone}", null, customer);
var statusChangedMessageWrapper = new MessageWrapper
await Task.Delay(1000);
var auctions = await auctionService.GetAllCurrentAutoOpenAndClosedAuctionsAsync();
if (auctions.Count > 0)
{
MessageType = nameof(ProductToAuctionStatusNotification),
SenderId = 0,
ResponseType = ResponseType.ToAllClients
};
await logger.InformationAsync($"LiveAnnouncementViewComponent.InvokeAsync(); auctions.Count > 0; count: {auctions.Count}; names: {string.Join("; ", auctions.Select(x => x.AuctionName))}");
foreach (var auction in auctions)
{
auction.Closed = false;
await auctionService.UpdateAuctionAsync(auction);
var auctionDto = new AuctionDto(auction);
var productToAuctions = (await auctionService.GetProductToAuctionsByAuctionIdAsync(auction.Id, false)).Where(x => x.AuctionStatus == AuctionStatus.None).ToList();
foreach (var productToAuction in productToAuctions)
var statusChangedMessageWrapper = new MessageWrapper
{
productToAuction.AuctionStatus = AuctionStatus.Active;
auctionDto.ProductToAuctionDtos.Add(new ProductToAuctionDto(productToAuction));
MessageType = nameof(ProductToAuctionStatusNotification),
SenderId = 0,
ResponseType = ResponseType.ToAllClients
};
////TEMPOPRARY - J.
//statusChangedMessageWrapper.Data = new ProductToAuctionStatusNotification(auctionDto, 0, $"Az aukciót megnyitottuk: {auction.AuctionName}").ToJson();
//await _auctionHubContext.Clients.All.SendAsync("send", statusChangedMessageWrapper.ToJson());
////TEMPOPRARY - J.
foreach (var auction in auctions)
{
auction.Closed = false;
await auctionService.UpdateAuctionAsync(auction);
var auctionDto = new AuctionDto(auction);
var productToAuctions = (await auctionService.GetProductToAuctionsByAuctionIdAsync(auction.Id, false)).Where(x => x.AuctionStatus == AuctionStatus.None).ToList();
foreach (var productToAuction in productToAuctions)
{
productToAuction.AuctionStatus = AuctionStatus.Active;
auctionDto.ProductToAuctionDtos.Add(new ProductToAuctionDto(productToAuction));
////TEMPOPRARY - J.
//statusChangedMessageWrapper.Data = new ProductToAuctionStatusNotification(auctionDto, 0, $"Az aukciót megnyitottuk: {auction.AuctionName}").ToJson();
//await _auctionHubContext.Clients.All.SendAsync("send", statusChangedMessageWrapper.ToJson());
////TEMPOPRARY - J.
}
await auctionService.UpdateProductToAuctionMappingAsync(productToAuctions);
statusChangedMessageWrapper.Data = new ProductToAuctionStatusNotification(auctionDto, 0, $"Az aukciót megnyitottuk: {auction.AuctionName}").ToJson();
await auctionHubContext.Clients.All.SendAsync("send", statusChangedMessageWrapper.ToJson());
}
await auctionService.UpdateProductToAuctionMappingAsync(productToAuctions);
statusChangedMessageWrapper.Data = new ProductToAuctionStatusNotification(auctionDto, 0, $"Az aukciót megnyitottuk: {auction.AuctionName}").ToJson();
await auctionHubContext.Clients.All.SendAsync("send", statusChangedMessageWrapper.ToJson());
}
await logger.InformationAsync($"LiveAnnouncementViewComponent.InvokeAsync(); Exit lock; widgetZone: {widgetZone}", null, customer);
}
//ensure that what3words widget is active and enabled
var customer = await workContext.GetCurrentCustomerAsync();
await logger.InformationAsync($"SignalR Widget called customer: {customer.Email}");
if (!await widgetPluginManager.IsPluginActiveAsync(AuctionDefaults.SystemName, customer))

View File

@ -2,6 +2,7 @@
console.log("signalRJs Starts");
window.RequestCount = 0;
window.ConnectionId = "";
// AuctionStatus Enum
window.AuctionStatus = Object.freeze({
@ -32,8 +33,13 @@
.withKeepAliveInterval(600000)
.build();
connection.on("send", data => {
MessageHandler.handle(data);
connection.on("send", messageWrapper => {
MessageHandler.handle(messageWrapper);
});
connection.on("OnConnected", connId => {
window.ConnectionId = connId;
console.log("SignalR connected! connectionId: " + window.ConnectionId);
});
function start() {
@ -49,16 +55,21 @@
start();
});
window.getRequestId = function() {
return window.ConnectionId + window.RequestCount;
}
// Global function to send a message to the server
window.sendMessageToServer = function (messageType, senderId, data) {
window.sendMessageToServer = function (messageType, senderId, messageWrapperData) {
window.RequestCount++;
var messageWrapper = {
MessageType: messageType,
SenderId: senderId,
RequestCount: window.RequestCount,
Data: data
};
var messageWrapper = {
MessageType: messageType,
SenderId: senderId,
RequestCount: window.RequestCount,
RequestId: getRequestId(),
Data: messageWrapperData
};
console.log("Before send message to the server! " + messageType);

View File

@ -47,7 +47,7 @@
if (publicProductBidBox) {
//var audio = new Audio('../Plugins/Misc.AuctionPlugin/Content/ding.mp3');
//audio.play();
refreshPublicBidBox(bidNotification);
refreshPublicBidBox(bidNotification, messageWrapper.RequestId == getRequestId());
}
if (publicInfo) {
var functionName = "refreshPublicInfo" + productToAuctionDto.productId;

View File

@ -18,10 +18,11 @@ using DocumentFormat.OpenXml.Spreadsheet;
namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
{
public class AuctionHub(SessionService sessionService, ILogger logger, IProductService productService, AuctionService auctionService, IWorkContext workContext, ICustomerService customerService, ICategoryService categoryService)
public class AuctionHub(SessionService sessionService, ILockService lockService, ILogger logger, IProductService productService, AuctionService auctionService, IWorkContext workContext, ICustomerService customerService, ICategoryService categoryService)
: Hub<IAuctionHubClient>
{
private readonly SemaphoreSlim _handleMessageMutex = new(1);
//private static readonly SemaphoreSlim _handleMessageMutex = new(1);
//private readonly Semaphore _handleMessageMutex = new(1, 1, "Nop.Plugin.Misc.AuctionPlugin.Hubs.AuctionHub");
public override async Task OnConnectedAsync()
{
@ -48,6 +49,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
}
await base.OnConnectedAsync();
await Clients.Caller.OnConnected(connectionId);
}
public override Task OnDisconnectedAsync(Exception exception)
@ -90,12 +92,15 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
await logger.InformationAsync($"AuctionHub.HandleMessageAsync(); Before lock; MessageType: {messageWrapper.MessageType}; connectionId: {connectionId}; jsonData: {messageWrapper.Data}", null, customer);
//TODO: az összes request-et egy base-ből származtatni és beletenni az AuctionRequestMode-ot! - J.
using (await _handleMessageMutex.UseWaitAsync())
//using (await _handleMessageMutex.WaitOne())
using (await lockService.SemaphoreSlim.UseWaitAsync())
{
try
{
await logger.InformationAsync($"AuctionHub.HandleMessageAsync(); Enter lock; MessageType: {messageWrapper.MessageType}; connectionId: {connectionId}", null, customer);
await Task.Delay(3000);
if (messageWrapper.MessageType == "BidRequestMessage") return await HandleBidRequestAsync(customer, messageWrapper);
else
{

View File

@ -9,6 +9,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
public interface IAuctionHubClient
{
Task send(string message);
Task OnConnected(string connectionId);
Task ReceiveMessageFromClient(string message);
Task SendPrice(string price);
}

View File

@ -1,5 +1,6 @@
using AyCode.Core.Extensions;
using Mango.Nop.Core;
using Mango.Nop.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Razor;
@ -43,6 +44,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Infrastructure
options.ViewLocationExpanders.Add(new ViewLocationExpander());
});
services.AddSingleton<ILockService, LockService>();
services.AddSingleton<SessionService>();
services.AddSignalR(hubOptions =>
{

View File

@ -0,0 +1,5 @@
using Mango.Nop.Services;
namespace Nop.Plugin.Misc.AuctionPlugin.Services;
public interface ILockService : IMgLockService{}

View File

@ -0,0 +1,14 @@
using Mango.Nop.Services;
namespace Nop.Plugin.Misc.AuctionPlugin.Services;
public class LockService : MgLockService, ILockService
{
public LockService() : this(new SemaphoreSlim(1))
{}
public LockService(SemaphoreSlim semaphoreSlim) : base(semaphoreSlim)
{
}
}

View File

@ -216,7 +216,7 @@
$("#signalRBidButton").on("click", function () {
document.getElementById("signalRBidButton").disabled = true;
setBidButtonDisabledById("signalRBidButton", true);
event.preventDefault();
if (!bidBoxPageViewModel) {
@ -295,7 +295,7 @@
}
var revertMessage = {
ProductToAuctionId: bidBoxPageViewModel.ProductToAuctionId,
ProductToAuctionId: bidBoxPageViewModel.ProductToAuctionId
};
var content = JSON.stringify(revertMessage);
@ -313,7 +313,7 @@
return false;
});
//var status = bidBoxPageViewModel.auctionDto.productToAuctionDtos[0].auctionStatus;
//var status = bidBoxPageViewModel.productToAuctionDto.auctionStatus;
//setButtons(status);
});
@ -342,23 +342,50 @@
sendMessageToServer("RevertAuctionBidRequest", bidBoxPageViewModel.ProductToAuctionId);
}
function setBidButtonDisabledById(bidButtonElementId, disabled, updateDisabledState = true) {
if (!updateDisabledState) return;
function refreshPublicBidBox(data) {
setBidButtonDisabled(document.getElementById(bidButtonElementId), disabled, updateDisabledState);
}
function setBidButtonDisabled(bidButtonElement, disabled, updateDisabledState = true) {
if (!updateDisabledState) return;
setElementDisabled(bidButtonElement, disabled, updateDisabledState);
}
function setElementDisabledById(domElementId, disabled) {
setElementDisabled(document.getElementById(domElementId), disabled);
}
function setElementDisabled(domElement, disabled) {
if (!domElement)
return;
domElement.disabled = disabled;
}
function refreshPublicBidBox(bidNotification, updateBidButtonDisabledState) {
//TODO: is it for me?
// if () {
// data.AuctionDto.
// bidNotification.AuctionDto.
// }
//TODO: KINYOMOZNI! valamiért mindig false a updateBidButtonDisabledState és emiatt nem állítja a button disabled-eket... - J.
updateBidButtonDisabledState = true;
var widgetPriceElement = document.getElementById("price-value-" + bidBoxPageViewModel.ProductId);
var currency = bidBoxPageViewModel.WorkingCurrency;
console.log(currency);
var bidButtonElement = document.getElementById("signalRBidButton");
var licitStepElement = document.getElementById("licitStepText");
var bidBox = document.getElementById("publicProductBidBox");
var bidBoxTitle = document.getElementById("bidBoxTitle");
console.log(data);
console.log(bidNotification);
let auctionDto = data.auctionDto;
let auctionDto = bidNotification.auctionDto;
let productToAuction = auctionDto.productToAuctionDtos[0];
var productAuctionMappingId = productToAuction.id;
var winnerId = productToAuction.winnerCustomerId;
@ -369,14 +396,15 @@
}
console.log(productAuctionMappingId);
console.log("ProductToAuctionId: " + productAuctionMappingId);
//TODO: TESZT STATUS!!! - JTEST.
var status = data.auctionDto.productToAuctionDtos[0].auctionStatus;
var status = productToAuction.auctionStatus;
//var status = AuctionStatus.TEST;
//if (status == AuctionStatus.FirstWarning) {
setButtons(status);
if (updateBidButtonDisabledState)
setButtons(status);
//}
// if (productAuctionMappingId == bidBoxPageViewModel.ProductToAuctionId) {
@ -388,15 +416,16 @@
if (productAuctionMappingId == bidBoxPageViewModel.ProductToAuctionId) {
console.log("THIS IS FOR US! SORRY FOR SHOUTING");
if(bidBoxPageViewModel.WorkingCurrency.CurrencyCode == "EUR") {
widgetPriceElement.textContent = EURFormatter.format(data.currentPrice * bidBoxPageViewModel.WorkingCurrency.Rate); // Update the price
licitStepElement.textContent = EURFormatter.format(data.nextStepAmount * bidBoxPageViewModel.WorkingCurrency.Rate);
widgetPriceElement.textContent = EURFormatter.format(bidNotification.currentPrice * bidBoxPageViewModel.WorkingCurrency.Rate); // Update the price
licitStepElement.textContent = EURFormatter.format(bidNotification.nextStepAmount * bidBoxPageViewModel.WorkingCurrency.Rate);
}
else {
widgetPriceElement.textContent = HUFFormatter.format(data.currentPrice); // Update the price
licitStepElement.textContent = HUFFormatter.format(data.nextStepAmount);
widgetPriceElement.textContent = HUFFormatter.format(bidNotification.currentPrice); // Update the price
licitStepElement.textContent = HUFFormatter.format(bidNotification.nextStepAmount);
}
bidBoxPageViewModel.NextBidPrice = Number(data.nextBidPrice);
bidButtonElement.disabled = false;
bidBoxPageViewModel.NextBidPrice = Number(bidNotification.nextBidPrice);
setBidButtonDisabled(bidButtonElement, false, updateBidButtonDisabledState);
var list;
if (isMyBid) {
console.log("This is my bid");
@ -404,33 +433,30 @@
list.add("bg-success");
list.remove("bg-primary");
bidButtonElement.textContent = "@(T("Plugins.Misc.AuctionPlugin.GoodJob"))";
bidBoxTitle.textContent = productToAuction.auctionStatus == AuctionStatus.Sold ? "@(T("Plugins.Misc.AuctionPlugin.YouWin"))" : "@(T("Plugins.Misc.AuctionPlugin.YourBidLeading"))";
if (bidBoxPageViewModel.IsAdmin) {
console.log("I AM WEASEL!!! " + bidBoxPageViewModel.IsAdmin);
bidButtonElement.disabled = false;
}
else {
console.log("I AM NOT WEASEL!!! " + bidBoxPageViewModel.IsAdmin);
bidButtonElement.disabled = true;
}
bidBoxTitle.textContent = productToAuction.auctionStatus == AuctionStatus.Sold ? "@(T("Plugins.Misc.AuctionPlugin.YouWin"))" : "@(T("Plugins.Misc.AuctionPlugin.YourBidLeading"))";
if (bidBoxPageViewModel.IsAdmin) {
console.log("I AM WEASEL!!! " + bidBoxPageViewModel.IsAdmin);
setBidButtonDisabled(bidButtonElement, false, updateBidButtonDisabledState);
} else {
console.log("I AM NOT WEASEL!!! " + bidBoxPageViewModel.IsAdmin);
setBidButtonDisabled(bidButtonElement, true, updateBidButtonDisabledState);
}
else {
list = bidBox.classList;
list.add("bg-primary");
list.remove("bg-success");
bidBoxTitle.textContent = productToAuction.auctionStatus == AuctionStatus.Sold ? "@(T("Plugins.Misc.AuctionPlugin.Sold"))" : "@(T("Plugins.Misc.AuctionPlugin.PlaceABid"))";
if(bidBoxPageViewModel.WorkingCurrency.CurrencyCode == "EUR") {
bidButtonElement.textContent = "@(T("Plugins.Misc.AuctionPlugin.BidButtonPrefix")) " + EURFormatter.format(bidBoxPageViewModel.NextBidPriceInWorkingCurrency);
}
else {
bidButtonElement.textContent = "@(T("Plugins.Misc.AuctionPlugin.BidButtonPrefix")) " + HUFFormatter.format(bidBoxPageViewModel.NextBidPrice);
} else {
list = bidBox.classList;
list.add("bg-primary");
list.remove("bg-success");
bidBoxTitle.textContent = productToAuction.auctionStatus == AuctionStatus.Sold ? "@(T("Plugins.Misc.AuctionPlugin.Sold"))" : "@(T("Plugins.Misc.AuctionPlugin.PlaceABid"))";
if (bidBoxPageViewModel.WorkingCurrency.CurrencyCode == "EUR") {
bidButtonElement.textContent = "@(T("Plugins.Misc.AuctionPlugin.BidButtonPrefix")) " + EURFormatter.format(bidBoxPageViewModel.NextBidPriceInWorkingCurrency);
} else {
bidButtonElement.textContent = "@(T("Plugins.Misc.AuctionPlugin.BidButtonPrefix")) " + HUFFormatter.format(bidBoxPageViewModel.NextBidPrice);
}
}
console.log(`WidgetPrice updated to: ${data.currentPrice}, next bid is ${bidBoxPageViewModel.NextBidPrice}`);
console.log(`WidgetPrice updated to: ${bidNotification.currentPrice}, next bid is ${bidBoxPageViewModel.NextBidPrice}`);
//bidButtonElement.disabled = false;
}
@ -445,17 +471,21 @@
}
}
function handleAuctionUpdate(data) {
function handleAuctionUpdate(auctionStatusNotification) {
var widgetPriceElement = document.getElementById("price-value-" + bidBoxPageViewModel.ProductId);
var bidButtonElement = document.getElementById("signalRBidButton");
var licitStepElement = document.getElementById("licitStepText");
var bidBoxTitle = document.getElementById("bidBoxTitle");
var productAuctionMappingId = data.auctionDto.productToAuctionDtos[0].id;
var auctionDto = auctionStatusNotification.auctionDto;
var productToAuctionDto = auctionDto.productToAuctionDtos[0];
var productAuctionMappingId = productToAuctionDto.id;
let isMyBid = false;
//TODO: TESZT STATUS!!! - JTEST.
let itemStatus = data.auctionDto.productToAuctionDtos[0].auctionStatus;
let itemStatus = productToAuctionDto.auctionStatus;
//var itemStatus = AuctionStatus.TEST;
let winnerId = data.auctionDto.productToAuctionDtos[0].winnerCustomerId;
let winnerId = productToAuctionDto.winnerCustomerId;
if (winnerId == bidBoxPageViewModel.CustomerId) {
isMyBid = true;
@ -471,15 +501,15 @@
location.reload();
// bidBoxTitle.textContent = "@(T("Plugins.Misc.AuctionPlugin.AuctionNotStarted"))";
// bidBoxPageViewModel.NextBidPrice = Number(data.nextBidPrice);
// bidBoxPageViewModel.NextBidPrice = Number(auctionStatusNotification.nextBidPrice);
// if(bidBoxPageViewModel.WorkingCurrency.CurrencyCode == "EUR") {
// widgetPriceElement.textContent = EURFormatter.format(data.currentPrice * bidBoxPageViewModel.WorkingCurrency.Rate); // Update the price
// licitStepElement.textContent = EURFormatter.format(data.nextStepAmount * bidBoxPageViewModel.WorkingCurrency.Rate);
// widgetPriceElement.textContent = EURFormatter.format(auctionStatusNotification.currentPrice * bidBoxPageViewModel.WorkingCurrency.Rate); // Update the price
// licitStepElement.textContent = EURFormatter.format(auctionStatusNotification.nextStepAmount * bidBoxPageViewModel.WorkingCurrency.Rate);
// }
// else {
// widgetPriceElement.textContent = HUFFormatter.format(data.currentPrice); // Update the price
// licitStepElement.textContent = HUFFormatter.format(data.nextStepAmount);
// widgetPriceElement.textContent = HUFFormatter.format(auctionStatusNotification.currentPrice); // Update the price
// licitStepElement.textContent = HUFFormatter.format(auctionStatusNotification.nextStepAmount);
// }
break;
@ -523,7 +553,7 @@
setButtons(itemStatus);
console.log(`WidgetPrice updated to: ${data.currentPrice}, next bid is ${bidBoxPageViewModel.NextBidPrice}`);
console.log(`WidgetPrice updated to: ${auctionStatusNotification.currentPrice}, next bid is ${bidBoxPageViewModel.NextBidPrice}`);
}