public IActionResult DeleteProduct(int id)
        {
            if (id <= 0)
            {
                return(Error(HttpStatusCode.BadRequest, "id", "invalid id"));
            }

            var product = _productApiService.GetProductById(id);

            if (product == null)
            {
                return(Error(HttpStatusCode.NotFound, "product", "not found"));
            }

            var genericAttribute = _genericAttributeService.GetAttributesForEntity(product.Id, "Product").FirstOrDefault();

            if (genericAttribute != null)
            {
                _genericAttributeService.DeleteAttribute(genericAttribute);
            }

            _productService.DeleteProduct(product);

            //activity log
            CustomerActivityService.InsertActivity("DeleteProduct",
                                                   string.Format(LocalizationService.GetResource("ActivityLog.DeleteProduct"), product.Name), product);

            return(new RawJsonActionResult("{}"));
        }
Пример #2
0
        /// <summary>
        /// Gets customer events related to a shopping cart
        /// </summary>
        /// <returns>customer event</returns>
        public IPagedList <CameleoCustomerEvent> GetCustomerEventsFromShoppingCart(ICollection <ShoppingCartItem> ShoppingCartItems, int shoppingCartId, int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var tmpCustomerEvents = new List <CameleoCustomerEvent>();

            //Get cart item
            var cartItem = ShoppingCartItems
                           .Where(sci => sci.Id == shoppingCartId)
                           .FirstOrDefault();

            if (!(cartItem == null))
            {
                //Get customer event id from attributes
                var tmpAttributes = _genericAttributeService.GetAttributesForEntity(cartItem.Id, "ShoppingCartItem");
                foreach (var tmpAttribute in tmpAttributes)
                {
                    //Get customer event
                    int tmpId = 0;
                    if (int.TryParse(tmpAttribute.Value, out tmpId))
                    {
                        var tmpCustomerEvent = GetCustomerEventById(tmpId);
                        if (!(tmpCustomerEvent == null))
                        {
                            //Customer event found
                            tmpCustomerEvents.Add(tmpCustomerEvent);
                        }
                    }
                }
            }

            var records = new PagedList <CameleoCustomerEvent>(tmpCustomerEvents, pageIndex, pageSize);

            return(records);
        }
        public virtual IActionResult Activate([FromBody] AccountActivationRequest model)
        {
            var response = new AccountActivationResponse {
                Result = ResultType.Error
            };
            var customer = _customerService.GetCustomerByPhone(model.Mobile);

            if (customer == null)
            {
                response.Messages.Add(_localizationService.GetResource("Account.AccountActivation.customerNotExist"));
                return(BadRequest(response));
            }

            var customerToken = _genericAttributeService.GetAttributesForEntity(customer.Id, customer.GetType().Name)
                                .SingleOrDefault(a => a.Key == BopCustomerDefaults.AccountActivationTokenAttribute);

            if (!customer.IsValidToken(customerToken, model.Code))
            {
                response.Messages.Add(_localizationService.GetResource("Account.AccountActivation.WrongToken"));
                return(BadRequest(response));
            }

            //activate customer account
            customer.Active = true;
            _customerService.UpdateCustomer(customer);
            _genericAttributeService.SaveAttribute(customer, BopCustomerDefaults.AccountActivationTokenAttribute, "");

            response.Result = ResultType.Success;
            return(Ok(response));
        }
Пример #4
0
        public IActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                return(AccessDeniedKendoGridJson());
            }

            var pickupPoints = _MediaService.GetAllsMedia(pageIndex: command.Page - 1, pageSize: command.PageSize);
            var model        = pickupPoints.Select(point =>
            {
                return(new MediaModel()
                {
                    Id = point.Id,
                    Title = point.Title,
                    CreateDates = Tools.Core.Date.ConvertDateTime.ToShorShamsi(point.CreateDate),
                    FileExtention = point.FileExtention,
                    CategoryName = _MediaCategoryService.CategoryNavigation(_MediaCategoriesService.GetLastCategory(point.Id).Id),
                    CustomerName = _genericAttributeService.GetAttributesForEntity(point.UserId, "Customer").Where(a => a.Key == "LastName").FirstOrDefault().Value,
                });
            }).ToList();

            return(Json(new DataSourceResult
            {
                Data = model,
                Total = pickupPoints.TotalCount
            }));
        }
Пример #5
0
        public static TPropType GetAttribute <TPropType>(this IGenericAttributeService genericAttributeService, string entityName, int entityId, string key, int storeId = 0)
        {
            Guard.NotNull(genericAttributeService, nameof(genericAttributeService));
            Guard.NotEmpty(entityName, nameof(entityName));

            var props = genericAttributeService.GetAttributesForEntity(entityId, entityName);

            // little hack here (only for unit testing). we should write expect-return rules in unit tests for such cases
            if (props == null)
            {
                return(default(TPropType));
            }

            if (!props.Any(x => x.StoreId == storeId))
            {
                return(default(TPropType));
            }

            var prop = props.FirstOrDefault(ga =>
                                            ga.StoreId == storeId && ga.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); //should be culture invariant

            if (prop == null || prop.Value.IsEmpty())
            {
                return(default(TPropType));
            }

            return(prop.Value.Convert <TPropType>());
        }
        private void OnReqPassChangeAdded(int customerId)
        {
            // Get customer
            var customer = _customerService.GetCustomerById(customerId);

            if (customer == null)
            {
                throw new InvalidOperationException($"Coud not find customer with id \"{customerId}\"");
            }

            // Get existing password recovery token
            var passwordRecoveryTokenExists = _genericAttributeService
                                              .GetAttributesForEntity(customerId, CustomerGenericAttributeKey)
                                              .Any(attr => attr.Key == SystemCustomerAttributeNames.PasswordRecoveryToken);

            // Create password recovery token if none exists.
            if (!passwordRecoveryTokenExists)
            {
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.PasswordRecoveryToken, Guid.NewGuid().ToString());
            }

            // Remove password recovery token valid date. Unlike normal password recovery tokens, this should not expire.
            DateTime?generatedDateTime = null;

            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.PasswordRecoveryTokenDateGenerated, generatedDateTime);
        }
        /// <summary>
        /// Gets a specialized generic attributes collection for the given entity.
        /// Loaded data will be cached for the duration of the request.
        /// </summary>
        /// <param name="entity">The entity instance to get attributes for.</param>
        public static GenericAttributeCollection GetAttributesForEntity(this IGenericAttributeService service, BaseEntity entity)
        {
            Guard.NotNull(service, nameof(service));
            Guard.NotNull(entity, nameof(entity));

            return(service.GetAttributesForEntity(entity.GetEntityName(), entity.Id));
        }
        public static TPropType GetAttribute <TPropType>(this BaseEntity entity, string key,
                                                         IGenericAttributeService genericAttributeService)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            string keyGroup = entity.GetUnproxiedEntityType().Name;

            var props = genericAttributeService.GetAttributesForEntity(entity.Id, keyGroup);

            if (props == null)
            {
                return(default(TPropType));
            }

            props = props.ToList();
            if (!props.Any())
            {
                return(default(TPropType));
            }

            var prop = props.FirstOrDefault(ga => ga.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));

            if (prop == null || string.IsNullOrEmpty(prop.Value))
            {
                return(default(TPropType));
            }

            return(CommonHelper.To <TPropType>(prop.Value));
        }
        /// <summary>
        /// Get an attribute of an entity
        /// </summary>
        /// <typeparam name="TPropType">Property type</typeparam>
        /// <param name="entity">Entity</param>
        /// <param name="key">Key</param>
        /// <param name="genericAttributeService">GenericAttributeService</param>
        /// <param name="storeId">Load a value specific for a certain store; pass 0 to load a value shared for all stores</param>
        /// <returns>Attribute</returns>
        public static TPropType GetAttribute <TPropType>(this BaseEntity entity,
                                                         string key, IGenericAttributeService genericAttributeService, int storeId = 0)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            string keyGroup = entity.GetUnproxiedEntityType().Name;

            var props = genericAttributeService.GetAttributesForEntity(entity.Id, keyGroup);

            //little hack here (only for unit testing). we should write ecpect-return rules in unit tests for such cases
            if (props == null)
            {
                return(default(TPropType));
            }
            props = props.Where(x => x.StoreId == storeId).ToList();
            if (props.Count == 0)
            {
                return(default(TPropType));
            }

            var prop = props.FirstOrDefault(ga =>
                                            ga.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); //should be culture invariant

            if (prop == null || string.IsNullOrEmpty(prop.Value))
            {
                return(default(TPropType));
            }

            return(CommonHelper.To <TPropType>(prop.Value));
        }
Пример #10
0
        /// <summary>
        /// Delete guest customer records
        /// </summary>
        /// <param name="registrationFrom">Customer registration from; null to load all customers</param>
        /// <param name="registrationTo">Customer registration to; null to load all customers</param>
        /// <param name="onlyWithoutShoppingCart">A value indicating whether to delete customers only without shopping cart</param>
        /// <returns>Number of deleted customers</returns>
        public virtual int DeleteGuestCustomers(DateTime?registrationFrom, DateTime?registrationTo, bool onlyWithoutShoppingCart)
        {
            var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

            if (guestRole == null)
            {
                throw new SmartException("'Guests' role could not be loaded");
            }

            var query = _customerRepository.Table;

            if (registrationFrom.HasValue)
            {
                query = query.Where(c => registrationFrom.Value <= c.CreatedOnUtc);
            }
            if (registrationTo.HasValue)
            {
                query = query.Where(c => registrationTo.Value >= c.CreatedOnUtc);
            }
            query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Contains(guestRole.Id));
            if (onlyWithoutShoppingCart)
            {
                query = query.Where(c => !c.ShoppingCartItems.Any());
            }
            //no orders
            query = query.Where(c => !c.Orders.Any());
            //no customer content
            query = query.Where(c => !c.CustomerContent.Any());
            //ensure that customers doesn't have forum posts or topics
            query = query.Where(c => !c.ForumTopics.Any());
            query = query.Where(c => !c.ForumPosts.Any());
            //don't delete system accounts
            query = query.Where(c => !c.IsSystemAccount);
            var customers = query.ToList();

            int numberOfDeletedCustomers = 0;

            foreach (var c in customers)
            {
                try
                {
                    //delete from database
                    _customerRepository.Delete(c);
                    numberOfDeletedCustomers++;

                    //delete attributes
                    var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer");
                    foreach (var attribute in attributes)
                    {
                        _genericAttributeService.DeleteAttribute(attribute);
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }

            return(numberOfDeletedCustomers);
        }
Пример #11
0
        public async Task <IList <PrivacyPreferenceModel> > Handle(GetPrivacyPreference request, CancellationToken cancellationToken)
        {
            var model               = new List <PrivacyPreferenceModel>();
            var consentCookies      = _cookiePreference.GetConsentCookies();
            var savedCookiesConsent = await _genericAttributeService.GetAttributesForEntity <Dictionary <string, bool> >(request.Customer, SystemCustomerAttributeNames.ConsentCookies, request.Store.Id);

            foreach (var item in consentCookies)
            {
                var state = item.DefaultState ?? false;
                if (savedCookiesConsent != null && savedCookiesConsent.ContainsKey(item.SystemName))
                {
                    state = savedCookiesConsent[item.SystemName];
                }

                var privacyPreferenceModel = new PrivacyPreferenceModel {
                    Description    = await item.FullDescription(),
                    Name           = await item.Name(),
                    SystemName     = item.SystemName,
                    AllowToDisable = item.AllowToDisable,
                    State          = state,
                    DisplayOrder   = item.DisplayOrder
                };
                model.Add(privacyPreferenceModel);
            }
            return(model);
        }
Пример #12
0
        private void OnShipmentChange(Shipment args)
        {
            if (string.IsNullOrWhiteSpace(args.TrackingNumber))
            {
                return;
            }

            var genericAttrs = _genericAttributeService.GetAttributesForEntity(args.Id, "Shipment");

            // Events for tracking is not yet registered. We register and save this entry in the generic attributes
            if (genericAttrs.Any(g => g.Value.Equals(args.TrackingNumber)))
            {
                return;
            }

            //remove the old tracker
            var oldTrackAttr = genericAttrs.FirstOrDefault(g => g.Key.Equals(Constants.SHIPMENT_TRACK_NUMBER_ATTRIBUTE_NAME));

            if (oldTrackAttr != null && !oldTrackAttr.Value.Equals(args.TrackingNumber))
            {
                if (RemoveTracking(oldTrackAttr.Value))
                {
                    foreach (var genericAttribute in genericAttrs)
                    {
                        _genericAttributeService.DeleteAttribute(genericAttribute);
                    }
                }
            }

            //create the new tracking in Aftarship
            CreateTracking(args);
        }
Пример #13
0
        public ActionResult GenericAttributesSelect(string entityName, int entityId, GridCommand command)
        {
            var model = new GridModel <GenericAttributeModel>();

            var storeId = _services.StoreContext.CurrentStore.Id;

            ViewBag.StoreId = storeId;

            if (_services.Permissions.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                if (entityName.HasValue() && entityId > 0)
                {
                    var attributes = _genericAttributeService.GetAttributesForEntity(entityId, entityName);

                    model.Data = attributes
                                 .Where(x => x.StoreId == storeId || x.StoreId == 0)
                                 .Select(x => new GenericAttributeModel
                    {
                        Id         = x.Id,
                        EntityId   = x.EntityId,
                        EntityName = x.KeyGroup,
                        Key        = x.Key,
                        Value      = x.Value
                    })
                                 .ToList();

                    model.Total = model.Data.Count();
                }
                else
                {
                    model.Data = Enumerable.Empty <GenericAttributeModel>();
                }
            }
            else
            {
                model.Data = Enumerable.Empty <GenericAttributeModel>();

                NotifyAccessDenied();
            }

            return(new JsonResult
            {
                Data = model
            });
        }
        /// <summary>
        /// Get an attribute of an entity
        /// </summary>
        /// <typeparam name="TPropType">Property type</typeparam>
        /// <param name="entity">Entity</param>
        /// <param name="genericAttributeService">GenericAttributeService</param>
        /// <param name="key">Key</param>
        /// <param name="storeId">Load a value specific for a certain store; pass 0 to load a value shared for all stores</param>
        /// <returns>Attribute</returns>
        public static async Task <TPropType> GetAttribute <TPropType>(this BaseEntity entity, IGenericAttributeService genericAttributeService, string key, string storeId = "")
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            return(await genericAttributeService.GetAttributesForEntity <TPropType>(entity, key, storeId));
        }
Пример #15
0
        /// <summary>
        /// Delete guest customers using LINQ
        /// </summary>
        /// <param name="createdFromUtc">Created from</param>
        /// <param name="createdToUtc">Created to</param>
        /// <returns>Number of delete customers</returns>
        protected virtual int DeleteGuestCustomersUseLinq(DateTime?createdFromUtc, DateTime?createdToUtc)
        {
            var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

            if (guestRole == null)
            {
                throw new GameException("'Guests' role could not be loaded");
            }

            var query = _customerRepository.Table;

            if (createdFromUtc.HasValue)
            {
                query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc);
            }
            if (createdToUtc.HasValue)
            {
                query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc);
            }
            query = query.Where(c => c.CustomerCustomerRoleMapping.Select(cr => cr.CustomerRoleId).Contains(guestRole.Id));
            //don't delete system accounts
            query = query.Where(c => !c.IsSystemAccount);

            //only distinct customers (group by ID)
            query = from c in query
                    group c by c.Id
                    into cGroup
                    orderby cGroup.Key
                    select cGroup.FirstOrDefault();

            query = query.OrderBy(c => c.Id);
            var customers = query.ToList();

            var totalRecordsDeleted = 0;

            foreach (var c in customers)
            {
                try
                {
                    //delete attributes
                    var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer");
                    _genericAttributeService.DeleteAttributes(attributes);

                    //delete from database
                    _customerRepository.Delete(c);
                    totalRecordsDeleted++;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }
            return(totalRecordsDeleted);
        }
        public static TPropType GetAttribute <TPropType>(this IGenericAttributeService genericAttributeService, string entityName, int entityId, string key, int storeId = 0)
        {
            Guard.NotNull(genericAttributeService, nameof(genericAttributeService));
            Guard.NotEmpty(entityName, nameof(entityName));

            var attrs = genericAttributeService.GetAttributesForEntity(entityId, entityName);

            // little hack here (only for unit testing). we should write expect-return rules in unit tests for such cases
            if (attrs == null)
            {
                return(default);
Пример #17
0
        public ActionResult GenericAttributesSelect(string entityName, int entityId, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                return(AccessDeniedView());
            }

            var storeId = _storeContext.CurrentStore.Id;

            ViewBag.StoreId = storeId;

            var model = new List <GenericAttributeModel>();

            if (entityName.HasValue() && entityId > 0)
            {
                var attributes = _genericAttributeService.GetAttributesForEntity(entityId, entityName);
                var query      = from attr in attributes
                                 where attr.StoreId == storeId || attr.StoreId == 0
                                 select new GenericAttributeModel
                {
                    Id         = attr.Id,
                    EntityId   = attr.EntityId,
                    EntityName = attr.KeyGroup,
                    Key        = attr.Key,
                    Value      = attr.Value
                };
                model.AddRange(query);
            }


            var result = new GridModel <GenericAttributeModel>
            {
                Data  = model,
                Total = model.Count
            };

            return(new JsonResult
            {
                Data = model
            });
        }
        public IActionResult GenericAttributesList(GridCommand command, string entityName, int entityId)
        {
            var storeId = Services.StoreContext.CurrentStore.Id;

            ViewBag.StoreId = storeId;

            var attributesItems = new List <GenericAttributeModel>();

            if (entityName.HasValue() && entityId > 0)
            {
                var infos = GetGenericAttributesInfos(entityName);
                if (infos.ReadPermission.IsEmpty() || Services.Permissions.Authorize(infos.ReadPermission))
                {
                    var attributes = _genericAttributeService
                                     .GetAttributesForEntity(entityName, entityId).UnderlyingEntities
                                     .AsQueryable()
                                     .ApplyGridCommand(command);

                    attributesItems = attributes
                                      .Where(x => x.StoreId == storeId || x.StoreId == 0)
                                      .OrderBy(x => x.Key)
                                      .Select(x => new GenericAttributeModel
                    {
                        Id = x.Id,
                        AttributeEntityId = x.EntityId,
                        EntityName        = x.KeyGroup,
                        Key   = x.Key,
                        Value = x.Value
                    })
                                      .ToList();
                }
            }

            var gridModel = new GridModel <GenericAttributeModel>
            {
                Rows  = attributesItems,
                Total = attributesItems.Count
            };

            return(Json(gridModel));
        }
        public IViewComponentResult Invoke(bool showNote)
        {
            //#region Shipping notes
            //public string ShippingNote { get; set; }
            //public bool DropShip { get; set; }
            //public bool ResidentialAddress { get; set; }
            //public string ShipToCompanyName { get; set; }
            //#endregion


            var customerId            = _workContext.CurrentCustomer.Id;
            var orderNoteExt          = string.Empty;
            var shipToCompanyNameExt  = string.Empty;
            var dropShipExt           = false;
            var residentialAddressExt = false;

            var gAttrs = _genericAttributeService.GetAttributesForEntity(customerId, "Customer").ToList();

            foreach (var attr in gAttrs)
            {
                if (attr.Key == "OrderNoteExt")
                {
                    orderNoteExt = attr.Value;
                }
                else if (attr.Key == "ShipToCompanyNameExt")
                {
                    shipToCompanyNameExt = attr.Value;
                }
                else if (attr.Key == "DropShipExt")
                {
                    dropShipExt = attr.Value == "true"?true:false;
                }
                else if (attr.Key == "ResidentialAddressExt")
                {
                    residentialAddressExt = attr.Value == "true" ? true : false;
                }
            }


            //_genericAttributeService.SaveAttribute(eventMessage.Customer, SystemCustomerAttributeNames.FirstName, firstName);

            var model = new ExtraOrderInfoModel
            {
                CustomerId         = customerId,
                ShowNote           = showNote,
                DropShip           = dropShipExt,
                Note               = orderNoteExt,
                ResidentialAddress = residentialAddressExt,
                ShipToCompanyName  = shipToCompanyNameExt,
            };

            return(View(model));
        }
Пример #20
0
        public ActionResult GenericAttributesSelect(string entityName, int entityId, GridCommand command)
        {
            var model = new GridModel <GenericAttributeModel>
            {
                Data = Enumerable.Empty <GenericAttributeModel>()
            };

            var storeId = _services.StoreContext.CurrentStore.Id;

            ViewBag.StoreId = storeId;

            if (entityName.HasValue() && entityId > 0)
            {
                var infos = GetGenericAttributesInfos(entityName);
                if (infos.ReadPermission.IsEmpty() || Services.Permissions.Authorize(infos.ReadPermission))
                {
                    var attributes = _genericAttributeService.GetAttributesForEntity(entityId, entityName);

                    model.Data = attributes
                                 .Where(x => x.StoreId == storeId || x.StoreId == 0)
                                 .OrderBy(x => x.Key)
                                 .Select(x => new GenericAttributeModel
                    {
                        Id         = x.Id,
                        EntityId   = x.EntityId,
                        EntityName = x.KeyGroup,
                        Key        = x.Key,
                        Value      = x.Value
                    })
                                 .ToList();

                    model.Total = model.Data.Count();
                }
            }

            return(new JsonResult
            {
                Data = model
            });
        }
Пример #21
0
        public static GenericAttribute GetAttributeByKey(this IGenericAttributeService genericAttributeService, BaseEntity entity, string key, int storeId = 0)
        {
            var entityName = entity.GetUnproxiedEntityType().Name;
            var ga         = genericAttributeService.GetAttributesForEntity(entity.Id, entityName)
                             .FirstOrDefault(
                x =>
                x.Key == key &&
                x.StoreId == storeId);

            if (ga != null) //weird but it works this way only
            {
                ga = genericAttributeService.GetAttributeById(ga.Id);
            }
            return(ga);
        }
        public virtual async Task <bool?> IsEnable(Customer customer, Store store, string cookieSystemName)
        {
            bool?result = default(bool?);
            var  savedCookiesConsent = await _genericAttributeService.GetAttributesForEntity <Dictionary <string, bool> >(customer, SystemCustomerAttributeNames.ConsentCookies, store.Id);

            if (savedCookiesConsent != null)
            {
                if (savedCookiesConsent.ContainsKey(cookieSystemName))
                {
                    result = savedCookiesConsent[cookieSystemName];
                }
            }

            return(result);
        }
        public ActionResult CustomerTabEditor(int Id = 0)
        {
            if (Id == 0)
            {
                return(null);
            }
            var visibleAttribute = _genericAttributeService.GetAttributesForEntity(Id, "Customer").FirstOrDefault(x => x.Key == "hideProfile");
            var model            = new MobSocialCustomerModel
            {
                CustomerId  = Id,
                HideProfile = visibleAttribute != null && visibleAttribute.Value == "True"
            };

            return(View(ViewHelpers.GetCorrectViewPath("Views/Customer/CustomerTabContents.cshtml"), model));
        }
        private void PrepareProductGenericAttributes(Product product, ProductDto productDto)
        {
            var attributes = _genericAttributeService.GetAttributesForEntity(product.Id, "Product");

            attributes = attributes.Where(a => a.Key != "nop.product.admindid" && a.Key != "nop.product.attributevalue.recordid" && a.Key != "nop.product.attribute.combination.records" && a.Key != "nop.product.attribute.combination.admind_id").ToList();

            productDto.DtoGenericAttributes = new List <ProductGenericAttributeDto>();
            foreach (var attr in attributes)
            {
                productDto.DtoGenericAttributes.Add(new ProductGenericAttributeDto()
                {
                    Name  = attr.Key.Replace("nop.product.", ""),
                    Value = attr.Value
                });
            }
        }
Пример #25
0
        public CartOffer ProcessCartOfferByProfileId(int profileId, string shippingCountryCode, int testOfferRuleId = 0)
        {
            var gas = _genericAttributeService.GetAttributesForEntity(profileId, "Profile");

            //get promocode
            var gaDiscountCouponCode = gas.FirstOrDefault(ga => ga.Key == SystemCustomerAttributeNames.DiscountCouponCode);
            var discountCouponCode   = string.Empty;

            if (gaDiscountCouponCode != null)
            {
                discountCouponCode = gaDiscountCouponCode.Value;
            }

            var cartOffer = _cartOfferProcessor.ProcessCart(profileId, shippingCountryCode, discountCouponCode, testOfferRuleId);

            return(cartOffer);
        }
        public ActionResult SMSDelete(ListSMSModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new DataSourceResult {
                    Errors = ModelState.SerializeErrors()
                }));
            }

            var storeId            = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var sendInBlueSettings = _settingService.LoadSetting <SendInBlueSettings>(storeId);

            //delete generic attributes
            var message = _messageTemplateService.GetMessageTemplateById(model.MessageId);

            if (message != null)
            {
                var attributes   = _genericAttributeService.GetAttributesForEntity(message.Id, "MessageTemplate");
                var smsAttribute = attributes.FirstOrDefault(x => x.Key == "UseSMS");
                if (smsAttribute != null)
                {
                    _genericAttributeService.DeleteAttribute(smsAttribute);
                }
                smsAttribute = attributes.FirstOrDefault(x => x.Key == "SMSText");
                if (smsAttribute != null)
                {
                    _genericAttributeService.DeleteAttribute(smsAttribute);
                }
                smsAttribute = attributes.FirstOrDefault(x => x.Key == "PhoneTypeId");
                if (smsAttribute != null)
                {
                    _genericAttributeService.DeleteAttribute(smsAttribute);
                }
            }

            //update list of the message templates which are sending in SMS
            if (sendInBlueSettings.SMSMessageTemplatesIds.Contains(model.MessageId))
            {
                sendInBlueSettings.SMSMessageTemplatesIds.Remove(model.MessageId);
                _settingService.SaveSetting(sendInBlueSettings, x => x.SMSMessageTemplatesIds, storeId, false);
                _settingService.ClearCache();
            }

            return(new NullJsonResult());
        }
Пример #27
0
        public static TPropType GetAttribute <TPropType>(this IEntity entity, string key, IGenericAttributeService service = null)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (service == null)
            {
                service = EngineContext.Current.Resolve <IGenericAttributeService>();
            }

            string entityId   = string.Join("|", entity.KeyValues);
            string entityType = GetUnproxiedEntityType(entity).Name;

            var props = service.GetAttributesForEntity(entityId, entityType);

            //little hack here (only for unit testing). we should write expect-return rules in unit tests for such cases
            if (props == null)
            {
                return(default(TPropType));
            }

            if (!props.Any())
            {
                return(default(TPropType));
            }

            var prop = props.FirstOrDefault(x => x.Property.Equals(key, StringComparison.InvariantCultureIgnoreCase));

            if (prop == null || string.IsNullOrEmpty(prop.Value))
            {
                return(default(TPropType));
            }

            return(prop.Value.ConvertTo <TPropType>());
        }
        /// <summary>
        /// Uninstall the plugin
        /// </summary>
        public override void Uninstall()
        {
            //settings
            _settingService.DeleteSetting <FraudLabsProSettings>();

            //generic attributes
            var orders = _orderService.SearchOrders();

            foreach (var order in orders)
            {
                var genericAttributes = _genericAttributeService.GetAttributesForEntity(order.Id, order.GetType().Name).ToList()
                                        .Where(w => w.Key.Equals(FraudLabsProDefaults.OrderResultAttribute) || w.Key.Equals(FraudLabsProDefaults.OrderStatusAttribute))
                                        .ToArray();
                if (genericAttributes.Any())
                {
                    _genericAttributeService.DeleteAttributes(genericAttributes);
                }
            }

            //locales
            _localizationService.DeletePluginLocaleResources("Plugins.Misc.FraudLabsPro");

            base.Uninstall();
        }
Пример #29
0
        public IActionResult GetProfile()
        {
            var response = new ProfileResponse {
                Result = ResultType.Error
            };
            var customer = _workContext.CurrentCustomer;

            if (customer == null)
            {
                response.Messages.Add(_localizationService.GetResource("Account.AccountActivation.customerNotExist"));
                return(BadRequest(response));
            }

            var genericAttributes = _genericAttributeService.GetAttributesForEntity(customer.Id, customer.GetType().Name);

            response.FirstName    = genericAttributes.SingleOrDefault(a => a.Key == BopCustomerDefaults.FirstName)?.Value;
            response.LastName     = genericAttributes.SingleOrDefault(a => a.Key == BopCustomerDefaults.LastName)?.Value;
            response.Email        = genericAttributes.SingleOrDefault(a => a.Key == BopCustomerDefaults.Email)?.Value;
            response.NationalCode = genericAttributes.SingleOrDefault(a => a.Key == BopCustomerDefaults.NationalCode)?.Value;
            //response.BirthDate = DateTimeOffset.Parse(genericAttributes.SingleOrDefault(a => a.Key == BopCustomerDefaults.BirthDate)?.Value);
            //response.Gender = bool.Parse(genericAttributes.SingleOrDefault(a => a.Key == BopCustomerDefaults.Gender)?.Value);
            response.Result = ResultType.Success;
            return(Ok(response));
        }
        public virtual IActionResult Edit(int id)
        {
            var model = new GenericModel {
                Id = id
            };
            var gAttrs = _genericAttributeService.GetAttributesForEntity(id, "Product").ToList();

            foreach (var attr in gAttrs)
            {
                switch (attr.Key)
                {
                case "ExcludeGoogleFeed":
                    model.ExcludeGoogleFeed = bool.Parse(attr.Value);
                    break;

                case "Color":
                    model.Color = attr.Value;
                    break;
                }
            }


            return(View("~/Plugins/Misc.ProductWizard/Views/GenericAttribs/Edit.cshtml", model));
        }