@@ -25,13 +25,29 @@ public class CreateBlockHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
return Mapper.ProjectToViewModel(block);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Block>> Validate(TvContext dbContext, CreateBlock request) =>
|
||||
await ValidateBlockName(dbContext, request).MapT(name => new Block
|
||||
private static async Task<Validation<BaseError, Block>> Validate(TvContext dbContext, CreateBlock request)
|
||||
{
|
||||
Validation<BaseError, Unit> blockGroupValidation = await ValidateBlockGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateBlockName(dbContext, request);
|
||||
|
||||
return (blockGroupValidation, nameValidation).Apply((_, name) => new Block
|
||||
{
|
||||
BlockGroupId = request.BlockGroupId,
|
||||
Name = name,
|
||||
Minutes = 30
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateBlockGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateBlock request)
|
||||
{
|
||||
bool blockGroupExists = await dbContext.BlockGroups.AnyAsync(bg => bg.Id == request.BlockGroupId);
|
||||
|
||||
return blockGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Block group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateBlockName(
|
||||
TvContext dbContext,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockGroupResponseModel(int Id, string Name);
|
||||
@@ -0,0 +1,24 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockItemResponseModel(
|
||||
int Id,
|
||||
int Index,
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
string? CollectionName,
|
||||
int? MultiCollectionId,
|
||||
string? MultiCollectionName,
|
||||
int? SmartCollectionId,
|
||||
string? SmartCollectionName,
|
||||
int? MediaItemId,
|
||||
string? MediaItemName,
|
||||
string SearchTitle,
|
||||
string SearchQuery,
|
||||
PlaybackOrder PlaybackOrder,
|
||||
bool IncludeInProgramGuide,
|
||||
bool DisableWatermarks,
|
||||
List<int> WatermarkIds,
|
||||
List<int> GraphicsElementIds);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockPreviewItemResponseModel(
|
||||
string Title,
|
||||
TimeSpan Start,
|
||||
TimeSpan Finish,
|
||||
string Duration);
|
||||
@@ -0,0 +1,12 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockResponseModel(
|
||||
int Id,
|
||||
int GroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
int Minutes,
|
||||
BlockStopScheduling StopScheduling);
|
||||
@@ -0,0 +1,13 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
public record BlockWithItemsResponseModel(
|
||||
int Id,
|
||||
int GroupId,
|
||||
string GroupName,
|
||||
string Name,
|
||||
int Minutes,
|
||||
BlockStopScheduling StopScheduling,
|
||||
List<BlockItemResponseModel> Items);
|
||||
@@ -0,0 +1,8 @@
|
||||
#nullable enable
|
||||
namespace ErsatzTV.Core.Api.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// A lightweight {id, name} option used by the block/schedule editor pickers
|
||||
/// (collection, television show, television season, smart collection search).
|
||||
/// </summary>
|
||||
public record SchedulingPickerOptionResponseModel(int Id, string Name);
|
||||
@@ -25,6 +25,7 @@ public class ApiControllerSecurityTests
|
||||
{
|
||||
Type[] apiControllers =
|
||||
[
|
||||
typeof(BlockController),
|
||||
typeof(ChannelController),
|
||||
typeof(CollectionController),
|
||||
typeof(FFmpegProfileController),
|
||||
|
||||
@@ -68,6 +68,17 @@ public class ApiErrorResponseMetadataTests
|
||||
[TestCase(typeof(ScheduleController), nameof(ScheduleController.ReplaceItems), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(ScheduleController), nameof(ScheduleController.DeleteItem), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(ScheduleController), nameof(ScheduleController.DeleteItem), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.CreateGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.CreateGroup), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.DeleteGroup), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.Delete), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(BlockController), nameof(BlockController.GetItems), StatusCodes.Status404NotFound)]
|
||||
[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(PlayoutController), nameof(PlayoutController.GetById), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status404NotFound)]
|
||||
[TestCase(typeof(PlayoutController), nameof(PlayoutController.Create), StatusCodes.Status422UnprocessableEntity)]
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
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 ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Domain.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;
|
||||
using Unit = LanguageExt.Unit;
|
||||
|
||||
namespace ErsatzTV.Tests.Controllers;
|
||||
|
||||
[TestFixture]
|
||||
public class BlockControllerTests
|
||||
{
|
||||
private BlockController _controller = null!;
|
||||
private IMediator _mediator = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_mediator = Substitute.For<IMediator>();
|
||||
_controller = new BlockController(_mediator);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
|
||||
{
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetGroups), "GET", "/api/blocks/groups");
|
||||
ShouldHaveActionRoute(nameof(BlockController.CreateGroup), "POST", "/api/blocks/groups");
|
||||
ShouldHaveActionRoute(nameof(BlockController.DeleteGroup), "DELETE", "/api/blocks/groups/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetAll), "GET", "/api/blocks");
|
||||
ShouldHaveActionRoute(nameof(BlockController.GetById), "GET", "/api/blocks/{id:int}");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Create), "POST", "/api/blocks");
|
||||
ShouldHaveActionRoute(nameof(BlockController.Delete), "DELETE", "/api/blocks/{id:int}");
|
||||
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");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_201_With_Location_And_Body()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlockGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, BlockGroupViewModel>(new BlockGroupViewModel(5, "Prime Time")));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateBlockGroupRequest("Prime Time"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/blocks/groups/5");
|
||||
created.Value.ShouldBeOfType<BlockGroupResponseModel>().Name.ShouldBe("Prime Time");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateBlockGroup>(c => c.Name == "Prime Time"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateGroup_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlockGroup>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, BlockGroupViewModel>(BaseError.New("bad")));
|
||||
|
||||
IActionResult result = await _controller.CreateGroup(
|
||||
new CreateBlockGroupRequest(string.Empty),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_204_When_Exists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllBlockGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockGroupViewModel> { new(3, "Prime Time") });
|
||||
_mediator.Send(Arg.Any<DeleteBlockGroup>(), 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<DeleteBlockGroup>(c => c.BlockGroupId == 3),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeleteGroup_Should_Return_404_When_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllBlockGroups>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockGroupViewModel>());
|
||||
|
||||
IActionResult result = await _controller.DeleteGroup(99, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteBlockGroup>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAll_Should_Map_ViewModels_To_Response_Models()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetAllBlocks>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockViewModel> { MakeBlock(1, 2, "Morning") });
|
||||
|
||||
List<BlockResponseModel> result = await _controller.GetAll(CancellationToken.None);
|
||||
|
||||
result.Count.ShouldBe(1);
|
||||
result[0].Id.ShouldBe(1);
|
||||
result[0].GroupId.ShouldBe(2);
|
||||
result[0].Name.ShouldBe("Morning");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_201_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, BlockViewModel>(MakeBlock(8, 2, "Morning")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateBlockRequest(2, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
var created = result.ShouldBeOfType<CreatedResult>();
|
||||
created.Location.ShouldBe("/api/blocks/8");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<CreateBlock>(c => c.BlockGroupId == 2 && c.Name == "Morning"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Create_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<CreateBlock>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, BlockViewModel>(BaseError.New("dupe")));
|
||||
|
||||
IActionResult result = await _controller.Create(
|
||||
new CreateBlockRequest(2, "Morning"),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_200_For_Some()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
|
||||
IActionResult result = await _controller.GetById(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<BlockResponseModel>().Id.ShouldBe(4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetById_Should_Return_404_For_None()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.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<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<DeleteBlock>(), 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<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Delete(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<DeleteBlock>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_200_Ordered_By_Index()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 2, "Morning")));
|
||||
_mediator.Send(Arg.Any<GetBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockItemViewModel> { MakeItem(20, 1), MakeItem(10, 0) });
|
||||
|
||||
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
|
||||
|
||||
var items = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<List<BlockItemResponseModel>>();
|
||||
items.Count.ShouldBe(2);
|
||||
items[0].Index.ShouldBe(0);
|
||||
items[1].Index.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetItems_Should_Return_404_When_Block_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_200_With_Refreshed_Block_And_Assign_Index_And_GroupId()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<ReplaceBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, Unit>(Unit.Default));
|
||||
_mediator.Send(Arg.Any<GetBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<BlockItemViewModel> { MakeItem(10, 0), MakeItem(11, 1) });
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceBlockRequest(
|
||||
"Morning",
|
||||
60,
|
||||
BlockStopScheduling.BeforeDurationEnd,
|
||||
[MakeItemRequest(), MakeItemRequest()]),
|
||||
CancellationToken.None);
|
||||
|
||||
var body = result.ShouldBeOfType<OkObjectResult>().Value.ShouldBeOfType<BlockWithItemsResponseModel>();
|
||||
body.Id.ShouldBe(4);
|
||||
body.Items.Count.ShouldBe(2);
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<ReplaceBlockItems>(c =>
|
||||
c.BlockId == 4 &&
|
||||
c.BlockGroupId == 7 &&
|
||||
c.Minutes == 60 &&
|
||||
c.StopScheduling == BlockStopScheduling.BeforeDurationEnd &&
|
||||
c.Items.Count == 2 &&
|
||||
c.Items[0].Index == 0 &&
|
||||
c.Items[1].Index == 1),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_404_When_Block_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<ReplaceBlockItems>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Replace_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<ReplaceBlockItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, Unit>(BaseError.New("bad minutes")));
|
||||
|
||||
IActionResult result = await _controller.Replace(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 7, BlockStopScheduling.AfterDurationEnd, []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Preview_Should_Return_200_With_Preview_Items()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.Some(MakeBlock(4, 7, "Morning")));
|
||||
_mediator.Send(Arg.Any<PreviewBlockPlayout>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PlayoutItemPreviewViewModel>
|
||||
{
|
||||
new("Show", TimeSpan.Zero, TimeSpan.FromMinutes(30), "00:30:00")
|
||||
});
|
||||
|
||||
IActionResult result = await _controller.Preview(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, [MakeItemRequest()]),
|
||||
CancellationToken.None);
|
||||
|
||||
var items = result.ShouldBeOfType<OkObjectResult>().Value
|
||||
.ShouldBeOfType<List<BlockPreviewItemResponseModel>>();
|
||||
items.Count.ShouldBe(1);
|
||||
items[0].Title.ShouldBe("Show");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<PreviewBlockPlayout>(p => p.Data.BlockId == 4 && p.Data.BlockGroupId == 7),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Preview_Should_Return_404_When_Block_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetBlockById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<BlockViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.Preview(
|
||||
4,
|
||||
new ReplaceBlockRequest("Morning", 60, BlockStopScheduling.AfterDurationEnd, []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<PreviewBlockPlayout>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
private static BlockViewModel MakeBlock(int id, int groupId, string name) =>
|
||||
new(id, groupId, "Group", name, 30, BlockStopScheduling.AfterDurationEnd);
|
||||
|
||||
private static BlockItemViewModel MakeItem(int id, int index) =>
|
||||
new(
|
||||
id,
|
||||
index,
|
||||
CollectionType.SearchQuery,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
"News",
|
||||
"news",
|
||||
PlaybackOrder.Shuffle,
|
||||
IncludeInProgramGuide: true,
|
||||
DisableWatermarks: false,
|
||||
[],
|
||||
[]);
|
||||
|
||||
private static BlockItemRequest MakeItemRequest() =>
|
||||
new(
|
||||
CollectionType.SearchQuery,
|
||||
CollectionId: null,
|
||||
MultiCollectionId: null,
|
||||
SmartCollectionId: null,
|
||||
MediaItemId: null,
|
||||
SearchTitle: "News",
|
||||
SearchQuery: "news",
|
||||
PlaybackOrder: PlaybackOrder.Shuffle,
|
||||
IncludeInProgramGuide: true,
|
||||
DisableWatermarks: false,
|
||||
WatermarkIds: [],
|
||||
GraphicsElementIds: []);
|
||||
|
||||
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
|
||||
{
|
||||
MethodInfo action = typeof(BlockController).GetMethod(actionName)
|
||||
?? throw new AssertionException($"Missing action {actionName}");
|
||||
|
||||
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
|
||||
attribute.HttpMethods.ShouldContain(httpMethod);
|
||||
attribute.Template.ShouldBe(route);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
using System.Reflection;
|
||||
using ErsatzTV.Application.MediaCollections;
|
||||
using ErsatzTV.Application.MediaItems;
|
||||
using ErsatzTV.Application.Search;
|
||||
using ErsatzTV.Controllers.Api;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using ErsatzTV.Core.Api.Search;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Routing;
|
||||
@@ -71,6 +75,53 @@ public class SearchControllerTests
|
||||
ok.Value.ShouldBe(results);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SearchCollections_Should_Map_To_Picker_Options()
|
||||
{
|
||||
_mediator.Send(Arg.Any<SearchCollections>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<MediaCollectionViewModel>
|
||||
{
|
||||
new(CollectionType.Collection, 3, "Movies", false, new MediaItemState())
|
||||
});
|
||||
|
||||
List<SchedulingPickerOptionResponseModel> result =
|
||||
await _controller.SearchCollections("mov", CancellationToken.None);
|
||||
|
||||
result.ShouldHaveSingleItem();
|
||||
result[0].Id.ShouldBe(3);
|
||||
result[0].Name.ShouldBe("Movies");
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<SearchCollections>(q => q.Query == "mov"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SearchTelevisionShows_Should_Map_MediaItemId_To_Option_Id()
|
||||
{
|
||||
_mediator.Send(Arg.Any<SearchTelevisionShows>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<NamedMediaItemViewModel> { new(42, "The Show") });
|
||||
|
||||
List<SchedulingPickerOptionResponseModel> result =
|
||||
await _controller.SearchTelevisionShows("show", CancellationToken.None);
|
||||
|
||||
result.ShouldHaveSingleItem();
|
||||
result[0].Id.ShouldBe(42);
|
||||
result[0].Name.ShouldBe("The Show");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SearchSmartCollections_Should_Map_To_Picker_Options()
|
||||
{
|
||||
_mediator.Send(Arg.Any<SearchSmartCollections>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<SmartCollectionViewModel> { new(9, "Recent", "query") });
|
||||
|
||||
List<SchedulingPickerOptionResponseModel> result =
|
||||
await _controller.SearchSmartCollections("rec", CancellationToken.None);
|
||||
|
||||
result.ShouldHaveSingleItem();
|
||||
result[0].Id.ShouldBe(9);
|
||||
}
|
||||
|
||||
private static SearchResultsResponseModel EmptyResults()
|
||||
{
|
||||
var empty = new SearchResultGroupResponseModel(0, []);
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
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 BlockController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
[HttpGet("/api/blocks/groups", Name = "GetBlockGroups")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Get all block groups")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<BlockGroupResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<BlockGroupResponseModel>> GetGroups(CancellationToken cancellationToken)
|
||||
{
|
||||
List<BlockGroupViewModel> groups = await mediator.Send(new GetAllBlockGroups(), cancellationToken);
|
||||
return groups.Map(ProjectToResponseModel).ToList();
|
||||
}
|
||||
|
||||
[HttpPost("/api/blocks/groups")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Create a block group")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(BlockGroupResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> CreateGroup(
|
||||
[Required] [FromBody] CreateBlockGroupRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Either<BaseError, BlockGroupViewModel> result =
|
||||
await mediator.Send(request.ToCommand(), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/blocks/groups/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
[HttpDelete("/api/blocks/groups/{id:int}")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Delete a block group")]
|
||||
[EndpointDescription(
|
||||
"Deletes the block group. The database cascade removes every block (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<BlockGroupViewModel> groups = await mediator.Send(new GetAllBlockGroups(), cancellationToken);
|
||||
if (groups.All(g => g.Id != id))
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(new DeleteBlockGroup(id), cancellationToken);
|
||||
return result.Match<IActionResult>(
|
||||
Some: error => error.ToErrorResult(),
|
||||
None: () => new NoContentResult());
|
||||
}
|
||||
|
||||
[HttpGet("/api/blocks")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Get all blocks")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<BlockResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<BlockResponseModel>> GetAll(CancellationToken cancellationToken)
|
||||
{
|
||||
List<BlockViewModel> blocks = await mediator.Send(new GetAllBlocks(), cancellationToken);
|
||||
return blocks.Map(ProjectToResponseModel).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/blocks/{id:int}", Name = "GetBlockById")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Get a block by id")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(BlockResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<BlockViewModel> result = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
return result.Map(ProjectToResponseModel).ToGetResult();
|
||||
}
|
||||
|
||||
[HttpPost("/api/blocks")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Create a block")]
|
||||
[EndpointDescription("Creates an empty block in the given block group. The block defaults to 30 minutes.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(BlockResponseModel), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Create(
|
||||
[Required] [FromBody] CreateBlockRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Either<BaseError, BlockViewModel> result = await mediator.Send(request.ToCommand(), cancellationToken);
|
||||
return result.ToCreatedResult(
|
||||
vm => $"/api/blocks/{vm.Id}",
|
||||
vm => ProjectToResponseModel(vm));
|
||||
}
|
||||
|
||||
[HttpDelete("/api/blocks/{id:int}")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Delete a block")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<BlockViewModel> existing = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
if (existing.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
Option<BaseError> result = await mediator.Send(new DeleteBlock(id), cancellationToken);
|
||||
return result.Match<IActionResult>(
|
||||
Some: error => error.ToErrorResult(),
|
||||
None: () => new NoContentResult());
|
||||
}
|
||||
|
||||
[HttpGet("/api/blocks/{id:int}/items")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Get block items")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<BlockItemResponseModel>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetItems(int id, CancellationToken cancellationToken)
|
||||
{
|
||||
Option<BlockViewModel> block = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
if (block.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
List<BlockItemViewModel> items = await mediator.Send(new GetBlockItems(id), cancellationToken);
|
||||
return new OkObjectResult(items.OrderBy(i => i.Index).Map(ProjectToResponseModel).ToList());
|
||||
}
|
||||
|
||||
[HttpPut("/api/blocks/{id:int}")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Replace a block and its items")]
|
||||
[EndpointDescription(
|
||||
"Replaces the block's name/minutes/stop-scheduling and its full item list. Item indexes are assigned " +
|
||||
"from the array order. Minutes must be greater than zero, divisible by 5, and at most 24 hours.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(BlockWithItemsResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
|
||||
public async Task<IActionResult> Replace(
|
||||
int id,
|
||||
[Required] [FromBody] ReplaceBlockRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<BlockViewModel> maybeBlock = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
if (maybeBlock.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
int groupId = maybeBlock.Map(b => b.GroupId).IfNone(0);
|
||||
|
||||
Either<BaseError, Unit> result =
|
||||
await mediator.Send(request.ToCommand(groupId, id), cancellationToken);
|
||||
|
||||
return await result.Match(
|
||||
Left: error => Task.FromResult(error.ToErrorResult()),
|
||||
Right: async _ =>
|
||||
{
|
||||
Option<BlockViewModel> refreshed = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
List<BlockItemViewModel> items = await mediator.Send(new GetBlockItems(id), cancellationToken);
|
||||
return refreshed.Match(
|
||||
Some: vm => (IActionResult)new OkObjectResult(
|
||||
ProjectToWithItemsResponseModel(vm, items)),
|
||||
None: () => ApiResults.NotFoundProblem());
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost("/api/blocks/{id:int}/preview")]
|
||||
[Tags("Blocks")]
|
||||
[EndpointSummary("Preview a block playout")]
|
||||
[EndpointDescription(
|
||||
"Builds a preview playout from the supplied block definition without persisting any changes to the " +
|
||||
"block, its items, or any playout. Returns the resulting start/finish/title/duration list.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<BlockPreviewItemResponseModel>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Preview(
|
||||
int id,
|
||||
[Required] [FromBody] ReplaceBlockRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<BlockViewModel> maybeBlock = await mediator.Send(new GetBlockById(id), cancellationToken);
|
||||
if (maybeBlock.IsNone)
|
||||
{
|
||||
return ApiResults.NotFoundProblem();
|
||||
}
|
||||
|
||||
int groupId = maybeBlock.Map(b => b.GroupId).IfNone(0);
|
||||
|
||||
List<PlayoutItemPreviewViewModel> preview = await mediator.Send(
|
||||
new PreviewBlockPlayout(request.ToCommand(groupId, id)),
|
||||
cancellationToken);
|
||||
|
||||
return new OkObjectResult(preview.Map(ProjectToResponseModel).ToList());
|
||||
}
|
||||
|
||||
private static BlockGroupResponseModel ProjectToResponseModel(BlockGroupViewModel vm) =>
|
||||
new(vm.Id, vm.Name);
|
||||
|
||||
private static BlockResponseModel ProjectToResponseModel(BlockViewModel vm) =>
|
||||
new(vm.Id, vm.GroupId, vm.GroupName, vm.Name, vm.Minutes, vm.StopScheduling);
|
||||
|
||||
private static BlockWithItemsResponseModel ProjectToWithItemsResponseModel(
|
||||
BlockViewModel vm,
|
||||
List<BlockItemViewModel> items) =>
|
||||
new(
|
||||
vm.Id,
|
||||
vm.GroupId,
|
||||
vm.GroupName,
|
||||
vm.Name,
|
||||
vm.Minutes,
|
||||
vm.StopScheduling,
|
||||
items.OrderBy(i => i.Index).Map(ProjectToResponseModel).ToList());
|
||||
|
||||
private static BlockItemResponseModel ProjectToResponseModel(BlockItemViewModel vm) =>
|
||||
new(
|
||||
vm.Id,
|
||||
vm.Index,
|
||||
vm.CollectionType,
|
||||
vm.Collection?.Id,
|
||||
vm.Collection?.Name,
|
||||
vm.MultiCollection?.Id,
|
||||
vm.MultiCollection?.Name,
|
||||
vm.SmartCollection?.Id,
|
||||
vm.SmartCollection?.Name,
|
||||
vm.MediaItem?.MediaItemId,
|
||||
vm.MediaItem?.Name,
|
||||
vm.SearchTitle,
|
||||
vm.SearchQuery,
|
||||
vm.PlaybackOrder,
|
||||
vm.IncludeInProgramGuide,
|
||||
vm.DisableWatermarks,
|
||||
vm.Watermarks.Map(w => w.Id).ToList(),
|
||||
vm.GraphicsElements.Map(g => g.Id).ToList());
|
||||
|
||||
private static BlockPreviewItemResponseModel ProjectToResponseModel(PlayoutItemPreviewViewModel vm) =>
|
||||
new(vm.Title, vm.Start, vm.Finish, vm.Duration);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Core.Domain;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record BlockItemRequest(
|
||||
CollectionType CollectionType,
|
||||
int? CollectionId,
|
||||
int? MultiCollectionId,
|
||||
int? SmartCollectionId,
|
||||
int? MediaItemId,
|
||||
string SearchTitle,
|
||||
string SearchQuery,
|
||||
PlaybackOrder PlaybackOrder,
|
||||
bool IncludeInProgramGuide,
|
||||
bool DisableWatermarks,
|
||||
List<int> WatermarkIds,
|
||||
List<int> GraphicsElementIds)
|
||||
{
|
||||
public ReplaceBlockItem ToReplaceItem(int index) =>
|
||||
new(
|
||||
index,
|
||||
CollectionType,
|
||||
CollectionId,
|
||||
MultiCollectionId,
|
||||
SmartCollectionId,
|
||||
MediaItemId,
|
||||
SearchTitle,
|
||||
SearchQuery,
|
||||
PlaybackOrder,
|
||||
IncludeInProgramGuide,
|
||||
DisableWatermarks,
|
||||
WatermarkIds ?? [],
|
||||
GraphicsElementIds ?? []);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CreateBlockGroupRequest(string Name)
|
||||
{
|
||||
public CreateBlockGroup ToCommand() => new(Name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record CreateBlockRequest(int BlockGroupId, string Name)
|
||||
{
|
||||
public CreateBlock ToCommand() => new(BlockGroupId, Name);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using ErsatzTV.Application.Scheduling;
|
||||
using ErsatzTV.Core.Domain.Scheduling;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record ReplaceBlockRequest(
|
||||
string Name,
|
||||
int Minutes,
|
||||
BlockStopScheduling StopScheduling,
|
||||
List<BlockItemRequest> Items)
|
||||
{
|
||||
public ReplaceBlockItems ToCommand(int blockGroupId, int blockId) =>
|
||||
new(
|
||||
blockGroupId,
|
||||
blockId,
|
||||
Name,
|
||||
Minutes,
|
||||
StopScheduling,
|
||||
(Items ?? []).Select((item, index) => item.ToReplaceItem(index)).ToList());
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using ErsatzTV.Application.MediaCollections;
|
||||
using ErsatzTV.Application.MediaItems;
|
||||
using ErsatzTV.Application.Search;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Api.Scheduling;
|
||||
using ErsatzTV.Core.Api.Search;
|
||||
using ErsatzTV.Extensions;
|
||||
using MediatR;
|
||||
@@ -35,4 +38,68 @@ public class SearchController(IMediator mediator) : ControllerBase
|
||||
cancellationToken);
|
||||
return new OkObjectResult(result);
|
||||
}
|
||||
|
||||
[HttpGet("/api/search/collections", Name = "SearchCollections")]
|
||||
[Tags("Search")]
|
||||
[EndpointSummary("Search collections by name")]
|
||||
[EndpointDescription("Returns matching collections as {id, name} options for scheduling editors.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<SchedulingPickerOptionResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<SchedulingPickerOptionResponseModel>> SearchCollections(
|
||||
[FromQuery] string query = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<MediaCollectionViewModel> results = await mediator.Send(
|
||||
new SearchCollections(query ?? string.Empty),
|
||||
cancellationToken);
|
||||
return results.Map(c => new SchedulingPickerOptionResponseModel(c.Id, c.Name)).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/search/television-shows", Name = "SearchTelevisionShows")]
|
||||
[Tags("Search")]
|
||||
[EndpointSummary("Search television shows by name")]
|
||||
[EndpointDescription("Returns matching television shows as {id, name} options for scheduling editors.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<SchedulingPickerOptionResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<SchedulingPickerOptionResponseModel>> SearchTelevisionShows(
|
||||
[FromQuery] string query = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<NamedMediaItemViewModel> results = await mediator.Send(
|
||||
new SearchTelevisionShows(query ?? string.Empty),
|
||||
cancellationToken);
|
||||
return results.Map(s => new SchedulingPickerOptionResponseModel(s.MediaItemId, s.Name)).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/search/television-seasons", Name = "SearchTelevisionSeasons")]
|
||||
[Tags("Search")]
|
||||
[EndpointSummary("Search television seasons by name")]
|
||||
[EndpointDescription("Returns matching television seasons as {id, name} options for scheduling editors.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<SchedulingPickerOptionResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<SchedulingPickerOptionResponseModel>> SearchTelevisionSeasons(
|
||||
[FromQuery] string query = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<NamedMediaItemViewModel> results = await mediator.Send(
|
||||
new SearchTelevisionSeasons(query ?? string.Empty),
|
||||
cancellationToken);
|
||||
return results.Map(s => new SchedulingPickerOptionResponseModel(s.MediaItemId, s.Name)).ToList();
|
||||
}
|
||||
|
||||
[HttpGet("/api/search/smart-collections", Name = "SearchSmartCollections")]
|
||||
[Tags("Search")]
|
||||
[EndpointSummary("Search smart collections by name")]
|
||||
[EndpointDescription("Returns matching smart collections as {id, name} options for scheduling editors.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(List<SchedulingPickerOptionResponseModel>), StatusCodes.Status200OK)]
|
||||
public async Task<List<SchedulingPickerOptionResponseModel>> SearchSmartCollections(
|
||||
[FromQuery] string query = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<SmartCollectionViewModel> results = await mediator.Send(
|
||||
new SearchSmartCollections(query ?? string.Empty),
|
||||
cancellationToken);
|
||||
return results.Map(c => new SchedulingPickerOptionResponseModel(c.Id, c.Name)).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,7 @@ import {
|
||||
import {
|
||||
ArrowDownWideNarrow,
|
||||
Bell,
|
||||
Boxes,
|
||||
CalendarClock,
|
||||
Cast,
|
||||
Check,
|
||||
@@ -70,6 +71,7 @@ import { TraktListsScreen } from './screens/TraktListsScreen';
|
||||
import { TrashScreen } from './screens/TrashScreen';
|
||||
import { TroubleshootingScreen } from './screens/TroubleshootingScreen';
|
||||
import { WatermarksScreen } from './screens/WatermarksScreen';
|
||||
import { BlocksScreen } from './screens/BlocksScreen';
|
||||
import { navigateToPath } from './routing';
|
||||
import {
|
||||
Badge,
|
||||
@@ -149,6 +151,7 @@ type ScreenId =
|
||||
| 'editChannel'
|
||||
| 'guide'
|
||||
| 'schedules'
|
||||
| 'blocks'
|
||||
| 'playouts'
|
||||
| 'media'
|
||||
| 'search'
|
||||
@@ -250,6 +253,19 @@ const routes: ScreenRoute[] = [
|
||||
primaryAction: 'Add Schedule',
|
||||
placeholder: 'Schedule editor workspace'
|
||||
},
|
||||
{
|
||||
// The editor lives at a sub-path (/app/blocks/{id}); BlocksScreen owns parsing the id suffix.
|
||||
id: 'blocks',
|
||||
path: '/app/blocks',
|
||||
label: 'Blocks',
|
||||
title: 'Blocks',
|
||||
kicker: 'Programming',
|
||||
description: 'Group blocks and edit their items, durations, and playout preview.',
|
||||
icon: <Boxes aria-hidden="true" size={16} />,
|
||||
primaryAction: 'New Group',
|
||||
placeholder: 'Blocks workspace',
|
||||
allowSubPaths: true
|
||||
},
|
||||
{
|
||||
id: 'playouts',
|
||||
path: '/app/playouts',
|
||||
@@ -413,6 +429,7 @@ const primaryNavIds: ScreenId[] = [
|
||||
'builder',
|
||||
'guide',
|
||||
'schedules',
|
||||
'blocks',
|
||||
'playouts'
|
||||
];
|
||||
const mediaNavIds: ScreenId[] = [
|
||||
@@ -3377,6 +3394,10 @@ function ScreenContent({
|
||||
return <ScheduleScreen />;
|
||||
}
|
||||
|
||||
if (route.id === 'blocks') {
|
||||
return <BlocksScreen key={window.location.pathname} />;
|
||||
}
|
||||
|
||||
if (route.id === 'playouts') {
|
||||
return <PlayoutsScreen />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createBlock,
|
||||
createBlockGroup,
|
||||
deleteBlock,
|
||||
deleteBlockGroup,
|
||||
getBlock,
|
||||
getBlockGroups,
|
||||
getBlockItems,
|
||||
getBlocks,
|
||||
previewBlock,
|
||||
replaceBlock,
|
||||
searchCollections,
|
||||
searchSmartCollections,
|
||||
searchTelevisionSeasons,
|
||||
searchTelevisionShows,
|
||||
type ReplaceBlockRequest
|
||||
} from './blocks';
|
||||
|
||||
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: ReplaceBlockRequest = {
|
||||
name: 'Morning',
|
||||
minutes: 60,
|
||||
stopScheduling: 'AfterDurationEnd',
|
||||
items: [
|
||||
{
|
||||
collectionType: 'SearchQuery',
|
||||
collectionId: null,
|
||||
multiCollectionId: null,
|
||||
smartCollectionId: null,
|
||||
mediaItemId: null,
|
||||
searchTitle: 'News',
|
||||
searchQuery: 'news',
|
||||
playbackOrder: 'Shuffle',
|
||||
includeInProgramGuide: true,
|
||||
disableWatermarks: false,
|
||||
watermarkIds: [],
|
||||
graphicsElementIds: []
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
describe('blocks api client', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('getBlockGroups fetches all block groups', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([{ id: 1, name: 'Prime' }]));
|
||||
await expect(getBlockGroups()).resolves.toHaveLength(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/blocks/groups', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('createBlockGroup POSTs the name', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 3, name: 'Prime' }, 201));
|
||||
await createBlockGroup({ name: 'Prime' });
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/blocks/groups');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
expect(JSON.parse(String(init?.body)).name).toBe('Prime');
|
||||
});
|
||||
|
||||
it('deleteBlockGroup DELETEs by id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
|
||||
await expect(deleteBlockGroup(3)).resolves.toBeUndefined();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/blocks/groups/3', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
it('getBlocks fetches all blocks', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await getBlocks();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/blocks', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('getBlock fetches a block by id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4 }));
|
||||
await getBlock(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/blocks/4', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('createBlock POSTs group id and name', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 8 }, 201));
|
||||
await createBlock({ blockGroupId: 2, name: 'Morning' });
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/blocks');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
expect(JSON.parse(String(init?.body))).toMatchObject({ blockGroupId: 2, name: 'Morning' });
|
||||
});
|
||||
|
||||
it('deleteBlock DELETEs by id', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
|
||||
await deleteBlock(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/blocks/4', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
it('getBlockItems fetches items for a block', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await getBlockItems(4);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/blocks/4/items', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
it('replaceBlock PUTs the full block body', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4, items: [] }));
|
||||
await replaceBlock(4, sampleReplace);
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/blocks/4');
|
||||
expect(init).toMatchObject({ method: 'PUT' });
|
||||
const body = JSON.parse(String(init?.body));
|
||||
expect(body.minutes).toBe(60);
|
||||
expect(body.items).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('previewBlock POSTs to the preview route', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
|
||||
await previewBlock(4, sampleReplace);
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('/api/blocks/4/preview');
|
||||
expect(init).toMatchObject({ method: 'POST' });
|
||||
});
|
||||
|
||||
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');
|
||||
await searchTelevisionShows('show');
|
||||
await searchTelevisionSeasons('season');
|
||||
await searchSmartCollections('smart');
|
||||
expect(fetchMock.mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/search/collections?query=a%20b',
|
||||
'/api/search/television-shows?query=show',
|
||||
'/api/search/television-seasons?query=season',
|
||||
'/api/search/smart-collections?query=smart'
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { ApiError, request } from './client';
|
||||
import type { components } from './generated/v1';
|
||||
|
||||
export type BlockGroup = components['schemas']['BlockGroupResponseModel'];
|
||||
export type Block = components['schemas']['BlockResponseModel'];
|
||||
export type BlockItem = components['schemas']['BlockItemResponseModel'];
|
||||
export type BlockWithItems = components['schemas']['BlockWithItemsResponseModel'];
|
||||
export type BlockPreviewItem = components['schemas']['BlockPreviewItemResponseModel'];
|
||||
export type CreateBlockGroupRequest = components['schemas']['CreateBlockGroupRequest'];
|
||||
export type CreateBlockRequest = components['schemas']['CreateBlockRequest'];
|
||||
export type ReplaceBlockRequest = components['schemas']['ReplaceBlockRequest'];
|
||||
export type BlockItemRequest = components['schemas']['BlockItemRequest'];
|
||||
export type SchedulingPickerOption = components['schemas']['SchedulingPickerOptionResponseModel'];
|
||||
|
||||
// Block groups
|
||||
|
||||
export function getBlockGroups(): Promise<BlockGroup[]> {
|
||||
return request<BlockGroup[]>('/api/blocks/groups');
|
||||
}
|
||||
|
||||
export function createBlockGroup(body: CreateBlockGroupRequest): Promise<BlockGroup> {
|
||||
return request<BlockGroup>('/api/blocks/groups', { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteBlockGroup(id: number): Promise<void> {
|
||||
return request<void>(`/api/blocks/groups/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
// Blocks
|
||||
|
||||
export function getBlocks(): Promise<Block[]> {
|
||||
return request<Block[]>('/api/blocks');
|
||||
}
|
||||
|
||||
export function getBlock(id: number): Promise<Block> {
|
||||
return request<Block>(`/api/blocks/${id}`);
|
||||
}
|
||||
|
||||
export function createBlock(body: CreateBlockRequest): Promise<Block> {
|
||||
return request<Block>('/api/blocks', { body, method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteBlock(id: number): Promise<void> {
|
||||
return request<void>(`/api/blocks/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function getBlockItems(id: number): Promise<BlockItem[]> {
|
||||
return request<BlockItem[]>(`/api/blocks/${id}/items`);
|
||||
}
|
||||
|
||||
export function replaceBlock(id: number, body: ReplaceBlockRequest): Promise<BlockWithItems> {
|
||||
return request<BlockWithItems>(`/api/blocks/${id}`, { body, method: 'PUT' });
|
||||
}
|
||||
|
||||
export function previewBlock(id: number, body: ReplaceBlockRequest): Promise<BlockPreviewItem[]> {
|
||||
return request<BlockPreviewItem[]>(`/api/blocks/${id}/preview`, { body, method: 'POST' });
|
||||
}
|
||||
|
||||
// Scheduling search pickers
|
||||
|
||||
function searchOptions(path: string, query: string): Promise<SchedulingPickerOption[]> {
|
||||
return request<SchedulingPickerOption[]>(`${path}?query=${encodeURIComponent(query)}`);
|
||||
}
|
||||
|
||||
export function searchCollections(query: string): Promise<SchedulingPickerOption[]> {
|
||||
return searchOptions('/api/search/collections', query);
|
||||
}
|
||||
|
||||
export function searchTelevisionShows(query: string): Promise<SchedulingPickerOption[]> {
|
||||
return searchOptions('/api/search/television-shows', query);
|
||||
}
|
||||
|
||||
export function searchTelevisionSeasons(query: string): Promise<SchedulingPickerOption[]> {
|
||||
return searchOptions('/api/search/television-seasons', query);
|
||||
}
|
||||
|
||||
export function searchSmartCollections(query: string): Promise<SchedulingPickerOption[]> {
|
||||
return searchOptions('/api/search/smart-collections', query);
|
||||
}
|
||||
|
||||
export function messageFromBlockError(error: unknown, fallback = 'Unable to load blocks'): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.detail ?? error.message;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
Vendored
+79
@@ -28,6 +28,68 @@ export interface components {
|
||||
"ArtworkUploadResponseModel": {
|
||||
"path": string;
|
||||
"contentType": string;
|
||||
};
|
||||
"BlockGroupResponseModel": {
|
||||
"id": number;
|
||||
"name": string;
|
||||
};
|
||||
"BlockItemRequest": {
|
||||
"collectionType": components["schemas"]["CollectionType"];
|
||||
"collectionId": null | number;
|
||||
"multiCollectionId": null | number;
|
||||
"smartCollectionId": null | number;
|
||||
"mediaItemId": null | number;
|
||||
"searchTitle": null | string;
|
||||
"searchQuery": null | string;
|
||||
"playbackOrder": components["schemas"]["PlaybackOrder"];
|
||||
"includeInProgramGuide": boolean;
|
||||
"disableWatermarks": boolean;
|
||||
"watermarkIds": null | Array<number>;
|
||||
"graphicsElementIds": null | Array<number>;
|
||||
};
|
||||
"BlockItemResponseModel": {
|
||||
"id": number;
|
||||
"index": number;
|
||||
"collectionType": components["schemas"]["CollectionType"];
|
||||
"collectionId": null | number;
|
||||
"collectionName": null | string;
|
||||
"multiCollectionId": null | number;
|
||||
"multiCollectionName": null | string;
|
||||
"smartCollectionId": null | number;
|
||||
"smartCollectionName": null | string;
|
||||
"mediaItemId": null | number;
|
||||
"mediaItemName": null | string;
|
||||
"searchTitle": string;
|
||||
"searchQuery": string;
|
||||
"playbackOrder": components["schemas"]["PlaybackOrder"];
|
||||
"includeInProgramGuide": boolean;
|
||||
"disableWatermarks": boolean;
|
||||
"watermarkIds": Array<number>;
|
||||
"graphicsElementIds": Array<number>;
|
||||
};
|
||||
"BlockPreviewItemResponseModel": {
|
||||
"title": string;
|
||||
"start": string;
|
||||
"finish": string;
|
||||
"duration": string;
|
||||
};
|
||||
"BlockResponseModel": {
|
||||
"id": number;
|
||||
"groupId": number;
|
||||
"groupName": string;
|
||||
"name": string;
|
||||
"minutes": number;
|
||||
"stopScheduling": components["schemas"]["BlockStopScheduling"];
|
||||
};
|
||||
"BlockStopScheduling": "AfterDurationEnd" | "BeforeDurationEnd";
|
||||
"BlockWithItemsResponseModel": {
|
||||
"id": number;
|
||||
"groupId": number;
|
||||
"groupName": string;
|
||||
"name": string;
|
||||
"minutes": number;
|
||||
"stopScheduling": components["schemas"]["BlockStopScheduling"];
|
||||
"items": Array<components["schemas"]["BlockItemResponseModel"]>;
|
||||
};
|
||||
"BulkDeleteChannelsRequest": {
|
||||
"channelIds": Array<number>;
|
||||
@@ -161,6 +223,13 @@ export interface components {
|
||||
"CombinedVersion": {
|
||||
"apiVersion": number;
|
||||
"appVersion": null | string;
|
||||
};
|
||||
"CreateBlockGroupRequest": {
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateBlockRequest": {
|
||||
"blockGroupId": number;
|
||||
"name": null | string;
|
||||
};
|
||||
"CreateChannelFromLineupAdvancedOptionsRequest": {
|
||||
"playbackOrder"?: null | components["schemas"]["PlaybackOrder"];
|
||||
@@ -712,6 +781,12 @@ export interface components {
|
||||
"shuffleScheduleItems": boolean;
|
||||
"randomStartPoint": boolean;
|
||||
"fixedStartTimeBehavior": components["schemas"]["FixedStartTimeBehavior"];
|
||||
};
|
||||
"ReplaceBlockRequest": {
|
||||
"name": null | string;
|
||||
"minutes": number;
|
||||
"stopScheduling": components["schemas"]["BlockStopScheduling"];
|
||||
"items": null | Array<components["schemas"]["BlockItemRequest"]>;
|
||||
};
|
||||
"ReplaceScheduleItemsRequest": {
|
||||
"items": null | Array<components["schemas"]["ScheduleItemRequest"]>;
|
||||
@@ -787,6 +862,10 @@ export interface components {
|
||||
"preferredAudioTitle": null | string;
|
||||
"preferredSubtitleLanguageCode": null | string;
|
||||
"subtitleMode": null | components["schemas"]["ChannelSubtitleMode"];
|
||||
};
|
||||
"SchedulingPickerOptionResponseModel": {
|
||||
"id": number;
|
||||
"name": string;
|
||||
};
|
||||
"SearchResultGroupResponseModel": {
|
||||
"totalCount": number;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from './artwork';
|
||||
export * from './auth';
|
||||
export * from './blocks';
|
||||
export * from './channels';
|
||||
export * from './channelTemplates';
|
||||
export * from './client';
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { BlocksScreen } from './BlocksScreen';
|
||||
|
||||
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' }];
|
||||
const blocks = [{ id: 4, groupId: 2, groupName: 'Prime', name: 'Morning', minutes: 90, stopScheduling: 'AfterDurationEnd' }];
|
||||
|
||||
function blockItem(overrides: Record<string, unknown>) {
|
||||
return {
|
||||
id: 0,
|
||||
index: 0,
|
||||
collectionType: 'SearchQuery',
|
||||
collectionId: null,
|
||||
collectionName: null,
|
||||
multiCollectionId: null,
|
||||
multiCollectionName: null,
|
||||
smartCollectionId: null,
|
||||
smartCollectionName: null,
|
||||
mediaItemId: null,
|
||||
mediaItemName: null,
|
||||
searchTitle: '',
|
||||
searchQuery: '',
|
||||
playbackOrder: 'Shuffle',
|
||||
includeInProgramGuide: true,
|
||||
disableWatermarks: false,
|
||||
watermarkIds: [],
|
||||
graphicsElementIds: [],
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
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/blocks/groups' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(groups));
|
||||
}
|
||||
if (url === '/api/blocks' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(blocks));
|
||||
}
|
||||
if (url === '/api/blocks/4' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(blocks[0]));
|
||||
}
|
||||
if (url === '/api/blocks/4/items' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(items));
|
||||
}
|
||||
if (url === '/api/watermarks' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
if (url === '/api/graphics-elements' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
if (url === '/api/blocks/4' && method === 'PUT') {
|
||||
return Promise.resolve(jsonResponse({ ...blocks[0], items: [] }));
|
||||
}
|
||||
if (url === '/api/blocks/4/preview' && method === 'POST') {
|
||||
return Promise.resolve(
|
||||
jsonResponse([{ title: 'Episode 1', start: '00:00:00', finish: '00:30:00', duration: '00:30:00' }])
|
||||
);
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
}
|
||||
|
||||
describe('BlocksScreen', () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
window.history.pushState({}, '', '/app/blocks');
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
window.history.pushState({}, '', '/app/blocks');
|
||||
});
|
||||
|
||||
it('renders block groups and their blocks', async () => {
|
||||
mockApi();
|
||||
render(<BlocksScreen />);
|
||||
|
||||
expect(await screen.findByText('Prime')).toBeInTheDocument();
|
||||
expect(screen.getByText('Morning')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('loads the editor at a sub-path and hydrates duration from minutes', async () => {
|
||||
window.history.pushState({}, '', '/app/blocks/4');
|
||||
mockApi({ items: [blockItem({ id: 1, searchTitle: 'News', searchQuery: 'news' })] });
|
||||
render(<BlocksScreen />);
|
||||
|
||||
// 90 minutes -> 1 hour + 30 minutes
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Morning')).toBeInTheDocument());
|
||||
expect(screen.getByDisplayValue('1')).toBeInTheDocument();
|
||||
expect(screen.getByText('News')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves the block with items in array order via PUT', async () => {
|
||||
window.history.pushState({}, '', '/app/blocks/4');
|
||||
const fetchMock = mockApi({
|
||||
items: [
|
||||
blockItem({ id: 1, searchTitle: 'A', searchQuery: 'a' }),
|
||||
blockItem({ id: 2, searchTitle: 'B', searchQuery: 'b' })
|
||||
]
|
||||
});
|
||||
render(<BlocksScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Morning')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save block/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/blocks/4' && init?.method === 'PUT');
|
||||
expect(call).toBeTruthy();
|
||||
});
|
||||
|
||||
const putCall = fetchMock.mock.calls.find(([u, init]) => u === '/api/blocks/4' && init?.method === 'PUT');
|
||||
const sent = JSON.parse(String(putCall?.[1]?.body));
|
||||
expect(sent.minutes).toBe(90);
|
||||
expect(sent.name).toBe('Morning');
|
||||
expect(sent.items.map((i: { searchTitle: string }) => i.searchTitle)).toEqual(['A', 'B']);
|
||||
});
|
||||
|
||||
it('round-trips legacy Artist and MultiCollection items through load and save', async () => {
|
||||
window.history.pushState({}, '', '/app/blocks/4');
|
||||
const fetchMock = mockApi({
|
||||
items: [
|
||||
blockItem({
|
||||
id: 1,
|
||||
collectionType: 'Artist',
|
||||
mediaItemId: 42,
|
||||
mediaItemName: 'The Beatles'
|
||||
}),
|
||||
blockItem({
|
||||
id: 2,
|
||||
collectionType: 'MultiCollection',
|
||||
multiCollectionId: 99,
|
||||
multiCollectionName: 'My Multi Collection'
|
||||
})
|
||||
]
|
||||
});
|
||||
render(<BlocksScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Morning')).toBeInTheDocument());
|
||||
|
||||
// Both legacy items should display their carried-over selection name in the table.
|
||||
expect(await screen.findByText('The Beatles')).toBeInTheDocument();
|
||||
expect(screen.getByText('My Multi Collection')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save block/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/blocks/4' && init?.method === 'PUT');
|
||||
expect(call).toBeTruthy();
|
||||
});
|
||||
|
||||
const putCall = fetchMock.mock.calls.find(([u, init]) => u === '/api/blocks/4' && init?.method === 'PUT');
|
||||
const sent = JSON.parse(String(putCall?.[1]?.body));
|
||||
|
||||
const artistItem = sent.items.find((i: { collectionType: string }) => i.collectionType === 'Artist');
|
||||
expect(artistItem.mediaItemId).toBe(42);
|
||||
|
||||
const multiCollectionItem = sent.items.find(
|
||||
(i: { collectionType: string }) => i.collectionType === 'MultiCollection'
|
||||
);
|
||||
expect(multiCollectionItem.multiCollectionId).toBe(99);
|
||||
});
|
||||
|
||||
it('renders the preview table from POST preview', async () => {
|
||||
window.history.pushState({}, '', '/app/blocks/4');
|
||||
mockApi({ items: [blockItem({ id: 1, searchTitle: 'News', searchQuery: 'news' })] });
|
||||
render(<BlocksScreen />);
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Morning')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole('button', { name: /Preview/ }));
|
||||
|
||||
expect(await screen.findByText('Episode 1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user