fix(user-management): render loaded content restrictions (#1623)

This commit is contained in:
Ali Abuelkheir
2026-06-03 13:25:43 +01:00
committed by GitHub
parent 5b79e12e7b
commit 24079f0092
3 changed files with 265 additions and 25 deletions
@@ -64,7 +64,7 @@
</div>
}
@if (restrictions.length === 0) {
@if (restrictions().length === 0) {
<div class="empty-state">
<i class="pi pi-check-circle"></i>
<p>{{ t('emptyTitle') }}</p>
@@ -1,14 +1,236 @@
import {describe, it} from 'vitest';
import {provideZonelessChangeDetection, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MessageService} from 'primeng/api';
import {Subject} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
// NOTE(frontend-seam): Real coverage here needs seams around metadata-derived option lists,
// restriction-service mutations, and translated message flows so restriction editing can be
// asserted without mounting the full editable select stack.
describe.skip('ContentRestrictionsEditorComponent', () => {
it('needs metadata seams to verify option derivation, type-label helpers, and allow versus exclude grouping', () => {
// TODO(seam): Cover getValueOptions and the grouping helpers once the computed metadata signal is isolated for direct assertions.
import {BookService} from '../../../book/service/book.service';
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {ContentRestriction, ContentRestrictionMode, ContentRestrictionType} from '../content-restriction.model';
import {ContentRestrictionService} from '../content-restriction.service';
import {ContentRestrictionsEditorComponent} from './content-restrictions-editor.component';
describe('ContentRestrictionsEditorComponent', () => {
let fixture: ComponentFixture<ContentRestrictionsEditorComponent>;
let restrictionResponses: Map<number, Subject<ContentRestriction[]>>;
let addResponses: Map<number, Subject<ContentRestriction>>;
let deleteResponses: Map<number, Subject<void>>;
const getUserRestrictions = vi.fn();
const addRestriction = vi.fn();
const deleteRestriction = vi.fn();
const messageAdd = vi.fn();
beforeEach(async () => {
restrictionResponses = new Map<number, Subject<ContentRestriction[]>>();
addResponses = new Map<number, Subject<ContentRestriction>>();
deleteResponses = new Map<number, Subject<void>>();
getUserRestrictions
.mockReset()
.mockImplementation((userId: number) => restrictionResponseFor(userId).asObservable());
addRestriction
.mockReset()
.mockImplementation((userId: number) => addResponseFor(userId).asObservable());
deleteRestriction
.mockReset()
.mockImplementation((userId: number) => deleteResponseFor(userId).asObservable());
messageAdd.mockReset();
await TestBed.configureTestingModule({
imports: [ContentRestrictionsEditorComponent, getTranslocoModule()],
providers: [
provideZonelessChangeDetection(),
{
provide: ContentRestrictionService,
useValue: {
getUserRestrictions,
addRestriction,
deleteRestriction,
},
},
{
provide: BookService,
useValue: {
uniqueMetadata: signal({
categories: [],
tags: ['Loaded tag'],
moods: [],
authors: [],
publishers: [],
series: [],
}),
},
},
{
provide: MessageService,
useValue: {add: messageAdd},
},
],
})
.compileComponents();
fixture = TestBed.createComponent(ContentRestrictionsEditorComponent);
fixture.componentRef.setInput('userId', 42);
fixture.detectChanges();
});
it('needs mutation seams to verify loading, duplicate prevention, and add and remove restriction flows', () => {
// TODO(seam): Cover loadRestrictions, addRestriction, and removeRestriction after extracting service and toast side effects behind test doubles.
afterEach(() => {
fixture.destroy();
for (const response of restrictionResponses.values()) {
response.complete();
}
for (const response of addResponses.values()) {
response.complete();
}
for (const response of deleteResponses.values()) {
response.complete();
}
TestBed.resetTestingModule();
});
it('renders restrictions loaded from the service', async () => {
expect(fixture.nativeElement.querySelector('.empty-state')).not.toBeNull();
restrictionResponseFor(42).next([createRestriction('Loaded tag')]);
await fixture.whenStable();
fixture.detectChanges();
expect(getUserRestrictions).toHaveBeenCalledWith(42);
expect(fixture.nativeElement.querySelector('.chip-value').textContent.trim()).toBe('Loaded tag');
});
it('ignores stale restriction responses after the user changes', async () => {
fixture.componentRef.setInput('userId', 43);
fixture.detectChanges();
restrictionResponseFor(42).next([createRestriction('Old tag')]);
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.chip-value')).toBeNull();
restrictionResponseFor(43).next([createRestriction('Current tag', 43)]);
await fixture.whenStable();
fixture.detectChanges();
expect(getUserRestrictions).toHaveBeenCalledWith(42);
expect(getUserRestrictions).toHaveBeenCalledWith(43);
expect(fixture.nativeElement.querySelector('.chip-value').textContent.trim()).toBe('Current tag');
});
it('clears displayed restrictions when the active load fails', async () => {
const emitted: ContentRestriction[][] = [];
fixture.componentInstance.restrictionsChanged.subscribe(restrictions => emitted.push(restrictions));
restrictionResponseFor(42).next([createRestriction('Old tag')]);
await fixture.whenStable();
fixture.detectChanges();
emitted.length = 0;
messageAdd.mockClear();
fixture.componentRef.setInput('userId', 43);
fixture.detectChanges();
restrictionResponseFor(43).error(new Error('load failed'));
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.chip-value')).toBeNull();
expect(emitted).toEqual([[]]);
expect(messageAdd).toHaveBeenCalledWith(expect.objectContaining({
severity: 'error',
}));
});
it('ignores stale add responses after the user changes', async () => {
const emitted: ContentRestriction[][] = [];
fixture.componentInstance.restrictionsChanged.subscribe(restrictions => emitted.push(restrictions));
fixture.componentInstance.newRestriction = {
restrictionType: ContentRestrictionType.TAG,
mode: ContentRestrictionMode.EXCLUDE,
value: 'Loaded tag',
};
fixture.componentInstance.addRestriction();
fixture.componentRef.setInput('userId', 43);
fixture.detectChanges();
addResponseFor(42).next(createRestriction('Loaded tag'));
await fixture.whenStable();
fixture.detectChanges();
expect(addRestriction).toHaveBeenCalledWith(42, expect.objectContaining({
userId: 42,
value: 'Loaded tag',
}));
expect(fixture.nativeElement.querySelector('.chip-value')).toBeNull();
expect(emitted).toEqual([]);
expect(messageAdd).not.toHaveBeenCalled();
});
it('ignores stale delete responses after the user changes', async () => {
const emitted: ContentRestriction[][] = [];
fixture.componentInstance.restrictionsChanged.subscribe(restrictions => emitted.push(restrictions));
restrictionResponseFor(42).next([createRestriction('Old tag')]);
await fixture.whenStable();
fixture.detectChanges();
emitted.length = 0;
messageAdd.mockClear();
fixture.componentInstance.removeRestriction(createRestriction('Old tag'));
fixture.componentRef.setInput('userId', 43);
fixture.detectChanges();
deleteResponseFor(42).next();
await fixture.whenStable();
fixture.detectChanges();
expect(deleteRestriction).toHaveBeenCalledWith(42, 1);
expect(fixture.nativeElement.querySelector('.chip-value').textContent.trim()).toBe('Old tag');
expect(emitted).toEqual([]);
expect(messageAdd).not.toHaveBeenCalled();
restrictionResponseFor(43).next([createRestriction('Current tag', 43)]);
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.chip-value').textContent.trim()).toBe('Current tag');
});
function restrictionResponseFor(userId: number): Subject<ContentRestriction[]> {
let response = restrictionResponses.get(userId);
if (!response) {
response = new Subject<ContentRestriction[]>();
restrictionResponses.set(userId, response);
}
return response;
}
function addResponseFor(userId: number): Subject<ContentRestriction> {
let response = addResponses.get(userId);
if (!response) {
response = new Subject<ContentRestriction>();
addResponses.set(userId, response);
}
return response;
}
function deleteResponseFor(userId: number): Subject<void> {
let response = deleteResponses.get(userId);
if (!response) {
response = new Subject<void>();
deleteResponses.set(userId, response);
}
return response;
}
});
function createRestriction(value: string, userId = 42): ContentRestriction {
return {
id: 1,
userId,
restrictionType: ContentRestrictionType.TAG,
mode: ContentRestrictionMode.EXCLUDE,
value,
};
}
@@ -1,4 +1,4 @@
import {Component, computed, DestroyRef, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {ChangeDetectionStrategy, Component, computed, DestroyRef, EventEmitter, inject, Input, OnChanges, OnInit, Output, signal, SimpleChanges} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
@@ -28,7 +28,8 @@ import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/tran
TranslocoPipe
],
templateUrl: './content-restrictions-editor.component.html',
styleUrls: ['./content-restrictions-editor.component.scss']
styleUrls: ['./content-restrictions-editor.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
@Input() userId!: number;
@@ -49,7 +50,10 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
};
});
restrictions: ContentRestriction[] = [];
readonly restrictions = signal<ContentRestriction[]>([]);
private readonly excludeRestrictions = computed(() => this.restrictions().filter(r => r.mode === ContentRestrictionMode.EXCLUDE));
private readonly allowOnlyRestrictions = computed(() => this.restrictions().filter(r => r.mode === ContentRestrictionMode.ALLOW_ONLY));
get availableCategories(): string[] { return this.sortedMetadata().categories; }
get availableTags(): string[] { return this.sortedMetadata().tags; }
get availableMoods(): string[] { return this.sortedMetadata().moods; }
@@ -88,15 +92,21 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
loadRestrictions() {
if (!this.userId) return;
const requestedUserId = this.userId;
this.contentRestrictionService.getUserRestrictions(this.userId).pipe(
this.contentRestrictionService.getUserRestrictions(requestedUserId).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (restrictions) => {
this.restrictions = restrictions;
this.restrictionsChanged.emit(this.restrictions);
if (this.userId !== requestedUserId) return;
this.restrictions.set(restrictions);
this.restrictionsChanged.emit(restrictions);
},
error: () => {
if (this.userId !== requestedUserId) return;
const restrictions: ContentRestriction[] = [];
this.restrictions.set(restrictions);
this.restrictionsChanged.emit(restrictions);
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -133,7 +143,7 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
return;
}
const exists = this.restrictions.some(r =>
const exists = this.restrictions().some(r =>
r.restrictionType === this.newRestriction.restrictionType &&
r.value === this.newRestriction.value
);
@@ -153,13 +163,16 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
mode: this.newRestriction.mode!,
value: this.newRestriction.value!
};
const requestedUserId = this.userId;
this.contentRestrictionService.addRestriction(this.userId, restriction).pipe(
this.contentRestrictionService.addRestriction(requestedUserId, restriction).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (added) => {
this.restrictions.push(added);
this.restrictionsChanged.emit(this.restrictions);
if (this.userId !== requestedUserId) return;
const restrictions = [...this.restrictions(), added];
this.restrictions.set(restrictions);
this.restrictionsChanged.emit(restrictions);
this.newRestriction.value = '';
this.messageService.add({
severity: 'success',
@@ -168,6 +181,7 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
});
},
error: () => {
if (this.userId !== requestedUserId) return;
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -179,13 +193,16 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
removeRestriction(restriction: ContentRestriction) {
if (!restriction.id) return;
const requestedUserId = this.userId;
this.contentRestrictionService.deleteRestriction(this.userId, restriction.id).pipe(
this.contentRestrictionService.deleteRestriction(requestedUserId, restriction.id).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: () => {
this.restrictions = this.restrictions.filter(r => r.id !== restriction.id);
this.restrictionsChanged.emit(this.restrictions);
if (this.userId !== requestedUserId) return;
const restrictions = this.restrictions().filter(r => r.id !== restriction.id);
this.restrictions.set(restrictions);
this.restrictionsChanged.emit(restrictions);
this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
@@ -193,6 +210,7 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
});
},
error: () => {
if (this.userId !== requestedUserId) return;
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -218,10 +236,10 @@ export class ContentRestrictionsEditorComponent implements OnInit, OnChanges {
}
getExcludeRestrictions(): ContentRestriction[] {
return this.restrictions.filter(r => r.mode === ContentRestrictionMode.EXCLUDE);
return this.excludeRestrictions();
}
getAllowOnlyRestrictions(): ContentRestriction[] {
return this.restrictions.filter(r => r.mode === ContentRestrictionMode.ALLOW_ONLY);
return this.allowOnlyRestrictions();
}
}