Add support for annotations and book notes in the new ebook reader (#2313)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+67
@@ -0,0 +1,67 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Annotation;
|
||||
import com.adityachandel.booklore.model.dto.CreateAnnotationRequest;
|
||||
import com.adityachandel.booklore.model.dto.UpdateAnnotationRequest;
|
||||
import com.adityachandel.booklore.service.book.AnnotationService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/annotations")
|
||||
@Tag(name = "Annotations", description = "Endpoints for managing book annotations (highlights, underlines, etc.)")
|
||||
public class AnnotationController {
|
||||
|
||||
private final AnnotationService annotationService;
|
||||
|
||||
@Operation(summary = "Get annotations for a book", description = "Retrieve all annotations for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Annotations returned successfully")
|
||||
@GetMapping("/book/{bookId}")
|
||||
public List<Annotation> getAnnotationsForBook(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return annotationService.getAnnotationsForBook(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a specific annotation", description = "Retrieve a specific annotation by its ID.")
|
||||
@ApiResponse(responseCode = "200", description = "Annotation returned successfully")
|
||||
@GetMapping("/{annotationId}")
|
||||
public Annotation getAnnotationById(
|
||||
@Parameter(description = "ID of the annotation") @PathVariable Long annotationId) {
|
||||
return annotationService.getAnnotationById(annotationId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Create an annotation", description = "Create a new annotation (highlight, underline, etc.) for a book.")
|
||||
@ApiResponse(responseCode = "200", description = "Annotation created successfully")
|
||||
@PostMapping
|
||||
public Annotation createAnnotation(
|
||||
@Parameter(description = "Annotation creation request") @Valid @RequestBody CreateAnnotationRequest request) {
|
||||
return annotationService.createAnnotation(request);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update an annotation", description = "Update an existing annotation's properties (color, style, note).")
|
||||
@ApiResponse(responseCode = "200", description = "Annotation updated successfully")
|
||||
@PutMapping("/{annotationId}")
|
||||
public Annotation updateAnnotation(
|
||||
@Parameter(description = "ID of the annotation to update") @PathVariable Long annotationId,
|
||||
@Parameter(description = "Annotation update request") @Valid @RequestBody UpdateAnnotationRequest request) {
|
||||
return annotationService.updateAnnotation(annotationId, request);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete an annotation", description = "Delete a specific annotation by its ID.")
|
||||
@ApiResponse(responseCode = "204", description = "Annotation deleted successfully")
|
||||
@DeleteMapping("/{annotationId}")
|
||||
public ResponseEntity<Void> deleteAnnotation(
|
||||
@Parameter(description = "ID of the annotation to delete") @PathVariable Long annotationId) {
|
||||
annotationService.deleteAnnotation(annotationId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookNoteV2;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.service.book.BookNoteV2Service;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v2/book-notes")
|
||||
@Tag(name = "Book Notes V2", description = "Endpoints for managing CFI-based book notes with text selection context")
|
||||
public class BookNotesV2Controller {
|
||||
|
||||
private final BookNoteV2Service bookNoteV2Service;
|
||||
|
||||
@Operation(summary = "Get notes for a book", description = "Retrieve all notes for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Notes returned successfully")
|
||||
@GetMapping("/book/{bookId}")
|
||||
public List<BookNoteV2> getNotesForBook(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return bookNoteV2Service.getNotesForBook(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a specific note", description = "Retrieve a specific note by its ID.")
|
||||
@ApiResponse(responseCode = "200", description = "Note returned successfully")
|
||||
@GetMapping("/{noteId}")
|
||||
public BookNoteV2 getNoteById(
|
||||
@Parameter(description = "ID of the note") @PathVariable Long noteId) {
|
||||
return bookNoteV2Service.getNoteById(noteId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Create a note", description = "Create a new note at a specific location in a book.")
|
||||
@ApiResponse(responseCode = "200", description = "Note created successfully")
|
||||
@PostMapping
|
||||
public BookNoteV2 createNote(
|
||||
@Parameter(description = "Note creation request") @Valid @RequestBody CreateBookNoteV2Request request) {
|
||||
return bookNoteV2Service.createNote(request);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update a note", description = "Update an existing note's content or color.")
|
||||
@ApiResponse(responseCode = "200", description = "Note updated successfully")
|
||||
@PutMapping("/{noteId}")
|
||||
public BookNoteV2 updateNote(
|
||||
@Parameter(description = "ID of the note to update") @PathVariable Long noteId,
|
||||
@Parameter(description = "Note update request") @Valid @RequestBody UpdateBookNoteV2Request request) {
|
||||
return bookNoteV2Service.updateNote(noteId, request);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete a note", description = "Delete a specific note by its ID.")
|
||||
@ApiResponse(responseCode = "204", description = "Note deleted successfully")
|
||||
@DeleteMapping("/{noteId}")
|
||||
public ResponseEntity<Void> deleteNote(
|
||||
@Parameter(description = "ID of the note to delete") @PathVariable Long noteId) {
|
||||
bookNoteV2Service.deleteNote(noteId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Annotation;
|
||||
import com.adityachandel.booklore.model.entity.AnnotationEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface AnnotationMapper {
|
||||
|
||||
@Mapping(source = "book.id", target = "bookId")
|
||||
@Mapping(source = "user.id", target = "userId")
|
||||
Annotation toDto(AnnotationEntity entity);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookNoteV2;
|
||||
import com.adityachandel.booklore.model.entity.BookNoteV2Entity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface BookNoteV2Mapper {
|
||||
|
||||
@Mapping(source = "book.id", target = "bookId")
|
||||
@Mapping(source = "user.id", target = "userId")
|
||||
BookNoteV2 toDto(BookNoteV2Entity entity);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Annotation {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private Long bookId;
|
||||
private String cfi;
|
||||
private String text;
|
||||
private String color;
|
||||
private String style;
|
||||
private String note;
|
||||
private String chapterTitle;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BookNoteV2 {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private Long bookId;
|
||||
private String cfi;
|
||||
private String selectedText;
|
||||
private String noteContent;
|
||||
private String color;
|
||||
private String chapterTitle;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CreateAnnotationRequest {
|
||||
|
||||
@NotNull(message = "Book ID is required")
|
||||
private Long bookId;
|
||||
|
||||
@NotEmpty(message = "CFI is required")
|
||||
@Size(max = 1000, message = "CFI must not exceed 1000 characters")
|
||||
private String cfi;
|
||||
|
||||
@NotEmpty(message = "Text is required")
|
||||
@Size(max = 5000, message = "Text must not exceed 5000 characters")
|
||||
private String text;
|
||||
|
||||
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
|
||||
private String color;
|
||||
|
||||
@Pattern(regexp = "^(highlight|underline|strikethrough|squiggly)$", message = "Style must be one of: highlight, underline, strikethrough, squiggly")
|
||||
private String style;
|
||||
|
||||
@Size(max = 5000, message = "Note must not exceed 5000 characters")
|
||||
private String note;
|
||||
|
||||
@Size(max = 500, message = "Chapter title must not exceed 500 characters")
|
||||
private String chapterTitle;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CreateBookNoteV2Request {
|
||||
|
||||
@NotNull(message = "Book ID is required")
|
||||
private Long bookId;
|
||||
|
||||
@NotEmpty(message = "CFI is required")
|
||||
@Size(max = 1000, message = "CFI must not exceed 1000 characters")
|
||||
private String cfi;
|
||||
|
||||
@Size(max = 5000, message = "Selected text must not exceed 5000 characters")
|
||||
private String selectedText;
|
||||
|
||||
@NotEmpty(message = "Note content is required")
|
||||
private String noteContent;
|
||||
|
||||
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
|
||||
private String color;
|
||||
|
||||
@Size(max = 500, message = "Chapter title must not exceed 500 characters")
|
||||
private String chapterTitle;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class UpdateAnnotationRequest {
|
||||
|
||||
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
|
||||
private String color;
|
||||
|
||||
@Pattern(regexp = "^(highlight|underline|strikethrough|squiggly)$", message = "Style must be one of: highlight, underline, strikethrough, squiggly")
|
||||
private String style;
|
||||
|
||||
@Size(max = 5000, message = "Note must not exceed 5000 characters")
|
||||
private String note;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class UpdateBookNoteV2Request {
|
||||
|
||||
private String noteContent;
|
||||
|
||||
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
|
||||
private String color;
|
||||
|
||||
@Size(max = 500, message = "Chapter title must not exceed 500 characters")
|
||||
private String chapterTitle;
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "annotations")
|
||||
public class AnnotationEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@Column(name = "user_id", insertable = false, updatable = false)
|
||||
private Long userId;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "book_id", nullable = false)
|
||||
private BookEntity book;
|
||||
|
||||
@Column(name = "book_id", insertable = false, updatable = false)
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "cfi", nullable = false, length = 1000)
|
||||
private String cfi;
|
||||
|
||||
@Column(name = "text", nullable = false, length = 5000)
|
||||
private String text;
|
||||
|
||||
@Column(name = "color", length = 20)
|
||||
private String color;
|
||||
|
||||
@Column(name = "style", length = 50)
|
||||
private String style;
|
||||
|
||||
@Column(name = "note", length = 5000)
|
||||
private String note;
|
||||
|
||||
@Column(name = "chapter_title", length = 500)
|
||||
private String chapterTitle;
|
||||
|
||||
@jakarta.persistence.Version
|
||||
@Column(name = "version", nullable = false)
|
||||
private Long version;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "book_notes_v2")
|
||||
public class BookNoteV2Entity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@Column(name = "user_id", insertable = false, updatable = false)
|
||||
private Long userId;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "book_id", nullable = false)
|
||||
private BookEntity book;
|
||||
|
||||
@Column(name = "book_id", insertable = false, updatable = false)
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "cfi", nullable = false, length = 1000)
|
||||
private String cfi;
|
||||
|
||||
@Column(name = "selected_text", length = 5000)
|
||||
private String selectedText;
|
||||
|
||||
@Column(name = "note_content", nullable = false, columnDefinition = "TEXT")
|
||||
private String noteContent;
|
||||
|
||||
@Column(name = "color", length = 20)
|
||||
private String color;
|
||||
|
||||
@Column(name = "chapter_title", length = 500)
|
||||
private String chapterTitle;
|
||||
|
||||
@jakarta.persistence.Version
|
||||
@Column(name = "version", nullable = false)
|
||||
private Long version;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AnnotationEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface AnnotationRepository extends JpaRepository<AnnotationEntity, Long> {
|
||||
|
||||
Optional<AnnotationEntity> findByIdAndUserId(Long id, Long userId);
|
||||
|
||||
@Query("SELECT a FROM AnnotationEntity a WHERE a.bookId = :bookId AND a.userId = :userId ORDER BY a.createdAt DESC")
|
||||
List<AnnotationEntity> findByBookIdAndUserIdOrderByCreatedAtDesc(
|
||||
@Param("bookId") Long bookId,
|
||||
@Param("userId") Long userId
|
||||
);
|
||||
|
||||
boolean existsByCfiAndBookIdAndUserId(String cfi, Long bookId, Long userId);
|
||||
|
||||
@Query("SELECT COUNT(a) > 0 FROM AnnotationEntity a WHERE a.cfi = :cfi AND a.bookId = :bookId AND a.userId = :userId AND a.id != :excludeId")
|
||||
boolean existsByCfiAndBookIdAndUserIdExcludeId(
|
||||
@Param("cfi") String cfi,
|
||||
@Param("bookId") Long bookId,
|
||||
@Param("userId") Long userId,
|
||||
@Param("excludeId") Long excludeId
|
||||
);
|
||||
|
||||
long countByBookIdAndUserId(Long bookId, Long userId);
|
||||
|
||||
void deleteByBookIdAndUserId(Long bookId, Long userId);
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookNoteV2Entity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface BookNoteV2Repository extends JpaRepository<BookNoteV2Entity, Long> {
|
||||
|
||||
Optional<BookNoteV2Entity> findByIdAndUserId(Long id, Long userId);
|
||||
|
||||
@Query("SELECT n FROM BookNoteV2Entity n WHERE n.bookId = :bookId AND n.userId = :userId ORDER BY n.createdAt DESC")
|
||||
List<BookNoteV2Entity> findByBookIdAndUserIdOrderByCreatedAtDesc(
|
||||
@Param("bookId") Long bookId,
|
||||
@Param("userId") Long userId
|
||||
);
|
||||
|
||||
boolean existsByCfiAndBookIdAndUserId(String cfi, Long bookId, Long userId);
|
||||
|
||||
@Query("SELECT COUNT(n) > 0 FROM BookNoteV2Entity n WHERE n.cfi = :cfi AND n.bookId = :bookId AND n.userId = :userId AND n.id != :excludeId")
|
||||
boolean existsByCfiAndBookIdAndUserIdExcludeId(
|
||||
@Param("cfi") String cfi,
|
||||
@Param("bookId") Long bookId,
|
||||
@Param("userId") Long userId,
|
||||
@Param("excludeId") Long excludeId
|
||||
);
|
||||
|
||||
long countByBookIdAndUserId(Long bookId, Long userId);
|
||||
|
||||
void deleteByBookIdAndUserId(Long bookId, Long userId);
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.adityachandel.booklore.service.book;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.mapper.AnnotationMapper;
|
||||
import com.adityachandel.booklore.model.dto.Annotation;
|
||||
import com.adityachandel.booklore.model.dto.CreateAnnotationRequest;
|
||||
import com.adityachandel.booklore.model.dto.UpdateAnnotationRequest;
|
||||
import com.adityachandel.booklore.model.entity.AnnotationEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.AnnotationRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AnnotationService {
|
||||
|
||||
private final AnnotationRepository annotationRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AnnotationMapper mapper;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Annotation> getAnnotationsForBook(Long bookId) {
|
||||
Long userId = getCurrentUserId();
|
||||
return annotationRepository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)
|
||||
.stream()
|
||||
.map(mapper::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Annotation getAnnotationById(Long annotationId) {
|
||||
return mapper.toDto(findAnnotationByIdAndUser(annotationId));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Annotation createAnnotation(CreateAnnotationRequest request) {
|
||||
Long userId = getCurrentUserId();
|
||||
validateNoDuplicateAnnotation(request.getCfi(), request.getBookId(), userId);
|
||||
|
||||
String color = request.getColor() != null ? request.getColor() : "#FFFF00";
|
||||
String style = request.getStyle() != null ? request.getStyle() : "highlight";
|
||||
|
||||
AnnotationEntity annotation = AnnotationEntity.builder()
|
||||
.cfi(request.getCfi())
|
||||
.text(request.getText())
|
||||
.color(color)
|
||||
.style(style)
|
||||
.note(request.getNote())
|
||||
.chapterTitle(request.getChapterTitle())
|
||||
.book(findBook(request.getBookId()))
|
||||
.user(findUser(userId))
|
||||
.build();
|
||||
|
||||
log.info("Creating annotation for book {} by user {}", request.getBookId(), userId);
|
||||
return mapper.toDto(annotationRepository.save(annotation));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Annotation updateAnnotation(Long annotationId, UpdateAnnotationRequest request) {
|
||||
AnnotationEntity annotation = findAnnotationByIdAndUser(annotationId);
|
||||
|
||||
applyUpdates(annotation, request);
|
||||
|
||||
log.info("Updating annotation {}", annotationId);
|
||||
return mapper.toDto(annotationRepository.save(annotation));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAnnotation(Long annotationId) {
|
||||
AnnotationEntity annotation = findAnnotationByIdAndUser(annotationId);
|
||||
log.info("Deleting annotation {}", annotationId);
|
||||
annotationRepository.delete(annotation);
|
||||
}
|
||||
|
||||
private Long getCurrentUserId() {
|
||||
return authenticationService.getAuthenticatedUser().getId();
|
||||
}
|
||||
|
||||
private AnnotationEntity findAnnotationByIdAndUser(Long annotationId) {
|
||||
Long userId = getCurrentUserId();
|
||||
return annotationRepository.findByIdAndUserId(annotationId, userId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Annotation not found: " + annotationId));
|
||||
}
|
||||
|
||||
private BookEntity findBook(Long bookId) {
|
||||
return bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Book not found: " + bookId));
|
||||
}
|
||||
|
||||
private BookLoreUserEntity findUser(Long userId) {
|
||||
return userRepository.findById(userId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("User not found: " + userId));
|
||||
}
|
||||
|
||||
private void validateNoDuplicateAnnotation(String cfi, Long bookId, Long userId) {
|
||||
boolean exists = annotationRepository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId);
|
||||
if (exists) {
|
||||
throw new APIException("Annotation already exists at this location", HttpStatus.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyUpdates(AnnotationEntity annotation, UpdateAnnotationRequest request) {
|
||||
Optional.ofNullable(request.getColor()).ifPresent(annotation::setColor);
|
||||
Optional.ofNullable(request.getStyle()).ifPresent(annotation::setStyle);
|
||||
Optional.ofNullable(request.getNote()).ifPresent(annotation::setNote);
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.adityachandel.booklore.service.book;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.mapper.BookNoteV2Mapper;
|
||||
import com.adityachandel.booklore.model.dto.BookNoteV2;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookNoteV2Entity;
|
||||
import com.adityachandel.booklore.repository.BookNoteV2Repository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class BookNoteV2Service {
|
||||
|
||||
private final BookNoteV2Repository bookNoteV2Repository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookNoteV2Mapper mapper;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookNoteV2> getNotesForBook(Long bookId) {
|
||||
Long userId = getCurrentUserId();
|
||||
return bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)
|
||||
.stream()
|
||||
.map(mapper::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public BookNoteV2 getNoteById(Long noteId) {
|
||||
return mapper.toDto(findNoteByIdAndUser(noteId));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookNoteV2 createNote(CreateBookNoteV2Request request) {
|
||||
Long userId = getCurrentUserId();
|
||||
validateNoDuplicateNote(request.getCfi(), request.getBookId(), userId);
|
||||
|
||||
String color = request.getColor() != null ? request.getColor() : "#FFC107";
|
||||
|
||||
BookNoteV2Entity note = BookNoteV2Entity.builder()
|
||||
.cfi(request.getCfi())
|
||||
.selectedText(request.getSelectedText())
|
||||
.noteContent(request.getNoteContent())
|
||||
.color(color)
|
||||
.chapterTitle(request.getChapterTitle())
|
||||
.book(findBook(request.getBookId()))
|
||||
.user(findUser(userId))
|
||||
.build();
|
||||
|
||||
log.info("Creating note for book {} by user {}", request.getBookId(), userId);
|
||||
return mapper.toDto(bookNoteV2Repository.save(note));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookNoteV2 updateNote(Long noteId, UpdateBookNoteV2Request request) {
|
||||
BookNoteV2Entity note = findNoteByIdAndUser(noteId);
|
||||
|
||||
applyUpdates(note, request);
|
||||
|
||||
log.info("Updating note {}", noteId);
|
||||
return mapper.toDto(bookNoteV2Repository.save(note));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteNote(Long noteId) {
|
||||
BookNoteV2Entity note = findNoteByIdAndUser(noteId);
|
||||
log.info("Deleting note {}", noteId);
|
||||
bookNoteV2Repository.delete(note);
|
||||
}
|
||||
|
||||
private Long getCurrentUserId() {
|
||||
return authenticationService.getAuthenticatedUser().getId();
|
||||
}
|
||||
|
||||
private BookNoteV2Entity findNoteByIdAndUser(Long noteId) {
|
||||
Long userId = getCurrentUserId();
|
||||
return bookNoteV2Repository.findByIdAndUserId(noteId, userId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Note not found: " + noteId));
|
||||
}
|
||||
|
||||
private BookEntity findBook(Long bookId) {
|
||||
return bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Book not found: " + bookId));
|
||||
}
|
||||
|
||||
private BookLoreUserEntity findUser(Long userId) {
|
||||
return userRepository.findById(userId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("User not found: " + userId));
|
||||
}
|
||||
|
||||
private void validateNoDuplicateNote(String cfi, Long bookId, Long userId) {
|
||||
boolean exists = bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId);
|
||||
if (exists) {
|
||||
throw new APIException("Note already exists at this location", HttpStatus.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyUpdates(BookNoteV2Entity note, UpdateBookNoteV2Request request) {
|
||||
Optional.ofNullable(request.getNoteContent()).ifPresent(note::setNoteContent);
|
||||
Optional.ofNullable(request.getColor()).ifPresent(note::setColor);
|
||||
Optional.ofNullable(request.getChapterTitle()).ifPresent(note::setChapterTitle);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
CREATE TABLE annotations
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT NOT NULL,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
cfi VARCHAR(1000) NOT NULL,
|
||||
text VARCHAR(5000) NOT NULL,
|
||||
color VARCHAR(20) NULL,
|
||||
style VARCHAR(50) NULL,
|
||||
note VARCHAR(5000) NULL,
|
||||
chapter_title VARCHAR(500) NULL,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
created_at datetime NOT NULL,
|
||||
updated_at datetime NOT NULL,
|
||||
CONSTRAINT pk_annotations PRIMARY KEY (id),
|
||||
CONSTRAINT uq_annotation_user_book_cfi UNIQUE (user_id, book_id, cfi)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_annotations_user_id ON annotations (user_id);
|
||||
CREATE INDEX idx_annotations_book_id ON annotations (book_id);
|
||||
CREATE INDEX idx_annotations_user_book ON annotations (user_id, book_id);
|
||||
|
||||
ALTER TABLE annotations
|
||||
ADD CONSTRAINT fk_annotations_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE annotations
|
||||
ADD CONSTRAINT fk_annotations_book_id FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE;
|
||||
@@ -0,0 +1,26 @@
|
||||
CREATE TABLE book_notes_v2
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT NOT NULL,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
cfi VARCHAR(1000) NOT NULL,
|
||||
selected_text VARCHAR(5000) NULL,
|
||||
note_content TEXT NOT NULL,
|
||||
color VARCHAR(20) NULL,
|
||||
chapter_title VARCHAR(500) NULL,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
created_at datetime NOT NULL,
|
||||
updated_at datetime NOT NULL,
|
||||
CONSTRAINT pk_book_notes_v2 PRIMARY KEY (id),
|
||||
CONSTRAINT uq_book_notes_v2_user_book_cfi UNIQUE (user_id, book_id, cfi)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_book_notes_v2_user_id ON book_notes_v2 (user_id);
|
||||
CREATE INDEX idx_book_notes_v2_book_id ON book_notes_v2 (book_id);
|
||||
CREATE INDEX idx_book_notes_v2_user_book ON book_notes_v2 (user_id, book_id);
|
||||
|
||||
ALTER TABLE book_notes_v2
|
||||
ADD CONSTRAINT fk_book_notes_v2_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE book_notes_v2
|
||||
ADD CONSTRAINT fk_book_notes_v2_book_id FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE;
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookNoteV2;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.service.book.BookNoteV2Service;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookNotesV2ControllerTest {
|
||||
|
||||
@Mock
|
||||
private BookNoteV2Service bookNoteV2Service;
|
||||
|
||||
@InjectMocks
|
||||
private BookNotesV2Controller controller;
|
||||
|
||||
private final Long bookId = 1L;
|
||||
private final Long noteId = 2L;
|
||||
private final Long userId = 3L;
|
||||
private final String cfi = "epubcfi(/6/4!/4/2/1:0)";
|
||||
private final String selectedText = "Some selected text";
|
||||
private final String noteContent = "My note content";
|
||||
private final String color = "#FFC107";
|
||||
private final String chapterTitle = "Chapter 1";
|
||||
|
||||
@Test
|
||||
void getNotesForBook_returnsNotesList() {
|
||||
BookNoteV2 note1 = createSampleNote(1L);
|
||||
BookNoteV2 note2 = createSampleNote(2L);
|
||||
List<BookNoteV2> expectedNotes = List.of(note1, note2);
|
||||
|
||||
when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(expectedNotes);
|
||||
|
||||
List<BookNoteV2> result = controller.getNotesForBook(bookId);
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals(1L, result.get(0).getId());
|
||||
assertEquals(2L, result.get(1).getId());
|
||||
verify(bookNoteV2Service).getNotesForBook(bookId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotesForBook_returnsEmptyList_whenNoNotes() {
|
||||
when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<BookNoteV2> result = controller.getNotesForBook(bookId);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
verify(bookNoteV2Service).getNotesForBook(bookId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNoteById_returnsNote() {
|
||||
BookNoteV2 expectedNote = createSampleNote(noteId);
|
||||
|
||||
when(bookNoteV2Service.getNoteById(noteId)).thenReturn(expectedNote);
|
||||
|
||||
BookNoteV2 result = controller.getNoteById(noteId);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertEquals(cfi, result.getCfi());
|
||||
assertEquals(selectedText, result.getSelectedText());
|
||||
assertEquals(noteContent, result.getNoteContent());
|
||||
assertEquals(color, result.getColor());
|
||||
assertEquals(chapterTitle, result.getChapterTitle());
|
||||
verify(bookNoteV2Service).getNoteById(noteId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_createsAndReturnsNote() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.selectedText(selectedText)
|
||||
.noteContent(noteContent)
|
||||
.color(color)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
BookNoteV2 expectedNote = createSampleNote(noteId);
|
||||
|
||||
when(bookNoteV2Service.createNote(request)).thenReturn(expectedNote);
|
||||
|
||||
BookNoteV2 result = controller.createNote(request);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertEquals(cfi, result.getCfi());
|
||||
assertEquals(noteContent, result.getNoteContent());
|
||||
verify(bookNoteV2Service).createNote(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_createsNoteWithoutOptionalFields() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.build();
|
||||
|
||||
BookNoteV2 expectedNote = BookNoteV2.builder()
|
||||
.id(noteId)
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.color("#FFC107")
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Service.createNote(request)).thenReturn(expectedNote);
|
||||
|
||||
BookNoteV2 result = controller.createNote(request);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertNull(result.getSelectedText());
|
||||
assertNull(result.getChapterTitle());
|
||||
verify(bookNoteV2Service).createNote(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNote_updatesAndReturnsNote() {
|
||||
UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder()
|
||||
.noteContent("Updated content")
|
||||
.color("#00FF00")
|
||||
.chapterTitle("Updated chapter")
|
||||
.build();
|
||||
|
||||
BookNoteV2 expectedNote = BookNoteV2.builder()
|
||||
.id(noteId)
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.cfi(cfi)
|
||||
.noteContent("Updated content")
|
||||
.color("#00FF00")
|
||||
.chapterTitle("Updated chapter")
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Service.updateNote(noteId, request)).thenReturn(expectedNote);
|
||||
|
||||
BookNoteV2 result = controller.updateNote(noteId, request);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertEquals("Updated content", result.getNoteContent());
|
||||
assertEquals("#00FF00", result.getColor());
|
||||
assertEquals("Updated chapter", result.getChapterTitle());
|
||||
verify(bookNoteV2Service).updateNote(noteId, request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNote_updatesPartialFields() {
|
||||
UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder()
|
||||
.noteContent("Updated content only")
|
||||
.build();
|
||||
|
||||
BookNoteV2 expectedNote = BookNoteV2.builder()
|
||||
.id(noteId)
|
||||
.noteContent("Updated content only")
|
||||
.color(color)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Service.updateNote(noteId, request)).thenReturn(expectedNote);
|
||||
|
||||
BookNoteV2 result = controller.updateNote(noteId, request);
|
||||
|
||||
assertEquals("Updated content only", result.getNoteContent());
|
||||
assertEquals(color, result.getColor());
|
||||
assertEquals(chapterTitle, result.getChapterTitle());
|
||||
verify(bookNoteV2Service).updateNote(noteId, request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNote_deletesNoteAndReturnsNoContent() {
|
||||
doNothing().when(bookNoteV2Service).deleteNote(noteId);
|
||||
|
||||
ResponseEntity<Void> response = controller.deleteNote(noteId);
|
||||
|
||||
assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
|
||||
assertNull(response.getBody());
|
||||
verify(bookNoteV2Service).deleteNote(noteId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNote_callsServiceWithCorrectId() {
|
||||
doNothing().when(bookNoteV2Service).deleteNote(noteId);
|
||||
|
||||
controller.deleteNote(noteId);
|
||||
|
||||
verify(bookNoteV2Service, times(1)).deleteNote(noteId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotesForBook_delegatesToService() {
|
||||
List<BookNoteV2> notes = List.of(createSampleNote(1L), createSampleNote(2L), createSampleNote(3L));
|
||||
when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(notes);
|
||||
|
||||
List<BookNoteV2> result = controller.getNotesForBook(bookId);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
verify(bookNoteV2Service, times(1)).getNotesForBook(bookId);
|
||||
verifyNoMoreInteractions(bookNoteV2Service);
|
||||
}
|
||||
|
||||
private BookNoteV2 createSampleNote(Long id) {
|
||||
return BookNoteV2.builder()
|
||||
.id(id)
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.cfi(cfi)
|
||||
.selectedText(selectedText)
|
||||
.noteContent(noteContent)
|
||||
.color(color)
|
||||
.chapterTitle(chapterTitle)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.updatedAt(LocalDateTime.now())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.mapper.BookNoteV2Mapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.BookNoteV2;
|
||||
import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookNoteV2Entity;
|
||||
import com.adityachandel.booklore.repository.BookNoteV2Repository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.book.BookNoteV2Service;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BookNoteV2ServiceTest {
|
||||
|
||||
private BookNoteV2Repository bookNoteV2Repository;
|
||||
private BookRepository bookRepository;
|
||||
private UserRepository userRepository;
|
||||
private AuthenticationService authenticationService;
|
||||
private BookNoteV2Mapper mapper;
|
||||
private BookNoteV2Service service;
|
||||
|
||||
private final Long userId = 1L;
|
||||
private final Long bookId = 2L;
|
||||
private final Long noteId = 3L;
|
||||
private final String cfi = "epubcfi(/6/4!/4/2/1:0)";
|
||||
private final String selectedText = "Some selected text";
|
||||
private final String noteContent = "My note content";
|
||||
private final String defaultColor = "#FFC107";
|
||||
private final String customColor = "#FF5733";
|
||||
private final String chapterTitle = "Chapter 1";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
bookNoteV2Repository = mock(BookNoteV2Repository.class);
|
||||
bookRepository = mock(BookRepository.class);
|
||||
userRepository = mock(UserRepository.class);
|
||||
authenticationService = mock(AuthenticationService.class);
|
||||
mapper = mock(BookNoteV2Mapper.class);
|
||||
service = new BookNoteV2Service(bookNoteV2Repository, bookRepository, userRepository, authenticationService, mapper);
|
||||
|
||||
BookLoreUser user = new BookLoreUser();
|
||||
user.setId(userId);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotesForBook_returnsMappedNotes() {
|
||||
BookNoteV2Entity entity = BookNoteV2Entity.builder().id(noteId).cfi(cfi).build();
|
||||
BookNoteV2 dto = BookNoteV2.builder().id(noteId).cfi(cfi).build();
|
||||
when(bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId))
|
||||
.thenReturn(Collections.singletonList(entity));
|
||||
when(mapper.toDto(entity)).thenReturn(dto);
|
||||
|
||||
List<BookNoteV2> result = service.getNotesForBook(bookId);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(noteId, result.getFirst().getId());
|
||||
assertEquals(cfi, result.getFirst().getCfi());
|
||||
verify(bookNoteV2Repository).findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotesForBook_returnsEmptyList_whenNoNotes() {
|
||||
when(bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId))
|
||||
.thenReturn(Collections.emptyList());
|
||||
|
||||
List<BookNoteV2> result = service.getNotesForBook(bookId);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNoteById_returnsNote_whenExists() {
|
||||
BookNoteV2Entity entity = BookNoteV2Entity.builder().id(noteId).cfi(cfi).build();
|
||||
BookNoteV2 dto = BookNoteV2.builder().id(noteId).cfi(cfi).build();
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(entity));
|
||||
when(mapper.toDto(entity)).thenReturn(dto);
|
||||
|
||||
BookNoteV2 result = service.getNoteById(noteId);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertEquals(cfi, result.getCfi());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNoteById_throwsEntityNotFoundException_whenNotFound() {
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
||||
|
||||
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.getNoteById(noteId));
|
||||
|
||||
assertTrue(ex.getMessage().contains(String.valueOf(noteId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_createsNewNote_withDefaultColor() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.selectedText(selectedText)
|
||||
.noteContent(noteContent)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder().id(bookId).build();
|
||||
BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build();
|
||||
BookNoteV2Entity savedEntity = BookNoteV2Entity.builder()
|
||||
.id(noteId)
|
||||
.cfi(cfi)
|
||||
.selectedText(selectedText)
|
||||
.noteContent(noteContent)
|
||||
.color(defaultColor)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
BookNoteV2 dto = BookNoteV2.builder()
|
||||
.id(noteId)
|
||||
.cfi(cfi)
|
||||
.selectedText(selectedText)
|
||||
.noteContent(noteContent)
|
||||
.color(defaultColor)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false);
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(userEntity));
|
||||
when(bookNoteV2Repository.save(any(BookNoteV2Entity.class))).thenReturn(savedEntity);
|
||||
when(mapper.toDto(savedEntity)).thenReturn(dto);
|
||||
|
||||
BookNoteV2 result = service.createNote(request);
|
||||
|
||||
assertEquals(noteId, result.getId());
|
||||
assertEquals(defaultColor, result.getColor());
|
||||
|
||||
ArgumentCaptor<BookNoteV2Entity> captor = ArgumentCaptor.forClass(BookNoteV2Entity.class);
|
||||
verify(bookNoteV2Repository).save(captor.capture());
|
||||
BookNoteV2Entity captured = captor.getValue();
|
||||
assertEquals(cfi, captured.getCfi());
|
||||
assertEquals(selectedText, captured.getSelectedText());
|
||||
assertEquals(noteContent, captured.getNoteContent());
|
||||
assertEquals(defaultColor, captured.getColor());
|
||||
assertEquals(chapterTitle, captured.getChapterTitle());
|
||||
assertEquals(book, captured.getBook());
|
||||
assertEquals(userEntity, captured.getUser());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_createsNewNote_withCustomColor() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.selectedText(selectedText)
|
||||
.noteContent(noteContent)
|
||||
.color(customColor)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder().id(bookId).build();
|
||||
BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build();
|
||||
BookNoteV2Entity savedEntity = BookNoteV2Entity.builder()
|
||||
.id(noteId)
|
||||
.color(customColor)
|
||||
.build();
|
||||
BookNoteV2 dto = BookNoteV2.builder()
|
||||
.id(noteId)
|
||||
.color(customColor)
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false);
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(userEntity));
|
||||
when(bookNoteV2Repository.save(any(BookNoteV2Entity.class))).thenReturn(savedEntity);
|
||||
when(mapper.toDto(savedEntity)).thenReturn(dto);
|
||||
|
||||
BookNoteV2 result = service.createNote(request);
|
||||
|
||||
assertEquals(customColor, result.getColor());
|
||||
|
||||
ArgumentCaptor<BookNoteV2Entity> captor = ArgumentCaptor.forClass(BookNoteV2Entity.class);
|
||||
verify(bookNoteV2Repository).save(captor.capture());
|
||||
assertEquals(customColor, captor.getValue().getColor());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_throwsAPIException_whenDuplicateCfiExists() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(true);
|
||||
|
||||
APIException ex = assertThrows(APIException.class, () -> service.createNote(request));
|
||||
|
||||
assertTrue(ex.getMessage().contains("Note already exists"));
|
||||
verify(bookNoteV2Repository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_throwsEntityNotFoundException_whenBookNotFound() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false);
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.empty());
|
||||
|
||||
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.createNote(request));
|
||||
|
||||
assertTrue(ex.getMessage().contains(String.valueOf(bookId)));
|
||||
verify(bookNoteV2Repository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNote_throwsEntityNotFoundException_whenUserNotFound() {
|
||||
CreateBookNoteV2Request request = CreateBookNoteV2Request.builder()
|
||||
.bookId(bookId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder().id(bookId).build();
|
||||
|
||||
when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false);
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.empty());
|
||||
|
||||
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.createNote(request));
|
||||
|
||||
assertTrue(ex.getMessage().contains(String.valueOf(userId)));
|
||||
verify(bookNoteV2Repository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNote_updatesAllFields() {
|
||||
UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder()
|
||||
.noteContent("Updated content")
|
||||
.color("#00FF00")
|
||||
.chapterTitle("Updated chapter")
|
||||
.build();
|
||||
|
||||
BookNoteV2Entity existingEntity = BookNoteV2Entity.builder()
|
||||
.id(noteId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.color(defaultColor)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
BookNoteV2Entity savedEntity = BookNoteV2Entity.builder()
|
||||
.id(noteId)
|
||||
.cfi(cfi)
|
||||
.noteContent("Updated content")
|
||||
.color("#00FF00")
|
||||
.chapterTitle("Updated chapter")
|
||||
.build();
|
||||
|
||||
BookNoteV2 dto = BookNoteV2.builder()
|
||||
.id(noteId)
|
||||
.noteContent("Updated content")
|
||||
.color("#00FF00")
|
||||
.chapterTitle("Updated chapter")
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookNoteV2Repository.save(existingEntity)).thenReturn(savedEntity);
|
||||
when(mapper.toDto(savedEntity)).thenReturn(dto);
|
||||
|
||||
BookNoteV2 result = service.updateNote(noteId, request);
|
||||
|
||||
assertEquals("Updated content", result.getNoteContent());
|
||||
assertEquals("#00FF00", result.getColor());
|
||||
assertEquals("Updated chapter", result.getChapterTitle());
|
||||
|
||||
assertEquals("Updated content", existingEntity.getNoteContent());
|
||||
assertEquals("#00FF00", existingEntity.getColor());
|
||||
assertEquals("Updated chapter", existingEntity.getChapterTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNote_updatesOnlyNonNullFields() {
|
||||
UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder()
|
||||
.noteContent("Updated content")
|
||||
.build();
|
||||
|
||||
BookNoteV2Entity existingEntity = BookNoteV2Entity.builder()
|
||||
.id(noteId)
|
||||
.cfi(cfi)
|
||||
.noteContent(noteContent)
|
||||
.color(defaultColor)
|
||||
.chapterTitle(chapterTitle)
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookNoteV2Repository.save(existingEntity)).thenReturn(existingEntity);
|
||||
when(mapper.toDto(existingEntity)).thenReturn(BookNoteV2.builder().id(noteId).build());
|
||||
|
||||
service.updateNote(noteId, request);
|
||||
|
||||
assertEquals("Updated content", existingEntity.getNoteContent());
|
||||
assertEquals(defaultColor, existingEntity.getColor());
|
||||
assertEquals(chapterTitle, existingEntity.getChapterTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNote_throwsEntityNotFoundException_whenNoteNotFound() {
|
||||
UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder()
|
||||
.noteContent("Updated content")
|
||||
.build();
|
||||
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
||||
|
||||
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.updateNote(noteId, request));
|
||||
|
||||
assertTrue(ex.getMessage().contains(String.valueOf(noteId)));
|
||||
verify(bookNoteV2Repository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNote_deletesExistingNote() {
|
||||
BookNoteV2Entity entity = BookNoteV2Entity.builder().id(noteId).build();
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(entity));
|
||||
|
||||
service.deleteNote(noteId);
|
||||
|
||||
verify(bookNoteV2Repository).delete(entity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNote_throwsEntityNotFoundException_whenNotFound() {
|
||||
when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
||||
|
||||
EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.deleteNote(noteId));
|
||||
|
||||
assertTrue(ex.getMessage().contains(String.valueOf(noteId)));
|
||||
verify(bookNoteV2Repository, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotesForBook_returnsMultipleNotes_orderedByCreatedAtDesc() {
|
||||
BookNoteV2Entity entity1 = BookNoteV2Entity.builder().id(1L).cfi("cfi1").build();
|
||||
BookNoteV2Entity entity2 = BookNoteV2Entity.builder().id(2L).cfi("cfi2").build();
|
||||
BookNoteV2Entity entity3 = BookNoteV2Entity.builder().id(3L).cfi("cfi3").build();
|
||||
|
||||
BookNoteV2 dto1 = BookNoteV2.builder().id(1L).cfi("cfi1").build();
|
||||
BookNoteV2 dto2 = BookNoteV2.builder().id(2L).cfi("cfi2").build();
|
||||
BookNoteV2 dto3 = BookNoteV2.builder().id(3L).cfi("cfi3").build();
|
||||
|
||||
when(bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId))
|
||||
.thenReturn(List.of(entity3, entity2, entity1));
|
||||
when(mapper.toDto(entity3)).thenReturn(dto3);
|
||||
when(mapper.toDto(entity2)).thenReturn(dto2);
|
||||
when(mapper.toDto(entity1)).thenReturn(dto1);
|
||||
|
||||
List<BookNoteV2> result = service.getNotesForBook(bookId);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertEquals(3L, result.get(0).getId());
|
||||
assertEquals(2L, result.get(1).getId());
|
||||
assertEquals(1L, result.get(2).getId());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user