Merge pull request 'Release/versao1' (#19) from Release/versao1 into main
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 20m12s
BCards Deployment Pipeline / Deploy to Release Swarm (ARM) (push) Has been skipped
BCards Deployment Pipeline / Deploy to Production (ARM - OCI) (push) Successful in 1m21s
BCards Deployment Pipeline / Cleanup Old Resources (push) Has been skipped
BCards Deployment Pipeline / Deployment Summary (push) Successful in 0s
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 20m12s
BCards Deployment Pipeline / Deploy to Release Swarm (ARM) (push) Has been skipped
BCards Deployment Pipeline / Deploy to Production (ARM - OCI) (push) Successful in 1m21s
BCards Deployment Pipeline / Cleanup Old Resources (push) Has been skipped
BCards Deployment Pipeline / Deployment Summary (push) Successful in 0s
Reviewed-on: http://git.carneiro.ddnsfree.com/ricardo/BCards/pulls/19
This commit is contained in:
commit
d76435f98a
@ -27,7 +27,8 @@
|
||||
"Bash(./clean-build.sh:*)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(scp:*)",
|
||||
"Bash(ssh:*)"
|
||||
"Bash(ssh:*)",
|
||||
"Bash(cat:*)"
|
||||
]
|
||||
},
|
||||
"enableAllProjectMcpServers": false
|
||||
|
||||
@ -28,16 +28,21 @@ Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Testing|Any CPU = Testing|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{2E8F4B5C-9B3A-4F8E-8C7D-1A2B3C4D5E6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2E8F4B5C-9B3A-4F8E-8C7D-1A2B3C4D5E6F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2E8F4B5C-9B3A-4F8E-8C7D-1A2B3C4D5E6F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2E8F4B5C-9B3A-4F8E-8C7D-1A2B3C4D5E6F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2E8F4B5C-9B3A-4F8E-8C7D-1A2B3C4D5E6F}.Testing|Any CPU.ActiveCfg = Testing|Any CPU
|
||||
{2E8F4B5C-9B3A-4F8E-8C7D-1A2B3C4D5E6F}.Testing|Any CPU.Build.0 = Testing|Any CPU
|
||||
{8F9E4C7D-2A3B-4E5F-9C8D-1B2A3E4F5C6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8F9E4C7D-2A3B-4E5F-9C8D-1B2A3E4F5C6D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8F9E4C7D-2A3B-4E5F-9C8D-1B2A3E4F5C6D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8F9E4C7D-2A3B-4E5F-9C8D-1B2A3E4F5C6D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{8F9E4C7D-2A3B-4E5F-9C8D-1B2A3E4F5C6D}.Testing|Any CPU.ActiveCfg = Testing|Any CPU
|
||||
{8F9E4C7D-2A3B-4E5F-9C8D-1B2A3E4F5C6D}.Testing|Any CPU.Build.0 = Testing|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@ -6,6 +6,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<Configurations>Debug;Release;Testing</Configurations>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@ -6,6 +6,7 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems>
|
||||
<RuntimeIdentifiers>linux-x64;linux-arm64</RuntimeIdentifiers>
|
||||
<Configurations>Debug;Release;Testing</Configurations>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@ -36,4 +37,8 @@
|
||||
<EmbeddedResource Include="Resources\**\*.resx" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Testing'">
|
||||
<DefineConstants>$(DefineConstants);TESTING</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@ -24,6 +24,7 @@ public class AdminController : Controller
|
||||
private readonly ILivePageService _livePageService;
|
||||
private readonly IImageStorageService _imageStorage;
|
||||
private readonly IPaymentService _paymentService;
|
||||
private readonly IDowngradeService _downgradeService;
|
||||
private readonly ILogger<AdminController> _logger;
|
||||
|
||||
public AdminController(
|
||||
@ -36,6 +37,7 @@ public class AdminController : Controller
|
||||
ILivePageService livePageService,
|
||||
IImageStorageService imageStorage,
|
||||
IPaymentService paymentService,
|
||||
IDowngradeService downgradeService,
|
||||
ILogger<AdminController> logger)
|
||||
{
|
||||
_authService = authService;
|
||||
@ -47,6 +49,7 @@ public class AdminController : Controller
|
||||
_livePageService = livePageService;
|
||||
_imageStorage = imageStorage;
|
||||
_paymentService = paymentService;
|
||||
_downgradeService = downgradeService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@ -299,6 +302,19 @@ public class AdminController : Controller
|
||||
|
||||
if (model.IsNewPage)
|
||||
{
|
||||
// CRITICAL: Check if user can create new page (validate MaxPages limit)
|
||||
var existingPages = await _userPageService.GetUserPagesAsync(user.Id);
|
||||
var userPlanType = Enum.TryParse<PlanType>(user.CurrentPlan, true, out var planType) ? planType : PlanType.Trial;
|
||||
var maxPages = userPlanType.GetMaxPages();
|
||||
|
||||
if (existingPages.Count >= maxPages)
|
||||
{
|
||||
TempData["Error"] = $"Você já atingiu o limite de {maxPages} página(s) do seu plano atual. Faça upgrade para criar mais páginas.";
|
||||
model.AvailableCategories = await _categoryService.GetAllCategoriesAsync();
|
||||
model.AvailableThemes = await _themeService.GetAvailableThemesAsync();
|
||||
return View(model);
|
||||
}
|
||||
|
||||
// Generate slug if not provided
|
||||
if (string.IsNullOrEmpty(model.Slug))
|
||||
{
|
||||
@ -535,6 +551,54 @@ public class AdminController : Controller
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.TiktokUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "TikTok",
|
||||
Url = model.TiktokUrl,
|
||||
Icon = "fab fa-tiktok",
|
||||
IsActive = true,
|
||||
Order = userPage.Links.Count + socialLinks.Count
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.PinterestUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Pinterest",
|
||||
Url = model.PinterestUrl,
|
||||
Icon = "fab fa-pinterest",
|
||||
IsActive = true,
|
||||
Order = userPage.Links.Count + socialLinks.Count
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.DiscordUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Discord",
|
||||
Url = model.DiscordUrl,
|
||||
Icon = "fab fa-discord",
|
||||
IsActive = true,
|
||||
Order = userPage.Links.Count + socialLinks.Count
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.KawaiUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Kawai",
|
||||
Url = model.KawaiUrl,
|
||||
Icon = "fas fa-heart",
|
||||
IsActive = true,
|
||||
Order = userPage.Links.Count + socialLinks.Count
|
||||
});
|
||||
}
|
||||
|
||||
userPage.Links.AddRange(socialLinks);
|
||||
|
||||
await _userPageService.CreatePageAsync(userPage);
|
||||
@ -806,6 +870,54 @@ public class AdminController : Controller
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.TiktokUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "TikTok",
|
||||
Url = model.TiktokUrl,
|
||||
Icon = "fab fa-tiktok",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.PinterestUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Pinterest",
|
||||
Url = model.PinterestUrl,
|
||||
Icon = "fab fa-pinterest",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.DiscordUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Discord",
|
||||
Url = model.DiscordUrl,
|
||||
Icon = "fab fa-discord",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.KawaiUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Kawai",
|
||||
Url = model.KawaiUrl,
|
||||
Icon = "fas fa-heart",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
userPage.Links.AddRange(socialLinks);
|
||||
return userPage;
|
||||
}
|
||||
@ -916,6 +1028,54 @@ public class AdminController : Controller
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.TiktokUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "TikTok",
|
||||
Url = model.TiktokUrl,
|
||||
Icon = "fab fa-tiktok",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.PinterestUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Pinterest",
|
||||
Url = model.PinterestUrl,
|
||||
Icon = "fab fa-pinterest",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.DiscordUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Discord",
|
||||
Url = model.DiscordUrl,
|
||||
Icon = "fab fa-discord",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(model.KawaiUrl))
|
||||
{
|
||||
socialLinks.Add(new LinkItem
|
||||
{
|
||||
Title = "Kawai",
|
||||
Url = model.KawaiUrl,
|
||||
Icon = "fas fa-heart",
|
||||
IsActive = true,
|
||||
Order = currentOrder++
|
||||
});
|
||||
}
|
||||
|
||||
page.Links.AddRange(socialLinks);
|
||||
}
|
||||
|
||||
@ -1126,6 +1286,18 @@ public class AdminController : Controller
|
||||
}
|
||||
}
|
||||
|
||||
// Método auxiliar para critérios de downgrade (usado na API)
|
||||
private DowngradeCriteria GetDowngradeCriteria(PlanType plan)
|
||||
{
|
||||
return new DowngradeCriteria
|
||||
{
|
||||
MaxPages = plan.GetMaxPages(),
|
||||
MaxLinksPerPage = plan.GetMaxLinksPerPage(),
|
||||
SelectionCriteria = "Páginas mais antigas têm prioridade",
|
||||
LinksCriteria = "Páginas com muitos links são automaticamente suspensas"
|
||||
};
|
||||
}
|
||||
|
||||
private void CleanSocialMediaFields(ManagePageViewModel model)
|
||||
{
|
||||
// Tratar espaço em branco como campo vazio para redes sociais
|
||||
@ -1140,8 +1312,81 @@ public class AdminController : Controller
|
||||
|
||||
if (string.IsNullOrWhiteSpace(model.TwitterUrl) || model.TwitterUrl.Trim().Length <= 1)
|
||||
model.TwitterUrl = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(model.TiktokUrl) || model.TiktokUrl.Trim().Length <= 1)
|
||||
model.TiktokUrl = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(model.PinterestUrl) || model.PinterestUrl.Trim().Length <= 1)
|
||||
model.PinterestUrl = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(model.DiscordUrl) || model.DiscordUrl.Trim().Length <= 1)
|
||||
model.DiscordUrl = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(model.KawaiUrl) || model.KawaiUrl.Trim().Length <= 1)
|
||||
model.KawaiUrl = string.Empty;
|
||||
}
|
||||
|
||||
// Endpoint para validar impacto de downgrade
|
||||
[HttpPost]
|
||||
[Route("ValidateDowngrade")]
|
||||
public async Task<IActionResult> ValidateDowngrade(string targetPlan)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = await _authService.GetCurrentUserAsync(User);
|
||||
if (user == null)
|
||||
return Json(new { error = "Usuário não encontrado" });
|
||||
|
||||
if (!Enum.TryParse<PlanType>(targetPlan, true, out var newPlan))
|
||||
return Json(new { error = "Plano inválido" });
|
||||
|
||||
var analysis = await _downgradeService.AnalyzeDowngradeImpact(user.Id, newPlan);
|
||||
|
||||
// CASO CRÍTICO: Nenhuma página atende os critérios
|
||||
if (analysis.IsCritical)
|
||||
{
|
||||
return Json(new
|
||||
{
|
||||
canDowngrade = false,
|
||||
critical = true,
|
||||
title = "⚠️ Downgrade não recomendado",
|
||||
message = "Nenhuma de suas páginas atende aos limites do novo plano. Todas seriam suspensas.",
|
||||
details = analysis.Issues,
|
||||
suggestion = "Considere editar suas páginas para reduzir o número de links antes do downgrade.",
|
||||
criteria = GetDowngradeCriteria(newPlan)
|
||||
});
|
||||
}
|
||||
|
||||
// CASO NORMAL: Algumas páginas serão afetadas
|
||||
return Json(new
|
||||
{
|
||||
canDowngrade = true,
|
||||
critical = false,
|
||||
title = "Confirmação de Downgrade",
|
||||
summary = analysis.Summary,
|
||||
eligiblePages = analysis.EligiblePages.Select(p => new
|
||||
{
|
||||
name = p.DisplayName,
|
||||
linkCount = p.LinkCount,
|
||||
reason = "✅ Dentro dos limites"
|
||||
}),
|
||||
suspendedPages = analysis.AffectedPages.Select(p => new
|
||||
{
|
||||
name = p.DisplayName,
|
||||
linkCount = p.LinkCount,
|
||||
reason = p.SuspensionReason
|
||||
}),
|
||||
criteria = GetDowngradeCriteria(newPlan)
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Erro ao validar downgrade para usuário {User}", User.Identity?.Name);
|
||||
return Json(new { error = "Erro interno do servidor" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 🔥 OTIMIZAÇÃO: Endpoint para manter a sessão do usuário ativa
|
||||
[HttpPost]
|
||||
[Route("KeepAlive")]
|
||||
@ -1157,6 +1402,10 @@ public class AdminController : Controller
|
||||
modelState.Remove<ManagePageViewModel>(x => x.FacebookUrl);
|
||||
modelState.Remove<ManagePageViewModel>(x => x.TwitterUrl);
|
||||
modelState.Remove<ManagePageViewModel>(x => x.WhatsAppNumber);
|
||||
modelState.Remove<ManagePageViewModel>(x => x.TiktokUrl);
|
||||
modelState.Remove<ManagePageViewModel>(x => x.PinterestUrl);
|
||||
modelState.Remove<ManagePageViewModel>(x => x.DiscordUrl);
|
||||
modelState.Remove<ManagePageViewModel>(x => x.KawaiUrl);
|
||||
|
||||
// Remover validação de 'Description' para links do tipo 'Normal'
|
||||
if (model.Links != null)
|
||||
|
||||
@ -6,7 +6,9 @@ using Microsoft.AspNetCore.Authentication.MicrosoftAccount;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
#if TESTING
|
||||
using BCards.Web.TestSupport;
|
||||
#endif
|
||||
|
||||
namespace BCards.Web.Controllers;
|
||||
|
||||
@ -148,8 +150,10 @@ public class AuthController : Controller
|
||||
return Challenge(properties, MicrosoftAccountDefaults.AuthenticationScheme);
|
||||
}
|
||||
|
||||
#if TESTING
|
||||
[HttpPost]
|
||||
[Route("LoginWithTest")]
|
||||
|
||||
public IActionResult LoginWithTest(string? returnUrl = null)
|
||||
{
|
||||
if (!_env.IsEnvironment("Testing"))
|
||||
@ -170,6 +174,7 @@ public class AuthController : Controller
|
||||
var properties = new AuthenticationProperties { RedirectUri = redirectUrlString };
|
||||
return Challenge(properties, TestAuthConstants.AuthenticationScheme);
|
||||
}
|
||||
#endif
|
||||
|
||||
[HttpGet]
|
||||
[Route("GoogleCallback")]
|
||||
|
||||
170
src/BCards.Web/Controllers/TestToolsController.cs
Normal file
170
src/BCards.Web/Controllers/TestToolsController.cs
Normal file
@ -0,0 +1,170 @@
|
||||
#if TESTING
|
||||
using BCards.Web.Models;
|
||||
using BCards.Web.Repositories;
|
||||
using BCards.Web.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace BCards.Web.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[Route("testing/tools")]
|
||||
public class TestToolsController : ControllerBase
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly ISubscriptionRepository _subscriptionRepository;
|
||||
private readonly IUserPageService _userPageService;
|
||||
private readonly ILivePageService _livePageService;
|
||||
private readonly IPlanConfigurationService _planConfigurationService;
|
||||
private readonly IWebHostEnvironment _environment;
|
||||
|
||||
public TestToolsController(
|
||||
IUserRepository userRepository,
|
||||
ISubscriptionRepository subscriptionRepository,
|
||||
IUserPageService userPageService,
|
||||
ILivePageService livePageService,
|
||||
IPlanConfigurationService planConfigurationService,
|
||||
IWebHostEnvironment environment)
|
||||
{
|
||||
_userRepository = userRepository;
|
||||
_subscriptionRepository = subscriptionRepository;
|
||||
_userPageService = userPageService;
|
||||
_livePageService = livePageService;
|
||||
_planConfigurationService = planConfigurationService;
|
||||
_environment = environment;
|
||||
}
|
||||
|
||||
[HttpPost("plan")]
|
||||
public async Task<IActionResult> SetPlan([FromBody] SetPlanRequest request)
|
||||
{
|
||||
if (!_environment.IsEnvironment("Testing"))
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (!Enum.TryParse<PlanType>(request.Plan, true, out var planType))
|
||||
{
|
||||
return BadRequest(new { error = $"Plano desconhecido: {request.Plan}" });
|
||||
}
|
||||
|
||||
var email = string.IsNullOrWhiteSpace(request.Email)
|
||||
? TestUserDefaults.Email
|
||||
: request.Email!.Trim();
|
||||
|
||||
var user = await _userRepository.GetByEmailAsync(email);
|
||||
if (user == null)
|
||||
{
|
||||
return NotFound(new { error = $"Usuário de teste não encontrado para o e-mail {email}" });
|
||||
}
|
||||
|
||||
var planLimits = _planConfigurationService.GetPlanLimitations(planType);
|
||||
var normalizedPlan = planLimits.PlanType ?? planType.ToString().ToLowerInvariant();
|
||||
|
||||
user.CurrentPlan = normalizedPlan;
|
||||
user.SubscriptionStatus = "active";
|
||||
user.UpdatedAt = DateTime.UtcNow;
|
||||
await _userRepository.UpdateAsync(user);
|
||||
|
||||
var subscription = await _subscriptionRepository.GetByUserIdAsync(user.Id);
|
||||
if (subscription == null)
|
||||
{
|
||||
subscription = new Subscription
|
||||
{
|
||||
UserId = user.Id,
|
||||
StripeSubscriptionId = $"test-{Guid.NewGuid():N}",
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
subscription.PlanType = normalizedPlan;
|
||||
subscription.Status = "active";
|
||||
subscription.MaxLinks = planLimits.MaxLinks;
|
||||
subscription.AllowAnalytics = planLimits.AllowAnalytics;
|
||||
subscription.AllowCustomThemes = planLimits.AllowCustomThemes;
|
||||
subscription.AllowCustomDomain = planLimits.AllowCustomDomain;
|
||||
subscription.AllowMultipleDomains = planLimits.AllowMultipleDomains;
|
||||
subscription.PrioritySupport = planLimits.PrioritySupport;
|
||||
subscription.CurrentPeriodStart = DateTime.UtcNow.Date;
|
||||
subscription.CurrentPeriodEnd = DateTime.UtcNow.Date.AddMonths(1);
|
||||
subscription.CancelAtPeriodEnd = false;
|
||||
subscription.UpdatedAt = DateTime.UtcNow;
|
||||
|
||||
if (string.IsNullOrEmpty(subscription.Id))
|
||||
{
|
||||
await _subscriptionRepository.CreateAsync(subscription);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _subscriptionRepository.UpdateAsync(subscription);
|
||||
}
|
||||
|
||||
var pages = await _userPageService.GetUserPagesAsync(user.Id);
|
||||
var originalPagesCount = pages.Count;
|
||||
var removed = 0;
|
||||
if (request.ResetPages)
|
||||
{
|
||||
foreach (var page in pages)
|
||||
{
|
||||
await _livePageService.DeleteByOriginalPageIdAsync(page.Id);
|
||||
await _userPageService.DeletePageAsync(page.Id);
|
||||
removed++;
|
||||
}
|
||||
|
||||
pages = new List<UserPage>();
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var page in pages)
|
||||
{
|
||||
page.PlanLimitations = ClonePlanLimitations(planLimits);
|
||||
page.UpdatedAt = DateTime.UtcNow;
|
||||
await _userPageService.UpdatePageAsync(page);
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
email,
|
||||
plan = normalizedPlan,
|
||||
pagesAffected = request.ResetPages ? originalPagesCount : pages.Count,
|
||||
pagesRemoved = removed
|
||||
});
|
||||
}
|
||||
|
||||
private static PlanLimitations ClonePlanLimitations(PlanLimitations source)
|
||||
{
|
||||
return new PlanLimitations
|
||||
{
|
||||
MaxLinks = source.MaxLinks,
|
||||
AllowCustomThemes = source.AllowCustomThemes,
|
||||
AllowAnalytics = source.AllowAnalytics,
|
||||
AllowCustomDomain = source.AllowCustomDomain,
|
||||
AllowMultipleDomains = source.AllowMultipleDomains,
|
||||
PrioritySupport = source.PrioritySupport,
|
||||
PlanType = source.PlanType,
|
||||
MaxProductLinks = source.MaxProductLinks,
|
||||
MaxOGExtractionsPerDay = source.MaxOGExtractionsPerDay,
|
||||
AllowProductLinks = source.AllowProductLinks,
|
||||
SpecialModeration = source.SpecialModeration,
|
||||
OGExtractionsUsedToday = 0,
|
||||
LastExtractionDate = null
|
||||
};
|
||||
}
|
||||
|
||||
private static class TestUserDefaults
|
||||
{
|
||||
public const string Email = "test.user@example.com";
|
||||
}
|
||||
|
||||
public class SetPlanRequest
|
||||
{
|
||||
public string? Email { get; set; }
|
||||
|
||||
public string Plan { get; set; } = "trial";
|
||||
|
||||
public bool ResetPages { get; set; }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@ -18,7 +18,9 @@ using Serilog;
|
||||
using Serilog.Events;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Serilog.Sinks.OpenSearch;
|
||||
#if TESTING
|
||||
using BCards.Web.TestSupport;
|
||||
#endif
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
|
||||
@ -421,6 +423,7 @@ authBuilder.AddGoogle(options =>
|
||||
};
|
||||
});
|
||||
|
||||
#if TESTING
|
||||
// Conditionally set the DefaultChallengeScheme and register the Test scheme
|
||||
if (builder.Environment.IsEnvironment("Testing"))
|
||||
{
|
||||
@ -437,6 +440,12 @@ else
|
||||
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
|
||||
});
|
||||
}
|
||||
#else
|
||||
authBuilder.Services.Configure<AuthenticationOptions>(options =>
|
||||
{
|
||||
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
|
||||
});
|
||||
#endif
|
||||
|
||||
// Localization
|
||||
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
|
||||
@ -471,6 +480,7 @@ builder.Services.AddScoped<ICategoryService, CategoryService>();
|
||||
builder.Services.AddScoped<IOpenGraphService, OpenGraphService>();
|
||||
builder.Services.AddScoped<IModerationService, ModerationService>();
|
||||
builder.Services.AddScoped<IEmailService, EmailService>();
|
||||
builder.Services.AddScoped<IDowngradeService, DowngradeService>();
|
||||
|
||||
builder.Services.AddScoped<IImageStorageService, GridFSImageStorage>();
|
||||
|
||||
|
||||
225
src/BCards.Web/Services/DowngradeService.cs
Normal file
225
src/BCards.Web/Services/DowngradeService.cs
Normal file
@ -0,0 +1,225 @@
|
||||
using BCards.Web.Models;
|
||||
using BCards.Web.ViewModels;
|
||||
|
||||
namespace BCards.Web.Services;
|
||||
|
||||
public class DowngradeService : IDowngradeService
|
||||
{
|
||||
private readonly IUserPageService _userPageService;
|
||||
private readonly ILogger<DowngradeService> _logger;
|
||||
|
||||
// Ordem de prioridade dos planos (menor = melhor)
|
||||
private static readonly Dictionary<PlanType, int> PlanPriority = new()
|
||||
{
|
||||
{ PlanType.Trial, 0 },
|
||||
{ PlanType.Basic, 1 },
|
||||
{ PlanType.Professional, 2 },
|
||||
{ PlanType.Premium, 3 },
|
||||
{ PlanType.PremiumAffiliate, 4 }
|
||||
};
|
||||
|
||||
public DowngradeService(IUserPageService userPageService, ILogger<DowngradeService> logger)
|
||||
{
|
||||
_userPageService = userPageService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<DowngradeAnalysis> AnalyzeDowngradeImpact(string userId, PlanType newPlan)
|
||||
{
|
||||
var pages = await _userPageService.GetUserPagesAsync(userId);
|
||||
var activePagesOnly = pages.Where(p => p.Status == PageStatus.Active).ToList();
|
||||
|
||||
var newMaxPages = newPlan.GetMaxPages();
|
||||
var newMaxLinks = newPlan.GetMaxLinksPerPage();
|
||||
|
||||
var eligiblePages = activePagesOnly
|
||||
.Where(p => newMaxLinks == -1 || (p.Links?.Count ?? 0) <= newMaxLinks)
|
||||
.OrderBy(p => p.CreatedAt) // Mais antigas primeiro
|
||||
.Take(newMaxPages)
|
||||
.Select(p => new PageInfo
|
||||
{
|
||||
Id = p.Id,
|
||||
DisplayName = p.DisplayName,
|
||||
LinkCount = p.Links?.Count ?? 0,
|
||||
CreatedAt = p.CreatedAt
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var affectedPages = activePagesOnly
|
||||
.Where(p => !eligiblePages.Any(ep => ep.Id == p.Id))
|
||||
.Select(p => new PageInfo
|
||||
{
|
||||
Id = p.Id,
|
||||
DisplayName = p.DisplayName,
|
||||
LinkCount = p.Links?.Count ?? 0,
|
||||
CreatedAt = p.CreatedAt,
|
||||
SuspensionReason = GetSuspensionReason(p, newPlan)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var issues = new List<string>();
|
||||
|
||||
var pagesWithTooManyLinks = activePagesOnly
|
||||
.Where(p => newMaxLinks != -1 && (p.Links?.Count ?? 0) > newMaxLinks)
|
||||
.Count();
|
||||
|
||||
if (pagesWithTooManyLinks > 0)
|
||||
issues.Add($"{pagesWithTooManyLinks} páginas têm muitos links");
|
||||
|
||||
if (activePagesOnly.Count > newMaxPages)
|
||||
issues.Add($"Total de páginas ({activePagesOnly.Count}) excede limite ({newMaxPages})");
|
||||
|
||||
return new DowngradeAnalysis
|
||||
{
|
||||
EligiblePages = eligiblePages,
|
||||
AffectedPages = affectedPages,
|
||||
Issues = issues
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<DowngradeResult> ProcessAutomaticDowngrade(string userId, PlanType newPlan)
|
||||
{
|
||||
try
|
||||
{
|
||||
var analysis = await AnalyzeDowngradeImpact(userId, newPlan);
|
||||
|
||||
// PROTEÇÃO: Se nenhuma página for elegível, cancelar downgrade
|
||||
if (analysis.IsCritical)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Downgrade cancelado: nenhuma página atende aos critérios do novo plano. " +
|
||||
"Edite suas páginas para reduzir links ou escolha um plano superior."
|
||||
);
|
||||
}
|
||||
|
||||
// Processar normalmente - suspender páginas afetadas
|
||||
foreach (var pageInfo in analysis.AffectedPages)
|
||||
{
|
||||
var page = await _userPageService.GetPageByIdAsync(pageInfo.Id);
|
||||
if (page != null)
|
||||
{
|
||||
page.Status = PageStatus.SuspendedByPlanLimit;
|
||||
var detailedReason = GetDetailedSuspensionReason(page, newPlan);
|
||||
await _userPageService.UpdatePageAsync(page);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Página {PageName} (ID: {PageId}) suspensa por downgrade para {PlanType}. Motivo: {Reason}",
|
||||
page.DisplayName, page.Id, newPlan, detailedReason
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
var result = new DowngradeResult
|
||||
{
|
||||
Success = true,
|
||||
KeptActive = analysis.EligiblePages.Count,
|
||||
Suspended = analysis.AffectedPages.Count,
|
||||
Message = $"Downgrade concluído. {analysis.EligiblePages.Count} páginas ativas, {analysis.AffectedPages.Count} suspensas.",
|
||||
Details = analysis.AffectedPages.Select(p => $"{p.DisplayName}: {p.SuspensionReason}").ToList()
|
||||
};
|
||||
|
||||
_logger.LogInformation(
|
||||
"Downgrade automático concluído para usuário {UserId}: {KeptActive} mantidas, {Suspended} suspensas",
|
||||
userId, result.KeptActive, result.Suspended
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Erro no processamento automático de downgrade para usuário {UserId}", userId);
|
||||
return new DowngradeResult
|
||||
{
|
||||
Success = false,
|
||||
Message = $"Erro no processamento: {ex.Message}",
|
||||
Details = new List<string> { ex.Message }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<DowngradeResult> ProcessAutomaticUpgrade(string userId, PlanType newPlan)
|
||||
{
|
||||
try
|
||||
{
|
||||
var pages = await _userPageService.GetUserPagesAsync(userId);
|
||||
var suspendedPages = pages.Where(p => p.Status == PageStatus.SuspendedByPlanLimit).ToList();
|
||||
|
||||
var newMaxPages = newPlan.GetMaxPages();
|
||||
var newMaxLinks = newPlan.GetMaxLinksPerPage();
|
||||
|
||||
var reactivated = 0;
|
||||
|
||||
// Reativar páginas que agora cabem no novo plano
|
||||
foreach (var page in suspendedPages.OrderBy(p => p.CreatedAt).Take(newMaxPages))
|
||||
{
|
||||
// Verificar se a página atende aos critérios de links
|
||||
if (newMaxLinks == -1 || (page.Links?.Count ?? 0) <= newMaxLinks)
|
||||
{
|
||||
page.Status = PageStatus.Active;
|
||||
await _userPageService.UpdatePageAsync(page);
|
||||
reactivated++;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Página {PageName} (ID: {PageId}) reativada por upgrade para {PlanType}",
|
||||
page.DisplayName, page.Id, newPlan
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new DowngradeResult
|
||||
{
|
||||
Success = true,
|
||||
KeptActive = reactivated,
|
||||
Suspended = 0,
|
||||
Message = $"Upgrade concluído. {reactivated} páginas reativadas.",
|
||||
Details = suspendedPages.Take(reactivated).Select(p => $"{p.DisplayName}: Reativada").ToList()
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Erro no processamento automático de upgrade para usuário {UserId}", userId);
|
||||
return new DowngradeResult
|
||||
{
|
||||
Success = false,
|
||||
Message = $"Erro no processamento: {ex.Message}",
|
||||
Details = new List<string> { ex.Message }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsDowngrade(PlanType oldPlan, PlanType newPlan)
|
||||
{
|
||||
return PlanPriority.TryGetValue(oldPlan, out var oldPriority) &&
|
||||
PlanPriority.TryGetValue(newPlan, out var newPriority) &&
|
||||
newPriority < oldPriority;
|
||||
}
|
||||
|
||||
public bool IsUpgrade(PlanType oldPlan, PlanType newPlan)
|
||||
{
|
||||
return PlanPriority.TryGetValue(oldPlan, out var oldPriority) &&
|
||||
PlanPriority.TryGetValue(newPlan, out var newPriority) &&
|
||||
newPriority > oldPriority;
|
||||
}
|
||||
|
||||
private string GetSuspensionReason(UserPage page, PlanType newPlan)
|
||||
{
|
||||
var maxLinks = newPlan.GetMaxLinksPerPage();
|
||||
var currentLinks = page.Links?.Count ?? 0;
|
||||
|
||||
if (maxLinks != -1 && currentLinks > maxLinks)
|
||||
return $"❌ Tem {currentLinks} links (limite: {maxLinks})";
|
||||
|
||||
return "❌ Excesso de páginas (critério: mais recentes são suspensas)";
|
||||
}
|
||||
|
||||
private string GetDetailedSuspensionReason(UserPage page, PlanType newPlan)
|
||||
{
|
||||
var maxLinks = newPlan.GetMaxLinksPerPage();
|
||||
var currentLinks = page.Links?.Count ?? 0;
|
||||
|
||||
if (maxLinks != -1 && currentLinks > maxLinks)
|
||||
return $"Página suspensa: possui {currentLinks} links, mas o plano {newPlan.GetDisplayName()} permite apenas {maxLinks} links por página.";
|
||||
|
||||
return $"Página suspensa: plano {newPlan.GetDisplayName()} permite apenas {newPlan.GetMaxPages()} páginas ativas. Páginas mais recentes foram suspensas automaticamente.";
|
||||
}
|
||||
}
|
||||
32
src/BCards.Web/Services/IDowngradeService.cs
Normal file
32
src/BCards.Web/Services/IDowngradeService.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using BCards.Web.Models;
|
||||
using BCards.Web.ViewModels;
|
||||
|
||||
namespace BCards.Web.Services;
|
||||
|
||||
public interface IDowngradeService
|
||||
{
|
||||
/// <summary>
|
||||
/// Analisa o impacto de um downgrade para um usuário
|
||||
/// </summary>
|
||||
Task<DowngradeAnalysis> AnalyzeDowngradeImpact(string userId, PlanType newPlan);
|
||||
|
||||
/// <summary>
|
||||
/// Processa automaticamente um downgrade, suspendendo páginas necessárias
|
||||
/// </summary>
|
||||
Task<DowngradeResult> ProcessAutomaticDowngrade(string userId, PlanType newPlan);
|
||||
|
||||
/// <summary>
|
||||
/// Reativa páginas suspensas por limite quando há upgrade
|
||||
/// </summary>
|
||||
Task<DowngradeResult> ProcessAutomaticUpgrade(string userId, PlanType newPlan);
|
||||
|
||||
/// <summary>
|
||||
/// Detecta se uma mudança de plano é um downgrade
|
||||
/// </summary>
|
||||
bool IsDowngrade(PlanType oldPlan, PlanType newPlan);
|
||||
|
||||
/// <summary>
|
||||
/// Detecta se uma mudança de plano é um upgrade
|
||||
/// </summary>
|
||||
bool IsUpgrade(PlanType oldPlan, PlanType newPlan);
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
|
||||
#if TESTING
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Claims;
|
||||
@ -82,3 +83,4 @@ namespace BCards.Web.TestSupport
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@ -28,6 +28,14 @@ public class CreatePageViewModel
|
||||
|
||||
public string InstagramUrl { get; set; } = string.Empty;
|
||||
|
||||
public string TiktokUrl { get; set; } = string.Empty;
|
||||
|
||||
public string PinterestUrl { get; set; } = string.Empty;
|
||||
|
||||
public string DiscordUrl { get; set; } = string.Empty;
|
||||
|
||||
public string KawaiUrl { get; set; } = string.Empty;
|
||||
|
||||
public List<CreateLinkViewModel> Links { get; set; } = new();
|
||||
|
||||
public string Slug { get; set; } = string.Empty;
|
||||
|
||||
@ -34,6 +34,14 @@ public class ManagePageViewModel
|
||||
|
||||
public string InstagramUrl { get; set; } = string.Empty;
|
||||
|
||||
public string TiktokUrl { get; set; } = string.Empty;
|
||||
|
||||
public string PinterestUrl { get; set; } = string.Empty;
|
||||
|
||||
public string DiscordUrl { get; set; } = string.Empty;
|
||||
|
||||
public string KawaiUrl { get; set; } = string.Empty;
|
||||
|
||||
public List<ManageLinkViewModel> Links { get; set; } = new();
|
||||
|
||||
// Profile image fields
|
||||
@ -139,5 +147,43 @@ public enum PageStatus
|
||||
PendingModeration = 4, // Aguardando moderação
|
||||
Rejected = 5, // Rejeitada na moderação
|
||||
Creating = 6, // Em desenvolvimento/criação
|
||||
Approved = 7 // Aprovada
|
||||
Approved = 7, // Aprovada
|
||||
SuspendedByPlanLimit = 8 // Suspensa por limite de plano (downgrade)
|
||||
}
|
||||
|
||||
// Modelos para análise de downgrade
|
||||
public class DowngradeAnalysis
|
||||
{
|
||||
public List<PageInfo> EligiblePages { get; set; } = new();
|
||||
public List<PageInfo> AffectedPages { get; set; } = new();
|
||||
public List<string> Issues { get; set; } = new();
|
||||
public bool IsCritical => EligiblePages.Count == 0;
|
||||
public string Summary => $"{EligiblePages.Count} mantidas, {AffectedPages.Count} suspensas";
|
||||
}
|
||||
|
||||
public class PageInfo
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public int LinkCount { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public string SuspensionReason { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class DowngradeResult
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public int KeptActive { get; set; }
|
||||
public int Suspended { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
public List<string> Details { get; set; } = new();
|
||||
}
|
||||
|
||||
public class DowngradeCriteria
|
||||
{
|
||||
public int MaxPages { get; set; }
|
||||
public int MaxLinksPerPage { get; set; }
|
||||
public string MaxLinksDisplay => MaxLinksPerPage == -1 ? "Ilimitado" : MaxLinksPerPage.ToString();
|
||||
public string SelectionCriteria { get; set; } = "Páginas mais antigas têm prioridade";
|
||||
public string LinksCriteria { get; set; } = "Páginas com muitos links são automaticamente suspensas";
|
||||
}
|
||||
@ -249,7 +249,11 @@
|
||||
"facebook",
|
||||
"whatsapp",
|
||||
"twitter",
|
||||
"instagram"
|
||||
"instagram",
|
||||
"tiktok",
|
||||
"pinterest",
|
||||
"discord",
|
||||
"kawai"
|
||||
};
|
||||
var match = myList.FirstOrDefault(stringToCheck =>
|
||||
!string.IsNullOrEmpty(Model.Links[i].Icon) &&
|
||||
@ -280,6 +284,7 @@
|
||||
<span asp-validation-for="Links[i].Url" class="text-danger"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Descrição (opcional)</label>
|
||||
@ -381,10 +386,18 @@
|
||||
var twitter = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("twitter")).FirstOrDefault();
|
||||
var whatsapp = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("whatsapp")).FirstOrDefault();
|
||||
var instagram = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("instagram")).FirstOrDefault();
|
||||
var tiktok = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("tiktok")).FirstOrDefault();
|
||||
var pinterest = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("pinterest")).FirstOrDefault();
|
||||
var discord = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("discord")).FirstOrDefault();
|
||||
var kawai = Model.Links.Where(x => !string.IsNullOrEmpty(x.Icon) && x.Icon.Contains("kawai")).FirstOrDefault();
|
||||
var facebookUrl = facebook !=null ? facebook.Url.Replace("https://facebook.com/","").Replace("https://www.facebook.com/","").Replace("https://fb.com/","") : "";
|
||||
var twitterUrl = twitter !=null ? twitter.Url.Replace("https://x.com/","").Replace("https://twitter.com/","").Replace("https://www.twitter.com/","") : "";
|
||||
var whatsappUrl = whatsapp !=null ? whatsapp.Url.Replace("https://wa.me/","").Replace("whatsapp://","") : "";
|
||||
var instagramUrl = instagram !=null ? instagram.Url.Replace("https://instagram.com/","").Replace("https://www.instagram.com/","") : "";
|
||||
var tiktokUrl = tiktok !=null ? tiktok.Url.Replace("https://tiktok.com/@@","").Replace("https://www.tiktok.com/@@","").Replace("https://vm.tiktok.com/","") : "";
|
||||
var pinterestUrl = pinterest !=null ? pinterest.Url.Replace("https://pinterest.com/","").Replace("https://www.pinterest.com/","").Replace("https://pin.it/","") : "";
|
||||
var discordUrl = discord !=null ? discord.Url.Replace("https://discord.gg/","").Replace("https://discord.com/invite/","") : "";
|
||||
var kawaiUrl = kawai !=null ? kawai.Url.Replace("https://kawai.com/","").Replace("https://www.kawai.com/","") : "";
|
||||
}
|
||||
<!-- Passo 4: Redes Sociais (Opcional) -->
|
||||
<div class="accordion-item">
|
||||
@ -490,6 +503,92 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-lg-6">
|
||||
<!-- TikTok -->
|
||||
<div class="mb-4">
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="enableTiktok">
|
||||
<label class="form-check-label" for="enableTiktok">
|
||||
<i class="fab fa-tiktok me-2"></i>
|
||||
<strong>Conectar TikTok</strong>
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group social-input-group" id="tiktokGroup" style="display: none;">
|
||||
<span class="input-group-text">
|
||||
<i class="fab fa-tiktok me-2"></i>
|
||||
https://tiktok.com/@@
|
||||
</span>
|
||||
<input type="text" class="form-control" id="tiktokUser" placeholder="seu-usuario">
|
||||
</div>
|
||||
<input asp-for="TiktokUrl" type="hidden" value="@(tiktokUrl ?? "")">
|
||||
<span asp-validation-for="TiktokUrl" class="text-danger"></span>
|
||||
</div>
|
||||
|
||||
<!-- Pinterest -->
|
||||
<div class="mb-4">
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="enablePinterest">
|
||||
<label class="form-check-label" for="enablePinterest">
|
||||
<i class="fab fa-pinterest me-2"></i>
|
||||
<strong>Conectar Pinterest</strong>
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group social-input-group" id="pinterestGroup" style="display: none;">
|
||||
<span class="input-group-text">
|
||||
<i class="fab fa-pinterest me-2"></i>
|
||||
https://pinterest.com/
|
||||
</span>
|
||||
<input type="text" class="form-control" id="pinterestUser" placeholder="seu-usuario">
|
||||
</div>
|
||||
<input asp-for="PinterestUrl" type="hidden" value="@(pinterestUrl ?? "")">
|
||||
<span asp-validation-for="PinterestUrl" class="text-danger"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-6">
|
||||
<!-- Discord -->
|
||||
<div class="mb-4">
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="enableDiscord">
|
||||
<label class="form-check-label" for="enableDiscord">
|
||||
<i class="fab fa-discord me-2"></i>
|
||||
<strong>Conectar Discord</strong>
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group social-input-group" id="discordGroup" style="display: none;">
|
||||
<span class="input-group-text">
|
||||
<i class="fab fa-discord me-2"></i>
|
||||
https://discord.gg/
|
||||
</span>
|
||||
<input type="text" class="form-control" id="discordUser" placeholder="codigo-convite">
|
||||
</div>
|
||||
<input asp-for="DiscordUrl" type="hidden" value="@(discordUrl ?? "")">
|
||||
<span asp-validation-for="DiscordUrl" class="text-danger"></span>
|
||||
</div>
|
||||
|
||||
<!-- Kawai -->
|
||||
<div class="mb-4">
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="enableKawai">
|
||||
<label class="form-check-label" for="enableKawai">
|
||||
<i class="fas fa-heart me-2"></i>
|
||||
<strong>Conectar Kawai</strong>
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group social-input-group" id="kawaiGroup" style="display: none;">
|
||||
<span class="input-group-text">
|
||||
<i class="fas fa-heart me-2"></i>
|
||||
https://kawai.com/
|
||||
</span>
|
||||
<input type="text" class="form-control" id="kawaiUser" placeholder="seu-usuario">
|
||||
</div>
|
||||
<input asp-for="KawaiUrl" type="hidden" value="@(kawaiUrl ?? "")">
|
||||
<span asp-validation-for="KawaiUrl" class="text-danger"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between">
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="previousStep(3)">
|
||||
<i class="fas fa-arrow-left me-1"></i> Anterior
|
||||
@ -1602,7 +1701,11 @@
|
||||
{ checkbox: '#enableWhatsApp', hidden: 'input[name="WhatsAppNumber"]' },
|
||||
{ checkbox: '#enableFacebook', hidden: 'input[name="FacebookUrl"]' },
|
||||
{ checkbox: '#enableInstagram', hidden: 'input[name="InstagramUrl"]' },
|
||||
{ checkbox: '#enableTwitter', hidden: 'input[name="TwitterUrl"]' }
|
||||
{ checkbox: '#enableTwitter', hidden: 'input[name="TwitterUrl"]' },
|
||||
{ checkbox: '#enableTiktok', hidden: 'input[name="TiktokUrl"]' },
|
||||
{ checkbox: '#enablePinterest', hidden: 'input[name="PinterestUrl"]' },
|
||||
{ checkbox: '#enableDiscord', hidden: 'input[name="DiscordUrl"]' },
|
||||
{ checkbox: '#enableKawai', hidden: 'input[name="KawaiUrl"]' }
|
||||
];
|
||||
|
||||
socialFields.forEach(field => {
|
||||
@ -1618,7 +1721,11 @@
|
||||
'Facebook': ['https://facebook.com/', 'https://www.facebook.com/', 'https://fb.com/', 'https://www.fb.com/'],
|
||||
'Instagram': ['https://instagram.com/', 'https://www.instagram.com/', 'https://instagr.am/'],
|
||||
'Twitter': ['https://x.com/', 'https://twitter.com/', 'https://www.twitter.com/', 'https://www.x.com/'],
|
||||
'WhatsApp': ['https://wa.me/', 'whatsapp://', 'https://api.whatsapp.com/', 'wa.me/']
|
||||
'WhatsApp': ['https://wa.me/', 'whatsapp://', 'https://api.whatsapp.com/', 'wa.me/'],
|
||||
'Tiktok': ['https://tiktok.com/@@', 'https://www.tiktok.com/@@', 'https://vm.tiktok.com/'],
|
||||
'Pinterest': ['https://pinterest.com/', 'https://www.pinterest.com/', 'https://pin.it/'],
|
||||
'Discord': ['https://discord.gg/', 'https://discord.com/invite/'],
|
||||
'Kawai': ['https://kawai.com/', 'https://www.kawai.com/']
|
||||
};
|
||||
|
||||
const typePrefixes = prefixes[socialType] || [];
|
||||
@ -1644,6 +1751,18 @@
|
||||
|
||||
// Twitter
|
||||
setupSocialField('Twitter', 'TwitterUrl', 'https://x.com/', false);
|
||||
|
||||
// TikTok
|
||||
setupSocialField('Tiktok', 'TiktokUrl', 'https://tiktok.com/@@', false);
|
||||
|
||||
// Pinterest
|
||||
setupSocialField('Pinterest', 'PinterestUrl', 'https://pinterest.com/', false);
|
||||
|
||||
// Discord
|
||||
setupSocialField('Discord', 'DiscordUrl', 'https://discord.gg/', false);
|
||||
|
||||
// Kawai
|
||||
setupSocialField('Kawai', 'KawaiUrl', 'https://kawai.com/', false);
|
||||
}
|
||||
|
||||
function setupSocialField(name, hiddenFieldName, prefix, isWhatsApp) {
|
||||
|
||||
@ -38,6 +38,139 @@
|
||||
@Html.Raw(writer.ToString())
|
||||
}
|
||||
}
|
||||
|
||||
/* QR Code Section Styles */
|
||||
.qrcode-section {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.qrcode-toggle {
|
||||
width: 100%;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 12px;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
color: inherit;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.qrcode-toggle:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.qrcode-toggle i {
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.qrcode-container {
|
||||
margin-top: 1rem;
|
||||
padding: 1.5rem;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
animation: slideDown 0.3s ease;
|
||||
}
|
||||
|
||||
@@keyframes slideDown {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.qrcode-canvas {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin: 0 auto 1rem;
|
||||
padding: 1rem;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
max-width: 250px;
|
||||
}
|
||||
|
||||
.qrcode-canvas > div {
|
||||
display: flex !important;
|
||||
justify-content: center !important;
|
||||
align-items: center !important;
|
||||
}
|
||||
|
||||
.qrcode-canvas img,
|
||||
.qrcode-canvas canvas {
|
||||
display: block !important;
|
||||
margin: 0 auto !important;
|
||||
max-width: 200px !important;
|
||||
max-height: 200px !important;
|
||||
}
|
||||
|
||||
/* Hide duplicate canvas/img if library generates both */
|
||||
.qrcode-canvas img + canvas,
|
||||
.qrcode-canvas canvas + img {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.qrcode-hint {
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.btn-download-qr {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem 1.5rem;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.btn-download-qr:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.btn-download-qr:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
/* Mobile Responsive */
|
||||
@@media (max-width: 576px) {
|
||||
.qrcode-toggle {
|
||||
font-size: 0.9rem;
|
||||
padding: 0.875rem;
|
||||
}
|
||||
|
||||
.qrcode-container {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.qrcode-canvas {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.btn-download-qr {
|
||||
padding: 0.625rem 1.25rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
}
|
||||
|
||||
@ -184,6 +317,23 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- QR Code Section -->
|
||||
<div class="qrcode-section mt-4">
|
||||
<button class="qrcode-toggle" onclick="toggleQRCode()" type="button">
|
||||
<i class="fas fa-qrcode me-2"></i>
|
||||
<span id="qrToggleText">Ocultar QR Code</span>
|
||||
<i class="fas fa-chevron-up ms-auto" id="qrToggleIcon"></i>
|
||||
</button>
|
||||
|
||||
<div class="qrcode-container" id="qrcodeContainer" style="display: block;">
|
||||
<div class="qrcode-canvas" id="qrcode"></div>
|
||||
<p class="qrcode-hint">Escaneie para compartilhar esta página</p>
|
||||
<button class="btn-download-qr" onclick="downloadQR()" type="button">
|
||||
<i class="fas fa-download me-1"></i> Baixar QR Code
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="profile-footer">
|
||||
<div class="footer-promo" onclick="togglePromo(this)">
|
||||
@ -215,6 +365,9 @@
|
||||
</div>
|
||||
|
||||
@section Scripts {
|
||||
<!-- QRCode.js Library - Load FIRST -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
|
||||
|
||||
<script>
|
||||
function recordClick(pageId, linkIndex) {
|
||||
// Detectar se é LivePage ou UserPage
|
||||
@ -276,6 +429,95 @@
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Generate QR Code on page load
|
||||
generateQRCode();
|
||||
});
|
||||
|
||||
// QR Code Functions
|
||||
let qrCodeGenerated = false;
|
||||
|
||||
function toggleQRCode() {
|
||||
const container = document.getElementById('qrcodeContainer');
|
||||
const icon = document.getElementById('qrToggleIcon');
|
||||
const text = document.getElementById('qrToggleText');
|
||||
|
||||
if (container.style.display === 'block') {
|
||||
// Close
|
||||
container.style.display = 'none';
|
||||
icon.classList.remove('fa-chevron-up');
|
||||
icon.classList.add('fa-chevron-down');
|
||||
text.textContent = 'Mostrar QR Code';
|
||||
} else {
|
||||
// Open
|
||||
container.style.display = 'block';
|
||||
icon.classList.remove('fa-chevron-down');
|
||||
icon.classList.add('fa-chevron-up');
|
||||
text.textContent = 'Ocultar QR Code';
|
||||
}
|
||||
}
|
||||
|
||||
function generateQRCode() {
|
||||
if (qrCodeGenerated) {
|
||||
console.log('QR Code already generated, skipping...');
|
||||
return;
|
||||
}
|
||||
|
||||
const qrcodeElement = document.getElementById("qrcode");
|
||||
if (!qrcodeElement) {
|
||||
console.error('QR Code container not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if already has content (double-call prevention)
|
||||
if (qrcodeElement.querySelector('canvas')) {
|
||||
console.log('Canvas already exists, skipping generation');
|
||||
qrCodeGenerated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark as generated BEFORE creating to prevent race conditions
|
||||
qrCodeGenerated = true;
|
||||
|
||||
// Clear any existing content
|
||||
qrcodeElement.innerHTML = '';
|
||||
|
||||
const pageUrl = window.location.href.split('?')[0]; // Remove query params
|
||||
|
||||
try {
|
||||
new QRCode(qrcodeElement, {
|
||||
text: pageUrl,
|
||||
width: 200,
|
||||
height: 200,
|
||||
colorDark: "#000000",
|
||||
colorLight: "#ffffff",
|
||||
correctLevel: QRCode.CorrectLevel.H
|
||||
});
|
||||
console.log('QR Code generated successfully for:', pageUrl);
|
||||
} catch (error) {
|
||||
console.error('Error generating QR Code:', error);
|
||||
qrcodeElement.innerHTML = '<p class="text-danger small">Erro ao gerar QR Code</p>';
|
||||
qrCodeGenerated = false; // Reset on error so it can retry
|
||||
}
|
||||
}
|
||||
|
||||
function downloadQR() {
|
||||
try {
|
||||
const canvas = document.querySelector('#qrcode canvas');
|
||||
if (!canvas) {
|
||||
alert('QR Code não está disponível');
|
||||
return;
|
||||
}
|
||||
|
||||
const url = canvas.toDataURL("image/png");
|
||||
const link = document.createElement('a');
|
||||
link.download = 'qrcode-@(Model.Slug ?? "page").png';
|
||||
link.href = url;
|
||||
link.click();
|
||||
} catch (error) {
|
||||
console.error('Error downloading QR Code:', error);
|
||||
alert('Erro ao baixar QR Code');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user