Add ability to mark magic shelves as public (#1489)

Adds a checkbox to the create/edit magic shelf dialog to set the shelf
as public.
If public then it shows up for all users.
Only admins can edit public shelves (edit options disabled for
non-admin)
This commit is contained in:
Chris Debenham
2025-11-20 21:17:10 -07:00
committed by GitHub
parent 229c360116
commit 79ab4ec5a1
9 changed files with 100 additions and 33 deletions
@@ -21,4 +21,6 @@ public class MagicShelf {
@NotNull(message = "Filter JSON must not be null") @NotNull(message = "Filter JSON must not be null")
@Size(min = 2, message = "Filter JSON must not be empty") @Size(min = 2, message = "Filter JSON must not be empty")
private String filterJson; private String filterJson;
private Boolean isPublic = false;
} }
@@ -32,6 +32,10 @@ public class MagicShelfEntity {
@Column(name = "filter_json", columnDefinition = "json", nullable = false) @Column(name = "filter_json", columnDefinition = "json", nullable = false)
private String filterJson; private String filterJson;
@Column(name = "is_public", nullable = false)
@lombok.Builder.Default
private boolean isPublic = false;
@Column(name = "created_at", nullable = false, updatable = false) @Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt = LocalDateTime.now(); private LocalDateTime createdAt = LocalDateTime.now();
@@ -10,6 +10,8 @@ public interface MagicShelfRepository extends JpaRepository<MagicShelfEntity, Lo
List<MagicShelfEntity> findAllByUserId(Long userId); List<MagicShelfEntity> findAllByUserId(Long userId);
List<MagicShelfEntity> findAllByIsPublicIsTrue();
Optional<MagicShelfEntity> findByUserIdAndName(Long userId, String name); Optional<MagicShelfEntity> findByUserIdAndName(Long userId, String name);
boolean existsByUserIdAndName(Long userId, String name); boolean existsByUserIdAndName(Long userId, String name);
@@ -9,6 +9,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@AllArgsConstructor @AllArgsConstructor
@Service @Service
@@ -19,9 +20,20 @@ public class MagicShelfService {
public List<MagicShelf> getUserShelves() { public List<MagicShelf> getUserShelves() {
Long userId = authenticationService.getAuthenticatedUser().getId(); Long userId = authenticationService.getAuthenticatedUser().getId();
return repository.findAllByUserId(userId).stream()
List<MagicShelf> shelves = repository.findAllByUserId(userId).stream()
.map(this::toDto) .map(this::toDto)
.collect(Collectors.toList());
List<Long> userShelfIds = shelves.stream().map(MagicShelf::getId).toList();
List<MagicShelf> publicShelves = repository.findAllByIsPublicIsTrue().stream()
.map(this::toDto)
.filter(shelf -> !userShelfIds.contains(shelf.getId()))
.toList(); .toList();
shelves.addAll(publicShelves);
return shelves;
} }
@Transactional @Transactional
@@ -32,9 +44,13 @@ public class MagicShelfService {
if (!existing.getUserId().equals(userId)) { if (!existing.getUserId().equals(userId)) {
throw new SecurityException("You are not authorized to update this shelf"); throw new SecurityException("You are not authorized to update this shelf");
} }
if (existing.isPublic() && !authenticationService.getAuthenticatedUser().getPermissions().isAdmin()) {
throw new SecurityException("You are not authorized to update a public shelf");
}
existing.setName(dto.getName()); existing.setName(dto.getName());
existing.setIcon(dto.getIcon()); existing.setIcon(dto.getIcon());
existing.setFilterJson(dto.getFilterJson()); existing.setFilterJson(dto.getFilterJson());
existing.setPublic(dto.getIsPublic());
return toDto(repository.save(existing)); return toDto(repository.save(existing));
} }
if (repository.existsByUserIdAndName(userId, dto.getName())) { if (repository.existsByUserIdAndName(userId, dto.getName())) {
@@ -59,6 +75,7 @@ public class MagicShelfService {
dto.setName(entity.getName()); dto.setName(entity.getName());
dto.setIcon(entity.getIcon()); dto.setIcon(entity.getIcon());
dto.setFilterJson(entity.getFilterJson()); dto.setFilterJson(entity.getFilterJson());
dto.setIsPublic(entity.isPublic());
return dto; return dto;
} }
@@ -68,6 +85,7 @@ public class MagicShelfService {
entity.setName(dto.getName()); entity.setName(dto.getName());
entity.setIcon(dto.getIcon()); entity.setIcon(dto.getIcon());
entity.setFilterJson(dto.getFilterJson()); entity.setFilterJson(dto.getFilterJson());
entity.setPublic(dto.getIsPublic());
entity.setUserId(userId); entity.setUserId(userId);
return entity; return entity;
} }
@@ -76,4 +94,4 @@ public class MagicShelfService {
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found")); MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
return toDto(shelf); return toDto(shelf);
} }
} }
@@ -0,0 +1 @@
ALTER TABLE magic_shelf ADD COLUMN is_public BOOLEAN NOT NULL DEFAULT FALSE;
@@ -15,6 +15,7 @@ import {MagicShelfComponent} from '../../magic-shelf/component/magic-shelf-compo
import {TaskCreateRequest, TaskType} from '../../settings/task-management/task.service'; import {TaskCreateRequest, TaskType} from '../../settings/task-management/task.service';
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model'; import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
import {TaskHelperService} from '../../settings/task-management/task-helper.service'; import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {UserService} from "../../settings/user-management/user.service";
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -29,6 +30,7 @@ export class LibraryShelfMenuService {
private router = inject(Router); private router = inject(Router);
private dialogService = inject(DialogService); private dialogService = inject(DialogService);
private magicShelfService = inject(MagicShelfService); private magicShelfService = inject(MagicShelfService);
private userService = inject(UserService);
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] { initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
return [ return [
@@ -203,13 +205,18 @@ export class LibraryShelfMenuService {
} }
initializeMagicShelfMenuItems(entity: any): MenuItem[] { initializeMagicShelfMenuItems(entity: any): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = isPublicShelf && !isAdmin;
return [ return [
{ {
label: 'Options', label: (isPublicShelf ? 'Public Shelf - ' : '') + (disableOptions ? 'Read only' : 'Options'),
items: [ items: [
{ {
label: 'Edit Magic Shelf', label: 'Edit Magic Shelf',
icon: 'pi pi-pen-to-square', icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => { command: () => {
this.dialogService.open(MagicShelfComponent, { this.dialogService.open(MagicShelfComponent, {
header: 'Edit Magic Shelf', header: 'Edit Magic Shelf',
@@ -224,6 +231,7 @@ export class LibraryShelfMenuService {
{ {
label: 'Delete Magic Shelf', label: 'Delete Magic Shelf',
icon: 'pi pi-trash', icon: 'pi pi-trash',
disabled: disableOptions,
command: () => { command: () => {
this.confirmationService.confirm({ this.confirmationService.confirm({
message: `Are you sure you want to delete magic shelf: ${entity?.name}?`, message: `Are you sure you want to delete magic shelf: ${entity?.name}?`,
@@ -2,36 +2,46 @@
<div class="px-8 pt-8 flex-grow overflow-auto" [formGroup]="form"> <div class="px-8 pt-8 flex-grow overflow-auto" [formGroup]="form">
<div class="mb-4 flex w-full gap-4"> <fieldset [disabled]="form.get('isPublic')?.value && !isAdmin">
<div class="flex-1"> <div class="mb-4 flex w-full gap-4">
<label for="shelfName" class="block mb-1 font-semibold">Shelf Name</label> <div class="flex-1">
<input pInputText id="shelfName" type="text" formControlName="name" placeholder="E.g. Rom-Zom-Coms, Fast & Furious, Missing Metadata" class="w-full"/> <label for="shelfName" class="block mb-1 font-semibold">Shelf Name</label>
</div> <input pInputText id="shelfName" type="text" formControlName="name" placeholder="E.g. Rom-Zom-Coms, Fast & Furious, Missing Metadata" class="w-full"/>
<div class="flex items-end">
<div>
<label class="block mb-1 font-semibold">Shelf Icon</label>
<p-button
[icon]="form.get('icon')?.value || 'pi pi-plus'"
(click)="openIconPicker()"
[outlined]="form.get('icon')?.value"
[severity]="form.get('icon')?.value ? 'success' : 'danger'"
[label]="form.get('icon')?.value ? 'Icon Selected' : 'Select Icon'">
</p-button>
</div> </div>
<div class="flex items-end">
<div>
<label class="block mb-1 font-semibold">Shelf Icon</label>
<p-button
[icon]="form.get('icon')?.value || 'pi pi-plus'"
(click)="openIconPicker()"
[outlined]="form.get('icon')?.value"
[severity]="form.get('icon')?.value ? 'success' : 'danger'"
[label]="form.get('icon')?.value ? 'Icon Selected' : 'Select Icon'">
</p-button>
</div>
</div>
@if (isAdmin) {
<div class="flex items-end">
<div class="flex items-center">
<p-checkbox formControlName="isPublic" [binary]="true" inputId="isPublic" (onChange)="onIsPublicChange($event)"></p-checkbox>
<label for="isPublic" class="ml-2">Public</label>
</div>
</div>
}
</div> </div>
</div>
<div class="overflow-auto max-h-[40rem]"> <div class="overflow-auto max-h-[40rem]">
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: form.get('group') }"></ng-container> <ng-container *ngTemplateOutlet="groupTemplate; context: { group: form.get('group') }"></ng-container>
</div> </div>
<div class="my-4 text-left"> <div class="my-4 text-left">
<p-button <p-button
label="Save Filter" label="Save Filter"
outlined outlined
severity="success" severity="success"
(click)="submit()" (click)="submit()"
[disabled]="form.invalid"></p-button> [disabled]="form.invalid"></p-button>
</div> </div>
</fieldset>
</div> </div>
<ng-template #groupTemplate let-group="group"> <ng-template #groupTemplate let-group="group">
@@ -16,6 +16,8 @@ import {MultiSelect} from 'primeng/multiselect';
import {AutoComplete} from 'primeng/autocomplete'; import {AutoComplete} from 'primeng/autocomplete';
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils'; import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils';
import {IconPickerService} from '../../../shared/service/icon-picker.service'; import {IconPickerService} from '../../../shared/service/icon-picker.service';
import {CheckboxModule} from "primeng/checkbox";
import {UserService} from "../../settings/user-management/user.service";
export type RuleOperator = export type RuleOperator =
| 'equals' | 'equals'
@@ -150,7 +152,8 @@ const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
DatePicker, DatePicker,
InputNumber, InputNumber,
MultiSelect, MultiSelect,
AutoComplete AutoComplete,
CheckboxModule
] ]
}) })
export class MagicShelfComponent implements OnInit { export class MagicShelfComponent implements OnInit {
@@ -190,15 +193,18 @@ export class MagicShelfComponent implements OnInit {
form = new FormGroup({ form = new FormGroup({
name: new FormControl<string | null>(null), name: new FormControl<string | null>(null),
icon: new FormControl<string | null>(null), icon: new FormControl<string | null>(null),
isPublic: new FormControl<boolean>(false),
group: this.createGroup() group: this.createGroup()
}); });
shelfId: number | null = null; shelfId: number | null = null;
isAdmin: boolean = false;
libraryService = inject(LibraryService); libraryService = inject(LibraryService);
magicShelfService = inject(MagicShelfService); magicShelfService = inject(MagicShelfService);
messageService = inject(MessageService); messageService = inject(MessageService);
config = inject(DynamicDialogConfig); config = inject(DynamicDialogConfig);
userService = inject(UserService);
private iconPicker = inject(IconPickerService); private iconPicker = inject(IconPickerService);
trackByFn(ruleCtrl: AbstractControl, index: number): any { trackByFn(ruleCtrl: AbstractControl, index: number): any {
@@ -206,6 +212,7 @@ export class MagicShelfComponent implements OnInit {
} }
ngOnInit(): void { ngOnInit(): void {
this.isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const id = this.config?.data?.id; const id = this.config?.data?.id;
if (id) { if (id) {
@@ -214,6 +221,7 @@ export class MagicShelfComponent implements OnInit {
this.form = new FormGroup({ this.form = new FormGroup({
name: new FormControl<string | null>(data?.name ?? null, {nonNullable: true, validators: [Validators.required]}), name: new FormControl<string | null>(data?.name ?? null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(data?.icon ?? null, {nonNullable: true, validators: [Validators.required]}), icon: new FormControl<string | null>(data?.icon ?? null, {nonNullable: true, validators: [Validators.required]}),
isPublic: new FormControl<boolean>(data?.isPublic ?? false),
group: data?.filterJson ? this.buildGroupFromData(JSON.parse(data.filterJson)) : this.createGroup() group: data?.filterJson ? this.buildGroupFromData(JSON.parse(data.filterJson)) : this.createGroup()
}); });
}); });
@@ -221,6 +229,7 @@ export class MagicShelfComponent implements OnInit {
this.form = new FormGroup({ this.form = new FormGroup({
name: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}), name: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}), icon: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}),
isPublic: new FormControl<boolean>(false),
group: this.createGroup() group: this.createGroup()
}); });
} }
@@ -432,25 +441,36 @@ export class MagicShelfComponent implements OnInit {
} }
} }
onIsPublicChange(event: any) {
this.form.get('isPublic')?.setValue(event.checked);
}
submit() { submit() {
if (!this.hasAtLeastOneValidRule(this.group)) { if (!this.hasAtLeastOneValidRule(this.group)) {
this.messageService.add({severity: 'warn', summary: 'Validation Error', detail: 'You must add at least one valid rule before saving.'}); this.messageService.add({severity: 'warn', summary: 'Validation Error', detail: 'You must add at least one valid rule before saving.'});
return; return;
} }
const value = this.form.value as { name: string | null; icon: string | null; group: GroupRule }; const value = this.form.value as { name: string | null; icon: string | null; group: GroupRule, isPublic: boolean | null };
const cleanedGroup = removeNulls(serializeDateRules(value.group)); const cleanedGroup = removeNulls(serializeDateRules(value.group));
this.magicShelfService.saveShelf({ this.magicShelfService.saveShelf({
id: this.shelfId ?? undefined, id: this.shelfId ?? undefined,
name: value.name, name: value.name,
icon: value.icon, icon: value.icon,
isPublic: !!value.isPublic, // Ensure it's a boolean
group: cleanedGroup group: cleanedGroup
}).subscribe({ }).subscribe({
next: (savedShelf) => { next: (savedShelf) => {
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Magic shelf saved successfully.'}); this.messageService.add({severity: 'success', summary: 'Success', detail: 'Magic shelf saved successfully.'});
if (savedShelf?.id) { if (savedShelf?.id) {
this.shelfId = savedShelf.id; this.shelfId = savedShelf.id;
// Update the form with the saved data to reflect changes immediately
this.form.patchValue({
name: savedShelf.name,
icon: savedShelf.icon,
isPublic: savedShelf.isPublic
});
} }
}, },
error: (err) => { error: (err) => {
@@ -13,6 +13,7 @@ export interface MagicShelf {
name: string; name: string;
icon?: string; icon?: string;
filterJson: string; filterJson: string;
isPublic?: boolean;
} }
export interface MagicShelfState { export interface MagicShelfState {
@@ -92,12 +93,13 @@ export class MagicShelfService {
); );
} }
saveShelf(data: { id?: number; name: string | null; icon: string | null; group: any }): Observable<MagicShelf> { saveShelf(data: { id?: number; name: string | null; icon: string | null; group: any, isPublic?: boolean | null }): Observable<MagicShelf> {
const payload: MagicShelf = { const payload: MagicShelf = {
id: data.id, id: data.id,
name: data.name ?? '', name: data.name ?? '',
icon: data.icon ?? 'pi pi-book', icon: data.icon ?? 'pi pi-book',
filterJson: JSON.stringify(data.group), filterJson: JSON.stringify(data.group),
isPublic: data.isPublic ?? false
}; };
return this.http.post<MagicShelf>(this.url, payload).pipe( return this.http.post<MagicShelf>(this.url, payload).pipe(