refactor: Complete BookListingServiceImpl and BookEditingServiceImpl logic

This commit is contained in:
2025-02-08 15:49:28 +03:00
parent 41a59cb00e
commit 834687bd49
2 changed files with 130 additions and 14 deletions
@@ -14,38 +14,83 @@ public class BookEditingServiceImpl implements BookEditingService {
private final BookCacheService bookCacheService;
private final TelegramClientService telegramClientService;
@Override
public void processBookSelection(BotUser user, Long bookId) {
// Logic for processing book selection
try {
Optional<Book> book = bookRepository.findByIdAndBotUser(bookId, user);
var bookCache = bookCacheService.getBookEditCache(user.getId());
if (bookCache != null) {
bookCache.setBookId(bookId);
} else {
bookCache = BookEditStateCache.builder().bookEditState(BookEditStateCache.BookEditState.NONE).bookId(bookId).build();
}
bookCacheService.updateBookEditCache(user.getId(), bookCache);
if (book.isPresent()) {
log.info("Found book with id {}", bookId);
telegramClientService.sendMessage(user, "Выберите поле для редактирования:", getEditOptions(user));
} else {
telegramClientService.sendMessage(user, "Книга не найдена");
}
} catch (NumberFormatException e) {
telegramClientService.sendMessage(user, "Некорректный ID книги");
}
}
@Override
public void handleEditTitle(BotUser user) {
// Logic for handling edit title
var bookCache = bookCacheService.getBookEditCache(user.getId());
bookCache.setBookEditState(BookEditStateCache.BookEditState.EDITING_TITLE);
bookCacheService.updateBookEditCache(user.getId(), bookCache);
telegramClientService.sendMessage(user, "Введите новое название:");
}
@Override
public void handleEditAuthor(BotUser user) {
// Logic for handling edit author
var bookCache = bookCacheService.getBookEditCache(user.getId());
bookCache.setBookEditState(BookEditStateCache.BookEditState.EDITING_AUTHOR);
bookCacheService.updateBookEditCache(user.getId(), bookCache);
telegramClientService.sendMessage(user, "Введите нового автора:");
}
@Override
public void handleEditRating(BotUser user) {
// Logic for handling edit rating
var bookCache = bookCacheService.getBookEditCache(user.getId());
bookCache.setBookEditState(BookEditStateCache.BookEditState.EDITING_RATING);
bookCacheService.updateBookEditCache(user.getId(), bookCache);
telegramClientService.sendMessage(user, "Введите рейтинг:");
}
@Override
public void updateBookTitle(BotUser user, String newTitle) {
// Logic for updating book title
var bookEditState = bookCacheService.getBookEditCache(user.getId());
Book book = bookRepository.findById(bookEditState.getBookId()).orElseThrow();
book.setTitle(newTitle);
bookRepository.save(book);
bookEditState.setBookEditState(BookEditStateCache.BookEditState.NONE);
bookCacheService.updateBookEditCache(user.getId(), bookEditState);
telegramClientService.sendMessage(user, "Название успешно обновлено!");
handleRestartMessage(user);
}
@Override
public void updateBookAuthor(BotUser user, String newAuthor) {
// Logic for updating book author
var bookEditState = bookCacheService.getBookEditCache(user.getId());
Book book = bookRepository.findById(bookEditState.getBookId()).orElseThrow();
book.setAuthor(newAuthor);
bookRepository.save(book);
bookEditState.setBookEditState(BookEditStateCache.BookEditState.NONE);
bookCacheService.updateBookEditCache(user.getId(), bookEditState);
telegramClientService.sendMessage(user, "Автор успешно обновлен");
handleRestartMessage(user);
}
@Override
public void updateBookRating(BotUser user, String newRating) {
// Logic for updating book rating
var bookEditState = bookCacheService.getBookEditCache(user.getId());
Book book = bookRepository.findById(bookEditState.getBookId()).orElseThrow();
book.setRating(Integer.parseInt(newRating));
bookRepository.save(book);
bookEditState.setBookEditState(BookEditStateCache.BookEditState.NONE);
bookCacheService.updateBookEditCache(user.getId(), bookEditState);
telegramClientService.sendMessage(user, "Рейтинг успешно обновлен");
handleRestartMessage(user);
}
}
}
@@ -14,7 +14,78 @@ public class BookListingServiceImpl implements BookListingService {
private final BookCacheService bookCacheService;
private final TelegramClientService telegramClientService;
private static final String FULL_STAR = ""; // Эмодзи U+2B50
private static final String EMPTY_STAR = ""; // Символ U+2606
@Override
public void showPaginatedBookList(BotUser botUser, int page, Integer messageId, Boolean forEdit) {
try {
Pageable pageable = PageRequest.of(page, 5);
Page<Book> books = bookRepository.findByBotUserOrderByIdAsc(botUser, pageable);
StringBuilder sb = new StringBuilder();
sb.append("📚 *Ваша книжная полка*\n\n");
int counter = 1;
for (Book book : books) {
sb.append(formatBookEntry(book, (counter - 1) % 5, forEdit));
counter++;
}
var bookListCache = bookCacheService.getBookListState(botUser.getId());
if (bookListCache != null) {
bookListCache.setCurrentPage(page);
bookCacheService.updateBookListState(botUser.getId(), bookListCache);
telegramClientService.editMessageWithMarkdown(botUser, messageId, sb.toString(), getBookListKeyboard(page, books.hasNext(), books, forEdit));
} else {
var message = telegramClientService.sendMessageWithMarkdown(botUser, sb.toString(), getBookListKeyboard(page, books.hasNext(), books, forEdit));
bookCacheService.updateBookListState(botUser.getId(), BookListCache.builder().currentPage(page).listMessageId(message.getMessageId()).build());
}
if (forEdit) {
bookCacheService.updateBookEditCache(botUser.getId(), BookEditStateCache.builder().bookEditState(BookEditStateCache.BookEditState.CHOOSING_FIELD).build());
}
} catch (Exception e) {
log.error("Error loading book list", e);
telegramClientService.sendMessage(botUser, "❌ Ошибка при загрузке списка книг");
}
}
private String formatBookEntry(Book book, int index, boolean forEdit) {
if (forEdit) {
return String.format("%s %s *%s*\n" + "✍️ _%s_\n" + "🏆 %s\n" +
"▔▔▔▔▔▔▔▔▔▔▔▔▔▔\n", String.valueOf((char) ('0' + index + 1)) + "\uFE0F\u20E3", getBookIcon(index), escapeMarkdown(book.getTitle()), escapeMarkdown(book.getAuthor()), escapeMarkdown(formatRating(book.getRating())));
}
return String.format("%s *%s*\n" + "✍️ _%s_\n" + "🏆 %s\n" +
"▔▔▔▔▔▔▔▔▔▔▔▔▔▔\n", getBookIcon(index), escapeMarkdown(book.getTitle()), escapeMarkdown(book.getAuthor()), escapeMarkdown(formatRating(book.getRating())));
}
private String getBookIcon(int index) {
String[] icons = {"📘", "📙", "📕", "📗", "📓"};
return icons[index % icons.length];
}
private String escapeMarkdown(String text) {
return text.replaceAll("([_*\\[\\]()~`>#+=|{}.!-])", "\\\\$1");
}
public static String formatRating(int rating) {
int validatedRating = Math.min(10, Math.max(0, rating));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < validatedRating; i++) {
sb.append(FULL_STAR);
}
for (int i = validatedRating; i < 10; i++) {
sb.append(EMPTY_STAR);
}
sb.append(" (").append(validatedRating).append("/10)");
return sb.toString();
}
public void showPaginatedBookList(BotUser botUser, int page, Integer messageId, Boolean forEdit) {
// Logic for showing paginated book list
}