Compare commits

...

3 Commits

Author SHA1 Message Date
Loretta 59ae22f5cd signalR client improvements, fixes 2024-11-19 19:29:09 +01:00
Loretta ae63aa8edc Merge branch 'main' of https://git2.aycode.com/Adam/Mango.Nop.Plugins 2024-11-19 17:33:47 +01:00
Loretta 0f6d7006a7 fixes 2024-11-19 17:32:54 +01:00
6 changed files with 104 additions and 91 deletions

View File

@ -17,6 +17,7 @@ using Nop.Web.Framework.Mvc;
using Nop.Web.Framework.Mvc.Filters;
using System;
using System.Linq;
using AyCode.Core.Extensions;
namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Controllers
{

View File

@ -40,8 +40,9 @@
});
$('.toast-success').css("background-color", "#4caf50");
const publicProductBidBox = document.getElementById("publicProductBidBox");
if (publicProductBidBox) {
var publicProductBidBox = document.getElementById("publicProductBidBox");
if (publicProductBidBox)
{
refreshPublicBidBox(data);
}

View File

@ -1,4 +1,6 @@
using Nop.Plugin.Misc.AuctionPlugin.Hubs.Messages;
using System.Globalization;
using AyCode.Core.Extensions;
using Nop.Plugin.Misc.AuctionPlugin.Hubs.Messages;
using Newtonsoft.Json.Linq;
using Nop.Plugin.Misc.AuctionPlugin.Models;
using Nop.Plugin.Misc.AuctionPlugin.Services;
@ -8,6 +10,7 @@ using Nop.Services.Logging;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.SignalR;
using Nop.Core;
namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
{
@ -17,116 +20,111 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Hubs
protected readonly IProductService _productService;
protected readonly AuctionService _auctionService;
private IHubContext<AuctionHub> _hubContext;
private readonly IWorkContext _workContext;
public SignalRMessageHandler(ILogger logger, IProductService productService, AuctionService auctionService, IHubContext<AuctionHub> hubContext)
public SignalRMessageHandler(ILogger logger, IProductService productService, AuctionService auctionService, IHubContext<AuctionHub> hubContext, IWorkContext workContext)
{
_logger = logger;
_productService = productService;
_auctionService = auctionService;
_hubContext = hubContext;
_workContext = workContext;
}
public async Task HandleMessage(MessageWrapper message)
{
if (message?.Data == null)
{
_logger.Error($"SignalRMessageHandler.HandleMessage(); message?.Data == null");
return;
}
//TODO: A MessageWrapper-ben kéne küldözgetni a UserId (CustomerId-t) - J.
//if (message.UserId != (await _workContext.GetCurrentCustomerAsync()).Id)
//{
// _logger.Error($"SignalRMessageHandler.HandleMessage(); message.UserId != (await _workContext.GetCurrentCustomerAsync()).Id");
// return;
//}
switch (message.MessageType)
{
//nameof(IAuctionHubClient.SendPrice)
case "BidRequestMessage":
await HandleBidRequest(message.Data);
await HandleBidRequest(message.Data.ToString()?.JsonTo<AuctionBidRequest>());
break;
// Add other message types here
default:
await _logger.ErrorAsync("Unknown message type");
await _logger.ErrorAsync("SignalRMessageHandler.HandleMessage(); Unknown message type");
break;
}
}
private async Task HandleBidRequest(object data)
private async Task HandleBidRequest(AuctionBidRequest bidRequestMessage)
{
AuctionBidRequest bidRequestMessage = new AuctionBidRequest();
try
if (bidRequestMessage == null)
{
var a = JsonConvert.DeserializeObject<AuctionBidRequest>(data.ToString());
//var b = (message.Data as JObject)?.ToObject<AuctionBidRequest>();
if (a == null)
{
await _logger.InformationAsync("Deserialization returned null. Message data might not match the expected structure.");
}
bidRequestMessage = a;
_logger.Error($"SignalRMessageHandler.HandleBidRequest(); bidRequestMessage == null");
return;
}
catch (Exception ex)
{
await _logger.ErrorAsync("Error during deserialization of AuctionBidRequest", ex);
}
//AuctionBidRequest bidRequestMessage = new AuctionBidRequest();
try
{
await _logger.InformationAsync($"SignalRMessageHandler.HandleBidRequest(); Bid received: - Auction: {bidRequestMessage.AuctionId} Product: {bidRequestMessage.ProductId} - Bid: {bidRequestMessage.BidPrice} - Customer: {bidRequestMessage.CustomerId}");
if (bidRequestMessage != null)
if (bidRequestMessage.CustomerId != (await _workContext.GetCurrentCustomerAsync()).Id)
{
await _logger.InformationAsync($"Bid received: - Auction:{bidRequestMessage.AuctionId} Product: {bidRequestMessage.ProductId} - Bid: {bidRequestMessage.BidPrice} - Customer: {bidRequestMessage.CustomerId}");
//get product
var product = await _productService.GetProductByIdAsync(Convert.ToInt32(bidRequestMessage.ProductId));
if (product != null)
{
//validate the bidprice amount
//set new price
product.Price = Convert.ToDecimal(bidRequestMessage.BidPrice);
}
List<ProductToAuctionMapping> mapping = await _auctionService.GetProductToAuctionByAuctionIdAndProductIdAsync(Convert.ToInt32(bidRequestMessage.AuctionId), Convert.ToInt32(bidRequestMessage.ProductId));
AuctionBid auctionBid = new AuctionBid();
auctionBid.ProductId = Convert.ToInt32(bidRequestMessage.ProductId);
auctionBid.CustomerId = Convert.ToInt32(bidRequestMessage.CustomerId);
auctionBid.BidPrice = Convert.ToDecimal(bidRequestMessage.BidPrice);
auctionBid.ProductAuctionMappingId = mapping.FirstOrDefault().Id;
//save bid
try
{
await _auctionService.InsertBidAsync(auctionBid);
}
catch (Exception e)
{
_logger.Error($"MessageHandling InsertBidAsync error: {e.ToString()}");
}
//update product
await _productService.UpdateProductAsync(product);
// Optionally broadcast to all clients
var bid = new MessageWrapper
{
MessageType = "bidNotification",
Data = new BidNotificationMessage
{
ProductName = bidRequestMessage.ProductId,
BidPrice = bidRequestMessage.BidPrice,
NextStepAmount = "50000"
}
};
var jsonMessage = JsonConvert.SerializeObject(bid, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
await _hubContext.Clients.All.SendAsync("send", jsonMessage);
_logger.Error($"SignalRMessageHandler.HandleBidRequest(); bidRequestMessage.CustomerId != (await _workContext.GetCurrentCustomerAsync()).Id");
return;
}
var product = await _productService.GetProductByIdAsync(bidRequestMessage.ProductId);
if (product == null)
{
_logger.Error($"SignalRMessageHandler.HandleBidRequest(); product == null");
return; //ha nincs product vagy exception van, akkor ne broadcast-eljük ki az invalid Bid-et! - J.
}
var mapping = await _auctionService.GetProductToAuctionByAuctionIdAndProductIdAsync(bidRequestMessage.AuctionId, bidRequestMessage.ProductId);
if (mapping == null || mapping.Count == 0)
{
_logger.Error($"SignalRMessageHandler.HandleBidRequest(); mapping == null || mapping.Count == 0");
return; //ha nincs ProductToAuction, akkor ne broadcast-eljük ki az invalid Bid-et! - J.
}
var auctionBid = bidRequestMessage.CreateMainEntity();
auctionBid.ProductAuctionMappingId = mapping.FirstOrDefault()!.Id;
//TODO: validate the bidprice amount
if (product.Price >= auctionBid.BidPrice)
{
_logger.Warning($"SignalRMessageHandler.HandleBidRequest(); product.Price >= bidRequestMessage.BidPrice; productPrice: {product.Price}; bidRequestPrice: {auctionBid.BidPrice}");
return;
}
//save bid
await _auctionService.InsertBidAsync(auctionBid);
//set new price
product.Price = bidRequestMessage.BidPrice;
await _productService.UpdateProductAsync(product);
// Optionally broadcast to all clients
var bid = new MessageWrapper
{
MessageType = "bidNotification",
Data = new BidNotificationMessage
{
ProductName = auctionBid.ProductId.ToString(),
BidPrice = auctionBid.BidPrice.ToString(CultureInfo.InvariantCulture),
NextStepAmount = "50000"
}
};
await _hubContext.Clients.All.SendAsync("send", bid.ToJson());
}
catch (Exception ex)
{
_logger.Error($"MessageHandling error: {ex.ToString()}");
_logger.Error($"SignalRMessageHandler.HandleBidRequest(); MessageHandling error: {ex}");
}
}
}

View File

@ -3,15 +3,16 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Dtos;
namespace Nop.Plugin.Misc.AuctionPlugin.Models
{
public class AuctionBidRequest
public class AuctionBidRequest : AuctionBidDto
{
public string AuctionId { get; set; }
public string BidPrice { get; set; }
public string ProductId { get; set; }
public string CustomerId { get; set; }
public int AuctionId { get; set; }
//public string BidPrice { get; set; }
//public int ProductId { get; set; }
//public int CustomerId { get; set; }
}
}

View File

@ -74,7 +74,7 @@ public class AuctionService : IAuctionService
private async Task<bool> ValidateAuctionBid(AuctionBid auctionBid)
{
auctionBid.CustomerId = (await _workContext.GetCurrentCustomerAsync()).Id; //elvileg megnézi cache-ben, csak utána DB-zik! - J.
//auctionBid.CustomerId = (await _workContext.GetCurrentCustomerAsync()).Id; //elvileg megnézi cache-ben, csak utána DB-zik! - J.
//etc...
return true;

View File

@ -21,7 +21,7 @@
<span class="value">@String.Format("{0:c}", Model.LicitStep)</span>
</div>
<div>
<button id="signalRBidButton" class="btn btn-success">
<button id="signalRBidButton" class="btn btn-success" type="button">
Bid @String.Format("{0:c}", Model.BidPrice)
</button>
@* <button id="bidButton" class="btn btn-success">
@ -81,6 +81,10 @@
// });
$("#signalRBidButton").on("click", function () {
document.getElementById("signalRBidButton").disabled = true;
event.preventDefault();
var bidMessage = {
AuctionId: pageViewModel.AuctionId.toFixed(),
BidPrice: pageViewModel.BidPrice.toFixed(2),
@ -90,7 +94,7 @@
sendMessageToServer("BidRequestMessage", bidMessage);
return false;
});
@ -114,13 +118,21 @@
// }
// });
const widgetPriceElement = document.getElementById("price-value-"+pageViewModel.ProductId);
const budButtonelement = document.getElementById("signalRBidButton");
var widgetPriceElement = document.getElementById("price-value-"+pageViewModel.ProductId);
var budButtonElement = document.getElementById("signalRBidButton");
if (widgetPriceElement) {
widgetPriceElement.textContent = data.bidPrice; // Update the price
budButtonElement.textContent = data.bidPrice + data.nextStep;
pageViewModel.BidPrice = Number(data.bidPrice) + Number(data.nextStepAmount);
budButtonElement.textContent = pageViewModel.BidPrice.toFixed(2);
// if (pageViewModel.CustomerId == data.CustomerId) {
// }
console.log(`WidgetPrice updated to: ${data.bidPrice}`);
budButtonElement.disabled = false;
} else {
console.warn("Element with ID 'WidgetPrice' not found in the DOM.");
}