assign product to the auction

This commit is contained in:
Adam 2024-11-18 12:54:06 +01:00
parent 8577d26812
commit 0dd529e36d
5 changed files with 171 additions and 51 deletions

View File

@ -13,6 +13,8 @@ using Nop.Web.Areas.Admin.Models.Orders;
using Nop.Web.Framework.Components; using Nop.Web.Framework.Components;
using Nop.Web.Framework.Factories; using Nop.Web.Framework.Factories;
using Nop.Web.Framework.Infrastructure; using Nop.Web.Framework.Infrastructure;
using Nop.Web.Models.Catalog;
using System.Linq.Expressions;
namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Components namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Components
@ -25,7 +27,8 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Components
protected readonly IProductAttributeService _productAttributeService; protected readonly IProductAttributeService _productAttributeService;
protected readonly IWidgetPluginManager _widgetPluginManager; protected readonly IWidgetPluginManager _widgetPluginManager;
protected readonly AuctionSettings _auctionSettings; protected readonly AuctionSettings _auctionSettings;
protected readonly IAuctionService _auctionService; protected readonly AuctionService _auctionService;
protected readonly MyProductModelFactory _productModelFactory;
@ -39,13 +42,15 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Components
IProductAttributeService productAttributeService, IProductAttributeService productAttributeService,
IWidgetPluginManager widgetPluginManager, IWidgetPluginManager widgetPluginManager,
AuctionSettings auctionSettings, AuctionSettings auctionSettings,
IAuctionService auctionService) : base(widgetModelFactory) AuctionService auctionService,
MyProductModelFactory productModelFactory) : base(widgetModelFactory)
{ {
_logger = logger; _logger = logger;
_productAttributeService = productAttributeService; _productAttributeService = productAttributeService;
_widgetPluginManager = widgetPluginManager; _widgetPluginManager = widgetPluginManager;
_auctionSettings = auctionSettings; _auctionSettings = auctionSettings;
_auctionService = auctionService; _auctionService = auctionService;
_productModelFactory = productModelFactory;
} }
#endregion #endregion
@ -83,6 +88,8 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Components
} }
var product = (additionalData as ProductModel); var product = (additionalData as ProductModel);
//ProductDetailsModel detailsModel = await _productModelFactory.PrepareProductDetailsModelAsync(product.Price);
productId = product.Id; productId = product.Id;
var auctions = await _auctionService.GetAllAuctionsAsync() ?? new List<Auction>(); var auctions = await _auctionService.GetAllAuctionsAsync() ?? new List<Auction>();
@ -90,9 +97,14 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Components
// Assign the auctions to the ViewBag // Assign the auctions to the ViewBag
ViewBag.Auctions = auctions; ViewBag.Auctions = auctions;
ProductAssignToAuctionViewModel viewModel = new ProductAssignToAuctionViewModel(); ProductAssignToAuctionViewModel viewModel = new ProductAssignToAuctionViewModel();
viewModel.StartingPrice = product.BasepriceAmount; viewModel.ProductId = productId;
viewModel.StartingPrice = product.OldPrice;
viewModel.BidPrice = product.OldPrice;
//viewModel.InAuctions = await _auctionService.GetAllAuctionsAsync()
viewModel.InAuctions = [];
await _logger.InformationAsync($"Admin auction widget called from {widgetZone}! II. "); await _logger.InformationAsync($"Admin auction widget called from {widgetZone}! II. ");
return View("~/Plugins/Misc.AuctionPlugin/Areas/Admin/Views/AdminProductAuctionSettingsBox.cshtml", productId.ToString()); return View("~/Plugins/Misc.AuctionPlugin/Areas/Admin/Views/AdminProductAuctionSettingsBox.cshtml", viewModel);
} }
#endregion #endregion

View File

@ -11,21 +11,23 @@ using Nop.Services.Logging;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities; using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Nop.Plugin.Misc.AuctionPlugin.Services; using Nop.Plugin.Misc.AuctionPlugin.Services;
using Nop.Web.Framework.Models.DataTables; using Nop.Web.Framework.Models.DataTables;
using Nop.Plugin.Misc.AuctionPlugin.Models;
using AyCode.Core.Extensions;
namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Controllers; namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Controllers;
[AutoValidateAntiforgeryToken] //[AutoValidateAntiforgeryToken]
[AuthorizeAdmin] //[AuthorizeAdmin]
[Area(AreaNames.ADMIN)] [Area(AreaNames.ADMIN)]
public class AuctionPluginAdminController : BasePluginController public class AuctionPluginAdminController : BasePluginController
{ {
//private readonly SignalRservice _signalRservice; //private readonly SignalRservice _signalRservice;
private readonly ILocalizationService _localizationService; protected readonly ILocalizationService _localizationService;
private readonly INotificationService _notificationService; protected readonly INotificationService _notificationService;
private readonly ISettingService _settingService; protected readonly ISettingService _settingService;
private readonly AuctionSettings _auctionSettings; protected readonly AuctionSettings _auctionSettings;
private readonly AuctionService _auctionService; protected readonly AuctionService _auctionService;
private readonly ILogger _logger; protected readonly ILogger _logger;
//public AuctionPluginAdminController(SignalRservice signalRservice) //public AuctionPluginAdminController(SignalRservice signalRservice)
public AuctionPluginAdminController(ILocalizationService localizationService, INotificationService notificationService, ISettingService settingService, AuctionSettings auctionSettings, ILogger logger, AuctionService auctionService) public AuctionPluginAdminController(ILocalizationService localizationService, INotificationService notificationService, ISettingService settingService, AuctionSettings auctionSettings, ILogger logger, AuctionService auctionService)
@ -156,15 +158,30 @@ public class AuctionPluginAdminController : BasePluginController
} }
[HttpPost] public async Task<IActionResult> AssignProductToAuction()
public async Task<IActionResult> AssignProductToAuction(int productId, int auctionId)
{ {
if (productId <= 0 || auctionId <= 0) _logger.Information("AssignProductToAuction has been called");
var result = await _auctionService.GetProductToAuctionsByAuctionIdAsync(1);
return Ok(result.ToJson());
}
[HttpPost]
public async Task<IActionResult> AssignProductToAuction([FromBody] AssignAuctionRequestModel model)
{
_logger.Information("AssignProductToAuction has been called");
if (Convert.ToInt32(model.ProductId) <= 0 || Convert.ToInt32(model.AuctionId) <= 0)
return BadRequest(); return BadRequest();
var result = await _auctionService.AssignProductToAuctionAsync(productId, auctionId); var result = await _auctionService.AssignProductToAuctionAsync(Convert.ToInt32(model.ProductId),
Convert.ToDecimal(model.StartingPrice), Convert.ToDecimal(model.BidPrice), Convert.ToInt32(model.AuctionId));
if (result) if (result)
return Ok(); return Ok("Baaaazdmeeeeeeeeg");
return StatusCode(500, "Error assigning product to auction."); return StatusCode(500, "Error assigning product to auction.");
} }

View File

@ -1,4 +1,5 @@
using Nop.Web.Framework.Models; using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Nop.Web.Framework.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -10,7 +11,7 @@ namespace Nop.Plugin.Misc.AuctionPlugin.Areas.Admin.Models
public record ProductAssignToAuctionViewModel : BaseNopModel public record ProductAssignToAuctionViewModel : BaseNopModel
{ {
public int ProductId { get; set; } public int ProductId { get; set; }
public int AuctionId { get; set; } public List<ProductToAuctionMapping> InAuctions { get; set; }
public decimal StartingPrice { get; set; } public decimal StartingPrice { get; set; }
public decimal BidPrice { get; set; } public decimal BidPrice { get; set; }
public decimal BidAmount { get; set; } public decimal BidAmount { get; set; }

View File

@ -2,45 +2,116 @@
<div class="auction-settings-box"> <div class="auction-settings-box">
<h3>@T("Plugins.Misc.AuctionPlugin.AssignToAuction")</h3> <h3>@T("Plugins.Misc.AuctionPlugin.AssignToAuction")</h3>
<form id="assignAuctionForm" method="post" action="@Url.Action("AssignProductToAuction", "AuctionPluginAdmin", new { area = "Admin" })"> <div id="assignAuctionContainer">
<input type="hidden" name="productId" value="@Model.ProductId" /> <h3>Assign Product to Auction</h3>
<input type="hidden" name="startingPrice" value="@Model.StartingPrice" /> <input type="hidden" id="productId" value="@Model.ProductId" />
@* <input type="hidden" name="bidPrice" value="@Model.StartingPrice" /> *@ <input type="hidden" id="startingPrice" value="@Model.StartingPrice" />
<input type="hidden" id="bidPrice" value="@Model.StartingPrice" />
<div class="form-group"> <label for="auctionDropdown">@T("Plugins.Misc.AuctionPlugin.SelectAuction")</label>
<label for="auctionSelect">@T("Plugins.Misc.AuctionPlugin.SelectAuction")</label> <select id="auctionDropdown" class="form-control">
<select id="auctionSelect" name="auctionId" class="form-control"> <option value="">Select an auction...</option>
<option value="">@T("Plugins.Misc.AuctionPlugin.SelectAuctionPlaceholder")</option>
@foreach (var auction in ViewBag.Auctions as List<Nop.Plugin.Misc.AuctionPlugin.Domains.Entities.Auction>) @foreach (var auction in ViewBag.Auctions as List<Nop.Plugin.Misc.AuctionPlugin.Domains.Entities.Auction>)
{ {
<option value="@auction.Id">@auction.AuctionName</option> <option value="@auction.Id">@auction.AuctionName</option>
} }
</select> </select>
<button id="assignAuctionButton" class="btn btn-primary mt-2">@T("Plugins.Misc.AuctionPlugin.AssignToAuctionButton")</button>
</div> </div>
<button type="submit" class="btn btn-primary">
@T("Plugins.Misc.AuctionPlugin.AssignToAuctionButton")
</button>
</form>
</div> </div>
<script> <script>
$(document).ready(function () {
$('#assignAuctionForm').on('submit', function (e) {
e.preventDefault();
var form = $(this);
$(document).ready(function () {
// Handle button click
$("#assignAuctionButton").on("click", function () {
var productId = $("#productId").val();
var startingPrice = $("#startingPrice").val();
// var bidPrice = $("#bidPrice").val()toFixed(2);
var bidPrice = $("#bidPrice").val();
var auctionId = $("#auctionDropdown").val();
if (!auctionId) {
alert("Please select an auction.");
return;
}
var postData = {
ProductId: productId,
StartingPrice: startingPrice,
BidPrice: bidPrice,
AuctionId: auctionId
};
addAntiForgeryToken(postData);
console.log("postData: " + JSON.stringify(postData));
// Perform AJAX call
$.ajax({ $.ajax({
url: form.attr('action'), url: "/Admin/AuctionPluginAdmin/AssignProductToAuction", // Update to match your endpoint
type: 'POST', type: "POST",
data: form.serialize(), contentType: "application/json",
data: JSON.stringify(postData),
traditional: true,
success: function (response) { success: function (response) {
toastr.success("@T("Plugins.Misc.AuctionPlugin.ProductAssignedSuccess")"); alert("Product successfully assigned to the auction!");
console.log(response); // Optional: Log response for debugging
}, },
error: function (error) { error: function (xhr, status, error) {
toastr.error("@T("Plugins.Misc.AuctionPlugin.ProductAssignedError")"); console.error("Error assigning product to auction:", error);
alert("Failed to assign the product to the auction. Please try again.");
} }
}); });
}); });
}); });
// $("#assignAuctionForm").on("submit", function (event) {
// event.preventDefault(); // Prevent the default form submission behavior
// var productId = $("#productId").val();
// var startingPrice = $("startingPrice").val();
// var bidPrice = $("bidPrice").val();
// var auctionId = $("#auctionDropdown").val();
// // AJAX call or form submission logic here
// $.ajax({
// url: "/Admin/Auction/AssignProductToAuction",
// type: "POST",
// data: { productId: productId, startingPrice: startingPrice, bidPrice: bidPrice, auctionId: auctionId },
// success: function (response) {
// console.log("Product assigned to auction successfully!");
// },
// error: function (xhr, status, error) {
// console.error("Error assigning product to auction:", error);
// }
// });
// });
// $(document).ready(function () {
// $('#assignAuctionForm').on('submit', function (e) {
// e.preventDefault();
// var form = $(this);
// $.ajax({
// url: form.attr('action'),
// type: 'POST',
// data: form.serialize(),
// success: function (response) {
// toastr.success("@T("Plugins.Misc.AuctionPlugin.ProductAssignedSuccess")");
// },
// error: function (error) {
// toastr.error("@T("Plugins.Misc.AuctionPlugin.ProductAssignedError")");
// }
// });
// });
// });
</script> </script>

View File

@ -6,6 +6,7 @@ using Nop.Plugin.Misc.AuctionPlugin.Domains;
using Nop.Plugin.Misc.AuctionPlugin.Domains.DataLayer; using Nop.Plugin.Misc.AuctionPlugin.Domains.DataLayer;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Dtos; using Nop.Plugin.Misc.AuctionPlugin.Domains.Dtos;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities; using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Nop.Services.Logging;
namespace Nop.Plugin.Misc.AuctionPlugin.Services; namespace Nop.Plugin.Misc.AuctionPlugin.Services;
@ -36,6 +37,7 @@ public class AuctionService : IAuctionService
protected readonly IShortTermCacheManager _shortTermCacheManager; protected readonly IShortTermCacheManager _shortTermCacheManager;
protected readonly IStaticCacheManager _staticCacheManager; protected readonly IStaticCacheManager _staticCacheManager;
protected readonly IWorkContext _workContext; protected readonly IWorkContext _workContext;
protected readonly ILogger _logger;
#endregion #endregion
#region Ctor #region Ctor
@ -46,7 +48,14 @@ public class AuctionService : IAuctionService
/// <param name="ctx"></param> /// <param name="ctx"></param>
/// <param name="shortTermCacheManager">Short term cache manager</param> /// <param name="shortTermCacheManager">Short term cache manager</param>
/// <param name="staticCacheManager">Cache manager</param> /// <param name="staticCacheManager">Cache manager</param>
public AuctionService(AuctionDbContext ctx, IRepository<Auction> auctionRepository, IRepository<ProductToAuctionMapping> productToAuctionRepository, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, IWorkContext workContext) public AuctionService(
AuctionDbContext ctx,
IRepository<Auction> auctionRepository,
IRepository<ProductToAuctionMapping> productToAuctionRepository,
IShortTermCacheManager shortTermCacheManager,
IStaticCacheManager staticCacheManager,
IWorkContext workContext,
ILogger logger)
{ {
_ctx = ctx; _ctx = ctx;
//_customerBidRepository = customerBidRepository; //_customerBidRepository = customerBidRepository;
@ -55,6 +64,7 @@ public class AuctionService : IAuctionService
_shortTermCacheManager = shortTermCacheManager; _shortTermCacheManager = shortTermCacheManager;
_staticCacheManager = staticCacheManager; _staticCacheManager = staticCacheManager;
_workContext = workContext; _workContext = workContext;
_logger = logger;
} }
#endregion #endregion
@ -171,7 +181,7 @@ public class AuctionService : IAuctionService
{ {
return new AuctionBidDto(await _ctx.AuctionBids.GetByIdAsync(auctionBidId)); return new AuctionBidDto(await _ctx.AuctionBids.GetByIdAsync(auctionBidId));
} }
public async Task<bool> AssignProductToAuctionAsync(int productId, int auctionId) public async Task<bool> AssignProductToAuctionAsync(int productId, decimal startingPrice, decimal bidPrice, int auctionId)
{ {
var auction = await _ctx.Auctions.GetByIdAsync(auctionId); var auction = await _ctx.Auctions.GetByIdAsync(auctionId);
if (auction == null) if (auction == null)
@ -180,10 +190,19 @@ public class AuctionService : IAuctionService
var mapping = new ProductToAuctionMapping var mapping = new ProductToAuctionMapping
{ {
ProductId = productId, ProductId = productId,
StartingPrice = Convert.ToInt32(startingPrice),
BidPrice = Convert.ToInt32(bidPrice),
BidAmount = 0,
AuctionStatus = Domains.Enums.AuctionStatus.Active,
AuctionId = auctionId AuctionId = auctionId
}; };
try
await _productToAuctionRepository.InsertAsync(mapping); {
await _ctx.ProductToAuctions.InsertAsync(mapping);
}
catch (Exception ex) {
await _logger.InformationAsync(ex.ToString());
}
return true; return true;
} }