From 32b83923dc78402edb7481494b872d820e289cb1 Mon Sep 17 00:00:00 2001 From: Ricardo Carneiro Date: Sun, 7 Sep 2025 22:32:01 -0300 Subject: [PATCH] =?UTF-8?q?fix:=20busca=20do=20usu=C3=A1rio=20para=20criar?= =?UTF-8?q?=20assinatura?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/StripeWebhookController.cs | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/BCards.Web/Controllers/StripeWebhookController.cs b/src/BCards.Web/Controllers/StripeWebhookController.cs index 71922d5..9d8443e 100644 --- a/src/BCards.Web/Controllers/StripeWebhookController.cs +++ b/src/BCards.Web/Controllers/StripeWebhookController.cs @@ -4,6 +4,7 @@ using BCards.Web.Services; using BCards.Web.Repositories; using BCards.Web.Configuration; using Microsoft.Extensions.Options; +using MongoDB.Driver; namespace BCards.Web.Controllers; @@ -14,17 +15,20 @@ public class StripeWebhookController : ControllerBase private readonly ILogger _logger; private readonly ISubscriptionRepository _subscriptionRepository; private readonly IUserPageService _userPageService; + private readonly IUserRepository _userRepository; private readonly string _webhookSecret; public StripeWebhookController( ILogger logger, ISubscriptionRepository subscriptionRepository, IUserPageService userPageService, + IUserRepository userRepository, IOptions stripeSettings) { _logger = logger; _subscriptionRepository = subscriptionRepository; _userPageService = userPageService; + _userRepository = userRepository; _webhookSecret = stripeSettings.Value.WebhookSecret ?? ""; } @@ -313,6 +317,9 @@ public class StripeWebhookController : ControllerBase else { _logger.LogWarning($"Subscription not found in database: {stripeSubscription.Id}"); + + // Try to find user by Stripe Customer ID and create/update subscription + await HandleSubscriptionCreatedForNewSubscription(stripeSubscription); } } else @@ -377,4 +384,69 @@ public class StripeWebhookController : ControllerBase return null; } + + private async Task HandleSubscriptionCreatedForNewSubscription(Subscription stripeSubscription) + { + try + { + // Find user by Stripe Customer ID using a MongoDB query + // Since IUserRepository doesn't have GetByStripeCustomerIdAsync, we'll use MongoDB directly + var mongoDatabase = HttpContext.RequestServices.GetRequiredService(); + var usersCollection = mongoDatabase.GetCollection("users"); + + var user = await usersCollection.Find(u => u.StripeCustomerId == stripeSubscription.CustomerId).FirstOrDefaultAsync(); + + if (user != null) + { + _logger.LogInformation($"Found user {user.Id} for customer {stripeSubscription.CustomerId}"); + + var service = new SubscriptionItemService(); + var subItem = service.Get(stripeSubscription.Items.Data[0].Id); + + // Get plan type from price ID + var priceId = stripeSubscription.Items.Data.FirstOrDefault()?.Price.Id; + var planType = !string.IsNullOrEmpty(priceId) ? MapPriceIdToPlanType(priceId) : "Trial"; + + // Create new subscription in our database + var newSubscription = new Models.Subscription + { + Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString(), + UserId = user.Id, + StripeSubscriptionId = stripeSubscription.Id, + Status = "active", + PlanType = planType, + CurrentPeriodStart = subItem.CurrentPeriodStart, + CurrentPeriodEnd = subItem.CurrentPeriodEnd, + CancelAtPeriodEnd = stripeSubscription.CancelAtPeriodEnd, + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + + await _subscriptionRepository.CreateAsync(newSubscription); + _logger.LogInformation($"Created new subscription {newSubscription.Id} for user {user.Id}"); + + // Activate user pages that were pending payment or expired + var userPages = await _userPageService.GetUserPagesAsync(user.Id); + foreach (var page in userPages.Where(p => + p.Status == ViewModels.PageStatus.PendingPayment || + p.Status == ViewModels.PageStatus.Expired)) + { + page.Status = ViewModels.PageStatus.Active; + page.UpdatedAt = DateTime.UtcNow; + await _userPageService.UpdatePageAsync(page); + } + + _logger.LogInformation($"Activated {userPages.Count()} pages for user {user.Id} after subscription creation"); + } + else + { + _logger.LogError($"User not found for Stripe customer ID: {stripeSubscription.CustomerId}"); + } + } + catch (Exception ex) + { + _logger.LogError(ex, $"Error handling new subscription creation for {stripeSubscription.Id}"); + throw; + } + } } \ No newline at end of file