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

818 lines
30 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
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-07-28 12:29:03 +00:00
private readonly ICache _cache;
private readonly ICacheNotify<TariffCacheItem> _notify;
private readonly ILogger<TariffService> _logger;
private readonly IQuotaService _quotaService;
private readonly ITenantService _tenantService;
2022-07-14 11:19:23 +00:00
private readonly IUserService _userService;
2022-07-28 12:29:03 +00:00
private readonly int _paymentDelay;
private TimeSpan _cacheExpiration;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly CoreSettings _coreSettings;
private readonly IDbContextFactory<CoreDbContext> _dbContextFactory;
private readonly TariffServiceStorage _tariffServiceStorage;
2022-04-15 09:08:06 +00:00
private readonly BillingClient _billingClient;
2022-09-06 09:14:08 +00:00
private readonly IServiceProvider _serviceProvider;
//private readonly int _activeUsersMin;
2022-04-15 09:08:06 +00:00
//private readonly int _activeUsersMax;
2022-02-15 11:52:43 +00:00
public TariffService()
{
2022-07-28 12:29:03 +00:00
_cacheExpiration = _defaultCacheExpiration;
2022-02-15 11:52:43 +00:00
}
public TariffService(
IQuotaService quotaService,
ITenantService tenantService,
2022-07-14 11:19:23 +00:00
IUserService userService,
2022-02-15 11:52:43 +00:00
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
IConfiguration configuration,
2022-07-28 12:29:03 +00:00
IDbContextFactory<CoreDbContext> coreDbContextManager,
2022-02-15 11:52:43 +00:00
TariffServiceStorage tariffServiceStorage,
ILogger<TariffService> logger,
2022-09-06 09:14:08 +00:00
BillingClient billingClient,
IServiceProvider serviceProvider)
2022-02-15 11:52:43 +00:00
: this()
{
2022-07-28 12:29:03 +00:00
_logger = logger;
_quotaService = quotaService;
_tenantService = tenantService;
2022-07-14 11:19:23 +00:00
_userService = userService;
2022-07-28 12:29:03 +00:00
_coreSettings = coreSettings;
_tariffServiceStorage = tariffServiceStorage;
2022-04-15 09:08:06 +00:00
_billingClient = billingClient;
2022-09-06 09:14:08 +00:00
_serviceProvider = serviceProvider;
2022-07-28 12:29:03 +00:00
_coreBaseSettings = coreBaseSettings;
_paymentDelay = configuration.GetSection("core:payment").Get<PaymentConfiguration>().Delay;
2022-02-15 11:52:43 +00:00
2022-07-28 12:29:03 +00:00
_cache = _tariffServiceStorage.Cache;
_notify = _tariffServiceStorage.Notify;
_dbContextFactory = coreDbContextManager;
//var range = (_configuration["core.payment-user-range"] ?? "").Split('-');
//if (!int.TryParse(range[0], out _activeUsersMin))
//{
// _activeUsersMin = 0;
//}
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-07-28 12:29:03 +00:00
if (_coreBaseSettings.Standalone)
2022-02-15 11:52:43 +00:00
{
tenantId = -1;
}
var key = GetTariffCacheKey(tenantId);
2022-07-28 12:29:03 +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-07-28 12:29:03 +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
{
2022-07-13 08:47:26 +00:00
//Task.Run(() =>
// {
2022-08-24 16:05:15 +00:00
try
{
var currentPayments = _billingClient.GetCurrentPayments(GetPortalId(tenantId));
2022-08-24 16:05:15 +00:00
if (currentPayments.Length == 0) throw new BillingNotFoundException("Empty PaymentLast");
var asynctariff = Tariff.CreateDefault(true);
string email = null;
foreach (var currentPayment in currentPayments)
{
var quota = _quotaService.GetTenantQuotas().SingleOrDefault(q => q.ProductId == currentPayment.ProductId.ToString());
if (quota == null)
{
throw new InvalidOperationException($"Quota with id {currentPayment.ProductId} not found for portal {GetPortalId(tenantId)}.");
}
var paymentEndDate = 9999 <= currentPayment.EndDate.Year ? DateTime.MaxValue : currentPayment.EndDate;
asynctariff.DueDate = DateTime.Compare(asynctariff.DueDate, paymentEndDate) < 0 ? asynctariff.DueDate : paymentEndDate;
asynctariff.Quotas.Add(new Tuple<int, int>(quota.Tenant, currentPayment.Quantity));
email = currentPayment.PaymentEmail;
}
if (!string.IsNullOrEmpty(email))
{
var customer = _userService.GetUser(tenantId, email);
asynctariff.CustomerId = customer != null && !customer.Removed ? customer.Id : Guid.Empty;
}
if (SaveBillingInfo(tenantId, asynctariff))
{
asynctariff = CalculateTariff(tenantId, asynctariff);
ClearCache(tenantId);
_cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration()));
}
}
catch (BillingNotFoundException)
{
var freeTariff = tariff.Quotas.Exists(tariffRow =>
{
var q = _quotaService.GetTenantQuota(tariffRow.Item1);
return q == null
|| q.Trial
|| q.Free
|| q.NonProfit
|| q.Custom;
});
if (!freeTariff)
{
var asynctariff = Tariff.CreateDefault();
asynctariff.DueDate = DateTime.Today.AddDays(-1);
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());
}
//});
}
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
return tariff;
}
2022-08-05 12:36:00 +00:00
public bool PaymentChange(int tenantId, Dictionary<string, int> quantity)
{
if (quantity == null || !quantity.Any()
|| !_billingClient.Configured)
return false;
var allQuotas = _quotaService.GetTenantQuotas().Where(q => !string.IsNullOrEmpty(q.ProductId));
var newQuotas = quantity.Keys.Select(name => allQuotas.FirstOrDefault(q => q.Name == name));
var tariff = GetTariff(tenantId);
// update the quantity of present quotas
TenantQuota updatedQuota = null;
foreach (var tariffRow in tariff.Quotas)
{
var quotaId = tariffRow.Item1;
var qty = tariffRow.Item2;
var quota = _quotaService.GetTenantQuota(quotaId);
var mustUpdateQuota = newQuotas.FirstOrDefault(q => q.Tenant == quota.Tenant);
if (mustUpdateQuota != null)
{
qty = quantity[mustUpdateQuota.Name];
}
2022-08-24 16:05:15 +00:00
quota *= qty;
updatedQuota += quota;
}
// add new quotas
var addedQuotas = newQuotas.Where(q => !tariff.Quotas.Any(t => t.Item1 == q.Tenant));
foreach (var addedQuota in addedQuotas)
{
var qty = quantity[addedQuota.Name];
var quota = addedQuota;
2022-08-24 16:05:15 +00:00
quota *= qty;
updatedQuota += quota;
}
2022-09-06 09:14:08 +00:00
updatedQuota.Check(_serviceProvider);
var productIds = newQuotas.Select(q => q.ProductId);
2022-08-05 12:36:00 +00:00
try
{
var changed = _billingClient.ChangePayment(GetPortalId(tenantId), productIds.ToArray(), quantity.Values.ToArray());
2022-08-05 12:36:00 +00:00
if (!changed) return false;
ClearCache(tenantId);
}
catch (Exception error)
{
_logger.ErrorWithException(error);
}
return true;
}
2022-02-15 11:52:43 +00:00
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
List<TenantQuota> quotas = null;
if (tariff.Quotas == null ||
(quotas = tariff.Quotas.Select(q => _quotaService.GetTenantQuota(q.Item1)).ToList()).Any(q => q == null))
2022-02-15 11:52:43 +00:00
{
return;
}
2021-05-17 11:35:00 +00:00
2022-02-15 11:52:43 +00:00
SaveBillingInfo(tenantId, tariff);
if (quotas.Any(q => q.Trial))
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
// reset trial date
2022-07-28 12:29:03 +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-07-28 12:29:03 +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-07-28 12:29:03 +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-07-28 12:29:03 +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-07-28 12:29:03 +00:00
var quotas = _quotaService.GetTenantQuotas();
foreach (var pi in _billingClient.GetPayments(GetPortalId(tenantId)))
2021-11-12 12:33:03 +00:00
{
2022-07-14 13:12:01 +00:00
var quota = quotas.SingleOrDefault(q => q.ProductId == pi.ProductRef.ToString());
2022-02-15 11:52:43 +00:00
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-07-28 12:29:03 +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, string currency = null, string language = null, string customerEmail = null, Dictionary<string, int> quantity = null, string backUrl = null)
2022-07-14 09:10:05 +00:00
{
var hasQuantity = quantity != null && quantity.Any();
var key = "shopingurl_" + (hasQuantity ? string.Join('_', quantity.Keys.ToArray()) : "all");
2022-07-14 09:10:05 +00:00
var url = _cache.Get<string>(key);
if (url == null)
{
url = string.Empty;
if (_billingClient.Configured)
{
var allQuotas = _quotaService.GetTenantQuotas().Where(q => !string.IsNullOrEmpty(q.ProductId) && q.Visible);
var newQuotas = quantity.Select(item => allQuotas.FirstOrDefault(q => q.Name == item.Key));
TenantQuota updatedQuota = null;
foreach (var addedQuota in newQuotas)
{
var qty = quantity[addedQuota.Name];
var quota = addedQuota;
quota *= qty;
updatedQuota += quota;
}
2022-09-06 09:14:08 +00:00
updatedQuota.Check(_serviceProvider);
var productIds = newQuotas.Select(q => q.ProductId);
2022-07-14 09:10:05 +00:00
try
{
2022-07-14 09:10:05 +00:00
url =
_billingClient.GetPaymentUrl(
2022-07-14 09:10:05 +00:00
"__Tenant__",
productIds.ToArray(),
null,
null,
!string.IsNullOrEmpty(currency) ? "__Currency__" : null,
!string.IsNullOrEmpty(language) ? "__Language__" : null,
2022-07-14 11:19:23 +00:00
!string.IsNullOrEmpty(customerEmail) ? "__CustomerEmail__" : null,
hasQuantity ? "__Quantity__" : null,
2022-07-14 13:27:34 +00:00
!string.IsNullOrEmpty(backUrl) ? "__BackUrl__" : null
2022-07-14 09:10:05 +00:00
);
}
catch (Exception error)
{
_logger.ErrorWithException(error);
}
}
_cache.Insert(key, url, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)));
}
ResetCacheExpiration();
if (string.IsNullOrEmpty(url))
{
return null;
}
var result = new Uri(url.ToString()
.Replace("__Tenant__", HttpUtility.UrlEncode(GetPortalId(tenant)))
.Replace("__Currency__", HttpUtility.UrlEncode(currency ?? ""))
.Replace("__Language__", HttpUtility.UrlEncode((language ?? "").ToLower()))
2022-07-14 11:19:23 +00:00
.Replace("__CustomerEmail__", HttpUtility.UrlEncode(customerEmail ?? ""))
.Replace("__Quantity__", hasQuantity ? string.Join(',', quantity.Values) : "")
.Replace("__BackUrl__", HttpUtility.UrlEncode(backUrl ?? "")));
2022-07-14 09:10:05 +00:00
return result;
}
2022-02-15 11:52:43 +00:00
public Uri GetShoppingUri(int? tenant, int quotaId, string affiliateId, string currency = null, string language = null, string customerId = null, string quantity = null)
{
2022-07-28 12:29:03 +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-07-28 12:29:03 +00:00
if (_cache.Get<Dictionary<string, Uri>>(key) is not IDictionary<string, Uri> urls)
2022-02-15 11:52:43 +00:00
{
2022-06-01 14:07:08 +00:00
urls = new Dictionary<string, 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-07-28 12:29:03 +00:00
var products = _quotaService.GetTenantQuotas()
.Where(q => !string.IsNullOrEmpty(q.ProductId) && q.Visible == quota.Visible)
.Select(q => q.ProductId)
2022-02-15 11:52:43 +00:00
.ToArray();
urls =
_billingClient.GetPaymentUrls(
2022-02-15 11:52:43 +00:00
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-07-28 12:29:03 +00:00
_logger.ErrorGetShoppingUri(error);
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
}
2022-07-28 12:29:03 +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.ProductId) && urls.TryGetValue(quota.ProductId, out var url))
2022-02-15 11:52:43 +00:00
{
2022-06-01 14:07:08 +00:00
if (url == null)
2022-02-15 11:52:43 +00:00
{
return null;
}
2021-05-17 11:35:00 +00:00
2022-06-01 14:07:08 +00:00
url = new Uri(url.ToString()
2022-02-15 11:52:43 +00:00
.Replace("__Currency__", HttpUtility.UrlEncode(currency ?? ""))
.Replace("__Language__", HttpUtility.UrlEncode((language ?? "").ToLower()))
.Replace("__CustomerID__", HttpUtility.UrlEncode(customerId ?? ""))
.Replace("__Quantity__", HttpUtility.UrlEncode(quantity ?? "")));
2022-06-01 14:07:08 +00:00
return url;
2022-02-15 11:52:43 +00:00
}
return null;
}
2022-06-01 14:07:08 +00:00
public Uri GetShoppingUri(string[] productIds, string affiliateId = null, string currency = null, string language = null, string customerId = null, string quantity = null)
{
var key = "shopingurl" + string.Join("_", productIds) + (!string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : "");
2022-07-28 12:29:03 +00:00
var url = _cache.Get<string>(key);
2022-06-01 14:07:08 +00:00
if (url == null)
{
url = string.Empty;
if (_billingClient.Configured)
{
try
{
url =
_billingClient.GetPaymentUrl(
2022-06-01 14:07:08 +00:00
null,
productIds,
affiliateId,
null,
!string.IsNullOrEmpty(currency) ? "__Currency__" : null,
!string.IsNullOrEmpty(language) ? "__Language__" : null,
!string.IsNullOrEmpty(customerId) ? "__CustomerID__" : null,
!string.IsNullOrEmpty(quantity) ? "__Quantity__" : null
);
}
catch (Exception error)
{
2022-07-28 12:29:03 +00:00
_logger.ErrorWithException(error);
2022-06-01 14:07:08 +00:00
}
}
2022-07-28 12:29:03 +00:00
_cache.Insert(key, url, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)));
2022-06-01 14:07:08 +00:00
}
ResetCacheExpiration();
if (string.IsNullOrEmpty(url))
{
return null;
}
var result = new Uri(url.ToString()
.Replace("__Currency__", HttpUtility.UrlEncode(currency ?? ""))
.Replace("__Language__", HttpUtility.UrlEncode((language ?? "").ToLower()))
.Replace("__CustomerID__", HttpUtility.UrlEncode(customerId ?? ""))
.Replace("__Quantity__", HttpUtility.UrlEncode(quantity ?? "")));
return result;
}
2022-02-15 11:52:43 +00:00
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-07-28 12:29:03 +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
{
result = _billingClient.GetProductPriceInfo(productIds);
2022-07-28 12:29:03 +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);
}
}
2022-07-14 13:27:34 +00:00
public Uri GetAccountLink(int tenant, string backUrl)
2022-07-14 13:12:01 +00:00
{
var key = "accountlink_" + tenant;
var url = _cache.Get<string>(key);
if (url == null)
{
if (_billingClient.Configured)
{
try
{
url = _billingClient.GetAccountLink(GetPortalId(tenant), backUrl);
2022-07-14 13:12:01 +00:00
}
catch (Exception error)
{
LogError(error);
}
}
_cache.Insert(key, url, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)));
}
if (!string.IsNullOrEmpty(url))
{
return new Uri(url);
}
return null;
}
2022-02-15 11:52:43 +00:00
private Tariff GetBillingInfo(int tenant)
{
2022-07-28 12:29:03 +00:00
using var coreDbContext = _dbContextFactory.CreateDbContext();
var r = coreDbContext.Tariffs
2022-02-15 11:52:43 +00:00
.Where(r => r.Tenant == tenant)
.OrderByDescending(r => r.Id)
.FirstOrDefault();
if (r == null)
{
return Tariff.CreateDefault();
}
var tariff = Tariff.CreateDefault(true);
2022-02-15 11:52:43 +00:00
tariff.DueDate = r.Stamp.Year < 9999 ? r.Stamp : DateTime.MaxValue;
2022-07-14 11:19:23 +00:00
tariff.CustomerId = r.CustomerId;
var tariffRows = coreDbContext.TariffRows
2022-08-30 16:01:12 +00:00
.Where(row => row.TariffId == r.Id && row.Tenant == tenant);
tariff.Quotas = tariffRows.Select(r => new Tuple<int, int>(r.Quota, r.Quantity)).ToList();
2022-02-15 11:52:43 +00:00
return tariff;
}
private bool SaveBillingInfo(int tenant, Tariff tariffInfo)
2022-02-15 11:52:43 +00:00
{
var inserted = false;
var currentTariff = GetBillingInfo(tenant);
if (!tariffInfo.EqualsByParams(currentTariff))
{
2022-07-28 12:29:03 +00:00
using var dbContext = _dbContextFactory.CreateDbContext();
var strategy = dbContext.Database.CreateExecutionStrategy();
2022-02-15 11:52:43 +00:00
strategy.Execute(() =>
2022-07-28 12:29:03 +00:00
{
using var dbContext = _dbContextFactory.CreateDbContext();
using var tx = dbContext.Database.BeginTransaction();
var efTariff = new DbTariff
{
Tenant = tenant,
Stamp = tariffInfo.DueDate,
2022-07-14 11:19:23 +00:00
CustomerId = tariffInfo.CustomerId,
CreateOn = DateTime.UtcNow
};
2022-07-28 12:29:03 +00:00
2022-08-30 16:01:12 +00:00
efTariff = dbContext.Tariffs.Add(efTariff).Entity;
dbContext.SaveChanges();
var tariffRows = tariffInfo.Quotas.Select(q => new DbTariffRow
{
TariffId = efTariff.Id,
Quota = q.Item1,
Quantity = q.Item2,
Tenant = tenant
});
dbContext.TariffRows.AddRange(tariffRows);
dbContext.SaveChanges();
2022-07-28 12:29:03 +00:00
_cache.Remove(GetTariffCacheKey(tenant));
inserted = true;
2022-02-15 11:52:43 +00:00
2022-07-28 12:29:03 +00:00
tx.Commit();
});
2022-02-15 11:52:43 +00:00
}
if (inserted)
{
2022-07-28 12:29:03 +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-07-28 12:29:03 +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-07-28 12:29:03 +00:00
using var coreDbContext = _dbContextFactory.CreateDbContext();
var tariffs = coreDbContext.Tariffs.Where(r => r.Tenant == tenant).ToList();
2022-02-15 11:52:43 +00:00
foreach (var t in tariffs)
{
t.Tenant = -2;
t.CreateOn = DateTime.UtcNow;
2022-02-15 11:52:43 +00:00
}
2022-07-28 12:29:03 +00:00
coreDbContext.SaveChanges();
2022-02-15 11:52:43 +00:00
ClearCache(tenant);
}
private Tariff CalculateTariff(int tenantId, Tariff tariff)
{
tariff.State = TariffState.Paid;
if (tariff.Quotas.Count == 0)
2022-02-15 11:52:43 +00:00
{
tariff.Quotas.Add(new Tuple<int, int>(Tenant.DefaultTenant, 1));
2022-02-15 11:52:43 +00:00
}
var trial = tariff.Quotas.Exists(q => _quotaService.GetTenantQuota(q.Item1).Trial);
2022-02-15 11:52:43 +00:00
var delay = 0;
if (trial)
2022-02-15 11:52:43 +00:00
{
tariff.State = TariffState.Trial;
if (tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue)
{
2022-07-28 12:29:03 +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-07-28 12:29:03 +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;
}
return tariff;
}
private int GetPeriod(string key, int defaultValue)
{
2022-07-28 12:29:03 +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 string GetPortalId(int tenant)
{
2022-07-28 12:29:03 +00:00
return _coreSettings.GetKey(tenant);
2022-02-15 11:52:43 +00:00
}
private string GetAffiliateId(int tenant)
{
2022-07-28 12:29:03 +00:00
return _coreSettings.GetAffiliateId(tenant);
2022-02-15 11:52:43 +00:00
}
private string GetCampaign(int tenant)
{
2022-07-28 12:29:03 +00:00
return _coreSettings.GetCampaign(tenant);
2022-02-15 11:52:43 +00:00
}
private TimeSpan GetCacheExpiration()
{
2022-07-28 12:29:03 +00:00
if (_coreBaseSettings.Standalone && _cacheExpiration < _standaloneCacheExpiration)
2022-02-15 11:52:43 +00:00
{
2022-07-28 12:29:03 +00:00
_cacheExpiration = _cacheExpiration.Add(TimeSpan.FromSeconds(30));
2022-02-15 11:52:43 +00:00
}
2022-07-28 12:29:03 +00:00
return _cacheExpiration;
2022-02-15 11:52:43 +00:00
}
private void ResetCacheExpiration()
{
2022-07-28 12:29:03 +00:00
if (_coreBaseSettings.Standalone)
2022-02-15 11:52:43 +00:00
{
2022-07-28 12:29:03 +00:00
_cacheExpiration = _defaultCacheExpiration;
2022-02-15 11:52:43 +00:00
}
}
private void LogError(Exception error, string tenantId = null)
{
if (error is BillingNotFoundException)
{
2022-07-28 12:29:03 +00:00
_logger.DebugPaymentTenant(tenantId, error.Message);
2022-02-15 11:52:43 +00:00
}
else if (error is BillingNotConfiguredException)
{
2022-07-28 12:29:03 +00:00
_logger.DebugBillingTenant(tenantId, error.Message);
2022-02-15 11:52:43 +00:00
}
else
{
2022-07-28 12:29:03 +00:00
if (_logger.IsEnabled(LogLevel.Debug))
2021-05-17 11:35:00 +00:00
{
2022-07-28 12:29:03 +00:00
_logger.ErrorBillingWithException(tenantId, error);
2021-05-17 11:35:00 +00:00
}
else
{
2022-07-28 12:29:03 +00:00
_logger.ErrorBilling(tenantId, error.Message);
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
}
}
}