Files
ersatztv/ErsatzTV.Application/ProgramSchedules/Commands/ReplaceProgramScheduleItemsHandler.cs
T
timothyandClaude Fable 5 794bb0d4bb fix(schedules): reload write-path response with read includes + order GET by index (#229)
Bug 1 (500 on watermark/graphics save): Replace/Add handlers projected the
freshly-built entity graph, whose ProgramScheduleItemWatermark / -GraphicsElement
join rows carry only foreign-key ids — the Watermark/GraphicsElement navs are null,
and Mapper.ProjectToViewModel dereferences them unguarded, throwing an NRE that the
controller surfaced as a 500 on PUT/POST. Both handlers now reload the persisted
item(s) through the read-side include chain before projecting. Extracted that chain
into ProgramScheduleItemQueryExtensions.IncludeScheduleItemDetails() so GET, Replace
and Add share one source of truth.

Masking: PersistItems returned a lazy LanguageExt Map, and the existing round-trip
test only checked .IsRight — never enumerating it, so the deferred NRE never fired.
The new ScheduleItemWriteProjectionTests force enumeration (as the controller's
.ToList()/serialization does) and seed watermark/graphics via a separate context so
the handler's fresh factory context has nothing pre-tracked.

Bug 2 (server side): GetProgramScheduleItemsHandler now .OrderBy(i => i.Index) —
it previously returned id order, which is not index order.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 01:26:25 +02:00

168 lines
7.0 KiB
C#

using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.ProgramSchedules.Mapper;
namespace ErsatzTV.Application.ProgramSchedules;
public class ReplaceProgramScheduleItemsHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> channel) : ProgramScheduleItemCommandBase,
IRequestHandler<ReplaceProgramScheduleItems, Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>>
{
public async Task<Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>> Handle(
ReplaceProgramScheduleItems request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<ProgramSchedule> maybeProgramSchedule =
await ProgramScheduleMustExist(dbContext, request.ProgramScheduleId, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule);
return await validation.Apply(ps => PersistItems(dbContext, request, ps, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>>(
new NotFoundError("[ProgramScheduleId] does not exist.")));
}
private async Task<IEnumerable<ProgramScheduleItemViewModel>> PersistItems(
TvContext dbContext,
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule,
CancellationToken cancellationToken)
{
dbContext.RemoveRange(programSchedule.Items);
// reset index starting with zero
programSchedule.Items = [];
var orderedItems = request.Items.OrderBy(i => i.Index).ToList();
for (var i = 0; i < orderedItems.Count; i++)
{
programSchedule.Items.Add(BuildItem(programSchedule, i, orderedItems[i]));
}
await dbContext.SaveChangesAsync(cancellationToken);
// refresh any playouts that use this schedule
foreach (Playout playout in programSchedule.Playouts)
{
await channel.WriteAsync(new BuildPlayout(playout.Id, PlayoutBuildMode.Refresh), cancellationToken);
}
// reload with the full navigation graph before projecting: BuildItem creates the watermark/graphics
// join rows with only their foreign-key ids set, so the tracked entities have null Watermark /
// GraphicsElement navs that ProjectToViewModel dereferences (would 500 on PUT — see #229).
List<ProgramScheduleItem> persisted = await dbContext.ProgramScheduleItems
.Filter(psi => psi.ProgramScheduleId == programSchedule.Id)
.IncludeScheduleItemDetails()
.OrderBy(i => i.Index)
.ToListAsync(cancellationToken);
return persisted.Map(ProjectToViewModel).ToList();
}
private static async Task<Validation<BaseError, ProgramSchedule>> Validate(
TvContext dbContext,
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule)
{
Validation<BaseError, ProgramSchedule> validation = PlayoutModesMustBeValid(request, programSchedule)
.Bind(programSchedule => CollectionTypesMustBeValid(request, programSchedule))
.Bind(programSchedule => PlaybackOrdersMustBeValid(request, programSchedule));
return await validation.ToEither().Match(
Left: error => Task.FromResult<Validation<BaseError, ProgramSchedule>>(
Fail<BaseError, ProgramSchedule>(error)),
Right: validProgramSchedule => FillerConfigurationsMustBeValid(dbContext, request, validProgramSchedule));
}
private static Validation<BaseError, ProgramSchedule> PlayoutModesMustBeValid(
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule) =>
request.Items.Map(item => PlayoutModeMustBeValid(item, programSchedule)).Sequence()
.Map(_ => programSchedule);
private static Validation<BaseError, ProgramSchedule> CollectionTypesMustBeValid(
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule) =>
request.Items.Map(item => CollectionTypeMustBeValid(item, programSchedule)).Sequence()
.Map(_ => programSchedule);
private static async Task<Validation<BaseError, ProgramSchedule>> FillerConfigurationsMustBeValid(
TvContext dbContext,
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule)
{
foreach (ReplaceProgramScheduleItem item in request.Items)
{
Either<BaseError, ProgramSchedule> result = await FillerConfigurationMustBeValid(
dbContext,
item,
programSchedule);
if (result.IsLeft)
{
return result.ToValidation();
}
}
return programSchedule;
}
private static Validation<BaseError, ProgramSchedule> PlaybackOrdersMustBeValid(
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule)
{
var keyOrders = new Dictionary<CollectionKey, System.Collections.Generic.HashSet<PlaybackOrder>>();
foreach (ReplaceProgramScheduleItem item in request.Items)
{
if (item.PlaybackOrder is PlaybackOrder.ShuffleInOrder &&
item.FillWithGroupMode is not FillWithGroupMode.None)
{
return new BaseError("Shuffle in Order cannot be used with Fill With Group Mode");
}
var key = new CollectionKey(
item.CollectionType,
item.CollectionId,
item.MediaItemId,
item.MultiCollectionId,
item.SmartCollectionId,
item.RerunCollectionId,
item.PlaylistId,
item.SearchQuery);
if (keyOrders.TryGetValue(key, out System.Collections.Generic.HashSet<PlaybackOrder> playbackOrders))
{
playbackOrders.Add(item.PlaybackOrder);
keyOrders[key] = playbackOrders;
}
else
{
keyOrders.Add(key, new System.Collections.Generic.HashSet<PlaybackOrder> { item.PlaybackOrder });
}
}
return Optional(keyOrders.Values.Count(set => set.Count != 1))
.Filter(count => count == 0)
.Map(_ => programSchedule)
.ToValidation<BaseError>("A collection must not use multiple playback orders");
}
private sealed record CollectionKey(
CollectionType CollectionType,
int? CollectionId,
int? MediaItemId,
int? MultiCollectionId,
int? SmartCollectionId,
int? RerunCollectionId,
int? PlaylistId,
string SearchQuery);
}