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:
parent
0728d2a3f7
commit
650e5f5e30
69 changed files with 19111 additions and 203 deletions
|
|
@ -117,7 +117,7 @@ namespace Yavsc.Controllers
|
|||
Avatar = user.Avatar,
|
||||
BankInfo = user.BankInfo,
|
||||
DiskUsage = user.DiskUsage,
|
||||
DiskQuota = user.DiskQuota,
|
||||
DiskQuota = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow),
|
||||
DedicatedCalendarId = user.DedicatedGoogleCalendar,
|
||||
EMail = user.Email,
|
||||
EmailConfirmed = await _userManager.IsEmailConfirmedAsync(user),
|
||||
|
|
|
|||
|
|
@ -138,6 +138,10 @@ namespace Yavsc.Controllers
|
|||
{
|
||||
return View();
|
||||
}
|
||||
public IActionResult CGU()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
public IActionResult AboutMarkdown()
|
||||
{
|
||||
return View();
|
||||
|
|
|
|||
167
src/Yavsc.Org/Controllers/ResourceSubscriptionController.cs
Normal file
167
src/Yavsc.Org/Controllers/ResourceSubscriptionController.cs
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
#nullable enable
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Settings;
|
||||
using Yavsc.ViewModels;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Controllers;
|
||||
|
||||
[Authorize(Policy = "WebUser")]
|
||||
[ResourceUsageExempt]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ResourceSubscriptionController(IResourceSubscriptionService subscriptions,
|
||||
IPayPalSubscriptionGateway paypal, IResourceUsageService usage,
|
||||
IOptions<ResourceSubscriptionOptions> options, IOptions<ResourceUsageOptions> usageOptions,
|
||||
IOptions<SiteSettings> site, ILogger<ResourceSubscriptionController> logger) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(CancellationToken ct)
|
||||
=> View(new ResourceSubscriptionPage(options.Value, usageOptions.Value.DefaultLimit,
|
||||
await usage.GetCurrentAsync(User.GetUserId(), User.Identity?.Name ?? User.GetUserId(), ct),
|
||||
await subscriptions.GetAllAsync(User.GetUserId(), ct)));
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Create(string pack, CancellationToken ct)
|
||||
{
|
||||
var subscription = await subscriptions.PrepareAsync(User.GetUserId(), pack, ct);
|
||||
PayPalSubscriptionDetails remote;
|
||||
if (subscription.PayPalId is null)
|
||||
{
|
||||
var root = SiteRoot();
|
||||
remote = await paypal.CreateAsync(subscription,
|
||||
root + "ResourceSubscription/Return?id=" + subscription.Id,
|
||||
root + "ResourceSubscription", ct);
|
||||
await subscriptions.BindAsync(subscription, remote, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
remote = await paypal.GetAsync(subscription.PayPalId, ct);
|
||||
await subscriptions.BindAsync(subscription, remote, ct);
|
||||
}
|
||||
if (remote.ApprovalUrl is not null && remote.State == "APPROVAL_PENDING")
|
||||
return Redirect(remote.ApprovalUrl);
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Return(Guid id, CancellationToken ct)
|
||||
{
|
||||
var subscription = await OwnedAsync(id, ct);
|
||||
if (subscription is null) return NotFound();
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Refresh(CancellationToken ct)
|
||||
{
|
||||
foreach (var subscription in await subscriptions.GetAllAsync(User.GetUserId(), ct))
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
|
||||
{
|
||||
var subscription = await OwnedAsync(id, ct);
|
||||
if (subscription is null || subscription.PayPalId is null) return NotFound();
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
if (subscription.State is not ("CANCELLED" or "EXPIRED"))
|
||||
await paypal.CancelAsync(subscription.PayPalId, ct);
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
[AllowAnonymous, HttpPost, IgnoreAntiforgeryToken, RawPayPalNotification, RequestSizeLimit(64 * 1024)]
|
||||
public async Task<IActionResult> Notify(CancellationToken ct)
|
||||
{
|
||||
JsonDocument notification;
|
||||
try
|
||||
{
|
||||
notification = await JsonDocument.ParseAsync(Request.Body, cancellationToken: ct);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Malformed PayPal subscription notification");
|
||||
return BadRequest();
|
||||
}
|
||||
using (notification)
|
||||
{
|
||||
var headers = Request.Headers.ToDictionary(pair => pair.Key, pair => pair.Value.ToString(), StringComparer.OrdinalIgnoreCase);
|
||||
await paypal.VerifyWebhookAsync(notification.RootElement, headers, ct);
|
||||
var value = notification.RootElement;
|
||||
if (value.ValueKind != JsonValueKind.Object
|
||||
|| !value.TryGetProperty("event_type", out var type) || type.ValueKind != JsonValueKind.String
|
||||
|| !value.TryGetProperty("resource", out var resource) || resource.ValueKind != JsonValueKind.Object)
|
||||
throw new SubscriptionOperationException(400, "Notification PayPal incomplete.");
|
||||
var eventType = type.GetString()!;
|
||||
if (!eventType.StartsWith("BILLING.SUBSCRIPTION.", StringComparison.Ordinal)
|
||||
&& eventType is not ("PAYMENT.SALE.COMPLETED" or "PAYMENT.SALE.REFUNDED" or "PAYMENT.SALE.REVERSED"))
|
||||
return NoContent();
|
||||
ResourceSubscription? subscription;
|
||||
var key = eventType.StartsWith("BILLING.", StringComparison.Ordinal) ? "id" : "billing_agreement_id";
|
||||
var paypalId = NotificationText(resource, key);
|
||||
if (paypalId is not null)
|
||||
subscription = await subscriptions.FindPayPalAsync(paypalId, ct);
|
||||
else
|
||||
{
|
||||
var transactionId = NotificationText(resource, "sale_id") ?? NotificationText(resource, "id");
|
||||
subscription = transactionId is null ? null : await subscriptions.FindPaymentAsync(transactionId, ct);
|
||||
if (subscription is null && resource.TryGetProperty("links", out var links))
|
||||
{
|
||||
if (links.ValueKind != JsonValueKind.Array)
|
||||
throw new SubscriptionOperationException(400, "Liens de notification PayPal invalides.");
|
||||
foreach (var link in links.EnumerateArray())
|
||||
{
|
||||
if (link.ValueKind != JsonValueKind.Object)
|
||||
throw new SubscriptionOperationException(400, "Lien de notification PayPal invalide.");
|
||||
if (!Uri.TryCreate(NotificationText(link, "href"), UriKind.Absolute, out var uri)
|
||||
|| uri.Scheme != "https" || uri.Host is not ("api.paypal.com" or "api.sandbox.paypal.com" or "api-m.paypal.com" or "api-m.sandbox.paypal.com")
|
||||
|| !uri.AbsolutePath.StartsWith("/v1/payments/sale/", StringComparison.Ordinal)) continue;
|
||||
subscription = await subscriptions.FindPaymentAsync(uri.Segments[^1], ct);
|
||||
if (subscription is not null) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (subscription is null) return NotFound();
|
||||
// The signed notification is a trigger, not the payment authority.
|
||||
// Re-fetch the bound subscription and all transactions from PayPal.
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ResourceSubscription?> OwnedAsync(Guid id, CancellationToken ct)
|
||||
=> (await subscriptions.GetAllAsync(User.GetUserId(), ct)).SingleOrDefault(s => s.Id == id);
|
||||
|
||||
private static string? NotificationText(JsonElement value, string property)
|
||||
{
|
||||
if (!value.TryGetProperty(property, out var found)) return null;
|
||||
return found.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(found.GetString())
|
||||
? found.GetString() : throw new SubscriptionOperationException(400, "Reference de notification PayPal invalide.");
|
||||
}
|
||||
|
||||
private string SiteRoot()
|
||||
{
|
||||
if (!Uri.TryCreate(site.Value.ExternalUrl, UriKind.Absolute, out var uri)
|
||||
|| uri.Scheme != "https" || !string.IsNullOrEmpty(uri.UserInfo))
|
||||
throw new SubscriptionOperationException(503, "L'adresse HTTPS publique du site n'est pas configuree.");
|
||||
return site.Value.ExternalUrl.TrimEnd('/') + "/";
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var executed = await next();
|
||||
if (executed.Exception is not SubscriptionOperationException error || Response.HasStarted) return;
|
||||
logger.LogError(error, "Resource subscription operation failed for {Action}", context.ActionDescriptor.DisplayName);
|
||||
executed.ExceptionHandled = true;
|
||||
executed.Result = Problem(statusCode: error.StatusCode, title: "Abonnement indisponible", detail: error.Message);
|
||||
}
|
||||
}
|
||||
|
|
@ -83,6 +83,19 @@ public static class HostingExtensions
|
|||
builder.Services.AddSwaggerGen();
|
||||
|
||||
IServiceCollection services = LoadConfiguration(builder);
|
||||
services.AddResourceUsage(builder.Configuration);
|
||||
services.AddOptions<ResourceSubscriptionOptions>()
|
||||
.Bind(builder.Configuration.GetSection(ResourceSubscriptionOptions.SectionName))
|
||||
.Validate(o => o.DiscoveryPriceExcludingTax > 0m && o.PremiumPriceExcludingTax > 0m
|
||||
&& decimal.Round(o.DiscoveryPriceExcludingTax, 2) == o.DiscoveryPriceExcludingTax
|
||||
&& decimal.Round(o.PremiumPriceExcludingTax, 2) == o.PremiumPriceExcludingTax
|
||||
&& o.VatPercent >= 0m && o.VatPercent <= 100m,
|
||||
"ResourceSubscriptions prices and VAT are invalid.")
|
||||
.ValidateOnStart();
|
||||
services.AddHttpClient<Yavsc.Web.Services.IPayPalSubscriptionGateway, Yavsc.Web.Services.PayPalSubscriptionGateway>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
services.AddScoped<Yavsc.Web.Services.IResourceSubscriptionService, Yavsc.Web.Services.ResourceSubscriptionService>();
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
|
||||
services.AddSession();
|
||||
|
||||
|
|
|
|||
5197
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.Designer.cs
generated
Normal file
5197
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
107
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.cs
Normal file
107
src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ResourceSubscriptions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<decimal>(
|
||||
name: "CreditPoints",
|
||||
table: "ResourceUsageRecords",
|
||||
type: "numeric(28,8)",
|
||||
precision: 28,
|
||||
scale: 8,
|
||||
nullable: false,
|
||||
defaultValue: 0m);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ResourceSubscriptions",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||
Pack = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
PlanId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
PayPalId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
|
||||
State = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
MonthlyPoints = table.Column<decimal>(type: "numeric(28,8)", precision: 28, scale: 8, nullable: false),
|
||||
PriceExcludingTax = table.Column<decimal>(type: "numeric(18,2)", nullable: false),
|
||||
VatPercent = table.Column<decimal>(type: "numeric", nullable: false),
|
||||
PriceIncludingTax = table.Column<decimal>(type: "numeric(18,2)", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
StartsAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
NextBillingAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
LastCreditedCycle = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ResourceSubscriptions", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ResourceSubscriptions_AspNetUsers_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ResourceSubscriptionPayments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
SubscriptionId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Cycle = table.Column<int>(type: "integer", nullable: false),
|
||||
PaidAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
GrantedPoints = table.Column<decimal>(type: "numeric(28,8)", precision: 28, scale: 8, nullable: false),
|
||||
Reversed = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ResourceSubscriptionPayments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ResourceSubscriptionPayments_ResourceSubscriptions_Subscrip~",
|
||||
column: x => x.SubscriptionId,
|
||||
principalTable: "ResourceSubscriptions",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ResourceSubscriptionPayments_SubscriptionId_Cycle",
|
||||
table: "ResourceSubscriptionPayments",
|
||||
columns: new[] { "SubscriptionId", "Cycle" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ResourceSubscriptions_PayPalId",
|
||||
table: "ResourceSubscriptions",
|
||||
column: "PayPalId",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ResourceSubscriptions_UserId",
|
||||
table: "ResourceSubscriptions",
|
||||
column: "UserId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "ResourceSubscriptionPayments");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "ResourceSubscriptions");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CreditPoints",
|
||||
table: "ResourceUsageRecords");
|
||||
}
|
||||
}
|
||||
}
|
||||
5200
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.Designer.cs
generated
Normal file
5200
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
29
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.cs
Normal file
29
src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PremiumDiskQuota : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "PremiumDiskQuotaUntil",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PremiumDiskQuotaUntil",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
5203
src/Yavsc.Org/Migrations/20261108045419_DiscoveryDiskQuota.Designer.cs
generated
Normal file
5203
src/Yavsc.Org/Migrations/20261108045419_DiscoveryDiskQuota.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,29 @@
|
|||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class DiscoveryDiskQuota : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "DiscoveryDiskQuotaUntil",
|
||||
table: "AspNetUsers",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DiscoveryDiskQuotaUntil",
|
||||
table: "AspNetUsers");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1150,6 +1150,9 @@ namespace Yavsc.Migrations
|
|||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<DateTimeOffset?>("DiscoveryDiskQuotaUntil")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<long>("DiskQuota")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint")
|
||||
|
|
@ -1202,6 +1205,9 @@ namespace Yavsc.Migrations
|
|||
b.Property<long?>("PostalAddressId")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<DateTimeOffset?>("PremiumDiskQuotaUntil")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
|
|
@ -2803,6 +2809,101 @@ namespace Yavsc.Migrations
|
|||
b.ToTable("PerformerDonations");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscription", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("LastCreditedCycle")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<decimal>("MonthlyPoints")
|
||||
.HasPrecision(28, 8)
|
||||
.HasColumnType("numeric(28,8)");
|
||||
|
||||
b.Property<DateTimeOffset?>("NextBillingAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Pack")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("PayPalId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("PlanId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<decimal>("PriceExcludingTax")
|
||||
.HasColumnType("numeric(18,2)");
|
||||
|
||||
b.Property<decimal>("PriceIncludingTax")
|
||||
.HasColumnType("numeric(18,2)");
|
||||
|
||||
b.Property<DateTimeOffset?>("StartsAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("State")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("UserId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(450)
|
||||
.HasColumnType("character varying(450)");
|
||||
|
||||
b.Property<decimal>("VatPercent")
|
||||
.HasColumnType("numeric");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PayPalId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("ResourceSubscriptions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscriptionPayment", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<int>("Cycle")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<decimal>("GrantedPoints")
|
||||
.HasPrecision(28, 8)
|
||||
.HasColumnType("numeric(28,8)");
|
||||
|
||||
b.Property<DateTimeOffset>("PaidAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("Reversed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid>("SubscriptionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("SubscriptionId", "Cycle")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("ResourceSubscriptionPayments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
|
|
@ -2997,6 +3098,12 @@ namespace Yavsc.Migrations
|
|||
b.Property<decimal>("CpuSeconds")
|
||||
.HasColumnType("numeric");
|
||||
|
||||
b.Property<decimal>("CreditPoints")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasPrecision(28, 8)
|
||||
.HasColumnType("numeric(28,8)")
|
||||
.HasDefaultValue(0m);
|
||||
|
||||
b.Property<string>("Currency")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
|
|
@ -4623,6 +4730,24 @@ namespace Yavsc.Migrations
|
|||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscription", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscriptionPayment", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.Payment.ResourceSubscription", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("SubscriptionId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b =>
|
||||
{
|
||||
b.HasOne("Yavsc.Models.ApplicationUser", null)
|
||||
|
|
|
|||
38
src/Yavsc.Org/ResourceSubscriptions.http
Normal file
38
src/Yavsc.Org/ResourceSubscriptions.http
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
@baseUrl = https://localhost:5001
|
||||
@antiforgeryToken = replace-from-subscription-page
|
||||
@sessionCookie = replace-with-web-session-and-antiforgery-cookies
|
||||
|
||||
### Subscription management remains accessible with an exhausted quota
|
||||
GET {{baseUrl}}/ResourceSubscription
|
||||
Cookie: {{sessionCookie}}
|
||||
|
||||
### Start the Discovery checkout (Premium uses pack=Premium)
|
||||
POST {{baseUrl}}/ResourceSubscription/Create
|
||||
Cookie: {{sessionCookie}}
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
pack=Discovery&__RequestVerificationToken={{antiforgeryToken}}
|
||||
|
||||
### Reconcile confirmed payments from PayPal, including missed webhooks
|
||||
POST {{baseUrl}}/ResourceSubscription/Refresh
|
||||
Cookie: {{sessionCookie}}
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
__RequestVerificationToken={{antiforgeryToken}}
|
||||
|
||||
### Cancel an owned subscription
|
||||
POST {{baseUrl}}/ResourceSubscription/Cancel
|
||||
Cookie: {{sessionCookie}}
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
id=replace-with-local-subscription-uuid&__RequestVerificationToken={{antiforgeryToken}}
|
||||
|
||||
### A browser return only reconciles server-verified payments
|
||||
GET {{baseUrl}}/ResourceSubscription/Return?id=replace-with-local-subscription-uuid
|
||||
Cookie: {{sessionCookie}}
|
||||
|
||||
### A forged notification must be rejected; real headers are supplied by PayPal
|
||||
POST {{baseUrl}}/ResourceSubscription/Notify
|
||||
Content-Type: application/json
|
||||
|
||||
{"event_type":"PAYMENT.SALE.COMPLETED","resource":{"billing_agreement_id":"I-EXAMPLE"}}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
249
src/Yavsc.Org/Services/PayPalSubscriptionGateway.cs
Normal file
249
src/Yavsc.Org/Services/PayPalSubscriptionGateway.cs
Normal 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.");
|
||||
}
|
||||
177
src/Yavsc.Org/Services/ResourceSubscriptionService.cs
Normal file
177
src/Yavsc.Org/Services/ResourceSubscriptionService.cs
Normal 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.");
|
||||
}
|
||||
}
|
||||
9
src/Yavsc.Org/ViewModels/ResourceSubscriptionPage.cs
Normal file
9
src/Yavsc.Org/ViewModels/ResourceSubscriptionPage.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
#nullable enable
|
||||
using Yavsc.Abstract.Resources;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.ViewModels;
|
||||
|
||||
public sealed record ResourceSubscriptionPage(ResourceSubscriptionOptions Prices, decimal FreeQuota,
|
||||
ResourceUsageSummary Usage, IReadOnlyList<ResourceSubscription> Subscriptions);
|
||||
138
src/Yavsc.Org/Views/Home/CGU.cshtml
Normal file
138
src/Yavsc.Org/Views/Home/CGU.cshtml
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
@using Yavsc.Settings
|
||||
@using Yavsc.Server.Helpers
|
||||
@inject Microsoft.Extensions.Options.IOptions<ResourceUsageOptions> UsageOptions
|
||||
@inject Microsoft.Extensions.Options.IOptions<ResourceSubscriptionOptions> SubscriptionOptions
|
||||
@{
|
||||
ViewBag.Title = "CGU de PostIt et de Yavsc";
|
||||
var rule = UsageOptions.Value;
|
||||
var packs = SubscriptionOptions.Value;
|
||||
var userId = User.GetUserId();
|
||||
var limit = string.IsNullOrWhiteSpace(userId) ? rule.DefaultLimit : rule.GetLimit(userId);
|
||||
}
|
||||
|
||||
<h1>Conditions d'utilisation de PostIt et de Yavsc : consommation des ressources</h1>
|
||||
<p>
|
||||
PostIt est un client de Yavsc. Les opérations authentifiées sur les services API et Blogs
|
||||
consomment des ressources communes, comptabilisées par identifiant de compte,
|
||||
quel que soit le client utilisé.
|
||||
</p>
|
||||
|
||||
<h2>Calcul de l'indicateur</h2>
|
||||
<p>L'indicateur est une somme pondérée, exprimée en points :</p>
|
||||
<p>
|
||||
<strong>
|
||||
I = @rule.ApiCallWeight × appels API
|
||||
+ @rule.CpuSecondWeight × secondes CPU enregistrées
|
||||
+ @rule.BandwidthMbWeight × Mio transférés
|
||||
+ @rule.StorageMbWeight × Mio ajoutés au stockage
|
||||
</strong>
|
||||
</p>
|
||||
<ul>
|
||||
<li>Un Mio vaut 1 048 576 octets ; les anciens champs de l'API portent le suffixe « Mb ».</li>
|
||||
<li>Les compteurs sont cumulés depuis le début de leur comptabilisation, sans remise à zéro mensuelle.</li>
|
||||
<li>
|
||||
Les transferts comprennent le corps entrant déclaré ou lu et les octets de réponse écrits,
|
||||
y compris les réponses diffusées sans taille annoncée. Les en-têtes et le surcoût du transport ne sont pas inclus.
|
||||
</li>
|
||||
<li>
|
||||
Le stockage est le volume cumulé ajouté par les opérations instrumentées (fichiers personnels et génération de PDF),
|
||||
pas l'espace disque actuellement occupé : suppression et remplacement ne remboursent pas de points.
|
||||
</li>
|
||||
<li>
|
||||
Le compteur historique « CPU » contient les durées enregistrées par les traitements instrumentés,
|
||||
notamment le temps écoulé de génération de PDF ; ce n'est pas une mesure exhaustive du processeur.
|
||||
Les ressources locales de PostIt, les appels directs entre appareils et le trafic WebSocket ne sont pas mesurés par cet indicateur HTTP.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
Le calcul utilise les valeurs décimales non arrondies ; l'arrondi de l'affichage ne décide pas du blocage.
|
||||
Cet indicateur n'est ni un prix, ni une facture, ni une estimation de compensation financière.
|
||||
</p>
|
||||
<h2>Inscription gratuite et abonnements mensuels</h2>
|
||||
<p>
|
||||
L'inscription gratuite donne accès au quota décrit ci-dessous. Elle ne renouvelle pas automatiquement
|
||||
ce quota chaque mois. Les compteurs historiques ne sont jamais supprimés par un abonnement :
|
||||
les crédits sont déduits de l'indicateur brut pour obtenir la consommation nette soumise au seuil.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Découverte</strong> : @packs.DiscoveryPriceExcludingTax.ToString("F2") € HT par mois,
|
||||
TVA @packs.VatPercent %, soit @packs.TotalPrice(packs.DiscoveryPriceExcludingTax).ToString("F2") € TTC prélevés ;
|
||||
chaque mensualité payée permet d'effacer jusqu'à @rule.DefaultLimit points.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Premium</strong> : @packs.PremiumPriceExcludingTax.ToString("F2") € HT par mois,
|
||||
TVA @packs.VatPercent %, soit @packs.TotalPrice(packs.PremiumPriceExcludingTax).ToString("F2") € TTC prélevés ;
|
||||
chaque mensualité payée permet d'effacer jusqu'à @(rule.DefaultLimit * 3m) points.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
Le prix et le volume mensuel sont fixés à la souscription, sur la base du quota gratuit par défaut
|
||||
(pas d'une éventuelle exception individuelle). Le premier crédit est accordé dès le premier paiement
|
||||
confirmé par PayPal, puis à chaque mensualité payée, à la date anniversaire UTC du début de l'abonnement.
|
||||
Pour une date de fin de mois absente du mois suivant, l'anniversaire est le dernier jour de ce mois.
|
||||
Il n'y a pas de remise à zéro calendaire ou de crédit accordé sur la seule approbation dans le navigateur.
|
||||
</p>
|
||||
<p>
|
||||
Le crédit reporté existant est utilisé en premier. Le nouveau crédit mensuel efface ensuite
|
||||
la consommation nette restante, sans la rendre négative ; les <strong>deux tiers du crédit mensuel
|
||||
inutilisé</strong> sont conservés. Le tiers restant est perdu. Les reports antérieurs ne subissent
|
||||
pas une nouvelle réduction, n'expirent pas et restent acquis après résiliation.
|
||||
Le report est arrondi vers zéro à huit décimales de point.
|
||||
Exemple : avec @(rule.DefaultLimit * 0.4m) points de consommation et un crédit Découverte de @rule.DefaultLimit points,
|
||||
@(rule.DefaultLimit * 0.4m) points sont effacés et @(ResourceUsageCredit.MonthlyGrant(rule.DefaultLimit * 0.4m, 0m, rule.DefaultLimit) - rule.DefaultLimit * 0.4m) points sont reportés.
|
||||
</p>
|
||||
<p>
|
||||
Les mensualités en attente ou impayées ne donnent aucun crédit. Les paiements sont rapprochés côté serveur
|
||||
avec PayPal, de manière idempotente ; une notification répétée ne donne pas de crédit supplémentaire.
|
||||
Si une notification est retardée, le crédit prend effet lors de son rapprochement sur la consommation
|
||||
alors enregistrée. Un remboursement, même partiel, retire le crédit de la mensualité concernée.
|
||||
La résiliation arrête les futurs prélèvements, sans effacer les crédits des paiements non remboursés.
|
||||
Un seul abonnement non résilié est autorisé par compte ; un changement de pack nécessite sa résiliation préalable.
|
||||
</p>
|
||||
<p>
|
||||
<a asp-controller="ResourceSubscription" asp-action="Index">Souscrire, consulter ou résilier un abonnement</a>.
|
||||
Cette page et la consultation du quota restent accessibles lorsque le seuil est atteint.
|
||||
</p>
|
||||
<p>
|
||||
L'inscription gratuite dispose du quota disque standard (@Constants.DefaultFSQ octets).
|
||||
Découverte porte le quota disque à deux fois ce quota (@(Constants.DefaultFSQ * 2L) octets),
|
||||
et Premium à cinq fois ce quota (@(Constants.DefaultFSQ * 5L) octets),
|
||||
pendant la mensualité payée, même après résiliation jusqu'à son échéance UTC.
|
||||
À l'échéance sans renouvellement payé, ou après remboursement de la mensualité, le quota habituel reprend.
|
||||
Aucun fichier existant n'est supprimé ; si l'espace occupé dépasse le quota redevenu applicable,
|
||||
de nouveaux téléversements sont refusés. La taille maximale autorisée d'un fichier n'augmente pas.
|
||||
</p>
|
||||
|
||||
<h2>Seuil et contrôle des opérations</h2>
|
||||
<p>
|
||||
Le seuil par défaut de cette instance est de <strong>@rule.DefaultLimit points</strong>.
|
||||
Un seuil individuel peut être fixé par l'administration.
|
||||
@if (!string.IsNullOrWhiteSpace(userId))
|
||||
{
|
||||
<span>Le seuil actuellement applicable à votre compte est de <strong>@limit points</strong>.</span>
|
||||
}
|
||||
</p>
|
||||
<p>
|
||||
Une opération est refusée si le quota est déjà atteint ou si son coût connu dépasse le solde disponible.
|
||||
L'appel API et le corps entrant de taille connue sont comptabilisés avant son exécution.
|
||||
Pour un téléversement de fichiers personnels, le volume de fichiers est aussi contrôlé avant l'écriture.
|
||||
Le coût restant, inconnu à l'avance, est constaté après l'opération.
|
||||
Une opération en cours peut donc porter l'indicateur au-delà du seuil, notamment en cas d'opérations simultanées ;
|
||||
les suivantes sont alors refusées. Il ne s'agit pas d'une interruption stricte à chaque octet ou seconde consommée.
|
||||
</p>
|
||||
<p>
|
||||
Un refus est signalé par le code HTTP <strong>429</strong> et le motif <code>resource_quota_exceeded</code>.
|
||||
Les opérations exécutées, même en échec, peuvent consommer des points ; une tentative refusée par le contrôle
|
||||
d'admission n'est pas comptabilisée. La consultation de la consommation et des présentes CGU,
|
||||
ainsi que la connexion et le renouvellement de session, restent accessibles.
|
||||
Le compte n'est pas suspendu : les opérations redeviennent possibles dès que le seuil configuré autorise leur coût.
|
||||
</p>
|
||||
<p>
|
||||
Dans PostIt, consultez « Mon profil » pour connaître votre indicateur et votre solde.
|
||||
En cas de quota insuffisant, contactez l'administration via
|
||||
<a asp-controller="Home" asp-action="Contact">la page de contact</a>.
|
||||
Les coefficients et seuils sont configurés par l'exploitant ; toute modification des coefficients
|
||||
recalcule l'indicateur à partir des compteurs existants.
|
||||
</p>
|
||||
<p><a asp-controller="Home" asp-action="Privacy">Protection des données</a></p>
|
||||
64
src/Yavsc.Org/Views/ResourceSubscription/Index.cshtml
Normal file
64
src/Yavsc.Org/Views/ResourceSubscription/Index.cshtml
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
@model Yavsc.ViewModels.ResourceSubscriptionPage
|
||||
@{
|
||||
ViewBag.Title = "Abonnements de consommation";
|
||||
}
|
||||
<h1>Abonnements Découverte et Premium</h1>
|
||||
<p>L'inscription gratuite donne accès à @Model.FreeQuota points, sans renouvellement mensuel automatique.</p>
|
||||
<p>
|
||||
Consommation brute : @Model.Usage.GrossConsumption points.
|
||||
Après crédits : <strong>@Model.Usage.Consumption points</strong>.
|
||||
Crédit reporté disponible : <strong>@Model.Usage.CreditBalance points</strong>.
|
||||
Solde utilisable avec le quota gratuit : @Model.Usage.RemainingConsumption points.
|
||||
Quota disque actuel : @Model.Usage.DiskQuota octets.
|
||||
</p>
|
||||
<p>
|
||||
Chaque mensualité PayPal confirmée efface la consommation disponible, dans la limite du pack.
|
||||
Les deux tiers du crédit mensuel inutilisé sont conservés sans expiration, même après résiliation.
|
||||
Le crédit déjà reporté est utilisé avant le nouveau crédit. Aucune mensualité impayée ne donne de crédit.
|
||||
</p>
|
||||
<div class="row">
|
||||
@foreach (var pack in new[] { "Discovery", "Premium" })
|
||||
{
|
||||
var premium = pack == "Premium";
|
||||
var name = premium ? "Premium" : "Découverte";
|
||||
var price = premium ? Model.Prices.PremiumPriceExcludingTax : Model.Prices.DiscoveryPriceExcludingTax;
|
||||
<section class="col-md-6">
|
||||
<h2>@name</h2>
|
||||
<p>@(Model.FreeQuota * (premium ? 3 : 1)) points par mensualité payée.</p>
|
||||
<p>Quota disque : @(premium ? "cinq" : "deux") fois le quota gratuit standard
|
||||
(@(Constants.DefaultFSQ * (premium ? 5L : 2L)) octets) pendant la mensualité payée,
|
||||
même après résiliation jusqu'à son échéance. Aucun fichier supprimé au retour au quota habituel.</p>
|
||||
<p>
|
||||
@price.ToString("F2") € HT par mois + TVA @Model.Prices.VatPercent %,
|
||||
soit <strong>@Model.Prices.TotalPrice(price).ToString("F2") € TTC prélevés par mois</strong>.
|
||||
</p>
|
||||
<form asp-action="Create" method="post">
|
||||
<input type="hidden" name="pack" value="@pack" />
|
||||
<button type="submit" class="btn btn-primary">Souscrire / reprendre @name avec PayPal</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
<p>Le premier crédit est accordé après le premier paiement confirmé, puis à chaque mensualité payée à la date anniversaire UTC du début PayPal.</p>
|
||||
<p>Un seul abonnement non résilié par compte. Pour changer de pack, résiliez d'abord le précédent. Un remboursement, même partiel, retire le crédit de la mensualité correspondante.</p>
|
||||
<h2>Mes abonnements</h2>
|
||||
@foreach (var subscription in Model.Subscriptions)
|
||||
{
|
||||
<section class="border rounded p-3 mb-3">
|
||||
<h3>@(subscription.Pack == "Premium" ? "Premium" : "Découverte")</h3>
|
||||
<p>État PayPal : @subscription.State. Référence : @subscription.PayPalId</p>
|
||||
<p>Tarif souscrit : @subscription.PriceExcludingTax.ToString("F2") € HT, @subscription.PriceIncludingTax.ToString("F2") € TTC. Crédit mensuel : @subscription.MonthlyPoints points.</p>
|
||||
<p>Début UTC : @subscription.StartsAt?.ToUniversalTime().ToString("u"). Prochain prélèvement UTC : @subscription.NextBillingAt?.ToUniversalTime().ToString("u").</p>
|
||||
@if (subscription.PayPalId is not null && subscription.State is not ("CANCELLED" or "EXPIRED"))
|
||||
{
|
||||
<form asp-action="Cancel" method="post">
|
||||
<input type="hidden" name="id" value="@subscription.Id" />
|
||||
<button type="submit" class="btn btn-outline-danger">Résilier cet abonnement PayPal</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
<form asp-action="Refresh" method="post">
|
||||
<button type="submit" class="btn btn-secondary">Actualiser les paiements et les crédits depuis PayPal</button>
|
||||
</form>
|
||||
<p><a asp-controller="Home" asp-action="CGU">CGU de PostIt et de Yavsc</a></p>
|
||||
|
|
@ -42,6 +42,8 @@
|
|||
<footer class="border-top footer text-muted">
|
||||
<div class="container">
|
||||
© WTFPL 2025 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
|
||||
- <a asp-area="" asp-controller="Home" asp-action="CGU">CGU de PostIt et de Yavsc</a>
|
||||
- <a asp-area="" asp-controller="ResourceSubscription" asp-action="Index">Abonnements</a>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,15 @@
|
|||
{
|
||||
"ResourceSubscriptions": {
|
||||
"DiscoveryPlanId": "",
|
||||
"PremiumPlanId": "",
|
||||
"WebhookId": "",
|
||||
"DiscoveryPriceExcludingTax": 1,
|
||||
"PremiumPriceExcludingTax": 2,
|
||||
"VatPercent": 20
|
||||
},
|
||||
"ResourceUsage": {
|
||||
"UserLimits": {}
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
|
|
|||
Loading…
Reference in a new issue