feat: add resource quotas, PayPal subscriptions and paid disk allowances

Calculate and enforce configurable resource consumption, expose balances in PostIt and document the rule in CGU. Add confirmed monthly PayPal credits and disk quotas of twice the free default for Discovery and five times for Premium, with payment reconciliation, migrations and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-08 05:02:23 +00:00
commit 650e5f5e30
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
69 changed files with 19111 additions and 203 deletions

View file

@ -1,4 +1,5 @@
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Yavsc;
using Yavsc.Models;
using Yavsc.Services;
@ -40,7 +41,7 @@ public class DiskUsageTracker : IDiskUsageTracker
DUTInfo usage = new DUTInfo
{
Usage = user.DiskUsage,
Quota = user.DiskQuota
Quota = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow)
};
DiskUsage.Add(username, usage);
if (DiskUsage.Count > ulistLength)
@ -71,6 +72,8 @@ public class DiskUsageTracker : IDiskUsageTracker
public bool GetSpace(string userName, long space)
{
var info = GetInfo(userName);
var user = context.Users.AsNoTracking().Single(u => u.UserName == userName);
info.Quota = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow);
if (info.Quota < info.Usage + space) return false;
info.Usage += space;
#pragma warning disable CS4014

View file

@ -0,0 +1,249 @@
#nullable enable
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Options;
using Yavsc.Models.Payment;
using Yavsc.Settings;
namespace Yavsc.Web.Services;
public sealed class SubscriptionOperationException(int statusCode, string message) : Exception(message)
{
public int StatusCode { get; } = statusCode;
}
public sealed record PayPalSubscriptionDetails(string Id, string CustomId, string PlanId, string State,
DateTimeOffset? StartsAt, DateTimeOffset? NextBillingAt, string? ApprovalUrl);
public sealed record PayPalSubscriptionTransaction(string Id, string State, decimal Amount, string Currency, DateTimeOffset PaidAt);
public interface IPayPalSubscriptionGateway
{
Task<PayPalSubscriptionDetails> CreateAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct);
Task<PayPalSubscriptionDetails> GetAsync(string id, CancellationToken ct);
Task<IReadOnlyList<PayPalSubscriptionTransaction>> TransactionsAsync(string id, DateTimeOffset from, DateTimeOffset to, CancellationToken ct);
Task CancelAsync(string id, CancellationToken ct);
Task VerifyWebhookAsync(JsonElement notification, IReadOnlyDictionary<string, string> headers, CancellationToken ct);
}
public sealed class PayPalSubscriptionGateway(HttpClient http, IOptions<PayPalSettings> paypalOptions,
IOptions<ResourceSubscriptionOptions> subscriptionOptions) : IPayPalSubscriptionGateway
{
private static readonly Regex SubscriptionId = new("^I-[A-Z0-9]{1,62}$", RegexOptions.CultureInvariant);
private string Origin => paypalOptions.Value.Mode switch
{
"production" => "https://api-m.paypal.com",
"sandbox" => "https://api-m.sandbox.paypal.com",
_ => throw new SubscriptionOperationException(503, "Le paiement PayPal REST n'est pas configure.")
};
public async Task<PayPalSubscriptionDetails> CreateAsync(ResourceSubscription subscription,
string returnUrl, string cancelUrl, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(subscriptionOptions.Value.WebhookId))
throw new SubscriptionOperationException(503, "Le webhook PayPal des abonnements n'est pas configure.");
await ValidatePlanAsync(subscription, ct);
using var result = await SendAsync(HttpMethod.Post, "/v1/billing/subscriptions", new
{
plan_id = subscription.PlanId,
custom_id = subscription.Id.ToString("N"),
application_context = new
{
brand_name = "Yavsc", user_action = "SUBSCRIBE_NOW", shipping_preference = "NO_SHIPPING",
return_url = returnUrl, cancel_url = cancelUrl
}
}, subscription.Id.ToString("N"), ct);
return ReadSubscription(result.RootElement);
}
private async Task ValidatePlanAsync(ResourceSubscription subscription, CancellationToken ct)
{
if (!Regex.IsMatch(subscription.PlanId, "^P-[A-Z0-9]{1,62}$", RegexOptions.CultureInvariant))
throw new SubscriptionOperationException(503, "Le plan PayPal du pack n'est pas configure.");
using var result = await SendAsync(HttpMethod.Get, "/v1/billing/plans/" + subscription.PlanId, null, null, ct);
var plan = Object(result.RootElement);
var cycles = Array(Property(plan, "billing_cycles")).ToArray();
if (Text(plan, "id") != subscription.PlanId || Text(plan, "status") != "ACTIVE" || cycles.Length != 1)
throw new SubscriptionOperationException(503, "Le plan PayPal doit etre actif, mensuel et sans periode d'essai.");
var cycle = cycles[0];
var frequency = Property(cycle, "frequency");
var price = Property(Property(cycle, "pricing_scheme"), "fixed_price");
var preferences = Object(Property(plan, "payment_preferences"));
if (Text(cycle, "tenure_type") != "REGULAR" || Integer(Property(cycle, "total_cycles")) != 0
|| Text(frequency, "interval_unit") != "MONTH" || Integer(Property(frequency, "interval_count")) != 1
|| Text(price, "currency_code") != "EUR" || Amount(Property(price, "value")) != subscription.PriceIncludingTax
|| Boolean(Property(preferences, "auto_bill_outstanding"))
|| (preferences.TryGetProperty("setup_fee", out var fee) && Amount(Property(fee, "value")) != 0m)
|| (plan.TryGetProperty("taxes", out var taxes) && Amount(Property(taxes, "percentage")) != 0m)
|| (plan.TryGetProperty("quantity_supported", out var quantity) && Boolean(quantity)))
throw new SubscriptionOperationException(503, "Le plan PayPal doit correspondre au tarif TTC du pack, sans frais supplementaires ni regroupement des impayes.");
}
public async Task<PayPalSubscriptionDetails> GetAsync(string id, CancellationToken ct)
{
CheckId(id);
using var result = await SendAsync(HttpMethod.Get, "/v1/billing/subscriptions/" + id, null, null, ct);
return ReadSubscription(result.RootElement);
}
public async Task<IReadOnlyList<PayPalSubscriptionTransaction>> TransactionsAsync(
string id, DateTimeOffset from, DateTimeOffset to, CancellationToken ct)
{
CheckId(id);
var all = new List<PayPalSubscriptionTransaction>();
// PayPal accepts bounded date ranges. Adjacent ranges can repeat an
// endpoint transaction; reconciliation deduplicates by PayPal ID.
while (from < to)
{
var end = from.AddDays(30) < to ? from.AddDays(30) : to;
string Date(DateTimeOffset value) => Uri.EscapeDataString(value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture));
using var result = await SendAsync(HttpMethod.Get,
$"/v1/billing/subscriptions/{id}/transactions?start_time={Date(from)}&end_time={Date(end)}", null, null, ct);
foreach (var item in Array(Property(result.RootElement, "transactions")))
{
var amount = Property(Property(item, "amount_with_breakdown"), "gross_amount");
all.Add(new(Text(item, "id"), Text(item, "status"), Amount(Property(amount, "value")),
Text(amount, "currency_code"), ReadDate(Text(item, "time"))));
}
from = end;
}
return all;
}
public async Task CancelAsync(string id, CancellationToken ct)
{
CheckId(id);
using var result = await SendAsync(HttpMethod.Post, $"/v1/billing/subscriptions/{id}/cancel",
new { reason = "Resiliation demandee par l'abonne Yavsc" }, null, ct);
}
public async Task VerifyWebhookAsync(JsonElement notification, IReadOnlyDictionary<string, string> headers, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(subscriptionOptions.Value.WebhookId))
throw new SubscriptionOperationException(503, "Le webhook PayPal des abonnements n'est pas configure.");
string Header(string name) => headers.TryGetValue(name, out var value) && !string.IsNullOrWhiteSpace(value)
? value : throw new SubscriptionOperationException(400, "Signature PayPal manquante.");
using var result = await SendAsync(HttpMethod.Post, "/v1/notifications/verify-webhook-signature", new
{
auth_algo = Header("PAYPAL-AUTH-ALGO"), cert_url = Header("PAYPAL-CERT-URL"),
transmission_id = Header("PAYPAL-TRANSMISSION-ID"), transmission_sig = Header("PAYPAL-TRANSMISSION-SIG"),
transmission_time = Header("PAYPAL-TRANSMISSION-TIME"),
webhook_id = subscriptionOptions.Value.WebhookId, webhook_event = notification
}, null, ct);
if (Text(result.RootElement, "verification_status") != "SUCCESS")
throw new SubscriptionOperationException(400, "Notification PayPal non verifiee.");
}
private async Task<JsonDocument> SendAsync(HttpMethod method, string path, object? payload, string? requestId, CancellationToken ct)
{
var settings = paypalOptions.Value;
if (string.IsNullOrWhiteSpace(settings.ClientId) || string.IsNullOrWhiteSpace(settings.ClientSecret))
throw new SubscriptionOperationException(503, "Les identifiants REST PayPal ne sont pas configures.");
try
{
using var tokenRequest = new HttpRequestMessage(HttpMethod.Post, Origin + "/v1/oauth2/token");
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.ClientId + ":" + settings.ClientSecret)));
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string> { ["grant_type"] = "client_credentials" });
using var tokenResponse = await http.SendAsync(tokenRequest, ct);
if (!tokenResponse.IsSuccessStatusCode)
throw new SubscriptionOperationException(502, "L'authentification PayPal a echoue.");
using var token = JsonDocument.Parse(await tokenResponse.Content.ReadAsStringAsync(ct));
using var request = new HttpRequestMessage(method, Origin + path);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Text(token.RootElement, "access_token"));
if (requestId is not null) request.Headers.Add("PayPal-Request-Id", requestId);
if (payload is not null) request.Content = JsonContent.Create(payload);
using var response = await http.SendAsync(request, ct);
if (!response.IsSuccessStatusCode)
throw new SubscriptionOperationException(502, "PayPal a refuse l'operation. Verifiez l'etat de l'abonnement avant de recommencer.");
return response.StatusCode == System.Net.HttpStatusCode.NoContent
? JsonDocument.Parse("{}") : JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));
}
catch (HttpRequestException)
{
throw new SubscriptionOperationException(502, "PayPal est indisponible. Aucun paiement n'est presume reussi.");
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new SubscriptionOperationException(504, "PayPal n'a pas repondu a temps. Verifiez l'abonnement avant de recommencer.");
}
catch (JsonException)
{
throw new SubscriptionOperationException(502, "PayPal a retourne une reponse invalide.");
}
}
private static PayPalSubscriptionDetails ReadSubscription(JsonElement value)
{
value = Object(value);
var id = Text(value, "id");
CheckId(id);
if (value.TryGetProperty("plan_overridden", out var overridden) && Boolean(overridden))
throw new SubscriptionOperationException(409, "Le plan de cet abonnement a ete modifie.");
if ((value.TryGetProperty("quantity", out var quantity) && Amount(quantity) != 1m)
|| (value.TryGetProperty("shipping_amount", out var shipping) && Amount(Property(shipping, "value")) != 0m))
throw new SubscriptionOperationException(409, "L'abonnement comporte une quantite ou des frais non autorises.");
string? approval = null;
if (value.TryGetProperty("links", out var links))
{
var approvals = Array(links).Where(link => Text(link, "rel") == "approve")
.Select(link => Text(link, "href")).ToArray();
if (approvals.Length > 1)
throw new SubscriptionOperationException(502, "Plusieurs liens d'approbation PayPal ont ete retournes.");
approval = approvals.SingleOrDefault();
}
if (approval is not null && (!Uri.TryCreate(approval, UriKind.Absolute, out var uri)
|| uri.Scheme != "https" || !string.IsNullOrEmpty(uri.UserInfo)
|| uri.Host is not ("www.paypal.com" or "www.sandbox.paypal.com")))
throw new SubscriptionOperationException(502, "Lien d'approbation PayPal invalide.");
DateTimeOffset? Date(JsonElement element, string key) => element.TryGetProperty(key, out _)
? ReadDate(Text(element, key)) : null;
var next = value.TryGetProperty("billing_info", out var info) ? Date(Object(info), "next_billing_time") : null;
return new(id, Text(value, "custom_id"), Text(value, "plan_id"), Text(value, "status"),
Date(value, "start_time"), next, approval);
}
private static void CheckId(string id)
{
if (!SubscriptionId.IsMatch(id)) throw new SubscriptionOperationException(400, "Reference d'abonnement PayPal invalide.");
}
private static JsonElement Property(JsonElement value, string property)
=> value.ValueKind == JsonValueKind.Object && value.TryGetProperty(property, out var found)
? found : throw new SubscriptionOperationException(502, "Reponse PayPal incomplete.");
private static JsonElement Object(JsonElement value)
=> value.ValueKind == JsonValueKind.Object
? value : throw new SubscriptionOperationException(502, "Objet PayPal invalide.");
private static JsonElement.ArrayEnumerator Array(JsonElement value)
=> value.ValueKind == JsonValueKind.Array
? value.EnumerateArray() : throw new SubscriptionOperationException(502, "Liste PayPal invalide.");
private static int Integer(JsonElement value)
=> value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out var number)
? number : throw new SubscriptionOperationException(502, "Entier PayPal invalide.");
private static bool Boolean(JsonElement value)
=> value.ValueKind is JsonValueKind.True or JsonValueKind.False
? value.GetBoolean() : throw new SubscriptionOperationException(502, "Booleen PayPal invalide.");
private static string Text(JsonElement value, string property)
{
var found = Property(value, property);
return found.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(found.GetString())
? found.GetString()! : throw new SubscriptionOperationException(502, "Reponse PayPal invalide.");
}
private static decimal Amount(JsonElement value)
=> value.ValueKind == JsonValueKind.String
&& decimal.TryParse(value.GetString(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var amount)
? amount : throw new SubscriptionOperationException(502, "Montant PayPal invalide.");
private static DateTimeOffset ReadDate(string value)
=> DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date)
? date.ToUniversalTime() : throw new SubscriptionOperationException(502, "Date PayPal invalide.");
}

View file

@ -0,0 +1,177 @@
#nullable enable
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Models.Payment;
using Yavsc.Server.Helpers;
using Yavsc.Settings;
namespace Yavsc.Web.Services;
public interface IResourceSubscriptionService
{
Task<List<ResourceSubscription>> GetAllAsync(string userId, CancellationToken ct);
Task<ResourceSubscription?> FindPayPalAsync(string paypalId, CancellationToken ct);
Task<ResourceSubscription?> FindPaymentAsync(string transactionId, CancellationToken ct);
Task<ResourceSubscription> PrepareAsync(string userId, string pack, CancellationToken ct);
Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct);
Task ReconcileAsync(ResourceSubscription subscription, CancellationToken ct);
}
public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPalSubscriptionGateway paypal,
IOptions<ResourceSubscriptionOptions> options, IOptions<ResourceUsageOptions> usageOptions,
TimeProvider clock) : IResourceSubscriptionService
{
public Task<List<ResourceSubscription>> GetAllAsync(string userId, CancellationToken ct)
=> db.ResourceSubscriptions.Where(s => s.UserId == userId).OrderByDescending(s => s.CreatedAt).ToListAsync(ct);
public Task<ResourceSubscription?> FindPayPalAsync(string paypalId, CancellationToken ct)
=> db.ResourceSubscriptions.SingleOrDefaultAsync(s => s.PayPalId == paypalId, ct);
public Task<ResourceSubscription?> FindPaymentAsync(string transactionId, CancellationToken ct)
=> db.ResourceSubscriptions.Join(db.ResourceSubscriptionPayments.Where(p => p.Id == transactionId),
s => s.Id, p => p.SubscriptionId, (s, p) => s).SingleOrDefaultAsync(ct);
public Task<ResourceSubscription> PrepareAsync(string userId, string pack, CancellationToken ct)
{
if (pack is not ("Discovery" or "Premium"))
throw new SubscriptionOperationException(400, "Pack inconnu.");
return ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
{
var existing = await db.ResourceSubscriptions.Where(s => s.UserId == userId
&& s.State != "CANCELLED" && s.State != "EXPIRED").SingleOrDefaultAsync(ct);
if (existing is not null)
{
if (existing.Pack != pack)
throw new SubscriptionOperationException(409, "Resiliez l'abonnement existant avant de changer de pack.");
if (existing.State == "CREATING" && existing.CreatedAt < clock.GetUtcNow().AddHours(-24))
throw new SubscriptionOperationException(409, "Une creation PayPal ancienne doit etre rapprochee par l'administration avant tout nouvel essai.");
return existing;
}
var settings = options.Value;
var plan = pack == "Premium" ? settings.PremiumPlanId : settings.DiscoveryPlanId;
if (string.IsNullOrWhiteSpace(plan))
throw new SubscriptionOperationException(503, "Ce pack PayPal n'est pas configure.");
var price = pack == "Premium" ? settings.PremiumPriceExcludingTax : settings.DiscoveryPriceExcludingTax;
var subscription = new ResourceSubscription
{
Id = Guid.NewGuid(), UserId = userId, Pack = pack, PlanId = plan,
CreatedAt = DateTimeOffset.FromUnixTimeSeconds(clock.GetUtcNow().ToUnixTimeSeconds()),
MonthlyPoints = usageOptions.Value.DefaultLimit * (pack == "Premium" ? 3m : 1m),
PriceExcludingTax = price, VatPercent = settings.VatPercent, PriceIncludingTax = settings.TotalPrice(price)
};
db.ResourceSubscriptions.Add(subscription);
await db.SaveChangesAsync(ct);
return subscription;
}, ct);
}
public Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct)
=> ResourceUsageTracker.WithUserLockAsync(db, subscription.UserId, async () =>
{
await db.Entry(subscription).ReloadAsync(ct);
CheckBinding(subscription, remote);
subscription.PayPalId = remote.Id;
subscription.State = remote.State;
subscription.StartsAt = remote.StartsAt;
subscription.NextBillingAt = remote.NextBillingAt;
await db.SaveChangesAsync(ct);
return true;
}, ct);
public async Task ReconcileAsync(ResourceSubscription subscription, CancellationToken ct)
{
if (subscription.PayPalId is null) return;
var remote = await paypal.GetAsync(subscription.PayPalId, ct);
CheckBinding(subscription, remote);
var transactions = await paypal.TransactionsAsync(remote.Id, subscription.CreatedAt, clock.GetUtcNow(), ct);
await ResourceUsageTracker.WithUserLockAsync(db, subscription.UserId, async () =>
{
await db.Entry(subscription).ReloadAsync(ct);
CheckBinding(subscription, remote);
subscription.State = remote.State;
subscription.StartsAt = remote.StartsAt;
subscription.NextBillingAt = remote.NextBillingAt;
var record = await db.ResourceUsageRecords.Where(r => r.UserId == subscription.UserId)
.OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id).FirstOrDefaultAsync(ct);
if (record is not null) await db.Entry(record).ReloadAsync(ct);
foreach (var payment in transactions.DistinctBy(p => p.Id).OrderBy(p => p.PaidAt).ThenBy(p => p.Id))
{
if (payment.State is not ("COMPLETED" or "REFUNDED" or "PARTIALLY_REFUNDED" or "FAILED" or "DECLINED")) continue;
if (payment.Currency != "EUR" || payment.Amount != subscription.PriceIncludingTax
|| payment.PaidAt > clock.GetUtcNow() || payment.PaidAt < subscription.CreatedAt)
throw new SubscriptionOperationException(409, "La mensualite PayPal ne correspond pas au tarif de cet abonnement.");
if (remote.StartsAt is null)
throw new SubscriptionOperationException(409, "La date de debut PayPal est manquante.");
var anchor = new DateTimeOffset(remote.StartsAt.Value.UtcDateTime.Date, TimeSpan.Zero);
if (payment.PaidAt < anchor)
throw new SubscriptionOperationException(409, "Le paiement precede le debut de l'abonnement.");
var cycle = ResourceUsageCredit.BillingCycle(anchor, payment.PaidAt);
var receipt = await db.ResourceSubscriptionPayments.FindAsync([payment.Id], ct);
if (receipt is not null)
{
if (receipt.SubscriptionId != subscription.Id)
throw new SubscriptionOperationException(409, "La transaction PayPal est deja affectee a un autre abonnement.");
if (payment.State != "COMPLETED" && !receipt.Reversed)
{
if (record is null || record.CreditPoints < receipt.GrantedPoints)
throw new SubscriptionOperationException(409, "Le solde des credits ne permet pas le rapprochement du remboursement.");
record.CreditPoints -= receipt.GrantedPoints;
receipt.Reversed = true;
}
continue;
}
if (payment.State is "FAILED" or "DECLINED") continue;
if (await db.ResourceSubscriptionPayments.AnyAsync(p => p.SubscriptionId == subscription.Id && p.Cycle == cycle, ct))
throw new SubscriptionOperationException(409, "Plusieurs paiements PayPal correspondent a la meme mensualite. Contactez l'administration.");
if (record is null)
{
var name = await db.Users.Where(u => u.Id == subscription.UserId).Select(u => u.UserName).SingleAsync(ct);
record = new ResourceUsageRecord
{
UserId = subscription.UserId, UserName = name ?? subscription.UserId,
UserCreated = subscription.UserId, UserModified = subscription.UserId
};
db.ResourceUsageRecords.Add(record);
}
var gross = usageOptions.Value.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb);
var grant = payment.State == "COMPLETED"
? ResourceUsageCredit.MonthlyGrant(gross, record.CreditPoints, subscription.MonthlyPoints) : 0m;
record.CreditPoints += grant;
db.ResourceSubscriptionPayments.Add(new ResourceSubscriptionPayment
{
Id = payment.Id, SubscriptionId = subscription.Id, Cycle = cycle, PaidAt = payment.PaidAt,
GrantedPoints = grant, Reversed = payment.State != "COMPLETED"
});
subscription.LastCreditedCycle = Math.Max(subscription.LastCreditedCycle, cycle);
// Make subsequent transactions in this reconciliation see the receipt.
await db.SaveChangesAsync(subscription.UserId, ct);
}
await db.SaveChangesAsync(subscription.UserId, ct);
var owner = await db.Users.SingleAsync(u => u.Id == subscription.UserId, ct);
await db.Entry(owner).ReloadAsync(ct);
var paidPeriods = await db.ResourceSubscriptions.Where(s => s.UserId == subscription.UserId
&& (s.Pack == "Premium" || s.Pack == "Discovery") && s.StartsAt != null)
.Join(db.ResourceSubscriptionPayments.Where(p => !p.Reversed), s => s.Id, p => p.SubscriptionId,
(s, p) => new { s.Pack, s.StartsAt, p.Cycle }).ToListAsync(ct);
owner.PremiumDiskQuotaUntil = paidPeriods.Where(p => p.Pack == "Premium")
.Select(p => p.StartsAt!.Value.AddMonths(p.Cycle + 1))
.Cast<DateTimeOffset?>().Max();
owner.DiscoveryDiskQuotaUntil = paidPeriods.Where(p => p.Pack == "Discovery")
.Select(p => p.StartsAt!.Value.AddMonths(p.Cycle + 1))
.Cast<DateTimeOffset?>().Max();
await db.SaveChangesAsync(subscription.UserId, ct);
return true;
}, ct);
}
private static void CheckBinding(ResourceSubscription subscription, PayPalSubscriptionDetails remote)
{
if (remote.CustomId != subscription.Id.ToString("N") || remote.PlanId != subscription.PlanId
|| (subscription.PayPalId is not null && subscription.PayPalId != remote.Id)
|| (subscription.StartsAt is not null && subscription.StartsAt != remote.StartsAt)
|| (subscription.State is "CANCELLED" or "EXPIRED" && remote.State is not ("CANCELLED" or "EXPIRED"))
|| remote.State is not ("APPROVAL_PENDING" or "APPROVED" or "ACTIVE" or "SUSPENDED" or "CANCELLED" or "EXPIRED"))
throw new SubscriptionOperationException(409, "L'abonnement PayPal ne correspond pas au compte et au pack attendus.");
}
}