feat: add MVC Razor admin UI for email templates

- GetAllEmailTemplatesQuery + handler (new GetAll use case)
- IEmailTemplateRepository.GetAllAsync + EF implementation
- AdminTemplatesController: Index, Create, Edit, Save, Delete
- EmailTemplateEditViewModel with IsNew/PageTitle helpers
- Views/_ViewStart, _ViewImports, Shared/_Layout (Bootstrap 5)
- Shared/_EditorLayout (chained layout for all edit screens)
- Views/AdminTemplates/Index (table with edit/delete actions)
- Views/AdminTemplates/Edit (card form, readonly composite key on edit)
- Program.cs: AddControllersWithViews, UseStaticFiles, MapDefaultControllerRoute

Ref: IT-634

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Anatolii Grynchuk
2026-05-02 02:06:08 +03:00
parent cec8f42ece
commit 2a0a5f737d
13 changed files with 432 additions and 1 deletions
@@ -4,6 +4,7 @@ namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
public interface IEmailTemplateRepository public interface IEmailTemplateRepository
{ {
Task<IReadOnlyList<EmailTemplate>> GetAllAsync(CancellationToken ct = default);
Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default); Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default);
Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default); Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default);
Task AddAsync(EmailTemplate template, CancellationToken ct = default); Task AddAsync(EmailTemplate template, CancellationToken ct = default);
@@ -12,6 +12,12 @@ internal sealed class EmailTemplateRepository : EfRepository<EmailTemplateEntity
{ {
} }
public async Task<IReadOnlyList<EmailTemplate>> GetAllAsync(CancellationToken ct = default)
{
List<EmailTemplateEntity> entities = await DbSet.ToListAsync(ct);
return entities.Select(MapToDomain).ToList();
}
public async Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default) public async Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
{ {
List<EmailTemplateEntity> entities = await DbSet List<EmailTemplateEntity> entities = await DbSet
@@ -0,0 +1,30 @@
using HrynCo.NotificationService.DAL.Abstract;
using HrynCo.NotificationService.DAL.Abstract.Repositories;
using HrynCo.NotificationService.DAL.Abstract.Templates;
using HrynCo.NotificationService.Services.Core;
using HrynCo.NotificationService.Services.Logging;
using static HrynCo.NotificationService.Services.Core.ServiceResultHelper;
namespace HrynCo.NotificationService.Services.EmailTemplates.GetAll;
internal sealed class GetAllEmailTemplatesHandler
: RequestHandler<GetAllEmailTemplatesQuery, ServiceResult<IReadOnlyList<EmailTemplate>>>
{
private readonly IEmailTemplateRepository _templates;
public GetAllEmailTemplatesHandler(
IContextualSerilogLogger<GetAllEmailTemplatesQuery> logger,
IUnitOfWork unitOfWork,
IEmailTemplateRepository templates)
: base(logger, unitOfWork)
{
_templates = templates;
}
protected override async Task<ServiceResult<IReadOnlyList<EmailTemplate>>> DoOnHandle(
GetAllEmailTemplatesQuery request, CancellationToken cancellationToken)
{
var templates = await _templates.GetAllAsync(cancellationToken);
return Success(templates);
}
}
@@ -0,0 +1,7 @@
using HrynCo.NotificationService.DAL.Abstract.Templates;
using MediatR;
using HrynCo.NotificationService.Services.Core;
namespace HrynCo.NotificationService.Services.EmailTemplates.GetAll;
public sealed record GetAllEmailTemplatesQuery : IRequest<ServiceResult<IReadOnlyList<EmailTemplate>>>;
@@ -0,0 +1,138 @@
using System.Text.Json;
using HrynCo.NotificationService.DAL.Abstract.Templates;
using HrynCo.NotificationService.Services.EmailTemplates.Create;
using HrynCo.NotificationService.Services.EmailTemplates.Delete;
using HrynCo.NotificationService.Services.EmailTemplates.Get;
using HrynCo.NotificationService.Services.EmailTemplates.GetAll;
using HrynCo.NotificationService.Services.EmailTemplates.Update;
using HrynCo.NotificationService.Web.Controllers.Admin.ViewModels;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace HrynCo.NotificationService.Web.Controllers.Admin;
[Route("admin/templates")]
public class AdminTemplatesController : Controller
{
private readonly IMediator _mediator;
public AdminTemplatesController(IMediator mediator)
{
_mediator = mediator;
}
// GET /admin/templates
[HttpGet("")]
public async Task<IActionResult> Index(CancellationToken ct)
{
var result = await _mediator.Send(new GetAllEmailTemplatesQuery(), ct);
if (!result.IsSuccess)
{
ModelState.AddModelError("", result.Error?.Message ?? "Failed to load templates.");
return View(Array.Empty<EmailTemplate>());
}
return View(result.Result);
}
// GET /admin/templates/create
[HttpGet("create")]
public IActionResult Create()
{
return View("Edit", new EmailTemplateEditViewModel());
}
// GET /admin/templates/{serviceName}/{key}/{languageCode}
[HttpGet("{serviceName}/{key}/{languageCode}")]
public async Task<IActionResult> Edit(string serviceName, string key, string languageCode, CancellationToken ct)
{
var result = await _mediator.Send(new GetEmailTemplateQuery(serviceName, key, languageCode), ct);
if (!result.IsSuccess || result.Result is null)
return NotFound();
var template = result.Result;
var vm = new EmailTemplateEditViewModel
{
Id = template.Id,
ServiceName = template.ServiceName,
Key = template.Key,
LanguageCode = template.LanguageCode,
Subject = template.Subject,
HtmlBody = template.HtmlBody,
TextBody = template.TextBody,
VariablesJson = JsonSerializer.Serialize(template.Variables)
};
return View(vm);
}
// POST /admin/templates/save
[HttpPost("save")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Save(EmailTemplateEditViewModel model, CancellationToken ct)
{
if (!ModelState.IsValid)
return View("Edit", model);
List<EmailTemplateVariable> variables;
try
{
variables = JsonSerializer.Deserialize<List<EmailTemplateVariable>>(model.VariablesJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? [];
}
catch (JsonException)
{
ModelState.AddModelError(nameof(model.VariablesJson), "Invalid JSON format for variables.");
return View("Edit", model);
}
if (model.IsNew)
{
var command = new CreateEmailTemplateCommand(
model.ServiceName,
model.Key,
model.LanguageCode,
model.Subject,
model.HtmlBody,
model.TextBody,
variables);
var result = await _mediator.Send(command, ct);
if (!result.IsSuccess)
{
ModelState.AddModelError("", result.Error?.Message ?? "Failed to create template.");
return View("Edit", model);
}
}
else
{
var command = new UpdateEmailTemplateCommand(
model.ServiceName,
model.Key,
model.LanguageCode,
model.Subject,
model.HtmlBody,
model.TextBody,
variables);
var result = await _mediator.Send(command, ct);
if (!result.IsSuccess)
{
ModelState.AddModelError("", result.Error?.Message ?? "Failed to update template.");
return View("Edit", model);
}
}
return RedirectToAction(nameof(Index));
}
// POST /admin/templates/{serviceName}/{key}/{languageCode}/delete
[HttpPost("{serviceName}/{key}/{languageCode}/delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(string serviceName, string key, string languageCode, CancellationToken ct)
{
await _mediator.Send(new DeleteEmailTemplateCommand(serviceName, key, languageCode), ct);
return RedirectToAction(nameof(Index));
}
}
@@ -0,0 +1,31 @@
using System.ComponentModel.DataAnnotations;
namespace HrynCo.NotificationService.Web.Controllers.Admin.ViewModels;
public class EmailTemplateEditViewModel
{
public Guid? Id { get; set; }
[Required]
public string ServiceName { get; set; } = "";
[Required]
public string Key { get; set; } = "";
[Required]
public string LanguageCode { get; set; } = "";
[Required]
public string Subject { get; set; } = "";
[Required]
public string HtmlBody { get; set; } = "";
public string TextBody { get; set; } = "";
// JSON array: [{"name":"UserName","required":true}, ...]
public string VariablesJson { get; set; } = "[]";
public bool IsNew => Id == null;
public string PageTitle => IsNew ? "Create Email Template" : "Edit Email Template";
}
+3 -1
View File
@@ -13,7 +13,7 @@ var appSettings = builder.Configuration
builder.Services.AddSingleton(appSettings); builder.Services.AddSingleton(appSettings);
builder.Services.AddOpenApi(); builder.Services.AddOpenApi();
builder.Services.AddControllers(); builder.Services.AddControllersWithViews();
builder.Services.AddNotificationDataAccess(appSettings.ConnectionString); builder.Services.AddNotificationDataAccess(appSettings.ConnectionString);
builder.Services.AddNotificationServices(); builder.Services.AddNotificationServices();
@@ -29,6 +29,8 @@ if (app.Environment.IsDevelopment())
}); });
} }
app.UseStaticFiles();
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.MapControllers(); app.MapControllers();
app.MapDefaultControllerRoute();
app.Run(); app.Run();
@@ -0,0 +1,71 @@
@using HrynCo.NotificationService.Web.Controllers.Admin.ViewModels
@model EmailTemplateEditViewModel
@{
Layout = "~/Views/Shared/_EditorLayout.cshtml";
ViewData["Title"] = Model.PageTitle;
ViewData["EditorTitle"] = Model.PageTitle;
}
<form asp-action="Save" asp-controller="AdminTemplates" method="post">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<input type="hidden" name="IsNew" value="@Model.IsNew" />
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger mb-3">
@foreach (var error in ViewData.ModelState.Values.SelectMany(v => v.Errors))
{
<div>@error.ErrorMessage</div>
}
</div>
}
<div class="mb-3">
<label asp-for="ServiceName" class="form-label fw-semibold">Service Name</label>
<input asp-for="ServiceName" class="form-control" readonly="@(!Model.IsNew)" />
<span asp-validation-for="ServiceName" class="text-danger small"></span>
</div>
<div class="mb-3">
<label asp-for="Key" class="form-label fw-semibold">Key</label>
<input asp-for="Key" class="form-control" readonly="@(!Model.IsNew)" />
<span asp-validation-for="Key" class="text-danger small"></span>
</div>
<div class="mb-3">
<label asp-for="LanguageCode" class="form-label fw-semibold">Language Code</label>
<input asp-for="LanguageCode" class="form-control" readonly="@(!Model.IsNew)" />
<span asp-validation-for="LanguageCode" class="text-danger small"></span>
</div>
<div class="mb-3">
<label asp-for="Subject" class="form-label fw-semibold">Subject</label>
<input asp-for="Subject" class="form-control" />
<span asp-validation-for="Subject" class="text-danger small"></span>
</div>
<div class="mb-3">
<label asp-for="HtmlBody" class="form-label fw-semibold">HTML Body</label>
<textarea asp-for="HtmlBody" class="form-control font-monospace" rows="10"></textarea>
<span asp-validation-for="HtmlBody" class="text-danger small"></span>
</div>
<div class="mb-3">
<label asp-for="TextBody" class="form-label fw-semibold">Text Body</label>
<textarea asp-for="TextBody" class="form-control font-monospace" rows="5"></textarea>
</div>
<div class="mb-3">
<label asp-for="VariablesJson" class="form-label fw-semibold">Variables (JSON)</label>
<textarea asp-for="VariablesJson" class="form-control font-monospace" rows="4"
placeholder='[{"name":"UserName","required":true}]'></textarea>
<span asp-validation-for="VariablesJson" class="text-danger small"></span>
<div class="form-text">JSON array of <code>{"name":"...", "required":true|false}</code></div>
</div>
@section FormActions {
<button type="submit" class="btn btn-primary">💾 Save</button>
<a href="/admin/templates" class="btn btn-secondary">✖ Cancel</a>
}
</form>
@@ -0,0 +1,68 @@
@using HrynCo.NotificationService.DAL.Abstract.Templates
@model IReadOnlyList<EmailTemplate>
@{
ViewData["Title"] = "Email Templates";
}
<div class="d-flex justify-content-between align-items-center mb-4">
<h2 class="mb-0">📋 Email Templates</h2>
<a href="/admin/templates/create" class="btn btn-primary">+ Create New Template</a>
</div>
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger">
@foreach (var error in ViewData.ModelState.Values.SelectMany(v => v.Errors))
{
<div>@error.ErrorMessage</div>
}
</div>
}
@if (Model is null || Model.Count == 0)
{
<div class="alert alert-info">No email templates found.</div>
}
else
{
<div class="card shadow-sm">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-dark">
<tr>
<th>Service Name</th>
<th>Key</th>
<th>Language</th>
<th>Subject</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var t in Model)
{
<tr>
<td>@t.ServiceName</td>
<td>@t.Key</td>
<td>@t.LanguageCode</td>
<td>@t.Subject</td>
<td class="text-end">
<a href="/admin/templates/@t.ServiceName/@t.Key/@t.LanguageCode"
class="btn btn-sm btn-outline-primary me-1">✏️ Edit</a>
<form method="post"
action="/admin/templates/@t.ServiceName/@t.Key/@t.LanguageCode/delete"
class="d-inline">
@Html.AntiForgeryToken()
<button type="submit"
class="btn btn-sm btn-outline-danger"
onclick="return confirm('Delete this template?')">
🗑️ Delete
</button>
</form>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
@@ -0,0 +1,14 @@
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="card shadow-sm">
<div class="card-header bg-primary text-white">
<h5 class="mb-0">@ViewData["EditorTitle"]</h5>
</div>
<div class="card-body">
@RenderBody()
</div>
<div class="card-footer d-flex gap-2">
@RenderSection("FormActions", required: false)
</div>
</div>
@@ -0,0 +1,57 @@
@{
var currentController = ViewContext.RouteData.Values["controller"]?.ToString() ?? "";
bool isTemplates = currentController.Equals("AdminTemplates", StringComparison.OrdinalIgnoreCase);
bool isChannels = currentController.Equals("AdminChannels", StringComparison.OrdinalIgnoreCase);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>@ViewData["Title"] Notification Service</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous" />
<style>
body { background-color: #f8f9fa; }
.sidebar { min-height: calc(100vh - 56px); background-color: #212529; padding-top: 1rem; }
.sidebar .nav-link { color: #adb5bd; border-radius: .375rem; margin-bottom: .25rem; }
.sidebar .nav-link:hover { color: #fff; background-color: #343a40; }
.sidebar .nav-link.active { color: #fff; background-color: #0d6efd; }
.main-content { padding: 2rem; }
</style>
</head>
<body>
<nav class="navbar navbar-dark bg-dark px-3">
<a class="navbar-brand fw-bold" href="/">📧 Notification Service</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-md-2 d-none d-md-block sidebar py-3">
<ul class="nav flex-column px-2">
<li class="nav-item">
<a class="nav-link @(isTemplates ? "active" : "")" href="/admin/templates">
📋 Email Templates
</a>
</li>
<li class="nav-item">
<a class="nav-link @(isChannels ? "active" : "")" href="/admin/channels">
📡 Email Channels
</a>
</li>
</ul>
</nav>
<main class="col-md-10 ms-sm-auto main-content">
@RenderBody()
</main>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc4s9bIOgUxi8T/jzmGBE+rYG8O9HP+CyEb1BQGE8B8Z"
crossorigin="anonymous"></script>
</body>
</html>
@@ -0,0 +1,3 @@
@using HrynCo.NotificationService.Web
@using HrynCo.NotificationService.Web.Controllers.Admin
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@@ -0,0 +1,3 @@
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}