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 ?? []
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user