UPDATE 04-Sept

This commit is contained in:
PAVEL PALMA
2025-09-05 11:32:38 -06:00
parent 499bc002ae
commit 37c1b31b7c
9 changed files with 323 additions and 258 deletions

View File

@@ -62,4 +62,15 @@ public record ConversationEntryDTO(
null
);
}
public static ConversationEntryDTO forSystem(String text, Map<String, Object> parameters) {
return new ConversationEntryDTO(
ConversationEntryEntity.SISTEMA,
ConversationEntryType.CONVERSACION,
Instant.now(),
text,
parameters,
null
);
}
}

View File

@@ -57,12 +57,22 @@ public class ConversationContextMapper {
case AGENTE:
prefix = "Agent: ";
break;
case SISTEMA:
prefix = "System: ";
break;
case USUARIO:
default:
prefix = "User: ";
break;
}
}
return prefix + entry.text();
String text = prefix + entry.text();
if (entry.parameters() != null && !entry.parameters().isEmpty()) {
text += " " + entry.parameters().toString();
}
return text;
}
}

View File

@@ -5,11 +5,12 @@
package com.example.mapper.notification;
import com.example.dto.dialogflow.notification.EventInputDTO;
import com.example.dto.dialogflow.notification.ExternalNotRequestDTO;
import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
import com.example.dto.dialogflow.conversation.QueryInputDTO;
import com.example.dto.dialogflow.conversation.QueryParamsDTO;
import com.example.dto.dialogflow.conversation.TextInputDTO;
import org.springframework.stereotype.Component;
@@ -26,9 +27,12 @@ import java.util.Objects;
*/
@Component
public class ExternalNotRequestMapper {
private static final String EVENT_NAME = "notificacion";
private static final String LANGUAGE_CODE = "es";
private static final String TELEPHONE_PARAM_NAME = "telefono";
private static final String NOTIFICATION_TEXT_PARAM = "notification_text";
private static final String PREFIX_PO_PARAM = "notification_po_";
public DetectIntentRequestDTO map(ExternalNotRequestDTO request) {
Objects.requireNonNull(request, "NotificationRequestDTO cannot be null for mapping.");
@@ -37,16 +41,22 @@ public class ExternalNotRequestMapper {
throw new IllegalArgumentException("List of 'telefonos' (phone numbers) is required and cannot be empty in NotificationRequestDTO.");
}
String phoneNumber = request.phoneNumber();
EventInputDTO eventInput = new EventInputDTO(EVENT_NAME);
QueryInputDTO queryInput = new QueryInputDTO(null,eventInput, LANGUAGE_CODE);
Map<String, Object> parameters = new HashMap<>();
parameters.put(TELEPHONE_PARAM_NAME, phoneNumber);
parameters.put(NOTIFICATION_TEXT_PARAM, request.text());
if (request.text() != null && !request.text().trim().isEmpty()) {
parameters.put("notification_text", request.text());
if (request.hiddenParameters() != null && !request.hiddenParameters().isEmpty()) {
request.hiddenParameters().forEach((key, value) -> {
parameters.put(PREFIX_PO_PARAM + key, value);
});
}
TextInputDTO textInput = new TextInputDTO(request.text());
QueryInputDTO queryInput = new QueryInputDTO(textInput, null, LANGUAGE_CODE);
QueryParamsDTO queryParams = new QueryParamsDTO(parameters);
return new DetectIntentRequestDTO(queryInput, queryParams);

View File

@@ -7,8 +7,6 @@ import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
import com.example.dto.dialogflow.conversation.ConversationContext;
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
import com.example.dto.dialogflow.conversation.ConversationEntryEntity;
import com.example.dto.dialogflow.conversation.ConversationEntryType;
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
import com.example.dto.dialogflow.conversation.ExternalConvRequestDTO;
import com.example.dto.dialogflow.notification.NotificationDTO;
@@ -31,6 +29,7 @@ import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@Service
public class ConversationManagerService {
private static final Logger logger = LoggerFactory.getLogger(ConversationManagerService.class);
@@ -244,6 +243,7 @@ public class ConversationManagerService {
.doOnError(e -> logger.error("Error during primary Redis write for session {}. Type: {}: {}", sessionId,
entry.type().name(), e.getMessage(), e));
}
private ConversationContext resolveAndValidateRequest(DetectIntentRequestDTO request) {
Map<String, Object> params = Optional.ofNullable(request.queryParams())
.map(queryParamsDTO -> queryParamsDTO.parameters())

View File

@@ -57,20 +57,18 @@ public class FirestoreNotificationService {
// Use the phone number as the document ID for the session.
String notificationSessionId = phoneNumber;
// Synchronize on the notification session ID to prevent race conditions when creating a new session.
// Synchronize on the notification session ID to prevent race conditions when
// creating a new session.
synchronized (notificationSessionId.intern()) {
DocumentReference notificationDocRef =
getNotificationDocumentReference(notificationSessionId);
Map<String, Object> entryMap =
firestoreNotificationMapper.mapNotificationDTOToMap(newEntry);
DocumentReference notificationDocRef = getNotificationDocumentReference(notificationSessionId);
Map<String, Object> entryMap = firestoreNotificationMapper.mapNotificationDTOToMap(newEntry);
try {
// Check if the session document exists.
boolean docExists = firestoreBaseRepository.documentExists(notificationDocRef);
if (docExists) {
// If the document exists, append the new entry to the 'notificaciones' array.
Map<String, Object> updates =
Map.of(
Map<String, Object> updates = Map.of(
FIELD_MESSAGES, FieldValue.arrayUnion(entryMap),
FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
@@ -79,8 +77,7 @@ public class FirestoreNotificationService {
notificationSessionId);
} else {
// If the document does not exist, create a new session document.
Map<String, Object> newSessionData =
Map.of(
Map<String, Object> newSessionData = Map.of(
FIELD_NOTIFICATION_ID,
notificationSessionId,
FIELD_PHONE_NUMBER,
@@ -136,7 +133,8 @@ public class FirestoreNotificationService {
try {
Map<String, Object> sessionData = firestoreBaseRepository.getDocument(notificationDocRef, Map.class);
if (sessionData != null) {
List<Map<String, Object>> notifications = (List<Map<String, Object>>) sessionData.get(FIELD_MESSAGES);
List<Map<String, Object>> notifications = (List<Map<String, Object>>) sessionData
.get(FIELD_MESSAGES);
if (notifications != null) {
List<Map<String, Object>> updatedNotifications = new ArrayList<>();
for (Map<String, Object> notification : notifications) {
@@ -148,18 +146,23 @@ public class FirestoreNotificationService {
updates.put(FIELD_MESSAGES, updatedNotifications);
updates.put(FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
logger.info("Successfully updated notification status to '{}' for session {} in Firestore.", status, sessionId);
logger.info("Successfully updated notification status to '{}' for session {} in Firestore.",
status, sessionId);
}
} else {
logger.warn("Notification session {} not found in Firestore. Cannot update status.", sessionId);
}
} catch (ExecutionException e) {
logger.error("Error updating notification status in Firestore for session {}: {}", sessionId, e.getMessage(), e);
throw new FirestorePersistenceException("Failed to update notification status in Firestore for session " + sessionId, e);
logger.error("Error updating notification status in Firestore for session {}: {}", sessionId,
e.getMessage(), e);
throw new FirestorePersistenceException(
"Failed to update notification status in Firestore for session " + sessionId, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Thread interrupted while updating notification status in Firestore for session {}: {}", sessionId, e.getMessage(), e);
throw new FirestorePersistenceException("Updating notification status was interrupted for session " + sessionId, e);
logger.error("Thread interrupted while updating notification status in Firestore for session {}: {}",
sessionId, e.getMessage(), e);
throw new FirestorePersistenceException(
"Updating notification status was interrupted for session " + sessionId, e);
}
})
.subscribeOn(Schedulers.boundedElastic())

View File

@@ -10,10 +10,10 @@ import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
import com.example.dto.dialogflow.conversation.QueryInputDTO;
import com.example.dto.dialogflow.conversation.QueryParamsDTO;
import com.example.dto.dialogflow.notification.NotificationDTO;
import com.example.mapper.notification.ExternalNotRequestMapper;
import com.example.service.base.DialogflowClientService;
import com.example.service.conversation.DataLossPrevention;
import com.example.util.SessionIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -22,23 +22,25 @@ import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.example.dto.dialogflow.conversation.TextInputDTO;
@Service
public class NotificationManagerService {
private static final Logger logger = LoggerFactory.getLogger(NotificationManagerService.class);
private static final String NOTIFICATION_TEXT_PARAM = "notificationText";
private static final String eventName = "notificacion";
private static final String PREFIX_PO_PARAM = "notification_po_";
private final DialogflowClientService dialogflowClientService;
private final FirestoreNotificationService firestoreNotificationService;
private final MemoryStoreNotificationService memoryStoreNotificationService;
private final FirestoreNotificationConvService firestoreConversationService;
private final ExternalNotRequestMapper externalNotRequestMapper;
private final DataLossPrevention dataLossPrevention;
private final String dlpTemplateCompleteFlow;
@Value("${dialogflow.default-language-code:es}")
private String defaultLanguageCode;
@@ -47,11 +49,17 @@ public NotificationManagerService(
DialogflowClientService dialogflowClientService,
FirestoreNotificationService firestoreNotificationService,
MemoryStoreNotificationService memoryStoreNotificationService,
FirestoreNotificationConvService firestoreConversationService) {
FirestoreNotificationConvService firestoreConversationService,
ExternalNotRequestMapper externalNotRequestMapper,
DataLossPrevention dataLossPrevention,
@Value("${google.cloud.dlp.dlpTemplateCompleteFlow}") String dlpTemplateCompleteFlow) {
this.dialogflowClientService = dialogflowClientService;
this.firestoreNotificationService = firestoreNotificationService;
this.memoryStoreNotificationService = memoryStoreNotificationService;
this.firestoreConversationService = firestoreConversationService;
this.externalNotRequestMapper = externalNotRequestMapper;
this.dataLossPrevention = dataLossPrevention;
this.dlpTemplateCompleteFlow = dlpTemplateCompleteFlow;
}
public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO externalRequest) {
@@ -63,17 +71,30 @@ public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO e
return Mono.error(new IllegalArgumentException("Phone number is required."));
}
return dataLossPrevention.getObfuscatedString(externalRequest.text(), dlpTemplateCompleteFlow)
.flatMap(obfuscatedMessage -> {
ExternalNotRequestDTO obfuscatedRequest = new ExternalNotRequestDTO(
obfuscatedMessage,
externalRequest.phoneNumber(),
externalRequest.hiddenParameters()
);
// 1. Persist the incoming notification entry
String newNotificationId = SessionIdGenerator.generateStandardSessionId();
Map<String, Object> parameters = new HashMap<>();
if (obfuscatedRequest.hiddenParameters() != null) {
obfuscatedRequest.hiddenParameters().forEach((key, value) -> parameters.put(PREFIX_PO_PARAM + key, value));
}
NotificationDTO newNotificationEntry = new NotificationDTO(newNotificationId, telefono, Instant.now(),
externalRequest.text(), eventName, defaultLanguageCode, Collections.emptyMap(), "active");
obfuscatedRequest.text(), eventName, defaultLanguageCode, parameters, "active");
Mono<Void> persistenceMono = memoryStoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
.doOnSuccess(v -> {
logger.info("Notification for phone {} cached. Kicking off async Firestore write-back.", telefono);
firestoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
.subscribe(
ignored -> logger.debug(
"Background: Notification entry persistence initiated for phone {} in Firestore.",telefono),
"Background: Notification entry persistence initiated for phone {} in Firestore.",
telefono),
e -> logger.error(
"Background: Error during notification entry persistence for phone {} in Firestore: {}",
telefono, e.getMessage(), e));
@@ -84,15 +105,28 @@ public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO e
.doOnNext(session -> logger.info("Found existing conversation session {} for phone number {}",
session.sessionId(), telefono))
.flatMap(session -> {
ConversationEntryDTO systemEntry = ConversationEntryDTO.forSystem(externalRequest.text());
Map<String, Object> prefixedParameters = new HashMap<>();
if (obfuscatedRequest.hiddenParameters() != null) {
obfuscatedRequest.hiddenParameters()
.forEach((key, value) -> prefixedParameters.put(PREFIX_PO_PARAM + key, value));
}
ConversationEntryDTO systemEntry = ConversationEntryDTO.forSystem(obfuscatedRequest.text(),
prefixedParameters);
return persistConversationTurn(session.userId(), session.sessionId(), systemEntry, telefono)
.thenReturn(session);
})
.switchIfEmpty(Mono.defer(() -> {
String newSessionId = SessionIdGenerator.generateStandardSessionId();
logger.info("No existing conversation session found for phone number {}. Creating new session: {}",telefono, newSessionId);
logger.info("No existing conversation session found for phone number {}. Creating new session: {}",
telefono, newSessionId);
String userId = "user_by_phone_" + telefono;
ConversationEntryDTO systemEntry = ConversationEntryDTO.forSystem(externalRequest.text());
Map<String, Object> prefixedParameters = new HashMap<>();
if (obfuscatedRequest.hiddenParameters() != null) {
obfuscatedRequest.hiddenParameters()
.forEach((key, value) -> prefixedParameters.put(PREFIX_PO_PARAM + key, value));
}
ConversationEntryDTO systemEntry = ConversationEntryDTO.forSystem(obfuscatedRequest.text(),
prefixedParameters);
return persistConversationTurn(userId, newSessionId, systemEntry, telefono)
.then(Mono.just(ConversationSessionDTO.create(newSessionId, userId, telefono)));
}));
@@ -104,27 +138,14 @@ public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO e
final String sessionId = session.sessionId();
logger.info("Sending notification text to Dialogflow using conversation session: {}", sessionId);
Map<String, Object> parameters = new HashMap<>();
parameters.put("telefono", telefono);
parameters.put(NOTIFICATION_TEXT_PARAM, newNotificationEntry.texto());
if (externalRequest.hiddenParameters() != null && !externalRequest.hiddenParameters().isEmpty()) {
parameters.putAll(externalRequest.hiddenParameters());
}
// Use a TextInputDTO to correctly build the QueryInputDTO
TextInputDTO textInput = new TextInputDTO(newNotificationEntry.texto());
QueryInputDTO queryInput = new QueryInputDTO(textInput, null, defaultLanguageCode);
DetectIntentRequestDTO detectIntentRequest = new DetectIntentRequestDTO(
queryInput,
new QueryParamsDTO(parameters));
DetectIntentRequestDTO detectIntentRequest = externalNotRequestMapper.map(obfuscatedRequest);
return dialogflowClientService.detectIntent(sessionId, detectIntentRequest);
})
.doOnSuccess(response -> logger
.info("Finished processing notification. Dialogflow response received for phone {}.", telefono))
.doOnError(e -> logger.error("Overall error in NotificationManagerService: {}", e.getMessage(), e));
});
}
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry,

View File

@@ -9,7 +9,7 @@
# Best Practices:
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
# to manage environment-specific settings.
# - Do not store in PROD sensitive information (e.g., API keys, passwords) directly here.
# - Do not store in PROD sensitive information directly here.
# Use environment variables or a configuration server for production environments.
# - This template can be adapted for logging configuration, database connections,
# and other external service settings.

View File

@@ -9,7 +9,7 @@
# Best Practices:
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
# to manage environment-specific settings.
# - Do not store in PROD sensitive information (e.g., API keys, passwords) directly here.
# - Do not store in PROD sensitive information directly here.
# Use environment variables or a configuration server for production environments.
# - This template can be adapted for logging configuration, database connections,
# and other external service settings.
@@ -67,3 +67,8 @@ google.cloud.dlp.dlpTemplatePersistFlow=${DLP_TEMPLATE_PERSIST_FLOW}
# Quick-replies Preset-data
# =========================================================
firestore.data.importer.enabled=true
# =========================================================
# LOGGING Configuration
# =========================================================
logging.level.root=${LOGGING_LEVEL_ROOT:INFO}
logging.level.com.example=${LOGGING_LEVEL_COM_EXAMPLE:INFO}

View File

@@ -9,7 +9,7 @@
# Best Practices:
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
# to manage environment-specific settings.
# - Do not store in PROD sensitive information (e.g., API keys, passwords) directly here.
# - Do not store in PROD sensitive information directly here.
# Use environment variables or a configuration server for production environments.
# - This template can be adapted for logging configuration, database connections,
# and other external service settings.
@@ -67,3 +67,8 @@ google.cloud.dlp.dlpTemplatePersistFlow=${DLP_TEMPLATE_PERSIST_FLOW}
# Quick-replies Preset-data
# =========================================================
firestore.data.importer.enabled=true
# =========================================================
# LOGGING Configuration
# =========================================================
logging.level.root=${LOGGING_LEVEL_ROOT:INFO}
logging.level.com.example=${LOGGING_LEVEL_COM_EXAMPLE:DEBUG}