feat(templates): add service language template management
Add normalized service and template catalogs, scoped administration, migration, validation, and regression coverage. Ref: IT-1601
This commit is contained in:
@@ -3,30 +3,12 @@ namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
public sealed class AdminTemplatesIndexViewTests
|
||||
{
|
||||
[Fact]
|
||||
public void CreateAndEditLinks_UseExplicitFilterQueryInterpolation()
|
||||
public void CreateAndEditLinks_KeepTheirServiceAndKeyFilter()
|
||||
{
|
||||
string view = File.ReadAllText(FindIndexView());
|
||||
|
||||
Assert.Contains("/admin/templates/create@(filterQuery)", view);
|
||||
Assert.Contains("@t.LanguageCode@(filterQuery)", view);
|
||||
Assert.DoesNotContain("create@filterQuery", view);
|
||||
Assert.DoesNotContain("LanguageCode@filterQuery", view);
|
||||
}
|
||||
|
||||
private static string FindIndexView()
|
||||
{
|
||||
DirectoryInfo? directory = new(AppContext.BaseDirectory);
|
||||
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "HrynCo.NotificationService.slnx")))
|
||||
{
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
Assert.NotNull(directory);
|
||||
return Path.Combine(
|
||||
directory.FullName,
|
||||
"HrynCo.NotificationService.Web",
|
||||
"Views",
|
||||
"AdminTemplates",
|
||||
"Index.cshtml");
|
||||
string view = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "TestViews", "Index.cshtml"));
|
||||
Assert.Contains("asp-route-serviceId=\"@serviceId\"", view);
|
||||
Assert.Contains("asp-route-keyFilter=\"@keyFilter\"", view);
|
||||
Assert.Contains("new { serviceId, definitionId = template.Id, keyFilter }", view);
|
||||
Assert.DoesNotContain("/admin/templates", view);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class EditorLayoutTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task ServiceAndTemplateEditorsRenderOneBreadcrumbBeforeTheCard_IncludingValidationErrors()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
using var scope = app.Services.CreateScope();
|
||||
var service = (await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().GetAllAsync()).Single();
|
||||
var definition = new EmailTemplateDefinition { ServiceName = service.Name, Key = "Layout" };
|
||||
await scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>().SaveDefinitionAsync(definition, true);
|
||||
var root = $"/admin/services/{service.Id}";
|
||||
var editors = new[]
|
||||
{
|
||||
(Url: "/admin/services/create", Title: "Create Service", Form: "serviceForm"),
|
||||
(Url: root + "/edit", Title: "Edit Service", Form: "serviceForm"),
|
||||
(Url: root + "/templates/create", Title: "Create Email Template", Form: "templateForm"),
|
||||
(Url: root + "/templates/" + definition.Id, Title: "Edit Email Template", Form: "templateForm")
|
||||
};
|
||||
foreach (var editor in editors)
|
||||
AssertEditorLayout(await client.GetStringAsync(editor.Url), editor.Title, editor.Form);
|
||||
var fields = TemplateEditorTestFields.Read(await client.GetStringAsync(root + "/templates/create"));
|
||||
fields["Key"] = "InvalidDraft";
|
||||
fields["VariablesJson"] = "{invalid";
|
||||
var errorHtml = await (await client.PostAsync(root + "/templates/save", new FormUrlEncodedContent(fields))).Content.ReadAsStringAsync();
|
||||
Assert.Contains("Invalid variables JSON", errorHtml);
|
||||
AssertEditorLayout(errorHtml, "Create Email Template", "templateForm");
|
||||
Assert.Contains("<dl class=\"template-service-context\">", errorHtml);
|
||||
Assert.Contains("<dt>Service</dt>", errorHtml);
|
||||
Assert.Contains("<dd>TestService</dd>", errorHtml);
|
||||
Assert.DoesNotContain("form-control-plaintext", errorHtml);
|
||||
Assert.Equal(service.Name, TemplateEditorTestFields.Read(errorHtml)["ServiceName"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChannelEditorWorksWithoutTheOptionalBreadcrumbSection()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
var html = await client.GetStringAsync("/admin/channels/create");
|
||||
Assert.Contains("<h1 class=\"editor-card-title\">", html);
|
||||
Assert.Contains("<span>Create Channel</span>", html);
|
||||
Assert.Contains("id=\"channelForm\"", html);
|
||||
Assert.DoesNotContain("aria-label=\"Breadcrumb\"", html);
|
||||
}
|
||||
|
||||
private static void AssertEditorLayout(string html, string title, string form)
|
||||
{
|
||||
Assert.Single(Regex.Matches(html, "aria-label=\"Breadcrumb\""));
|
||||
var breadcrumb = html.IndexOf("<nav aria-label=\"Breadcrumb\"", StringComparison.Ordinal);
|
||||
var card = html.IndexOf("<div class=\"card editor-card\">", StringComparison.Ordinal);
|
||||
Assert.True(breadcrumb >= 0 && breadcrumb < card);
|
||||
Assert.Single(Regex.Matches(html, "<h1 class=\"editor-card-title\">"));
|
||||
Assert.Contains("aria-hidden=\"true\"", html);
|
||||
Assert.Contains("<span>" + title + "</span>", html);
|
||||
Assert.Contains("id=\"" + form + "\"", html);
|
||||
Assert.Contains("aria-current=\"page\"", html);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class EmailTemplateApiTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task LegacyApi_CreatesReadsUpdatesAndDeletesLanguageVersions_WithoutContractDivergence()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
var created = await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
Assert.Equal(HttpStatusCode.Created, created.StatusCode);
|
||||
var originalId = (await created.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("data").GetGuid();
|
||||
Assert.Equal(HttpStatusCode.Created, (await client.PostAsJsonAsync("/api/v1/email-templates", Content("uk"))).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await client.PostAsJsonAsync("/api/v1/email-templates", Content("de", "Other"))).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await client.PutAsJsonAsync("/api/v1/email-templates/TestService/Welcome/en", Content("en", "Other"))).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.PutAsJsonAsync("/api/v1/email-templates/TestService/Welcome/uk", Content("uk", subject: "Updated uk"))).StatusCode);
|
||||
var all = await client.GetFromJsonAsync<JsonElement>("/api/v1/email-templates?serviceName=TestService&key=Welcome");
|
||||
Assert.Equal(2, all.GetProperty("data").GetArrayLength());
|
||||
var en = await ReadAsync(client, "en");
|
||||
Assert.Equal(originalId, en.GetProperty("id").GetGuid());
|
||||
Assert.Equal("Subject en", en.GetProperty("subject").GetString());
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync("/api/v1/email-templates/TestService/Welcome/uk")).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync("/api/v1/email-templates/TestService/Welcome/en")).StatusCode);
|
||||
Assert.Contains("data-state=\"missing\"", await client.GetStringAsync("/admin/templates?serviceName=TestService"));
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/api/v1/email-templates/TestService/Welcome/de")).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentLegacyCreates_OnlyPersistOneLanguage()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
var responses = await Task.WhenAll(
|
||||
client.PostAsJsonAsync("/api/v1/email-templates", Content("uk")),
|
||||
client.PostAsJsonAsync("/api/v1/email-templates", Content("uk")));
|
||||
Assert.Equal(1, responses.Count(r => r.StatusCode == HttpStatusCode.Created));
|
||||
Assert.Equal(1, responses.Count(r => r.StatusCode == HttpStatusCode.Conflict));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GroupEditor_SharedContractIsSavedForAllLanguages_AndPreservesContentIdsAndFilters()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient(new() { AllowAutoRedirect = false });
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("uk"));
|
||||
var originalId = (await ReadAsync(client, "uk")).GetProperty("id").GetGuid();
|
||||
var fields = await EditorFieldsAsync(client);
|
||||
fields["VariablesJson"] = """[{"name":"Shared","required":true}]""";
|
||||
fields["KeyFilter"] = "Welcome";
|
||||
fields["Languages[0].Subject"] = "Edited English";
|
||||
var response = await client.PostAsync(SaveUrl(fields), new FormUrlEncodedContent(fields));
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal($"/admin/services/{fields["ServiceId"]}?key=Welcome", response.Headers.Location!.OriginalString);
|
||||
var uk = await ReadAsync(client, "uk");
|
||||
Assert.Equal(originalId, uk.GetProperty("id").GetGuid());
|
||||
Assert.Equal("Subject uk", uk.GetProperty("subject").GetString());
|
||||
Assert.Equal("Shared", uk.GetProperty("variables")[0].GetProperty("name").GetString());
|
||||
Assert.Equal("Edited English", (await ReadAsync(client, "en")).GetProperty("subject").GetString());
|
||||
var html = await client.GetStringAsync($"/admin/services/{fields["ServiceId"]}?key=Welcome");
|
||||
Assert.Single(Regex.Matches(html, "<td>Welcome</td>"));
|
||||
Assert.Contains("data-language-code=\"en\" data-state=\"present\"", html);
|
||||
Assert.Contains("data-language-code=\"uk\" data-state=\"present\"", html);
|
||||
Assert.Contains("keyFilter=Welcome", html);
|
||||
Assert.DoesNotContain("@filterQuery", html);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{broken", "Invalid variables JSON")]
|
||||
[InlineData("null", "Variables must be a JSON array")]
|
||||
[InlineData("[{\"name\":\"Name\",\"required\":true},{\"name\":\"Name\",\"required\":false}]", "Variable names must be unique")]
|
||||
public async Task InvalidSharedContract_KeepsEnteredValuesAndPersistsNothing(string json, string error)
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("uk"));
|
||||
var fields = await EditorFieldsAsync(client);
|
||||
fields["VariablesJson"] = json;
|
||||
fields["Languages[1].Subject"] = "Unsaved Ukrainian";
|
||||
fields["ActiveLanguageIndex"] = "1";
|
||||
var response = await client.PostAsync(SaveUrl(fields), new FormUrlEncodedContent(fields));
|
||||
var html = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains(error, html);
|
||||
Assert.Contains("Unsaved Ukrainian", html);
|
||||
Assert.Contains("name=\"ActiveLanguageIndex\" value=\"1\"", html);
|
||||
Assert.Equal("Subject uk", (await ReadAsync(client, "uk")).GetProperty("subject").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DuplicateLanguageIncompleteContentAndStaleSave_AreRejectedAtomically()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("uk"));
|
||||
var fields = await EditorFieldsAsync(client);
|
||||
fields["Languages[1].LanguageCode"] = "en";
|
||||
Assert.Contains("Language codes must be unique", await PostEditorAsync(client, fields));
|
||||
fields["Languages[1].LanguageCode"] = "uk";
|
||||
fields["Languages[1].TextBody"] = "";
|
||||
Assert.Contains("TextBody field is required", await PostEditorAsync(client, fields));
|
||||
fields["Languages[1].TextBody"] = "Restored text";
|
||||
await client.PutAsJsonAsync("/api/v1/email-templates/TestService/Welcome/en", Content("en", subject: "Concurrent change"));
|
||||
Assert.Contains("changed after you opened it", await PostEditorAsync(client, fields));
|
||||
Assert.Equal("Concurrent change", (await ReadAsync(client, "en")).GetProperty("subject").GetString());
|
||||
Assert.Equal("Subject uk", (await ReadAsync(client, "uk")).GetProperty("subject").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GroupEditor_RemovesOneLanguageAndAddsAnother_WithoutChangingRemainingLanguage()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient(new() { AllowAutoRedirect = false });
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("uk"));
|
||||
var fields = await EditorFieldsAsync(client);
|
||||
fields["Languages[1].Subject"] = "";
|
||||
fields["Languages[1].HtmlBody"] = "";
|
||||
fields["Languages[1].TextBody"] = "";
|
||||
AddLanguageFields(fields, 2, "de");
|
||||
fields["Languages[2].Subject"] = "German";
|
||||
Assert.Equal(HttpStatusCode.Redirect, (await client.PostAsync(SaveUrl(fields), new FormUrlEncodedContent(fields))).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/api/v1/email-templates/TestService/Welcome/uk")).StatusCode);
|
||||
Assert.Equal("Subject en", (await ReadAsync(client, "en")).GetProperty("subject").GetString());
|
||||
Assert.Equal("German", (await ReadAsync(client, "de")).GetProperty("subject").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedSave_ShowsActionableErrorAndKeepsEnteredValues()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var failingApp = app.WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
|
||||
services.AddScoped<IEmailTemplateDefinitionRepository, FailingEmailTemplateDefinitionRepository>()));
|
||||
using var client = failingApp.CreateClient();
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("en"));
|
||||
await client.PostAsJsonAsync("/api/v1/email-templates", Content("uk"));
|
||||
var fields = await EditorFieldsAsync(client);
|
||||
fields["Languages[1].Subject"] = "Unsaved after failure";
|
||||
var html = await PostEditorAsync(client, fields);
|
||||
Assert.Contains("Could not save the template", html);
|
||||
Assert.Contains("Unsaved after failure", html);
|
||||
Assert.Equal("Subject uk", (await ReadAsync(client, "uk")).GetProperty("subject").GetString());
|
||||
}
|
||||
|
||||
private static object Content(string language, string variable = "Name", string? subject = null) => new
|
||||
{
|
||||
serviceName = "TestService", key = "Welcome", languageCode = language,
|
||||
subject = subject ?? "Subject " + language, htmlBody = "<p>Hello {{Name}}</p>", textBody = "Hello {{Name}}",
|
||||
variables = new[] { new { name = variable, required = true } }
|
||||
};
|
||||
|
||||
private static async Task<JsonElement> ReadAsync(HttpClient client, string language) =>
|
||||
(await client.GetFromJsonAsync<JsonElement>("/api/v1/email-templates/TestService/Welcome/" + language)).GetProperty("data");
|
||||
|
||||
private static async Task<Dictionary<string, string>> EditorFieldsAsync(HttpClient client)
|
||||
{
|
||||
var response = await client.GetAsync("/admin/templates/TestService/Welcome/uk");
|
||||
var html = response.Headers.Location is Uri location ? await client.GetStringAsync(location) : await response.Content.ReadAsStringAsync();
|
||||
var fields = new Dictionary<string, string>();
|
||||
foreach (Match input in Regex.Matches(html, "<input[^>]+>"))
|
||||
{
|
||||
var name = Regex.Match(input.Value, "name=\"([^\"]+)\"");
|
||||
var value = Regex.Match(input.Value, "value=\"([^\"]*)\"");
|
||||
if (name.Success && value.Success)
|
||||
fields[WebUtility.HtmlDecode(name.Groups[1].Value)] = WebUtility.HtmlDecode(value.Groups[1].Value);
|
||||
}
|
||||
foreach (var codeField in fields.Keys.Where(k => k.EndsWith(".LanguageCode")).ToList())
|
||||
{
|
||||
var prefix = codeField[..^"LanguageCode".Length];
|
||||
fields.TryAdd(prefix + "Subject", "");
|
||||
fields.TryAdd(prefix + "HtmlBody", "");
|
||||
fields.TryAdd(prefix + "TextBody", "");
|
||||
}
|
||||
fields["ServiceName"] = "TestService";
|
||||
fields["Key"] = "Welcome";
|
||||
fields["VariablesJson"] = """[{"name":"Name","required":true}]""";
|
||||
AddLanguageFields(fields, 0, "en");
|
||||
AddLanguageFields(fields, 1, "uk");
|
||||
return fields;
|
||||
}
|
||||
|
||||
private static void AddLanguageFields(Dictionary<string, string> fields, int index, string language)
|
||||
{
|
||||
fields[$"Languages[{index}].LanguageCode"] = language;
|
||||
fields[$"Languages[{index}].Subject"] = "Subject " + language;
|
||||
fields[$"Languages[{index}].HtmlBody"] = "<p>Hello {{Name}}</p>";
|
||||
fields[$"Languages[{index}].TextBody"] = "Hello {{Name}}";
|
||||
}
|
||||
|
||||
private static string SaveUrl(Dictionary<string, string> fields) => $"/admin/services/{fields["ServiceId"]}/templates/save";
|
||||
|
||||
private static async Task<string> PostEditorAsync(HttpClient client, Dictionary<string, string> fields) =>
|
||||
await (await client.PostAsync(SaveUrl(fields), new FormUrlEncodedContent(fields))).Content.ReadAsStringAsync();
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class EmailTemplateMigrationTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task EquivalentContracts_PreserveLanguageIdsContentAndSharedVariables_AndRerunSafely()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync(legacy: true);
|
||||
var en = await TemplateDatabaseFixture.InsertLegacyAsync(connection, "en", """[{"name":"Name","required":true},{"name":"Link","required":false}]""");
|
||||
var uk = await TemplateDatabaseFixture.InsertLegacyAsync(connection, "UK", """[{"required":false,"name":"Link"},{"required":true,"name":"Name"}]""");
|
||||
await MigrateAsync(connection);
|
||||
await MigrateAsync(connection);
|
||||
using var services = new ServiceCollection().AddNotificationDataAccess(connection).BuildServiceProvider();
|
||||
using var scope = services.CreateScope();
|
||||
var repository = scope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>();
|
||||
var templates = await repository.GetAllAsync("TestService", "Welcome");
|
||||
Assert.Equal(2, templates.Count);
|
||||
Assert.Contains(templates, t => t.Id == en && t.Subject == "Subject en" && t.HtmlBody == "<p>{{Name}}</p>");
|
||||
Assert.Contains(templates, t => t.Id == uk && t.LanguageCode == "UK" && t.Subject == "Subject UK");
|
||||
Assert.All(templates, t => Assert.Equal(2, t.Variables.Count));
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connection);
|
||||
await db.GetService<IMigrator>().MigrateAsync(TemplateDatabaseFixture.LegacyMigration);
|
||||
await db.Database.MigrateAsync();
|
||||
Assert.Equal(en, (await repository.GetAsync("TestService", "Welcome", "en"))!.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("[{\"name\":\"Other\",\"required\":true}]", "Conflicting shared variables")]
|
||||
[InlineData("{}", "Invalid template identity or variables array")]
|
||||
[InlineData("[null]", "Invalid variables shape")]
|
||||
[InlineData("[{\"name\":\"Name\",\"required\":\"yes\"}]", "Invalid variables shape")]
|
||||
[InlineData("[{\"name\":\"Name\",\"required\":true},{\"name\":\"Name\",\"required\":true}]", "Duplicate variable names")]
|
||||
public async Task InvalidLegacyData_StopsWithoutChangingSource_ThenCanRecover(string variables, string diagnostic)
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync(legacy: true);
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connection, "en", """[{"name":"Name","required":true}]""");
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connection, "uk", variables);
|
||||
var error = await Assert.ThrowsAsync<PostgresException>(() => MigrateAsync(connection));
|
||||
Assert.Contains(diagnostic, error.MessageText);
|
||||
Assert.Contains("TestService", error.MessageText);
|
||||
Assert.DoesNotContain("Hello", error.MessageText);
|
||||
await TemplateDatabaseFixture.ExecuteAsync(connection, """
|
||||
DO $$ BEGIN
|
||||
IF to_regclass('public.services') IS NOT NULL OR (SELECT count(*) FROM email_templates) <> 2 THEN
|
||||
RAISE EXCEPTION 'Migration partially changed source';
|
||||
END IF;
|
||||
END $$;
|
||||
UPDATE email_templates SET variables = '[{"name":"Name","required":true}]'::jsonb;
|
||||
""");
|
||||
await MigrateAsync(connection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExactLanguageCodes_RemainDistinctAfterMigration()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync(legacy: true);
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connection, "ru", "[]");
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connection, "ru-RU", "[]");
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connection, "EN", "[]");
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connection, "en", "[]");
|
||||
await MigrateAsync(connection);
|
||||
await TemplateDatabaseFixture.ExecuteAsync(connection, """
|
||||
DO $$ BEGIN
|
||||
IF (SELECT count(*) FROM service_languages) <> 4
|
||||
OR NOT EXISTS (SELECT 1 FROM service_languages WHERE code = 'ru-RU')
|
||||
OR NOT EXISTS (SELECT 1 FROM service_languages WHERE code = 'EN') THEN
|
||||
RAISE EXCEPTION 'Migration changed exact language codes';
|
||||
END IF;
|
||||
END $$;
|
||||
""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InterruptedConversion_RollsBackAndCanBeRetried()
|
||||
{
|
||||
var connectionString = await fixture.CreateDatabaseAsync(legacy: true);
|
||||
await TemplateDatabaseFixture.InsertLegacyAsync(connectionString, "en", "[]");
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connectionString);
|
||||
var script = db.GetService<IMigrator>().GenerateScript(TemplateDatabaseFixture.LegacyMigration, options: MigrationsSqlGenerationOptions.NoTransactions);
|
||||
script = script.Replace("ALTER TABLE email_templates DROP COLUMN", "PERFORM pg_sleep(2); ALTER TABLE email_templates DROP COLUMN");
|
||||
await using (var connection = new NpgsqlConnection(connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
await using var transaction = await connection.BeginTransactionAsync();
|
||||
await using var command = new NpgsqlCommand("SET LOCAL statement_timeout = '500ms'; " + script, connection, transaction);
|
||||
var error = await Assert.ThrowsAsync<PostgresException>(() => command.ExecuteNonQueryAsync());
|
||||
Assert.Equal("57014", error.SqlState);
|
||||
await transaction.RollbackAsync();
|
||||
}
|
||||
await MigrateAsync(connectionString);
|
||||
}
|
||||
|
||||
private static async Task MigrateAsync(string connectionString)
|
||||
{
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connectionString);
|
||||
await db.Database.MigrateAsync();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class FailingEmailTemplateDefinitionRepository(IEmailTemplateRepository inner) : IEmailTemplateDefinitionRepository
|
||||
{
|
||||
public Task<IReadOnlyList<EmailTemplateDefinition>> GetDefinitionsAsync(string? serviceName = null, string? key = null, CancellationToken ct = default) =>
|
||||
((IEmailTemplateDefinitionRepository)inner).GetDefinitionsAsync(serviceName, key, ct);
|
||||
|
||||
public Task<EmailTemplateDefinition?> GetDefinitionAsync(string serviceName, string key, CancellationToken ct = default) =>
|
||||
((IEmailTemplateDefinitionRepository)inner).GetDefinitionAsync(serviceName, key, ct);
|
||||
|
||||
public Task SaveDefinitionAsync(EmailTemplateDefinition definition, bool isNew, CancellationToken ct = default) =>
|
||||
throw new IOException("Simulated save failure.");
|
||||
}
|
||||
+7
-1
@@ -10,16 +10,22 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="Testcontainers.PostgreSql" />
|
||||
<PackageReference Include="SSH.NET" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
<None Include="..\HrynCo.NotificationService.Web\Views\AdminTemplates\Index.cshtml"
|
||||
Link="TestViews\Index.cshtml" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HrynCo.NotificationService.Web\HrynCo.NotificationService.Web.csproj" />
|
||||
<ProjectReference Include="..\HrynCo.NotificationService.Worker.Services\HrynCo.NotificationService.Worker.Services.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public static class InterimEmailTemplateFixture
|
||||
{
|
||||
public const string MigrationId = "20261017070315_EmailTemplateLocalizations";
|
||||
|
||||
public static async Task<string> CreateAsync(TemplateDatabaseFixture fixture)
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync(legacy: true);
|
||||
await TemplateDatabaseFixture.ExecuteAsync(connection, """
|
||||
DROP INDEX "IX_email_templates_service_name_key_language_code";
|
||||
ALTER TABLE email_templates DROP COLUMN service_name, DROP COLUMN key, DROP COLUMN variables;
|
||||
ALTER TABLE email_templates ADD COLUMN definition_id uuid NOT NULL;
|
||||
CREATE TABLE services (id uuid PRIMARY KEY, name varchar(100) NOT NULL, created timestamptz NOT NULL, updated timestamptz);
|
||||
CREATE UNIQUE INDEX "IX_services_name" ON services(name);
|
||||
CREATE TABLE email_template_definitions (
|
||||
id uuid PRIMARY KEY, service_id uuid NOT NULL REFERENCES services(id) ON DELETE RESTRICT,
|
||||
key varchar(100) NOT NULL, revision uuid NOT NULL, variables jsonb NOT NULL,
|
||||
created timestamptz NOT NULL, updated timestamptz);
|
||||
CREATE UNIQUE INDEX "IX_email_template_definitions_service_id_key" ON email_template_definitions(service_id, key);
|
||||
ALTER TABLE email_templates ADD CONSTRAINT "FK_email_templates_email_template_definitions_definition_id"
|
||||
FOREIGN KEY(definition_id) REFERENCES email_template_definitions(id) ON DELETE CASCADE;
|
||||
CREATE UNIQUE INDEX "IX_email_templates_definition_id_language_code" ON email_templates(definition_id, language_code);
|
||||
INSERT INTO "__EFMigrationsHistory" VALUES ('20261017070315_EmailTemplateLocalizations', '10.0.7');
|
||||
INSERT INTO services VALUES
|
||||
('11111111-1111-1111-1111-111111111111', 'InterimService', '2026-01-01Z', '2026-02-01Z'),
|
||||
('88888888-8888-8888-8888-888888888888', 'UnusedService', '2026-01-02Z', null);
|
||||
INSERT INTO email_template_definitions VALUES
|
||||
('22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111', 'Welcome',
|
||||
'44444444-4444-4444-4444-444444444444', '[{"name":"Name","required":true}]', '2026-01-03Z', '2026-02-03Z'),
|
||||
('33333333-3333-3333-3333-333333333333', '11111111-1111-1111-1111-111111111111', 'Empty',
|
||||
'55555555-5555-5555-5555-555555555555', '[]', '2026-01-04Z', null);
|
||||
INSERT INTO email_templates(id, definition_id, language_code, subject, html_body, text_body, created, updated) VALUES
|
||||
('66666666-6666-6666-6666-666666666666', '22222222-2222-2222-2222-222222222222', 'ru-RU',
|
||||
'Hello {{Name}}', '<p>{{Name}}</p>', 'Hello {{Name}}', '2026-01-05Z', '2026-02-05Z'),
|
||||
('77777777-7777-7777-7777-777777777777', '22222222-2222-2222-2222-222222222222', 'ru',
|
||||
'Welcome {{Name}}', '<p>Welcome {{Name}}</p>', 'Welcome {{Name}}', '2026-01-06Z', null);
|
||||
""");
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class InterimEmailTemplateMigrationTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task KnownInterimLayout_UpgradesInPlacePreservingEveryExistingFieldAndHistory()
|
||||
{
|
||||
var connection = await InterimEmailTemplateFixture.CreateAsync(fixture);
|
||||
var original = await SourceSnapshotAsync(connection, upgraded: false);
|
||||
await MigrateAsync(connection);
|
||||
Assert.Equal(original, await SourceSnapshotAsync(connection, upgraded: true));
|
||||
var firstServices = await ScalarAsync(connection, "SELECT jsonb_agg(to_jsonb(s) ORDER BY id)::text FROM services s");
|
||||
await MigrateAsync(connection);
|
||||
Assert.Equal(firstServices, await ScalarAsync(connection, "SELECT jsonb_agg(to_jsonb(s) ORDER BY id)::text FROM services s"));
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connection);
|
||||
var history = (await db.Database.GetAppliedMigrationsAsync()).ToList();
|
||||
Assert.Equal(4, history.Count);
|
||||
Assert.Contains(InterimEmailTemplateFixture.MigrationId, history);
|
||||
using var provider = new ServiceCollection().AddNotificationDataAccess(connection).BuildServiceProvider();
|
||||
using var scope = provider.CreateScope();
|
||||
var repository = scope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>();
|
||||
Assert.Equal(Guid.Parse("66666666-6666-6666-6666-666666666666"), (await repository.GetAsync("InterimService", "Welcome", "ru-RU"))!.Id);
|
||||
Assert.Equal(Guid.Parse("77777777-7777-7777-7777-777777777777"), (await repository.GetAsync("InterimService", "Welcome", "ru"))!.Id);
|
||||
var definitions = scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
Assert.Empty((await definitions.GetDefinitionAsync("InterimService", "Empty"))!.Languages);
|
||||
var services = await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().GetAllAsync();
|
||||
Assert.Contains(services, s => s.Name == "UnusedService" && s.Languages.Count == 0);
|
||||
Assert.All(services, s => Assert.NotEqual(Guid.Empty, s.Revision));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ALTER TABLE email_templates ADD COLUMN service_name varchar(100)")]
|
||||
[InlineData("ALTER TABLE email_templates ALTER COLUMN language_code TYPE varchar(11)")]
|
||||
[InlineData("DROP INDEX \"IX_email_templates_definition_id_language_code\"")]
|
||||
[InlineData("DROP INDEX \"IX_email_templates_definition_id_language_code\"; CREATE UNIQUE INDEX \"IX_email_templates_definition_id_language_code\" ON email_templates(id)")]
|
||||
[InlineData("ALTER TABLE email_templates DROP CONSTRAINT \"FK_email_templates_email_template_definitions_definition_id\"; ALTER TABLE email_templates ADD CONSTRAINT \"FK_email_templates_email_template_definitions_definition_id\" FOREIGN KEY(definition_id) REFERENCES email_template_definitions(id) ON DELETE RESTRICT")]
|
||||
[InlineData("DELETE FROM \"__EFMigrationsHistory\" WHERE \"MigrationId\" = '20261017070315_EmailTemplateLocalizations'")]
|
||||
[InlineData("CREATE TABLE service_languages(id uuid)")]
|
||||
public async Task HybridOrUnknownLayout_FailsWithoutAdoptingOrChangingIt(string change)
|
||||
{
|
||||
var connection = await InterimEmailTemplateFixture.CreateAsync(fixture);
|
||||
await TemplateDatabaseFixture.ExecuteAsync(connection, change);
|
||||
var original = await SourceSnapshotAsync(connection, upgraded: false);
|
||||
var error = await Assert.ThrowsAsync<PostgresException>(() => MigrateAsync(connection));
|
||||
Assert.Contains("Unsupported email-template source layout", error.MessageText);
|
||||
Assert.Equal(original, await SourceSnapshotAsync(connection, upgraded: false));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("UPDATE email_template_definitions SET variables = '{}'", "Invalid interim shared variables array")]
|
||||
[InlineData("UPDATE email_template_definitions SET variables = '[null]'", "Invalid interim shared variables shape")]
|
||||
[InlineData("UPDATE email_templates SET language_code = '' WHERE id = '66666666-6666-6666-6666-666666666666'", "Invalid blank identity")]
|
||||
public async Task InvalidInterimData_FailsBeforeSchemaChanges(string change, string diagnostic)
|
||||
{
|
||||
var connection = await InterimEmailTemplateFixture.CreateAsync(fixture);
|
||||
await TemplateDatabaseFixture.ExecuteAsync(connection, change);
|
||||
var original = await SourceSnapshotAsync(connection, upgraded: false);
|
||||
var error = await Assert.ThrowsAsync<PostgresException>(() => MigrateAsync(connection));
|
||||
Assert.Contains(diagnostic, error.MessageText);
|
||||
Assert.Equal(original, await SourceSnapshotAsync(connection, upgraded: false));
|
||||
Assert.Equal("0", await ScalarAsync(connection, "SELECT count(*)::text FROM information_schema.columns WHERE table_name = 'services' AND column_name = 'revision'"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InterruptedInterimUpgrade_RollsBackAndCanBeRetried()
|
||||
{
|
||||
var connectionString = await InterimEmailTemplateFixture.CreateAsync(fixture);
|
||||
var original = await SourceSnapshotAsync(connectionString, upgraded: false);
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connectionString);
|
||||
var script = db.GetService<IMigrator>().GenerateScript(TemplateDatabaseFixture.LegacyMigration, options: MigrationsSqlGenerationOptions.NoTransactions);
|
||||
script = script.Replace("ALTER TABLE email_templates DROP COLUMN language_code;", "PERFORM pg_sleep(2); ALTER TABLE email_templates DROP COLUMN language_code;");
|
||||
await using (var connection = new NpgsqlConnection(connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
await using var transaction = await connection.BeginTransactionAsync();
|
||||
await using var command = new NpgsqlCommand("SET LOCAL statement_timeout = '500ms'; " + script, connection, transaction);
|
||||
Assert.Equal("57014", (await Assert.ThrowsAsync<PostgresException>(() => command.ExecuteNonQueryAsync())).SqlState);
|
||||
await transaction.RollbackAsync();
|
||||
}
|
||||
Assert.Equal(original, await SourceSnapshotAsync(connectionString, upgraded: false));
|
||||
await MigrateAsync(connectionString);
|
||||
Assert.Equal(original, await SourceSnapshotAsync(connectionString, upgraded: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InterimOrigin_DownIsBlockedBeforeAnyChanges()
|
||||
{
|
||||
var connection = await InterimEmailTemplateFixture.CreateAsync(fixture);
|
||||
await MigrateAsync(connection);
|
||||
var original = await SourceSnapshotAsync(connection, upgraded: true);
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connection);
|
||||
var error = await Assert.ThrowsAsync<PostgresException>(() => db.GetService<IMigrator>().MigrateAsync(TemplateDatabaseFixture.LegacyMigration));
|
||||
Assert.Contains("Cannot downgrade an interim-origin database", error.MessageText);
|
||||
Assert.Equal(original, await SourceSnapshotAsync(connection, upgraded: true));
|
||||
}
|
||||
|
||||
private static async Task MigrateAsync(string connection)
|
||||
{
|
||||
await using var db = TemplateDatabaseFixture.CreateContext(connection);
|
||||
await db.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
private static Task<string> SourceSnapshotAsync(string connection, bool upgraded)
|
||||
{
|
||||
var versions = upgraded
|
||||
? "SELECT (to_jsonb(t) - 'service_id' - 'service_language_id') || jsonb_build_object('language_code', l.code) AS value FROM email_templates t JOIN service_languages l ON l.id = t.service_language_id"
|
||||
: "SELECT to_jsonb(t) AS value FROM email_templates t";
|
||||
return ScalarAsync(connection, $"""
|
||||
SELECT jsonb_build_object(
|
||||
'services', (SELECT jsonb_agg(to_jsonb(s) - 'revision' ORDER BY id) FROM services s),
|
||||
'definitions', (SELECT jsonb_agg(to_jsonb(d) ORDER BY id) FROM email_template_definitions d),
|
||||
'versions', (SELECT jsonb_agg(value ORDER BY value->>'id') FROM ({versions}) q))::text
|
||||
""");
|
||||
}
|
||||
|
||||
private static async Task<string> ScalarAsync(string connectionString, string sql)
|
||||
{
|
||||
await using var connection = new NpgsqlConnection(connectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand(sql, connection);
|
||||
return (string)(await command.ExecuteScalarAsync())!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class ServiceLanguageTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task EmptyDefinition_CanBeCreatedAndRetainedAfterItsFinalVersionIsRemoved()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = Provider(connection);
|
||||
var definition = new EmailTemplateDefinition { ServiceName = "TestService", Key = "Empty", Variables = [] };
|
||||
using (var scope = provider.CreateScope())
|
||||
await scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>().SaveDefinitionAsync(definition, true);
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
Assert.Contains("data-state=\"missing\"", await client.GetStringAsync("/admin/templates?serviceName=TestService&key=Empty"));
|
||||
var content = new { serviceName = "TestService", key = "Empty", languageCode = "en", subject = "Hello", htmlBody = "<p>Hello</p>", textBody = "Hello", variables = Array.Empty<object>() };
|
||||
Assert.Equal(HttpStatusCode.Created, (await client.PostAsJsonAsync("/api/v1/email-templates", content)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync("/api/v1/email-templates/TestService/Empty/en")).StatusCode);
|
||||
using var readScope = provider.CreateScope();
|
||||
var saved = await readScope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>().GetDefinitionAsync("TestService", "Empty");
|
||||
Assert.Equal(definition.Id, saved!.Id);
|
||||
Assert.Empty(saved.Languages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CatalogDeletion_BlocksOrdinaryRemoval_RequiresCurrentCount_AndRetainsDefinitions()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = Provider(connection);
|
||||
await AddTemplateAsync(provider, "First", "en");
|
||||
var original = await ReadServiceAsync(provider);
|
||||
var language = original.Languages.Single(l => l.Code == "en");
|
||||
original.Languages = original.Languages.Where(l => l.Id != language.Id).ToList();
|
||||
using (var scope = provider.CreateScope())
|
||||
{
|
||||
var error = await Assert.ThrowsAsync<EmailTemplateWriteException>(() => scope.ServiceProvider
|
||||
.GetRequiredService<INotificationServiceRepository>().SaveAsync(original, false));
|
||||
Assert.Contains("1 version(s)", error.Message);
|
||||
}
|
||||
await AddTemplateAsync(provider, "Second", "en");
|
||||
using (var scope = provider.CreateScope())
|
||||
{
|
||||
var error = await Assert.ThrowsAsync<EmailTemplateWriteException>(() => scope.ServiceProvider
|
||||
.GetRequiredService<INotificationServiceRepository>().RemoveLanguageAsync(original.Id, language.Id, 1, original.Revision));
|
||||
Assert.Contains("count changed", error.Message);
|
||||
}
|
||||
var current = await ReadServiceAsync(provider);
|
||||
Assert.Equal(2, current.Languages.Single(l => l.Code == "en").VersionCount);
|
||||
using (var scope = provider.CreateScope())
|
||||
await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().RemoveLanguageAsync(current.Id, language.Id, 2, current.Revision);
|
||||
using var readScope = provider.CreateScope();
|
||||
var definitions = await readScope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>().GetDefinitionsAsync("TestService");
|
||||
Assert.Equal(2, definitions.Count);
|
||||
Assert.All(definitions, d => Assert.Empty(d.Languages));
|
||||
Assert.DoesNotContain((await ReadServiceAsync(provider)).Languages, l => l.Code == "en");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ServiceEditor_CanSwapLanguageCodesWithoutLosingVersionIdentity()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = Provider(connection);
|
||||
await AddTemplateAsync(provider, "First", "en");
|
||||
var service = await ReadServiceAsync(provider);
|
||||
var en = service.Languages.Single(l => l.Code == "en");
|
||||
var uk = service.Languages.Single(l => l.Code == "uk");
|
||||
en.Code = "uk";
|
||||
uk.Code = "en";
|
||||
using (var scope = provider.CreateScope())
|
||||
await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().SaveAsync(service, false);
|
||||
using var readScope = provider.CreateScope();
|
||||
var version = await readScope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>().GetAsync("TestService", "First", "uk");
|
||||
Assert.NotNull(version);
|
||||
Assert.Null(await readScope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>().GetAsync("TestService", "First", "en"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task FailedServiceSave_RefreshesUsedLanguageCountsAndRetainsEnteredFields(bool modelValidationFailure)
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = Provider(connection);
|
||||
await AddTemplateAsync(provider, "First", "en");
|
||||
var service = await ReadServiceAsync(provider);
|
||||
var usedIndex = service.Languages.ToList().FindIndex(l => l.Code == "en");
|
||||
var unusedIndex = service.Languages.ToList().FindIndex(l => l.Code == "uk");
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
var fields = HiddenFields(await client.GetStringAsync($"/admin/services/{service.Id}/edit"));
|
||||
var revision = fields["Revision"];
|
||||
var enteredName = modelValidationFailure ? new string('x', 101) : "Entered unsaved name";
|
||||
fields["Name"] = enteredName;
|
||||
fields[$"Languages[{usedIndex}].Code"] = "xx";
|
||||
if (!modelValidationFailure)
|
||||
fields[$"Languages[{unusedIndex}].Code"] = "de";
|
||||
var html = await (await client.PostAsync("/admin/services/save", new FormUrlEncodedContent(fields))).Content.ReadAsStringAsync();
|
||||
var usedRow = Assert.Single(Regex.Matches(html, "<tr>.*?</tr>", RegexOptions.Singleline).Cast<Match>(),
|
||||
row => row.Value.Contains(service.Languages[usedIndex].Id.ToString(), StringComparison.OrdinalIgnoreCase)).Value;
|
||||
Assert.Contains("data-count=\"1\"", usedRow);
|
||||
Assert.Contains("<td>1</td>", usedRow);
|
||||
var returnedFields = HiddenFields(html);
|
||||
Assert.Equal(enteredName, returnedFields["Name"]);
|
||||
Assert.Equal("xx", returnedFields[$"Languages[{usedIndex}].Code"]);
|
||||
Assert.Equal(revision, returnedFields["Revision"]);
|
||||
Assert.Equal("en", (await ReadServiceAsync(provider)).Languages.Single(l => l.Id == service.Languages[usedIndex].Id).Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MigratedNonstandardCode_AllowsUnchangedServiceEditsAndNewLanguages()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync(legacy: true);
|
||||
var originalVersionId = await TemplateDatabaseFixture.InsertLegacyAsync(connection, "en_US", "[]");
|
||||
await using (var db = TemplateDatabaseFixture.CreateContext(connection))
|
||||
await db.Database.MigrateAsync();
|
||||
using var provider = Provider(connection);
|
||||
var service = await ReadServiceAsync(provider);
|
||||
service.Name = "RenamedService";
|
||||
service.Languages = [..service.Languages, new ServiceLanguageInfo { Code = "uk" }];
|
||||
using (var saveScope = provider.CreateScope())
|
||||
await saveScope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().SaveAsync(service, false);
|
||||
using var readScope = provider.CreateScope();
|
||||
var services = readScope.ServiceProvider.GetRequiredService<INotificationServiceRepository>();
|
||||
var saved = (await services.GetAsync(service.Id))!;
|
||||
Assert.Contains(saved.Languages, l => l.Code == "en_US");
|
||||
Assert.Contains(saved.Languages, l => l.Code == "uk");
|
||||
var version = await readScope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>().GetAsync("RenamedService", "Welcome", "en_US");
|
||||
Assert.Equal(originalVersionId, version!.Id);
|
||||
saved.Languages.Single(l => l.Code == "en_US").Code = "en_GB";
|
||||
var error = await Assert.ThrowsAsync<EmailTemplateWriteException>(() => services.SaveAsync(saved, false));
|
||||
Assert.Contains("new or renamed", error.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LegacyApi_RejectsUnknownServiceLanguage_WithoutCreatingDefinition()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient();
|
||||
var content = new { serviceName = "TestService", key = "Unknown", languageCode = "fr", subject = "Hello", htmlBody = "Hello", textBody = "Hello", variables = Array.Empty<object>() };
|
||||
var response = await client.PostAsJsonAsync("/api/v1/email-templates", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Contains("catalog", await response.Content.ReadAsStringAsync());
|
||||
using var scope = app.Services.CreateScope();
|
||||
Assert.Null(await scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>().GetDefinitionAsync("TestService", "Unknown"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DatabaseConstraints_RejectDuplicatesAndLanguageFromAnotherService()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = Provider(connection);
|
||||
await AddTemplateAsync(provider, "First", "en");
|
||||
using (var scope = provider.CreateScope())
|
||||
await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().SaveAsync(new NotificationServiceInfo
|
||||
{ Name = "OtherService", Languages = [new ServiceLanguageInfo { Code = "en" }] }, true);
|
||||
await AssertSqlStateAsync(connection, "23505", "INSERT INTO services SELECT gen_random_uuid(), name, gen_random_uuid(), created, updated FROM services WHERE name = 'TestService'");
|
||||
await AssertSqlStateAsync(connection, "23505", "INSERT INTO service_languages SELECT gen_random_uuid(), service_id, code, created, updated FROM service_languages LIMIT 1");
|
||||
await AssertSqlStateAsync(connection, "23505", "INSERT INTO email_template_definitions SELECT gen_random_uuid(), service_id, key, revision, variables, created, updated FROM email_template_definitions LIMIT 1");
|
||||
await AssertSqlStateAsync(connection, "23505", """
|
||||
INSERT INTO email_templates(id, definition_id, service_id, service_language_id, subject, html_body, text_body, created)
|
||||
SELECT gen_random_uuid(), definition_id, service_id, service_language_id, subject, html_body, text_body, created FROM email_templates LIMIT 1
|
||||
""");
|
||||
await AssertSqlStateAsync(connection, "23503", """
|
||||
INSERT INTO email_templates(id, definition_id, service_id, service_language_id, subject, html_body, text_body, created)
|
||||
SELECT gen_random_uuid(), t.definition_id, t.service_id, l.id, 'Hello', 'Hello', 'Hello', now()
|
||||
FROM email_templates t CROSS JOIN service_languages l JOIN services s ON s.id = l.service_id WHERE s.name = 'OtherService' LIMIT 1
|
||||
""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ServiceForm_CreatesEditsInlineLanguages_RejectsDuplicatesAndRequiresDestructiveConfirmation()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient(new() { AllowAutoRedirect = false });
|
||||
var createHtml = await client.GetStringAsync("/admin/services/create");
|
||||
var fields = HiddenFields(createHtml);
|
||||
fields["Name"] = "FormService";
|
||||
fields["Languages[0].Code"] = "ru";
|
||||
fields["Languages[1].Code"] = "ru-RU";
|
||||
var createResponse = await client.PostAsync("/admin/services/save", new FormUrlEncodedContent(fields));
|
||||
Assert.Equal(HttpStatusCode.Redirect, createResponse.StatusCode);
|
||||
var createdService = (await app.Services.GetRequiredService<INotificationServiceRepository>().GetAllAsync()).Single(s => s.Name == "FormService");
|
||||
var serviceUrl = $"/admin/services/{createdService.Id}";
|
||||
Assert.Equal(serviceUrl, createResponse.Headers.Location!.OriginalString);
|
||||
var editUrl = serviceUrl + "/edit";
|
||||
var editHtml = await client.GetStringAsync(editUrl);
|
||||
Assert.Contains("ru-RU", editHtml);
|
||||
var savedFields = HiddenFields(editHtml);
|
||||
var editResponse = await client.PostAsync("/admin/services/save", new FormUrlEncodedContent(savedFields));
|
||||
Assert.Equal(HttpStatusCode.Redirect, editResponse.StatusCode);
|
||||
Assert.Equal(serviceUrl, editResponse.Headers.Location!.OriginalString);
|
||||
savedFields = HiddenFields(await client.GetStringAsync(editUrl));
|
||||
savedFields["Name"] = "FormServiceRenamed";
|
||||
savedFields["Languages[0].Code"] = "ru";
|
||||
savedFields["Languages[1].Code"] = "ru";
|
||||
Assert.Contains("must be unique", await (await client.PostAsync("/admin/services/save", new FormUrlEncodedContent(savedFields))).Content.ReadAsStringAsync());
|
||||
savedFields["Languages[1].Code"] = "ru-RU";
|
||||
var renameResponse = await client.PostAsync("/admin/services/save", new FormUrlEncodedContent(savedFields));
|
||||
Assert.Equal(HttpStatusCode.Redirect, renameResponse.StatusCode);
|
||||
Assert.Equal(serviceUrl, renameResponse.Headers.Location!.OriginalString);
|
||||
var service = (await app.Services.GetRequiredService<INotificationServiceRepository>().GetAllAsync()).Single(s => s.Name == "FormServiceRenamed");
|
||||
var removalUrl = $"/admin/services/{service.Id}/languages/{service.Languages[0].Id}/delete";
|
||||
var removalHtml = await client.GetStringAsync(removalUrl);
|
||||
var removalFields = HiddenFields(removalHtml);
|
||||
Assert.Contains("0 template version(s)", removalHtml);
|
||||
Assert.Contains("Confirm deletion", await (await client.PostAsync(removalUrl, new FormUrlEncodedContent(removalFields))).Content.ReadAsStringAsync());
|
||||
removalFields["ConfirmDelete"] = "true";
|
||||
Assert.Equal(HttpStatusCode.Redirect, (await client.PostAsync(removalUrl, new FormUrlEncodedContent(removalFields))).StatusCode);
|
||||
}
|
||||
|
||||
private static ServiceProvider Provider(string connection) => new ServiceCollection().AddNotificationDataAccess(connection).BuildServiceProvider();
|
||||
|
||||
private static async Task<NotificationServiceInfo> ReadServiceAsync(ServiceProvider provider)
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
return (await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().GetAllAsync()).Single(s => s.Name == "TestService");
|
||||
}
|
||||
|
||||
private static async Task AddTemplateAsync(ServiceProvider provider, string key, string language)
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>().AddAsync(new EmailTemplate
|
||||
{
|
||||
ServiceName = "TestService", Key = key, LanguageCode = language, Subject = "Hello", HtmlBody = "Hello", TextBody = "Hello"
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task AssertSqlStateAsync(string connection, string code, string sql) =>
|
||||
Assert.Equal(code, (await Assert.ThrowsAsync<PostgresException>(() => TemplateDatabaseFixture.ExecuteAsync(connection, sql))).SqlState);
|
||||
|
||||
private static Dictionary<string, string> HiddenFields(string html)
|
||||
{
|
||||
var result = new Dictionary<string, string>();
|
||||
foreach (Match input in Regex.Matches(html, "<input[^>]+>"))
|
||||
{
|
||||
var name = Regex.Match(input.Value, "name=\"([^\"]+)\"");
|
||||
var value = Regex.Match(input.Value, "value=\"([^\"]*)\"");
|
||||
if (name.Success && value.Success)
|
||||
result[WebUtility.HtmlDecode(name.Groups[1].Value)] = WebUtility.HtmlDecode(value.Groups[1].Value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Net;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using HrynCo.NotificationService.Services.EmailTemplates.Delete;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class ServiceTemplateNavigationTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task ServicesAreTheEntryPoint_AndEachServiceListsOnlyItsOwnTemplates()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = new ServiceCollection().AddNotificationDataAccess(connection).BuildServiceProvider();
|
||||
using var scope = provider.CreateScope();
|
||||
var services = scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>();
|
||||
var service = (await services.GetAllAsync()).Single();
|
||||
var other = new NotificationServiceInfo { Name = "OtherService", Languages = [new ServiceLanguageInfo { Code = "en" }] };
|
||||
await services.SaveAsync(other, true);
|
||||
var definitions = scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
await definitions.SaveDefinitionAsync(new EmailTemplateDefinition { ServiceName = service.Name, Key = "OwnTemplate" }, true);
|
||||
await definitions.SaveDefinitionAsync(new EmailTemplateDefinition { ServiceName = other.Name, Key = "OtherTemplate" }, true);
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient(new() { AllowAutoRedirect = false });
|
||||
Assert.Equal("/admin/services", (await client.GetAsync("/")).Headers.Location!.OriginalString);
|
||||
Assert.Equal("/admin/services", (await client.GetAsync("/admin/templates")).Headers.Location!.OriginalString);
|
||||
Assert.Equal($"/admin/services/{service.Id}/templates/create?keyFilter=Welcome",
|
||||
(await client.GetAsync("/admin/templates/create?serviceNameFilter=TestService&keyFilter=Welcome")).Headers.Location!.OriginalString);
|
||||
var list = await client.GetStringAsync("/admin/services");
|
||||
Assert.Contains($"href=\"/admin/services/{service.Id}\">TestService</a>", list);
|
||||
Assert.Contains($"href=\"/admin/services/{service.Id}/edit\"", list);
|
||||
Assert.DoesNotContain("href=\"/admin/templates\"", list);
|
||||
var detail = await client.GetStringAsync($"/admin/services/{service.Id}");
|
||||
Assert.Contains("OwnTemplate", detail);
|
||||
Assert.Contains($"href=\"/admin/services/{service.Id}/edit\" class=\"btn btn-outline-primary\"", detail);
|
||||
Assert.DoesNotContain("OtherTemplate", detail);
|
||||
Assert.Contains($"/admin/services/{service.Id}/templates/create", detail);
|
||||
Assert.Contains("data-state=\"missing\"", detail);
|
||||
Assert.Contains("No email templates found", await client.GetStringAsync($"/admin/services/{service.Id}?key=Missing"));
|
||||
Assert.Contains("Language codes", await client.GetStringAsync($"/admin/services/{service.Id}/edit"));
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync($"/admin/services/{Guid.NewGuid()}" )).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AllConfiguredTabsAllowBlankDefinitions_PopulateAndClearWithoutLosingTheTemplate()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient(new() { AllowAutoRedirect = false });
|
||||
using var scope = app.Services.CreateScope();
|
||||
var service = (await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().GetAllAsync()).Single();
|
||||
var baseUrl = $"/admin/services/{service.Id}";
|
||||
var createHtml = await client.GetStringAsync(baseUrl + "/templates/create?keyFilter=Welcome");
|
||||
Assert.Equal(5, System.Text.RegularExpressions.Regex.Matches(createHtml, "role=\"tab\"").Count);
|
||||
Assert.DoesNotContain("id=\"addLanguage\"", createHtml);
|
||||
Assert.DoesNotContain("remove-language", createHtml);
|
||||
var fields = TemplateEditorTestFields.Read(createHtml);
|
||||
fields["Key"] = "Welcome";
|
||||
var response = await client.PostAsync(baseUrl + "/templates/save", new FormUrlEncodedContent(fields));
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal(baseUrl + "?key=Welcome", response.Headers.Location!.OriginalString);
|
||||
var definitions = scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
var empty = (await definitions.GetDefinitionAsync("TestService", "Welcome"))!;
|
||||
Assert.Empty(empty.Languages);
|
||||
var editUrl = baseUrl + "/templates/" + empty.Id;
|
||||
fields = TemplateEditorTestFields.Read(await client.GetStringAsync(editUrl));
|
||||
TemplateEditorTestFields.SetLanguage(fields, "uk", "Subject uk", "<p>Hello</p>", "Hello");
|
||||
Assert.Equal(HttpStatusCode.Redirect, (await client.PostAsync(baseUrl + "/templates/save", new FormUrlEncodedContent(fields))).StatusCode);
|
||||
Assert.Equal("uk", Assert.Single((await definitions.GetDefinitionAsync("TestService", "Welcome"))!.Languages).LanguageCode);
|
||||
fields = TemplateEditorTestFields.Read(await client.GetStringAsync(editUrl));
|
||||
TemplateEditorTestFields.SetLanguage(fields, "uk", "", "", "");
|
||||
Assert.Equal(HttpStatusCode.Redirect, (await client.PostAsync(baseUrl + "/templates/save", new FormUrlEncodedContent(fields))).StatusCode);
|
||||
var cleared = (await definitions.GetDefinitionAsync("TestService", "Welcome"))!;
|
||||
Assert.Equal(empty.Id, cleared.Id);
|
||||
Assert.Empty(cleared.Languages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CrossServiceGetSaveAndDeleteAreRejected_WithoutChangingEitherService()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var client = app.CreateClient(new() { AllowAutoRedirect = false });
|
||||
using var scope = app.Services.CreateScope();
|
||||
var services = scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>();
|
||||
var service = (await services.GetAllAsync()).Single();
|
||||
var other = new NotificationServiceInfo { Name = "OtherService", Languages = [new ServiceLanguageInfo { Code = "en" }] };
|
||||
await services.SaveAsync(other, true);
|
||||
var repository = scope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>();
|
||||
await repository.AddAsync(new EmailTemplate { ServiceName = service.Name, Key = "Welcome", LanguageCode = "en", Subject = "Original", HtmlBody = "Original", TextBody = "Original" });
|
||||
await repository.AddAsync(new EmailTemplate { ServiceName = service.Name, Key = "Welcome", LanguageCode = "uk", Subject = "Retained", HtmlBody = "Retained", TextBody = "Retained" });
|
||||
var retained = (await repository.GetAsync(service.Name, "Welcome", "uk"))!;
|
||||
var definitions = scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
var definition = (await definitions.GetDefinitionAsync(service.Name, "Welcome"))!;
|
||||
var foreignBase = $"/admin/services/{other.Id}/templates";
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync(foreignBase + "/" + definition.Id)).StatusCode);
|
||||
var fields = TemplateEditorTestFields.Read(await client.GetStringAsync($"/admin/services/{service.Id}/templates/{definition.Id}"));
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsync(foreignBase + "/save", new FormUrlEncodedContent(fields))).StatusCode);
|
||||
fields["ServiceId"] = other.Id.ToString();
|
||||
fields["ServiceName"] = other.Name;
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsync(foreignBase + "/save", new FormUrlEncodedContent(fields))).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsync(foreignBase + $"/{definition.Id}/languages/en/delete", new FormUrlEncodedContent(fields))).StatusCode);
|
||||
Assert.Equal("Original", (await repository.GetAsync(service.Name, "Welcome", "en"))!.Subject);
|
||||
Assert.Empty(await definitions.GetDefinitionsAsync(other.Name));
|
||||
var delete = await client.PostAsync($"/admin/services/{service.Id}/templates/{definition.Id}/languages/en/delete", new FormUrlEncodedContent(fields));
|
||||
Assert.Equal(HttpStatusCode.Redirect, delete.StatusCode);
|
||||
Assert.Equal($"/admin/services/{service.Id}", delete.Headers.Location!.OriginalString);
|
||||
Assert.Equal("uk", Assert.Single((await definitions.GetDefinitionAsync(service.Name, "Welcome"))!.Languages).LanguageCode);
|
||||
Assert.Equal(retained.Updated, (await repository.GetAsync(service.Name, "Welcome", "uk"))!.Updated);
|
||||
var staleDelete = await scope.ServiceProvider.GetRequiredService<IMediator>()
|
||||
.Send(new DeleteEmailTemplateCommand(service.Name, "Welcome", "uk", Guid.NewGuid()));
|
||||
Assert.False(staleDelete.IsSuccess);
|
||||
Assert.NotNull(await repository.GetAsync(service.Name, "Welcome", "uk"));
|
||||
Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsync("/admin/templates/save", new FormUrlEncodedContent(fields))).StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class TemplateCatalogPresentationTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task CatalogStatusesUseExactCodes_AndEmptyDefinitionsShowEveryLanguageMissing()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var scope = app.Services.CreateScope();
|
||||
var services = scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>();
|
||||
var service = (await services.GetAllAsync()).Single();
|
||||
service.Languages = new[] { "EN", "en", "ru", "ru-RU" }.Select(code => new ServiceLanguageInfo { Code = code }).ToList();
|
||||
await services.SaveAsync(service, false);
|
||||
var versions = scope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>();
|
||||
await versions.AddAsync(new EmailTemplate { ServiceName = service.Name, Key = "CaseCheck", LanguageCode = "en", Subject = "Hello", HtmlBody = "Hello", TextBody = "Hello" });
|
||||
await versions.AddAsync(new EmailTemplate { ServiceName = service.Name, Key = "CaseCheck", LanguageCode = "ru", Subject = "Hello", HtmlBody = "Hello", TextBody = "Hello" });
|
||||
var definitions = scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
await definitions.SaveDefinitionAsync(new EmailTemplateDefinition { ServiceName = service.Name, Key = "Empty" }, true);
|
||||
using var client = app.CreateClient();
|
||||
var html = await client.GetStringAsync($"/admin/services/{service.Id}");
|
||||
var catalog = Regex.Match(html, "<div class=\"service-template-catalog.*?</div>", RegexOptions.Singleline).Value;
|
||||
Assert.Equal(4, Regex.Matches(catalog, "class=\"service-template-language-code\"").Count);
|
||||
Assert.Contains(">EN</span>", catalog);
|
||||
Assert.Contains(">en</span>", catalog);
|
||||
Assert.Contains(">ru-RU</span>", catalog);
|
||||
var row = TemplateRow(html, "CaseCheck");
|
||||
Assert.Contains("data-language-code=\"en\" data-state=\"present\"", row);
|
||||
Assert.Contains("data-language-code=\"EN\" data-state=\"missing\"", row);
|
||||
Assert.Contains("data-language-code=\"ru\" data-state=\"present\"", row);
|
||||
Assert.Contains("data-language-code=\"ru-RU\" data-state=\"missing\"", row);
|
||||
Assert.Equal(2, Regex.Matches(row, ">Present</span>").Count);
|
||||
Assert.Equal(2, Regex.Matches(row, ">Missing</span>").Count);
|
||||
var empty = TemplateRow(html, "Empty");
|
||||
Assert.Equal(4, Regex.Matches(empty, "data-state=\"missing\"").Count);
|
||||
Assert.DoesNotContain("data-state=\"present\"", empty);
|
||||
Assert.Equal(2, (await versions.GetAllAsync(service.Name)).Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EmbeddedKeyFilterSurvivesMiss_AndClearAndEditorLinksStayWithinTheService()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var scope = app.Services.CreateScope();
|
||||
var service = (await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().GetAllAsync()).Single();
|
||||
var definitions = scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
await definitions.SaveDefinitionAsync(new EmailTemplateDefinition { ServiceName = service.Name, Key = "Welcome" }, true);
|
||||
await definitions.SaveDefinitionAsync(new EmailTemplateDefinition { ServiceName = service.Name, Key = "Other" }, true);
|
||||
using var client = app.CreateClient();
|
||||
var baseUrl = $"/admin/services/{service.Id}";
|
||||
var miss = await client.GetStringAsync(baseUrl + "?key=Absent");
|
||||
Assert.Matches("(?s)<th[^>]*>\\s*<form[^>]*method=\"get\"[^>]*class=\"template-key-filter\"", miss);
|
||||
Assert.Contains("value=\"Absent\"", miss);
|
||||
Assert.Contains("No email templates found", miss);
|
||||
Assert.Contains("class=\"template-actions\">Action</th>", miss);
|
||||
Assert.Contains($"href=\"{baseUrl}\" class=\"btn btn-outline-secondary btn-sm\">Clear</a>", miss);
|
||||
var filtered = await client.GetStringAsync(baseUrl + "?key=Welcome");
|
||||
Assert.Contains("<td>Welcome</td>", filtered);
|
||||
Assert.DoesNotContain("<td>Other</td>", filtered);
|
||||
Assert.Contains("keyFilter=Welcome", filtered);
|
||||
Assert.Contains("aria-label=\"Edit template Welcome\"", filtered);
|
||||
var cleared = await client.GetStringAsync(baseUrl);
|
||||
Assert.Contains("<td>Welcome</td>", cleared);
|
||||
Assert.Contains("<td>Other</td>", cleared);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoCatalogAndNoDefinitionsHaveExplicitStates_AndRetainTheTableHeader()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
await using var app = new TemplateWebApplicationFactory(connection);
|
||||
using var scope = app.Services.CreateScope();
|
||||
var services = scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>();
|
||||
var service = new NotificationServiceInfo { Name = "NoLanguages" };
|
||||
await services.SaveAsync(service, true);
|
||||
using var client = app.CreateClient();
|
||||
var baseUrl = $"/admin/services/{service.Id}";
|
||||
var empty = await client.GetStringAsync(baseUrl);
|
||||
Assert.Contains("No languages configured for this service.", empty);
|
||||
Assert.Contains("template-key-filter", empty);
|
||||
Assert.Contains("No email templates found", empty);
|
||||
await scope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>()
|
||||
.SaveDefinitionAsync(new EmailTemplateDefinition { ServiceName = service.Name, Key = "Empty" }, true);
|
||||
var withDefinition = await client.GetStringAsync(baseUrl);
|
||||
Assert.Contains("No configured languages", TemplateRow(withDefinition, "Empty"));
|
||||
Assert.DoesNotContain("data-state=", withDefinition);
|
||||
Assert.DoesNotContain("No email templates found", withDefinition);
|
||||
}
|
||||
|
||||
private static string TemplateRow(string html, string key)
|
||||
{
|
||||
var row = Regex.Match(html, "<tr>\\s*<td>" + Regex.Escape(WebUtility.HtmlEncode(key)) + "</td>.*?</tr>", RegexOptions.Singleline).Value;
|
||||
Assert.NotEmpty(row);
|
||||
return row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql;
|
||||
using Testcontainers.PostgreSql;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class TemplateDatabaseFixture : IAsyncLifetime
|
||||
{
|
||||
public const string LegacyMigration = "20260502154249_PendingChanges";
|
||||
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder().WithImage("postgres:17-alpine").Build();
|
||||
|
||||
public Task InitializeAsync() => _postgres.StartAsync();
|
||||
public Task DisposeAsync() => _postgres.DisposeAsync().AsTask();
|
||||
|
||||
public async Task<string> CreateDatabaseAsync(bool legacy = false)
|
||||
{
|
||||
var name = "templates_" + Guid.NewGuid().ToString("N");
|
||||
await using var connection = new NpgsqlConnection(_postgres.GetConnectionString());
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand($"CREATE DATABASE {name}", connection);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
var builder = new NpgsqlConnectionStringBuilder(_postgres.GetConnectionString()) { Database = name };
|
||||
await using var db = CreateContext(builder.ConnectionString);
|
||||
await db.GetService<IMigrator>().MigrateAsync(legacy ? LegacyMigration : null);
|
||||
if (!legacy)
|
||||
{
|
||||
using var provider = new ServiceCollection().AddNotificationDataAccess(builder.ConnectionString).BuildServiceProvider();
|
||||
using var scope = provider.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<INotificationServiceRepository>().SaveAsync(new NotificationServiceInfo
|
||||
{
|
||||
Name = "TestService", Languages = new[] { "en", "uk", "de", "ru", "ru-RU" }
|
||||
.Select(code => new ServiceLanguageInfo { Code = code }).ToList()
|
||||
}, true);
|
||||
}
|
||||
return builder.ConnectionString;
|
||||
}
|
||||
|
||||
public static NotificationDbContext CreateContext(string connectionString) => new(
|
||||
new DbContextOptionsBuilder<NotificationDbContext>().UseNpgsql(connectionString).Options);
|
||||
|
||||
public static async Task ExecuteAsync(string connectionString, string sql)
|
||||
{
|
||||
await using var connection = new NpgsqlConnection(connectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand(sql, connection);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
public static async Task<Guid> InsertLegacyAsync(string connectionString, string language, string variables)
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
await using var connection = new NpgsqlConnection(connectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand("""
|
||||
INSERT INTO email_templates(id, service_name, key, language_code, subject, html_body, text_body, variables, created)
|
||||
VALUES (@id, 'TestService', 'Welcome', @language, @subject, '<p>{{Name}}</p>', 'Hello {{Name}}', @variables, now())
|
||||
""", connection);
|
||||
command.Parameters.AddWithValue("id", id);
|
||||
command.Parameters.AddWithValue("language", language);
|
||||
command.Parameters.AddWithValue("subject", "Subject " + language);
|
||||
command.Parameters.AddWithValue("variables", NpgsqlTypes.NpgsqlDbType.Jsonb, variables);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public static class TemplateEditorTestFields
|
||||
{
|
||||
public static Dictionary<string, string> Read(string html)
|
||||
{
|
||||
var fields = new Dictionary<string, string>();
|
||||
foreach (Match input in Regex.Matches(html, "<input[^>]+>"))
|
||||
{
|
||||
var name = Regex.Match(input.Value, "name=\"([^\"]+)\"");
|
||||
var value = Regex.Match(input.Value, "value=\"([^\"]*)\"");
|
||||
if (name.Success && value.Success)
|
||||
fields[WebUtility.HtmlDecode(name.Groups[1].Value)] = WebUtility.HtmlDecode(value.Groups[1].Value);
|
||||
}
|
||||
foreach (Match textarea in Regex.Matches(html, "<textarea[^>]+name=\"([^\"]+)\"[^>]*>(.*?)</textarea>", RegexOptions.Singleline))
|
||||
fields[WebUtility.HtmlDecode(textarea.Groups[1].Value)] = WebUtility.HtmlDecode(textarea.Groups[2].Value);
|
||||
return fields;
|
||||
}
|
||||
|
||||
public static void SetLanguage(Dictionary<string, string> fields, string code, string subject, string html, string text)
|
||||
{
|
||||
var codeField = fields.Single(p => p.Key.EndsWith(".LanguageCode") && p.Value == code).Key;
|
||||
var prefix = codeField[..^"LanguageCode".Length];
|
||||
fields[prefix + "Subject"] = subject;
|
||||
fields[prefix + "HtmlBody"] = html;
|
||||
fields[prefix + "TextBody"] = text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class TemplateWebApplicationFactory(string connectionString) : WebApplicationFactory<Program>
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseEnvironment("Testing");
|
||||
builder.UseSetting("App:ConnectionString", connectionString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using HrynCo.NotificationService.Contracts.Messages;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using HrynCo.NotificationService.Worker.Services;
|
||||
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||
|
||||
public sealed class WorkerTemplateIntegrationTests(TemplateDatabaseFixture fixture) : IClassFixture<TemplateDatabaseFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task Worker_UsesExactLanguageContentAndCurrentSharedContract()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = new ServiceCollection().AddNotificationDataAccess(connection).AddNotificationWorkerServices().BuildServiceProvider();
|
||||
var codes = new[] { "de", "en", "ru", "uk", "ru-RU" };
|
||||
foreach (var code in codes)
|
||||
await AddVersionAsync(provider, code);
|
||||
foreach (var code in codes)
|
||||
{
|
||||
using var readScope = provider.CreateScope();
|
||||
var template = await readScope.ServiceProvider.GetRequiredService<IEmailTemplateService>().GetAsync("TestService", "Delivery", code, default);
|
||||
var rendered = readScope.ServiceProvider.GetRequiredService<IEmailTemplateRenderingService>().Render(template, Message(code));
|
||||
Assert.Equal(code + " A < B", rendered.Subject);
|
||||
Assert.Equal("<p>A < B</p>", rendered.HtmlBody);
|
||||
Assert.Equal("A < B", rendered.TextBody);
|
||||
}
|
||||
using (var updateScope = provider.CreateScope())
|
||||
{
|
||||
var definitions = updateScope.ServiceProvider.GetRequiredService<IEmailTemplateDefinitionRepository>();
|
||||
var definition = (await definitions.GetDefinitionAsync("TestService", "Delivery"))!;
|
||||
definition.Variables = [new EmailTemplateVariable { Name = "Extra", Required = true }];
|
||||
await definitions.SaveDefinitionAsync(definition, false);
|
||||
}
|
||||
using var finalScope = provider.CreateScope();
|
||||
var loader = finalScope.ServiceProvider.GetRequiredService<IEmailTemplateService>();
|
||||
var updated = await loader.GetAsync("TestService", "Delivery", "ru-RU", default);
|
||||
var error = Assert.Throws<InvalidDataException>(() => finalScope.ServiceProvider.GetRequiredService<IEmailTemplateRenderingService>().Render(updated, Message("ru-RU")));
|
||||
Assert.Contains("Extra", error.Message);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => loader.GetAsync("TestService", "Delivery", "RU-ru", default));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => loader.GetAsync("TestService", "Missing", "en", default));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Worker_CompatibilityRetryPreservesExactVersionPriorityAndRepositoryCodes()
|
||||
{
|
||||
var connection = await fixture.CreateDatabaseAsync();
|
||||
using var provider = new ServiceCollection().AddNotificationDataAccess(connection).AddNotificationWorkerServices().BuildServiceProvider();
|
||||
await AddVersionAsync(provider, "ru");
|
||||
await AddVersionAsync(provider, "ru-RU");
|
||||
using (var legacyScope = provider.CreateScope())
|
||||
{
|
||||
var loader = legacyScope.ServiceProvider.GetRequiredService<IEmailTemplateService>();
|
||||
Assert.Equal("ru", (await loader.GetAsync("TestService", "Delivery", "RU", default)).LanguageCode);
|
||||
Assert.Equal("ru", (await loader.GetAsync("TestService", "Delivery", " ru ", default)).LanguageCode);
|
||||
Assert.Null(await legacyScope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>().GetAsync("TestService", "Delivery", "RU"));
|
||||
}
|
||||
using (var catalogScope = provider.CreateScope())
|
||||
{
|
||||
var services = catalogScope.ServiceProvider.GetRequiredService<INotificationServiceRepository>();
|
||||
var service = (await services.GetAllAsync()).Single(s => s.Name == "TestService");
|
||||
service.Languages = [..service.Languages, new ServiceLanguageInfo { Code = "RU" }];
|
||||
await services.SaveAsync(service, false);
|
||||
}
|
||||
await AddVersionAsync(provider, "RU");
|
||||
using var exactScope = provider.CreateScope();
|
||||
var exactLoader = exactScope.ServiceProvider.GetRequiredService<IEmailTemplateService>();
|
||||
Assert.Equal("RU", (await exactLoader.GetAsync("TestService", "Delivery", "RU", default)).LanguageCode);
|
||||
Assert.Equal("ru-RU", (await exactLoader.GetAsync("TestService", "Delivery", "ru-RU", default)).LanguageCode);
|
||||
Assert.Equal("ru", (await exactLoader.GetAsync("TestService", "Delivery", "ru", default)).LanguageCode);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => exactLoader.GetAsync("TestService", "Delivery", "RU-ru", default));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => exactLoader.GetAsync("TestService", "Delivery", "zz", default));
|
||||
}
|
||||
|
||||
private static async Task AddVersionAsync(ServiceProvider provider, string code)
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<IEmailTemplateRepository>().AddAsync(new EmailTemplate
|
||||
{
|
||||
ServiceName = "TestService", Key = "Delivery", LanguageCode = code,
|
||||
Subject = code + " {{Name}}", HtmlBody = "<p>{{Name}}</p>", TextBody = "{{Name}}",
|
||||
Variables = [new EmailTemplateVariable { Name = "Name", Required = true }]
|
||||
});
|
||||
}
|
||||
|
||||
private static SendEmailMessageData Message(string code) => new()
|
||||
{
|
||||
ServiceName = "TestService", TemplateKey = "Delivery", LanguageCode = code,
|
||||
RecipientEmail = "test@example.invalid", RecipientName = "Test", Variables = new Dictionary<string, string> { ["Name"] = "A < B" }
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user