UPDATE 04-Sept
This commit is contained in:
@@ -62,4 +62,15 @@ public record ConversationEntryDTO(
|
|||||||
null
|
null
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static ConversationEntryDTO forSystem(String text, Map<String, Object> parameters) {
|
||||||
|
return new ConversationEntryDTO(
|
||||||
|
ConversationEntryEntity.SISTEMA,
|
||||||
|
ConversationEntryType.CONVERSACION,
|
||||||
|
Instant.now(),
|
||||||
|
text,
|
||||||
|
parameters,
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -57,12 +57,22 @@ public class ConversationContextMapper {
|
|||||||
case AGENTE:
|
case AGENTE:
|
||||||
prefix = "Agent: ";
|
prefix = "Agent: ";
|
||||||
break;
|
break;
|
||||||
|
case SISTEMA:
|
||||||
|
prefix = "System: ";
|
||||||
|
break;
|
||||||
case USUARIO:
|
case USUARIO:
|
||||||
default:
|
default:
|
||||||
prefix = "User: ";
|
prefix = "User: ";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return prefix + entry.text();
|
|
||||||
|
String text = prefix + entry.text();
|
||||||
|
|
||||||
|
if (entry.parameters() != null && !entry.parameters().isEmpty()) {
|
||||||
|
text += " " + entry.parameters().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return text;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,11 +5,12 @@
|
|||||||
|
|
||||||
package com.example.mapper.notification;
|
package com.example.mapper.notification;
|
||||||
|
|
||||||
import com.example.dto.dialogflow.notification.EventInputDTO;
|
|
||||||
import com.example.dto.dialogflow.notification.ExternalNotRequestDTO;
|
import com.example.dto.dialogflow.notification.ExternalNotRequestDTO;
|
||||||
import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
||||||
import com.example.dto.dialogflow.conversation.QueryInputDTO;
|
import com.example.dto.dialogflow.conversation.QueryInputDTO;
|
||||||
import com.example.dto.dialogflow.conversation.QueryParamsDTO;
|
import com.example.dto.dialogflow.conversation.QueryParamsDTO;
|
||||||
|
import com.example.dto.dialogflow.conversation.TextInputDTO;
|
||||||
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@@ -26,9 +27,12 @@ import java.util.Objects;
|
|||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
public class ExternalNotRequestMapper {
|
public class ExternalNotRequestMapper {
|
||||||
private static final String EVENT_NAME = "notificacion";
|
|
||||||
private static final String LANGUAGE_CODE = "es";
|
private static final String LANGUAGE_CODE = "es";
|
||||||
private static final String TELEPHONE_PARAM_NAME = "telefono";
|
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) {
|
public DetectIntentRequestDTO map(ExternalNotRequestDTO request) {
|
||||||
Objects.requireNonNull(request, "NotificationRequestDTO cannot be null for mapping.");
|
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.");
|
throw new IllegalArgumentException("List of 'telefonos' (phone numbers) is required and cannot be empty in NotificationRequestDTO.");
|
||||||
}
|
}
|
||||||
String phoneNumber = request.phoneNumber();
|
String phoneNumber = request.phoneNumber();
|
||||||
EventInputDTO eventInput = new EventInputDTO(EVENT_NAME);
|
|
||||||
QueryInputDTO queryInput = new QueryInputDTO(null,eventInput, LANGUAGE_CODE);
|
|
||||||
|
|
||||||
Map<String, Object> parameters = new HashMap<>();
|
Map<String, Object> parameters = new HashMap<>();
|
||||||
parameters.put(TELEPHONE_PARAM_NAME, phoneNumber);
|
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);
|
QueryParamsDTO queryParams = new QueryParamsDTO(parameters);
|
||||||
|
|
||||||
return new DetectIntentRequestDTO(queryInput, queryParams);
|
return new DetectIntentRequestDTO(queryInput, queryParams);
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
|||||||
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
||||||
import com.example.dto.dialogflow.conversation.ConversationContext;
|
import com.example.dto.dialogflow.conversation.ConversationContext;
|
||||||
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
|
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.ConversationSessionDTO;
|
||||||
import com.example.dto.dialogflow.conversation.ExternalConvRequestDTO;
|
import com.example.dto.dialogflow.conversation.ExternalConvRequestDTO;
|
||||||
import com.example.dto.dialogflow.notification.NotificationDTO;
|
import com.example.dto.dialogflow.notification.NotificationDTO;
|
||||||
@@ -31,6 +29,7 @@ import java.util.Collections;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class ConversationManagerService {
|
public class ConversationManagerService {
|
||||||
private static final Logger logger = LoggerFactory.getLogger(ConversationManagerService.class);
|
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,
|
.doOnError(e -> logger.error("Error during primary Redis write for session {}. Type: {}: {}", sessionId,
|
||||||
entry.type().name(), e.getMessage(), e));
|
entry.type().name(), e.getMessage(), e));
|
||||||
}
|
}
|
||||||
|
|
||||||
private ConversationContext resolveAndValidateRequest(DetectIntentRequestDTO request) {
|
private ConversationContext resolveAndValidateRequest(DetectIntentRequestDTO request) {
|
||||||
Map<String, Object> params = Optional.ofNullable(request.queryParams())
|
Map<String, Object> params = Optional.ofNullable(request.queryParams())
|
||||||
.map(queryParamsDTO -> queryParamsDTO.parameters())
|
.map(queryParamsDTO -> queryParamsDTO.parameters())
|
||||||
|
|||||||
@@ -57,20 +57,18 @@ public class FirestoreNotificationService {
|
|||||||
// Use the phone number as the document ID for the session.
|
// Use the phone number as the document ID for the session.
|
||||||
String notificationSessionId = phoneNumber;
|
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()) {
|
synchronized (notificationSessionId.intern()) {
|
||||||
DocumentReference notificationDocRef =
|
DocumentReference notificationDocRef = getNotificationDocumentReference(notificationSessionId);
|
||||||
getNotificationDocumentReference(notificationSessionId);
|
Map<String, Object> entryMap = firestoreNotificationMapper.mapNotificationDTOToMap(newEntry);
|
||||||
Map<String, Object> entryMap =
|
|
||||||
firestoreNotificationMapper.mapNotificationDTOToMap(newEntry);
|
|
||||||
try {
|
try {
|
||||||
// Check if the session document exists.
|
// Check if the session document exists.
|
||||||
boolean docExists = firestoreBaseRepository.documentExists(notificationDocRef);
|
boolean docExists = firestoreBaseRepository.documentExists(notificationDocRef);
|
||||||
|
|
||||||
if (docExists) {
|
if (docExists) {
|
||||||
// If the document exists, append the new entry to the 'notificaciones' array.
|
// If the document exists, append the new entry to the 'notificaciones' array.
|
||||||
Map<String, Object> updates =
|
Map<String, Object> updates = Map.of(
|
||||||
Map.of(
|
|
||||||
FIELD_MESSAGES, FieldValue.arrayUnion(entryMap),
|
FIELD_MESSAGES, FieldValue.arrayUnion(entryMap),
|
||||||
FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
|
FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
|
||||||
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
|
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
|
||||||
@@ -79,8 +77,7 @@ public class FirestoreNotificationService {
|
|||||||
notificationSessionId);
|
notificationSessionId);
|
||||||
} else {
|
} else {
|
||||||
// If the document does not exist, create a new session document.
|
// If the document does not exist, create a new session document.
|
||||||
Map<String, Object> newSessionData =
|
Map<String, Object> newSessionData = Map.of(
|
||||||
Map.of(
|
|
||||||
FIELD_NOTIFICATION_ID,
|
FIELD_NOTIFICATION_ID,
|
||||||
notificationSessionId,
|
notificationSessionId,
|
||||||
FIELD_PHONE_NUMBER,
|
FIELD_PHONE_NUMBER,
|
||||||
@@ -136,7 +133,8 @@ public class FirestoreNotificationService {
|
|||||||
try {
|
try {
|
||||||
Map<String, Object> sessionData = firestoreBaseRepository.getDocument(notificationDocRef, Map.class);
|
Map<String, Object> sessionData = firestoreBaseRepository.getDocument(notificationDocRef, Map.class);
|
||||||
if (sessionData != null) {
|
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) {
|
if (notifications != null) {
|
||||||
List<Map<String, Object>> updatedNotifications = new ArrayList<>();
|
List<Map<String, Object>> updatedNotifications = new ArrayList<>();
|
||||||
for (Map<String, Object> notification : notifications) {
|
for (Map<String, Object> notification : notifications) {
|
||||||
@@ -148,18 +146,23 @@ public class FirestoreNotificationService {
|
|||||||
updates.put(FIELD_MESSAGES, updatedNotifications);
|
updates.put(FIELD_MESSAGES, updatedNotifications);
|
||||||
updates.put(FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
|
updates.put(FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
|
||||||
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
|
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 {
|
} else {
|
||||||
logger.warn("Notification session {} not found in Firestore. Cannot update status.", sessionId);
|
logger.warn("Notification session {} not found in Firestore. Cannot update status.", sessionId);
|
||||||
}
|
}
|
||||||
} catch (ExecutionException e) {
|
} catch (ExecutionException e) {
|
||||||
logger.error("Error updating notification status in Firestore for session {}: {}", sessionId, e.getMessage(), e);
|
logger.error("Error updating notification status in Firestore for session {}: {}", sessionId,
|
||||||
throw new FirestorePersistenceException("Failed to update notification status in Firestore for session " + sessionId, e);
|
e.getMessage(), e);
|
||||||
|
throw new FirestorePersistenceException(
|
||||||
|
"Failed to update notification status in Firestore for session " + sessionId, e);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
logger.error("Thread interrupted while updating notification status in Firestore for session {}: {}", sessionId, e.getMessage(), e);
|
logger.error("Thread interrupted while updating notification status in Firestore for session {}: {}",
|
||||||
throw new FirestorePersistenceException("Updating notification status was interrupted for session " + sessionId, e);
|
sessionId, e.getMessage(), e);
|
||||||
|
throw new FirestorePersistenceException(
|
||||||
|
"Updating notification status was interrupted for session " + sessionId, e);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.subscribeOn(Schedulers.boundedElastic())
|
.subscribeOn(Schedulers.boundedElastic())
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
|||||||
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
||||||
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
|
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
|
||||||
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
|
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.dto.dialogflow.notification.NotificationDTO;
|
||||||
|
import com.example.mapper.notification.ExternalNotRequestMapper;
|
||||||
import com.example.service.base.DialogflowClientService;
|
import com.example.service.base.DialogflowClientService;
|
||||||
|
import com.example.service.conversation.DataLossPrevention;
|
||||||
import com.example.util.SessionIdGenerator;
|
import com.example.util.SessionIdGenerator;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -22,39 +22,47 @@ import org.springframework.stereotype.Service;
|
|||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import com.example.dto.dialogflow.conversation.TextInputDTO;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class NotificationManagerService {
|
public class NotificationManagerService {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(NotificationManagerService.class);
|
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 eventName = "notificacion";
|
private static final String PREFIX_PO_PARAM = "notification_po_";
|
||||||
|
|
||||||
private final DialogflowClientService dialogflowClientService;
|
private final DialogflowClientService dialogflowClientService;
|
||||||
private final FirestoreNotificationService firestoreNotificationService;
|
private final FirestoreNotificationService firestoreNotificationService;
|
||||||
private final MemoryStoreNotificationService memoryStoreNotificationService;
|
private final MemoryStoreNotificationService memoryStoreNotificationService;
|
||||||
private final FirestoreNotificationConvService firestoreConversationService;
|
private final FirestoreNotificationConvService firestoreConversationService;
|
||||||
|
private final ExternalNotRequestMapper externalNotRequestMapper;
|
||||||
|
|
||||||
@Value("${dialogflow.default-language-code:es}")
|
private final DataLossPrevention dataLossPrevention;
|
||||||
private String defaultLanguageCode;
|
private final String dlpTemplateCompleteFlow;
|
||||||
|
|
||||||
public NotificationManagerService(
|
@Value("${dialogflow.default-language-code:es}")
|
||||||
|
private String defaultLanguageCode;
|
||||||
|
|
||||||
|
public NotificationManagerService(
|
||||||
DialogflowClientService dialogflowClientService,
|
DialogflowClientService dialogflowClientService,
|
||||||
FirestoreNotificationService firestoreNotificationService,
|
FirestoreNotificationService firestoreNotificationService,
|
||||||
MemoryStoreNotificationService memoryStoreNotificationService,
|
MemoryStoreNotificationService memoryStoreNotificationService,
|
||||||
FirestoreNotificationConvService firestoreConversationService) {
|
FirestoreNotificationConvService firestoreConversationService,
|
||||||
|
ExternalNotRequestMapper externalNotRequestMapper,
|
||||||
|
DataLossPrevention dataLossPrevention,
|
||||||
|
@Value("${google.cloud.dlp.dlpTemplateCompleteFlow}") String dlpTemplateCompleteFlow) {
|
||||||
this.dialogflowClientService = dialogflowClientService;
|
this.dialogflowClientService = dialogflowClientService;
|
||||||
this.firestoreNotificationService = firestoreNotificationService;
|
this.firestoreNotificationService = firestoreNotificationService;
|
||||||
this.memoryStoreNotificationService = memoryStoreNotificationService;
|
this.memoryStoreNotificationService = memoryStoreNotificationService;
|
||||||
this.firestoreConversationService = firestoreConversationService;
|
this.firestoreConversationService = firestoreConversationService;
|
||||||
}
|
this.externalNotRequestMapper = externalNotRequestMapper;
|
||||||
|
this.dataLossPrevention = dataLossPrevention;
|
||||||
|
this.dlpTemplateCompleteFlow = dlpTemplateCompleteFlow;
|
||||||
|
}
|
||||||
|
|
||||||
public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO externalRequest) {
|
public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO externalRequest) {
|
||||||
Objects.requireNonNull(externalRequest, "ExternalNotRequestDTO cannot be null.");
|
Objects.requireNonNull(externalRequest, "ExternalNotRequestDTO cannot be null.");
|
||||||
|
|
||||||
String telefono = externalRequest.phoneNumber();
|
String telefono = externalRequest.phoneNumber();
|
||||||
@@ -63,17 +71,30 @@ public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO e
|
|||||||
return Mono.error(new IllegalArgumentException("Phone number is required."));
|
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
|
// 1. Persist the incoming notification entry
|
||||||
String newNotificationId = SessionIdGenerator.generateStandardSessionId();
|
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(),
|
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)
|
Mono<Void> persistenceMono = memoryStoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
|
||||||
.doOnSuccess(v -> {
|
.doOnSuccess(v -> {
|
||||||
logger.info("Notification for phone {} cached. Kicking off async Firestore write-back.", telefono);
|
logger.info("Notification for phone {} cached. Kicking off async Firestore write-back.", telefono);
|
||||||
firestoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
|
firestoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
|
||||||
.subscribe(
|
.subscribe(
|
||||||
ignored -> logger.debug(
|
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(
|
e -> logger.error(
|
||||||
"Background: Error during notification entry persistence for phone {} in Firestore: {}",
|
"Background: Error during notification entry persistence for phone {} in Firestore: {}",
|
||||||
telefono, e.getMessage(), e));
|
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 {}",
|
.doOnNext(session -> logger.info("Found existing conversation session {} for phone number {}",
|
||||||
session.sessionId(), telefono))
|
session.sessionId(), telefono))
|
||||||
.flatMap(session -> {
|
.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)
|
return persistConversationTurn(session.userId(), session.sessionId(), systemEntry, telefono)
|
||||||
.thenReturn(session);
|
.thenReturn(session);
|
||||||
})
|
})
|
||||||
.switchIfEmpty(Mono.defer(() -> {
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
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;
|
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)
|
return persistConversationTurn(userId, newSessionId, systemEntry, telefono)
|
||||||
.then(Mono.just(ConversationSessionDTO.create(newSessionId, userId, telefono)));
|
.then(Mono.just(ConversationSessionDTO.create(newSessionId, userId, telefono)));
|
||||||
}));
|
}));
|
||||||
@@ -104,27 +138,14 @@ public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO e
|
|||||||
final String sessionId = session.sessionId();
|
final String sessionId = session.sessionId();
|
||||||
logger.info("Sending notification text to Dialogflow using conversation session: {}", sessionId);
|
logger.info("Sending notification text to Dialogflow using conversation session: {}", sessionId);
|
||||||
|
|
||||||
Map<String, Object> parameters = new HashMap<>();
|
DetectIntentRequestDTO detectIntentRequest = externalNotRequestMapper.map(obfuscatedRequest);
|
||||||
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));
|
|
||||||
|
|
||||||
return dialogflowClientService.detectIntent(sessionId, detectIntentRequest);
|
return dialogflowClientService.detectIntent(sessionId, detectIntentRequest);
|
||||||
})
|
})
|
||||||
.doOnSuccess(response -> logger
|
.doOnSuccess(response -> logger
|
||||||
.info("Finished processing notification. Dialogflow response received for phone {}.", telefono))
|
.info("Finished processing notification. Dialogflow response received for phone {}.", telefono))
|
||||||
.doOnError(e -> logger.error("Overall error in NotificationManagerService: {}", e.getMessage(), e));
|
.doOnError(e -> logger.error("Overall error in NotificationManagerService: {}", e.getMessage(), e));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry,
|
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry,
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
# Best Practices:
|
# Best Practices:
|
||||||
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
|
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
|
||||||
# to manage environment-specific settings.
|
# 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.
|
# Use environment variables or a configuration server for production environments.
|
||||||
# - This template can be adapted for logging configuration, database connections,
|
# - This template can be adapted for logging configuration, database connections,
|
||||||
# and other external service settings.
|
# and other external service settings.
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
# Best Practices:
|
# Best Practices:
|
||||||
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
|
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
|
||||||
# to manage environment-specific settings.
|
# 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.
|
# Use environment variables or a configuration server for production environments.
|
||||||
# - This template can be adapted for logging configuration, database connections,
|
# - This template can be adapted for logging configuration, database connections,
|
||||||
# and other external service settings.
|
# and other external service settings.
|
||||||
@@ -67,3 +67,8 @@ google.cloud.dlp.dlpTemplatePersistFlow=${DLP_TEMPLATE_PERSIST_FLOW}
|
|||||||
# Quick-replies Preset-data
|
# Quick-replies Preset-data
|
||||||
# =========================================================
|
# =========================================================
|
||||||
firestore.data.importer.enabled=true
|
firestore.data.importer.enabled=true
|
||||||
|
# =========================================================
|
||||||
|
# LOGGING Configuration
|
||||||
|
# =========================================================
|
||||||
|
logging.level.root=${LOGGING_LEVEL_ROOT:INFO}
|
||||||
|
logging.level.com.example=${LOGGING_LEVEL_COM_EXAMPLE:INFO}
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
# Best Practices:
|
# Best Practices:
|
||||||
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
|
# - Use Spring Profiles (e.g., application-dev.properties, application-prod.properties)
|
||||||
# to manage environment-specific settings.
|
# 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.
|
# Use environment variables or a configuration server for production environments.
|
||||||
# - This template can be adapted for logging configuration, database connections,
|
# - This template can be adapted for logging configuration, database connections,
|
||||||
# and other external service settings.
|
# and other external service settings.
|
||||||
@@ -67,3 +67,8 @@ google.cloud.dlp.dlpTemplatePersistFlow=${DLP_TEMPLATE_PERSIST_FLOW}
|
|||||||
# Quick-replies Preset-data
|
# Quick-replies Preset-data
|
||||||
# =========================================================
|
# =========================================================
|
||||||
firestore.data.importer.enabled=true
|
firestore.data.importer.enabled=true
|
||||||
|
# =========================================================
|
||||||
|
# LOGGING Configuration
|
||||||
|
# =========================================================
|
||||||
|
logging.level.root=${LOGGING_LEVEL_ROOT:INFO}
|
||||||
|
logging.level.com.example=${LOGGING_LEVEL_COM_EXAMPLE:DEBUG}
|
||||||
Reference in New Issue
Block a user