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")
@Size(min = 2, message = "Filter JSON must not be empty")
private String filterJson;
private Boolean isPublic = false;
}
@@ -32,6 +32,10 @@ public class MagicShelfEntity {
@Column(name = "filter_json", columnDefinition = "json", nullable = false)
private String filterJson;
@Column(name = "is_public", nullable = false)
@lombok.Builder.Default
private boolean isPublic = false;
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt = LocalDateTime.now();
@@ -10,6 +10,8 @@ public interface MagicShelfRepository extends JpaRepository<MagicShelfEntity, Lo
List<MagicShelfEntity> findAllByUserId(Long userId);
List<MagicShelfEntity> findAllByIsPublicIsTrue();
Optional<MagicShelfEntity> findByUserIdAndName(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 java.util.List;
import java.util.stream.Collectors;
@AllArgsConstructor
@Service
@@ -19,9 +20,20 @@ public class MagicShelfService {
public List<MagicShelf> getUserShelves() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return repository.findAllByUserId(userId).stream()
List<MagicShelf> shelves = repository.findAllByUserId(userId).stream()
.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();
shelves.addAll(publicShelves);
return shelves;
}
@Transactional
@@ -32,9 +44,13 @@ public class MagicShelfService {
if (!existing.getUserId().equals(userId)) {
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.setIcon(dto.getIcon());
existing.setFilterJson(dto.getFilterJson());
existing.setPublic(dto.getIsPublic());
return toDto(repository.save(existing));
}
if (repository.existsByUserIdAndName(userId, dto.getName())) {
@@ -59,6 +75,7 @@ public class MagicShelfService {
dto.setName(entity.getName());
dto.setIcon(entity.getIcon());
dto.setFilterJson(entity.getFilterJson());
dto.setIsPublic(entity.isPublic());
return dto;
}
@@ -68,6 +85,7 @@ public class MagicShelfService {
entity.setName(dto.getName());
entity.setIcon(dto.getIcon());
entity.setFilterJson(dto.getFilterJson());
entity.setPublic(dto.getIsPublic());
entity.setUserId(userId);
return entity;
}
@@ -76,4 +94,4 @@ public class MagicShelfService {
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
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 {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {UserService} from "../../settings/user-management/user.service";
@Injectable({
providedIn: 'root',
@@ -29,6 +30,7 @@ export class LibraryShelfMenuService {
private router = inject(Router);
private dialogService = inject(DialogService);
private magicShelfService = inject(MagicShelfService);
private userService = inject(UserService);
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
return [
@@ -203,13 +205,18 @@ export class LibraryShelfMenuService {
}
initializeMagicShelfMenuItems(entity: any): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = isPublicShelf && !isAdmin;
return [
{
label: 'Options',
label: (isPublicShelf ? 'Public Shelf - ' : '') + (disableOptions ? 'Read only' : 'Options'),
items: [
{
label: 'Edit Magic Shelf',
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogService.open(MagicShelfComponent, {
header: 'Edit Magic Shelf',
@@ -224,6 +231,7 @@ export class LibraryShelfMenuService {
{
label: 'Delete Magic Shelf',
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
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="mb-4 flex w-full gap-4">
<div class="flex-1">
<label for="shelfName" class="block mb-1 font-semibold">Shelf Name</label>
<input pInputText id="shelfName" type="text" formControlName="name" placeholder="E.g. Rom-Zom-Coms, Fast & Furious, Missing Metadata" class="w-full"/>
</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>
<fieldset [disabled]="form.get('isPublic')?.value && !isAdmin">
<div class="mb-4 flex w-full gap-4">
<div class="flex-1">
<label for="shelfName" class="block mb-1 font-semibold">Shelf Name</label>
<input pInputText id="shelfName" type="text" formControlName="name" placeholder="E.g. Rom-Zom-Coms, Fast & Furious, Missing Metadata" class="w-full"/>
</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 class="overflow-auto max-h-[40rem]">
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: form.get('group') }"></ng-container>
</div>
<div class="my-4 text-left">
<p-button
label="Save Filter"
outlined
severity="success"
(click)="submit()"
[disabled]="form.invalid"></p-button>
</div>
<div class="overflow-auto max-h-[40rem]">
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: form.get('group') }"></ng-container>
</div>
<div class="my-4 text-left">
<p-button
label="Save Filter"
outlined
severity="success"
(click)="submit()"
[disabled]="form.invalid"></p-button>
</div>
</fieldset>
</div>
<ng-template #groupTemplate let-group="group">
@@ -16,6 +16,8 @@ import {MultiSelect} from 'primeng/multiselect';
import {AutoComplete} from 'primeng/autocomplete';
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils';
import {IconPickerService} from '../../../shared/service/icon-picker.service';
import {CheckboxModule} from "primeng/checkbox";
import {UserService} from "../../settings/user-management/user.service";
export type RuleOperator =
| 'equals'
@@ -150,7 +152,8 @@ const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
DatePicker,
InputNumber,
MultiSelect,
AutoComplete
AutoComplete,
CheckboxModule
]
})
export class MagicShelfComponent implements OnInit {
@@ -190,15 +193,18 @@ export class MagicShelfComponent implements OnInit {
form = new FormGroup({
name: new FormControl<string | null>(null),
icon: new FormControl<string | null>(null),
isPublic: new FormControl<boolean>(false),
group: this.createGroup()
});
shelfId: number | null = null;
isAdmin: boolean = false;
libraryService = inject(LibraryService);
magicShelfService = inject(MagicShelfService);
messageService = inject(MessageService);
config = inject(DynamicDialogConfig);
userService = inject(UserService);
private iconPicker = inject(IconPickerService);
trackByFn(ruleCtrl: AbstractControl, index: number): any {
@@ -206,6 +212,7 @@ export class MagicShelfComponent implements OnInit {
}
ngOnInit(): void {
this.isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const id = this.config?.data?.id;
if (id) {
@@ -214,6 +221,7 @@ export class MagicShelfComponent implements OnInit {
this.form = new FormGroup({
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]}),
isPublic: new FormControl<boolean>(data?.isPublic ?? false),
group: data?.filterJson ? this.buildGroupFromData(JSON.parse(data.filterJson)) : this.createGroup()
});
});
@@ -221,6 +229,7 @@ export class MagicShelfComponent implements OnInit {
this.form = new FormGroup({
name: 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()
});
}
@@ -432,25 +441,36 @@ export class MagicShelfComponent implements OnInit {
}
}
onIsPublicChange(event: any) {
this.form.get('isPublic')?.setValue(event.checked);
}
submit() {
if (!this.hasAtLeastOneValidRule(this.group)) {
this.messageService.add({severity: 'warn', summary: 'Validation Error', detail: 'You must add at least one valid rule before saving.'});
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));
this.magicShelfService.saveShelf({
id: this.shelfId ?? undefined,
name: value.name,
icon: value.icon,
isPublic: !!value.isPublic, // Ensure it's a boolean
group: cleanedGroup
}).subscribe({
next: (savedShelf) => {
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Magic shelf saved successfully.'});
if (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) => {
@@ -13,6 +13,7 @@ export interface MagicShelf {
name: string;
icon?: string;
filterJson: string;
isPublic?: boolean;
}
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 = {
id: data.id,
name: data.name ?? '',
icon: data.icon ?? 'pi pi-book',
filterJson: JSON.stringify(data.group),
isPublic: data.isPublic ?? false
};
return this.http.post<MagicShelf>(this.url, payload).pipe(