fix: busca do usuário para criar assinatura
All checks were successful
BCards Deployment Pipeline / Run Tests (push) Successful in 3s
BCards Deployment Pipeline / PR Validation (push) Has been skipped
BCards Deployment Pipeline / Build and Push Image (push) Successful in 15m54s
BCards Deployment Pipeline / Deploy to Production (ARM - OCI) (push) Successful in 1m22s
BCards Deployment Pipeline / Deploy to Staging (x86 - Local) (push) Has been skipped
BCards Deployment Pipeline / Cleanup Old Resources (push) Has been skipped
BCards Deployment Pipeline / Deployment Summary (push) Successful in 0s

This commit is contained in:
Ricardo Carneiro 2025-09-07 22:32:01 -03:00
parent 0f6ae71997
commit 32b83923dc

View File

@ -4,6 +4,7 @@ using BCards.Web.Services;
using BCards.Web.Repositories; using BCards.Web.Repositories;
using BCards.Web.Configuration; using BCards.Web.Configuration;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using MongoDB.Driver;
namespace BCards.Web.Controllers; namespace BCards.Web.Controllers;
@ -14,17 +15,20 @@ public class StripeWebhookController : ControllerBase
private readonly ILogger<StripeWebhookController> _logger; private readonly ILogger<StripeWebhookController> _logger;
private readonly ISubscriptionRepository _subscriptionRepository; private readonly ISubscriptionRepository _subscriptionRepository;
private readonly IUserPageService _userPageService; private readonly IUserPageService _userPageService;
private readonly IUserRepository _userRepository;
private readonly string _webhookSecret; private readonly string _webhookSecret;
public StripeWebhookController( public StripeWebhookController(
ILogger<StripeWebhookController> logger, ILogger<StripeWebhookController> logger,
ISubscriptionRepository subscriptionRepository, ISubscriptionRepository subscriptionRepository,
IUserPageService userPageService, IUserPageService userPageService,
IUserRepository userRepository,
IOptions<StripeSettings> stripeSettings) IOptions<StripeSettings> stripeSettings)
{ {
_logger = logger; _logger = logger;
_subscriptionRepository = subscriptionRepository; _subscriptionRepository = subscriptionRepository;
_userPageService = userPageService; _userPageService = userPageService;
_userRepository = userRepository;
_webhookSecret = stripeSettings.Value.WebhookSecret ?? ""; _webhookSecret = stripeSettings.Value.WebhookSecret ?? "";
} }
@ -313,6 +317,9 @@ public class StripeWebhookController : ControllerBase
else else
{ {
_logger.LogWarning($"Subscription not found in database: {stripeSubscription.Id}"); _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 else
@ -377,4 +384,69 @@ public class StripeWebhookController : ControllerBase
return null; 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<IMongoDatabase>();
var usersCollection = mongoDatabase.GetCollection<Models.User>("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;
}
}
} }