Esempio n. 1
0
        public virtual Task UpdateTaskAsync(TaskDescriptor task)
        {
            Guard.NotNull(task, nameof(task));

            try
            {
                _db.TryUpdate(task);
                return(_db.SaveChangesAsync());
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
Esempio n. 2
0
        /// <inheritdoc />
        public override async Task <SignInResult> PasswordSignInAsync(Customer user, string password, bool isPersistent, bool lockoutOnFailure)
        {
            if (user == null || user.Deleted)
            {
                return(SignInResult.Failed);
            }

            if (!user.Active)
            {
                return(SignInResult.NotAllowed);
            }

            if (!user.IsRegistered())
            {
                return(SignInResult.NotAllowed);
            }

            var result = await base.PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);

            if (result.Succeeded)
            {
                user.LastLoginDateUtc = DateTime.UtcNow;
                _db.TryUpdate(user);
                await _db.SaveChangesAsync();
            }

            return(result);
        }
Esempio n. 3
0
        /// <inheritdoc />
        public override async Task <SignInResult> PasswordSignInAsync(Customer user, string password, bool isPersistent, bool lockoutOnFailure)
        {
            if (user == null || user.Deleted)
            {
                return(SignInResult.Failed);
            }

            if (!user.Active)
            {
                // TODO: (mh) (core) We should return an error message for the user saying "Please check you email account for an activation link".
                return(SignInResult.NotAllowed);
            }

            if (!user.IsRegistered())
            {
                return(SignInResult.NotAllowed);
            }

            var result = await base.PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);

            if (result.Succeeded)
            {
                user.LastLoginDateUtc = DateTime.UtcNow;
                _db.TryUpdate(user);
                await _db.SaveChangesAsync();
            }

            return(result);
        }
Esempio n. 4
0
        protected virtual async Task AddItemToCartAsync(AddToCartContext ctx)
        {
            if (ctx.Item != null)
            {
                ctx.Customer.ShoppingCartItems.Add(ctx.Item);

                if (!ctx.ChildItems.IsNullOrEmpty())
                {
                    foreach (var childItem in ctx.ChildItems)
                    {
                        childItem.ParentItemId = ctx.Item.Id;
                    }

                    ctx.Customer.ShoppingCartItems.AddRange(ctx.ChildItems);
                }

                _db.TryUpdate(ctx.Customer);
                await _db.SaveChangesAsync();
            }
        }
        protected virtual async Task AddItemToCartAsync(AddToCartContext ctx)
        {
            Guard.NotNull(ctx, nameof(ctx));
            Guard.NotNull(ctx.Item, nameof(ctx.Item));

            var customer = ctx.Customer ?? _workContext.CurrentCustomer;

            customer.ShoppingCartItems.Add(ctx.Item);

            if (ctx.ChildItems.Any())
            {
                foreach (var childItem in ctx.ChildItems)
                {
                    childItem.ParentItemId = ctx.Item.Id;
                }

                customer.ShoppingCartItems.AddRange(ctx.ChildItems);
            }

            _db.TryUpdate(customer);
            await _db.SaveChangesAsync();
        }
Esempio n. 6
0
        public Task UpdateTaskAsync(ITaskDescriptor task)
        {
            Guard.IsTypeOf <TaskDescriptor>(task);

            try
            {
                _db.TryUpdate((TaskDescriptor)task);
                return(_db.SaveChangesAsync());
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
Esempio n. 7
0
        public async Task <IdentityResult> UpdateAsync(Customer user, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Guard.NotNull(user, nameof(user));

            // TODO: (core) Add Customer.ConcurrencyStamp field (?)
            //user.ConcurrencyStamp = Guid.NewGuid().ToString();
            _db.TryUpdate(user);

            try
            {
                await SaveChanges(cancellationToken);
            }
            catch (DbUpdateConcurrencyException)
            {
                return(Failed(ErrorDescriber.ConcurrencyFailure()));
            }

            return(IdentityResult.Success);
        }
Esempio n. 8
0
        private async Task <(MediaFile Copy, bool IsDupe)> InternalCopyFile(
            MediaFile file,
            MediaPathData destPathData,
            bool copyData,
            DuplicateEntryHandling dupeEntryHandling,
            Func <Task <MediaFile> > dupeFileSelector,
            Func <MediaPathData, Task> uniqueFileNameChecker)
        {
            // Find dupe and handle
            var isDupe = false;

            var dupe = await dupeFileSelector();

            if (dupe != null)
            {
                switch (dupeEntryHandling)
                {
                case DuplicateEntryHandling.Skip:
                    await uniqueFileNameChecker(destPathData);

                    return(dupe, true);

                case DuplicateEntryHandling.ThrowError:
                    var fullPath = destPathData.FullPath;
                    await uniqueFileNameChecker(destPathData);

                    throw _exceptionFactory.DuplicateFile(fullPath, ConvertMediaFile(dupe), destPathData.FullPath);

                case DuplicateEntryHandling.Rename:
                    await uniqueFileNameChecker(destPathData);

                    dupe = null;
                    break;

                case DuplicateEntryHandling.Overwrite:
                    if (file.FolderId == destPathData.Folder.Id)
                    {
                        throw new IOException(T("Admin.Media.Exception.Overwrite"));
                    }
                    break;
                }
            }

            isDupe = dupe != null;
            var copy = dupe ?? new MediaFile();

            // Simple clone
            MapMediaFile(file, copy);

            // Set folder id
            copy.FolderId = destPathData.Folder.Id;

            // A copied file cannot stay in deleted state
            copy.Deleted = false;

            // Set name stuff
            if (!copy.Name.EqualsNoCase(destPathData.FileName))
            {
                copy.Name      = destPathData.FileName;
                copy.Extension = destPathData.Extension;
                copy.MimeType  = destPathData.MimeType;
            }

            // Save to DB
            if (isDupe)
            {
                _db.TryUpdate(copy);
            }
            else
            {
                _db.MediaFiles.Add(copy);
            }

            // Copy data: blob, alt, title etc.
            if (copyData)
            {
                await InternalCopyFileData(file, copy);
            }

            return(copy, isDupe);
        }
        private async Task MapRegisterModelToCustomerAsync(Customer customer, RegisterModel model)
        {
            // Properties
            if (_dateTimeSettings.AllowCustomersToSetTimeZone)
            {
                customer.TimeZoneId = model.TimeZoneId;
            }

            // VAT number
            if (_taxSettings.EuVatEnabled)
            {
                customer.GenericAttributes.VatNumber = model.VatNumber;

                var vatCheckResult = await _taxService.GetVatNumberStatusAsync(model.VatNumber);

                customer.VatNumberStatusId = (int)vatCheckResult.Status;

                // Send VAT number admin notification.
                if (model.VatNumber.HasValue() && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                {
                    await _messageFactory.SendNewVatSubmittedStoreOwnerNotificationAsync(customer, model.VatNumber, vatCheckResult.Address, _localizationSettings.DefaultAdminLanguageId);
                }
            }

            // Form fields
            customer.FirstName = model.FirstName;
            customer.LastName  = model.LastName;

            if (_customerSettings.CompanyEnabled)
            {
                customer.Company = model.Company;
            }

            if (_customerSettings.DateOfBirthEnabled)
            {
                try
                {
                    customer.BirthDate = new DateTime(model.DateOfBirthYear.Value, model.DateOfBirthMonth.Value, model.DateOfBirthDay.Value);
                }
                catch
                {
                }
            }

            if (_customerSettings.CustomerNumberMethod == CustomerNumberMethod.AutomaticallySet && customer.CustomerNumber.IsEmpty())
            {
                customer.CustomerNumber = customer.Id.Convert <string>();
            }
            if (_customerSettings.GenderEnabled)
            {
                customer.Gender = model.Gender;
            }
            if (_customerSettings.ZipPostalCodeEnabled)
            {
                customer.GenericAttributes.ZipPostalCode = model.ZipPostalCode;
            }
            if (_customerSettings.CountryEnabled)
            {
                customer.GenericAttributes.CountryId = model.CountryId;
            }
            if (_customerSettings.StreetAddressEnabled)
            {
                customer.GenericAttributes.StreetAddress = model.StreetAddress;
            }
            if (_customerSettings.StreetAddress2Enabled)
            {
                customer.GenericAttributes.StreetAddress2 = model.StreetAddress2;
            }
            if (_customerSettings.CityEnabled)
            {
                customer.GenericAttributes.City = model.City;
            }
            if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
            {
                customer.GenericAttributes.StateProvinceId = model.StateProvinceId;
            }
            if (_customerSettings.PhoneEnabled)
            {
                customer.GenericAttributes.Phone = model.Phone;
            }
            if (_customerSettings.FaxEnabled)
            {
                customer.GenericAttributes.Fax = model.Fax;
            }

            // Newsletter subscription
            if (_customerSettings.NewsletterEnabled && model.Newsletter)
            {
                var subscription = await _db.NewsletterSubscriptions
                                   .ApplyMailAddressFilter(customer.Email, Services.StoreContext.CurrentStore.Id)
                                   .FirstOrDefaultAsync();

                if (subscription != null)
                {
                    subscription.Active = true;
                }
                else
                {
                    subscription = new NewsletterSubscription
                    {
                        NewsletterSubscriptionGuid = Guid.NewGuid(),
                        Email             = customer.Email,
                        Active            = true,
                        CreatedOnUtc      = DateTime.UtcNow,
                        StoreId           = Services.StoreContext.CurrentStore.Id,
                        WorkingLanguageId = Services.WorkContext.WorkingLanguage.Id
                    };

                    _db.NewsletterSubscriptions.Add(subscription);
                }

                await _db.SaveChangesAsync();
            }

            // Insert default address (if possible).
            var defaultAddress = new Address
            {
                Title           = customer.Title,
                FirstName       = customer.FirstName,
                LastName        = customer.LastName,
                Email           = customer.Email,
                Company         = customer.Company,
                CountryId       = customer.GenericAttributes.CountryId,
                ZipPostalCode   = customer.GenericAttributes.ZipPostalCode,
                StateProvinceId = customer.GenericAttributes.StateProvinceId,
                City            = customer.GenericAttributes.City,
                Address1        = customer.GenericAttributes.StreetAddress,
                Address2        = customer.GenericAttributes.StreetAddress2,
                PhoneNumber     = customer.GenericAttributes.Phone,
                FaxNumber       = customer.GenericAttributes.Fax,
                CreatedOnUtc    = customer.CreatedOnUtc
            };

            if (await _addressService.IsAddressValidAsync(defaultAddress))
            {
                // Set default addresses.
                customer.Addresses.Add(defaultAddress);
                customer.BillingAddress  = defaultAddress;
                customer.ShippingAddress = defaultAddress;
            }

            _db.TryUpdate(customer);
            await _db.SaveChangesAsync();
        }
Esempio n. 10
0
        public async Task <IActionResult> ReturnRequestSubmit(int id /* orderId */, SubmitReturnRequestModel model)
        {
            var order = await _db.Orders.FindByIdAsync(id);

            var customer = Services.WorkContext.CurrentCustomer;

            if (order == null || customer.Id != order.CustomerId)
            {
                return(new UnauthorizedResult());
            }

            if (!_orderProcessingService.IsReturnRequestAllowed(order))
            {
                return(RedirectToRoute("Homepage"));
            }

            foreach (var orderItem in order.OrderItems)
            {
                var form = Request.Form;

                var quantity = 0;
                foreach (var formKey in form.Keys)
                {
                    if (formKey.EqualsNoCase($"quantity{orderItem.Id}"))
                    {
                        _ = int.TryParse(form[formKey], out quantity);
                        break;
                    }
                }

                if (quantity > 0)
                {
                    var rr = new ReturnRequest
                    {
                        StoreId             = Services.StoreContext.CurrentStore.Id,
                        OrderItemId         = orderItem.Id,
                        Quantity            = quantity,
                        CustomerId          = customer.Id,
                        ReasonForReturn     = model.ReturnReason,
                        RequestedAction     = model.ReturnAction,
                        CustomerComments    = model.Comments,
                        StaffNotes          = string.Empty,
                        ReturnRequestStatus = ReturnRequestStatus.Pending
                    };

                    customer.ReturnRequests.Add(rr);

                    _db.TryUpdate(customer);
                    await _db.SaveChangesAsync();

                    model.AddedReturnRequestIds.Add(rr.Id);

                    // Notify store owner here by sending an email.
                    await _messageFactory.SendNewReturnRequestStoreOwnerNotificationAsync(rr, orderItem, _localizationSettings.DefaultAdminLanguageId);
                }
            }

            model = await PrepareReturnRequestModelAsync(model, order);

            if (model.AddedReturnRequestIds.Any())
            {
                model.Result = T("ReturnRequests.Submitted");
            }
            else
            {
                NotifyWarning(T("ReturnRequests.NoItemsSubmitted"));
            }

            return(View(model));
        }
Esempio n. 11
0
        public virtual async Task <CreateMessageResult> CreateMessageAsync(MessageContext messageContext, bool queue, params object[] modelParts)
        {
            Guard.NotNull(messageContext, nameof(messageContext));

            modelParts ??= Array.Empty <object>();

            // Handle TestMode
            if (messageContext.TestMode && modelParts.Length == 0)
            {
                modelParts = await GetTestModelsAsync(messageContext);
            }

            ValidateMessageContext(messageContext, ref modelParts);

            // Create and assign model.
            var model = messageContext.Model = new TemplateModel();

            // Do not create message if the template does not exist, is not authorized or not active.
            if (messageContext.MessageTemplate == null)
            {
                return(new CreateMessageResult {
                    Model = model, MessageContext = messageContext
                });
            }

            // Add all global template model parts.
            await _modelProvider.AddGlobalModelPartsAsync(messageContext);

            // Add specific template models for passed parts.
            foreach (var part in modelParts)
            {
                if (model != null)
                {
                    await _modelProvider.AddModelPartAsync(part, messageContext);
                }
            }

            // Give implementors the chance to customize the final template model.
            await _eventPublisher.PublishAsync(new MessageModelCreatedEvent(messageContext, model));

            var messageTemplate = messageContext.MessageTemplate;
            var languageId      = messageContext.Language.Id;

            // Render templates
            var to      = RenderEmailAddress(messageTemplate.To, messageContext);
            var replyTo = RenderEmailAddress(messageTemplate.ReplyTo, messageContext, false);
            var bcc     = RenderTemplate(messageTemplate.GetLocalized((x) => x.BccEmailAddresses, languageId), messageContext, false);

            var subject = RenderTemplate(messageTemplate.GetLocalized((x) => x.Subject, languageId), messageContext);

            ((dynamic)model).Email.Subject = subject;

            var body = RenderBodyTemplate(messageContext);

            // CSS inliner
            body = InlineCss(body, model);

            // Model tree
            var modelTree     = _modelProvider.BuildModelTree(model);
            var modelTreeJson = JsonConvert.SerializeObject(modelTree, Formatting.None);

            if (modelTreeJson != messageTemplate.LastModelTree)
            {
                messageContext.MessageTemplate.LastModelTree = modelTreeJson;
                if (!messageTemplate.IsTransientRecord())
                {
                    _db.TryUpdate(messageContext.MessageTemplate);
                    await _db.SaveChangesAsync();
                }
            }

            // Create queued email from template
            var qe = new QueuedEmail
            {
                Priority = 5,
                From     = messageContext.SenderMailAddress ?? messageContext.EmailAccount.ToMailAddress(),
                //To = to.ToString(),
                To             = "",        // TODO: (mh) (core) Uncomment once template engine is available.
                Bcc            = bcc,
                ReplyTo        = replyTo?.ToString(),
                Subject        = subject,
                Body           = body,
                CreatedOnUtc   = DateTime.UtcNow,
                EmailAccountId = messageContext.EmailAccount.Id,
                SendManually   = messageTemplate.SendManually
            };

            // Create and add attachments (if any).
            await CreateAttachmentsAsync(qe, messageContext);

            if (queue)
            {
                // Put to queue.
                await QueueMessageAsync(messageContext, qe);
            }

            return(new CreateMessageResult {
                Email = qe, Model = model, MessageContext = messageContext
            });
        }
        private void DoTrack(ActionExecutingContext context)
        {
            if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
            {
                return;
            }

            var customer = _workContext.CurrentCustomer;

            if (customer == null || customer.Deleted || customer.IsSystemAccount)
            {
                return;
            }

            bool dirty = false;

            // Last activity date
            if (_attribute.TrackDate && customer.LastActivityDateUtc.AddMinutes(1.0) < DateTime.UtcNow)
            {
                customer.LastActivityDateUtc = DateTime.UtcNow;
                dirty = true;
            }

            // Last IP address
            if (_attribute.TrackIpAddress && _privacySettings.StoreLastIpAddress)
            {
                var currentIpAddress = _webHelper.GetClientIpAddress().ToString();
                if (currentIpAddress.HasValue())
                {
                    customer.LastIpAddress = currentIpAddress;
                    dirty = true;
                }
            }

            // Last visited page
            if (_attribute.TrackPage && _customerSettings.StoreLastVisitedPage)
            {
                var currentUrl = _webHelper.GetCurrentPageUrl(true);
                if (currentUrl.HasValue())
                {
                    customer.GenericAttributes.LastVisitedPage = currentUrl;
                    dirty = true;
                }
            }

            // Last user agent
            if (_attribute.TrackUserAgent && _customerSettings.StoreLastVisitedPage)
            {
                // TODO: (core) Make new setting CustomerSettings.StoreLastUserAgent
                var currentUserAgent = _userAgent.RawValue;
                if (currentUserAgent.HasValue())
                {
                    customer.LastUserAgent = currentUserAgent;
                    dirty = true;
                }
            }

            if (dirty)
            {
                _db.TryUpdate(customer);
            }
        }