|
| 1 | +namespace Nop.Plugin.Widgets.AzPersonalizer.Components |
| 2 | +{ |
| 3 | + |
| 4 | + using System; |
| 5 | + using System.Collections.Generic; |
| 6 | + using System.Globalization; |
| 7 | + using System.Linq; |
| 8 | + using System.Text; |
| 9 | + using System.Threading.Tasks; |
| 10 | + using Microsoft.AspNetCore.Mvc; |
| 11 | + using Microsoft.Azure.CognitiveServices.Personalizer.Models; |
| 12 | + using Nop.Core; |
| 13 | + using Nop.Core.Domain.Catalog; |
| 14 | + using Nop.Core.Domain.Logging; |
| 15 | + using Nop.Plugin.Widgets.AzPersonalizer.Controllers; |
| 16 | + using Nop.Plugin.Widgets.AzPersonalizer.Models; |
| 17 | + using Nop.Plugin.Widgets.AzPersonalizer.Services; |
| 18 | + using Nop.Services.Catalog; |
| 19 | + using Nop.Services.Logging; |
| 20 | + using Nop.Web.Factories; |
| 21 | + using Nop.Web.Framework.Components; |
| 22 | + using Nop.Web.Framework.Infrastructure; |
| 23 | + using Nop.Web.Models.Catalog; |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// Represents the view component to place a widget into pages |
| 27 | + /// </summary> |
| 28 | + [ViewComponent(Name = "WidgetsAzPersonalizer")] |
| 29 | + public class WidgetsAzPersonalizerViewComponent : NopViewComponent |
| 30 | + { |
| 31 | + |
| 32 | + #region fields |
| 33 | + |
| 34 | + private readonly IWebHelper _webHelper; |
| 35 | + private readonly IProductService _productService; |
| 36 | + private readonly IProductModelFactory _productModelFactory; |
| 37 | + private readonly ILogger _logger; |
| 38 | + private readonly PersonalizerClientService _personalizerClientService; |
| 39 | + |
| 40 | + #endregion |
| 41 | + |
| 42 | + #region ctor |
| 43 | + |
| 44 | + public WidgetsAzPersonalizerViewComponent (PersonalizerClientService personalizerClientService, |
| 45 | + IProductService productService, |
| 46 | + IProductModelFactory productModelFactory, |
| 47 | + IWebHelper webHelper, |
| 48 | + ILogger logger) |
| 49 | + { |
| 50 | + _logger = logger; |
| 51 | + _webHelper = webHelper; |
| 52 | + _personalizerClientService = personalizerClientService; |
| 53 | + _productService = productService; |
| 54 | + _productModelFactory = productModelFactory; |
| 55 | + } |
| 56 | + |
| 57 | + #endregion |
| 58 | + |
| 59 | + #region methods |
| 60 | + |
| 61 | + /// <summary> |
| 62 | + /// Invoke view component |
| 63 | + /// </summary> |
| 64 | + /// <param name="widgetZone">Widget zone name</param> |
| 65 | + /// <param name="additionalData">Additional data</param> |
| 66 | + /// <returns> |
| 67 | + /// A task that represents the asynchronous operation |
| 68 | + /// The task result contains the view component result |
| 69 | + /// </returns |
| 70 | + public async Task<IViewComponentResult> InvokeAsync (string widgetZone, object additionalData) |
| 71 | + { |
| 72 | + if (widgetZone == null) |
| 73 | + { |
| 74 | + await _logger.ErrorAsync("Widget Zone was null"); |
| 75 | + throw new ArgumentNullException(widgetZone); |
| 76 | + } |
| 77 | + |
| 78 | + if (widgetZone.Equals(PublicWidgetZones.ProductDetailsEssentialBottom, |
| 79 | + StringComparison.InvariantCultureIgnoreCase)) |
| 80 | + { |
| 81 | + try |
| 82 | + { |
| 83 | + string[] url = _webHelper.GetThisPageUrl(true)?.Split("?"); |
| 84 | + if (TempData["RewardID"] != null |
| 85 | + && TempData["OrderedIDs"] != null) |
| 86 | + { |
| 87 | + string id = TempData["RewardID"] is string rewardID ? rewardID : null; |
| 88 | + string pos = TempData["OrderedIDs"] is string position ? position : null; |
| 89 | + |
| 90 | + await ProcessRewardAsync(id, pos, additionalData); |
| 91 | + } |
| 92 | + |
| 93 | + IViewComponentResult list = await RecommendedListAsync(additionalData); |
| 94 | + if (list == null) |
| 95 | + { |
| 96 | + await _logger.ErrorAsync("Confirm everything is corret in the plugin settings."); |
| 97 | + return View("~/Plugins/Widgets.AzPersonalizer/Views/Default.cshtml"); |
| 98 | + } |
| 99 | + |
| 100 | + return list; |
| 101 | + } |
| 102 | + catch (Exception e) |
| 103 | + { |
| 104 | + await _logger.ErrorAsync(e.Message, e); |
| 105 | + return View("~/Plugins/Widgets.AzPersonalizer/Views/Default.cshtml"); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + // While there is only one widget zone in the plugin this shouldn't return anything. If you want to add |
| 110 | + // recommendations to multiple widget zones, then you should make this an else if and return the appropriate view. |
| 111 | + return View("~/Plugins/Widgets.AzPersonalizer/Views/Default.cshtml"); |
| 112 | + } |
| 113 | + |
| 114 | + |
| 115 | + /// <summary> |
| 116 | + /// Prepares the view component with a list of Ranked Actions |
| 117 | + /// </summary> |
| 118 | + /// <param name="azPersonalizerSettings"></param> |
| 119 | + /// <param name="additionalData"></param> |
| 120 | + /// <returns> |
| 121 | + /// A task that represents the asynchronous operation |
| 122 | + /// The task result contains the view component result |
| 123 | + /// </returns> |
| 124 | + private async Task<IViewComponentResult> RecommendedListAsync (object additionalData) |
| 125 | + { |
| 126 | + try |
| 127 | + { |
| 128 | + RankResponse rankedActions = |
| 129 | + await _personalizerClientService?.GetRankedActionsAsync(additionalData); |
| 130 | + IList<RankedAction> model = rankedActions.Ranking.OrderByDescending(r => r.Probability).ToList(); |
| 131 | + TempDataTokenController tdt = new(rankedActions.EventId); |
| 132 | + TempData["RewardID"] = rankedActions.EventId; |
| 133 | + IList<Product> products = new List<Product>(model.Count); |
| 134 | + StringBuilder odds = new(rankedActions.EventId + ": "); |
| 135 | + |
| 136 | + for (int i = 0; i < model.Count; i++) |
| 137 | + { |
| 138 | + odds.Append("(" + model[i]?.Id + "," + model[i].Probability + ");"); |
| 139 | + products.Insert(i, |
| 140 | + await _productService?.GetProductByIdAsync(int.Parse(model[i]?.Id, |
| 141 | + new CultureInfo("en-UK")))); |
| 142 | + tdt.AddId(model[i]?.Id); |
| 143 | + } |
| 144 | + |
| 145 | + TempData["OrderedIDs"] = tdt.OrderedIDs; |
| 146 | + |
| 147 | + await _logger.InsertLogAsync(LogLevel.Debug, odds.ToString()); |
| 148 | + |
| 149 | + return View("~/Plugins/Widgets.AzPersonalizer/Views/Recommendations.cshtml", |
| 150 | + new ProductOverviewToRankingList( |
| 151 | + (await _productModelFactory.PrepareProductOverviewModelsAsync(products)).ToList(), |
| 152 | + rankedActions.EventId)); |
| 153 | + } |
| 154 | + catch (Exception e) |
| 155 | + { |
| 156 | + await _logger.ErrorAsync( |
| 157 | + $"Failed to get recommendations: Exception type:{e.GetType()} and message:{e.Message}", e); |
| 158 | + return null; |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + /// <summary> |
| 163 | + /// Calculates and sends a reward to a given Event. |
| 164 | + /// </summary> |
| 165 | + /// <param name="ID"></param> |
| 166 | + /// <param name="orderIDs"></param> |
| 167 | + /// <param name="additionalData"></param> |
| 168 | + /// <returns>An empty task.</returns> |
| 169 | + private async Task ProcessRewardAsync (string eventID, string orderIDs, object additionalData) |
| 170 | + { |
| 171 | + try |
| 172 | + { |
| 173 | + ProductDetailsModel product = additionalData is ProductDetailsModel model ? model : null; |
| 174 | + if (string.IsNullOrEmpty(eventID) || string.IsNullOrEmpty(orderIDs) || product == null) |
| 175 | + { |
| 176 | + return; |
| 177 | + } |
| 178 | + |
| 179 | + string[] products = orderIDs.Split("-"); |
| 180 | + for (int i = 0; i < products.Length; i++) |
| 181 | + { |
| 182 | + if (products[i].Equals(product.Id.ToString(new CultureInfo("en-UK")), |
| 183 | + StringComparison.InvariantCultureIgnoreCase)) |
| 184 | + { |
| 185 | + await _personalizerClientService.RewardAnActionAsync(eventID, i); |
| 186 | + return; |
| 187 | + } |
| 188 | + } |
| 189 | + } |
| 190 | + catch (Exception e) |
| 191 | + { |
| 192 | + await _logger.ErrorAsync($"Failed to reward event with EventId:{eventID}", e); |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + #endregion |
| 197 | + } |
| 198 | +} |
0 commit comments