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;
|
||||
Reference in New Issue
Block a user