UPDATE int-layer 25-Ago
This commit is contained in:
@@ -11,42 +11,50 @@ import com.example.dto.dialogflow.conversation.ConversationEntryEntity;
|
||||
import com.example.dto.dialogflow.conversation.ConversationEntryType;
|
||||
import com.example.dto.dialogflow.conversation.ExternalConvRequestDTO;
|
||||
import com.example.dto.quickreplies.QuickReplyScreenRequestDTO;
|
||||
import com.example.service.conversation.DataLossPrevention;
|
||||
import com.example.dto.quickreplies.QuestionDTO;
|
||||
import com.example.dto.quickreplies.QuickReplyDTO;
|
||||
import com.example.service.conversation.FirestoreConversationService;
|
||||
import com.example.service.conversation.MemoryStoreConversationService;
|
||||
import com.example.util.SessionIdGenerator;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class QuickRepliesManagerService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(QuickRepliesManagerService.class);
|
||||
|
||||
private final MemoryStoreConversationService memoryStoreConversationService;
|
||||
private final FirestoreConversationService firestoreConversationService;
|
||||
private final QuickReplyContentService quickReplyContentService;
|
||||
private final DataLossPrevention dataLossPrevention;
|
||||
private final String dlpTemplatePersistFlow;
|
||||
|
||||
public QuickRepliesManagerService(
|
||||
MemoryStoreConversationService memoryStoreConversationService,
|
||||
FirestoreConversationService firestoreConversationService,
|
||||
QuickReplyContentService quickReplyContentService) {
|
||||
QuickReplyContentService quickReplyContentService,
|
||||
DataLossPrevention dataLossPrevention,
|
||||
@Value("${google.cloud.dlp.dlpTemplatePersistFlow}") String dlpTemplatePersistFlow) {
|
||||
this.memoryStoreConversationService = memoryStoreConversationService;
|
||||
this.firestoreConversationService = firestoreConversationService;
|
||||
this.quickReplyContentService = quickReplyContentService;
|
||||
this.dataLossPrevention = dataLossPrevention;
|
||||
this.dlpTemplatePersistFlow = dlpTemplatePersistFlow;
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> startQuickReplySession(QuickReplyScreenRequestDTO externalRequest) {
|
||||
String userPhoneNumber = externalRequest.user().telefono();
|
||||
if (userPhoneNumber == null || userPhoneNumber.isBlank()) {
|
||||
logger.warn("No phone number provided in request. Cannot manage conversation session without it.");
|
||||
return Mono.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
return Mono
|
||||
.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
}
|
||||
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.flatMap(session -> Mono.just(session.sessionId()))
|
||||
.switchIfEmpty(Mono.fromCallable(SessionIdGenerator::generateStandardSessionId))
|
||||
@@ -58,10 +66,9 @@ public class QuickRepliesManagerService {
|
||||
Instant.now(),
|
||||
"Pantalla :" + externalRequest.pantallaContexto() + " Agregada a la conversacion :",
|
||||
null,
|
||||
null
|
||||
);
|
||||
|
||||
return persistConversationTurn(userId, sessionId, systemEntry, userPhoneNumber, externalRequest.pantallaContexto())
|
||||
null);
|
||||
return persistConversationTurn(userId, sessionId, systemEntry, userPhoneNumber,
|
||||
externalRequest.pantallaContexto())
|
||||
.then(quickReplyContentService.getQuickReplies(externalRequest.pantallaContexto()))
|
||||
.map(quickReplyDTO -> new DetectIntentResponseDTO(sessionId, null, quickReplyDTO));
|
||||
});
|
||||
@@ -71,34 +78,93 @@ public class QuickRepliesManagerService {
|
||||
String userPhoneNumber = externalRequest.user().telefono();
|
||||
if (userPhoneNumber == null || userPhoneNumber.isBlank()) {
|
||||
logger.warn("No phone number provided in request. Cannot manage conversation session without it.");
|
||||
return Mono.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
return Mono
|
||||
.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
}
|
||||
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.switchIfEmpty(Mono.error(new IllegalStateException("No quick reply session found for phone number: " + userPhoneNumber)))
|
||||
.switchIfEmpty(Mono.error(
|
||||
new IllegalStateException("No quick reply session found for phone number: " + userPhoneNumber)))
|
||||
.flatMap(session -> {
|
||||
String userId = session.userId();
|
||||
String sessionId = session.sessionId();
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(externalRequest.message());
|
||||
return dataLossPrevention.getObfuscatedString(externalRequest.message(), dlpTemplatePersistFlow)
|
||||
.flatMap(obfuscatedMessage -> {
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(obfuscatedMessage);
|
||||
|
||||
return persistConversationTurn(userId, sessionId, userEntry, userPhoneNumber, session.pantallaContexto())
|
||||
.then(quickReplyContentService.getQuickReplies(session.pantallaContexto()))
|
||||
.flatMap(quickReplyDTO -> {
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO.forAgentWithMessage(quickReplyDTO.toString());
|
||||
return persistConversationTurn(userId, sessionId, agentEntry, userPhoneNumber, session.pantallaContexto())
|
||||
.thenReturn(new DetectIntentResponseDTO(sessionId, null, quickReplyDTO));
|
||||
});
|
||||
long userMessagesCount = session.entries().stream()
|
||||
.filter(e -> e.entity() == ConversationEntryEntity.USUARIO)
|
||||
.count();
|
||||
|
||||
if (userMessagesCount == 0) { // Is the first user message in the Quick-Replies flow
|
||||
// This is the second message of the flow. Return the full list.
|
||||
return persistConversationTurn(userId, sessionId, userEntry, userPhoneNumber,
|
||||
session.pantallaContexto())
|
||||
.then(quickReplyContentService.getQuickReplies(session.pantallaContexto()))
|
||||
.flatMap(quickReplyDTO -> {
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO
|
||||
.forAgentWithMessage(quickReplyDTO.toString());
|
||||
return persistConversationTurn(userId, sessionId, agentEntry, userPhoneNumber,
|
||||
session.pantallaContexto())
|
||||
.thenReturn(new DetectIntentResponseDTO(sessionId, null, quickReplyDTO));
|
||||
});
|
||||
} else if (userMessagesCount == 1) { // Is the second user message in the QR flow
|
||||
// This is the third message of the flow. Filter and end.
|
||||
return persistConversationTurn(userId, sessionId, userEntry, userPhoneNumber,
|
||||
session.pantallaContexto())
|
||||
.then(quickReplyContentService.getQuickReplies(session.pantallaContexto()))
|
||||
.flatMap(quickReplyDTO -> {
|
||||
List<QuestionDTO> matchedPreguntas = quickReplyDTO.preguntas().stream()
|
||||
.filter(p -> p.titulo().equalsIgnoreCase(externalRequest.message().trim()))
|
||||
.toList();
|
||||
|
||||
QuickReplyDTO responseQuickReplyDTO;
|
||||
if (!matchedPreguntas.isEmpty()) {
|
||||
responseQuickReplyDTO = new QuickReplyDTO(quickReplyDTO.header(),
|
||||
matchedPreguntas);
|
||||
} else {
|
||||
responseQuickReplyDTO = new QuickReplyDTO(quickReplyDTO.header(),
|
||||
Collections.emptyList());
|
||||
}
|
||||
|
||||
// End the quick reply flow by clearing the pantallaContexto
|
||||
return memoryStoreConversationService
|
||||
.updateSession(session.withPantallaContexto(null))
|
||||
.then(persistConversationTurn(userId, sessionId,
|
||||
ConversationEntryDTO.forAgentWithMessage(
|
||||
responseQuickReplyDTO.toString()),
|
||||
userPhoneNumber, null))
|
||||
.thenReturn(new DetectIntentResponseDTO(sessionId, null,
|
||||
responseQuickReplyDTO));
|
||||
});
|
||||
} else {
|
||||
// Should not happen. End the flow.
|
||||
return memoryStoreConversationService.updateSession(session.withPantallaContexto(null))
|
||||
.then(Mono.just(new DetectIntentResponseDTO(session.sessionId(), null,
|
||||
new QuickReplyDTO("Flow Error", Collections.emptyList()))));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry, String userPhoneNumber, String pantallaContexto) {
|
||||
logger.debug("Starting Write-Back persistence for quick reply session {}. Type: {}. Writing to Redis first.", sessionId, entry.type().name());
|
||||
|
||||
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry,
|
||||
String userPhoneNumber, String pantallaContexto) {
|
||||
logger.debug("Starting Write-Back persistence for quick reply session {}. Type: {}. Writing to Redis first.",
|
||||
sessionId, entry.type().name());
|
||||
return memoryStoreConversationService.saveEntry(userId, sessionId, entry, userPhoneNumber, pantallaContexto)
|
||||
.doOnSuccess(v -> logger.info("Entry saved to Redis for quick reply session {}. Type: {}. Kicking off async Firestore write-back.", sessionId, entry.type().name()))
|
||||
.then(firestoreConversationService.saveEntry(userId, sessionId, entry, userPhoneNumber, pantallaContexto)
|
||||
.doOnSuccess(fsVoid -> logger.debug("Asynchronously (Write-Back): Entry successfully saved to Firestore for quick reply session {}. Type: {}.", sessionId, entry.type().name()))
|
||||
.doOnError(fsError -> logger.error("Asynchronously (Write-Back): Failed to save entry to Firestore for quick reply session {}. Type: {}: {}", sessionId, entry.type().name(), fsError.getMessage(), fsError)))
|
||||
.doOnError(e -> logger.error("Error during primary Redis write for quick reply session {}. Type: {}: {}", sessionId, entry.type().name(), e.getMessage(), e));
|
||||
.doOnSuccess(v -> logger.info(
|
||||
"Entry saved to Redis for quick reply session {}. Type: {}. Kicking off async Firestore write-back.",
|
||||
sessionId, entry.type().name()))
|
||||
.then(firestoreConversationService
|
||||
.saveEntry(userId, sessionId, entry, userPhoneNumber, pantallaContexto)
|
||||
.doOnSuccess(fsVoid -> logger.debug(
|
||||
"Asynchronously (Write-Back): Entry successfully saved to Firestore for quick reply session {}. Type: {}.",
|
||||
sessionId, entry.type().name()))
|
||||
.doOnError(fsError -> logger.error(
|
||||
"Asynchronously (Write-Back): Failed to save entry to Firestore for quick reply session {}. Type: {}: {}",
|
||||
sessionId, entry.type().name(), fsError.getMessage(), fsError)))
|
||||
.doOnError(
|
||||
e -> logger.error("Error during primary Redis write for quick reply session {}. Type: {}: {}",
|
||||
sessionId, entry.type().name(), e.getMessage(), e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user