feat: migrate direct tenant content and learning endpoints

This commit is contained in:
xiong
2026-07-26 17:57:03 +08:00
parent 1d7e09b1f0
commit 91a4162908
18 changed files with 4079 additions and 0 deletions

View File

@@ -198,6 +198,58 @@ public sealed class AssetManagementEndpointTests
Assert.Single(detail.RootElement.GetProperty("issues").EnumerateArray());
}
[Fact]
public async Task Tenant_admin_can_upsert_asset_sign_access_and_query_asset_events()
{
await using var factory = new ApiTestFactory(objectStorageService: new FakeObjectStorageService());
var seed = await SeedAdminAsync(factory);
using var client = factory.CreateClient();
await LoginAsync(client, seed);
var upsertResponse = await client.PutAsJsonAsync(
"/api/tenant-content/assets",
new UpsertAssetDto
{
Title = "管理侧资料",
FileName = "admin.pdf",
AssetType = "pdf",
Visibility = "members",
Provider = "local_dev",
Bucket = "tenant-assets",
ObjectKey = $"{seed.TenantId:N}/admin.pdf",
PreviewObjectKey = $"{seed.TenantId:N}/admin-preview.pdf",
MimeType = "application/pdf",
FileSizeBytes = 512
});
var upsert = await ReadJsonAsync(upsertResponse);
var assetId = upsert.RootElement.GetProperty("item").GetProperty("id").GetGuid();
await factory.SeedAsync(new ContentAssetSecurityScanEvent
{
TenantId = seed.TenantId,
AssetId = assetId,
Provider = "local",
ScanStatus = AssetSecurityScanStatus.Passed,
RiskLevel = AssetSecurityRiskLevel.None
});
var downloadResponse = await client.PostAsJsonAsync(
"/api/tenant-content/assets/sign-download",
new AssetAccessSignDto { AssetId = assetId, ExpiresInSeconds = 120 });
var previewResponse = await client.PostAsJsonAsync(
"/api/tenant-content/assets/sign-preview",
new AssetAccessSignDto { AssetId = assetId, ExpiresInSeconds = 120 });
var accessEventsResponse = await client.GetAsync($"/api/tenant-content/assets/access-events?assetId={assetId}");
var scanEventsResponse = await client.GetAsync($"/api/tenant-content/assets/security-scan-events?assetId={assetId}");
var accessEvents = await ReadJsonAsync(accessEventsResponse);
var scanEvents = await ReadJsonAsync(scanEventsResponse);
Assert.Equal(HttpStatusCode.OK, upsertResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, downloadResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, previewResponse.StatusCode);
Assert.Equal(2, accessEvents.RootElement.GetProperty("items").GetArrayLength());
Assert.Single(scanEvents.RootElement.GetProperty("items").EnumerateArray());
}
private static async Task<(Guid TenantId, Guid UserId, string Phone)> SeedAdminAsync(ApiTestFactory factory)
{
var tenantId = Guid.NewGuid();

View File

@@ -0,0 +1,250 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Tiku.Api.Contracts;
using Tiku.Domain.Common;
using Tiku.Domain.Content;
using Tiku.Domain.Identity;
using Tiku.Domain.QuestionBanks;
using Tiku.Domain.Tenancy;
using Tiku.Infrastructure.Auth;
using Tiku.Infrastructure.Persistence;
namespace Tiku.IntegrationTests.Api;
public sealed class DirectContentEndpointTests
{
[Fact]
public async Task Tenant_admin_can_create_question_and_sync_primary_collection()
{
await using var factory = new ApiTestFactory();
var seed = await SeedAdminAsync(factory);
var collectionId = Guid.NewGuid();
await factory.SeedAsync(new QuestionCollection
{
Id = collectionId,
TenantId = seed.TenantId,
Name = "直接迁移题集",
CollectionType = QuestionCollectionType.Manual,
SourceType = QuestionCollectionSourceType.ManualQuestions
});
using var client = factory.CreateClient();
await LoginAsync(client, seed);
using var response = await client.PostAsJsonAsync(
"/api/tenant-content/questions",
new DirectQuestionWriteDto
{
PrimaryCollectionId = collectionId,
Type = "choice",
Content = "1 + 1 = ?",
Options = JsonSerializer.SerializeToElement(new[] { "1", "2" }),
CorrectOptionIndex = 1,
Tags = JsonSerializer.SerializeToElement(new[] { "math" })
});
var json = await ReadJsonAsync(response);
var questionId = json.RootElement.GetProperty("item").GetProperty("id").GetGuid();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(collectionId, json.RootElement.GetProperty("item").GetProperty("primaryCollectionId").GetGuid());
using var scope = factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
Assert.Contains(dbContext.QuestionCollectionItems, item => item.CollectionId == collectionId && item.QuestionId == questionId);
Assert.Equal(1, dbContext.QuestionCollections.Single(item => item.Id == collectionId).QuestionCount);
}
[Fact]
public async Task Tenant_admin_can_upsert_vocabulary_handbook_video_and_operations_content()
{
await using var factory = new ApiTestFactory();
var seed = await SeedAdminAsync(factory);
using var client = factory.CreateClient();
await LoginAsync(client, seed);
var unitResponse = await client.PutAsJsonAsync(
"/api/tenant-content/vocabulary-units",
new DirectVocabularyUnitDto { Name = "Unit 1", WordCount = 1 });
var unitJson = await ReadJsonAsync(unitResponse);
var unitId = unitJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();
var wordResponse = await client.PutAsJsonAsync(
"/api/tenant-content/vocabulary-words",
new DirectVocabularyWordDto { UnitId = unitId, Word = "scale", Meaning = "规模" });
var subjectResponse = await client.PutAsJsonAsync(
"/api/tenant-content/handbook-subjects",
new DirectHandbookSubjectDto { Name = "文化常识", Type = "Common" });
var subjectJson = await ReadJsonAsync(subjectResponse);
var subjectId = subjectJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();
var chapterResponse = await client.PutAsJsonAsync(
"/api/tenant-content/handbook-chapters",
new DirectHandbookChapterDto { SubjectId = subjectId, Name = "第一章" });
var chapterJson = await ReadJsonAsync(chapterResponse);
var chapterId = chapterJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();
var entryResponse = await client.PutAsJsonAsync(
"/api/tenant-content/handbook-entries",
new DirectHandbookEntryDto { ChapterId = chapterId, Title = "知识点", Content = "正文" });
var videoResponse = await client.PutAsJsonAsync(
"/api/tenant-content/videos",
new DirectVideoDto { Title = "解析视频", VideoUrl = "https://example.test/video.mp4" });
var bannerResponse = await client.PutAsJsonAsync(
"/api/tenant-content/operations/banners",
new DirectOperationContentDto { Title = "开屏", Content = "欢迎", IsActive = true });
using var bannerListResponse = await client.GetAsync("/api/tenant-content/operations/banners");
var bannerListJson = await ReadJsonAsync(bannerListResponse);
Assert.Equal(HttpStatusCode.OK, unitResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, wordResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, subjectResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, chapterResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, entryResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, videoResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, bannerResponse.StatusCode);
Assert.Single(bannerListJson.RootElement.GetProperty("items").EnumerateArray());
}
[Fact]
public async Task Tenant_admin_can_bind_question_video_and_run_import_skeleton()
{
await using var factory = new ApiTestFactory();
var seed = await SeedAdminAsync(factory);
using var client = factory.CreateClient();
await LoginAsync(client, seed);
var questionResponse = await client.PostAsJsonAsync(
"/api/tenant-content/questions",
new DirectQuestionWriteDto { Type = "choice", Content = "题目" });
var questionJson = await ReadJsonAsync(questionResponse);
var questionId = questionJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();
var videoResponse = await client.PutAsJsonAsync(
"/api/tenant-content/videos",
new DirectVideoDto { Title = "视频" });
var videoJson = await ReadJsonAsync(videoResponse);
var videoId = videoJson.RootElement.GetProperty("item").GetProperty("id").GetGuid();
var bindResponse = await client.PostAsJsonAsync(
"/api/tenant-content/question-videos",
new DirectQuestionVideoDto { QuestionId = questionId, VideoId = videoId });
var previewResponse = await client.PostAsJsonAsync(
"/api/tenant-content/imports/preview/questions",
new DirectImportDto
{
Items =
[
JsonSerializer.SerializeToElement(new { type = "choice", content = "导入预览题" })
]
});
var previewJson = await ReadJsonAsync(previewResponse);
var previewJobId = previewJson.RootElement.GetProperty("job").GetProperty("id").GetGuid();
var executeResponse = await client.PostAsJsonAsync(
"/api/tenant-content/imports/questions",
new DirectImportDto
{
Items =
[
JsonSerializer.SerializeToElement(new { type = "choice", content = "导入执行题" })
]
});
var executeJson = await ReadJsonAsync(executeResponse);
var executeJobId = executeJson.RootElement.GetProperty("job").GetProperty("id").GetGuid();
var postCheckResponse = await client.PostAsJsonAsync(
"/api/tenant-content/imports/post-check",
new DirectImportJobDto { JobId = executeJobId });
Assert.Equal(HttpStatusCode.OK, bindResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, previewResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, executeResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, postCheckResponse.StatusCode);
Assert.NotEqual(Guid.Empty, previewJobId);
using var scope = factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
Assert.True(dbContext.ContentImportJobs.Any(item => item.Id == executeJobId && item.InsertedCount == 1));
Assert.True(dbContext.Questions.Count(item => item.TenantId == seed.TenantId) >= 2);
Assert.True(dbContext.Questions.Single(item => item.Id == questionId).HasVideoExplanation);
}
private static async Task<(Guid TenantId, Guid UserId, string Phone)> SeedAdminAsync(ApiTestFactory factory)
{
var tenantId = Guid.NewGuid();
var userId = Guid.NewGuid();
var phone = $"137{Random.Shared.Next(10000000, 99999999)}";
var passwordHash = new PasswordHasher().Hash("passw0rd!");
await factory.SeedAsync(
new Tenant
{
Id = tenantId,
Slug = tenantId.ToString("N"),
Name = "Test Tenant",
Status = TenantStatus.Active,
Metadata = JsonDefaults.Object()
},
new User
{
Id = userId,
Phone = phone,
Name = "Tenant Admin"
},
new TenantMembership
{
TenantId = tenantId,
UserId = userId,
Role = TenantRole.TenantAdmin,
Status = MembershipStatus.Active
},
new UserIdentity
{
UserId = userId,
Provider = "password",
ProviderSubject = phone,
Phone = phone,
SecretPayload = CreateSecretPayload(passwordHash)
});
return (tenantId, userId, phone);
}
private static async Task LoginAsync(
HttpClient client,
(Guid TenantId, Guid UserId, string Phone) seed)
{
var loginResponse = await client.PostAsJsonAsync(
"/api/auth/login/password",
new PasswordLoginDto
{
TenantId = seed.TenantId,
Phone = seed.Phone,
Password = "passw0rd!"
});
var loginJson = await ReadJsonAsync(loginResponse);
var accessToken = loginJson.RootElement
.GetProperty("tokens")
.GetProperty("accessToken")
.GetString();
client.DefaultRequestHeaders.Authorization = new("Bearer", accessToken);
}
private static async Task<JsonDocument> ReadJsonAsync(HttpResponseMessage response)
{
var stream = await response.Content.ReadAsStreamAsync();
return await JsonDocument.ParseAsync(stream);
}
private static JsonElement CreateSecretPayload(string passwordHash)
{
using var document = JsonDocument.Parse(
$$"""{"passwordHash":{{JsonSerializer.Serialize(passwordHash)}}}""");
return document.RootElement.Clone();
}
}

View File

@@ -297,6 +297,78 @@ public sealed class LearningEndpointTests
Assert.Equal("重点", item.GetProperty("note").GetString());
}
[Fact]
public async Task Learning_stats_plans_leaderboard_and_word_review_are_available()
{
await using var factory = new ApiTestFactory();
var seed = await SeedLearningUserAsync(factory);
var questionId = Guid.NewGuid();
var wordId = Guid.NewGuid();
await factory.SeedAsync(
new Question
{
Id = questionId,
TenantId = seed.TenantId,
Type = "choice",
Status = QuestionStatus.Published
},
new VocabularyWord
{
Id = wordId,
TenantId = seed.TenantId,
Word = "review",
IsActive = true
});
using var client = factory.CreateClient();
await LoginAsync(client, seed);
await client.PostAsJsonAsync(
"/api/learning/answers",
new SubmitAnswerDto
{
QuestionId = questionId,
SelectedOptions = ["A"],
SelfJudgedCorrect = false
});
await client.PostAsJsonAsync(
"/api/learning/vocabulary/progress",
new WordProgressDto
{
WordId = wordId,
Status = "learning",
WrongDelta = 1,
NextReviewAt = DateTimeOffset.UtcNow.AddMinutes(-1)
});
var statsResponse = await client.GetAsync("/api/learning/stats");
var trendResponse = await client.GetAsync("/api/learning/trend?limit=7");
var leaderboardResponse = await client.GetAsync("/api/learning/leaderboard?limit=10");
var wrongPlanResponse = await client.GetAsync("/api/learning/wrong-questions/review-plan");
var wordPlanResponse = await client.GetAsync("/api/learning/vocabulary/review-plan");
var reviewResponse = await client.PostAsJsonAsync(
"/api/learning/vocabulary/review",
new WordReviewDto { WordId = wordId, Result = "correct" });
var wordStatsResponse = await client.GetAsync("/api/learning/vocabulary/stats");
var stats = await ReadJsonAsync(statsResponse);
var trend = await ReadItemsAsync(trendResponse);
var leaderboard = await ReadJsonAsync(leaderboardResponse);
var wrongPlan = await ReadJsonAsync(wrongPlanResponse);
var wordPlan = await ReadJsonAsync(wordPlanResponse);
var review = await ReadJsonAsync(reviewResponse);
var wordStats = await ReadJsonAsync(wordStatsResponse);
Assert.Equal(HttpStatusCode.OK, statsResponse.StatusCode);
Assert.Equal(1, stats.RootElement.GetProperty("answerCount").GetInt32());
Assert.Equal(1, stats.RootElement.GetProperty("wrongCount").GetInt32());
Assert.NotEmpty(trend);
Assert.Equal(seed.UserId, Assert.Single(leaderboard.RootElement.GetProperty("items").EnumerateArray()).GetProperty("userId").GetGuid());
Assert.Single(wrongPlan.RootElement.GetProperty("items").EnumerateArray());
Assert.Single(wordPlan.RootElement.GetProperty("items").EnumerateArray());
Assert.Equal(1, review.RootElement.GetProperty("correctCount").GetInt32());
Assert.Equal(1, wordStats.RootElement.GetProperty("total").GetInt32());
}
private static async Task<(Guid TenantId, Guid UserId, string Phone)> SeedLearningUserAsync(
ApiTestFactory factory)
{