/// <summary> /// Gets the Promotion dto without caching the results. /// </summary> /// <param name="promotionId">The promotion id.</param> /// <returns></returns> public static PromotionDto GetPromotionDto(int promotionId) { // Assign new cache key, specific for site guid and response groups requested //string cacheKey = MarketingCache.CreateCacheKey("Promotion", PromotionId.ToString()); PromotionDto dto = null; // check cache first //object cachedObject = MarketingCache.Get(cacheKey); //if (cachedObject != null) // dto = (PromotionDto)cachedObject; // Load the object if (dto == null) { PromotionAdmin admin = new PromotionAdmin(); admin.Load(promotionId); dto = admin.CurrentDto; // Insert to the cache collection //MarketingCache.Insert(cacheKey, dto, MarketingConfiguration.CacheConfig.PromotionCollectionTimeout); } return(dto); }
private static Promotion GetMockedPromotionWithSettings(XDocument settingsXml) { var stream = new MemoryStream(); settingsXml.Save(stream); var settings = stream.ToArray(); var promotionDto = new PromotionDto(); var promotionTable = new PromotionDto.PromotionDataTable(); promotionDto.Tables.Add(promotionTable); var promotionRow = promotionTable.AddPromotionRow("", ApplicationGuid, "", DateTime.MinValue, DateTime.MaxValue, "", 0, 0, "", 0, "", 0, DateTime.MinValue, DateTime.MinValue, "", "", 0, 0, settings, 0, 0); var promotionLanguageTable = new PromotionDto.PromotionLanguageDataTable(); promotionDto.Tables.Add(promotionLanguageTable); var promotionLanguageRow = promotionLanguageTable.AddPromotionLanguageRow("", "en-US", promotionRow); var campaignDto = new CampaignDto(); var campaignTable = new CampaignDto.CampaignDataTable(); campaignDto.Tables.Add(campaignTable); var campaignRow = campaignTable.AddCampaignRow(ApplicationGuid, DateTime.MinValue, DateTime.MaxValue, "", DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, "", true, false, ""); return(new Promotion(promotionLanguageRow, promotionRow, campaignRow)); }
/// <summary> /// Processes the status command. /// </summary> /// <param name="items">The items.</param> void ProcessStatusCommand(string[] items) { for (int i = 0; i < items.Length; i++) { string[] keys = EcfListView.GetPrimaryKeyIdStringItems(items[i]); if (keys != null) { string id = keys[0]; using (TransactionScope scope = new TransactionScope()) { PromotionDto dto = PromotionManager.GetPromotionDto(Int32.Parse(id)); List <int> expressionList = new List <int>(); if (dto.Promotion.Count > 0) { if (dto.Promotion[0].Status == PromotionStatus.Active) { dto.Promotion[0].Status = PromotionStatus.Inactive; } else { dto.Promotion[0].Status = PromotionStatus.Active; } PromotionManager.SavePromotion(dto); } scope.Complete(); } } } }
public ActionResult CreatePromotion(PromotionDto promotionDto) { var promotion = mapper.Map <Promotion>(promotionDto); promotionService.CreatePromotion(promotion); return(Ok("Promotion placed successfully")); }
public async Task <ActionResult> Edit(int id, PromotionDto promotion) { if (id != promotion.PromotionId) { return(RedirectToAction("Edit", new { id })); } if (!ModelState.IsValid) { return(RedirectToAction("Edit", new { id })); } try { bool result = await _promo.UpdatePromotionWithId(promotion); if (result) { return(RedirectToAction(nameof(Index))); } return(RedirectToAction("Edit", new { id })); } catch { return(RedirectToAction("Error", "Home")); } }
public async Task <bool> UpdatePromotionWithId(PromotionDto promotionDto) { if (PromotionExists(promotionDto.PromotionId)) { string path = null; if (promotionDto.File != null) { path = _img.EditImage(promotionDto.File, promotionDto.OldImage); } Promotion promotion = await _ctx.Promotions.Where(p => p.PromotionId == promotionDto.PromotionId) .Select(p => new Promotion { CategoryForTabId = promotionDto.CategoryForTabId, ImagePath = !string.IsNullOrEmpty(path) ? path : p.ImagePath, PromotionAvailable = promotionDto.PromotionAvailable, PromotionId = p.PromotionId, PromotionName = promotionDto.PromotionName, PromotionDescription = promotionDto.PromotionDescription, PromotionExtra = promotionDto.PromotionExtra }).SingleOrDefaultAsync(); try { _ctx.Update(promotion); await _ctx.SaveChangesAsync(); return(true); } catch (Exception ex) { _logger.LogInformation($"The promotion could not be updated {ex.Message}"); } } return(false); }
public async Task <ActionResult> Create(bool sendToAll, PromotionDto promotion) { if (!ModelState.IsValid) { return(RedirectToAction("Create")); } try { var result = await _promo.AddPromotion(promotion, sendToAll); if (result.Item1) { if (result.Item2) { ViewData["Mail"] = "Success"; } else { ViewData["Mail"] = "Failure"; } return(RedirectToAction(nameof(Index))); } return(RedirectToAction("Create")); } catch { return(RedirectToAction("Error", "Home")); } }
public IActionResult EditPromotion(PromotionDto promotionDto) { Promotion promo = _mapper.Map <PromotionDto, Promotion>(promotionDto); if (ModelState.IsValid) { _promoService.EditPromotion(promo); var promoDto = _mapper.Map <Promotion, PromotionDto>(promo); return(Ok(promoDto)); } if (String.IsNullOrEmpty(promotionDto.PromotionName)) { return(BadRequest("You must provide a name for the promotion")); } if (promotionDto.Quantity <= 0) { return(BadRequest("You must provide a min quantity for the promotion")); } if (promotionDto.PromotionPrice <= 0) { return(BadRequest("You must provide a price offer for the promotion")); } return(BadRequest("Please provide valid promotion details")); }
/// <summary> /// Loads the data and data bind. /// </summary> /// <param name="sortExpression">The sort expression.</param> private void LoadDataAndDataBind(string sortExpression) { PromotionDto dto = PromotionManager.GetPromotionDto(); if (dto.Promotion != null) { PromotionDto.PromotionDataTable table = dto.Promotion; table.Columns.Add(new DataColumn("TotalUsed", typeof(Int32))); // Get existing statistics DataTable usageStatistics = PromotionManager.GetPromotionUsageStatistics(); // Populate extra column that can be used for display purpose foreach (PromotionDto.PromotionRow row in table) { int totalUsed = 0; System.Data.DataRow[] rows = usageStatistics.Select(String.Format("PromotionId = {0}", row.PromotionId)); if (rows != null && rows.Length > 0) { totalUsed = (int)rows[0]["TotalUsed"]; } row["TotalUsed"] = totalUsed; } DataView view = table.DefaultView; view.Sort = sortExpression; MyListView.DataSource = view; } MyListView.CurrentListView.PrimaryKeyId = EcfListView.MakePrimaryKeyIdString("PromotionId"); MyListView.DataBind(); }
public IActionResult OnGet(int?id) { var t = Request.Cookies["logon"]; if (t == null) { return(RedirectToPage("../Accounts/Login")); } if (t == "false") { return(RedirectToPage("../Accounts/Login")); } if (id == null) { return(NotFound()); } Promotion = _service.GetPromotion(id ?? default(int)); if (Promotion == null) { return(NotFound()); } return(Page()); }
/// <summary> /// Saves the promotion. /// </summary> /// <param name="dto">The dto.</param> public static void SavePromotion(PromotionDto dto) { if (dto == null) { throw new ArgumentNullException("dto", String.Format("PromotionDto can not be null")); } //TODO: check concurrency when updating the records //TODO: need to check security roles here, // The procedure will be following: // 1. Retrieve the record from the database for each category that is about to be updated // 2. Check Write permissions (if failed generate the error and exit) // 3. Otherwise proceed to update // Continue with security checks and other operations /* * foreach (PromotionDto.PromotionRow row in dto.Promotion.Rows) * { * // Check Security * IDataReader reader = DataHelper.CreateDataReader(dto.PromotionSecurity, String.Format("PromotionId = -1 or PromotionId = {0}", row.PromotionId)); * PermissionRecordSet recordSet = new PermissionRecordSet(PermissionHelper.ConvertReaderToRecords(reader)); * if (!PermissionManager.CheckPermission(PromotionScope.Promotion, Permission.Read, recordSet)) * { * row.Delete(); * continue; * } * } * */ PromotionAdmin admin = new PromotionAdmin(dto); admin.Save(); }
/// <summary> /// Gets the marketing helper. /// </summary> /// <param name="useCache">if set to <c>true</c> [use cache].</param> /// <returns></returns> private MarketingHelper GetMarketingHelper(bool useCache) { MarketingHelper helper = null; string cacheKey = MarketingCache.CreateCacheKey("MarketingHelper"); if (useCache) { object cachedObject = MarketingCache.Get(cacheKey); if (cachedObject != null) { helper = (MarketingHelper)cachedObject; } } // If marketing is not initialized, init it if (helper == null) { // Load promotion Dto PromotionDto promotionDto = PromotionManager.GetPromotionDto(FrameworkContext.Current.CurrentDateTime); // Get all the data from the database first helper = new MarketingHelper(CampaignManager.GetCampaignDto(), ExpressionManager.GetExpressionDto(), PolicyManager.GetPolicyDto(), promotionDto, SegmentManager.GetSegmentDto()); // Insert cache //if (useCache) MarketingCache.Insert(cacheKey, helper, MarketingConfiguration.Instance.CacheConfig.PromotionCollectionTimeout); } return(helper); }
public async Task <IActionResult> Edit( [Bind("Id,Title,Description,PromotionTypeId,PromotionStateId,Deleted,StartDate, EndDate,PromotionProductTypeId")] PromotionDto promotionDto) { var flag = false; if (ModelState.IsValid) { if (promotionDto.EndDate <= promotionDto.StartDate || promotionDto.EndDate <= DateTime.Now) { ModelState.AddModelError("EndDate", "结束时间不能小于开始时间或当前系统时间"); } else { flag = true; } } if (flag) { var promotion = _mapper.Map <Promotion>(promotionDto); _promotionContext.Promotions.Update(promotion); await _promotionContext.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewData["PromotionTypes"] = GeneratePromotionTypes(); ViewData["PromotionStates"] = GeneratePromotionStates(); ViewData["PromotionProductTypes"] = GeneratePromotionProductTypes(); return(View(promotionDto)); }
/// <summary> /// Loads the context. /// </summary> private void LoadContext() { if (PromotionId > 0) { PromotionDto promo = null; if (!this.IsPostBack && (!this.Request.QueryString.ToString().Contains("Callback=yes"))) // load fresh on initial load { promo = LoadFresh(); } else // load from session { promo = (PromotionDto)Session[_PromotionDtoEditSessionKey]; if (promo == null) { promo = LoadFresh(); } } // Put a dictionary key that can be used by other tabs IDictionary dic = new ListDictionary(); dic.Add(_PromotionDtoString, promo); // Call tabs load context ViewControl.LoadContext(dic); } }
/// <summary> /// Initializes a new instance of the <see cref="MarketingHelper"/> class. /// </summary> /// <param name="campaigns">The campaigns.</param> /// <param name="expressions">The expressions.</param> /// <param name="policies">The policies.</param> /// <param name="promotions">The promotions.</param> /// <param name="segments">The segments.</param> public MarketingHelper(CampaignDto campaigns, ExpressionDto expressions, PolicyDto policies, PromotionDto promotions, SegmentDto segments) { _Campaigns = campaigns; _Expressions = expressions; _Policies = policies; _Promotions = promotions; _Segments = segments; }
public static void MappingPromotion(this PromotionDto promotionDto, Promotion promotion) { promotion.Id = promotionDto.Id; promotion.Title = promotionDto.Title; promotion.StartDate = promotionDto.StartDate; promotion.FinishDate = promotionDto.FinishDate; promotion.Status = promotionDto.Status; }
public Promotion Create(PromotionDto Promotion) { var promotion = _mapper.Map <Promotion>(Promotion); _context.Add(promotion); _context.SaveChanges(); return(promotion); }
/// <summary> /// Saves the changes. /// </summary> /// <param name="context">The context.</param> public virtual void SaveChanges(IDictionary context) { _PromotionDto = (PromotionDto)context["PromotionDto"]; _Config = (PromotionConfig)context["Config"]; _PromotionDto.Promotion[0].PromotionGroup = _Config.Group; _PromotionDto.Promotion[0].PromotionType = _Config.Type; }
/// <summary> /// Loads the fresh. /// </summary> /// <returns></returns> private PromotionDto LoadFresh() { PromotionDto promo = PromotionManager.GetPromotionDto(PromotionId); // persist in session Session[_PromotionDtoEditSessionKey] = promo; return(promo); }
public IActionResult EditPromotion(int productId) { PromotionDto promotion = productsService.GetPriceOffer(productId); if (promotion == null) { return(BadRequest()); } return(View(PriceOfferForm, promotion)); }
public static Promotion MappingPromotion(this PromotionDto promotionDto) { return(new Promotion { Id = promotionDto.Id, Title = promotionDto.Title, StartDate = promotionDto.StartDate, FinishDate = promotionDto.FinishDate, Status = promotionDto.Status }); }
public async Task <(bool, bool)> AddPromotion(PromotionDto promoDto, bool sendToAll) { string path = null; if (promoDto.File != null) { path = _img.CreateImage(promoDto.File); } Promotion promotion = new Promotion { CategoryForTabId = promoDto.CategoryForTabId, ImagePath = path, PromotionAvailable = promoDto.PromotionAvailable, PromotionName = promoDto.PromotionName, PromotionDescription = promoDto.PromotionDescription, PromotionExtra = promoDto.PromotionExtra }; try { _ctx.Promotions.Add(promotion); await _ctx.SaveChangesAsync(); } catch (Exception ex) { _logger.LogInformation($"Promotion record not created: {ex.Message}"); return(false, false); } if (sendToAll) { var usersEmail = await _userManager.Users.Where(u => u.UserLikesMail).Select(u => u.Email).ToListAsync(); if (usersEmail.Count > 0) { string subject = "WE ARE EXCITED TO TELL YOU ABOUT OUR PROMOTION"; string message = $"Dear Customer,\n{promotion.PromotionName}\n{promotion.PromotionsInformation} \n\nWarm regards,\nNwisu."; try { await _email.SendEmailToAllAsync(usersEmail, subject, message); } catch (Exception ex) { _logger.LogInformation($"Cannot send mail: {ex.Message}"); return(true, false); } } return(true, false); } return(true, true); }
public IActionResult Promote(PromotionDto promotionDto) { try { return(CreatedAtAction("Promote", _dbService.Promote(promotionDto))); } catch (NotFoundException e) { return(NotFound("NotFoundException: " + e.Message + "\n" + e.StackTrace)); } catch (Exception e) { return(BadRequest("Exception: " + e.Message + "\n" + e.StackTrace)); } }
public IActionResult SavePromotion(int?productId, PromotionDto promotion) { if (productId == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(View(PriceOfferForm, promotion)); } productsService.SavePriceOffer(productId.Value, promotion); return(RedirectToAction(nameof(Index))); }
public IActionResult Update(int id, [FromBody] PromotionDto promotionDto) { var promotion = _mapper.Map <PromotionDto>(promotionDto); promotion.Id = id; try { _promotionService.Update(promotion, promotionDto.Consoles); return(Ok()); } catch (AppException ex) { return(BadRequest(new { message = ex.Message })); } }
private PromotionModel TransformToModelFrom(PromotionDto promotion) { return(new PromotionModel { Id = promotion.PromotionId, Name = promotion.PromotionName, BonusCode = promotion.BonusCode, Order = promotion.Order, UpdatedDate = promotion.UpdatedDate, DisplayName = promotion.DisplayName, ImageUrl = promotion.ImageUrl, BigImageUrl = promotion.BigImageUrl, Summary = promotion.Summary, Terms = promotion.Terms }); }
public IActionResult AddPromotion(PromotionDto promotionDto) { if (ModelState.IsValid) { var promotion = _mapper.Map <PromotionDto, Promotion>(promotionDto); if (promotion.Start > promotion.End) { return(BadRequest("The promotions start date must be prior to the end date")); } if (_promoService.AddPromotion(promotion)) { return(Ok(promotionDto)); } return(BadRequest("that promtion already exists")); } return(BadRequest("Invalid promotion settings")); }
/// <summary> /// Handles the SaveChanges event of the EditSaveControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void EditSaveControl_SaveChanges(object sender, SaveControl.SaveEventArgs e) { // Validate form if (!this.Page.IsValid) { e.RunScript = false; return; } PromotionDto promo = (PromotionDto)Session[_PromotionDtoEditSessionKey]; if (promo == null && PromotionId > 0) { promo = PromotionManager.GetPromotionDto(PromotionId); //Int32.Parse(Parameters["PromotionId"].ToString())); } if (PromotionId == 0) { promo = new PromotionDto(); } /* * // if we add a new promotion, remove all other segments from Dto that is passed to control that saves changes * if (PromotionId == 0 && promo != null && promo.Promotion.Count > 0) * { * PromotionDto.PromotionRow[] rows2del = (PromotionDto.PromotionRow[])promo.Promotion.Select(String.Format("{0} <> {1}", _PromotionIdString, PromotionId)); * if (rows2del != null) * foreach (PromotionDto.PromotionRow row in rows2del) * promo.Promotion.RemovePromotionRow(row); * }*/ IDictionary context = new ListDictionary(); context.Add(_PromotionDtoString, promo); ViewControl.SaveChanges(context); if (promo.HasChanges()) { PromotionManager.SavePromotion(promo); } // we don't need to store Dto in session any more Session.Remove(_PromotionDtoEditSessionKey); }
/// <summary> /// Processes the table events. /// </summary> /// <param name="promo">The promo.</param> private void ProcessTableEvents(PromotionDto promo) { foreach (GridItem item in _addedItems) { int expressionId = item[_ExpressionIdString] == null ? 0 : Int32.Parse(item[_ExpressionIdString].ToString()); /* * int nodeId = item[_CatalogNodeIdString] == null ? 0 : Int32.Parse(item[_CatalogNodeIdString].ToString()); * int entryId = item[_CatalogEntryIdString] == null ? 0 : Int32.Parse(item[_CatalogEntryIdString].ToString()); * */ string nodeId = item[_CatalogNodeIdString] == null ? String.Empty : item[_CatalogNodeIdString].ToString(); string entryId = item[_CatalogEntryIdString] == null ? String.Empty : item[_CatalogEntryIdString].ToString(); string catalogName = item[_CatalogNameString] == null ? String.Empty : item[_CatalogNameString].ToString(); PromotionDto.PromotionConditionRow row = promo.PromotionCondition.NewPromotionConditionRow(); row.CatalogEntryId = entryId.ToString(); row.CatalogName = catalogName; row.CatalogNodeId = nodeId.ToString(); row.ExpressionId = expressionId; row.PromotionId = promo.Promotion[0].PromotionId; promo.PromotionCondition.Rows.Add(row); } _addedItems.Clear(); foreach (GridItem item in _removedItems) { int id = Int32.Parse(item["PromotionConditionId"].ToString()); // find the existing one foreach (PromotionDto.PromotionConditionRow row in promo.PromotionCondition.Rows) { if (row.PromotionConditionId == id) { row.Delete(); } } } _removedItems.Clear(); }
/// <summary> /// Evals the specified filter with checkEntryLevelLimit /// </summary> /// <param name="filter"> The filter</param> /// <param name="checkEntryLevelLimit"> The check Entry Level Limit</param> public void Eval(PromotionFilter filter, bool checkEntryLevelLimit) { if (checkEntryLevelLimit) { Dictionary <PromotionDto.PromotionRow, decimal?> entryDiscountApplicationCount = new Dictionary <PromotionDto.PromotionRow, decimal?>(); PromotionDto promotionDto = PromotionManager.GetPromotionDto(FrameworkContext.Current.CurrentDateTime); foreach (PromotionDto.PromotionRow promotion in promotionDto.Promotion) { if (!promotion.IsMaxEntryDiscountQuantityNull()) { entryDiscountApplicationCount.Add(promotion, promotion.MaxEntryDiscountQuantity); } } MarketingContext.Current.EvaluatePromotions(true, this.PromotionContext, filter, entryDiscountApplicationCount, true); } else { Eval(filter); } }
/// <summary> /// Gets the display name. /// </summary> /// <param name="row">The row.</param> /// <param name="languageCode">The language code.</param> /// <returns></returns> private string GetDisplayName(PromotionDto.PromotionRow row, string languageCode) { PromotionDto.PromotionLanguageRow[] langRows = row.GetPromotionLanguageRows(); if (langRows != null && langRows.Length > 0) { foreach (PromotionDto.PromotionLanguageRow lang in langRows) { if (lang.LanguageCode.Equals(languageCode, StringComparison.OrdinalIgnoreCase)) { return lang.DisplayName; } } } return row.Name; }
private void CreatePromotion(PromotionDto dto, string name, decimal reward, PromotionType rewardType, string promotionType, string promotionGroup, int campaignId) { var promotionRow = dto.Promotion.NewPromotionRow(); promotionRow.ApplicationId = AppContext.Current.ApplicationId; promotionRow.Name = name; promotionRow.StartDate = DateTime.Today; promotionRow.EndDate = DateTime.Today.AddYears(1); promotionRow.Created = DateTime.UtcNow; promotionRow.ModifiedBy = "admin"; promotionRow.Status = "active"; promotionRow.OfferAmount = reward; promotionRow.OfferType = (int)rewardType; promotionRow.PromotionGroup = promotionGroup; promotionRow.CampaignId = campaignId; promotionRow.ExclusivityType = "none"; promotionRow.PromotionType = promotionType; promotionRow.PerOrderLimit = 0; promotionRow.ApplicationLimit = 0; promotionRow.CustomerLimit = 0; promotionRow.Priority = 1; promotionRow.CouponCode = ""; if (name.Equals("25 % off Mens Shoes")) { promotionRow.OfferAmount = 25m; promotionRow.OfferType = 0; } //In commerce manager, this promotion type is displayed quite differently from others. //The percentage based offer type has value "0" and value based offer type has value "1". //But in C# code, PromotionType.Percentage = 1 and PromotionType.ValueBased = 2 else if (name.Equals("$10 off shipping from Women's Shoes")) { promotionRow.OfferType = 1; } dto.Promotion.Rows.Add(promotionRow); return; }
private void CreatePromotions(int campaignId) { var dto = new PromotionDto(); CreatePromotion(dto, "25 % off Mens Shoes", 0.00m, PromotionType.Percentage, "EntryCustomDiscount", "entry", campaignId); CreatePromotion(dto, "$50 off Order over $500", 50.00m, PromotionType.ValueBased, "OrderVolumeDiscount", "order", campaignId); CreatePromotion(dto, "$10 off shipping from Women's Shoes", 10.00m, PromotionType.ValueBased, "BuySKUFromCategoryXGetDiscountedShipping", "shipping", campaignId); PromotionManager.SavePromotion(dto); dto = PromotionManager.GetPromotionDto(); foreach (var promotion in dto.Promotion) { foreach (var languageCode in new[] { "en", "sv" }) { var name = String.Empty; switch (promotion.PromotionId) { case 1: name = languageCode.Equals("en") ? "25 % off Mens Shoes" : "25% rabatt på herrskor"; break; case 2: name = languageCode.Equals("en") ? "$50 off Order over $500" : "$50 rabatt på order över $500"; break; case 3: name = languageCode.Equals("en") ? "$10 off shipping from Women's Shoes" : "$10 rabatt på frakt av Damskor"; break; } var promoLanguageRow = dto.PromotionLanguage.NewPromotionLanguageRow(); promoLanguageRow.PromotionId = promotion.PromotionId; promoLanguageRow.LanguageCode = languageCode; promoLanguageRow.DisplayName = name; dto.PromotionLanguage.Rows.Add(promoLanguageRow); } } PromotionManager.SavePromotion(dto); UpdatePromotionParams(); CreateExpression(1, "25 % off Mens Shoes"); CreateExpression(2, "$50 off Order over $500"); CreateExpression(3, "$10 off shipping from Women's Shoes"); }