UPDATE code 20-Ago
This commit is contained in:
@@ -5,193 +5,290 @@
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import com.example.mapper.conversation.ExternalConvRequestMapper;
|
||||
import com.example.service.base.DialogflowClientService;
|
||||
import com.example.util.SessionIdGenerator;
|
||||
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;
|
||||
import com.example.mapper.conversation.ExternalConvRequestMapper;
|
||||
import com.example.mapper.messagefilter.ConversationContextMapper;
|
||||
import com.example.mapper.messagefilter.NotificationContextMapper;
|
||||
import com.example.service.base.DialogflowClientService;
|
||||
import com.example.service.base.MessageEntryFilter;
|
||||
import com.example.service.notification.MemoryStoreNotificationService;
|
||||
import com.example.service.quickreplies.QuickRepliesManagerService;
|
||||
import com.example.util.SessionIdGenerator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Service for orchestrating the end-to-end conversation flow.
|
||||
* It manages user sessions, creating new ones or reusing existing ones
|
||||
* based on a session reset threshold. The service handles the entire
|
||||
* conversation turn, from mapping an external request to calling Dialogflow,
|
||||
* and then persists both user and agent messages using a write-back strategy
|
||||
* to a primary cache (Redis) and an asynchronous write to Firestore.
|
||||
*/
|
||||
@Service
|
||||
public class ConversationManagerService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConversationManagerService.class);
|
||||
private static final long SESSION_RESET_THRESHOLD_HOURS = 24;
|
||||
private static final String CURRENT_PAGE_PARAM = "currentPage";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConversationManagerService.class);
|
||||
private final ExternalConvRequestMapper externalRequestToDialogflowMapper;
|
||||
private final DialogflowClientService dialogflowServiceClient;
|
||||
private final FirestoreConversationService firestoreConversationService;
|
||||
private final MemoryStoreConversationService memoryStoreConversationService;
|
||||
private final QuickRepliesManagerService quickRepliesManagerService;
|
||||
private final MessageEntryFilter messageEntryFilter;
|
||||
private final MemoryStoreNotificationService memoryStoreNotificationService;
|
||||
private final NotificationContextMapper notificationContextMapper;
|
||||
private final ConversationContextMapper conversationContextMapper;
|
||||
|
||||
private static final long SESSION_RESET_THRESHOLD_HOURS = 24;
|
||||
private static final String CURRENT_PAGE_PARAM = "currentPage";
|
||||
private final ExternalConvRequestMapper externalRequestToDialogflowMapper;
|
||||
|
||||
private final DialogflowClientService dialogflowServiceClient;
|
||||
private final FirestoreConversationService firestoreConversationService;
|
||||
private final MemoryStoreConversationService memoryStoreConversationService;
|
||||
|
||||
public ConversationManagerService(
|
||||
DialogflowClientService dialogflowServiceClient,
|
||||
FirestoreConversationService firestoreConversationService,
|
||||
MemoryStoreConversationService memoryStoreConversationService,
|
||||
ExternalConvRequestMapper externalRequestToDialogflowMapper) {
|
||||
public ConversationManagerService(
|
||||
DialogflowClientService dialogflowServiceClient,
|
||||
FirestoreConversationService firestoreConversationService,
|
||||
MemoryStoreConversationService memoryStoreConversationService,
|
||||
ExternalConvRequestMapper externalRequestToDialogflowMapper,
|
||||
QuickRepliesManagerService quickRepliesManagerService,
|
||||
MessageEntryFilter messageEntryFilter,
|
||||
MemoryStoreNotificationService memoryStoreNotificationService,
|
||||
NotificationContextMapper notificationContextMapper,
|
||||
ConversationContextMapper conversationContextMapper) {
|
||||
this.dialogflowServiceClient = dialogflowServiceClient;
|
||||
this.firestoreConversationService = firestoreConversationService;
|
||||
this.memoryStoreConversationService = memoryStoreConversationService;
|
||||
this.externalRequestToDialogflowMapper = externalRequestToDialogflowMapper;
|
||||
}
|
||||
this.quickRepliesManagerService = quickRepliesManagerService;
|
||||
this.messageEntryFilter = messageEntryFilter;
|
||||
this.memoryStoreNotificationService = memoryStoreNotificationService;
|
||||
this.notificationContextMapper = notificationContextMapper;
|
||||
this.conversationContextMapper = conversationContextMapper;
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO>manageConversation(ExternalConvRequestDTO Externalrequest) {
|
||||
final DetectIntentRequestDTO request;
|
||||
try {
|
||||
request = externalRequestToDialogflowMapper.mapExternalRequestToDetectIntentRequest(Externalrequest);
|
||||
logger.debug("Successfully pre-mapped ExternalRequestDTO to DetectIntentRequestDTO");
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Error during pre-mapping: {}", e.getMessage());
|
||||
return Mono.error(new IllegalArgumentException("Failed to process external request due to mapping error: " + e.getMessage(), e));
|
||||
public Mono<DetectIntentResponseDTO> manageConversation(ExternalConvRequestDTO externalrequest) {
|
||||
return memoryStoreConversationService.getSessionByTelefono(externalrequest.user().telefono())
|
||||
.flatMap(session -> {
|
||||
if (session != null && !session.entries().isEmpty()) {
|
||||
ConversationEntryDTO lastEntry = session.entries().get(session.entries().size() - 1);
|
||||
if (lastEntry.entity() == ConversationEntryEntity.SISTEMA && lastEntry.type() == ConversationEntryType.INICIO) {
|
||||
logger.info("Detected 'SISTEMA' and 'INICIO' values in last session entry. Delegating to QuickRepliesManagerService.");
|
||||
ExternalConvRequestDTO updatedRequest = new ExternalConvRequestDTO(
|
||||
externalrequest.message(),
|
||||
externalrequest.user(),
|
||||
externalrequest.channel(),
|
||||
externalrequest.tipo(),
|
||||
session.pantallaContexto()
|
||||
);
|
||||
return quickRepliesManagerService.manageConversation(updatedRequest);
|
||||
}
|
||||
}
|
||||
return continueManagingConversation(externalrequest);
|
||||
})
|
||||
.switchIfEmpty(continueManagingConversation(externalrequest));
|
||||
}
|
||||
|
||||
final ConversationContext context;
|
||||
try {
|
||||
context = resolveAndValidateRequest(request);
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Validation error for incoming request: {}", e.getMessage());
|
||||
return Mono.error(e);
|
||||
private Mono<DetectIntentResponseDTO> continueManagingConversation(ExternalConvRequestDTO externalrequest) {
|
||||
final DetectIntentRequestDTO request;
|
||||
try {
|
||||
request = externalRequestToDialogflowMapper.mapExternalRequestToDetectIntentRequest(externalrequest);
|
||||
logger.debug("Successfully pre-mapped ExternalRequestDTO to DetectIntentRequestDTO");
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Error during pre-mapping: {}", e.getMessage());
|
||||
return Mono.error(new IllegalArgumentException(
|
||||
"Failed to process external request due to mapping error: " + e.getMessage(), e));
|
||||
}
|
||||
|
||||
final ConversationContext context;
|
||||
try {
|
||||
context = resolveAndValidateRequest(request);
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Validation error for incoming request: {}", e.getMessage());
|
||||
return Mono.error(e);
|
||||
}
|
||||
|
||||
return handleMessageClassification(context, request);
|
||||
}
|
||||
|
||||
|
||||
private Mono<DetectIntentResponseDTO> handleMessageClassification(ConversationContext context, DetectIntentRequestDTO request) {
|
||||
final String userPhoneNumber = context.primaryPhoneNumber();
|
||||
final String userMessageText = context.userMessageText();
|
||||
|
||||
return memoryStoreNotificationService.getNotificationIdForPhone(userPhoneNumber)
|
||||
.flatMap(notificationId -> memoryStoreNotificationService.getCachedNotificationSession(notificationId))
|
||||
.map(notificationSession -> notificationSession.notificaciones().stream()
|
||||
.filter(notification -> "active".equalsIgnoreCase(notification.status()))
|
||||
.max(java.util.Comparator.comparing(NotificationDTO::timestampCreacion))
|
||||
.orElse(null))
|
||||
.filter(Objects::nonNull)
|
||||
.flatMap((NotificationDTO notification) -> {
|
||||
String notificationText = notificationContextMapper.toText(notification);
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.map(conversationContextMapper::toText)
|
||||
.defaultIfEmpty("")
|
||||
.flatMap(conversationHistory -> {
|
||||
String classification = messageEntryFilter.classifyMessage(userMessageText, notificationText, conversationHistory);
|
||||
if (MessageEntryFilter.CATEGORY_NOTIFICATION.equals(classification)) {
|
||||
return startNotificationConversation(context, request, notification);
|
||||
} else {
|
||||
return continueConversationFlow(context, request);
|
||||
}
|
||||
});
|
||||
})
|
||||
.switchIfEmpty(continueConversationFlow(context, request));
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> continueConversationFlow(ConversationContext context, DetectIntentRequestDTO request) {
|
||||
final String userId = context.userId();
|
||||
final String userMessageText = context.userMessageText();
|
||||
final String userPhoneNumber = context.primaryPhoneNumber();
|
||||
|
||||
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."));
|
||||
}
|
||||
|
||||
logger.info("Primary Check (MemoryStore): Looking up session for phone number: {}", userPhoneNumber);
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.flatMap(session -> {
|
||||
Instant now = Instant.now();
|
||||
if (Duration.between(session.lastModified(), now).toHours() < SESSION_RESET_THRESHOLD_HOURS) {
|
||||
logger.info("Recent Session Found: Session {} is within the 24-hour threshold. Proceeding to Dialogflow.", session.sessionId());
|
||||
return processDialogflowRequest(session, request, userId, userMessageText, userPhoneNumber, false);
|
||||
} else {
|
||||
logger.info("Old Session Found: Session {} is older than the threshold. Proceeding to full lookup.", session.sessionId());
|
||||
return fullLookupAndProcess(session, request, userId, userMessageText, userPhoneNumber);
|
||||
}
|
||||
})
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
logger.info("No session found in MemoryStore. Performing full lookup to Firestore.");
|
||||
return fullLookupAndProcess(null, request, userId, userMessageText, userPhoneNumber);
|
||||
}))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("Overall error handling conversation in ConversationManagerService: {}", e.getMessage(), e);
|
||||
return Mono.error(new RuntimeException("Failed to process conversation due to an internal error.", e));
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> fullLookupAndProcess(ConversationSessionDTO oldSession, DetectIntentRequestDTO request, String userId, String userMessageText, String userPhoneNumber) {
|
||||
return firestoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.map(conversationContextMapper::toTextWithLimits)
|
||||
.defaultIfEmpty("")
|
||||
.flatMap(conversationHistory -> {
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("Creating new session {} after full lookup.", newSessionId);
|
||||
ConversationSessionDTO newSession = ConversationSessionDTO.create(newSessionId, userId, userPhoneNumber);
|
||||
DetectIntentRequestDTO newRequest = request.withParameter(CURRENT_PAGE_PARAM, conversationHistory);
|
||||
return processDialogflowRequest(newSession, newRequest, userId, userMessageText, userPhoneNumber, true);
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> processDialogflowRequest(ConversationSessionDTO session, DetectIntentRequestDTO request, String userId, String userMessageText, String userPhoneNumber, boolean newSession) {
|
||||
final String finalSessionId = session.sessionId();
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(userMessageText);
|
||||
|
||||
return this.persistConversationTurn(userId, finalSessionId, userEntry, userPhoneNumber)
|
||||
.doOnSuccess(v -> logger.debug("User entry successfully persisted for session {}. Proceeding to Dialogflow...", finalSessionId))
|
||||
.doOnError(e -> logger.error("Error during user entry persistence for session {}: {}", finalSessionId, e.getMessage(), e))
|
||||
.then(Mono.defer(() -> dialogflowServiceClient.detectIntent(finalSessionId, request)
|
||||
.flatMap(response -> {
|
||||
logger.debug("Received Dialogflow CX response for session {}. Initiating agent response persistence.", finalSessionId);
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO.forAgent(response.queryResult());
|
||||
return persistConversationTurn(userId, finalSessionId, agentEntry, userPhoneNumber)
|
||||
.thenReturn(response);
|
||||
})
|
||||
.doOnError(error -> logger.error("Overall error during conversation management for session {}: {}", finalSessionId, error.getMessage(), error))
|
||||
));
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> startNotificationConversation(ConversationContext context, DetectIntentRequestDTO request, NotificationDTO notification) {
|
||||
final String userId = context.userId();
|
||||
final String userMessageText = context.userMessageText();
|
||||
final String userPhoneNumber = context.primaryPhoneNumber();
|
||||
|
||||
Mono<ConversationSessionDTO> sessionMono;
|
||||
if (userPhoneNumber != null && !userPhoneNumber.isBlank()) {
|
||||
logger.info("Checking for existing session for phone number: {}", userPhoneNumber);
|
||||
sessionMono = memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.doOnNext(session -> logger.info("Found existing session {} for phone number {}", session.sessionId(), userPhoneNumber))
|
||||
return memoryStoreNotificationService.getSessionByTelefono(userPhoneNumber)
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("No existing session found for phone number {}. Creating new session: {}", userPhoneNumber, newSessionId);
|
||||
return Mono.just(ConversationSessionDTO.create(newSessionId, userId, userPhoneNumber));
|
||||
}));
|
||||
} else {
|
||||
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."));
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("No existing notification session found for phone number {}. Creating new session: {}",
|
||||
userPhoneNumber, newSessionId);
|
||||
return Mono.just(ConversationSessionDTO.create(newSessionId, userId, userPhoneNumber));
|
||||
}))
|
||||
.flatMap(session -> {
|
||||
final String sessionId = session.sessionId();
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(userMessageText);
|
||||
return memoryStoreNotificationService.saveEntry(userId, sessionId, userEntry, userPhoneNumber)
|
||||
.then(dialogflowServiceClient.detectIntent(sessionId, request)
|
||||
.doOnSuccess(response -> {
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO.forAgent(response.queryResult());
|
||||
memoryStoreNotificationService.saveEntry(userId, sessionId, agentEntry, userPhoneNumber).subscribe();
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
return sessionMono.flatMap(session -> {
|
||||
final String finalSessionId = session.sessionId();
|
||||
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry,String userPhoneNumber) {
|
||||
logger.debug("Starting Write-Back persistence for session {}. Type: {}. Writing to Redis first.", sessionId,
|
||||
entry.type().name());
|
||||
|
||||
logger.info("Managing conversation for resolved session: {}", finalSessionId);
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(userMessageText);
|
||||
|
||||
final DetectIntentRequestDTO requestToDialogflow;
|
||||
Instant currentInteractionTimestamp = userEntry.timestamp();
|
||||
if (session.lastModified() != null &&
|
||||
Duration.between(session.lastModified(), currentInteractionTimestamp).toHours() >= SESSION_RESET_THRESHOLD_HOURS) {
|
||||
|
||||
logger.info("Session {} (last modified: {}) is older than {} hours. Adding '{}' parameter to Dialogflow request.",
|
||||
session.sessionId(), session.lastModified(), SESSION_RESET_THRESHOLD_HOURS, CURRENT_PAGE_PARAM);
|
||||
|
||||
requestToDialogflow = request.withParameter(CURRENT_PAGE_PARAM, true);
|
||||
|
||||
} else {
|
||||
requestToDialogflow = request;
|
||||
}
|
||||
|
||||
return this.persistConversationTurn(userId, finalSessionId, userEntry, userPhoneNumber)
|
||||
.doOnSuccess(v -> logger.debug("User entry successfully persisted for session {}. Proceeding to Dialogflow...", finalSessionId))
|
||||
.doOnError(e -> logger.error("Error during user entry persistence for session {}: {}", finalSessionId, e.getMessage(), e))
|
||||
.then(Mono.defer(() -> {
|
||||
return dialogflowServiceClient.detectIntent(finalSessionId, requestToDialogflow)
|
||||
.doOnSuccess(response -> {
|
||||
logger.debug("Received Dialogflow CX response for session {}. Initiating agent response persistence.", finalSessionId);
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO.forAgent(response.queryResult());
|
||||
this.persistConversationTurn(userId, finalSessionId, agentEntry, userPhoneNumber).subscribe(
|
||||
v -> logger.debug("Background: Agent entry persistence initiated for session {}.", finalSessionId),
|
||||
e -> logger.error("Background: Error during agent entry persistence for session {}: {}", finalSessionId, e.getMessage(), e)
|
||||
);
|
||||
})
|
||||
.doOnError(error -> logger.error("Overall error during conversation management for session {}: {}", finalSessionId, error.getMessage(), error));
|
||||
}));
|
||||
})
|
||||
.onErrorResume(e -> {
|
||||
logger.error("Overall error handling conversation in ConversationManagerService: {}", e.getMessage(), e);
|
||||
return Mono.error(new RuntimeException("Failed to process conversation due to an internal error.", e));
|
||||
})
|
||||
.subscribeOn(Schedulers.boundedElastic());
|
||||
}
|
||||
|
||||
private Mono<Void> persistConversationTurn(String userId, String sessionId, ConversationEntryDTO entry, String userPhoneNumber) {
|
||||
logger.debug("Starting Write-Back persistence for session {}. Type: {}. Writing to Redis first.", sessionId, entry.type().name());
|
||||
|
||||
return memoryStoreConversationService.saveEntry(userId, sessionId, entry, userPhoneNumber)
|
||||
.doOnSuccess(v -> {
|
||||
logger.info("Entry saved to Redis for session {}. Type: {}. Kicking off async Firestore write-back.", sessionId, entry.type().name());
|
||||
firestoreConversationService.saveEntry(userId, sessionId, entry, userPhoneNumber)
|
||||
.subscribe(
|
||||
fsVoid -> logger.debug("Asynchronously (Write-Back): Entry successfully saved to Firestore for session {}. Type: {}.",
|
||||
sessionId, entry.type().name()),
|
||||
fsError -> logger.error("Asynchronously (Write-Back): Failed to save entry to Firestore for session {}. Type: {}: {}",
|
||||
sessionId, entry.type().name(), fsError.getMessage(), fsError)
|
||||
);
|
||||
})
|
||||
.doOnError(e -> logger.error("Error during primary Redis write for session {}. Type: {}: {}", sessionId, entry.type().name(), e.getMessage(), e));
|
||||
}
|
||||
.doOnSuccess(v -> logger.info(
|
||||
"Entry saved to Redis for session {}. Type: {}. Kicking off async Firestore write-back.",
|
||||
sessionId, entry.type().name()))
|
||||
.then(firestoreConversationService.saveEntry(userId, sessionId, entry, userPhoneNumber)
|
||||
.doOnSuccess(fsVoid -> logger.debug(
|
||||
"Asynchronously (Write-Back): Entry successfully saved to Firestore for session {}. Type: {}.",
|
||||
sessionId, entry.type().name()))
|
||||
.doOnError(fsError -> logger.error(
|
||||
"Asynchronously (Write-Back): Failed to save entry to Firestore for session {}. Type: {}: {}",
|
||||
sessionId, entry.type().name(), fsError.getMessage(), fsError)))
|
||||
.doOnError(e -> logger.error("Error during primary Redis write for session {}. Type: {}: {}", sessionId,
|
||||
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(queryParamsDTO -> queryParamsDTO.parameters())
|
||||
.orElse(Collections.emptyMap());
|
||||
.map(queryParamsDTO -> queryParamsDTO.parameters())
|
||||
.orElse(Collections.emptyMap());
|
||||
|
||||
String primaryPhoneNumber = null;
|
||||
Object telefonoObj = params.get("telefono"); // Get from map
|
||||
if (telefonoObj instanceof String) {
|
||||
primaryPhoneNumber = (String) telefonoObj;
|
||||
primaryPhoneNumber = (String) telefonoObj;
|
||||
} else if (telefonoObj != null) {
|
||||
logger.warn("Parameter 'telefono' in queryParams is not a String (type: {}). Expected String.", telefonoObj.getClass().getName());
|
||||
logger.warn("Parameter 'telefono' in queryParams is not a String (type: {}). Expected String.",
|
||||
telefonoObj.getClass().getName());
|
||||
}
|
||||
|
||||
if (primaryPhoneNumber == null || primaryPhoneNumber.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Phone number (telefono) is required in query parameters for conversation management.");
|
||||
throw new IllegalArgumentException(
|
||||
"Phone number (telefono) is required in query parameters for conversation management.");
|
||||
}
|
||||
|
||||
String resolvedUserId = null;
|
||||
Object userIdObj = params.get("usuario_id");
|
||||
if (userIdObj instanceof String) {
|
||||
resolvedUserId = (String) userIdObj;
|
||||
resolvedUserId = (String) userIdObj;
|
||||
} else if (userIdObj != null) {
|
||||
logger.warn("Parameter 'userId' in queryParams is not a String (type: {}). Expected String.", userIdObj.getClass().getName());
|
||||
}
|
||||
|
||||
if (resolvedUserId == null || resolvedUserId.trim().isEmpty()) {
|
||||
resolvedUserId = "user_by_phone_" + primaryPhoneNumber.replaceAll("[^0-9]", "");
|
||||
logger.warn("User ID not provided in query parameters. Using derived ID from phone number: {}", resolvedUserId);
|
||||
logger.warn("Parameter 'userId' in query_params is not a String (type: {}). Expected String.",
|
||||
userIdObj.getClass().getName());
|
||||
}
|
||||
|
||||
if (request.queryInput() == null || request.queryInput().text() == null ||
|
||||
request.queryInput().text().text() == null || request.queryInput().text().text().trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Dialogflow query input text is required.");
|
||||
if (resolvedUserId == null || resolvedUserId.trim().isEmpty()) {
|
||||
resolvedUserId = "user_by_phone_" + primaryPhoneNumber.replaceAll("[^0-9]", "");
|
||||
logger.warn("User ID not provided in query parameters. Using derived ID from phone number: {}",
|
||||
resolvedUserId);
|
||||
}
|
||||
|
||||
if (request.queryInput() == null || request.queryInput().text() == null ||
|
||||
request.queryInput().text().text() == null || request.queryInput().text().text().trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Dialogflow query input text is required.");
|
||||
}
|
||||
|
||||
String userMessageText = request.queryInput().text().text();
|
||||
return new ConversationContext(resolvedUserId, null, userMessageText, primaryPhoneNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user