Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | /**
* Conversation Transfer Controller - ROBUST VERSION
* Handles conversation transfers between admin, stores, departments, and users
* Supports both WhatsApp Cloud and WhatsApp Web (Evolution API) conversations
*
* Features:
* - Transfer from admin to store/department/user
* - Transfer from store to department/user
* - Transfer from department to user
* - Transfer between users
* - Automatic claim release on transfer
* - Transfer history tracking
* - Real-time Socket.IO notifications
* - Full i18n support
*
* @module controllers/ConversationTransferController
*/
const { pool } = require('../config/database');
const { logger } = require('../config/logger');
const { asyncHandler } = require('../middleware/errorHandler');
class ConversationTransferController {
/**
* Transfer conversation - UNIFIED ROBUST VERSION
* Works for both conversations (Evolution API) and whatsapp_cloud_conversations tables
* POST /api/user/conversations/:id/transfer
* POST /api/user/whatsapp-cloud/conversations/:id/transfer
*/
static transferConversation = asyncHandler(async (req, res) => {
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
const conversationId = req.params.id;
const userId = req.user.id;
const tenantId = req.user.tenantId || req.tenantId;
const {
targetType, // 'store', 'department', 'user'
targetId, // ID or name of target
targetName, // Name of target (for backward compatibility)
reason, // Optional transfer reason
source = 'whatsapp_cloud' // 'whatsapp_cloud' or 'whatsapp_web'
} = req.body;
// Validation
if (!targetType || (!targetId && !targetName)) {
await connection.rollback();
return res.status(400).json({
success: false,
message: 'Transfer target type and ID/name are required',
error: 'MISSING_TRANSFER_TARGET'
});
}
if (!['store', 'department', 'user'].includes(targetType)) {
await connection.rollback();
return res.status(400).json({
success: false,
message: 'Invalid target type. Must be: store, department, or user',
error: 'INVALID_TARGET_TYPE'
});
}
logger.info('Transfer conversation request', {
conversationId,
userId,
tenantId,
targetType,
targetId,
targetName,
source
});
// Determine which table to use
const tableName = source === 'whatsapp_web' ? 'conversations' : 'whatsapp_cloud_conversations';
const phoneField = source === 'whatsapp_web' ? 'phone_number' : 'contact_phone';
// Get conversation with lock
const [conversations] = await connection.execute(
`SELECT * FROM ${tableName} WHERE id = ? AND tenant_id = ? FOR UPDATE`,
[conversationId, tenantId]
);
if (conversations.length === 0) {
await connection.rollback();
return res.status(404).json({
success: false,
message: 'Conversation not found',
error: 'CONVERSATION_NOT_FOUND'
});
}
const conversation = conversations[0];
// Resolve target based on type
let resolvedTargetId = targetId;
let resolvedTargetName = targetName;
let targetUserId = null;
if (targetType === 'store') {
// Resolve store
if (!resolvedTargetId && resolvedTargetName) {
const [stores] = await connection.execute(
`SELECT id, name FROM stores WHERE tenant_id = ? AND name = ? LIMIT 1`,
[tenantId, resolvedTargetName]
);
if (stores.length > 0) {
resolvedTargetId = stores[0].id;
resolvedTargetName = stores[0].name;
}
} else if (resolvedTargetId) {
const [stores] = await connection.execute(
`SELECT id, name FROM stores WHERE tenant_id = ? AND id = ? LIMIT 1`,
[tenantId, resolvedTargetId]
);
if (stores.length > 0) {
resolvedTargetName = stores[0].name;
}
}
if (!resolvedTargetId) {
await connection.rollback();
return res.status(404).json({
success: false,
message: 'Target store not found',
error: 'STORE_NOT_FOUND'
});
}
} else if (targetType === 'department') {
// Resolve department
if (!resolvedTargetId && resolvedTargetName) {
const [departments] = await connection.execute(
`SELECT id, name FROM departments WHERE tenant_id = ? AND name = ? LIMIT 1`,
[tenantId, resolvedTargetName]
);
if (departments.length > 0) {
resolvedTargetId = departments[0].id;
resolvedTargetName = departments[0].name;
}
} else if (resolvedTargetId) {
const [departments] = await connection.execute(
`SELECT id, name FROM departments WHERE tenant_id = ? AND id = ? LIMIT 1`,
[tenantId, resolvedTargetId]
);
if (departments.length > 0) {
resolvedTargetName = departments[0].name;
}
}
if (!resolvedTargetId) {
await connection.rollback();
return res.status(404).json({
success: false,
message: 'Target department not found',
error: 'DEPARTMENT_NOT_FOUND'
});
}
} else if (targetType === 'user') {
// Resolve user
targetUserId = resolvedTargetId;
const [users] = await connection.execute(
`SELECT id, name, store_id, department_id FROM users WHERE tenant_id = ? AND id = ? AND active = 1 LIMIT 1`,
[tenantId, targetUserId]
);
if (users.length === 0) {
await connection.rollback();
return res.status(404).json({
success: false,
message: 'Target user not found or inactive',
error: 'USER_NOT_FOUND'
});
}
resolvedTargetName = users[0].name;
// When transferring to user, also set their store/department
if (users[0].store_id) {
const [stores] = await connection.execute(
`SELECT id, name FROM stores WHERE id = ? LIMIT 1`,
[users[0].store_id]
);
if (stores.length > 0) {
resolvedTargetId = stores[0].id;
}
} else if (users[0].department_id) {
const [departments] = await connection.execute(
`SELECT id, name FROM departments WHERE id = ? LIMIT 1`,
[users[0].department_id]
);
if (departments.length > 0) {
resolvedTargetId = departments[0].id;
}
}
}
// Build update query based on target type
let updateQuery = '';
let updateParams = [];
if (targetType === 'store') {
if (source === 'whatsapp_web') {
updateQuery = `
UPDATE ${tableName}
SET
transferred_to_store = ?,
transferred_to_department = NULL,
transferred_at = NOW(),
transferred_by_user_id = ?,
claimed_by_user_id = NULL,
claimed_at = NULL,
is_claimed = FALSE,
status = 'waiting',
updated_at = NOW()
WHERE id = ? AND tenant_id = ?
`;
updateParams = [resolvedTargetName, userId, conversationId, tenantId];
} else {
updateQuery = `
UPDATE ${tableName}
SET
transferred_to_store = ?,
transferred_to_department = NULL,
transferred_at = NOW(),
transferred_by_user_id = ?,
claimed_by_user_id = NULL,
claimed_at = NULL,
store_id = ?,
department_id = NULL,
status = 'open',
updated_at = NOW()
WHERE id = ? AND tenant_id = ?
`;
updateParams = [resolvedTargetId, userId, resolvedTargetId, conversationId, tenantId];
}
} else if (targetType === 'department') {
if (source === 'whatsapp_web') {
updateQuery = `
UPDATE ${tableName}
SET
transferred_to_store = NULL,
transferred_to_department = ?,
transferred_at = NOW(),
transferred_by_user_id = ?,
claimed_by_user_id = NULL,
claimed_at = NULL,
is_claimed = FALSE,
status = 'waiting',
updated_at = NOW()
WHERE id = ? AND tenant_id = ?
`;
updateParams = [resolvedTargetName, userId, conversationId, tenantId];
} else {
updateQuery = `
UPDATE ${tableName}
SET
transferred_to_store = NULL,
transferred_to_department = ?,
transferred_at = NOW(),
transferred_by_user_id = ?,
claimed_by_user_id = NULL,
claimed_at = NULL,
store_id = NULL,
department_id = ?,
status = 'open',
updated_at = NOW()
WHERE id = ? AND tenant_id = ?
`;
updateParams = [resolvedTargetId, userId, resolvedTargetId, conversationId, tenantId];
}
} else if (targetType === 'user') {
if (source === 'whatsapp_web') {
updateQuery = `
UPDATE ${tableName}
SET
claimed_by_user_id = ?,
claimed_at = NOW(),
is_claimed = TRUE,
transferred_at = NOW(),
transferred_by_user_id = ?,
status = 'attended',
updated_at = NOW()
WHERE id = ? AND tenant_id = ?
`;
updateParams = [targetUserId, userId, conversationId, tenantId];
} else {
updateQuery = `
UPDATE ${tableName}
SET
claimed_by_user_id = ?,
claimed_at = NOW(),
transferred_at = NOW(),
transferred_by_user_id = ?,
assigned_to_user_id = ?,
status = 'open',
updated_at = NOW()
WHERE id = ? AND tenant_id = ?
`;
updateParams = [targetUserId, userId, targetUserId, conversationId, tenantId];
}
}
// Execute update
await connection.execute(updateQuery, updateParams);
// Log transfer in conversation_notes or conversation_logs
try {
const transferNote = `Transferred to ${targetType}: ${resolvedTargetName}${reason ? ` - Reason: ${reason}` : ''}`;
if (source === 'whatsapp_cloud') {
// Try to insert into conversation_notes
await connection.execute(
`INSERT INTO conversation_notes (
tenant_id, conversation_id, contact_phone, note_text, note_type,
created_by_user_id, created_by_name, is_internal_note, created_at
) VALUES (?, ?, ?, ?, 'transfer', ?, ?, TRUE, NOW())`,
[tenantId, conversationId, conversation[phoneField], transferNote, userId, req.user.name || 'User']
);
} else {
// For whatsapp_web, try conversation_logs if table exists
try {
await connection.execute(
`INSERT INTO conversation_logs (
conversation_id, user_id, action, details, created_at
) VALUES (?, ?, 'transferred', ?, NOW())`,
[conversationId, userId, JSON.stringify({
targetType,
targetId: resolvedTargetId,
targetName: resolvedTargetName,
reason
})]
);
} catch (logError) {
// Table might not exist, continue without logging
logger.warn('Could not log transfer (table may not exist)', {
error: logError.message,
conversationId
});
}
}
} catch (noteError) {
// Continue even if note insertion fails
logger.warn('Could not create transfer note', {
error: noteError.message,
conversationId
});
}
await connection.commit();
logger.info('Conversation transferred successfully', {
conversationId,
userId,
tenantId,
targetType,
targetId: resolvedTargetId,
targetName: resolvedTargetName,
source
});
// Emit Socket.IO events for real-time updates
const io = req.app.get('io');
if (io) {
const tenantNamespace = io.of(`/tenant/${tenantId}`);
// Emit transfer event
tenantNamespace.emit('conversation-transferred', {
conversationId,
targetType,
targetId: resolvedTargetId,
targetName: resolvedTargetName,
transferredBy: {
id: userId,
name: req.user.name
},
source,
timestamp: new Date().toISOString()
});
// Emit specific event for WhatsApp Cloud
if (source === 'whatsapp_cloud') {
tenantNamespace.emit('whatsapp-cloud:conversation-transferred', {
conversationId,
targetType,
targetId: resolvedTargetId,
targetName: resolvedTargetName,
transferredBy: userId,
timestamp: new Date().toISOString()
});
}
}
return res.json({
success: true,
message: 'Conversation transferred successfully',
data: {
conversationId,
targetType,
targetId: resolvedTargetId,
targetName: resolvedTargetName,
transferredAt: new Date().toISOString()
}
});
} catch (error) {
await connection.rollback();
logger.error('Error transferring conversation', {
error: error.message,
stack: error.stack,
conversationId: req.params.id,
userId: req.user.id
});
return res.status(500).json({
success: false,
message: 'Failed to transfer conversation',
error: process.env.NODE_ENV === 'development' ? error.message : undefined
});
} finally {
connection.release();
}
});
/**
* Get transfer options (stores, departments, users)
* GET /api/user/conversations/transfer-options
* GET /api/user/whatsapp-cloud/conversations/transfer-options
*/
static getTransferOptions = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId || req.tenantId;
const userId = req.user.id;
try {
// Get stores
const [stores] = await pool.execute(
`SELECT id, name, description, is_active
FROM stores
WHERE tenant_id = ? AND is_active = TRUE
ORDER BY name ASC`,
[tenantId]
);
// Get departments
const [departments] = await pool.execute(
`SELECT id, name, description, is_active
FROM departments
WHERE tenant_id = ? AND is_active = TRUE
ORDER BY name ASC`,
[tenantId]
);
// Get users (excluding current user)
const [users] = await pool.execute(
`SELECT u.id, u.name, u.email, u.role, u.store_id, u.department_id,
s.name as store_name, d.name as department_name
FROM users u
LEFT JOIN stores s ON u.store_id = s.id
LEFT JOIN departments d ON u.department_id = d.id
WHERE u.tenant_id = ? AND u.active = TRUE AND u.id != ?
ORDER BY u.name ASC`,
[tenantId, userId]
);
logger.info('Transfer options retrieved', {
tenantId,
userId,
storesCount: stores.length,
departmentsCount: departments.length,
usersCount: users.length
});
return res.json({
success: true,
data: {
stores,
departments,
users
}
});
} catch (error) {
logger.error('Error getting transfer options', {
error: error.message,
tenantId,
userId
});
return res.status(500).json({
success: false,
message: 'Failed to load transfer options'
});
}
});
/**
* Get transfer history for a conversation
* GET /api/user/conversations/:id/transfer-history
* GET /api/user/whatsapp-cloud/conversations/:id/transfer-history
*/
static getTransferHistory = asyncHandler(async (req, res) => {
const conversationId = req.params.id;
const tenantId = req.user.tenantId || req.tenantId;
const source = req.query.source || 'whatsapp_cloud';
try {
let history = [];
if (source === 'whatsapp_cloud') {
// Get from conversation_notes
const [notes] = await pool.execute(
`SELECT cn.*, u.name as user_name
FROM conversation_notes cn
LEFT JOIN users u ON cn.created_by_user_id = u.id
WHERE cn.conversation_id = ? AND cn.tenant_id = ? AND cn.note_type = 'transfer'
ORDER BY cn.created_at DESC`,
[conversationId, tenantId]
);
history = notes;
} else {
// Get from conversation_logs
try {
const [logs] = await pool.execute(
`SELECT cl.*, u.name as user_name
FROM conversation_logs cl
LEFT JOIN users u ON cl.user_id = u.id
WHERE cl.conversation_id = ? AND cl.action = 'transferred'
ORDER BY cl.created_at DESC`,
[conversationId]
);
history = logs;
} catch (error) {
// Table might not exist
logger.warn('conversation_logs table not found', { error: error.message });
}
}
return res.json({
success: true,
data: history
});
} catch (error) {
logger.error('Error getting transfer history', {
error: error.message,
conversationId,
tenantId
});
return res.status(500).json({
success: false,
message: 'Failed to load transfer history'
});
}
});
}
module.exports = ConversationTransferController;
|