70 lines
3.1 KiB
Java
70 lines
3.1 KiB
Java
/*
|
|
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
|
* Your use of it is subject to your agreement with Google.
|
|
*/
|
|
|
|
package com.example.service.quickreplies;
|
|
|
|
import com.example.dto.quickreplies.QuestionDTO;
|
|
import com.example.dto.quickreplies.QuickReplyDTO;
|
|
import com.google.cloud.firestore.DocumentSnapshot;
|
|
import com.google.cloud.firestore.Firestore;
|
|
import java.util.Map;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.stereotype.Service;
|
|
import reactor.core.publisher.Mono;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
|
|
@Service
|
|
public class QuickReplyContentService {
|
|
private static final Logger logger = LoggerFactory.getLogger(QuickReplyContentService.class);
|
|
private final Firestore firestore;
|
|
public QuickReplyContentService(Firestore firestore) {
|
|
this.firestore = firestore;
|
|
}
|
|
public Mono<QuickReplyDTO> getQuickReplies(String collectionId) {
|
|
logger.info("Fetching quick replies from Firestore for document: {}", collectionId);
|
|
if (collectionId == null || collectionId.isBlank()) {
|
|
logger.warn("collectionId is null or empty. Returning empty quick replies.");
|
|
return Mono.just(new QuickReplyDTO("empty", null, null, null, Collections.emptyList()));
|
|
}
|
|
return Mono.fromCallable(() -> {
|
|
try {
|
|
return firestore.collection("artifacts")
|
|
.document("default-app-id")
|
|
.collection("quick-replies")
|
|
.document(collectionId)
|
|
.get()
|
|
.get();
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
})
|
|
.filter(DocumentSnapshot::exists)
|
|
.map(document -> {
|
|
String header = document.getString("header");
|
|
String body = document.getString("body");
|
|
String button = document.getString("button");
|
|
String headerSection = document.getString("header_section");
|
|
List<Map<String, Object>> preguntasData = (List<Map<String, Object>>) document.get("preguntas");
|
|
List<QuestionDTO> preguntas = preguntasData.stream()
|
|
.map(p -> new QuestionDTO((String) p.get("titulo"), (String) p.get("descripcion"), (String) p.get("respuesta")))
|
|
.toList();
|
|
return new QuickReplyDTO(header, body, button, headerSection, preguntas);
|
|
})
|
|
.doOnSuccess(quickReplyDTO -> {
|
|
if (quickReplyDTO != null) {
|
|
logger.info("Successfully fetched {} quick replies for document: {}", quickReplyDTO.preguntas().size(), collectionId);
|
|
} else {
|
|
logger.info("No quick reply document found for id: {}", collectionId);
|
|
}
|
|
})
|
|
.doOnError(error -> logger.error("Error fetching quick replies from Firestore for document: {}", collectionId, error))
|
|
.switchIfEmpty(Mono.defer(() -> {
|
|
logger.info("No quick reply document found for id: {}", collectionId);
|
|
return Mono.empty();
|
|
}));
|
|
}
|
|
} |