From 24079f009247d354bd1e3b395a20916efe7009fa Mon Sep 17 00:00:00 2001 From: Ali Abuelkheir <114030430+AliAbuelkheir@users.noreply.github.com> Date: Wed, 3 Jun 2026 15:25:43 +0300 Subject: [PATCH] fix(user-management): render loaded content restrictions (#1623) --- ...content-restrictions-editor.component.html | 2 +- ...tent-restrictions-editor.component.spec.ts | 240 +++++++++++++++++- .../content-restrictions-editor.component.ts | 48 ++-- 3 files changed, 265 insertions(+), 25 deletions(-) diff --git a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.html b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.html index e0553ff52..10ef0d052 100644 --- a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.html +++ b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.html @@ -64,7 +64,7 @@ } - @if (restrictions.length === 0) { + @if (restrictions().length === 0) {

{{ t('emptyTitle') }}

diff --git a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts index 72365d815..c52cea544 100644 --- a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts +++ b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.spec.ts @@ -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; + let restrictionResponses: Map>; + let addResponses: Map>; + let deleteResponses: Map>; + const getUserRestrictions = vi.fn(); + const addRestriction = vi.fn(); + const deleteRestriction = vi.fn(); + const messageAdd = vi.fn(); + + beforeEach(async () => { + restrictionResponses = new Map>(); + addResponses = new Map>(); + deleteResponses = new Map>(); + 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 { + let response = restrictionResponses.get(userId); + if (!response) { + response = new Subject(); + restrictionResponses.set(userId, response); + } + return response; + } + + function addResponseFor(userId: number): Subject { + let response = addResponses.get(userId); + if (!response) { + response = new Subject(); + addResponses.set(userId, response); + } + return response; + } + + function deleteResponseFor(userId: number): Subject { + let response = deleteResponses.get(userId); + if (!response) { + response = new Subject(); + deleteResponses.set(userId, response); + } + return response; + } }); + +function createRestriction(value: string, userId = 42): ContentRestriction { + return { + id: 1, + userId, + restrictionType: ContentRestrictionType.TAG, + mode: ContentRestrictionMode.EXCLUDE, + value, + }; +} diff --git a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.ts b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.ts index 9f6260852..73800bcea 100644 --- a/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.ts +++ b/frontend/src/app/features/settings/user-management/content-restrictions-editor/content-restrictions-editor.component.ts @@ -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([]); + 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(); } }