Esempio n. 1
0
        public virtual async Task <IActionResult> Sample(int productId)
        {
            var product = await _productService.GetProductByIdAsync(productId);

            if (product == null)
            {
                return(InvokeHttp404());
            }

            if (!product.HasSampleDownload)
            {
                return(Content("Product doesn't have a sample download."));
            }

            var download = await _downloadService.GetDownloadByIdAsync(product.SampleDownloadId);

            if (download == null)
            {
                return(Content("Sample download is not available any more."));
            }

            //A warning (SCS0027 - Open Redirect) from the "Security Code Scan" analyzer may appear at this point.
            //In this case, it is not relevant. Url may not be local.
            if (download.UseDownloadUrl)
            {
                return(new RedirectResult(download.DownloadUrl));
            }

            if (download.DownloadBinary == null)
            {
                return(Content("Download data is not available any more."));
            }

            var fileName    = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString();
            var contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream;

            return(new FileContentResult(download.DownloadBinary, contentType)
            {
                FileDownloadName = fileName + download.Extension
            });
        }
        /// <summary>
        /// Prepare return request model
        /// </summary>
        /// <param name="model">Return request model</param>
        /// <param name="returnRequest">Return request</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>Return request model</returns>
        public virtual async Task <ReturnRequestModel> PrepareReturnRequestModelAsync(ReturnRequestModel model,
                                                                                      ReturnRequest returnRequest, bool excludeProperties = false)
        {
            if (returnRequest == null)
            {
                return(model);
            }

            //fill in model values from the entity
            model ??= new ReturnRequestModel
            {
                Id           = returnRequest.Id,
                CustomNumber = returnRequest.CustomNumber,
                CustomerId   = returnRequest.CustomerId,
                Quantity     = returnRequest.Quantity
            };

            var customer = await _customerService.GetCustomerByIdAsync(returnRequest.CustomerId);

            model.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(returnRequest.CreatedOnUtc, DateTimeKind.Utc);

            model.CustomerInfo = await _customerService.IsRegisteredAsync(customer)
                ? customer.Email : await _localizationService.GetResourceAsync("Admin.Customers.Guest");

            model.UploadedFileGuid = (await _downloadService.GetDownloadByIdAsync(returnRequest.UploadedFileId))?.DownloadGuid ?? Guid.Empty;
            var orderItem = await _orderService.GetOrderItemByIdAsync(returnRequest.OrderItemId);

            if (orderItem != null)
            {
                var order = await _orderService.GetOrderByIdAsync(orderItem.OrderId);

                var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

                model.ProductId         = product.Id;
                model.ProductName       = product.Name;
                model.OrderId           = order.Id;
                model.AttributeInfo     = orderItem.AttributeDescription;
                model.CustomOrderNumber = order.CustomOrderNumber;
            }

            if (excludeProperties)
            {
                return(model);
            }

            model.ReasonForReturn       = returnRequest.ReasonForReturn;
            model.RequestedAction       = returnRequest.RequestedAction;
            model.CustomerComments      = returnRequest.CustomerComments;
            model.StaffNotes            = returnRequest.StaffNotes;
            model.ReturnRequestStatusId = returnRequest.ReturnRequestStatusId;

            return(model);
        }
        /// <summary>
        /// Prepare the customer return requests model
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the customer return requests model
        /// </returns>
        public virtual async Task <CustomerReturnRequestsModel> PrepareCustomerReturnRequestsModelAsync()
        {
            var model = new CustomerReturnRequestsModel();
            var store = await _storeContext.GetCurrentStoreAsync();

            var customer = await _workContext.GetCurrentCustomerAsync();

            var returnRequests = await _returnRequestService.SearchReturnRequestsAsync(store.Id, customer.Id);

            foreach (var returnRequest in returnRequests)
            {
                var orderItem = await _orderService.GetOrderItemByIdAsync(returnRequest.OrderItemId);

                if (orderItem != null)
                {
                    var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

                    var download = await _downloadService.GetDownloadByIdAsync(returnRequest.UploadedFileId);

                    var itemModel = new CustomerReturnRequestsModel.ReturnRequestModel
                    {
                        Id                  = returnRequest.Id,
                        CustomNumber        = returnRequest.CustomNumber,
                        ReturnRequestStatus = await _localizationService.GetLocalizedEnumAsync(returnRequest.ReturnRequestStatus),
                        ProductId           = product.Id,
                        ProductName         = await _localizationService.GetLocalizedAsync(product, x => x.Name),
                        ProductSeName       = await _urlRecordService.GetSeNameAsync(product),
                        Quantity            = returnRequest.Quantity,
                        ReturnAction        = returnRequest.RequestedAction,
                        ReturnReason        = returnRequest.ReasonForReturn,
                        Comments            = returnRequest.CustomerComments,
                        UploadedFileGuid    = download?.DownloadGuid ?? Guid.Empty,
                        CreatedOn           = await _dateTimeHelper.ConvertToUserTimeAsync(returnRequest.CreatedOnUtc, DateTimeKind.Utc),
                    };
                    model.Items.Add(itemModel);
                }
            }

            return(model);
        }
Esempio n. 4
0
        /// <summary>
        /// Copy product
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="newName">New product name</param>
        /// <param name="isPublished">A value indicating whether a new product is published</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the
        /// </returns>
        protected virtual async Task <Product> CopyBaseProductDataAsync(Product product, string newName, bool isPublished)
        {
            //product download & sample download
            var downloadId       = product.DownloadId;
            var sampleDownloadId = product.SampleDownloadId;

            if (product.IsDownload)
            {
                var download = await _downloadService.GetDownloadByIdAsync(product.DownloadId);

                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew
                    };
                    await _downloadService.InsertDownloadAsync(downloadCopy);

                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = await _downloadService.GetDownloadByIdAsync(product.SampleDownloadId);

                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        await _downloadService.InsertDownloadAsync(sampleDownloadCopy);

                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            var newSku = !string.IsNullOrWhiteSpace(product.Sku)
                ? string.Format(await _localizationService.GetResourceAsync("Admin.Catalog.Products.Copy.SKU.New"), product.Sku)
                : product.Sku;
            // product
            var productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                VendorId             = product.VendorId,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomepage       = product.ShowOnHomepage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = newSku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                OverriddenGiftCardAmount         = product.OverriddenGiftCardAmount,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsRental                         = product.IsRental,
                RentalPriceLength                = product.RentalPriceLength,
                RentalPricePeriod                = product.RentalPricePeriod,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                ShipSeparately                   = product.ShipSeparately,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                DeliveryDateId                   = product.DeliveryDateId,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                IsTelecommunicationsOrBroadcastingOrElectronicServices =
                    product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
                ManageInventoryMethod      = product.ManageInventoryMethod,
                ProductAvailabilityRangeId = product.ProductAvailabilityRangeId,
                UseMultipleWarehouses      = product.UseMultipleWarehouses,
                WarehouseId                   = product.WarehouseId,
                StockQuantity                 = product.StockQuantity,
                DisplayStockAvailability      = product.DisplayStockAvailability,
                DisplayStockQuantity          = product.DisplayStockQuantity,
                MinStockQuantity              = product.MinStockQuantity,
                LowStockActivityId            = product.LowStockActivityId,
                NotifyAdminForQuantityBelow   = product.NotifyAdminForQuantityBelow,
                BackorderMode                 = product.BackorderMode,
                AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity          = product.OrderMinimumQuantity,
                OrderMaximumQuantity          = product.OrderMaximumQuantity,
                AllowedQuantities             = product.AllowedQuantities,
                AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
                NotReturnable         = product.NotReturnable,
                DisableBuyButton      = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder  = product.AvailableForPreOrder,
                PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
                CallForPrice                = product.CallForPrice,
                Price                       = product.Price,
                OldPrice                    = product.OldPrice,
                ProductCost                 = product.ProductCost,
                CustomerEntersPrice         = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice,
                BasepriceEnabled            = product.BasepriceEnabled,
                BasepriceAmount             = product.BasepriceAmount,
                BasepriceUnitId             = product.BasepriceUnitId,
                BasepriceBaseAmount         = product.BasepriceBaseAmount,
                BasepriceBaseUnitId         = product.BasepriceBaseUnitId,
                MarkAsNew                   = product.MarkAsNew,
                MarkAsNewStartDateTimeUtc   = product.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc     = product.MarkAsNewEndDateTimeUtc,
                Weight                      = product.Weight,
                Length                      = product.Length,
                Width                       = product.Width,
                Height                      = product.Height,
                AvailableStartDateTimeUtc   = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc     = product.AvailableEndDateTimeUtc,
                DisplayOrder                = product.DisplayOrder,
                Published                   = isPublished,
                Deleted                     = product.Deleted,
                CreatedOnUtc                = DateTime.UtcNow,
                UpdatedOnUtc                = DateTime.UtcNow
            };

            //validate search engine name
            await _productService.InsertProductAsync(productCopy);

            //search engine name
            await _urlRecordService.SaveSlugAsync(productCopy, await _urlRecordService.ValidateSeNameAsync(productCopy, string.Empty, productCopy.Name, true), 0);

            return(productCopy);
        }
Esempio n. 5
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloadId">Attachment download ID (another attachment)</param>
        /// <param name="headers">Headers</param>
        public virtual async Task SendEmailAsync(EmailAccount emailAccount, string subject, string body,
                                                 string fromAddress, string fromName, string toAddress, string toName,
                                                 string replyTo            = null, string replyToName = null,
                                                 IEnumerable <string> bcc  = null, IEnumerable <string> cc           = null,
                                                 string attachmentFilePath = null, string attachmentFileName         = null,
                                                 int attachedDownloadId    = 0, IDictionary <string, string> headers = null)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromName, fromAddress));
            message.To.Add(new MailboxAddress(toName, toAddress));

            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyTo.Add(new MailboxAddress(replyToName, replyTo));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(new MailboxAddress("", address.Trim()));
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.Cc.Add(new MailboxAddress("", address.Trim()));
                }
            }

            //content
            message.Subject = subject;

            //headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            var multipart = new Multipart("mixed")
            {
                new TextPart(TextFormat.Html)
                {
                    Text = body
                }
            };

            //create the file attachment for this e-mail message
            if (!string.IsNullOrEmpty(attachmentFilePath) && _fileProvider.FileExists(attachmentFilePath))
            {
                multipart.Add(await CreateMimeAttachmentAsync(attachmentFilePath, attachmentFileName));
            }

            //another attachment?
            if (attachedDownloadId > 0)
            {
                var download = await _downloadService.GetDownloadByIdAsync(attachedDownloadId);

                //we do not support URLs as attachments
                if (!download?.UseDownloadUrl ?? false)
                {
                    multipart.Add(CreateMimeAttachment(download));
                }
            }

            message.Body = multipart;

            //send email
            using var smtpClient = await _smtpBuilder.BuildAsync(emailAccount);

            await smtpClient.SendAsync(message);

            await smtpClient.DisconnectAsync(true);
        }