improvements, fixes, etc..

This commit is contained in:
Loretta 2024-12-06 16:10:18 +01:00
parent fa07f23d70
commit edaef40fb7
4 changed files with 294 additions and 224 deletions

View File

@ -1,13 +1,15 @@
var MessageHandler = (function () { var MessageHandler = (function() {
// Handlers for each message type // Handlers for each message type
var animation = "slideDown"; var animation = "slideDown";
var handlers = { var handlers = {
announcement: function (data) { announcement: function(messageWrapper) {
var myObject = JSON.parse(data); var announcementNotification = JSON.parse(messageWrapper.data);
var liveScreen = document.getElementById("auctionProductLiveScreenBox"); var liveScreen = document.getElementById("auctionProductLiveScreenBox");
if (!liveScreen) { if (!liveScreen && !messageWrapper.hideToaster) {
toastr.info(`<div class="item announcemantToast">${myObject.message}</div>`, myObject.title, { toastr.info(`<div class="item announcemantToast">${announcementNotification.message}</div>`,
announcementNotification.title,
{
"closeButton": true, "closeButton": true,
"positionClass": "toast-bottom-left", "positionClass": "toast-bottom-left",
"newestOnTop": true, "newestOnTop": true,
@ -25,16 +27,14 @@
}); });
$('.toast-info').css("background-color", "#008080"); $('.toast-info').css("background-color", "#008080");
} }
}, },
bidNotification: function (data) {
bidNotification: function(messageWrapper) {
var bidNotification = JSON.parse(messageWrapper.data);
console.log(data); console.log(bidNotification);
var myObject = JSON.parse(data);
console.log(myObject);
var auctionDto = myObject.auctionDto; var auctionDto = bidNotification.auctionDto;
var productToAuctionDto = auctionDto.productToAuctionDtos[0]; var productToAuctionDto = auctionDto.productToAuctionDtos[0];
//var productAuctionMappingId = productToAuctionDto.id; //var productAuctionMappingId = productToAuctionDto.id;
@ -44,23 +44,24 @@
var liveScreen = document.getElementById("auctionProductLiveScreenBox"); var liveScreen = document.getElementById("auctionProductLiveScreenBox");
var publicInfo = document.getElementById("publicInfoOverlay" + productToAuctionDto.productId); var publicInfo = document.getElementById("publicInfoOverlay" + productToAuctionDto.productId);
if (publicProductBidBox) if (publicProductBidBox) {
{
//var audio = new Audio('../Plugins/Misc.AuctionPlugin/Content/ding.mp3'); //var audio = new Audio('../Plugins/Misc.AuctionPlugin/Content/ding.mp3');
//audio.play(); //audio.play();
refreshPublicBidBox(myObject); refreshPublicBidBox(bidNotification);
} }
if (publicInfo) { if (publicInfo) {
var functionName = "refreshPublicInfo" + productToAuctionDto.productId; var functionName = "refreshPublicInfo" + productToAuctionDto.productId;
window[functionName](auctionDto); window[functionName](auctionDto);
} }
if (liveScreen) if (liveScreen) {
{
updateOnBid(myObject); updateOnBid(bidNotification);
} } else if (!messageWrapper.hideToaster) {
else { toastr.success(
toastr.success(`<div class="item bidToast"><p>${myObject.currentPrice}</p><p>${myObject.productName}</p></div>`, "New bid arrived", { `<div class="item bidToast"><p>${bidNotification.currentPrice}</p><p>${bidNotification.productName
}</p></div>`,
"New bid arrived",
{
"closeButton": true, "closeButton": true,
"positionClass": "toast-bottom-left", "positionClass": "toast-bottom-left",
"newestOnTop": true, "newestOnTop": true,
@ -79,20 +80,21 @@
$('.toast-success').css("background-color", "#4caf50"); $('.toast-success').css("background-color", "#4caf50");
} }
}, },
ProductToAuctionStatusNotification: function (data) {
console.log(data);
var myObject = JSON.parse(data); ProductToAuctionStatusNotification: function(messageWrapper) {
var auctionDto = myObject.auctionDto; var auctionStatusNotification = JSON.parse(messageWrapper.data);
var auctionDto = auctionStatusNotification.auctionDto;
var productToAuctionDto = auctionDto.productToAuctionDtos[0]; var productToAuctionDto = auctionDto.productToAuctionDtos[0];
var publicProductBidBox = document.getElementById("publicProductBidBox"); var publicProductBidBox = document.getElementById("publicProductBidBox");
var liveScreen = document.getElementById("auctionProductLiveScreenBox"); var liveScreen = document.getElementById("auctionProductLiveScreenBox");
var publicInfo = document.getElementById("publicInfoOverlay" + productToAuctionDto.productId); var publicInfo = document.getElementById("publicInfoOverlay" + productToAuctionDto.productId);
if (!liveScreen) { if (!liveScreen && !messageWrapper.hideToaster) {
var messageTitle = ""; var messageTitle = "";
var messageText = ""; var messageText = "";
var messageColor = ""; var messageColor = "";
switch (productToAuctionDto.auctionStatus) { switch (productToAuctionDto.auctionStatus) {
case AuctionStatus.None: case AuctionStatus.None:
messageTitle = `Item reset`; messageTitle = `Item reset`;
@ -133,8 +135,9 @@
break; break;
} }
toastr.success(`<div class="item bidToast"><p>${messageText}</p></div>`,
toastr.success(`<div class="item bidToast"><p>${messageText}</p></div>`, messageTitle, { messageTitle,
{
"closeButton": true, "closeButton": true,
"positionClass": "toast-bottom-left", "positionClass": "toast-bottom-left",
"newestOnTop": true, "newestOnTop": true,
@ -152,12 +155,15 @@
}); });
$('.toast-success').css("background-color", messageColor); $('.toast-success').css("background-color", messageColor);
} }
if (publicProductBidBox) { if (publicProductBidBox) {
handleAuctionUpdate(myObject); handleAuctionUpdate(auctionStatusNotification);
} }
if (liveScreen) { if (liveScreen) {
reloadOnUpdate(); reloadOnUpdate();
} }
if (publicInfo) { if (publicInfo) {
var functionName = "refreshPublicInfo" + productToAuctionDto.productId; var functionName = "refreshPublicInfo" + productToAuctionDto.productId;
window[functionName](auctionDto); window[functionName](auctionDto);
@ -169,9 +175,16 @@
// refreshPublicBidBox(myObject); // refreshPublicBidBox(myObject);
// } // }
}, },
//openItemMessage: function (data) {
// var myObject = JSON.parse(data); //openItemMessage: function(messageWrapper) {
// toastr.success(`<div class="item bidToast"><p>${myObject.nextBidPrice}</p><p>${myObject.productName}</p></div>`, "Item auction is OPENED!", { // var openItemNotification = JSON.parse(messageWrapper.data);
// if (!messageWrapper.hideToaster) {
// toastr.success(
// `<div class="item bidToast"><p>${openItemNotification.nextBidPrice}</p><p>${openItemNotification
// .productName}</p></div>`,
// "Item auction is OPENED!",
// {
// "closeButton": true, // "closeButton": true,
// "positionClass": "toast-top-right", // "positionClass": "toast-top-right",
// "newestOnTop": true, // "newestOnTop": true,
@ -188,33 +201,37 @@
// "hideMethod": "fadeOut" // "hideMethod": "fadeOut"
// }); // });
// $('.toast-success').css("background-color", "#4caf50"); // $('.toast-success').css("background-color", "#4caf50");
// }
// var publicProductBidBox = document.getElementById("publicProductBidBox"); // var publicProductBidBox = document.getElementById("publicProductBidBox");
// if (publicProductBidBox) { // if (publicProductBidBox) {
// refreshPublicBidBox(myObject); // refreshPublicBidBox(openItemNotification);
// } // }
//}, //},
// Add more handlers as needed // Add more handlers as needed
default: function (data) { default: function(messageWrapperJson) {
console.warn("Unhandled message type:", data); console.warn("Unhandled message type:", messageWrapperJson);
} }
}; };
// Message router to route to the appropriate handler based on message type // Message router to route to the appropriate handler based on message type
function messageRouter(message) { function messageRouter(messageWrapperJson) {
// Parse the JSON message // Parse the JSON message
try { try {
var parsedMessage = JSON.parse(message); console.log(messageWrapperJson);
var messageType = parsedMessage.messageType;
var senderId = parsedMessage.senderId; var messageWrapper = JSON.parse(messageWrapperJson);
var messageData = parsedMessage.data; var messageType = messageWrapper.messageType;
console.log("Message type:" + messageType); //var senderId = messageWrapper.senderId;
console.log("Message sender:" + senderId);
console.log("Message content" + parsedMessage.data); //console.log("Message type:" + messageType);
//console.log("Message sender:" + senderId);
//console.log("Message hideToaster:" + messageWrapper.hideToaster);
//console.log("Message content" + messageWrapper.data);
// Route to appropriate handler, default if no match // Route to appropriate handler, default if no match
(handlers[messageType] || handlers.default)(messageData); (handlers[messageType] || handlers.default)(messageWrapper);
} catch (e) { } catch (e) {
console.error("Error parsing message:", e); console.error("Error parsing message:", e);
} }

View File

@ -1,9 +1,11 @@
using AyCode.Core.Extensions; using System.Text.Json.Nodes;
using AyCode.Core.Extensions;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Nop.Services.Logging; using Nop.Services.Logging;
using Nop.Plugin.Misc.AuctionPlugin.Hubs.Messages; using Nop.Plugin.Misc.AuctionPlugin.Hubs.Messages;
using Nop.Plugin.Misc.AuctionPlugin.Services; using Nop.Plugin.Misc.AuctionPlugin.Services;
using AyCode.Utils.Extensions; using AyCode.Utils.Extensions;
using Newtonsoft.Json;
using Nop.Services.Customers; using Nop.Services.Customers;
using Nop.Core; using Nop.Core;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Enums; using Nop.Plugin.Misc.AuctionPlugin.Domains.Enums;
@ -11,10 +13,10 @@ using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers; using Nop.Core.Domain.Customers;
using Nop.Services.Catalog; using Nop.Services.Catalog;
using Newtonsoft.Json.Linq;
namespace Nop.Plugin.Misc.AuctionPlugin.Hubs 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, ILogger logger, IProductService productService, AuctionService auctionService, IWorkContext workContext, ICustomerService customerService, ICategoryService categoryService)
: Hub<IAuctionHubClient> : Hub<IAuctionHubClient>
{ {
@ -166,7 +168,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
else else
{ {
productToAuction.BidsCount = await auctionService.GetBidsCountByProductToAuctionIdAsync(productToAuction.Id); productToAuction.BidsCount = await auctionService.GetBidsCountByProductToAuctionIdAsync(productToAuction.Id);
await SetAuctionBidPrice(revertLastBid.BidPrice, productToAuction, product, revertLastBid.CustomerId); await SetAuctionBidPriceAsync(revertLastBid.BidPrice, productToAuction, product, revertLastBid.CustomerId);
} }
await SendAuctionBidMessageAsync(messageWrapper, productToAuction, product, customer.Id, ResponseType.ToAllClients); await SendAuctionBidMessageAsync(messageWrapper, productToAuction, product, customer.Id, ResponseType.ToAllClients);
@ -216,7 +218,13 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
return ResponseType.Error; return ResponseType.Error;
} }
if (!IsValidBidPrice(activeProductAuction.CurrentPrice, bidRequestMessage.BidPrice, activeProductAuction.BidsCount > 0, customer)) if (!await IsValidProductPricesAndSyncIfNeedAsync(activeProductAuction, product, customer))
{
await SendAuctionBidMessageAsync(messageWrapper, activeProductAuction, product, customer.Id, ResponseType.ToAllClients);
return ResponseType.Error;
}
if (!IsValidBidPrice(activeProductAuction, bidRequestMessage.BidPrice, customer))
{ {
await SendAuctionBidMessageAsync(messageWrapper, activeProductAuction, product, customer.Id, ResponseType.ToCaller); await SendAuctionBidMessageAsync(messageWrapper, activeProductAuction, product, customer.Id, ResponseType.ToCaller);
return ResponseType.Error; return ResponseType.Error;
@ -229,7 +237,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
activeProductAuction.BidsCount++; activeProductAuction.BidsCount++;
activeProductAuction.AuctionStatus = AuctionStatus.Active; activeProductAuction.AuctionStatus = AuctionStatus.Active;
if (!await SetAuctionBidPrice(auctionBid.BidPrice, activeProductAuction, product, customer.Id)) if (!await SetAuctionBidPriceAsync(auctionBid.BidPrice, activeProductAuction, product, customer.Id))
{ {
await SendAuctionBidMessageAsync(messageWrapper, activeProductAuction, product, customer.Id, ResponseType.ToCaller); await SendAuctionBidMessageAsync(messageWrapper, activeProductAuction, product, customer.Id, ResponseType.ToCaller);
return ResponseType.Error; return ResponseType.Error;
@ -373,7 +381,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
await HandleProductToAuctionStatusChangedRequest(customer, statusChangedMessageWrapper); await HandleProductToAuctionStatusChangedRequest(customer, statusChangedMessageWrapper);
} }
private async Task<bool> SetAuctionBidPrice(decimal bidPrice, ProductToAuctionMapping productToAuction, Product product, int lastBidCustomerId) private async Task<bool> SetAuctionBidPriceAsync(decimal bidPrice, ProductToAuctionMapping productToAuction, Product product, int lastBidCustomerId)
{ {
try try
{ {
@ -389,18 +397,48 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.Error($"AuctionHub.HandleBidRequest(); SetAuctionBidPrice() == false", ex); logger.Error($"AuctionHub.SetAuctionBidPriceAsync();", ex);
} }
return false; return false;
} }
private bool IsValidBidPrice(decimal productToAuctionCurrentPrice, decimal bidRequestPrice, bool hasAuctionBidInDb, Customer customer = null) private async Task<bool> IsValidProductPricesAndSyncIfNeedAsync(ProductToAuctionMapping productToAuction, Product product, Customer customer = null)
{ {
var nextBidPrice = AuctionService.GetNextBidPrice(productToAuctionCurrentPrice, hasAuctionBidInDb); if (product.Price == productToAuction.CurrentPrice) return true;
if (productToAuction.AuctionStatus is AuctionStatus.Sold or AuctionStatus.NotSold)
{
await logger.ErrorAsync($"AuctionHub.SyncProductPricesIfNeedAsync(); (product.Price != productToAuction.CurrentPrice && (productToAuction.AuctionStatus is AuctionStatus.Sold or AuctionStatus.NotSold)); productPrice: {product.Price}; productToAuctionCurrentPrice: {productToAuction.CurrentPrice}; auctionStatus: {productToAuction.AuctionStatus}", null, customer);
return false;
}
await logger.ErrorAsync($"AuctionHub.SyncProductPricesIfNeedAsync(); (product.Price != productToAuction.CurrentPrice); productPrice: {product.Price}; productToAuctionCurrentPrice: {productToAuction.CurrentPrice}", null, customer);
var lastBidPrice = product.OldPrice;
var lastBid = await auctionService.GetLastAuctionBidByProductToAuctionIdAsync(productToAuction.Id);
if (lastBid == null)
{
productToAuction.StartingPrice = lastBidPrice;
productToAuction.BidsCount = 0;
}
else lastBidPrice = lastBid.BidPrice;
await SetAuctionBidPriceAsync(lastBidPrice, productToAuction, product, lastBid?.CustomerId ?? 0);
await logger.InformationAsync($"AuctionHub.SyncProductPricesIfNeedAsync(); Synchronize the price was successful! lastBidPrice: {lastBidPrice};", null, customer);
return false;
}
private bool IsValidBidPrice(ProductToAuctionMapping productToAuction, decimal bidRequestPrice, Customer customer = null)
{
var hasAuctionBidInDb = productToAuction.BidsCount > 0;
var nextBidPrice = AuctionService.GetNextBidPrice(productToAuction.CurrentPrice, hasAuctionBidInDb);
if (bidRequestPrice != nextBidPrice) if (bidRequestPrice != nextBidPrice)
{ {
logger.Warning($"AuctionHub.IsValidBidPrice(); (bidRequestPrice != nextBidPrice); productToAuctionCurrentPrice: {productToAuctionCurrentPrice}; bidRequestPrice: {bidRequestPrice}; hasAuctionBidInDb: {hasAuctionBidInDb}", null, customer); logger.Warning($"AuctionHub.IsValidBidPrice(); (bidRequestPrice != nextBidPrice); productToAuctionCurrentPrice: {productToAuction.CurrentPrice}; bidRequestPrice: {bidRequestPrice}; hasAuctionBidInDb: {hasAuctionBidInDb}", null, customer);
return false; return false;
} }
@ -479,10 +517,24 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
switch (messageWrapper.ResponseType) switch (messageWrapper.ResponseType)
{ {
case ResponseType.ToCaller: case ResponseType.ToCaller:
messageWrapper.HideToaster = true;
await Clients.Caller.send(messageWrapper.ToJson()); await Clients.Caller.send(messageWrapper.ToJson());
break; break;
case ResponseType.ToAllClients: case ResponseType.ToAllClients:
await Clients.All.send(messageWrapper.ToJson()); var messageWrapperJson = messageWrapper.ToJson();
if (messageWrapper.HideToaster) await Clients.All.send(messageWrapperJson);
else
{
await Clients.Others.send(messageWrapperJson);
var messageWrapperJObject = JObject.Parse(messageWrapperJson);
messageWrapperJObject["hideToaster" /*nameof(MessageWrapper.HideToaster)*/] = "true";
await Clients.Caller.send(messageWrapperJObject.ToString(Formatting.None));
}
break; break;
case ResponseType.Error: case ResponseType.Error:
break; break;

View File

@ -14,6 +14,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs.Messages
public string RequestId { get; set; } public string RequestId { get; set; }
public int RequestCount { get; set; } public int RequestCount { get; set; }
public ResponseType ResponseType { get; set; } public ResponseType ResponseType { get; set; }
public bool HideToaster { get; set; }
public string Data { get; set; } public string Data { get; set; }
} }
} }

View File

@ -27,8 +27,8 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
//- ha bid-elt 1x is, kerüljön a watch-ba //- ha bid-elt 1x is, kerüljön a watch-ba
//- DbTransaction-t vhogy megcsinánli! //- DbTransaction-t vhogy megcsinánli!
public class SignalRMessageHandler(ILogger logger, IProductService productService, AuctionService auctionService, IHubContext<AuctionHub> hubContext, IWorkContext workContext, ICustomerService customerService, ICategoryService categoryService) //public class SignalRMessageHandler(ILogger logger, IProductService productService, AuctionService auctionService, IHubContext<AuctionHub> hubContext, IWorkContext workContext, ICustomerService customerService, ICategoryService categoryService)
{ //{
//private readonly Mutex _handleMessageMutex = new(); //private readonly Mutex _handleMessageMutex = new();
//public async Task HandleMessage(MessageWrapper messageWrapper, SessionItem sessionItem, string connectionId) //public async Task HandleMessage(MessageWrapper messageWrapper, SessionItem sessionItem, string connectionId)
@ -444,4 +444,4 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
// } // }
//} //}
} }
} //}