Thomas Fransolet af6b5b76ef Self-service onboarding (Stripe + Resend) + Postgres v3 schema (pgvector, media, visitor questions)
75 fichiers, ~1 mois de travail depuis f222861 (17/07). Contenu :

Onboarding self-service — jamais exécuté de bout en bout
  OnboardingController, StripeWebhookController, StripeService, ResendEmailService
  + IEmailService (10 templates), EmailTemplates/, TrialLifecycleService (Hangfire),
  PasswordTokenHelper, SlugHelper, 5 DTOs. Essai 14 j, Stripe customer/Checkout/Tax,
  mot de passe oublié + invitation user, plafond IA d'essai.

Schéma Postgres v3 — passe pendant que la base est vide
  ContentEmbedding + index HNSW (vector_cosine_ops), IEmbeddingService +
  GoogleEmbeddingService (gemini-embedding-001, 768 dims), Deployment/Dockerfile.postgres
  (postgis 3.4.3 + pgvector 0.8.6, épinglé par digest — un tag mobile rejouerait le
  warning de collation glibc). Colonnes Resource : StoragePath, FileName,
  IncludeInAiKnowledge, AiIndexStatus + nouveaux ResourceType ajoutés EN FIN d'enum.

Guide IA
  Champs Guide* sur Instance + InstanceDTO, AssistantService lit la configuration client
  dans les 4 blocs de prompt (ton codé en dur retiré, règle hors-sujet ajoutée aux deux
  variantes qui n'en avaient pas), IHttpClientFactory à la place des new HttpClient().
  Table VisitorQuestion + ConversationId sur AiChatRequest.

Stats
  Rétention unifiée à 13 mois (instances ET plans), VisitEventPurgeService.

Nettoyage
  IsStepLocked / IsHiddenInitially / FactContent supprimés de GuidedStep — IsStepLocked
  rendait une étape définitivement infranchissable même après réussite.
  SectionMap allégé (-57 lignes).

Tests
  SectionParcoursControllerTests, FakeConfiguration, FakeEmailService.
  ContentEmbedding a cassé 116 tests sur 124 (EF InMemory ne connaît pas Vector) :
  l'entité est exclue quand le provider n'est pas Npgsql. Conséquence assumée —
  le vector store n'est couvert par aucun test. dotnet test 124/124.

10 migrations EF. Base locale à jour, dotnet build 0 erreur.
Rien n'est en prod : la bascule Mongo → Postgres est décrite dans DOCS/STATUS.md §1quinquies.

⚠️ appsettings.json contient les clés Stripe (test) et Resend (prod) en clair — à rotationner.
2026-08-09 22:11:48 +02:00

209 lines
8.3 KiB
C#

using ManagerService.Controllers;
using ManagerService.Data;
using ManagerService.DTOs;
using ManagerService.Services;
using ManagerService.Tests.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace ManagerService.Tests.Controllers
{
public class AiControllerTests
{
private static readonly AiChatResponse FakeResponse = new AiChatResponse { Reply = "OK", TokensUsed = 42 };
// Chat vérifie les droits de l'appelant (IsSuperAdmin / instance du token) :
// sans utilisateur, User est null et le contrôleur renvoie un 500.
private AiController BuildController(MyInfoMateDbContext db, Mock<IAssistantService>? mockService = null,
string callerRole = Permissions.SuperAdmin, string callerInstanceId = "i1")
{
mockService ??= new Mock<IAssistantService>();
mockService
.Setup(s => s.ChatAsync(It.IsAny<AiChatRequest>()))
.ReturnsAsync(FakeResponse);
var controller = new AiController(mockService.Object, db, NullLogger<AiController>.Instance);
FakeUser.SetUser(controller, FakeUser.Create(callerRole, callerInstanceId));
return controller;
}
private static AiChatRequest MakeRequest(string instanceId, AppType appType = AppType.Tablet) =>
new AiChatRequest { InstanceId = instanceId, AppType = appType, Message = "Bonjour" };
// ── FORBID CASES ─────────────────────────────────────────────────────
[Fact]
public async Task Chat_InstanceNotFound_ReturnsForbid()
{
using var db = DbContextFactory.Create();
var result = await BuildController(db).Chat(MakeRequest("unknown"));
Assert.IsType<ForbidResult>(result);
}
[Fact]
public async Task Chat_InstanceAssistantDisabled_ReturnsForbid()
{
using var db = DbContextFactory.Create();
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = false, DateCreation = DateTime.UtcNow
});
db.ApplicationInstances.Add(new ApplicationInstance
{
Id = "ai1", InstanceId = "i1", AppType = AppType.Tablet, IsAssistant = true,
Languages = new List<string>()
});
db.SaveChanges();
var result = await BuildController(db).Chat(MakeRequest("i1"));
Assert.IsType<ForbidResult>(result);
}
[Fact]
public async Task Chat_AppInstanceAssistantDisabled_ReturnsForbid()
{
using var db = DbContextFactory.Create();
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = true, DateCreation = DateTime.UtcNow
});
db.ApplicationInstances.Add(new ApplicationInstance
{
Id = "ai1", InstanceId = "i1", AppType = AppType.Tablet, IsAssistant = false,
Languages = new List<string>()
});
db.SaveChanges();
var result = await BuildController(db).Chat(MakeRequest("i1"));
Assert.IsType<ForbidResult>(result);
}
[Fact]
public async Task Chat_NoAppInstance_ReturnsForbid()
{
using var db = DbContextFactory.Create();
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = true, DateCreation = DateTime.UtcNow
});
db.SaveChanges();
var result = await BuildController(db).Chat(MakeRequest("i1"));
Assert.IsType<ForbidResult>(result);
}
// ── QUOTA COUNTER ────────────────────────────────────────────────────
[Fact]
public async Task Chat_FirstRequestOfMonth_ResetsCounterAndAddsTokensUsed()
{
using var db = DbContextFactory.Create();
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = true, DateCreation = DateTime.UtcNow,
AiTokensThisMonth = 99, AiUsageMonthKey = "2020-01"
});
db.ApplicationInstances.Add(new ApplicationInstance
{
Id = "ai1", InstanceId = "i1", AppType = AppType.Tablet, IsAssistant = true,
Languages = new List<string>()
});
db.SaveChanges();
await BuildController(db).Chat(MakeRequest("i1"));
var inst = db.Instances.First();
Assert.Equal(42, inst.AiTokensThisMonth);
Assert.Equal(DateTime.UtcNow.ToString("yyyy-MM"), inst.AiUsageMonthKey);
}
[Fact]
public async Task Chat_SameMonth_AddsTokensUsedToCounter()
{
using var db = DbContextFactory.Create();
var monthKey = DateTime.UtcNow.ToString("yyyy-MM");
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = true, DateCreation = DateTime.UtcNow,
AiTokensThisMonth = 3, AiUsageMonthKey = monthKey
});
db.ApplicationInstances.Add(new ApplicationInstance
{
Id = "ai1", InstanceId = "i1", AppType = AppType.Tablet, IsAssistant = true,
Languages = new List<string>()
});
db.SaveChanges();
await BuildController(db).Chat(MakeRequest("i1"));
Assert.Equal(45, db.Instances.First().AiTokensThisMonth);
}
[Fact]
public async Task Chat_QuotaAlreadyReached_ReturnsTooManyRequestsWithoutCallingAssistantService()
{
using var db = DbContextFactory.Create();
var monthKey = DateTime.UtcNow.ToString("yyyy-MM");
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = true, DateCreation = DateTime.UtcNow,
AiTokensThisMonth = 100, AiTokensPerMonth = 100, AiUsageMonthKey = monthKey
});
db.ApplicationInstances.Add(new ApplicationInstance
{
Id = "ai1", InstanceId = "i1", AppType = AppType.Tablet, IsAssistant = true,
Languages = new List<string>()
});
db.SaveChanges();
var mockService = new Mock<IAssistantService>();
mockService.Setup(s => s.ChatAsync(It.IsAny<AiChatRequest>())).ReturnsAsync(FakeResponse);
var result = await BuildController(db, mockService).Chat(MakeRequest("i1"));
var status = Assert.IsType<ObjectResult>(result);
Assert.Equal(429, status.StatusCode);
mockService.Verify(s => s.ChatAsync(It.IsAny<AiChatRequest>()), Times.Never);
}
// ── NOMINAL ──────────────────────────────────────────────────────────
[Fact]
public async Task Chat_Success_CallsAssistantServiceAndReturns200()
{
using var db = DbContextFactory.Create();
var mockService = new Mock<IAssistantService>();
mockService.Setup(s => s.ChatAsync(It.IsAny<AiChatRequest>())).ReturnsAsync(FakeResponse);
db.Instances.Add(new Instance
{
Id = "i1", Name = "Musée", IsAssistant = true, DateCreation = DateTime.UtcNow,
AiUsageMonthKey = DateTime.UtcNow.ToString("yyyy-MM")
});
db.ApplicationInstances.Add(new ApplicationInstance
{
Id = "ai1", InstanceId = "i1", AppType = AppType.Tablet, IsAssistant = true,
Languages = new List<string>()
});
db.SaveChanges();
var result = await BuildController(db, mockService).Chat(MakeRequest("i1"));
var ok = Assert.IsType<OkObjectResult>(result);
Assert.Equal(FakeResponse, ok.Value);
mockService.Verify(s => s.ChatAsync(It.IsAny<AiChatRequest>()), Times.Once);
}
}
}