feat(notification): add admin rest management and deletion
Add revision-safe service and template APIs, channel mapping, and validated admin controls. Ref: IT-1601
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
using HrynCo.NotificationService.Services.TemplateDefinitions;
|
||||
using MediatR;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.Web.Controllers.Admin.ViewModels;
|
||||
@@ -6,7 +8,8 @@ using Microsoft.AspNetCore.Mvc;
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Admin;
|
||||
|
||||
[Route("admin/services")]
|
||||
public sealed class AdminServicesController(INotificationServiceRepository services, ILogger<AdminServicesController> logger) : Controller
|
||||
public sealed class AdminServicesController(INotificationServiceRepository services, ILogger<AdminServicesController> logger,
|
||||
IEmailTemplateDefinitionRepository definitions, IMediator mediator) : Controller
|
||||
{
|
||||
[HttpGet("")]
|
||||
public async Task<IActionResult> Index(CancellationToken ct) => View(await services.GetAllAsync(ct));
|
||||
@@ -77,6 +80,55 @@ public sealed class AdminServicesController(INotificationServiceRepository servi
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{serviceId:guid}/delete")]
|
||||
public async Task<IActionResult> ConfirmServiceDelete([FromRoute] Guid serviceId, CancellationToken ct)
|
||||
{
|
||||
var model = await ServiceDeleteModelAsync(serviceId, ct);
|
||||
return model is null ? NotFound() : View("DeleteService", model);
|
||||
}
|
||||
|
||||
[HttpPost("{serviceId:guid}/delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> DeleteService([FromRoute] Guid serviceId, NotificationServiceDeleteViewModel model, CancellationToken ct)
|
||||
{
|
||||
if (!ModelState.IsValid || !model.ConfirmDelete)
|
||||
return await ServiceDeleteErrorAsync(serviceId, "Confirm deletion of this service to continue.", ct);
|
||||
try
|
||||
{
|
||||
var result = await mediator.Send(new DeleteNotificationServiceCommand(serviceId, model.Revision), ct);
|
||||
if (result.IsSuccess)
|
||||
return RedirectToAction(nameof(Index));
|
||||
return await ServiceDeleteErrorAsync(serviceId, result.Error!.Message, ct);
|
||||
}
|
||||
catch (Exception error) when (error is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(error, "Failed to delete notification service.");
|
||||
return await ServiceDeleteErrorAsync(serviceId, "Could not complete deletion. Review the current service before trying again.", ct);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<NotificationServiceDeleteViewModel?> ServiceDeleteModelAsync(Guid serviceId, CancellationToken ct)
|
||||
{
|
||||
var service = await services.GetAsync(serviceId, ct);
|
||||
if (service is null)
|
||||
return null;
|
||||
return new NotificationServiceDeleteViewModel
|
||||
{
|
||||
ServiceId = service.Id, Name = service.Name, Revision = service.Revision,
|
||||
DefinitionCount = (await definitions.GetDefinitionsAsync(serviceId, ct)).Count
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IActionResult> ServiceDeleteErrorAsync(Guid serviceId, string error, CancellationToken ct)
|
||||
{
|
||||
var model = await ServiceDeleteModelAsync(serviceId, ct);
|
||||
if (model is null)
|
||||
return NotFound();
|
||||
ModelState.Clear();
|
||||
ModelState.AddModelError("", error);
|
||||
return View("DeleteService", model);
|
||||
}
|
||||
|
||||
private async Task<IActionResult> ServiceEditorViewAsync(NotificationServiceEditViewModel model, CancellationToken ct)
|
||||
{
|
||||
if (model.Id is not Guid id)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using HrynCo.NotificationService.Services.TemplateDefinitions;
|
||||
using System.Text.Json;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
@@ -95,6 +96,59 @@ public sealed class AdminTemplatesController(IMediator mediator, IEmailTemplateD
|
||||
return RedirectToAction(nameof(Index), new { serviceId, key = keyFilter });
|
||||
}
|
||||
|
||||
[HttpGet("{definitionId:guid}/delete")]
|
||||
public async Task<IActionResult> ConfirmDefinitionDelete([FromRoute] Guid serviceId, [FromRoute] Guid definitionId,
|
||||
[FromQuery] string? keyFilter, CancellationToken ct)
|
||||
{
|
||||
var model = await DefinitionDeleteModelAsync(serviceId, definitionId, keyFilter, ct);
|
||||
return model is null ? NotFound() : View("DeleteDefinition", model);
|
||||
}
|
||||
|
||||
[HttpPost("{definitionId:guid}/delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> DeleteDefinition([FromRoute] Guid serviceId, [FromRoute] Guid definitionId,
|
||||
EmailTemplateDefinitionDeleteViewModel model, CancellationToken ct)
|
||||
{
|
||||
var current = await DefinitionDeleteModelAsync(serviceId, definitionId, model.KeyFilter, ct);
|
||||
if (current is null)
|
||||
return NotFound();
|
||||
if (!ModelState.IsValid || !model.ConfirmDelete)
|
||||
return await DefinitionDeleteErrorAsync(serviceId, definitionId, model.KeyFilter, "Confirm deletion of this template and its translations to continue.", ct);
|
||||
try
|
||||
{
|
||||
var result = await mediator.Send(new DeleteEmailTemplateDefinitionCommand(serviceId, current.Key, model.Revision), ct);
|
||||
if (result.IsSuccess)
|
||||
return RedirectToAction(nameof(Index), new { serviceId, key = model.KeyFilter });
|
||||
return await DefinitionDeleteErrorAsync(serviceId, definitionId, model.KeyFilter, result.Error!.Message, ct);
|
||||
}
|
||||
catch (Exception error) when (error is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(error, "Failed to delete email template definition.");
|
||||
return await DefinitionDeleteErrorAsync(serviceId, definitionId, model.KeyFilter, "Could not complete deletion. Review the current template before trying again.", ct);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<EmailTemplateDefinitionDeleteViewModel?> DefinitionDeleteModelAsync(Guid serviceId, Guid definitionId, string? keyFilter, CancellationToken ct)
|
||||
{
|
||||
var service = await services.GetAsync(serviceId, ct);
|
||||
var definition = await OwnedDefinitionAsync(service, definitionId, ct);
|
||||
return definition is null ? null : new EmailTemplateDefinitionDeleteViewModel
|
||||
{
|
||||
ServiceId = serviceId, DefinitionId = definition.Id, ServiceName = definition.ServiceName, Key = definition.Key,
|
||||
Revision = definition.Revision, KeyFilter = keyFilter, LanguageCodes = definition.Languages.Select(l => l.LanguageCode).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IActionResult> DefinitionDeleteErrorAsync(Guid serviceId, Guid definitionId, string? keyFilter, string error, CancellationToken ct)
|
||||
{
|
||||
var model = await DefinitionDeleteModelAsync(serviceId, definitionId, keyFilter, ct);
|
||||
if (model is null)
|
||||
return NotFound();
|
||||
ModelState.Clear();
|
||||
ModelState.AddModelError("", error);
|
||||
return View("DeleteDefinition", model);
|
||||
}
|
||||
|
||||
private async Task<IActionResult> SaveDefinitionAsync(EmailTemplateDefinition definition, EmailTemplateEditViewModel model,
|
||||
NotificationServiceInfo service, CancellationToken ct)
|
||||
{
|
||||
@@ -117,7 +171,7 @@ public sealed class AdminTemplatesController(IMediator mediator, IEmailTemplateD
|
||||
{
|
||||
if (service is null)
|
||||
return null;
|
||||
return (await definitions.GetDefinitionsAsync(service.Name, ct: ct))
|
||||
return (await definitions.GetDefinitionsAsync(service.Id, ct))
|
||||
.SingleOrDefault(d => d.Id == definitionId && d.ServiceId == service.Id);
|
||||
}
|
||||
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Admin.ViewModels;
|
||||
|
||||
public sealed class EmailTemplateDefinitionDeleteViewModel
|
||||
{
|
||||
public Guid ServiceId { get; init; }
|
||||
public Guid DefinitionId { get; init; }
|
||||
public string ServiceName { get; init; } = "";
|
||||
public string Key { get; init; } = "";
|
||||
public Guid Revision { get; set; }
|
||||
public string? KeyFilter { get; set; }
|
||||
public IReadOnlyList<string> LanguageCodes { get; init; } = [];
|
||||
public bool ConfirmDelete { get; set; }
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Admin.ViewModels;
|
||||
|
||||
public sealed class NotificationServiceDeleteViewModel
|
||||
{
|
||||
public Guid ServiceId { get; init; }
|
||||
public string Name { get; init; } = "";
|
||||
public Guid Revision { get; set; }
|
||||
public int DefinitionCount { get; init; }
|
||||
public bool ConfirmDelete { get; set; }
|
||||
}
|
||||
+3
-2
@@ -1,12 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.EmailChannels;
|
||||
|
||||
public sealed record CreateEmailChannelRequest(
|
||||
string ServiceName,
|
||||
[Required, StringLength(100)] string ServiceName,
|
||||
int Priority,
|
||||
EmailChannelType ChannelType,
|
||||
EmailChannelSettings Settings,
|
||||
SmtpChannelSettingsDto Settings,
|
||||
int? DailyLimit,
|
||||
int? MonthlyLimit,
|
||||
int WarnThresholdPercent,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.EmailChannels;
|
||||
|
||||
public sealed record EmailChannelDto(Guid Id, string ServiceName, int Priority, EmailChannelType EmailChannelType,
|
||||
SmtpChannelSettingsDto Settings, int? DailyLimit, int? MonthlyLimit, int WarnThresholdPercent,
|
||||
bool IsActive, DateTimeOffset Created, DateTimeOffset? Updated);
|
||||
@@ -0,0 +1,23 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.EmailChannels;
|
||||
|
||||
internal static class EmailChannelMapping
|
||||
{
|
||||
public static SmtpChannelSettings ToSettings(SmtpChannelSettingsDto settings) => new()
|
||||
{
|
||||
Host = settings.Host, Port = settings.Port, Username = settings.Username, Password = settings.Password,
|
||||
UseSsl = settings.UseSsl, FromEmail = settings.FromEmail, FromName = settings.FromName
|
||||
};
|
||||
|
||||
public static EmailChannelDto Map(EmailChannel channel)
|
||||
{
|
||||
var smtp = (SmtpChannelSettings)channel.Settings;
|
||||
return new EmailChannelDto(channel.Id, channel.ServiceName, channel.Priority, channel.EmailChannelType,
|
||||
new SmtpChannelSettingsDto
|
||||
{
|
||||
Host = smtp.Host, Port = smtp.Port, Username = smtp.Username, Password = smtp.Password,
|
||||
UseSsl = smtp.UseSsl, FromEmail = smtp.FromEmail, FromName = smtp.FromName
|
||||
}, channel.DailyLimit, channel.MonthlyLimit, channel.WarnThresholdPercent, channel.IsActive, channel.Created, channel.Updated);
|
||||
}
|
||||
}
|
||||
+28
-7
@@ -1,8 +1,12 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
using HrynCo.NotificationService.Services.Core;
|
||||
using HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
using HrynCo.NotificationService.Web.Infrastructure;
|
||||
using HrynCo.NotificationService.Services.EmailChannels.Create;
|
||||
using HrynCo.NotificationService.Services.EmailChannels.Delete;
|
||||
using HrynCo.NotificationService.Services.EmailChannels.Get;
|
||||
using HrynCo.NotificationService.Services.EmailChannels.GetByService;
|
||||
using HrynCo.NotificationService.Services.EmailChannels.GetAll;
|
||||
using HrynCo.NotificationService.Services.EmailChannels.Update;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -10,32 +14,44 @@ using Microsoft.AspNetCore.Mvc;
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.EmailChannels;
|
||||
|
||||
[Route("api/v1/email-channels")]
|
||||
[TypeFilter(typeof(ApiRequestValidationFilter), Order = -3000)]
|
||||
public sealed class EmailChannelsController : ApiControllerBase
|
||||
{
|
||||
public EmailChannelsController(IMediator mediator) : base(mediator) { }
|
||||
|
||||
[HttpGet]
|
||||
[ProducesResponseType<ApiResponse<IReadOnlyList<EmailChannelDto>>>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetAll([FromQuery] string serviceName, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await Mediator.Send(new GetEmailChannelsQuery(serviceName), cancellationToken);
|
||||
return FromServiceResult(result);
|
||||
return FromChannels(result);
|
||||
}
|
||||
|
||||
[HttpGet("all")]
|
||||
[ProducesResponseType<ApiResponse<IReadOnlyList<EmailChannelDto>>>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetAllServices(CancellationToken cancellationToken) =>
|
||||
FromChannels(await Mediator.Send(new GetAllEmailChannelsQuery(), cancellationToken));
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> Get(Guid id, CancellationToken cancellationToken)
|
||||
[ProducesResponseType<ApiResponse<EmailChannelDto>>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Get([FromRoute] Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await Mediator.Send(new GetEmailChannelQuery(id), cancellationToken);
|
||||
return FromServiceResult(result);
|
||||
return result.IsSuccess
|
||||
? Ok(new ApiResponse<EmailChannelDto> { Success = true, Data = EmailChannelMapping.Map(result.Result!) })
|
||||
: MapServiceError(result.Error!);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateEmailChannelRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.ChannelType != EmailChannelType.Smtp)
|
||||
return MapServiceError(new ServiceError("Only SMTP channels are supported.", ServiceErrorCode.InvalidRequest));
|
||||
var command = new CreateEmailChannelCommand(
|
||||
request.ServiceName,
|
||||
request.Priority,
|
||||
request.ChannelType,
|
||||
request.Settings,
|
||||
EmailChannelMapping.ToSettings(request.Settings),
|
||||
request.DailyLimit,
|
||||
request.MonthlyLimit,
|
||||
request.WarnThresholdPercent,
|
||||
@@ -52,12 +68,12 @@ public sealed class EmailChannelsController : ApiControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateEmailChannelRequest request, CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] UpdateEmailChannelRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var command = new UpdateEmailChannelCommand(
|
||||
id,
|
||||
request.Priority,
|
||||
request.Settings,
|
||||
EmailChannelMapping.ToSettings(request.Settings),
|
||||
request.DailyLimit,
|
||||
request.MonthlyLimit,
|
||||
request.WarnThresholdPercent,
|
||||
@@ -69,9 +85,14 @@ public sealed class EmailChannelsController : ApiControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> Delete([FromRoute] Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await Mediator.Send(new DeleteEmailChannelCommand(id), cancellationToken);
|
||||
return FromServiceResult(result);
|
||||
}
|
||||
private IActionResult FromChannels(ServiceResult<IReadOnlyList<EmailChannel>> result) =>
|
||||
result.IsSuccess
|
||||
? Ok(new ApiResponse<IReadOnlyList<EmailChannelDto>> { Success = true, Data = result.Result!.Select(EmailChannelMapping.Map).ToList() })
|
||||
: MapServiceError(result.Error!);
|
||||
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.EmailChannels;
|
||||
|
||||
public sealed class SmtpChannelSettingsDto
|
||||
{
|
||||
public EmailChannelType EmailChannelType => EmailChannelType.Smtp;
|
||||
[Required]
|
||||
public string Host { get; init; } = "";
|
||||
[Range(1, 65535)]
|
||||
public int Port { get; init; } = 587;
|
||||
public string Username { get; init; } = "";
|
||||
public string Password { get; init; } = "";
|
||||
public bool UseSsl { get; init; } = true;
|
||||
[Required, EmailAddress]
|
||||
public string FromEmail { get; init; } = "";
|
||||
public string FromName { get; init; } = "";
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ namespace HrynCo.NotificationService.Web.Controllers.Api.EmailChannels;
|
||||
|
||||
public sealed record UpdateEmailChannelRequest(
|
||||
int Priority,
|
||||
EmailChannelSettings Settings,
|
||||
SmtpChannelSettingsDto Settings,
|
||||
int? DailyLimit,
|
||||
int? MonthlyLimit,
|
||||
int WarnThresholdPercent,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using HrynCo.NotificationService.Web.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
// Runs before ApiController's default model-state filter, only for these endpoints.
|
||||
public sealed class ApiRequestValidationFilter : IActionFilter
|
||||
{
|
||||
public void OnActionExecuting(ActionExecutingContext context)
|
||||
{
|
||||
if (context.ModelState.IsValid)
|
||||
return;
|
||||
var errors = context.ModelState.SelectMany(field => field.Value!.Errors.Select(error =>
|
||||
string.IsNullOrWhiteSpace(error.ErrorMessage) ? "Invalid JSON value at " + field.Key + "." : error.ErrorMessage));
|
||||
context.Result = new BadRequestObjectResult(new ApiResponse<object>
|
||||
{
|
||||
Success = false, Error = new ApiError { Code = "InvalidRequest", Message = string.Join(" ", errors) }
|
||||
});
|
||||
}
|
||||
|
||||
public void OnActionExecuted(ActionExecutedContext context) { }
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class CreateNotificationServiceRequest
|
||||
{
|
||||
public required string Name { get; init; }
|
||||
public required IReadOnlyList<ServiceLanguageRequest> Languages { get; init; }
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class DeleteServiceLanguageVersionsRequest
|
||||
{
|
||||
[JsonRequired]
|
||||
public Guid Revision { get; init; }
|
||||
[JsonRequired]
|
||||
public int ExpectedVersionCount { get; init; }
|
||||
[JsonRequired]
|
||||
public bool ConfirmDelete { get; init; }
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
using Unit = HrynCo.NotificationService.Services.Core.Unit;
|
||||
using HrynCo.NotificationService.Web.Infrastructure;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.Services.Core;
|
||||
using HrynCo.NotificationService.Services.TemplateDefinitions;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
[Route("api/v1/services/{serviceId:guid}/email-template-definitions")]
|
||||
[TypeFilter(typeof(ApiRequestValidationFilter), Order = -3000)]
|
||||
public sealed class EmailTemplateDefinitionsController(IMediator mediator) : ApiControllerBase(mediator)
|
||||
{
|
||||
[HttpGet]
|
||||
[ProducesResponseType<ApiResponse<EmailTemplateDefinitionDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Get([FromRoute] Guid serviceId, [FromQuery] string key, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new GetEmailTemplateDefinitionQuery(serviceId, key), cancellationToken));
|
||||
|
||||
[HttpPost("upsert")]
|
||||
[ProducesResponseType<ApiResponse<EmailTemplateDefinitionDto>>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ApiResponse<EmailTemplateDefinitionDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Upsert([FromRoute] Guid serviceId, [FromQuery] string key,
|
||||
[FromBody] UpsertTemplateDefinitionRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var patch = request.ToPatch(serviceId, key);
|
||||
var result = await Mediator.Send(new UpsertEmailTemplateDefinitionCommand(patch), cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
return MapServiceError(result.Error!);
|
||||
if (patch.Revision is null)
|
||||
return CreatedAtAction(nameof(Get), new { serviceId, key },
|
||||
new ApiResponse<EmailTemplateDefinitionDto> { Success = true, Data = result.Result });
|
||||
return FromServiceResult(result);
|
||||
}
|
||||
catch (EmailTemplateWriteException error)
|
||||
{
|
||||
return MapServiceError(new ServiceError(error.Message, ServiceErrorCode.InvalidRequest));
|
||||
}
|
||||
}
|
||||
[HttpGet("all")]
|
||||
[ProducesResponseType<ApiResponse<IReadOnlyList<EmailTemplateDefinitionDto>>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetAll([FromRoute] Guid serviceId, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new GetServiceTemplateDefinitionsQuery(serviceId), cancellationToken));
|
||||
|
||||
[HttpDelete]
|
||||
[ProducesResponseType<ApiResponse<Unit>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Delete([FromRoute] Guid serviceId, [FromQuery] string key, [FromQuery] Guid revision, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new DeleteEmailTemplateDefinitionCommand(serviceId, key, revision), cancellationToken));
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
internal static class NotificationServiceRequestMapping
|
||||
{
|
||||
public static NotificationServiceInfo Map(Guid? id, string name, IReadOnlyList<ServiceLanguageRequest>? languages, Guid revision)
|
||||
{
|
||||
if (languages is null || languages.Any(l => l is null))
|
||||
throw new EmailTemplateWriteException("languages must be a JSON array without null elements.", false);
|
||||
if (id is null && languages.Any(l => l.Id != Guid.Empty))
|
||||
throw new EmailTemplateWriteException("New services cannot reference persisted language IDs.", false);
|
||||
return new NotificationServiceInfo
|
||||
{
|
||||
Id = id ?? Guid.Empty, Name = name, Revision = revision,
|
||||
Languages = languages.Select(l => new ServiceLanguageInfo { Id = l.Id, Code = l.Code }).ToList()
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class ServiceLanguageRequest
|
||||
{
|
||||
public Guid Id { get; init; }
|
||||
public required string Code { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.Services.Core;
|
||||
using Unit = HrynCo.NotificationService.Services.Core.Unit;
|
||||
using HrynCo.NotificationService.Web.Infrastructure;
|
||||
using HrynCo.NotificationService.Services.TemplateDefinitions;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
[Route("api/v1/services")]
|
||||
[TypeFilter(typeof(ApiRequestValidationFilter), Order = -3000)]
|
||||
public sealed class ServicesController(IMediator mediator) : ApiControllerBase(mediator)
|
||||
{
|
||||
[HttpGet("{serviceId:guid}")]
|
||||
[ProducesResponseType<ApiResponse<NotificationServiceDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Get([FromRoute] Guid serviceId, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new GetNotificationServiceQuery(serviceId, null), cancellationToken));
|
||||
|
||||
[HttpGet]
|
||||
[ProducesResponseType<ApiResponse<NotificationServiceDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetByName([FromQuery] string? name, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new GetNotificationServiceQuery(null, name), cancellationToken));
|
||||
[HttpGet("all")]
|
||||
[ProducesResponseType<ApiResponse<IReadOnlyList<NotificationServiceDto>>>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetAll(CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new GetAllNotificationServicesQuery(), cancellationToken));
|
||||
|
||||
[HttpDelete("{serviceId:guid}")]
|
||||
[ProducesResponseType<ApiResponse<Unit>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Delete([FromRoute] Guid serviceId, [FromQuery] Guid revision, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new DeleteNotificationServiceCommand(serviceId, revision), cancellationToken));
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType<ApiResponse<NotificationServiceDto>>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public Task<IActionResult> Create([FromBody] CreateNotificationServiceRequest request, CancellationToken cancellationToken) =>
|
||||
SaveServiceAsync(null, request.Name, request.Languages, Guid.Empty, cancellationToken);
|
||||
|
||||
[HttpPut("{serviceId:guid}")]
|
||||
[ProducesResponseType<ApiResponse<NotificationServiceDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public Task<IActionResult> Update([FromRoute] Guid serviceId, [FromBody] UpdateNotificationServiceRequest request, CancellationToken cancellationToken) =>
|
||||
SaveServiceAsync(serviceId, request.Name, request.Languages, request.Revision, cancellationToken);
|
||||
|
||||
[HttpDelete("{serviceId:guid}/languages/{languageId:guid}")]
|
||||
[ProducesResponseType<ApiResponse<Unit>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> DeleteUnusedLanguage([FromRoute] Guid serviceId, [FromRoute] Guid languageId,
|
||||
[FromQuery] Guid revision, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new DeleteUnusedServiceLanguageCommand(serviceId, languageId, revision), cancellationToken));
|
||||
|
||||
[HttpPost("{serviceId:guid}/languages/{languageId:guid}/delete-with-versions")]
|
||||
[ProducesResponseType<ApiResponse<Unit>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ApiResponse<object>>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> DeleteLanguageWithVersions([FromRoute] Guid serviceId, [FromRoute] Guid languageId,
|
||||
[FromBody] DeleteServiceLanguageVersionsRequest request, CancellationToken cancellationToken) =>
|
||||
FromServiceResult(await Mediator.Send(new DeleteServiceLanguageVersionsCommand(serviceId, languageId, request.Revision,
|
||||
request.ExpectedVersionCount, request.ConfirmDelete), cancellationToken));
|
||||
|
||||
private async Task<IActionResult> SaveServiceAsync(Guid? id, string name, IReadOnlyList<ServiceLanguageRequest> languages, Guid revision, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var model = NotificationServiceRequestMapping.Map(id, name, languages, revision);
|
||||
var result = await Mediator.Send(new SaveNotificationServiceCommand(model, id is null), cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
return MapServiceError(result.Error!);
|
||||
if (id is null)
|
||||
return CreatedAtAction(nameof(Get), new { serviceId = result.Result!.Id },
|
||||
new ApiResponse<NotificationServiceDto> { Success = true, Data = result.Result });
|
||||
return FromServiceResult(result);
|
||||
}
|
||||
catch (EmailTemplateWriteException error)
|
||||
{
|
||||
return MapServiceError(new ServiceError(error.Message, ServiceErrorCode.InvalidRequest));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class TemplateTranslationRequest
|
||||
{
|
||||
public required string LanguageCode { get; init; }
|
||||
public required string Subject { get; init; }
|
||||
public required string HtmlBody { get; init; }
|
||||
public required string TextBody { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class TemplateVariableRequest
|
||||
{
|
||||
public required string Name { get; init; }
|
||||
[JsonRequired]
|
||||
public bool Required { get; init; }
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class UpdateNotificationServiceRequest
|
||||
{
|
||||
[JsonRequired]
|
||||
public Guid Revision { get; init; }
|
||||
public required string Name { get; init; }
|
||||
public required IReadOnlyList<ServiceLanguageRequest> Languages { get; init; }
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
namespace HrynCo.NotificationService.Web.Controllers.Api.Services;
|
||||
|
||||
public sealed class UpsertTemplateDefinitionRequest
|
||||
{
|
||||
public Guid? Revision { get; init; }
|
||||
public required IReadOnlyList<TemplateVariableRequest> Variables { get; init; }
|
||||
public required IReadOnlyList<TemplateTranslationRequest> Translations { get; init; }
|
||||
public IReadOnlyList<string>? RemoveLanguageCodes { get; init; }
|
||||
|
||||
public EmailTemplateDefinitionPatch ToPatch(Guid serviceId, string key)
|
||||
{
|
||||
if (Variables is null || Translations is null)
|
||||
throw new EmailTemplateWriteException("variables and translations must be JSON arrays, including when empty.", false);
|
||||
if (Variables.Any(v => v is null) || Translations.Any(t => t is null))
|
||||
throw new EmailTemplateWriteException("variables and translations cannot contain null elements.", false);
|
||||
return new EmailTemplateDefinitionPatch
|
||||
{
|
||||
ServiceId = serviceId, Key = key, Revision = Revision,
|
||||
Variables = Variables.Select(v => new EmailTemplateVariable { Name = v.Name, Required = v.Required }).ToList(),
|
||||
Translations = Translations.Select(t => new EmailTemplate
|
||||
{
|
||||
ServiceName = "", Key = key, LanguageCode = t.LanguageCode, Created = DateTimeOffset.UtcNow,
|
||||
Subject = t.Subject, HtmlBody = t.HtmlBody, TextBody = t.TextBody
|
||||
}).ToList(),
|
||||
RemoveLanguageCodes = RemoveLanguageCodes ?? []
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -37,16 +37,16 @@ else
|
||||
{
|
||||
<div class="card shadow-sm table-card">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-sm mb-0">
|
||||
<thead class="table-dark">
|
||||
<table class="table table-hover admin-data-table table-sm mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Service</th>
|
||||
<th>Type</th>
|
||||
<th>Priority</th>
|
||||
<th>Status</th>
|
||||
<th>Today</th>
|
||||
<th>This Month</th>
|
||||
<th class="text-end">Actions</th>
|
||||
<th scope="col">Service</th>
|
||||
<th scope="col">Type</th>
|
||||
<th scope="col">Priority</th>
|
||||
<th scope="col">Status</th>
|
||||
<th scope="col">Today</th>
|
||||
<th scope="col">This Month</th>
|
||||
<th scope="col" class="channel-actions">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -106,7 +106,7 @@ else
|
||||
<small class="text-muted">@monthlyLabel</small>
|
||||
}
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<td class="channel-actions">
|
||||
<a href="/admin/channels/@c.ChannelId"
|
||||
class="btn btn-sm btn-outline-primary me-1">
|
||||
<i class="bi bi-pencil"></i> Edit
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
@using HrynCo.NotificationService.Web.Controllers.Admin.ViewModels
|
||||
@model NotificationServiceDeleteViewModel
|
||||
@{ ViewData["Title"] = "Delete service"; }
|
||||
<div class="admin-delete-confirmation">
|
||||
<nav aria-label="Breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/admin/services">Services</a></li><li class="breadcrumb-item active" aria-current="page">Delete service</li></ol></nav>
|
||||
<h2>Delete service @Model.Name?</h2>
|
||||
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
|
||||
@if (Model.DefinitionCount > 0)
|
||||
{
|
||||
<div class="alert alert-warning">This service still has <strong>@Model.DefinitionCount template definition(s)</strong>, including definitions without translations. Remove every definition before deleting the service.</div>
|
||||
<a href="/admin/services/@Model.ServiceId" class="btn btn-primary mb-3">View templates</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="alert alert-danger">This permanently deletes the service and its language catalog.</div>
|
||||
}
|
||||
<p>Email channels are retained. Their service names are independent and are not renamed or deleted.</p>
|
||||
<form asp-action="DeleteService" asp-route-serviceId="@Model.ServiceId" method="post">
|
||||
@Html.AntiForgeryToken()
|
||||
<input asp-for="Revision" type="hidden" />
|
||||
<div class="form-check mb-3"><input asp-for="ConfirmDelete" class="form-check-input" disabled="@(Model.DefinitionCount > 0)" /><label asp-for="ConfirmDelete" class="form-check-label">I confirm deletion of service @Model.Name and its language catalog.</label></div>
|
||||
<div class="d-flex flex-wrap gap-2"><button type="submit" class="btn btn-danger" disabled="@(Model.DefinitionCount > 0)">Delete service</button><a class="btn btn-secondary" href="/admin/services">Cancel</a></div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -6,7 +6,7 @@
|
||||
ViewData["EditorTitle"] = ViewData["Title"];
|
||||
}
|
||||
@section Breadcrumbs {
|
||||
<nav aria-label="Breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/admin/services">Services</a></li>@if (!Model.IsNew) { <li class="breadcrumb-item"><a href="/admin/services/@Model.Id">@Model.Name</a></li> }<li class="breadcrumb-item active" aria-current="page">@ViewData["Title"]</li></ol></nav>
|
||||
<nav aria-label="Breadcrumb" class="service-editor-breadcrumbs"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/admin/services">Services</a></li>@if (!Model.IsNew) { <li class="breadcrumb-item"><a href="/admin/services/@Model.Id">@Model.Name</a></li> }<li class="breadcrumb-item active" aria-current="page">@ViewData["Title"]</li></ol></nav>
|
||||
}
|
||||
<form asp-action="Save" id="serviceForm" method="post">
|
||||
@Html.AntiForgeryToken()
|
||||
@@ -17,7 +17,7 @@
|
||||
<h3 class="h5">Language codes</h3>
|
||||
<p class="text-muted">Codes are case-sensitive and belong to this service. Existing template versions use these codes when sending. Renaming a service or code changes sender lookup; align publishers and email channel service names.</p>
|
||||
<div class="table-responsive">
|
||||
<table class="table service-language-table"><thead><tr><th>Code</th><th>Versions</th><th class="service-language-actions">Actions</th></tr></thead><tbody id="serviceLanguages">
|
||||
<table class="table admin-data-table service-language-table"><thead><tr><th scope="col">Code</th><th scope="col">Versions</th><th scope="col" class="service-language-actions">Actions</th></tr></thead><tbody id="serviceLanguages">
|
||||
@for (var i = 0; i < Model.Languages.Count; i++)
|
||||
{
|
||||
var countUnavailable = ViewData["LanguageCountsUnavailable"] is true && Model.Languages[i].Id != Guid.Empty;
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
@model IReadOnlyList<NotificationServiceInfo>
|
||||
@{ ViewData["Title"] = "Services"; }
|
||||
<div class="page-header"><h2>Services</h2><a href="/admin/services/create" class="btn btn-primary">Create service</a></div>
|
||||
@if (Model.Count == 0) { <p>No services yet. Create a service and its language codes before adding templates.</p> }
|
||||
@if (Model.Count == 0)
|
||||
{
|
||||
<div class="card shadow-sm table-card"><div class="empty-state"><i class="bi bi-collection" aria-hidden="true"></i><p class="mt-2 mb-0">No services yet.</p><a href="/admin/services/create" class="btn btn-primary btn-sm mt-3">Create First Service</a></div></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-responsive"><table class="table table-hover"><thead><tr><th>Name</th><th>Language codes</th><th class="service-actions">Action</th></tr></thead><tbody>
|
||||
<div class="table-responsive"><table class="table table-hover admin-data-table"><thead><tr><th scope="col">Name</th><th scope="col">Language codes</th><th scope="col" class="service-actions">Action</th></tr></thead><tbody>
|
||||
@foreach (var service in Model)
|
||||
{
|
||||
<tr><td><a href="/admin/services/@service.Id">@service.Name</a></td><td>@string.Join(", ", service.Languages.Select(l => l.Code))</td><td class="service-actions"><a href="/admin/services/@service.Id/edit" class="btn btn-outline-primary btn-sm" aria-label="Edit service @service.Name">Edit</a></td></tr>
|
||||
<tr><td><a href="/admin/services/@service.Id">@service.Name</a></td><td>@string.Join(", ", service.Languages.Select(l => l.Code))</td><td class="service-actions"><div class="list-action-links"><a href="/admin/services/@service.Id/edit" class="btn btn-outline-primary btn-sm" aria-label="Edit service @service.Name">Edit</a><a href="/admin/services/@service.Id/delete" class="btn btn-outline-danger btn-sm" aria-label="Delete service @service.Name">Delete</a></div></td></tr>
|
||||
}
|
||||
</tbody></table></div>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
@using HrynCo.NotificationService.Web.Controllers.Admin.ViewModels
|
||||
@model EmailTemplateDefinitionDeleteViewModel
|
||||
@{ ViewData["Title"] = "Delete email template"; var returnUrl = Url.Action("Index", "AdminTemplates", new { serviceId = Model.ServiceId, key = Model.KeyFilter }); }
|
||||
<div class="admin-delete-confirmation">
|
||||
<nav aria-label="Breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/admin/services">Services</a></li><li class="breadcrumb-item"><a href="@returnUrl">@Model.ServiceName</a></li><li class="breadcrumb-item active" aria-current="page">Delete template</li></ol></nav>
|
||||
<h2>Delete template @Model.Key?</h2>
|
||||
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
|
||||
<div class="alert alert-danger">This permanently deletes the definition, shared variables and <strong>@Model.LanguageCodes.Count translation(s)</strong> from service @Model.ServiceName.</div>
|
||||
<p>Languages: @(Model.LanguageCodes.Count == 0 ? "No translations" : string.Join(", ", Model.LanguageCodes))</p>
|
||||
<p>The service, its language catalog and email channels are retained.</p>
|
||||
<form asp-action="DeleteDefinition" asp-route-serviceId="@Model.ServiceId" asp-route-definitionId="@Model.DefinitionId" method="post">
|
||||
@Html.AntiForgeryToken()
|
||||
<input asp-for="Revision" type="hidden" /><input asp-for="KeyFilter" type="hidden" />
|
||||
<div class="form-check mb-3"><input asp-for="ConfirmDelete" class="form-check-input" /><label asp-for="ConfirmDelete" class="form-check-label">I confirm deletion of @Model.Key and its @Model.LanguageCodes.Count translation(s).</label></div>
|
||||
<div class="d-flex flex-wrap gap-2"><button type="submit" class="btn btn-danger">Delete template</button><a class="btn btn-secondary" href="@returnUrl">Cancel</a></div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -86,7 +86,7 @@
|
||||
<div class="template-preview-section-title">Rendered subject</div>
|
||||
<div id="previewSubject" class="template-preview-subject"></div>
|
||||
<div class="template-preview-section-title mt-3">Rendered HTML</div>
|
||||
<iframe id="previewHtmlFrame" class="template-preview-frame" sandbox="" referrerpolicy="no-referrer" title="Email HTML preview"></iframe>
|
||||
<iframe id="previewHtmlFrame" class="template-preview-frame" sandbox="allow-same-origin" referrerpolicy="no-referrer" title="Email HTML preview"></iframe>
|
||||
<div class="template-preview-section-title mt-3">Rendered text</div>
|
||||
<pre id="previewText" class="template-preview-text mb-0"></pre>
|
||||
</div>
|
||||
@@ -98,5 +98,6 @@
|
||||
<a id="cancelTemplate" href="@Url.Action("Index", "AdminTemplates", new { serviceId = Model.ServiceId, key = Model.KeyFilter })" class="btn btn-secondary">Cancel</a>
|
||||
}
|
||||
@section Scripts {
|
||||
<script src="~/js/email-template-preview.js" asp-append-version="true"></script>
|
||||
<script src="~/js/email-template-editor.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
var serviceId = Model.Service.Id;
|
||||
var keyFilter = Model.KeyFilter;
|
||||
}
|
||||
<nav aria-label="Breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/admin/services">Services</a></li><li class="breadcrumb-item active" aria-current="page">@Model.Service.Name</li></ol></nav>
|
||||
<nav aria-label="Breadcrumb" class="service-template-breadcrumbs"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/admin/services">Services</a></li><li class="breadcrumb-item active" aria-current="page">@Model.Service.Name</li></ol></nav>
|
||||
<div class="page-header">
|
||||
<h2>@Model.Service.Name</h2>
|
||||
<h2 class="service-template-service-name">@Model.Service.Name</h2>
|
||||
<a href="/admin/services/@serviceId/edit" class="btn btn-outline-primary">Edit Service</a>
|
||||
</div>
|
||||
<div class="service-template-catalog mb-3" aria-label="Configured service languages">
|
||||
@@ -29,7 +29,7 @@
|
||||
<a asp-action="Create" asp-route-serviceId="@serviceId" asp-route-keyFilter="@keyFilter" class="btn btn-primary">Create template</a>
|
||||
</div>
|
||||
<div asp-validation-summary="All" class="text-danger mb-3" role="alert"></div>
|
||||
<div class="table-responsive"><table class="table table-hover service-template-grid"><thead><tr>
|
||||
<div class="table-responsive"><table class="table table-hover admin-data-table service-template-grid"><thead><tr>
|
||||
<th scope="col">
|
||||
<form method="get" action="/admin/services/@serviceId" class="template-key-filter">
|
||||
<label for="key" class="form-label fw-semibold">Template Key</label>
|
||||
@@ -45,7 +45,20 @@
|
||||
</tr></thead><tbody>
|
||||
@if (Model.Definitions.Count == 0)
|
||||
{
|
||||
<tr><td colspan="3">No email templates found for this service.</td></tr>
|
||||
<tr><td colspan="3"><div class="empty-state">
|
||||
@if (!ViewData.ModelState.IsValid)
|
||||
{
|
||||
<p class="mb-0">Templates are unavailable. Review the error and try again.</p>
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(keyFilter))
|
||||
{
|
||||
<i class="bi bi-search" aria-hidden="true"></i><p class="mt-2 mb-0">No templates match this key.</p><a href="/admin/services/@serviceId" class="btn btn-primary btn-sm mt-3">Clear filter</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
<i class="bi bi-envelope" aria-hidden="true"></i><p class="mt-2 mb-0">No email templates for this service yet.</p><a asp-action="Create" asp-route-serviceId="@serviceId" class="btn btn-primary btn-sm mt-3">Create First Template</a>
|
||||
}
|
||||
</div></td></tr>
|
||||
}
|
||||
@foreach (var template in Model.Definitions)
|
||||
{
|
||||
@@ -71,7 +84,7 @@
|
||||
</ul>
|
||||
}
|
||||
</td>
|
||||
<td class="template-actions"><a href="@editUrl" class="btn btn-outline-primary btn-sm" aria-label="Edit template @template.Key">Edit</a></td>
|
||||
<td class="template-actions"><div class="list-action-links"><a href="@editUrl" class="btn btn-outline-primary btn-sm" aria-label="Edit template @template.Key">Edit</a><a asp-action="ConfirmDefinitionDelete" asp-route-serviceId="@serviceId" asp-route-definitionId="@template.Id" asp-route-keyFilter="@keyFilter" class="btn btn-outline-danger btn-sm" aria-label="Delete template @template.Key">Delete</a></div></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody></table></div>
|
||||
|
||||
@@ -16,10 +16,11 @@
|
||||
<link href="/css/admin.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-dark bg-dark px-3 admin-navbar">
|
||||
<nav class="navbar navbar-dark bg-dark admin-navbar">
|
||||
<a class="navbar-brand fw-bold" href="/">
|
||||
<i class="bi bi-bell-fill me-1"></i> Notification Service
|
||||
</a>
|
||||
<a class="admin-api-documentation" href="/scalar/v1" target="_blank" rel="noopener noreferrer" aria-label="API documentation (opens in a new tab)">API documentation</a>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid">
|
||||
@@ -43,6 +44,7 @@
|
||||
</div>
|
||||
|
||||
<script src="/lib/bootstrap/bootstrap.bundle.min.js"></script>
|
||||
<script src="~/js/admin-tables.js" asp-append-version="true"></script>
|
||||
@RenderSection("Scripts", required: false)
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -20,7 +20,10 @@ body {
|
||||
.admin-navbar {
|
||||
border-bottom: 1px solid rgba(255,255,255,.07);
|
||||
box-shadow: 0 2px 6px rgba(0,0,0,.4);
|
||||
height: 52px;
|
||||
min-height: 52px;
|
||||
align-items: center;
|
||||
gap: .5rem;
|
||||
padding-inline: 1rem;
|
||||
}
|
||||
|
||||
.admin-navbar .navbar-brand {
|
||||
@@ -29,6 +32,27 @@ body {
|
||||
letter-spacing: .02em;
|
||||
}
|
||||
|
||||
.admin-api-documentation {
|
||||
margin-left: auto;
|
||||
padding-block: .25rem;
|
||||
color: #f8f9fa;
|
||||
font-size: .85rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin-api-documentation:hover { color: #fff; }
|
||||
|
||||
.admin-api-documentation:focus-visible {
|
||||
outline: 2px solid #f8f9fa;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.admin-navbar { padding-inline: .5rem; }
|
||||
.admin-navbar .navbar-brand { margin-right: 0; font-size: .85rem; }
|
||||
.admin-api-documentation { font-size: .8rem; }
|
||||
}
|
||||
|
||||
/* ── Sidebar ──────────────────────────────────────────── */
|
||||
.sidebar {
|
||||
min-height: calc(100vh - 52px);
|
||||
@@ -109,21 +133,44 @@ body {
|
||||
.table tbody tr td { vertical-align: middle; }
|
||||
.table thead th { font-size: .75rem; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }
|
||||
|
||||
/* ── Administration list grids ────────────────────────── */
|
||||
.admin-data-table { border: 1px solid #b8c4d3; }
|
||||
|
||||
.admin-data-table :is(a, button, input, select, textarea) { scroll-margin-inline: .5rem; }
|
||||
|
||||
.admin-data-table > thead > tr > th {
|
||||
--bs-table-bg: #dce7f6;
|
||||
--bs-table-color: #243a55;
|
||||
border-bottom: 2px solid #aec0db;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.admin-data-table > tbody > tr > td:first-child { overflow-wrap: anywhere; }
|
||||
|
||||
.admin-data-table > :not(caption) > * > * + * {
|
||||
border-left: 1px solid #b8c4d3;
|
||||
}
|
||||
|
||||
.admin-data-table .list-action-links { display: inline-flex; align-items: center; gap: .375rem; }
|
||||
.admin-delete-confirmation { overflow-wrap: anywhere; }
|
||||
|
||||
/* ── List actions ─────────────────────────────────────── */
|
||||
.table .template-actions,
|
||||
.table .service-actions {
|
||||
.admin-data-table .template-actions,
|
||||
.admin-data-table .service-actions,
|
||||
.admin-data-table .channel-actions {
|
||||
width: 1%;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* ── Service template catalog and filters ─────────────── */
|
||||
.service-template-grid > thead > tr > th {
|
||||
--bs-table-bg: #dce7f6;
|
||||
--bs-table-color: #243a55;
|
||||
border-bottom: 2px solid #aec0db;
|
||||
.page-header .service-template-service-name {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.service-template-service-name + .btn { flex-shrink: 0; }
|
||||
|
||||
/* ── Service template catalog and filters ─────────────── */
|
||||
.service-template-grid .template-key-filter .btn-outline-secondary {
|
||||
--bs-btn-bg: #fff;
|
||||
}
|
||||
@@ -154,6 +201,7 @@ body {
|
||||
|
||||
.template-key-filter-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: .375rem;
|
||||
}
|
||||
@@ -302,7 +350,9 @@ body {
|
||||
}
|
||||
|
||||
/* ── Template service context ─────────────────────────── */
|
||||
.template-editor-breadcrumbs .breadcrumb-item {
|
||||
.template-editor-breadcrumbs .breadcrumb-item,
|
||||
.service-template-breadcrumbs .breadcrumb-item,
|
||||
.service-editor-breadcrumbs .breadcrumb-item {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
@@ -473,7 +523,7 @@ body {
|
||||
|
||||
.template-preview-frame {
|
||||
width: 100%;
|
||||
height: 420px;
|
||||
height: 80px;
|
||||
border: 1px solid #cfd8e3;
|
||||
border-radius: .5rem;
|
||||
background: #eef2f7;
|
||||
@@ -495,9 +545,6 @@ body {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.template-preview-frame {
|
||||
height: 360px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Form-section divider ─────────────────────────────── */
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Reveal keyboard-focused controls only within their nearest horizontal table scroller.
|
||||
(() => {
|
||||
let keyboardFocus = false;
|
||||
document.addEventListener('keydown', () => { keyboardFocus = true; }, true);
|
||||
document.addEventListener('pointerdown', () => { keyboardFocus = false; }, true);
|
||||
document.addEventListener('focusin', event => {
|
||||
const target = event.target;
|
||||
if (!keyboardFocus || !(target instanceof HTMLElement) || !target.closest('.admin-data-table')) return;
|
||||
const wrapper = target.closest('.table-responsive');
|
||||
if (!wrapper) return;
|
||||
const control = target.getBoundingClientRect();
|
||||
const viewport = wrapper.getBoundingClientRect();
|
||||
// Leave space for the focus ring without moving the document or vertical ancestors.
|
||||
const left = viewport.left + wrapper.clientLeft + 8;
|
||||
const right = left + wrapper.clientWidth - 16;
|
||||
if (control.left < left) wrapper.scrollLeft += control.left - left;
|
||||
else if (control.right > right) wrapper.scrollLeft += control.right - right;
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
// Trusted parent-side measurement; template scripts stay disabled by sandbox and CSP.
|
||||
(() => {
|
||||
const frame = document.getElementById('previewHtmlFrame');
|
||||
let observer;
|
||||
let scheduled = 0;
|
||||
|
||||
function resizePreview() {
|
||||
scheduled = 0;
|
||||
const document = frame.contentDocument;
|
||||
if (!document?.body) return;
|
||||
frame.style.height = '0px';
|
||||
const height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
|
||||
frame.style.height = `${Math.max(80, Math.ceil(height) + 2)}px`;
|
||||
}
|
||||
|
||||
function scheduleResize() {
|
||||
cancelAnimationFrame(scheduled);
|
||||
scheduled = requestAnimationFrame(resizePreview);
|
||||
}
|
||||
|
||||
function preventLinkNavigation(event) {
|
||||
if (event.target?.closest?.('a, area')) event.preventDefault();
|
||||
}
|
||||
|
||||
frame.addEventListener('load', () => {
|
||||
observer?.disconnect();
|
||||
const document = frame.contentDocument;
|
||||
if (!document?.body) return;
|
||||
document.addEventListener('click', preventLinkNavigation, true);
|
||||
document.addEventListener('submit', event => event.preventDefault(), true);
|
||||
observer = new ResizeObserver(scheduleResize);
|
||||
observer.observe(document.body);
|
||||
scheduleResize();
|
||||
});
|
||||
window.addEventListener('resize', scheduleResize);
|
||||
window.addEventListener('pagehide', () => {
|
||||
observer?.disconnect();
|
||||
cancelAnimationFrame(scheduled);
|
||||
});
|
||||
})();
|
||||
Reference in New Issue
Block a user