public virtual async Task <ActionResult> Editor(int?id)
        {
            if (id != null)
            {
                var record = await _userGroupsService.FindByIdAsync(id.Value);

                if (record != null)
                {
                    return(View(await _userGroupsModelFactory.PrepareUserGroupModelAsync(record)));
                }
            }

            return(View(await _userGroupsModelFactory.PrepareUserGroupModelAsync(null)));
        }
예제 #2
0
        public virtual async Task <ActionResult> UpgradeAccount(int selectedUserGroupId, Guid?invoiceId)
        {
            var userGroup = await _userGroupsService.FindByIdAsync(selectedUserGroupId);

            var currentUser = await UserManager.FindByIdAsync(HttpContext.User.Identity.GetUserId());

            if (userGroup == null)
            {
                return(View("Error"));
            }

            if (User.IsInRole("Admin") && invoiceId != null)
            {
                await _invoiceService.AddItemToInvoiceAsync(
                    InvoiceDetailsItemType.SubscriptionPlan,
                    string.Format(_localizationService.GetResource("UpgradeUserAccountTo"), userGroup.GetLocalized(p => p.GroupName)),
                    Url.Action("UpgradeAccount", null, null, Request.Url.Scheme),
                    userGroup.Id,
                    await _userGroupsService.CalculatePlanPriceForUserAsync(userGroup.Id, currentUser),
                    1,
                    invoiceId);

                return(RedirectToAction("index", "Invoice", new { id = invoiceId }));
            }
            else
            {
                await _invoiceService.AddItemToInvoiceAsync(
                    InvoiceDetailsItemType.SubscriptionPlan,
                    string.Format(_localizationService.GetResource("UpgradeUserAccountTo"), userGroup.GetLocalized(p => p.GroupName)),
                    Url.Action("UpgradeAccount", null, null, Request.Url.Scheme),
                    userGroup.Id,
                    await _userGroupsService.CalculatePlanPriceForUserAsync(userGroup.Id, currentUser),
                    1);

                return(RedirectToAction("index", "Invoice"));
            }
        }
예제 #3
0
        public virtual UserCanDownloadProductResult UserCanDownloadProduct(TblProducts product, TblUsers user, bool demoFiles)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            var result = UserCanDownloadProductResult.None;

            //Admin can download everything
            if (user != null && _usersService.UserIsAdmin(user.Id))
            {
                result |= UserCanDownloadProductResult.UserCanDownloadProduct;
            }

            if (demoFiles)
            {
                if (product.UserMustLoggedInToDownloadDemoFiles && user == null)
                {
                    return(UserCanDownloadProductResult.UserMustLoggedIn);
                }

                //Everyone can download Demo version files
                return(UserCanDownloadProductResult.UserCanDownloadProduct);
            }

            //To download product, user must registered and logged in
            if (product.UserMustLoggedInToDownloadFiles && user == null)
            {
                result |= UserCanDownloadProductResult.UserMustLoggedIn;
            }

            // Download is limited to user groups
            if (product.DownloadLimitedToUserGroupId != null)
            {
                var userGroup = AsyncHelper
                                .RunSync(() => _userGroupsService.FindByIdAsync(product.DownloadLimitedToUserGroupId.Value));
                if (product.HigherUserGroupsCanDownload)
                {
                    if (user == null ||
                        (user.SubscriptionExpireDate ?? DateTime.MinValue) < DateTime.Now ||
                        (user.UserGroup?.GroupPriority ?? int.MinValue) < userGroup.GroupPriority)
                    {
                        result |= UserCanDownloadProductResult.UserMustSubscribeToAPlanOrHigher;
                    }
                }
                else
                {
                    if (user == null ||
                        (user.SubscriptionExpireDate ?? DateTime.MinValue) < DateTime.Now ||
                        product.DownloadLimitedToUserGroupId != user.UserGroupId)
                    {
                        result |= UserCanDownloadProductResult.UserMustSubscribeToAPlan;
                    }
                }
            }

            var userNeedToPurchase = product.Price > 0;

            if (user != null)
            {
                //Discounts for user groups
                if (user.UserGroupId != null &&                 //user has subscribed to a user group ?
                    user.SubscriptionExpireDate > DateTime.Now) //user subscription not expired ?
                {
                    var discountsForUserGroup = _productDiscountsForUserGroupsService.FindProductDiscounts(product.Id)?.ToList();
                    if (discountsForUserGroup != null &&
                        discountsForUserGroup.Any()) //product has discount for user groups ?
                    {
                        var discountForUserGroup =
                            discountsForUserGroup.FirstOrDefault(p => p.UserGroupId == user.UserGroupId);

                        if (discountForUserGroup?.DiscountPercent > 0)
                        {
                            var priceForCurrentUser =
                                product.Price - (product.Price * discountForUserGroup.DiscountPercent) / 100;

                            if (priceForCurrentUser <= 0)
                            {
                                userNeedToPurchase = false;
                            }
                        }
                        else
                        {
                            discountForUserGroup =
                                discountsForUserGroup
                                .Where(p => p.ApplyDiscountToHigherUserGroups &&
                                       p.UserGroup.GroupPriority <= user.UserGroup.GroupPriority)
                                .OrderByDescending(p => p.UserGroup.GroupPriority)
                                .FirstOrDefault();
                            if (discountForUserGroup?.DiscountPercent > 0)
                            {
                                var priceForCurrentUser =
                                    product.Price - (product.Price * discountForUserGroup.DiscountPercent) / 100;

                                if (priceForCurrentUser <= 0)
                                {
                                    userNeedToPurchase = false;
                                }
                            }
                        }
                    }
                }

                //user purchased current product ?
                var purchasedProducts = _usersService.GetUserPurchasedProducts(user.Id, product.Id);
                if (purchasedProducts.Any(p => p.PurchaseExpiration > DateTime.Now))
                {
                    userNeedToPurchase = false;
                }

                //User number of download limitation
                if (user.MaxDownloadCount > 0 && user.MaxDownloadPeriodType != null)
                {
                    var date = DateTime.Now.AddTimePeriodToDateTime(user.MaxDownloadPeriodType, -1);
                    var userDownloadCount = _productDownloadsLogService.GetAsQueryable()
                                            .Where(p => p.UserId == user.Id && p.DownloadDate >= date && p.ProductId != product.Id &&
                                                   !p.IsDemoVersion)
                                            .GroupBy(p => p.ProductId).Count();

                    if (user.MaxDownloadCount <= userDownloadCount)
                    {
                        result |= UserCanDownloadProductResult.UserDownloadLimitReached;
                    }
                }

                //User group number of download limitation
                if (user.UserGroup?.MaxDownloadCount > 0 && user.UserGroup?.MaxDownloadPeriodType != null)
                {
                    var date = DateTime.Now.AddTimePeriodToDateTime(user.UserGroup.MaxDownloadPeriodType, -1);
                    var userDownloadCount = _productDownloadsLogService.GetAsQueryable()
                                            .Where(p => p.UserId == user.Id && p.DownloadDate >= date && p.ProductId != product.Id &&
                                                   !p.IsDemoVersion)
                                            .GroupBy(p => p.ProductId).Count();

                    if (user.UserGroup.MaxDownloadCount <= userDownloadCount)
                    {
                        result |= UserCanDownloadProductResult.UserGroupDownloadLimitReached;
                    }
                }
            }

            //Product is not free and user must purchase it
            if (userNeedToPurchase)
            {
                result |= UserCanDownloadProductResult.UserMustPurchaseTheProduct;
            }

            if (result == UserCanDownloadProductResult.None)
            {
                return(UserCanDownloadProductResult.UserCanDownloadProduct);
            }

            return(result);
        }
예제 #4
0
        public virtual ProductDownloadModel PrepareProductDownloadPurchaseButtonModel(TblProducts product, TblUsers currentUser)
        {
            var productCheckoutAttributes = AsyncHelper
                                            .RunSync(() => _checkoutAttributesService.FindProductAttributesAsync(product.Id)).ToList();
            TblUserGroups downloadLimitedToUserGroupRecord = null;

            if (product.DownloadLimitedToUserGroupId != null)
            {
                downloadLimitedToUserGroupRecord = AsyncHelper
                                                   .RunSync(() => _userGroupsService.FindByIdAsync(product.DownloadLimitedToUserGroupId.Value));
            }

            var result = new ProductDownloadModel
            {
                ProductId = product.Id,
                AlwaysShowDownloadButton    = product.AlwaysShowDownloadButton,
                DownloadLimitedToUserGroup  = downloadLimitedToUserGroupRecord,
                HigherUserGroupsCanDownload = product.HigherUserGroupsCanDownload,
                HasDownloadableFile         = !string.IsNullOrWhiteSpace(product.FilesPath) ||
                                              productCheckoutAttributes.Any(p =>
                                                                            p.Options.Any(x => !string.IsNullOrWhiteSpace(x.FilesPath))),
                PriceForCurrentUser = _productService.CalculateProductPriceForUser(product, currentUser),
                DiscountForUserGroupsDescription = GenerateUserGroupDiscountsDescription(product, currentUser),
                DownloadBlockingReason           = _productService.UserCanDownloadProduct(product, currentUser, false)
            };

            result.CanDownloadByCurrentUser = result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserCanDownloadProduct);
            result.CurrentUserGroup         = currentUser?.UserGroup;
            result.HasDemoVersion           = !string.IsNullOrWhiteSpace(product.DemoFilesPath);

            //user purchased current product ?
            var purchasedProducts = _usersService.GetUserPurchasedProducts(currentUser?.Id, product.Id);

            if (purchasedProducts.Any(p => p.PurchaseExpiration > DateTime.Now))
            {
                result.CurrentUserHasAlreadyPurchasedThisProduct = true;
            }


            //ShowUpgradeUserAccountBtn
            if (result.DownloadLimitedToUserGroup != null &&
                (result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlan) ||
                 result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlanOrHigher)))
            {
                if (result.CurrentUserGroup == null)
                {
                    //Current user don't subscribed to any plan
                    result.ShowUpgradeUserAccountBtn = true;
                }
                else
                {
                    if (result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlan) &&
                        result.CurrentUserGroup.Id != result.DownloadLimitedToUserGroup.Id)
                    {
                        result.ShowUpgradeUserAccountBtn = true;
                    }
                    if (result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlanOrHigher) &&
                        result.CurrentUserGroup.GroupPriority < result.DownloadLimitedToUserGroup.GroupPriority)
                    {
                        result.ShowUpgradeUserAccountBtn = true;
                    }
                }
            }

            //ShowDownloadFullVersionBtn
            if (result.HasDownloadableFile)
            {
                if (result.AlwaysShowDownloadButton ||
                    result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserCanDownloadProduct))
                {
                    result.ShowDownloadFullVersionBtn = true;
                }
                if (result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustLoggedIn) ||
                    result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserDownloadLimitReached) ||
                    result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserGroupDownloadLimitReached))
                {
                    if (!(result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlan) ||
                          result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlanOrHigher) ||
                          result.DownloadBlockingReason.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustPurchaseTheProduct)))
                    {
                        result.ShowDownloadFullVersionBtn = true;
                    }
                }
            }


            //ShowPurchaseBtn
            result.ShowPurchaseBtn =
                result.PriceForCurrentUser > 0 || !string.IsNullOrWhiteSpace(product.LicenseGeneratorServiceId) ||
                productCheckoutAttributes.Any(p =>
                                              (p.UnitPrice > 0 && p.AttributeType == ProductCheckoutAttributeType.NumberBox) ||
                                              !string.IsNullOrWhiteSpace(p.LicenseGeneratorServiceId)) ||
                productCheckoutAttributes.SelectMany(p => p.Options).Any(p =>
                                                                         p.Price > 0 ||
                                                                         !string.IsNullOrWhiteSpace(p.LicenseGeneratorServiceId));

            //ShowDownloadDemoVersionBtn
            result.ShowDownloadDemoVersionBtn = result.HasDemoVersion;

            return(result);
        }
예제 #5
0
        public virtual async Task CheckoutInvoiceAsync(TblInvoices invoice, string transactionId)
        {
            var paidAmount = invoice.ComputeInvoiceTotalAmount(false);
            await _dbContext.Invoices.Where(p => p.Id == invoice.Id)
            .UpdateAsync(p => new TblInvoices()
            {
                PaidAmount = paidAmount,
                Status     = InvoiceStatus.Paid
            });

            if (invoice.PaymentDate == null)
            {
                await _dbContext.Invoices.Where(p => p.Id == invoice.Id)
                .UpdateAsync(p => new TblInvoices()
                {
                    PaymentDate = DateTime.Now,
                });
            }

            if (!string.IsNullOrWhiteSpace(transactionId))
            {
                await _dbContext.Invoices.Where(p => p.Id == invoice.Id)
                .UpdateAsync(p => new TblInvoices()
                {
                    PaymentGatewayTransactionId = transactionId
                });
            }

            QueryCacheManager.ExpireTag(CacheTags.Invoice);

            _eventPublisher.Publish(new InvoiceCheckoutEvent(invoice, transactionId, paidAmount,
                                                             paidAmount.ExchangeCurrencyStr(), invoice.PaymentGatewayName, invoice.Currency.IsoCode));


            //Process User Group Upgrade
            var userGroupItem = invoice.InvoiceDetails.FirstOrDefault(p => p.ItemType == InvoiceDetailsItemType.SubscriptionPlan);

            if (userGroupItem != null)
            {
                var userGroup = await _userGroupsService.FindByIdAsync(userGroupItem.ItemId);

                if (userGroup != null && invoice.User != null)
                {
                    //Upgrade user plan
                    await _usersService.UpgradeCustomerUserGroupAsync(invoice.UserId, userGroup);

                    //Purchase Expiration
                    await SetItemExpirationAsync(userGroupItem.Id, invoice.PaymentDate?.AddTimePeriodToDateTime(userGroup.SubscriptionExpirationPeriodType, userGroup.SubscriptionExpirationTime));
                }
            }

            //Process Products
            foreach (var productItem in invoice.InvoiceDetails.Where(p => p.ItemType == InvoiceDetailsItemType.Product))
            {
                var product = await _productService.FindByIdAsync(productItem.ItemId);

                if (product != null)
                {
                    //Purchase Expiration
                    await SetItemExpirationAsync(productItem.Id, invoice.PaymentDate?.AddTimePeriodToDateTime(product.PurchaseExpirationTimeType, product.PurchaseExpiration));

                    //License Code
                    if (!string.IsNullOrWhiteSpace(product.LicenseGeneratorServiceId))
                    {
                        var licenseGenerator = _licenseManager.FindLicenseGeneratorById(product.LicenseGeneratorServiceId);
                        if (licenseGenerator != null)
                        {
                            var license = await licenseGenerator.GenerateLicenseForProductAsync(invoice, invoice.User, product, productItem.Qty);
                            await SetItemLicenseAsync(productItem.Id, license);
                        }
                    }
                }
            }

            //Process Products Attributes
            foreach (var attributeItem in invoice.InvoiceDetails.Where(p => p.ItemType == InvoiceDetailsItemType.ProductAttribute))
            {
                var attribute = await _productCheckoutAttributesService.FindByIdAsync(attributeItem.ItemId);

                if (attribute != null)
                {
                    //License Code
                    if (!string.IsNullOrWhiteSpace(attribute.LicenseGeneratorServiceId))
                    {
                        var licenseGenerator = _licenseManager.FindLicenseGeneratorById(attribute.LicenseGeneratorServiceId);
                        if (licenseGenerator != null)
                        {
                            var license = await licenseGenerator.GenerateLicenseForProductAttributeAsync(invoice, invoice.User, attribute, attributeItem.Qty);
                            await SetItemLicenseAsync(attributeItem.Id, license);
                        }
                    }
                }
            }

            //Process Products Attribute Options
            foreach (var attributeOptionItem in invoice.InvoiceDetails.Where(p => p.ItemType == InvoiceDetailsItemType.ProductAttributeOption))
            {
                var attributeOption = await _productCheckoutAttributesService.FindOptionByIdAsync(attributeOptionItem.ItemId);

                if (attributeOption != null)
                {
                    //Purchase Expiration
                    await SetItemExpirationAsync(attributeOptionItem.Id, invoice.PaymentDate?.AddTimePeriodToDateTime(attributeOption.PurchaseExpirationTimeType, attributeOption.PurchaseExpiration));

                    //License Code
                    if (!string.IsNullOrWhiteSpace(attributeOption.LicenseGeneratorServiceId))
                    {
                        var licenseGenerator = _licenseManager.FindLicenseGeneratorById(attributeOption.LicenseGeneratorServiceId);
                        if (licenseGenerator != null)
                        {
                            var license = await licenseGenerator.GenerateLicenseForProductAttributeOptionAsync(invoice, invoice.User, attributeOption, attributeOptionItem.Qty);
                            await SetItemLicenseAsync(attributeOptionItem.Id, license);
                        }
                    }
                }
            }
        }