Exemple #1
0
        private bool SaveBillingInfo(int tenant, Tariff tariffInfo, bool renewal = true)
        {
            var inserted      = false;
            var currentTariff = GetBillingInfo(tenant);

            if (!tariffInfo.EqualsByParams(currentTariff))
            {
                using (var db = GetDb())
                    using (var tx = db.BeginTransaction())
                    {
                        // last record is not the same
                        var q = new SqlQuery("tenants_tariff")
                                .SelectCount()
                                .Where("tenant", tenant)
                                .Where("tariff", tariffInfo.QuotaId)
                                .Where("stamp", tariffInfo.DueDate)
                                .Where("quantity", tariffInfo.Quantity);

                        if (tariffInfo.DueDate == DateTime.MaxValue || renewal || db.ExecuteScalar <int>(q) == 0)
                        {
                            var i = new SqlInsert("tenants_tariff")
                                    .InColumnValue("tenant", tenant)
                                    .InColumnValue("tariff", tariffInfo.QuotaId)
                                    .InColumnValue("stamp", tariffInfo.DueDate)
                                    .InColumnValue("quantity", tariffInfo.Quantity);
                            db.ExecuteNonQuery(i);
                            cache.Remove(GetTariffCacheKey(tenant));
                            inserted = true;
                        }
                        tx.Commit();
                    }
            }

            if (inserted)
            {
                var t = tenantService.GetTenant(tenant);
                if (t != null)
                {
                    // update tenant.LastModified to flush cache in documents
                    tenantService.SaveTenant(t);
                }
            }
            return(inserted);
        }
Exemple #2
0
        public Tariff GetTariff(int tenantId)
        {
            var key    = "tariff/" + tenantId;
            var tariff = cache.Get(key) as Tariff;

            if (tariff == null)
            {
                tariff = Tariff.CreateDefault();

                try
                {
                    using (var client = new BillingClient())
                    {
                        var xelement = client.GetLastPayment(tenantId);

                        var productid = xelement.Element("product-id").Value;
                        var quota     = quotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == productid);
                        tariff.QuotaId = quota.Id;

                        var enddate = xelement.Element("end-date");
                        tariff.DueDate = DateTime.ParseExact(enddate.Value, "yyyy-MM-dd HH:mm:ss", null);

                        SaveBillingInfo(tenantId, Tuple.Create(tariff.QuotaId, tariff.DueDate));
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);

                    var cached = GetBillingInfo(tenantId);
                    if (cached != null)
                    {
                        tariff.QuotaId = cached.Item1;
                        tariff.DueDate = cached.Item2;
                    }
                }

                CalculateState(tenantId, tariff);

                cache.Insert(key, tariff, DateTime.UtcNow.Add(CacheExpiration));
            }

            return(tariff);
        }
Exemple #3
0
        private Tariff GetBillingInfo(int tenant)
        {
            var q = new SqlQuery("tenants_tariff")
                    .Select("tariff", "stamp", "quantity")
                    .Where("tenant", tenant)
                    .OrderBy("id", false)
                    .SetMaxResults(1);

            return(ExecList(q)
                   .ConvertAll(r =>
            {
                var tariff = Tariff.CreateDefault();
                tariff.QuotaId = Convert.ToInt32(r[0]);
                tariff.DueDate = ((DateTime)r[1]).Year < 9999 ? (DateTime)r[1] : DateTime.MaxValue;
                tariff.Quantity = Convert.ToInt32(r[2]);
                return tariff;
            })
                   .SingleOrDefault()
                   ?? Tariff.CreateDefault());
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(this.GetType());

            Page.ClientScript.RegisterClientScriptInclude(typeof(string), "watermark_script", WebPath.GetPath("js/jquery.watermarkinput.js"));
            Page.ClientScript.RegisterClientScriptInclude(typeof(string), "tariffsettings_script", WebPath.GetPath("usercontrols/management/tariffsettings/js/tariffsettings.js"));
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "tariffsettings_style", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + WebSkin.GetUserSkin().GetAbsoluteWebPath("usercontrols/management/tariffsettings/css/<theme_folder>/tariffsettings.css") + "\">", false);

            var curTenant = CoreContext.TenantManager.GetCurrentTenant();

            tariff = CoreContext.TenantManager.GetTariff(curTenant.TenantId);

            var payments = CoreContext.TenantManager.GetTariffPayments(curTenant.TenantId);

            _paymentsRepeater.Visible = (payments.Count() > 0);
            _paymentsRepeater.DataSource = payments;
            _paymentsRepeater.DataBind();

            var buyNowControl = LoadControl(BuyNow.Location) as BuyNow;
            _buyNowHolder.Controls.Add(buyNowControl);
            _buyNowHolder.Visible = !CoreContext.Configuration.Standalone && tariff.State == TariffState.Trial;
        }
Exemple #5
0
        private Tariff CalculateTariff(int tenantId, Tariff tariff)
        {
            tariff.State = TariffState.Paid;
            var q = quotaService.GetTenantQuota(tariff.QuotaId);

            if (q == null || q.GetFeature("old"))
            {
                tariff.QuotaId = Tenant.DEFAULT_TENANT;
                q = quotaService.GetTenantQuota(tariff.QuotaId);
            }

            if (q != null && q.Trial)
            {
                tariff.State = TariffState.Trial;
                if (tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue)
                {
                    var tenant      = tenantService.GetTenant(tenantId);
                    var fromDate    = tenant.CreatedDateTime < tenant.VersionChanged ? tenant.VersionChanged : tenant.CreatedDateTime;
                    var trialPeriod = GetPeriod("TrialPeriod", DEFAULT_TRIAL_PERIOD);
                    tariff.DueDate = trialPeriod != default(int) ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue;
                }
            }
            if (tariff.DueDate.Date < DateTime.UtcNow.Date)
            {
                tariff.State = TariffState.NotPaid;

                if (config.Standalone)
                {
                    tariff = Tariff.CreateDefault();
                }
            }

            tariff.Prolongable = tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue ||
                                 tariff.State == TariffState.Trial ||
                                 new DateTime(tariff.DueDate.Year, tariff.DueDate.Month, 1) <= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1).AddMonths(1);

            return(tariff);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "productquotes_style", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + WebSkin.GetUserSkin().GetAbsoluteWebPath("usercontrols/statistics/productquotes/css/<theme_folder>/productquotes_style.css") + "\">", false);

            _tariff = CoreContext.TenantManager.GetTariff(CoreContext.TenantManager.GetCurrentTenant().TenantId);

            var data = new List<object>();
            foreach (var item in WebItemManager.Instance.GetItems(Web.Core.WebZones.WebZoneType.All, ItemAvailableState.All))
            {
                if (item.Context == null || item.Context.SpaceUsageStatManager == null)
                    continue;

                data.Add(new Product() {Id = item.ID, Name = item.Name, Icon = item.GetIconAbsoluteURL()});
            }

            _itemsRepeater.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(_itemsRepeater_ItemDataBound);
            _itemsRepeater.DataSource = data;
            _itemsRepeater.DataBind();

            if (!CoreContext.Configuration.Standalone)
            {
                _buyNowHolder.Controls.Add(LoadControl(BuyNow.Location));
            }
        }
Exemple #7
0
        public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true)
        {
            var key    = "tariff/" + tenantId;
            var tariff = cache.Get(key) as Tariff;

            if (tariff == null)
            {
                tariff = Tariff.CreateDefault();

                var cached = GetBillingInfo(tenantId);
                if (cached != null)
                {
                    tariff.QuotaId = cached.Item1;
                    tariff.DueDate = cached.Item2;
                }

                if (withRequestToPaymentSystem)
                {
                    Task.Run(() =>
                    {
                        try
                        {
                            using (var client = GetBillingClient())
                            {
                                try
                                {
                                    var p     = client.GetLastPayment(GetPortalId(tenantId));
                                    var quota = quotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == p.ProductId);
                                    if (quota == null)
                                    {
                                        throw new InvalidOperationException(string.Format("Quota with id {0} not found for portal {1}.", p.ProductId, GetPortalId(tenantId)));
                                    }
                                    var asynctariff         = Tariff.CreateDefault();
                                    asynctariff.QuotaId     = quota.Id;
                                    asynctariff.Autorenewal = p.Autorenewal;
                                    asynctariff.DueDate     = 9999 <= p.EndDate.Year ? DateTime.MaxValue : p.EndDate;

                                    if (SaveBillingInfo(tenantId, Tuple.Create(asynctariff.QuotaId, asynctariff.DueDate)))
                                    {
                                        asynctariff = CalculateTariff(tenantId, asynctariff);
                                        ClearCache(tenantId);
                                        cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration()));
                                    }
                                }
                                finally
                                {
                                    if (config.Standalone)
                                    {
                                        var po = client.GetPaymentOffice(GetPortalId(tenantId));
                                        if (!string.IsNullOrEmpty(po.Key2) && !Equals(config.SKey, po.Key2))
                                        {
                                            config.SKey = po.Key2;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception error)
                        {
                            LogError(error);
                        }
                    });
                }

                tariff = CalculateTariff(tenantId, tariff);
                cache.Insert(key, tariff, DateTime.UtcNow.Add(GetCacheExpiration()));
            }

            return(tariff);
        }
Exemple #8
0
        public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true)
        {
            //single tariff for all portals
            if (CoreContext.Configuration.Standalone)
            {
                tenantId = -1;
            }

            var key    = GetTariffCacheKey(tenantId);
            var tariff = cache.Get <Tariff>(key);

            if (tariff == null)
            {
                tariff = GetBillingInfo(tenantId);

                tariff = CalculateTariff(tenantId, tariff);
                cache.Insert(key, tariff, DateTime.UtcNow.Add(GetCacheExpiration()));

                if (BillingClient.Configured && withRequestToPaymentSystem)
                {
                    Task.Run(() =>
                    {
                        try
                        {
                            var client      = GetBillingClient();
                            var lastPayment = client.GetLastPayment(GetPortalId(tenantId));

                            var quota = quotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == lastPayment.ProductId);
                            if (quota == null)
                            {
                                throw new InvalidOperationException(string.Format("Quota with id {0} not found for portal {1}.", lastPayment.ProductId, GetPortalId(tenantId)));
                            }

                            var asynctariff         = Tariff.CreateDefault();
                            asynctariff.QuotaId     = quota.Id;
                            asynctariff.Autorenewal = lastPayment.Autorenewal;
                            asynctariff.DueDate     = 9999 <= lastPayment.EndDate.Year ? DateTime.MaxValue : lastPayment.EndDate;

                            if (quota.ActiveUsers == -1 &&
                                lastPayment.Quantity < ACTIVE_USERS_MIN)
                            {
                                throw new BillingException(string.Format("The portal {0} is paid for {1} users", tenantId, lastPayment.Quantity));
                            }
                            asynctariff.Quantity = lastPayment.Quantity;

                            if (SaveBillingInfo(tenantId, asynctariff, false))
                            {
                                asynctariff = CalculateTariff(tenantId, asynctariff);
                                ClearCache(tenantId);
                                cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration()));
                            }
                        }
                        catch (BillingNotFoundException)
                        {
                            var q = quotaService.GetTenantQuota(tariff.QuotaId);

                            if (q != null &&
                                !q.Trial &&
                                !q.Free &&
                                !q.NonProfit &&
                                !q.Open &&
                                !q.Custom)
                            {
                                var asynctariff         = Tariff.CreateDefault();
                                asynctariff.DueDate     = DateTime.Today.AddDays(-1);
                                asynctariff.Prolongable = false;
                                asynctariff.Autorenewal = false;
                                asynctariff.State       = TariffState.NotPaid;

                                if (SaveBillingInfo(tenantId, asynctariff))
                                {
                                    asynctariff = CalculateTariff(tenantId, asynctariff);
                                    ClearCache(tenantId);
                                    cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration()));
                                }
                            }
                        }
                        catch (Exception error)
                        {
                            LogError(error, tenantId.ToString());
                        }
                    });
                }
            }

            return(tariff);
        }
Exemple #9
0
        private Tariff CalculateTariff(int tenantId, Tariff tariff)
        {
            tariff.State = TariffState.Paid;
            var q = quotaService.GetTenantQuota(tariff.QuotaId);

            if (q == null || q.GetFeature("old"))
            {
                tariff.QuotaId = Tenant.DEFAULT_TENANT;
                q = quotaService.GetTenantQuota(tariff.QuotaId);
            }

            var delay = 0;

            if (q != null && q.Trial)
            {
                tariff.State = TariffState.Trial;
                if (tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue)
                {
                    var tenant = tenantService.GetTenant(tenantId);
                    if (tenant != null)
                    {
                        var fromDate    = tenant.CreatedDateTime < tenant.VersionChanged ? tenant.VersionChanged : tenant.CreatedDateTime;
                        var trialPeriod = GetPeriod("TrialPeriod", DEFAULT_TRIAL_PERIOD);
                        if (fromDate == DateTime.MinValue)
                        {
                            fromDate = DateTime.UtcNow.Date;
                        }
                        tariff.DueDate = trialPeriod != default(int) ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue;
                    }
                    else
                    {
                        tariff.DueDate = DateTime.MaxValue;
                    }
                }
            }
            else
            {
                delay = paymentDelay;
            }

            if (tariff.DueDate != DateTime.MinValue && tariff.DueDate.Date < DateTime.Today && delay > 0)
            {
                tariff.State = TariffState.Delay;

                tariff.DelayDueDate = tariff.DueDate.Date.AddDays(delay);
            }

            if (tariff.DueDate == DateTime.MinValue ||
                tariff.DueDate != DateTime.MaxValue && tariff.DueDate.Date.AddDays(delay) < DateTime.Today)
            {
                tariff.State = TariffState.NotPaid;

                if (config.Standalone)
                {
                    if (q != null)
                    {
                        var defaultQuota = quotaService.GetTenantQuota(Tenant.DEFAULT_TENANT);
                        defaultQuota.Name = "overdue";

                        defaultQuota.Features = q.Features;

                        quotaService.SaveTenantQuota(defaultQuota);
                    }

                    var unlimTariff = Tariff.CreateDefault();
                    unlimTariff.LicenseDate = tariff.DueDate;

                    tariff = unlimTariff;
                }
            }

            tariff.Prolongable = tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue ||
                                 tariff.State == TariffState.Trial ||
                                 new DateTime(tariff.DueDate.Year, tariff.DueDate.Month, 1) <= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1).AddMonths(1);

            return(tariff);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/management/tariffsettings/js/tariffusage.js"));
            Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/management/tariffsettings/css/tariffusage.less"));

            UsersCount = TenantStatisticsProvider.GetUsersCount();
            UsedSize = TenantStatisticsProvider.GetUsedSize();
            CurrentTariff = TenantExtra.GetCurrentTariff();
            CurrentQuota = TenantExtra.GetTenantQuota();

            var partner = CoreContext.PaymentManager.GetApprovedPartner();
            if (partner != null)
            {
                Partner = partner;

                _quotaList = CoreContext.PaymentManager.GetPartnerTariffs(Partner.Id);

                if (!string.IsNullOrEmpty(Partner.Currency))
                {
                    _region = new RegionInfo(Partner.Currency);
                }

                var control = (TariffPartner)LoadControl(TariffPartner.Location);
                control.CurPartner = Partner;
                control.TariffNotPaid = CurrentTariff.State >= TariffState.NotPaid;
                control.TariffProlongable = CurrentTariff.Prolongable;
                PaymentsCodeHolder.Controls.Add(control);
            }

            if (_quotaList == null || !_quotaList.Any())
            {
                _quotaList = TenantExtra.GetTenantQuotas();
            }
            else if (!CurrentQuota.Trial)
            {
                CurrentQuota = _quotaList.FirstOrDefault(q => q.Id == CurrentQuota.Id) ?? CurrentQuota;
            }
            _quotaList = _quotaList.OrderBy(r => r.ActiveUsers).ToList().Where(r => !r.Trial);
            QuotasYear = _quotaList.Where(r => r.Year).ToList();

            HideBuyRecommendation = CurrentTariff.Autorenewal || TariffSettings.HideRecommendation || Partner != null;

            AnnualDiscount = QuotasYear.All(q => q.Price2 != decimal.Zero);
            HideAnnualRecomendation = !AnnualDiscount
                                      || (CurrentQuota.Year && !CurrentQuota.Free && !CurrentQuota.Trial)
                                      || TariffSettings.HideAnnualRecomendation
                                      || CurrentQuota.NonProfit;
            if (!HideAnnualRecomendation)
            {
                AnnualQuotaForDisplay = QuotaForDisplay;
                if (AnnualQuotaForDisplay == null
                    || AnnualQuotaForDisplay.Free
                    || AnnualQuotaForDisplay.Trial
                    || !AnnualQuotaForDisplay.Visible)
                {
                    HideAnnualRecomendation = true;
                }
                else if (!AnnualQuotaForDisplay.Year)
                {
                    AnnualQuotaForDisplay = _quotaList.FirstOrDefault(r =>
                                                                      r.ActiveUsers == AnnualQuotaForDisplay.ActiveUsers
                                                                      && r.Year);
                    if (AnnualQuotaForDisplay == null)
                    {
                        HideAnnualRecomendation = true;
                    }
                }
            }

            downgradeInfoContainer.Options.IsPopup = true;
            buyRecommendationContainer.Options.IsPopup = true;
            annualRecomendationContainer.Options.IsPopup = true;
            AjaxPro.Utility.RegisterTypeForAjax(GetType());

            if (StudioSmsNotificationSettings.IsVisibleSettings
                && (SettingsManager.Instance.LoadSettings<StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting
                    || CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
                && Partner == null)
            {
                SmsEnable = true;
                var smsBuy = (SmsBuy)LoadControl(SmsBuy.Location);
                smsBuy.ShowLink = !SettingsManager.Instance.LoadSettings<StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting;
                SmsBuyHolder.Controls.Add(smsBuy);
            }

            if (VoipPaymentSettings.IsVisibleSettings
                && CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)
                && Partner == null)
            {
                VoipEnable = true;
                var voipBuy = (VoipBuy)LoadControl(VoipBuy.Location);
                VoipBuyHolder.Controls.Add(voipBuy);
            }

            if (Partner == null)
            {
                RegisterScript();
            }

            if (Partner == null && Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName == "ru")
            {
                _region = new RegionInfo("RU");
                RateRuble = SetupInfo.ExchangeRateRuble;

                SetStar(string.Format(Resource.TariffsCurrencyRu, RateRuble));
            }
        }
        public void SetTariff(int tenantId, Tariff tariff)
        {
            if (tariff == null)
            {
                throw new ArgumentNullException("tariff");
            }

            var q = quotaService.GetTenantQuota(tariff.QuotaId);
            if (q == null) return;
            SaveBillingInfo(tenantId, Tuple.Create(tariff.QuotaId, tariff.DueDate));
            if (q.Trial)
            {
                // reset trial date
                var tenant = tenantService.GetTenant(tenantId);
                if (tenant != null)
                {
                    tenant.VersionChanged = DateTime.UtcNow;
                    tenantService.SaveTenant(tenant);
                }
            }

            ClearCache(tenantId);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            UsersCount = TenantStatisticsProvider.GetUsersCount();
            UsedSize = TenantStatisticsProvider.GetUsedSize();
            CurrentTariff = TenantExtra.GetCurrentTariff();
            CurrentQuota = TenantExtra.GetTenantQuota();

            var partnerId = CoreContext.TenantManager.GetCurrentTenant().PartnerId;
            if (!string.IsNullOrEmpty(partnerId))
            {
                var partner = CoreContext.PaymentManager.GetPartner(partnerId);

                if (partner != null && partner.Status == PartnerStatus.Approved && !partner.Removed && partner.PartnerType != PartnerType.System)
                {
                    Partner = partner;

                    _quotaList = CoreContext.PaymentManager.GetPartnerTariffs(Partner.Id);
                    SalesMail = Partner.SalesEmail;
                    if (!string.IsNullOrEmpty(Partner.Currency))
                    {
                        Region = new RegionInfo(Partner.Currency);
                    }

                    var control = (TariffPartner)LoadControl(TariffPartner.Location);
                    control.CurPartner = Partner;
                    control.TariffNotPaid = CurrentTariff.State >= TariffState.NotPaid;
                    control.TariffProlongable = CurrentTariff.Prolongable;
                    PaymentsCodeHolder.Controls.Add(control);
                }
            }

            if (_quotaList == null || !_quotaList.Any())
            {
                _quotaList = TenantExtra.GetTenantQuotas();
            }
            else if (!CurrentQuota.Trial)
            {
                CurrentQuota = _quotaList.First(q => q.Id == CurrentQuota.Id) ?? CurrentQuota;
            }
            _quotaList = _quotaList.OrderBy(r => r.ActiveUsers).ToList().Where(r => !r.Trial);
            QuotasYear = _quotaList.Where(r => r.Year).ToList();

            HideBuyRecommendation = CurrentTariff.Autorenewal || TariffSettings.GetTariffSettings() || Partner != null;

            downgradeInfoContainer.Options.IsPopup = true;
            buyRecommendationContainer.Options.IsPopup = true;
            AjaxPro.Utility.RegisterTypeForAjax(GetType());

            if (StudioSmsNotificationSettings.IsVisibleSettings
                && SettingsManager.Instance.LoadSettings<StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting
                && Partner == null)
            {
                SmsEnable = true;
                SmsBuyHolder.Controls.Add(LoadControl(SmsBuy.Location));
            }

            if (Partner == null)
            {
                RegisterScript();
            }
        }
 public void SetTariff(int tenant, Tariff tariff)
 {
     tariffService.SetTariff(tenant, tariff);
 }
        private Tariff CalculateTariff(int tenantId, Tariff tariff)
        {
            tariff.State = TariffState.Paid;
            var q = quotaService.GetTenantQuota(tariff.QuotaId);

            if (q == null || q.GetFeature("old"))
            {
                tariff.QuotaId = Tenant.DEFAULT_TENANT;
                q = quotaService.GetTenantQuota(tariff.QuotaId);
            }

            if (q != null && q.Trial)
            {
                tariff.State = TariffState.Trial;
                if (tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue)
                {
                    var tenant = tenantService.GetTenant(tenantId);
                    if (tenant != null)
                    {
                        var fromDate = tenant.CreatedDateTime < tenant.VersionChanged ? tenant.VersionChanged : tenant.CreatedDateTime;
                        var trialPeriod = GetPeriod("TrialPeriod", DEFAULT_TRIAL_PERIOD);
                        if (fromDate == DateTime.MinValue) fromDate = DateTime.UtcNow.Date;
                        tariff.DueDate = trialPeriod != default(int) ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue;
                    }
                    else
                    {
                        tariff.DueDate = DateTime.MaxValue;
                    }
                }
            }
            if (tariff.DueDate.Date < DateTime.UtcNow.Date)
            {
                tariff.State = TariffState.NotPaid;

                if (config.Standalone)
                {
                    tariff = Tariff.CreateDefault();
                }
            }

            tariff.Prolongable = tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue ||
                                 tariff.State == TariffState.Trial ||
                                 new DateTime(tariff.DueDate.Year, tariff.DueDate.Month, 1) <= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1).AddMonths(1);

            return tariff;
        }
Exemple #15
0
        public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true)
        {
            //single tariff for all portals
            if (CoreContext.Configuration.Standalone)
            {
                tenantId = -1;
            }

            var key    = GetTariffCacheKey(tenantId);
            var tariff = cache.Get <Tariff>(key);

            if (tariff == null)
            {
                tariff = Tariff.CreateDefault();

                var cached = GetBillingInfo(tenantId);
                if (cached != null)
                {
                    tariff.QuotaId = cached.Item1;
                    tariff.DueDate = cached.Item2;
                }

                tariff = CalculateTariff(tenantId, tariff);
                cache.Insert(key, tariff, DateTime.UtcNow.Add(GetCacheExpiration()));

                if (billingConfigured && withRequestToPaymentSystem)
                {
                    Task.Run(() =>
                    {
                        try
                        {
                            using (var client = GetBillingClient())
                            {
                                var p     = client.GetLastPayment(GetPortalId(tenantId));
                                var quota = quotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == p.ProductId);
                                if (quota == null)
                                {
                                    throw new InvalidOperationException(string.Format("Quota with id {0} not found for portal {1}.", p.ProductId, GetPortalId(tenantId)));
                                }
                                var asynctariff         = Tariff.CreateDefault();
                                asynctariff.QuotaId     = quota.Id;
                                asynctariff.Autorenewal = p.Autorenewal;
                                asynctariff.DueDate     = 9999 <= p.EndDate.Year ? DateTime.MaxValue : p.EndDate;

                                if (SaveBillingInfo(tenantId, Tuple.Create(asynctariff.QuotaId, asynctariff.DueDate), false))
                                {
                                    asynctariff = CalculateTariff(tenantId, asynctariff);
                                    ClearCache(tenantId);
                                    cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration()));
                                }
                            }
                        }
                        catch (Exception error)
                        {
                            LogError(error);
                        }
                    });
                }
            }

            return(tariff);
        }
        private static void LicenseToDB(string licenseJsonString, string customerId = null)
        {
            var licenseJson = JObject.Parse(licenseJsonString);

            if (!licenseJson.Value <string>("customer_id").Equals(customerId ?? LicenseClient.CustomerId) ||
                string.IsNullOrEmpty(licenseJson.Value <string>("signature")))
            {
                throw new BillingNotConfiguredException("License not correct", licenseJsonString);
            }

            var dueDate = licenseJson.Value <DateTime>("end_date");

            if (dueDate < DateTime.UtcNow)
            {
                throw new BillingException("License expired", licenseJsonString);
            }

            var features = new List <string>
            {
                //free
                "domain", "docs",

                //pay
                "audit", "backup", "controlpanel", "healthcheck", "ldap", "whitelabel",
            };

            if (licenseJson.Value <bool>("trial"))
            {
                features.Add("trial");
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            var activeUsers = licenseJson.Value <int>("user_quota");

            if (activeUsers.Equals(default(int)) || activeUsers < 1)
            {
                activeUsers = 10000;
            }

            if (activeUsers < CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.User).Length)
            {
                throw new BillingException("License quota", licenseJsonString);
            }

            var quota = new TenantQuota(-1000)
            {
                ActiveUsers  = activeUsers,
                MaxFileSize  = 1024 * 1024 * 1024,
                MaxTotalSize = 1024L * 1024 * 1024 * 1024 - 1,
                Name         = "license",
                Features     = string.Join(",", features),
            };

            CoreContext.TenantManager.SaveTenantQuota(quota);

            var tariff = new Tariff
            {
                QuotaId = quota.Id,
                DueDate = dueDate,
            };

            CoreContext.PaymentManager.SetTariff(tenant.TenantId, tariff);

            var affiliateId = licenseJson.Value <string>("affiliate_id");

            if (!string.IsNullOrEmpty(affiliateId))
            {
                tenant.AffiliateId = affiliateId;
                CoreContext.TenantManager.SaveTenant(tenant);
            }
        }
        public void SendTrialRequest(int tenant, UserInfo user)
        {
            var trial = quotaService.GetTenantQuotas().FirstOrDefault(q => q.Trial);
            if (trial != null)
            {
                var uri = ConfigurationManager.AppSettings["core.payment-request"] ?? "http://billing.onlyoffice.com/avangate/requestatrialversion.aspx";
                uri += uri.Contains('?') ? "&" : "?";
                uri += "FIRSTNAME=" + HttpUtility.UrlEncode(user.FirstName) +
                    "&LASTNAME=" + HttpUtility.UrlEncode(user.FirstName) +
                    "&CUSTOMEREMAIL=" + HttpUtility.UrlEncode(user.Email) +
                    "&PORTALID=" + HttpUtility.UrlEncode(config.GetKey(tenant)) +
                    "&PRODUCTID=" + HttpUtility.UrlEncode(trial.AvangateId);

                using (var webClient = new WebClient())
                {
                    var result = webClient.DownloadString(uri);
                    var element = XElement.Parse(result);
                    if (element.Value != null &&
                        (element.Value.StartsWith("error:", StringComparison.InvariantCultureIgnoreCase) ||
                        element.Value.StartsWith("warning:", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        throw new BillingException(element.Value);
                    }
                    var tariff = new Tariff
                    {
                        QuotaId = trial.Id,
                        State = TariffState.Trial,
                        DueDate = DateTime.UtcNow.Date.AddMonths(1),
                    };
                    tariffService.SetTariff(tenant, tariff);
                    var tt = tariffService.GetTariff(tenant);
                }
            }
        }
 public void SetTariff(string region, int tenant, Tariff tariff)
 {
     GetRegionService(region).SetTariff(tenant, tariff);
 }
        private static void LicenseToDB(License license)
        {
            Validate(license);

            CustomerId = license.CustomerId;

            var defaultQuota = CoreContext.TenantManager.GetTenantQuota(Tenant.DEFAULT_TENANT);

            var quota = new TenantQuota(-1000)
            {
                ActiveUsers    = license.ActiveUsers,
                MaxFileSize    = defaultQuota.MaxFileSize,
                MaxTotalSize   = defaultQuota.MaxTotalSize,
                Name           = "license",
                DocsEdition    = true,
                HasDomain      = true,
                Audit          = true,
                ControlPanel   = true,
                HealthCheck    = true,
                Ldap           = true,
                Sso            = true,
                Customization  = license.Customization,
                WhiteLabel     = license.WhiteLabel || license.Customization,
                Branding       = license.Branding,
                SSBranding     = license.SSBranding,
                Update         = true,
                Support        = true,
                Trial          = license.Trial,
                CountPortals   = license.PortalCount,
                DiscEncryption = true,
                PrivacyRoom    = true,
                Restore        = true,
                ContentSearch  = true
            };

            if (defaultQuota.Name != "overdue" && !defaultQuota.Trial)
            {
                quota.WhiteLabel |= defaultQuota.WhiteLabel;
                quota.Branding   |= defaultQuota.Branding;
                quota.SSBranding |= defaultQuota.SSBranding;

                quota.CountPortals = Math.Max(defaultQuota.CountPortals, quota.CountPortals);
            }

            CoreContext.TenantManager.SaveTenantQuota(quota);

            var tariff = new Tariff
            {
                QuotaId = quota.Id,
                DueDate = license.DueDate,
            };

            CoreContext.PaymentManager.SetTariff(-1, tariff);

            if (!string.IsNullOrEmpty(license.AffiliateId))
            {
                var tenant = CoreContext.TenantManager.GetCurrentTenant();
                tenant.AffiliateId = license.AffiliateId;
                CoreContext.TenantManager.SaveTenant(tenant);
            }
        }