DocSpace-buildtools/common/ASC.Core.Common/Billing/TariffService.cs

725 lines
26 KiB
C#
Raw Normal View History

2022-03-15 18:00:53 +00:00
// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
// any third-party rights.
//
// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
2019-05-15 14:56:09 +00:00
2022-02-15 11:52:43 +00:00
namespace ASC.Core.Billing;
[Singletone]
public class TariffServiceStorage
2020-10-19 15:53:15 +00:00
{
2022-02-15 11:52:43 +00:00
public ICache Cache { get; }
2022-03-25 16:26:06 +00:00
internal readonly ICacheNotify<TariffCacheItem> Notify;
2022-02-15 11:52:43 +00:00
public TariffServiceStorage(ICacheNotify<TariffCacheItem> notify, ICache cache)
2020-02-20 08:05:10 +00:00
{
2022-02-15 11:52:43 +00:00
Cache = cache;
2022-03-25 16:26:06 +00:00
Notify = notify;
Notify.Subscribe((i) =>
2019-12-17 08:27:38 +00:00
{
2022-02-15 11:52:43 +00:00
Cache.Remove(TariffService.GetTariffCacheKey(i.TenantId));
Cache.Remove(TariffService.GetBillingUrlCacheKey(i.TenantId));
Cache.Remove(TariffService.GetBillingPaymentCacheKey(i.TenantId)); // clear all payments
2022-03-09 17:15:51 +00:00
}, CacheNotifyAction.Remove);
2022-02-15 11:52:43 +00:00
//TODO: Change code of WCF -> not supported in .NET standard/.Net Core
/*try
{
var section = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");
if (section != null)
{
2022-02-15 11:52:43 +00:00
billingConfigured = section.Endpoints.Cast<ChannelEndpointElement>()
.Any(e => e.Contract == typeof(IService).FullName);
}
2022-02-15 11:52:43 +00:00
}
catch (Exception err)
{
log.Error(err);
}*/
}
}
2022-02-15 11:52:43 +00:00
[Scope]
class ConfigureTariffService : IConfigureNamedOptions<TariffService>
{
public ConfigureTariffService(
IOptionsSnapshot<CachedQuotaService> quotaService,
IOptionsSnapshot<CachedTenantService> tenantService,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
IConfiguration configuration,
DbContextManager<CoreDbContext> coreDbContextManager,
TariffServiceStorage tariffServiceStorage,
2022-03-20 15:24:26 +00:00
IOptionsMonitor<ILog> options)
2022-02-15 11:52:43 +00:00
{
_quotaService = quotaService;
_tenantService = tenantService;
2022-02-15 11:52:43 +00:00
_coreBaseSettings = coreBaseSettings;
_coreSettings = coreSettings;
_configuration = configuration;
_coreDbContextManager = coreDbContextManager;
_tariffServiceStorage = tariffServiceStorage;
2022-03-20 15:24:26 +00:00
_options = options;
2022-02-15 11:52:43 +00:00
}
private readonly IOptionsSnapshot<CachedQuotaService> _quotaService;
private readonly IOptionsSnapshot<CachedTenantService> _tenantService;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly CoreSettings _coreSettings;
private readonly IConfiguration _configuration;
private readonly DbContextManager<CoreDbContext> _coreDbContextManager;
private readonly TariffServiceStorage _tariffServiceStorage;
2022-03-20 15:24:26 +00:00
private readonly IOptionsMonitor<ILog> _options;
2022-02-15 11:52:43 +00:00
public void Configure(string name, TariffService options)
{
Configure(options);
2022-03-25 16:26:06 +00:00
options.QuotaService = _quotaService.Get(name);
options.TenantService = _tenantService.Get(name);
options.LazyCoreDbContext = new Lazy<CoreDbContext>(() => _coreDbContextManager.Get(name));
2022-02-15 11:52:43 +00:00
}
public void Configure(TariffService options)
{
2022-03-20 15:24:26 +00:00
options.Logger = _options.CurrentValue;
2022-03-25 16:26:06 +00:00
options.CoreSettings = _coreSettings;
options.Configuration = _configuration;
options.TariffServiceStorage = _tariffServiceStorage;
2022-03-20 15:24:26 +00:00
options.Options = _options;
2022-03-25 16:26:06 +00:00
options.CoreBaseSettings = _coreBaseSettings;
options.Test = _configuration["core:payment:test"] == "true";
2022-02-15 11:52:43 +00:00
int.TryParse(_configuration["core:payment:delay"], out var paymentDelay);
2022-03-25 16:26:06 +00:00
options.PaymentDelay = paymentDelay;
options.Cache = _tariffServiceStorage.Cache;
options.Notify = _tariffServiceStorage.Notify;
2022-02-15 11:52:43 +00:00
2022-03-25 16:26:06 +00:00
options.QuotaService = _quotaService.Value;
options.TenantService = _tenantService.Value;
options.LazyCoreDbContext = new Lazy<CoreDbContext>(() => _coreDbContextManager.Value);
2022-02-15 11:52:43 +00:00
}
}
public class TariffService : ITariffService
{
2022-03-25 16:26:06 +00:00
private const int DefaultTrialPeriod = 30;
2022-02-15 11:52:43 +00:00
private static readonly TimeSpan _defaultCacheExpiration = TimeSpan.FromMinutes(5);
private static readonly TimeSpan _standaloneCacheExpiration = TimeSpan.FromMinutes(15);
2022-03-25 16:26:06 +00:00
internal ICache Cache { get; set; }
internal ICacheNotify<TariffCacheItem> Notify { get; set; }
internal ILog Logger { get; set; }
internal IQuotaService QuotaService { get; set; }
internal ITenantService TenantService { get; set; }
internal bool Test { get; set; }
internal int PaymentDelay { get; set; }
2022-02-15 11:52:43 +00:00
public TimeSpan CacheExpiration { get; set; }
2022-03-25 16:26:06 +00:00
internal CoreBaseSettings CoreBaseSettings { get; set; }
internal CoreSettings CoreSettings { get; set; }
internal IConfiguration Configuration { get; set; }
internal CoreDbContext CoreDbContext => LazyCoreDbContext.Value;
internal Lazy<CoreDbContext> LazyCoreDbContext;
internal TariffServiceStorage TariffServiceStorage { get; set; }
internal IOptionsMonitor<ILog> Options { get; set; }
2022-02-15 11:52:43 +00:00
2022-04-15 09:08:06 +00:00
private readonly BillingClient _billingClient;
private readonly IHttpClientFactory _httpClientFactory;
private readonly int _activeUsersMin;
//private readonly int _activeUsersMax;
2022-02-15 11:52:43 +00:00
public TariffService()
{
CacheExpiration = _defaultCacheExpiration;
}
public TariffService(
IQuotaService quotaService,
ITenantService tenantService,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
IConfiguration configuration,
DbContextManager<CoreDbContext> coreDbContextManager,
TariffServiceStorage tariffServiceStorage,
IOptionsMonitor<ILog> options,
Users.Constants constants,
BillingClient billingClient,
IHttpClientFactory httpClientFactory)
2022-02-15 11:52:43 +00:00
: this()
{
2022-03-25 16:26:06 +00:00
Logger = options.CurrentValue;
QuotaService = quotaService;
TenantService = tenantService;
CoreSettings = coreSettings;
Configuration = configuration;
TariffServiceStorage = tariffServiceStorage;
Options = options;
2022-04-15 09:08:06 +00:00
_billingClient = billingClient;
_httpClientFactory = httpClientFactory;
2022-03-25 16:26:06 +00:00
CoreBaseSettings = coreBaseSettings;
Test = configuration["core:payment:test"] == "true";
2022-02-15 11:52:43 +00:00
int.TryParse(configuration["core:payment:delay"], out var paymentDelay);
2022-03-25 16:26:06 +00:00
PaymentDelay = paymentDelay;
2022-02-15 11:52:43 +00:00
2022-03-25 16:26:06 +00:00
Cache = TariffServiceStorage.Cache;
Notify = TariffServiceStorage.Notify;
LazyCoreDbContext = new Lazy<CoreDbContext>(() => coreDbContextManager.Value);
var range = (Configuration["core.payment-user-range"] ?? "").Split('-');
2022-04-15 09:08:06 +00:00
if (!int.TryParse(range[0], out _activeUsersMin))
2022-02-15 11:52:43 +00:00
{
2022-04-15 09:08:06 +00:00
_activeUsersMin = 0;
2022-02-15 11:52:43 +00:00
}
2022-04-15 09:08:06 +00:00
//if (range.Length < 2 || !int.TryParse(range[1], out _activeUsersMax))
//{
// _activeUsersMax = constants.MaxEveryoneCount;
//}
2022-02-15 11:52:43 +00:00
}
public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true)
{
//single tariff for all portals
2022-03-25 16:26:06 +00:00
if (CoreBaseSettings.Standalone)
2022-02-15 11:52:43 +00:00
{
tenantId = -1;
}
var key = GetTariffCacheKey(tenantId);
2022-03-25 16:26:06 +00:00
var tariff = Cache.Get<Tariff>(key);
2022-02-15 11:52:43 +00:00
if (tariff == null)
{
tariff = GetBillingInfo(tenantId);
tariff = CalculateTariff(tenantId, tariff);
2022-03-25 16:26:06 +00:00
Cache.Insert(key, tariff, DateTime.UtcNow.Add(GetCacheExpiration()));
2022-02-15 11:52:43 +00:00
2022-04-15 09:08:06 +00:00
if (_billingClient.Configured && withRequestToPaymentSystem)
2022-02-15 11:52:43 +00:00
{
Task.Run(() =>
{
try
2020-09-30 11:50:39 +00:00
{
2022-02-15 11:52:43 +00:00
var client = GetBillingClient();
var lastPayment = client.GetLastPayment(GetPortalId(tenantId));
2022-03-25 16:26:06 +00:00
var quota = QuotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == lastPayment.ProductId);
2022-02-15 11:52:43 +00:00
if (quota == null)
2020-09-30 11:50:39 +00:00
{
2022-02-15 11:52:43 +00:00
throw new InvalidOperationException($"Quota with id {lastPayment.ProductId} not found for portal {GetPortalId(tenantId)}.");
2020-09-30 11:50:39 +00:00
}
2022-02-15 11:52:43 +00:00
var asynctariff = Tariff.CreateDefault();
asynctariff.QuotaId = quota.Tenant;
asynctariff.Autorenewal = lastPayment.Autorenewal;
asynctariff.DueDate = 9999 <= lastPayment.EndDate.Year ? DateTime.MaxValue : lastPayment.EndDate;
if (quota.ActiveUsers == -1
2022-04-15 09:08:06 +00:00
&& lastPayment.Quantity < _activeUsersMin)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
throw new BillingException(string.Format("The portal {0} is paid for {1} users", tenantId, lastPayment.Quantity));
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
asynctariff.Quantity = lastPayment.Quantity;
if (SaveBillingInfo(tenantId, asynctariff, false))
2020-09-30 11:50:39 +00:00
{
2022-02-15 11:52:43 +00:00
asynctariff = CalculateTariff(tenantId, asynctariff);
ClearCache(tenantId);
2022-03-25 16:26:06 +00:00
Cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration()));
2020-09-30 11:50:39 +00:00
}
2022-02-15 11:52:43 +00:00
}
catch (BillingNotFoundException)
{
}
catch (Exception error)
{
LogError(error, tenantId.ToString());
}
});
}
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
return tariff;
}
public void SetTariff(int tenantId, Tariff tariff)
{
2022-03-09 17:15:51 +00:00
ArgumentNullException.ThrowIfNull(tariff);
2022-02-15 11:52:43 +00:00
2022-03-25 16:26:06 +00:00
var q = QuotaService.GetTenantQuota(tariff.QuotaId);
2022-02-15 11:52:43 +00:00
if (q == null)
{
return;
}
2021-05-17 11:35:00 +00:00
2022-02-15 11:52:43 +00:00
SaveBillingInfo(tenantId, tariff);
if (q.Trial)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
// reset trial date
2022-03-25 16:26:06 +00:00
var tenant = TenantService.GetTenant(tenantId);
2022-02-15 11:52:43 +00:00
if (tenant != null)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
tenant.VersionChanged = DateTime.UtcNow;
2022-03-25 16:26:06 +00:00
TenantService.SaveTenant(CoreSettings, tenant);
2022-02-15 11:52:43 +00:00
}
}
ClearCache(tenantId);
}
internal static string GetTariffCacheKey(int tenantId)
{
return string.Format("{0}:{1}", tenantId, "tariff");
}
internal static string GetBillingUrlCacheKey(int tenantId)
{
return string.Format("{0}:{1}", tenantId, "billing:urls");
}
internal static string GetBillingPaymentCacheKey(int tenantId)
{
return string.Format("{0}:{1}", tenantId, "billing:payments");
}
public void ClearCache(int tenantId)
{
2022-04-15 09:08:06 +00:00
Notify.Publish(new TariffCacheItem { TenantId = tenantId }, CacheNotifyAction.Remove);
2022-02-15 11:52:43 +00:00
}
public IEnumerable<PaymentInfo> GetPayments(int tenantId)
{
var key = GetBillingPaymentCacheKey(tenantId);
2022-03-25 16:26:06 +00:00
var payments = Cache.Get<List<PaymentInfo>>(key);
2022-02-15 11:52:43 +00:00
if (payments == null)
{
payments = new List<PaymentInfo>();
2022-04-15 09:08:06 +00:00
if (_billingClient.Configured)
2022-02-15 11:52:43 +00:00
{
try
2021-05-17 11:35:00 +00:00
{
2022-03-25 16:26:06 +00:00
var quotas = QuotaService.GetTenantQuotas();
2022-02-15 11:52:43 +00:00
var client = GetBillingClient();
foreach (var pi in client.GetPayments(GetPortalId(tenantId)))
2021-11-12 12:33:03 +00:00
{
2022-02-15 11:52:43 +00:00
var quota = quotas.SingleOrDefault(q => q.AvangateId == pi.ProductRef);
if (quota != null)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
pi.QuotaId = quota.Tenant;
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
payments.Add(pi);
2021-05-17 11:35:00 +00:00
}
}
2022-02-15 11:52:43 +00:00
catch (Exception error)
{
LogError(error, tenantId.ToString());
}
2021-05-17 11:35:00 +00:00
}
2022-03-25 16:26:06 +00:00
Cache.Insert(key, payments, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)));
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
return payments;
}
public Uri GetShoppingUri(int? tenant, int quotaId, string affiliateId, string currency = null, string language = null, string customerId = null, string quantity = null)
{
2022-03-25 16:26:06 +00:00
var quota = QuotaService.GetTenantQuota(quotaId);
2022-02-15 11:52:43 +00:00
if (quota == null)
{
return null;
}
var key = tenant.HasValue
? GetBillingUrlCacheKey(tenant.Value)
: string.Format($"notenant{(!string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : "")}");
key += quota.Visible ? "" : "0";
2022-04-14 19:23:57 +00:00
if (Cache.Get<Dictionary<string, Tuple<Uri, Uri>>>(key) is not IDictionary<string, Tuple<Uri, Uri>> urls)
2022-02-15 11:52:43 +00:00
{
urls = new Dictionary<string, Tuple<Uri, Uri>>();
2022-04-15 09:08:06 +00:00
if (_billingClient.Configured)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
try
2021-05-17 11:35:00 +00:00
{
2022-03-25 16:26:06 +00:00
var products = QuotaService.GetTenantQuotas()
2022-02-15 11:52:43 +00:00
.Where(q => !string.IsNullOrEmpty(q.AvangateId) && q.Visible == quota.Visible)
.Select(q => q.AvangateId)
.ToArray();
var client = GetBillingClient();
urls =
client.GetPaymentUrls(
tenant.HasValue ? GetPortalId(tenant.Value) : null,
products,
tenant.HasValue ? GetAffiliateId(tenant.Value) : affiliateId,
tenant.HasValue ? GetCampaign(tenant.Value) : null,
!string.IsNullOrEmpty(currency) ? "__Currency__" : null,
!string.IsNullOrEmpty(language) ? "__Language__" : null,
!string.IsNullOrEmpty(customerId) ? "__CustomerID__" : null,
!string.IsNullOrEmpty(quantity) ? "__Quantity__" : null
);
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
catch (Exception error)
2021-05-17 11:35:00 +00:00
{
2022-03-25 16:26:06 +00:00
Logger.Error(error);
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
}
2022-03-25 16:26:06 +00:00
Cache.Insert(key, urls, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)));
2022-02-15 11:52:43 +00:00
}
ResetCacheExpiration();
if (!string.IsNullOrEmpty(quota.AvangateId) && urls.TryGetValue(quota.AvangateId, out var tuple))
{
var result = tuple.Item2;
2021-05-17 11:35:00 +00:00
2022-02-15 11:52:43 +00:00
if (result == null)
{
result = tuple.Item1;
}
else
{
var tariff = tenant.HasValue ? GetTariff(tenant.Value) : null;
if (tariff == null || tariff.QuotaId == quotaId || tariff.State >= TariffState.Delay)
{
2022-02-15 11:52:43 +00:00
result = tuple.Item1;
}
2022-02-15 11:52:43 +00:00
}
2021-05-17 11:35:00 +00:00
2022-02-15 11:52:43 +00:00
if (result == null)
{
return null;
}
2021-05-17 11:35:00 +00:00
2022-02-15 11:52:43 +00:00
result = new Uri(result.ToString()
.Replace("__Currency__", HttpUtility.UrlEncode(currency ?? ""))
.Replace("__Language__", HttpUtility.UrlEncode((language ?? "").ToLower()))
.Replace("__CustomerID__", HttpUtility.UrlEncode(customerId ?? ""))
.Replace("__Quantity__", HttpUtility.UrlEncode(quantity ?? "")));
return result;
}
return null;
}
public IDictionary<string, Dictionary<string, decimal>> GetProductPriceInfo(params string[] productIds)
{
2022-03-09 17:15:51 +00:00
ArgumentNullException.ThrowIfNull(productIds);
2022-02-15 11:52:43 +00:00
try
{
var key = "biling-prices" + string.Join(",", productIds);
2022-03-25 16:26:06 +00:00
var result = Cache.Get<IDictionary<string, Dictionary<string, decimal>>>(key);
2022-02-15 11:52:43 +00:00
if (result == null)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
var client = GetBillingClient();
result = client.GetProductPriceInfo(productIds);
2022-03-25 16:26:06 +00:00
Cache.Insert(key, result, DateTime.Now.AddHours(1));
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
return result;
}
catch (Exception error)
{
LogError(error);
return productIds
.Select(p => new { ProductId = p, Prices = new Dictionary<string, decimal>() })
.ToDictionary(e => e.ProductId, e => e.Prices);
}
}
public string GetButton(int tariffId, string partnerId)
{
return CoreDbContext.Buttons
.Where(r => r.TariffId == tariffId && r.PartnerId == partnerId)
.Select(r => r.ButtonUrl)
.SingleOrDefault();
}
public void SaveButton(int tariffId, string partnerId, string buttonUrl)
{
var efButton = new DbButton()
{
TariffId = tariffId,
PartnerId = partnerId,
ButtonUrl = buttonUrl
};
CoreDbContext.AddOrUpdate(r => r.Buttons, efButton);
CoreDbContext.SaveChanges();
}
private Tariff GetBillingInfo(int tenant)
{
var r = CoreDbContext.Tariffs
.Where(r => r.Tenant == tenant)
.OrderByDescending(r => r.Id)
.FirstOrDefault();
if (r == null)
{
return Tariff.CreateDefault();
}
var tariff = Tariff.CreateDefault();
tariff.QuotaId = r.Tariff;
tariff.DueDate = r.Stamp.Year < 9999 ? r.Stamp : DateTime.MaxValue;
tariff.Quantity = r.Quantity;
return tariff;
}
private bool SaveBillingInfo(int tenant, Tariff tariffInfo, bool renewal = true)
{
var inserted = false;
var currentTariff = GetBillingInfo(tenant);
if (!tariffInfo.EqualsByParams(currentTariff))
{
var strategy = CoreDbContext.Database.CreateExecutionStrategy();
2022-02-15 11:52:43 +00:00
strategy.Execute(() =>
2021-05-17 11:35:00 +00:00
{
using var tx = CoreDbContext.Database.BeginTransaction();
// last record is not the same
var any = CoreDbContext.Tariffs
.Any(r => r.Tenant == tenant && r.Tariff == tariffInfo.QuotaId && r.Stamp == tariffInfo.DueDate && r.Quantity == tariffInfo.Quantity);
if (tariffInfo.DueDate == DateTime.MaxValue || renewal || any)
{
var efTariff = new DbTariff
{
Tenant = tenant,
Tariff = tariffInfo.QuotaId,
Stamp = tariffInfo.DueDate,
Quantity = tariffInfo.Quantity,
CreateOn = DateTime.UtcNow
};
CoreDbContext.Tariffs.Add(efTariff);
CoreDbContext.SaveChanges();
Cache.Remove(GetTariffCacheKey(tenant));
inserted = true;
}
2022-02-15 11:52:43 +00:00
tx.Commit();
});
2022-02-15 11:52:43 +00:00
}
if (inserted)
{
2022-03-25 16:26:06 +00:00
var t = TenantService.GetTenant(tenant);
2022-02-15 11:52:43 +00:00
if (t != null)
{
2022-02-15 11:52:43 +00:00
// update tenant.LastModified to flush cache in documents
2022-03-25 16:26:06 +00:00
TenantService.SaveTenant(CoreSettings, t);
}
2022-02-15 11:52:43 +00:00
}
2021-05-17 11:35:00 +00:00
2022-02-15 11:52:43 +00:00
return inserted;
}
2022-02-15 11:52:43 +00:00
public void DeleteDefaultBillingInfo()
{
const int tenant = Tenant.DefaultTenant;
2022-02-15 11:52:43 +00:00
var tariffs = CoreDbContext.Tariffs.Where(r => r.Tenant == tenant).ToList();
foreach (var t in tariffs)
{
t.Tenant = -2;
}
CoreDbContext.SaveChanges();
ClearCache(tenant);
}
private Tariff CalculateTariff(int tenantId, Tariff tariff)
{
tariff.State = TariffState.Paid;
2022-03-25 16:26:06 +00:00
var q = QuotaService.GetTenantQuota(tariff.QuotaId);
2022-02-15 11:52:43 +00:00
if (q == null || q.GetFeature("old"))
{
tariff.QuotaId = Tenant.DefaultTenant;
2022-03-25 16:26:06 +00:00
q = QuotaService.GetTenantQuota(tariff.QuotaId);
2022-02-15 11:52:43 +00:00
}
var delay = 0;
if (q != null && q.Trial)
{
tariff.State = TariffState.Trial;
if (tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue)
{
2022-03-25 16:26:06 +00:00
var tenant = TenantService.GetTenant(tenantId);
2022-02-15 11:52:43 +00:00
if (tenant != null)
{
2022-02-15 11:52:43 +00:00
var fromDate = tenant.CreationDateTime < tenant.VersionChanged ? tenant.VersionChanged : tenant.CreationDateTime;
2022-03-25 16:26:06 +00:00
var trialPeriod = GetPeriod("TrialPeriod", DefaultTrialPeriod);
2022-02-15 11:52:43 +00:00
if (fromDate == DateTime.MinValue)
{
2022-02-15 11:52:43 +00:00
fromDate = DateTime.UtcNow.Date;
}
2022-02-15 11:52:43 +00:00
tariff.DueDate = trialPeriod != default ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue;
}
else
{
tariff.DueDate = DateTime.MaxValue;
}
}
}
else
{
2022-03-25 16:26:06 +00:00
delay = PaymentDelay;
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
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)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
tariff.State = TariffState.NotPaid;
2022-03-25 16:26:06 +00:00
if (CoreBaseSettings.Standalone)
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
if (q != null)
{
2022-03-25 16:26:06 +00:00
var defaultQuota = QuotaService.GetTenantQuota(Tenant.DefaultTenant);
2022-02-15 11:52:43 +00:00
defaultQuota.Name = "overdue";
defaultQuota.Features = q.Features;
defaultQuota.Support = false;
2022-03-25 16:26:06 +00:00
QuotaService.SaveTenantQuota(defaultQuota);
2022-02-15 11:52:43 +00:00
}
var unlimTariff = Tariff.CreateDefault();
unlimTariff.LicenseDate = tariff.DueDate;
tariff = unlimTariff;
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
}
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;
}
private int GetPeriod(string key, int defaultValue)
{
2022-03-25 16:26:06 +00:00
var settings = TenantService.GetTenantSettings(Tenant.DefaultTenant, key);
2022-02-15 11:52:43 +00:00
return settings != null ? Convert.ToInt32(Encoding.UTF8.GetString(settings)) : defaultValue;
}
private BillingClient GetBillingClient()
{
try
{
2022-04-15 09:08:06 +00:00
return new BillingClient(Test, Configuration, _httpClientFactory);
2022-02-15 11:52:43 +00:00
}
catch (InvalidOperationException ioe)
{
throw new BillingNotConfiguredException(ioe.Message, ioe);
}
catch (ReflectionTypeLoadException rtle)
{
2022-03-25 16:26:06 +00:00
Logger.ErrorFormat("{0}{1}LoaderExceptions: {2}",
2022-02-15 11:52:43 +00:00
rtle,
Environment.NewLine,
string.Join(Environment.NewLine, rtle.LoaderExceptions.Select(e => e.ToString())));
throw;
}
}
private string GetPortalId(int tenant)
{
2022-03-25 16:26:06 +00:00
return CoreSettings.GetKey(tenant);
2022-02-15 11:52:43 +00:00
}
private string GetAffiliateId(int tenant)
{
2022-03-25 16:26:06 +00:00
return CoreSettings.GetAffiliateId(tenant);
2022-02-15 11:52:43 +00:00
}
private string GetCampaign(int tenant)
{
2022-03-25 16:26:06 +00:00
return CoreSettings.GetCampaign(tenant);
2022-02-15 11:52:43 +00:00
}
private TimeSpan GetCacheExpiration()
{
2022-03-25 16:26:06 +00:00
if (CoreBaseSettings.Standalone && CacheExpiration < _standaloneCacheExpiration)
2022-02-15 11:52:43 +00:00
{
CacheExpiration = CacheExpiration.Add(TimeSpan.FromSeconds(30));
}
return CacheExpiration;
}
private void ResetCacheExpiration()
{
2022-03-25 16:26:06 +00:00
if (CoreBaseSettings.Standalone)
2022-02-15 11:52:43 +00:00
{
CacheExpiration = _defaultCacheExpiration;
}
}
private void LogError(Exception error, string tenantId = null)
{
if (error is BillingNotFoundException)
{
2022-03-25 16:26:06 +00:00
Logger.DebugFormat("Payment tenant {0} not found: {1}", tenantId, error.Message);
2022-02-15 11:52:43 +00:00
}
else if (error is BillingNotConfiguredException)
{
2022-03-25 16:26:06 +00:00
Logger.DebugFormat("Billing tenant {0} not configured: {1}", tenantId, error.Message);
2022-02-15 11:52:43 +00:00
}
else
{
2022-03-25 16:26:06 +00:00
if (Logger.IsDebugEnabled)
2021-05-17 11:35:00 +00:00
{
2022-03-25 16:26:06 +00:00
Logger.Error("Billing tenant " + tenantId);
Logger.Error(error);
2021-05-17 11:35:00 +00:00
}
else
{
2022-03-25 16:26:06 +00:00
Logger.ErrorFormat("Billing tenant {0}: {1}", tenantId, error.Message);
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
}
}
}