using Hutopy.Modules.Memberships.Contracts; using Hutopy.Modules.Memberships.Data; namespace Hutopy.Modules.Memberships.Services; public class MembershipNotifier( MembershipsDbContext dbContext) : IMembershipNotifier { public async Task NotifyCheckoutSessionCompleted( string stripeSessionId, string stripeSubscriptionId, string userId, string creatorId, string tierId, CancellationToken cancellationToken = default) { Membership membership = new() { Id = Guid.CreateVersion7(), CreatedAt = DateTimeOffset.UtcNow, UserId = Guid.Parse(userId), CreatorId = Guid.Parse(creatorId), TierId = Guid.Parse(tierId), StripeSubscriptionId = stripeSubscriptionId, State = MembershipState.Pending, StartDate = null, EndDate = null }; dbContext.Memberships.Add(membership); await dbContext.SaveChangesAsync(cancellationToken); } public async Task NotifyPaymentSucceedAsync( string stripeSubscriptionId, string hostedInvoiceUrl, decimal amount, string currency, CancellationToken cancellationToken = default) { Membership? membership = await dbContext .Memberships .SingleOrDefaultAsync( m => m.StripeSubscriptionId == stripeSubscriptionId, cancellationToken); if (membership is null) { return; } Payment payment = new() { Id = Guid.CreateVersion7(), CreatedAt = DateTimeOffset.UtcNow, Amount = amount, Currency = currency, InvoiceUrl = hostedInvoiceUrl }; membership.State = MembershipState.Active; membership.StartDate = DateTimeOffset.UtcNow; membership.Payments.Add(payment); dbContext.Payments.Add(payment); await dbContext.SaveChangesAsync(cancellationToken); } public async Task NotifySubscriptionUpdatedAsync( string subscriptionId, DateTimeOffset? endDate, CancellationToken cancellationToken = default) { Membership? membership = await dbContext .Memberships .SingleOrDefaultAsync( s => s.StripeSubscriptionId == subscriptionId, cancellationToken); if (membership == null) { return; } membership.EndDate = endDate; await dbContext.SaveChangesAsync(cancellationToken); } public async Task NotifySubscriptionDeletedAsync( string subscriptionId, CancellationToken cancellationToken) { Membership? membership = await dbContext .Memberships .SingleOrDefaultAsync( s => s.StripeSubscriptionId == subscriptionId, cancellationToken); if (membership == null) { return; } membership.State = MembershipState.Inactive; await dbContext.SaveChangesAsync(cancellationToken); } }