@@ -25,12 +25,28 @@ public class CreateTemplateHandler(IDbContextFactory<TvContext> dbContextFactory
|
||||
return Mapper.ProjectToViewModel(template);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Template>> Validate(TvContext dbContext, CreateTemplate request) =>
|
||||
await ValidateTemplateName(dbContext, request).MapT(name => new Template
|
||||
private static async Task<Validation<BaseError, Template>> Validate(TvContext dbContext, CreateTemplate request)
|
||||
{
|
||||
Validation<BaseError, Unit> templateGroupValidation = await ValidateTemplateGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateTemplateName(dbContext, request);
|
||||
|
||||
return (templateGroupValidation, nameValidation).Apply((_, name) => new Template
|
||||
{
|
||||
TemplateGroupId = request.TemplateGroupId,
|
||||
Name = name
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateTemplateGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateTemplate request)
|
||||
{
|
||||
bool templateGroupExists = await dbContext.TemplateGroups.AnyAsync(tg => tg.Id == request.TemplateGroupId);
|
||||
|
||||
return templateGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Template group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateTemplateName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -76,16 +76,29 @@ public class ReplaceTemplateItemsHandler(IDbContextFactory<TvContext> dbContextF
|
||||
.ToListAsync()
|
||||
.Map(list => list.ToDictionary(b => b.Id, b => b));
|
||||
|
||||
var missingBlockIds = allBlockIds.Filter(id => !allBlocks.ContainsKey(id)).ToList();
|
||||
if (missingBlockIds.Count > 0)
|
||||
{
|
||||
return BaseError.New($"[BlockId] {missingBlockIds.Head()} does not exist.");
|
||||
}
|
||||
|
||||
var allTemplateItems = request.Items.Map(i =>
|
||||
{
|
||||
Block block = allBlocks[i.BlockId];
|
||||
return new BlockTemplateItem(
|
||||
i.BlockId,
|
||||
i.StartTime,
|
||||
i.StartTime + TimeSpan.FromMinutes(block.Minutes));
|
||||
var endTime = i.StartTime + TimeSpan.FromMinutes(block.Minutes);
|
||||
return new BlockTemplateItem(i.BlockId, i.StartTime, endTime);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
foreach (BlockTemplateItem item in allTemplateItems)
|
||||
{
|
||||
if (item.EndTime > TimeSpan.FromHours(24))
|
||||
{
|
||||
return BaseError.New(
|
||||
$"Block from {item.StartTime} to {item.EndTime} crosses midnight, which is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (BlockTemplateItem item in allTemplateItems)
|
||||
{
|
||||
foreach (BlockTemplateItem otherItem in allTemplateItems)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateGroupResponseModel(int Id, string Name, int TemplateCount);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateItemResponseModel(int BlockId, string BlockName, int BlockMinutes, TimeSpan StartTime);
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateResponseModel(int Id, int TemplateGroupId, string GroupName, string Name);
|
||||
@@ -0,0 +1,9 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record TemplateWithItemsResponseModel(
|
||||
int Id,
|
||||
int TemplateGroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
List<TemplateItemResponseModel> Items);
|
||||
@@ -42,6 +42,7 @@ public class ApiControllerSecurityTests
|
||||
typeof(SessionController),
|
||||
typeof(SettingsController),
|
||||
typeof(SmartCollectionController),
|
||||
typeof(TemplateController),
|
||||
typeof(TraktController),
|
||||
typeof(TroubleshootController),
|
||||
typeof(WatermarkController)
|
||||
|
||||
@@ -79,6 +79,20 @@ public class ApiErrorResponseMetadataTests
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Preview), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Copy), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Copy), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.GetItems), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Replace), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Replace), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Copy), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(TemplateController), nameof(TemplateController.Copy), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
|
||||
@@ -44,6 +44,7 @@ public class BlockControllerTests
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetItems), "GET", "/api/blocks/{id:int}/items");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Replace), "PUT", "/api/blocks/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Preview), "POST", "/api/blocks/{id:int}/preview");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Copy), "POST", "/api/blocks/{id:int}/copy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -328,6 +329,57 @@ public class BlockControllerTests
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<PreviewBlockPlayout>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<CopyBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, BlockViewModel>(MakeBlock(9, 3, "Morning Copy")));
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyBlockRequest(3, "Morning Copy"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/blocks/9");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CopyBlock>(c => c.BlockId == 4 && c.NewBlockGroupId == 3 && c.NewBlockName == "Morning Copy"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_404_When_Source_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyBlockRequest(3, "Morning Copy"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<CopyBlock>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<CopyBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, BlockViewModel>(BaseError.New("dupe")));
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyBlockRequest(3, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
private static BlockViewModel MakeBlock(int id, int groupId, string name) =>
|
||||
new(id, groupId, "Group", name, 30, BlockStopScheduling.AfterDurationEnd);
|
||||
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
using System.Reflection;
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Controllers.Api;
|
||||
using ErsatzTV.Controllers.Api.Requests;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using LanguageExt;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Routing;
|
||||
using NSubstitute;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
using static LanguageExt.Prelude;
|
||||
|
||||
namespace ErsatzTV.Tests.Controllers;
|
||||
|
||||
[TestFixture]
|
||||
public class TemplateControllerTests
|
||||
{
|
||||
private TemplateController _controller = null!;
|
||||
private IMediator _mediator = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_mediator = Substitute.For<IMediator>();
|
||||
_controller = new TemplateController(_mediator);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
|
||||
{
|
||||
ShouldHaveActionRoute(nameof(TemplateController.GetGroups), "GET", "/api/templates/groups");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.CreateGroup), "POST", "/api/templates/groups");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.DeleteGroup), "DELETE", "/api/templates/groups/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.GetAll), "GET", "/api/templates");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.GetById), "GET", "/api/templates/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.Create), "POST", "/api/templates");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.Delete), "DELETE", "/api/templates/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.GetItems), "GET", "/api/templates/{id:int}/items");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.Replace), "PUT", "/api/templates/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(TemplateController.Copy), "POST", "/api/templates/{id:int}/copy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_201_With_Location_And_Body()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateTemplateGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, TemplateGroupViewModel>(new TemplateGroupViewModel(5, "Prime Time", 0)));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateTemplateGroupRequest("Prime Time"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/templates/groups/5");
|
||||
created.Value.ShouldBeOfType<TemplateGroupResponseModel>().Name.ShouldBe("Prime Time");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateTemplateGroup>(c => c.Name == "Prime Time"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateTemplateGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, TemplateGroupViewModel>(BaseError.New("bad")));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateTemplateGroupRequest(string.Empty),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllTemplateGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<TemplateGroupViewModel> { new(3, "Prime Time", 0) });
|
||||
_mediator.Send(Arg.Any<DeleteTemplateGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BaseError>.None);
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(3, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<DeleteTemplateGroup>(c => c.TemplateGroupId == 3),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllTemplateGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<TemplateGroupViewModel>());
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(99, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteTemplateGroup>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAll_Should_Map_ViewModels_To_Response_Models()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllTemplates>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<TemplateViewModel> { MakeTemplate(1, 2, "Morning") });
|
||||
|
||||
List<TemplateResponseModel> result = await _controller.GetAll(null, CancellationToken.None);
|
||||
|
||||
result.Count.ShouldBe(1);
|
||||
result[0].Id.ShouldBe(1);
|
||||
result[0].TemplateGroupId.ShouldBe(2);
|
||||
result[0].Name.ShouldBe("Morning");
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<GetTemplatesByTemplateGroupId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAll_Should_Filter_By_TemplateGroupId_When_Provided()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplatesByTemplateGroupId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<TemplateViewModel> { MakeTemplate(1, 2, "Morning") });
|
||||
|
||||
List<TemplateResponseModel> result = await _controller.GetAll(2, CancellationToken.None);
|
||||
|
||||
result.Count.ShouldBe(1);
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<GetTemplatesByTemplateGroupId>(c => c.TemplateGroupId == 2),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<GetAllTemplates>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateTemplate>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, TemplateViewModel>(MakeTemplate(8, 2, "Morning")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateTemplateRequest(2, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/templates/8");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateTemplate>(c => c.TemplateGroupId == 2 && c.Name == "Morning"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateTemplate>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, TemplateViewModel>(BaseError.New("dupe")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateTemplateRequest(2, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_200_For_Some()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 2, "Morning")));
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<TemplateResponseModel>().Id.ShouldBe(4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_404_For_None()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<DeleteTemplate>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BaseError>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteTemplate>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_200_Ordered_By_StartTime()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<GetTemplateItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<TemplateItemViewModel>
|
||||
{
|
||||
MakeItem(20, "News", TimeSpan.FromHours(12), 30),
|
||||
MakeItem(10, "Cartoons", TimeSpan.FromHours(6), 60)
|
||||
});
|
||||
|
||||
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
|
||||
|
||||
var items = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<List<TemplateItemResponseModel>>();
|
||||
items.Count.ShouldBe(2);
|
||||
items[0].BlockId.ShouldBe(10);
|
||||
items[0].StartTime.ShouldBe(TimeSpan.FromHours(6));
|
||||
items[0].BlockMinutes.ShouldBe(60);
|
||||
items[1].BlockId.ShouldBe(20);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_404_When_Template_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_200_With_Refreshed_Template_And_Map_Items()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<ReplaceTemplateItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, List<TemplateItemViewModel>>([]));
|
||||
_mediator.Send(Arg.Any<GetTemplateItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<TemplateItemViewModel>
|
||||
{
|
||||
MakeItem(10, "Cartoons", TimeSpan.FromHours(6), 60)
|
||||
});
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceTemplateRequest(
|
||||
"Morning",
|
||||
[new TemplateItemRequest(10, TimeSpan.FromHours(6))]),
|
||||
CancellationToken.None);
|
||||
|
||||
var body = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<TemplateWithItemsResponseModel>();
|
||||
body.Id.ShouldBe(4);
|
||||
body.Items.Count.ShouldBe(1);
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<ReplaceTemplateItems>(c =>
|
||||
c.TemplateId == 4 &&
|
||||
c.TemplateGroupId == 7 &&
|
||||
c.Name == "Morning" &&
|
||||
c.Items.Count == 1 &&
|
||||
c.Items[0].BlockId == 10 &&
|
||||
c.Items[0].StartTime == TimeSpan.FromHours(6)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_404_When_Template_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceTemplateRequest("Morning", []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<ReplaceTemplateItems>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<ReplaceTemplateItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, List<TemplateItemViewModel>>(BaseError.New("overlap")));
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceTemplateRequest("Morning", []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<GetTemplateItems>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<CopyTemplate>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, TemplateViewModel>(MakeTemplate(9, 3, "Morning Copy")));
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyTemplateRequest(3, "Morning Copy"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/templates/9");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CopyTemplate>(c => c.TemplateId == 4 && c.NewTemplateGroupId == 3 && c.NewTemplateName == "Morning Copy"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_404_When_Source_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyTemplateRequest(3, "Morning Copy"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<CopyTemplate>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Copy_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetTemplateById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<TemplateViewModel>.Some(MakeTemplate(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<CopyTemplate>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, TemplateViewModel>(BaseError.New("dupe")));
|
||||
|
||||
IActionResult result = await _controller.Copy(
|
||||
4,
|
||||
new CopyTemplateRequest(3, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
private static TemplateViewModel MakeTemplate(int id, int groupId, string name) =>
|
||||
new(id, groupId, "Group", name);
|
||||
|
||||
private static TemplateItemViewModel MakeItem(int blockId, string blockName, TimeSpan startTime, int minutes)
|
||||
{
|
||||
DateTime start = DateTime.Today.Add(startTime);
|
||||
return new TemplateItemViewModel(blockId, blockName, start, start.AddMinutes(minutes));
|
||||
}
|
||||
|
||||
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
|
||||
{
|
||||
MethodInfo action = typeof(TemplateController).GetMethod(actionName)
|
||||
?? throw new AssertionException($"Missing action {actionName}");
|
||||
|
||||
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
|
||||
attribute.HttpMethods.ShouldContain(httpMethod);
|
||||
attribute.Template.ShouldBe(route);
|
||||
}
|
||||
}
|
||||
@@ -211,6 +211,31 @@ public class BlockController(IMediator mediator) : ControllerBase
|
||||
return new OkObjectResult(preview.Map(ProjectToResponseModel).ToList());
|
||||
}
|
||||
|
||||
[HttpPost("/api/blocks/{id:int}/copy")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Copy a block")]
|
||||
[EndpointDescription("Copies the block and its items into another (or the same) block group under a new name.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(BlockResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Copy(
|
||||
int id,
|
||||
[Required] [FromBody] CopyBlockRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<BlockViewModel> existing = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
if (existing.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Either<BaseError, BlockViewModel> result = await mediator.Send(request.ToCommand(id), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/blocks/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
private static BlockGroupResponseModel ProjectToResponseModel(BlockGroupViewModel vm) =>
|
||||
new(vm.Id, vm.Name);
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CopyBlockRequest(int BlockGroupId, string Name)
|
||||
{
|
||||
public CopyBlock ToCommand(int blockId) => new(blockId, BlockGroupId, Name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CopyTemplateRequest(int TemplateGroupId, string Name)
|
||||
{
|
||||
public CopyTemplate ToCommand(int templateId) => new(templateId, TemplateGroupId, Name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CreateTemplateGroupRequest(string Name)
|
||||
{
|
||||
public CreateTemplateGroup ToCommand() => new(Name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CreateTemplateRequest(int TemplateGroupId, string Name)
|
||||
{
|
||||
public CreateTemplate ToCommand() => new(TemplateGroupId, Name);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record ReplaceTemplateRequest(string Name, List<TemplateItemRequest> Items)
|
||||
{
|
||||
public ReplaceTemplateItems ToCommand(int templateGroupId, int templateId) =>
|
||||
new(
|
||||
templateGroupId,
|
||||
templateId,
|
||||
Name,
|
||||
(Items ?? []).Select(item => item.ToReplaceItem()).ToList());
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record TemplateItemRequest(int BlockId, TimeSpan StartTime)
|
||||
{
|
||||
public ReplaceTemplateItem ToReplaceItem() => new(BlockId, StartTime);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Controllers.Api.Requests;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using ErsatzTV.Extensions;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api;
|
||||
|
||||
[ApiController]
|
||||
public class TemplateController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
[HttpGet("/api/templates/groups", Name = "GetTemplateGroups")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Get all template groups")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<TemplateGroupResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<TemplateGroupResponseModel>> GetGroups(CancellationToken cancellationToken)
|
||||
{
|
||||
List<TemplateGroupViewModel> groups = await mediator.Send(new GetAllTemplateGroups(), cancellationToken);
|
||||
return groups.Map(ProjectToResponseModel).ToList();
|
||||
}
|
||||
|
||||
[HttpPost("/api/templates/groups")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Create a template group")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(TemplateGroupResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> CreateGroup(
|
||||
[Required] [FromBody] CreateTemplateGroupRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Either<BaseError, TemplateGroupViewModel> result =
|
||||
await mediator.Send(request.ToCommand(), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/templates/groups/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
[HttpDelete("/api/templates/groups/{id:int}")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Delete a template group")]
|
||||
[EndpointDescription(
|
||||
"Deletes the template group. The database cascade removes every template (and its items) in the group.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteGroup(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
List<TemplateGroupViewModel> groups = await mediator.Send(new GetAllTemplateGroups(), cancellationToken);
|
||||
if (groups.All(g => g.Id != id))
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(new DeleteTemplateGroup(id), cancellationToken);
|
||||
return result.Match<IActionResult>(
|
||||
Some: error => error.ToErrorResult(),
|
||||
None: () => new NoContentResult());
|
||||
}
|
||||
|
||||
[HttpGet("/api/templates")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Get all templates")]
|
||||
[EndpointDescription(
|
||||
"Returns every template. Pass templateGroupId to filter to the templates in a single template group.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<TemplateResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<TemplateResponseModel>> GetAll(
|
||||
[FromQuery] int? templateGroupId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
List<TemplateViewModel> templates = templateGroupId is { } groupId
|
||||
? await mediator.Send(new GetTemplatesByTemplateGroupId(groupId), cancellationToken)
|
||||
: await mediator.Send(new GetAllTemplates(), cancellationToken);
|
||||
return templates.Map(ProjectToResponseModel).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/templates/{id:int}", Name = "GetTemplateById")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Get a template by id")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(TemplateResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<TemplateViewModel> result = await mediator.Send(new GetTemplateById(id), cancellationToken);
|
||||
return result.Map(ProjectToResponseModel).ToGetResult();
|
||||
}
|
||||
|
||||
[HttpPost("/api/templates")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Create a template")]
|
||||
[EndpointDescription("Creates an empty template in the given template group.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(TemplateResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Create(
|
||||
[Required] [FromBody] CreateTemplateRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Either<BaseError, TemplateViewModel> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/templates/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
[HttpDelete("/api/templates/{id:int}")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Delete a template")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<TemplateViewModel> existing = await mediator.Send(new GetTemplateById(id), cancellationToken);
|
||||
if (existing.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(new DeleteTemplate(id), cancellationToken);
|
||||
return result.Match<IActionResult>(
|
||||
Some: error => error.ToErrorResult(),
|
||||
None: () => new NoContentResult());
|
||||
}
|
||||
|
||||
[HttpGet("/api/templates/{id:int}/items")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Get template items")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<TemplateItemResponseModel>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetItems(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<TemplateViewModel> template = await mediator.Send(new GetTemplateById(id), cancellationToken);
|
||||
if (template.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
List<TemplateItemViewModel> items = await mediator.Send(new GetTemplateItems(id), cancellationToken);
|
||||
return new OkObjectResult(
|
||||
items.OrderBy(i => i.StartTime.TimeOfDay).Map(ProjectToResponseModel).ToList());
|
||||
}
|
||||
|
||||
[HttpPut("/api/templates/{id:int}")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Replace a template and its items")]
|
||||
[EndpointDescription(
|
||||
"Replaces the template's name and its full item list. Each item assigns a block to a start time of day; " +
|
||||
"items must not overlap (an item's end time is its start time plus the assigned block's duration).")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(TemplateWithItemsResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Replace(
|
||||
int id,
|
||||
[Required] [FromBody] ReplaceTemplateRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<TemplateViewModel> maybeTemplate = await mediator.Send(new GetTemplateById(id), cancellationToken);
|
||||
if (maybeTemplate.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
int templateGroupId = maybeTemplate.Map(t => t.TemplateGroupId).IfNone(0);
|
||||
|
||||
Either<BaseError, List<TemplateItemViewModel>> result =
|
||||
await mediator.Send(request.ToCommand(templateGroupId, id), cancellationToken);
|
||||
|
||||
return await result.Match(
|
||||
Left: error => Task.FromResult(error.ToErrorResult()),
|
||||
Right: async _ =>
|
||||
{
|
||||
Option<TemplateViewModel> refreshed = await mediator.Send(new GetTemplateById(id), cancellationToken);
|
||||
List<TemplateItemViewModel> items = await mediator.Send(new GetTemplateItems(id), cancellationToken);
|
||||
return refreshed.Match(
|
||||
Some: vm => (IActionResult)new OkObjectResult(ProjectToWithItemsResponseModel(vm, items)),
|
||||
None: () => ApiResults.NotFoundProblem());
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost("/api/templates/{id:int}/copy")]
|
||||
[Tags("Templates")]
|
||||
[EndpointSummary("Copy a template")]
|
||||
[EndpointDescription("Copies the template and its items into another (or the same) template group under a new name.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(TemplateResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Copy(
|
||||
int id,
|
||||
[Required] [FromBody] CopyTemplateRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<TemplateViewModel> existing = await mediator.Send(new GetTemplateById(id), cancellationToken);
|
||||
if (existing.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Either<BaseError, TemplateViewModel> result =
|
||||
await mediator.Send(request.ToCommand(id), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/templates/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
private static TemplateGroupResponseModel ProjectToResponseModel(TemplateGroupViewModel vm) =>
|
||||
new(vm.Id, vm.Name, vm.TemplateCount);
|
||||
|
||||
private static TemplateResponseModel ProjectToResponseModel(TemplateViewModel vm) =>
|
||||
new(vm.Id, vm.TemplateGroupId, vm.GroupName, vm.Name);
|
||||
|
||||
private static TemplateWithItemsResponseModel ProjectToWithItemsResponseModel(
|
||||
TemplateViewModel vm,
|
||||
List<TemplateItemViewModel> items) =>
|
||||
new(
|
||||
vm.Id,
|
||||
vm.TemplateGroupId,
|
||||
vm.GroupName,
|
||||
vm.Name,
|
||||
items.OrderBy(i => i.StartTime.TimeOfDay).Map(ProjectToResponseModel).ToList());
|
||||
|
||||
private static TemplateItemResponseModel ProjectToResponseModel(TemplateItemViewModel vm) =>
|
||||
new(vm.BlockId, vm.BlockName, (int)(vm.EndTime - vm.StartTime).TotalMinutes, vm.StartTime.TimeOfDay);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@ import {
|
||||
Bell,
|
||||
Boxes,
|
||||
CalendarClock,
|
||||
CalendarDays,
|
||||
Cast,
|
||||
Check,
|
||||
ChevronDown,
|
||||
@@ -72,6 +73,7 @@ import { TrashScreen } from './screens/TrashScreen';
|
||||
import { TroubleshootingScreen } from './screens/TroubleshootingScreen';
|
||||
import { WatermarksScreen } from './screens/WatermarksScreen';
|
||||
import { BlocksScreen } from './screens/BlocksScreen';
|
||||
import { TemplatesScreen } from './screens/TemplatesScreen';
|
||||
import { navigateToPath } from './routing';
|
||||
import {
|
||||
Badge,
|
||||
@@ -152,6 +154,7 @@ type ScreenId =
|
||||
| 'guide'
|
||||
| 'schedules'
|
||||
| 'blocks'
|
||||
| 'templates'
|
||||
| 'playouts'
|
||||
| 'media'
|
||||
| 'search'
|
||||
@@ -266,6 +269,19 @@ const routes: ScreenRoute[] = [
|
||||
placeholder: 'Blocks workspace',
|
||||
allowSubPaths: true
|
||||
},
|
||||
{
|
||||
// The editor lives at a sub-path (/app/templates/{id}); TemplatesScreen owns parsing the id suffix.
|
||||
id: 'templates',
|
||||
path: '/app/templates',
|
||||
label: 'Templates',
|
||||
title: 'Templates',
|
||||
kicker: 'Programming',
|
||||
description: 'Group templates and assign blocks to times of day.',
|
||||
icon: <CalendarDays aria-hidden="true" size={16} />,
|
||||
primaryAction: 'New Group',
|
||||
placeholder: 'Templates workspace',
|
||||
allowSubPaths: true
|
||||
},
|
||||
{
|
||||
id: 'playouts',
|
||||
path: '/app/playouts',
|
||||
@@ -430,6 +446,7 @@ const primaryNavIds: ScreenId[] = [
|
||||
'guide',
|
||||
'schedules',
|
||||
'blocks',
|
||||
'templates',
|
||||
'playouts'
|
||||
];
|
||||
const mediaNavIds: ScreenId[] = [
|
||||
@@ -3398,6 +3415,10 @@ function ScreenContent({
|
||||
return <BlocksScreen key={window.location.pathname} />;
|
||||
}
|
||||
|
||||
if (route.id === 'templates') {
|
||||
return <TemplatesScreen key={window.location.pathname} />;
|
||||
}
|
||||
|
||||
if (route.id === 'playouts') {
|
||||
return <PlayoutsScreen />;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
copyBlock,
|
||||
createBlock,
|
||||
createBlockGroup,
|
||||
deleteBlock,
|
||||
@@ -126,6 +127,15 @@ describe('blocks api client', () => {
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
});
|
||||
|
||||
it('copyBlock POSTs the target group and name to the copy route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 9 }, 201));
|
||||
await copyBlock(4, { blockGroupId: 3, name: 'Morning Copy' });
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/blocks/4/copy');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
expect(JSON.parse(String(init?.body))).toMatchObject({ blockGroupId: 3, name: 'Morning Copy' });
|
||||
});
|
||||
|
||||
it('search pickers encode the query and hit the right routes', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockImplementation(() => Promise.resolve(jsonResponse([])));
|
||||
await searchCollections('a b');
|
||||
|
||||
@@ -10,6 +10,7 @@ export type CreateBlockGroupRequest = components['schemas']['CreateBlockGroupReq
|
||||
export type CreateBlockRequest = components['schemas']['CreateBlockRequest'];
|
||||
export type ReplaceBlockRequest = components['schemas']['ReplaceBlockRequest'];
|
||||
export type BlockItemRequest = components['schemas']['BlockItemRequest'];
|
||||
export type CopyBlockRequest = components['schemas']['CopyBlockRequest'];
|
||||
export type SchedulingPickerOption = components['schemas']['SchedulingPickerOptionResponseModel'];
|
||||
|
||||
// Block groups
|
||||
@@ -56,6 +57,10 @@ export function previewBlock(id: number, body: ReplaceBlockRequest): Promise<Blo
|
||||
return request<BlockPreviewItem[]>(`/api/blocks/${id}/preview`, { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function copyBlock(id: number, body: CopyBlockRequest): Promise<Block> {
|
||||
return request<Block>(`/api/blocks/${id}/copy`, { body, method: 'POST' });
|
||||
}
|
||||
|
||||
// Scheduling search pickers
|
||||
|
||||
function searchOptions(path: string, query: string): Promise<SchedulingPickerOption[]> {
|
||||
|
||||
Vendored
+47
@@ -223,6 +223,14 @@ export interface components {
|
||||
"CombinedVersion": {
|
||||
"apiVersion": number;
|
||||
"appVersion": null | string;
|
||||
};
|
||||
"CopyBlockRequest": {
|
||||
"blockGroupId": number;
|
||||
"name": null | string;
|
||||
};
|
||||
"CopyTemplateRequest": {
|
||||
"templateGroupId": number;
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateBlockGroupRequest": {
|
||||
"name": null | string;
|
||||
@@ -414,6 +422,13 @@ export interface components {
|
||||
"CreateSmartCollectionRequest": {
|
||||
"name": null | string;
|
||||
"query": null | string;
|
||||
};
|
||||
"CreateTemplateGroupRequest": {
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateTemplateRequest": {
|
||||
"templateGroupId": number;
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateWatermarkRequest": {
|
||||
"name": string;
|
||||
@@ -790,6 +805,10 @@ export interface components {
|
||||
};
|
||||
"ReplaceScheduleItemsRequest": {
|
||||
"items": null | Array<components["schemas"]["ScheduleItemRequest"]>;
|
||||
};
|
||||
"ReplaceTemplateRequest": {
|
||||
"name": null | string;
|
||||
"items": null | Array<components["schemas"]["TemplateItemRequest"]>;
|
||||
};
|
||||
"RerunCollectionViewModel": {
|
||||
"id": number;
|
||||
@@ -896,6 +915,34 @@ export interface components {
|
||||
"StartType": "Dynamic" | "Fixed";
|
||||
"StreamingMode": "TransportStream" | "HttpLiveStreamingDirect" | "HttpLiveStreamingSegmenter" | "TransportStreamHybrid";
|
||||
"TailMode": "None" | "Offline" | "Slate" | "Filler";
|
||||
"TemplateGroupResponseModel": {
|
||||
"id": number;
|
||||
"name": string;
|
||||
"templateCount": number;
|
||||
};
|
||||
"TemplateItemRequest": {
|
||||
"blockId": number;
|
||||
"startTime": string;
|
||||
};
|
||||
"TemplateItemResponseModel": {
|
||||
"blockId": number;
|
||||
"blockName": string;
|
||||
"blockMinutes": number;
|
||||
"startTime": string;
|
||||
};
|
||||
"TemplateResponseModel": {
|
||||
"id": number;
|
||||
"templateGroupId": number;
|
||||
"groupName": string;
|
||||
"name": string;
|
||||
};
|
||||
"TemplateWithItemsResponseModel": {
|
||||
"id": number;
|
||||
"templateGroupId": number;
|
||||
"groupName": string;
|
||||
"name": string;
|
||||
"items": Array<components["schemas"]["TemplateItemResponseModel"]>;
|
||||
};
|
||||
"TraktListResponseModel": {
|
||||
"id": number;
|
||||
"traktId": number;
|
||||
|
||||
@@ -19,6 +19,7 @@ export * from './playouts';
|
||||
export * from './schedules';
|
||||
export * from './search';
|
||||
export * from './settings';
|
||||
export * from './templates';
|
||||
export * from './trakt';
|
||||
export * from './troubleshoot';
|
||||
export * from './useChannelsQuery';
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
copyTemplate,
|
||||
createTemplate,
|
||||
createTemplateGroup,
|
||||
deleteTemplate,
|
||||
deleteTemplateGroup,
|
||||
getTemplate,
|
||||
getTemplateGroups,
|
||||
getTemplateItems,
|
||||
getTemplates,
|
||||
replaceTemplate,
|
||||
type ReplaceTemplateRequest
|
||||
} from './templates';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
function noContent(): Response {
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
const sampleReplace: ReplaceTemplateRequest = {
|
||||
name: 'Weekdays',
|
||||
items: [{ blockId: 10, startTime: '06:00:00' }]
|
||||
};
|
||||
|
||||
describe('templates api client', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('getTemplateGroups fetches all template groups', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([{ id: 1, name: 'Prime', templateCount: 2 }]));
|
||||
await expect(getTemplateGroups()).resolves.toHaveLength(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/templates/groups', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('createTemplateGroup POSTs the name', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 3, name: 'Prime', templateCount: 0 }, 201));
|
||||
await createTemplateGroup({ name: 'Prime' });
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/templates/groups');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
expect(JSON.parse(String(init?.body)).name).toBe('Prime');
|
||||
});
|
||||
|
||||
it('deleteTemplateGroup DELETEs by id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
|
||||
await expect(deleteTemplateGroup(3)).resolves.toBeUndefined();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/templates/groups/3', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
it('getTemplates fetches all templates', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await getTemplates();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/templates', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('getTemplate fetches a template by id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4 }));
|
||||
await getTemplate(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/templates/4', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('createTemplate POSTs group id and name', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 8 }, 201));
|
||||
await createTemplate({ templateGroupId: 2, name: 'Weekdays' });
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/templates');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
expect(JSON.parse(String(init?.body))).toMatchObject({ templateGroupId: 2, name: 'Weekdays' });
|
||||
});
|
||||
|
||||
it('deleteTemplate DELETEs by id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
|
||||
await deleteTemplate(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/templates/4', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
it('getTemplateItems fetches items for a template', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await getTemplateItems(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/templates/4/items', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('replaceTemplate PUTs the full template body', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4, items: [] }));
|
||||
await replaceTemplate(4, sampleReplace);
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/templates/4');
|
||||
expect(init).toMatchObject({ method: 'PUT' });
|
||||
const body = JSON.parse(String(init?.body));
|
||||
expect(body.name).toBe('Weekdays');
|
||||
expect(body.items).toHaveLength(1);
|
||||
expect(body.items[0]).toMatchObject({ blockId: 10, startTime: '06:00:00' });
|
||||
});
|
||||
|
||||
it('copyTemplate POSTs the target group and name to the copy route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 9 }, 201));
|
||||
await copyTemplate(4, { templateGroupId: 3, name: 'Weekdays Copy' });
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/templates/4/copy');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
expect(JSON.parse(String(init?.body))).toMatchObject({ templateGroupId: 3, name: 'Weekdays Copy' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ApiError, request } from './client';
|
||||
import type { components } from './generated/v1';
|
||||
|
||||
export type TemplateGroup = components['schemas']['TemplateGroupResponseModel'];
|
||||
export type Template = components['schemas']['TemplateResponseModel'];
|
||||
export type TemplateItem = components['schemas']['TemplateItemResponseModel'];
|
||||
export type TemplateWithItems = components['schemas']['TemplateWithItemsResponseModel'];
|
||||
export type CreateTemplateGroupRequest = components['schemas']['CreateTemplateGroupRequest'];
|
||||
export type CreateTemplateRequest = components['schemas']['CreateTemplateRequest'];
|
||||
export type ReplaceTemplateRequest = components['schemas']['ReplaceTemplateRequest'];
|
||||
export type TemplateItemRequest = components['schemas']['TemplateItemRequest'];
|
||||
export type CopyTemplateRequest = components['schemas']['CopyTemplateRequest'];
|
||||
|
||||
// Template groups
|
||||
|
||||
export function getTemplateGroups(): Promise<TemplateGroup[]> {
|
||||
return request<TemplateGroup[]>('/api/templates/groups');
|
||||
}
|
||||
|
||||
export function createTemplateGroup(body: CreateTemplateGroupRequest): Promise<TemplateGroup> {
|
||||
return request<TemplateGroup>('/api/templates/groups', { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteTemplateGroup(id: number): Promise<void> {
|
||||
return request<void>(`/api/templates/groups/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
// Templates
|
||||
|
||||
export function getTemplates(): Promise<Template[]> {
|
||||
return request<Template[]>('/api/templates');
|
||||
}
|
||||
|
||||
export function getTemplate(id: number): Promise<Template> {
|
||||
return request<Template>(`/api/templates/${id}`);
|
||||
}
|
||||
|
||||
export function createTemplate(body: CreateTemplateRequest): Promise<Template> {
|
||||
return request<Template>('/api/templates', { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteTemplate(id: number): Promise<void> {
|
||||
return request<void>(`/api/templates/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function getTemplateItems(id: number): Promise<TemplateItem[]> {
|
||||
return request<TemplateItem[]>(`/api/templates/${id}/items`);
|
||||
}
|
||||
|
||||
export function replaceTemplate(id: number, body: ReplaceTemplateRequest): Promise<TemplateWithItems> {
|
||||
return request<TemplateWithItems>(`/api/templates/${id}`, { body, method: 'PUT' });
|
||||
}
|
||||
|
||||
export function copyTemplate(id: number, body: CopyTemplateRequest): Promise<Template> {
|
||||
return request<Template>(`/api/templates/${id}/copy`, { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function messageFromTemplateError(error: unknown, fallback = 'Unable to load templates'): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.detail ?? error.message;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TemplatesScreen } from './TemplatesScreen';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
const groups = [{ id: 2, name: 'Prime', templateCount: 1 }];
|
||||
const templates = [{ id: 4, templateGroupId: 2, groupName: 'Prime', name: 'Weekdays' }];
|
||||
const blockGroups = [{ id: 1, name: 'Morning Blocks' }];
|
||||
const blocks = [{ id: 10, groupId: 1, groupName: 'Morning Blocks', name: 'Cartoons', minutes: 60, stopScheduling: 'AfterDurationEnd' }];
|
||||
|
||||
interface MockOptions {
|
||||
items?: unknown[];
|
||||
onRequest?: (url: string, method: string, body: unknown) => Response | null;
|
||||
}
|
||||
|
||||
function mockApi(options: MockOptions = {}) {
|
||||
const items = options.items ?? [];
|
||||
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
|
||||
|
||||
if (options.onRequest) {
|
||||
const override = options.onRequest(url, method, body);
|
||||
if (override) {
|
||||
return Promise.resolve(override);
|
||||
}
|
||||
}
|
||||
|
||||
if (url === '/api/templates/groups' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(groups));
|
||||
}
|
||||
if (url === '/api/templates' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(templates));
|
||||
}
|
||||
if (url === '/api/templates/4' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(templates[0]));
|
||||
}
|
||||
if (url === '/api/templates/4/items' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(items));
|
||||
}
|
||||
if (url === '/api/blocks/groups' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(blockGroups));
|
||||
}
|
||||
if (url === '/api/blocks' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(blocks));
|
||||
}
|
||||
if (url === '/api/templates/4' && method === 'PUT') {
|
||||
return Promise.resolve(jsonResponse({ ...templates[0], items: [] }));
|
||||
}
|
||||
if (url === '/api/templates/4/copy' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 5, templateGroupId: 2, groupName: 'Prime', name: 'Weekdays copy' }, 201));
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
}
|
||||
|
||||
describe('TemplatesScreen', () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
window.history.pushState({}, '', '/app/templates');
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
window.history.pushState({}, '', '/app/templates');
|
||||
});
|
||||
|
||||
it('renders template groups and their templates', async () => {
|
||||
mockApi();
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
expect(await screen.findByText('Prime')).toBeInTheDocument();
|
||||
expect(screen.getByText('Weekdays')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the copy dialog and POSTs to the copy route', async () => {
|
||||
mockApi();
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await screen.findByText('Weekdays');
|
||||
fireEvent.click(screen.getByRole('button', { name: /Copy template/ }));
|
||||
|
||||
const dialog = await screen.findByText('Copy "Weekdays"');
|
||||
expect(dialog).toBeInTheDocument();
|
||||
|
||||
const fetchMock = vi.spyOn(window, 'fetch');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Copy' }));
|
||||
|
||||
await waitFor(() => {
|
||||
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/templates/4/copy' && init?.method === 'POST');
|
||||
expect(call).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
it('loads the editor at a sub-path and lists items sorted by start time', async () => {
|
||||
window.history.pushState({}, '', '/app/templates/4');
|
||||
mockApi({
|
||||
items: [
|
||||
{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '12:00:00' },
|
||||
{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '06:00:00' }
|
||||
]
|
||||
});
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
|
||||
|
||||
const rows = screen.getAllByText(/^\d{2}:\d{2}-\d{2}:\d{2}$/);
|
||||
expect(rows[0]).toHaveTextContent('06:00-07:00');
|
||||
expect(rows[1]).toHaveTextContent('12:00-13:00');
|
||||
});
|
||||
|
||||
it('adds an item via the block group/block/start-time pickers', async () => {
|
||||
window.history.pushState({}, '', '/app/templates/4');
|
||||
mockApi({ items: [] });
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Block group'), { target: { value: '1' } });
|
||||
fireEvent.change(screen.getByLabelText('Block'), { target: { value: '10' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add' }));
|
||||
|
||||
const cell = await screen.findByRole('cell', { name: 'Cartoons' });
|
||||
expect(cell).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves the template with items via PUT', async () => {
|
||||
window.history.pushState({}, '', '/app/templates/4');
|
||||
const fetchMock = mockApi({
|
||||
items: [{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '06:00:00' }]
|
||||
});
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save template/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/templates/4' && init?.method === 'PUT');
|
||||
expect(call).toBeTruthy();
|
||||
});
|
||||
|
||||
const putCall = fetchMock.mock.calls.find(([u, init]) => u === '/api/templates/4' && init?.method === 'PUT');
|
||||
const sent = JSON.parse(String(putCall?.[1]?.body));
|
||||
expect(sent.name).toBe('Weekdays');
|
||||
expect(sent.items).toEqual([{ blockId: 10, startTime: '06:00:00' }]);
|
||||
});
|
||||
|
||||
it('excludes the synthesized negative-id "(none)" placeholder row from the block picker', async () => {
|
||||
window.history.pushState({}, '', '/app/templates/4');
|
||||
mockApi({
|
||||
items: [],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/blocks' && method === 'GET') {
|
||||
return jsonResponse([
|
||||
...blocks,
|
||||
{ id: -1, groupId: 1, groupName: 'Morning Blocks', name: '(none)', minutes: 0, stopScheduling: 'AfterDurationEnd' }
|
||||
]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Block group'), { target: { value: '1' } });
|
||||
|
||||
const blockSelect = screen.getByLabelText('Block') as HTMLSelectElement;
|
||||
const optionValues = Array.from(blockSelect.options).map((o) => o.value);
|
||||
expect(optionValues).toEqual(['', '10']);
|
||||
});
|
||||
|
||||
it('shows a midnight-crossing warning and blocks save when an item crosses midnight', async () => {
|
||||
window.history.pushState({}, '', '/app/templates/4');
|
||||
mockApi({
|
||||
items: [{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '23:30:00' }]
|
||||
});
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
|
||||
|
||||
expect(await screen.findByText(/crosses midnight/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Save template/ })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows an overlap warning and blocks save when two items intersect', async () => {
|
||||
window.history.pushState({}, '', '/app/templates/4');
|
||||
mockApi({
|
||||
items: [
|
||||
{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '06:00:00' },
|
||||
{ blockId: 10, blockName: 'Cartoons', blockMinutes: 60, startTime: '06:30:00' }
|
||||
]
|
||||
});
|
||||
render(<TemplatesScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Weekdays')).toBeInTheDocument());
|
||||
|
||||
expect(await screen.findByText(/overlaps/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Save template/ })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,767 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeft, Check, Copy, FolderPlus, Plus, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { navigateToPath } from '../routing';
|
||||
import { Badge, Button, Card, ConfirmDialog, Dialog, IconButton, Input, Select, Spinner } from '../components';
|
||||
import {
|
||||
copyTemplate,
|
||||
createTemplate,
|
||||
createTemplateGroup,
|
||||
deleteTemplate,
|
||||
deleteTemplateGroup,
|
||||
getBlockGroups,
|
||||
getBlocks,
|
||||
getTemplate,
|
||||
getTemplateGroups,
|
||||
getTemplateItems,
|
||||
getTemplates,
|
||||
messageFromTemplateError,
|
||||
replaceTemplate,
|
||||
type Block,
|
||||
type BlockGroup,
|
||||
type Template,
|
||||
type TemplateGroup,
|
||||
type TemplateItem
|
||||
} from '../api';
|
||||
|
||||
const BASE_PATH = '/app/templates';
|
||||
|
||||
// Every start time is a five-minute increment across a full day (mirrors Blazor TemplateEditor.razor's picker).
|
||||
const START_TIME_OPTIONS = Array.from({ length: 288 }, (_, index) => {
|
||||
const totalMinutes = index * 5;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const value = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00`;
|
||||
return { label: value.slice(0, 5), value };
|
||||
});
|
||||
|
||||
function timeToMinutes(time: string): number {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
function minutesToClock(totalMinutes: number): string {
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
interface DraftItem {
|
||||
key: string;
|
||||
blockId: number;
|
||||
blockName: string;
|
||||
blockMinutes: number;
|
||||
startTime: string;
|
||||
}
|
||||
|
||||
interface Draft {
|
||||
name: string;
|
||||
items: DraftItem[];
|
||||
}
|
||||
|
||||
let keySeq = 0;
|
||||
function nextKey(): string {
|
||||
keySeq += 1;
|
||||
return `item-${keySeq}`;
|
||||
}
|
||||
|
||||
function itemFromResponse(item: TemplateItem): DraftItem {
|
||||
return {
|
||||
key: nextKey(),
|
||||
blockId: item.blockId,
|
||||
blockName: item.blockName,
|
||||
blockMinutes: item.blockMinutes,
|
||||
startTime: item.startTime
|
||||
};
|
||||
}
|
||||
|
||||
// Mirrors ReplaceTemplateItemsHandler.TemplateItemsMustBeValid: an item's end time is its start
|
||||
// time plus the assigned block's duration; two items overlap when one starts before the other ends.
|
||||
function findOverlap(items: DraftItem[]): null | string {
|
||||
const spans = items.map((item) => ({
|
||||
item,
|
||||
start: timeToMinutes(item.startTime),
|
||||
end: timeToMinutes(item.startTime) + item.blockMinutes
|
||||
}));
|
||||
|
||||
for (let i = 0; i < spans.length; i += 1) {
|
||||
for (let j = i + 1; j < spans.length; j += 1) {
|
||||
const a = spans[i];
|
||||
const b = spans[j];
|
||||
if (a.start < b.end && b.start < a.end) {
|
||||
return `"${a.item.blockName}" (${minutesToClock(a.start)}-${minutesToClock(a.end)}) overlaps "${b.item.blockName}" (${minutesToClock(b.start)}-${minutesToClock(b.end)})`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Mirrors ReplaceTemplateItemsHandler's end-of-day check: an item's end time (start + block
|
||||
// duration) must not cross midnight. Exactly 24:00 is allowed; anything past it is rejected.
|
||||
function findMidnightCrossing(items: DraftItem[]): null | string {
|
||||
for (const item of items) {
|
||||
const start = timeToMinutes(item.startTime);
|
||||
const end = start + item.blockMinutes;
|
||||
if (end > 24 * 60) {
|
||||
return `"${item.blockName}" (${minutesToClock(start)}-${minutesToClock(end)}) crosses midnight, which is not supported`;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function validate(draft: Draft): null | string {
|
||||
if (!draft.name.trim()) {
|
||||
return 'Template name is required';
|
||||
}
|
||||
|
||||
return findMidnightCrossing(draft.items) ?? findOverlap(draft.items);
|
||||
}
|
||||
|
||||
type Mode = { id: number; kind: 'edit' } | { kind: 'list' };
|
||||
|
||||
function modeFromPath(pathname: string): Mode {
|
||||
const normalized = pathname.replace(/\/+$/, '');
|
||||
if (normalized === BASE_PATH || !normalized.startsWith(`${BASE_PATH}/`)) {
|
||||
return { kind: 'list' };
|
||||
}
|
||||
const suffix = normalized.slice(BASE_PATH.length + 1).split('/')[0];
|
||||
const id = Number(suffix);
|
||||
return Number.isInteger(id) && id > 0 ? { id, kind: 'edit' } : { kind: 'list' };
|
||||
}
|
||||
|
||||
export function TemplatesScreen() {
|
||||
const [pathname, setPathname] = useState(() => window.location.pathname);
|
||||
|
||||
useEffect(() => {
|
||||
const onPop = () => setPathname(window.location.pathname);
|
||||
window.addEventListener('popstate', onPop);
|
||||
return () => window.removeEventListener('popstate', onPop);
|
||||
}, []);
|
||||
|
||||
const mode = modeFromPath(pathname);
|
||||
|
||||
if (mode.kind === 'list') {
|
||||
return <TemplateList key={pathname} />;
|
||||
}
|
||||
|
||||
return <TemplateEditor key={pathname} templateId={mode.id} />;
|
||||
}
|
||||
|
||||
function TemplateList() {
|
||||
const [groups, setGroups] = useState<TemplateGroup[] | null>(null);
|
||||
const [templates, setTemplates] = useState<Template[] | null>(null);
|
||||
const [error, setError] = useState<null | string>(null);
|
||||
const [groupDialogOpen, setGroupDialogOpen] = useState(false);
|
||||
const [newGroupName, setNewGroupName] = useState('');
|
||||
const [templateDialogGroup, setTemplateDialogGroup] = useState<TemplateGroup | null>(null);
|
||||
const [newTemplateName, setNewTemplateName] = useState('');
|
||||
const [copyTarget, setCopyTarget] = useState<Template | null>(null);
|
||||
const [copyGroupId, setCopyGroupId] = useState('');
|
||||
const [copyName, setCopyName] = useState('');
|
||||
const [deleteGroupTarget, setDeleteGroupTarget] = useState<TemplateGroup | null>(null);
|
||||
const [deleteTemplateTarget, setDeleteTemplateTarget] = useState<Template | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const activeRef = useRef(true);
|
||||
|
||||
const load = useCallback(() => {
|
||||
Promise.all([getTemplateGroups(), getTemplates()])
|
||||
.then(([groupData, templateData]) => {
|
||||
if (activeRef.current) {
|
||||
setGroups(groupData);
|
||||
setTemplates(templateData);
|
||||
setError(null);
|
||||
}
|
||||
})
|
||||
.catch((loadError: unknown) => {
|
||||
if (activeRef.current) {
|
||||
setError(messageFromTemplateError(loadError));
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = true;
|
||||
load();
|
||||
return () => {
|
||||
activeRef.current = false;
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const createGroup = async () => {
|
||||
if (!newGroupName.trim() || busy) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await createTemplateGroup({ name: newGroupName.trim() });
|
||||
setGroupDialogOpen(false);
|
||||
setNewGroupName('');
|
||||
load();
|
||||
} catch (createError) {
|
||||
setError(messageFromTemplateError(createError, 'Unable to create template group'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const createTemplateInGroup = async () => {
|
||||
if (!templateDialogGroup || !newTemplateName.trim() || busy) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const template = await createTemplate({
|
||||
templateGroupId: templateDialogGroup.id,
|
||||
name: newTemplateName.trim()
|
||||
});
|
||||
setTemplateDialogGroup(null);
|
||||
setNewTemplateName('');
|
||||
navigateToPath(`${BASE_PATH}/${template.id}`);
|
||||
} catch (createError) {
|
||||
setError(messageFromTemplateError(createError, 'Unable to create template'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmCopy = async () => {
|
||||
if (!copyTarget || !copyGroupId || !copyName.trim() || busy) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await copyTemplate(copyTarget.id, { templateGroupId: Number(copyGroupId), name: copyName.trim() });
|
||||
setCopyTarget(null);
|
||||
load();
|
||||
} catch (copyError) {
|
||||
setError(messageFromTemplateError(copyError, 'Unable to copy template'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmDeleteGroup = async () => {
|
||||
if (!deleteGroupTarget) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await deleteTemplateGroup(deleteGroupTarget.id);
|
||||
setDeleteGroupTarget(null);
|
||||
load();
|
||||
} catch (deleteError) {
|
||||
setError(messageFromTemplateError(deleteError, 'Unable to delete template group'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmDeleteTemplate = async () => {
|
||||
if (!deleteTemplateTarget) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await deleteTemplate(deleteTemplateTarget.id);
|
||||
setDeleteTemplateTarget(null);
|
||||
load();
|
||||
} catch (deleteError) {
|
||||
setError(messageFromTemplateError(deleteError, 'Unable to delete template'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (error && (!groups || !templates)) {
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
<div className="ctv-channels-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={15} />
|
||||
<span>{error}</span>
|
||||
<span className="ctv-channels-spacer" />
|
||||
<Button onClick={load} size="sm" variant="secondary">
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!groups || !templates) {
|
||||
return (
|
||||
<div className="ctv-collections-loading" role="status">
|
||||
<Spinner size={18} />
|
||||
<span>Loading templates…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sortedGroups = [...groups].sort((a, b) => a.name.localeCompare(b.name));
|
||||
const groupOptions = sortedGroups.map((group) => ({ label: group.name, value: String(group.id) }));
|
||||
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
<div className="ctv-channels-actionbar">
|
||||
<Badge tone="neutral">{templates.length} templates</Badge>
|
||||
<span className="ctv-channels-spacer" />
|
||||
<Button
|
||||
onClick={() => {
|
||||
setNewGroupName('');
|
||||
setGroupDialogOpen(true);
|
||||
}}
|
||||
size="sm"
|
||||
startIcon={<FolderPlus aria-hidden="true" size={14} />}
|
||||
>
|
||||
New group
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="ctv-channels-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={15} />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sortedGroups.length === 0 ? (
|
||||
<Card>
|
||||
<div className="ctv-collections-empty">No template groups yet. Create one to get started.</div>
|
||||
</Card>
|
||||
) : (
|
||||
sortedGroups.map((group) => {
|
||||
const groupTemplates = templates
|
||||
.filter((t) => t.templateGroupId === group.id && t.id > 0)
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return (
|
||||
<Card
|
||||
key={group.id}
|
||||
padded={false}
|
||||
title={group.name}
|
||||
actions={
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setNewTemplateName('');
|
||||
setTemplateDialogGroup(group);
|
||||
}}
|
||||
size="sm"
|
||||
startIcon={<Plus aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
New template
|
||||
</Button>
|
||||
<IconButton
|
||||
onClick={() => setDeleteGroupTarget(group)}
|
||||
size="sm"
|
||||
title="Delete group"
|
||||
variant="ghost"
|
||||
>
|
||||
<Trash2 aria-hidden="true" size={14} />
|
||||
</IconButton>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{groupTemplates.length === 0 ? (
|
||||
<div className="ctv-collections-empty">No templates in this group.</div>
|
||||
) : (
|
||||
groupTemplates.map((template, index) => (
|
||||
<div
|
||||
className="ctv-settings-flush-row"
|
||||
key={template.id}
|
||||
style={index === 0 ? { borderTop: 'none' } : undefined}
|
||||
>
|
||||
<button
|
||||
className="ctv-settings-flush-row-main ctv-settings-flush-row-title ctv-collections-linkbtn"
|
||||
onClick={() => navigateToPath(`${BASE_PATH}/${template.id}`)}
|
||||
type="button"
|
||||
>
|
||||
{template.name}
|
||||
</button>
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
setCopyTarget(template);
|
||||
setCopyGroupId(String(template.templateGroupId));
|
||||
setCopyName(`${template.name} copy`);
|
||||
}}
|
||||
size="sm"
|
||||
title="Copy template"
|
||||
variant="ghost"
|
||||
>
|
||||
<Copy aria-hidden="true" size={14} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
onClick={() => setDeleteTemplateTarget(template)}
|
||||
size="sm"
|
||||
title="Delete template"
|
||||
variant="ghost"
|
||||
>
|
||||
<Trash2 aria-hidden="true" size={14} />
|
||||
</IconButton>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button onClick={() => setGroupDialogOpen(false)} size="sm" variant="ghost">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button disabled={!newGroupName.trim() || busy} loading={busy} onClick={() => void createGroup()} size="sm">
|
||||
Create
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={() => setGroupDialogOpen(false)}
|
||||
open={groupDialogOpen}
|
||||
title="New template group"
|
||||
>
|
||||
<Input
|
||||
label="Name"
|
||||
onChange={(event) => setNewGroupName(event.target.value)}
|
||||
placeholder="Template group name"
|
||||
value={newGroupName}
|
||||
/>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button onClick={() => setTemplateDialogGroup(null)} size="sm" variant="ghost">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!newTemplateName.trim() || busy}
|
||||
loading={busy}
|
||||
onClick={() => void createTemplateInGroup()}
|
||||
size="sm"
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={() => setTemplateDialogGroup(null)}
|
||||
open={templateDialogGroup !== null}
|
||||
title={templateDialogGroup ? `New template in ${templateDialogGroup.name}` : 'New template'}
|
||||
>
|
||||
<Input
|
||||
label="Name"
|
||||
onChange={(event) => setNewTemplateName(event.target.value)}
|
||||
placeholder="Template name"
|
||||
value={newTemplateName}
|
||||
/>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button onClick={() => setCopyTarget(null)} size="sm" variant="ghost">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!copyGroupId || !copyName.trim() || busy}
|
||||
loading={busy}
|
||||
onClick={() => void confirmCopy()}
|
||||
size="sm"
|
||||
>
|
||||
Copy
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={() => setCopyTarget(null)}
|
||||
open={copyTarget !== null}
|
||||
title={copyTarget ? `Copy "${copyTarget.name}"` : 'Copy template'}
|
||||
>
|
||||
<Select label="Target group" onChange={(event) => setCopyGroupId(event.target.value)} options={groupOptions} value={copyGroupId} />
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<Input label="New name" onChange={(event) => setCopyName(event.target.value)} value={copyName} />
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDialog
|
||||
busy={busy}
|
||||
confirmLabel="Delete"
|
||||
message={
|
||||
deleteGroupTarget
|
||||
? `Delete group "${deleteGroupTarget.name}"? Every template in it will also be deleted. This cannot be undone.`
|
||||
: ''
|
||||
}
|
||||
onCancel={() => setDeleteGroupTarget(null)}
|
||||
onConfirm={() => void confirmDeleteGroup()}
|
||||
open={deleteGroupTarget !== null}
|
||||
title="Delete template group"
|
||||
tone="danger"
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
busy={busy}
|
||||
confirmLabel="Delete"
|
||||
message={deleteTemplateTarget ? `Delete template "${deleteTemplateTarget.name}"? This cannot be undone.` : ''}
|
||||
onCancel={() => setDeleteTemplateTarget(null)}
|
||||
onConfirm={() => void confirmDeleteTemplate()}
|
||||
open={deleteTemplateTarget !== null}
|
||||
title="Delete template"
|
||||
tone="danger"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplateEditor({ templateId }: { templateId: number }) {
|
||||
const [template, setTemplate] = useState<Template | null>(null);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [blockGroups, setBlockGroups] = useState<BlockGroup[]>([]);
|
||||
const [blocks, setBlocks] = useState<Block[]>([]);
|
||||
const [loadError, setLoadError] = useState<null | string>(null);
|
||||
const [saveError, setSaveError] = useState<null | string>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const [addGroupId, setAddGroupId] = useState('');
|
||||
const [addBlockId, setAddBlockId] = useState('');
|
||||
const [addStartTime, setAddStartTime] = useState('00:00:00');
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
Promise.all([getTemplate(templateId), getTemplateItems(templateId), getBlockGroups(), getBlocks()])
|
||||
.then(([templateData, items, groupData, blockData]) => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
setTemplate(templateData);
|
||||
setBlockGroups(groupData);
|
||||
setBlocks(blockData);
|
||||
setDraft({
|
||||
name: templateData.name,
|
||||
items: items.map(itemFromResponse)
|
||||
});
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (active) {
|
||||
setLoadError(messageFromTemplateError(error, 'Unable to load template'));
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [templateId]);
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className="ctv-settings-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={16} />
|
||||
<span>{loadError}</span>
|
||||
<Button onClick={() => navigateToPath(BASE_PATH)} size="sm" variant="secondary">
|
||||
Back to templates
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!draft || !template) {
|
||||
return (
|
||||
<div className="ctv-settings-loading">
|
||||
<Spinner size={18} />
|
||||
<span>Loading template…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const setDraftValue = (patch: Partial<Draft>) => {
|
||||
setDraft((current) => (current ? { ...current, ...patch } : current));
|
||||
};
|
||||
|
||||
const removeItem = (key: string) => {
|
||||
setDraft((current) =>
|
||||
current ? { ...current, items: current.items.filter((item) => item.key !== key) } : current
|
||||
);
|
||||
};
|
||||
|
||||
// Blocks belong to a group by id; the group picker narrows the block picker's options (derived
|
||||
// during render, not via an effect, since it's a pure function of addGroupId + blocks).
|
||||
const groupOptions = [{ label: 'Select a block group…', value: '' }].concat(
|
||||
[...blockGroups].sort((a, b) => a.name.localeCompare(b.name)).map((g) => ({ label: g.name, value: String(g.id) }))
|
||||
);
|
||||
const blocksInGroup = addGroupId
|
||||
? blocks
|
||||
.filter((b) => b.groupId === Number(addGroupId) && b.id > 0)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
: [];
|
||||
const blockOptions = [{ label: 'Select a block…', value: '' }].concat(
|
||||
blocksInGroup.map((b) => ({ label: b.name, value: String(b.id) }))
|
||||
);
|
||||
|
||||
const addItem = () => {
|
||||
if (!addBlockId) {
|
||||
return;
|
||||
}
|
||||
const block = blocks.find((b) => b.id === Number(addBlockId));
|
||||
if (!block) {
|
||||
return;
|
||||
}
|
||||
const item: DraftItem = {
|
||||
key: nextKey(),
|
||||
blockId: block.id,
|
||||
blockName: block.name,
|
||||
blockMinutes: block.minutes,
|
||||
startTime: addStartTime
|
||||
};
|
||||
setDraft((current) => (current ? { ...current, items: [...current.items, item] } : current));
|
||||
};
|
||||
|
||||
const sortedItems = [...draft.items].sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
|
||||
const validationError = validate(draft);
|
||||
|
||||
const save = async () => {
|
||||
if (validationError || saving) {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
await replaceTemplate(templateId, {
|
||||
name: draft.name.trim(),
|
||||
items: draft.items.map((item) => ({ blockId: item.blockId, startTime: item.startTime }))
|
||||
});
|
||||
navigateToPath(BASE_PATH);
|
||||
} catch (error) {
|
||||
setSaveError(messageFromTemplateError(error, 'Unable to save template'));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
<div className="ctv-channels-actionbar">
|
||||
<Button
|
||||
onClick={() => navigateToPath(BASE_PATH)}
|
||||
size="sm"
|
||||
startIcon={<ArrowLeft aria-hidden="true" size={14} />}
|
||||
variant="ghost"
|
||||
>
|
||||
All templates
|
||||
</Button>
|
||||
<span className="ctv-collections-detail-title">{template.groupName} / Edit template</span>
|
||||
<span className="ctv-channels-spacer" />
|
||||
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
|
||||
<Button
|
||||
disabled={validationError !== null || saving}
|
||||
loading={saving}
|
||||
onClick={() => void save()}
|
||||
size="sm"
|
||||
startIcon={<Check aria-hidden="true" size={14} />}
|
||||
>
|
||||
Save template
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{validationError && (
|
||||
<div className="ctv-channels-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={15} />
|
||||
<span>{validationError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card padded={false} title="Template">
|
||||
<div className="ctv-settings-row" style={{ borderTop: 'none' }}>
|
||||
<div className="ctv-settings-row-main">
|
||||
<div className="ctv-settings-row-label">Template group</div>
|
||||
</div>
|
||||
<div className="ctv-settings-row-control" style={{ flex: '0 0 360px' }}>
|
||||
<Input disabled size="sm" value={template.groupName} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="ctv-settings-row">
|
||||
<div className="ctv-settings-row-main">
|
||||
<div className="ctv-settings-row-label">Template name</div>
|
||||
</div>
|
||||
<div className="ctv-settings-row-control" style={{ flex: '0 0 360px' }}>
|
||||
<Input
|
||||
error={draft.name.trim() ? null : 'Template name is required'}
|
||||
onChange={(event) => setDraftValue({ name: event.target.value })}
|
||||
size="sm"
|
||||
value={draft.name}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card padded={false} title="Add content">
|
||||
<div style={{ display: 'flex', gap: 12, padding: 16, flexWrap: 'wrap', alignItems: 'flex-end' }}>
|
||||
<div style={{ minWidth: 200 }}>
|
||||
<Select
|
||||
label="Block group"
|
||||
onChange={(event) => {
|
||||
setAddGroupId(event.target.value);
|
||||
setAddBlockId('');
|
||||
}}
|
||||
options={groupOptions}
|
||||
value={addGroupId}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ minWidth: 200 }}>
|
||||
<Select
|
||||
label="Block"
|
||||
onChange={(event) => setAddBlockId(event.target.value)}
|
||||
options={blockOptions}
|
||||
value={addBlockId}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ minWidth: 140 }}>
|
||||
<Select
|
||||
label="Start time"
|
||||
onChange={(event) => setAddStartTime(event.target.value)}
|
||||
options={START_TIME_OPTIONS}
|
||||
value={addStartTime}
|
||||
/>
|
||||
</div>
|
||||
<Button disabled={!addBlockId} onClick={addItem} size="sm" startIcon={<Plus aria-hidden="true" size={14} />}>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card padded={false} title="Template items">
|
||||
{sortedItems.length === 0 ? (
|
||||
<div className="ctv-collections-empty">No items yet. Add one above to build the template.</div>
|
||||
) : (
|
||||
<table className="ctv-channels-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Time</th>
|
||||
<th>Block</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sortedItems.map((item) => {
|
||||
const start = timeToMinutes(item.startTime);
|
||||
const end = start + item.blockMinutes;
|
||||
return (
|
||||
<tr key={item.key}>
|
||||
<td>
|
||||
{minutesToClock(start)}-{minutesToClock(end)}
|
||||
</td>
|
||||
<td>{item.blockName}</td>
|
||||
<td>
|
||||
<IconButton onClick={() => removeItem(item.key)} size="sm" title="Remove" variant="ghost">
|
||||
<Trash2 aria-hidden="true" size={14} />
|
||||
</IconButton>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user