-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
212 lines (178 loc) · 6.19 KB
/
index.js
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
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const qrcode = require('qrcode-terminal');
const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const User = require('./models/user');
const Ticket = require('./models/ticket');
const adminRoutes = require('./routes/admin');
const fs = require('fs');
const multer = require('multer');
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
const JWT_SECRET = 'tu_clave_secreta';
// Conexión a MongoDB
mongoose.connect('mongodb://localhost:27017/soporte-ti', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Conectado a MongoDB');
}).catch((error) => {
console.error('Error al conectar a MongoDB:', error);
});
// Configuración de whatsapp-web.js
const client = new Client({
authStrategy: new LocalAuth()
});
client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('WhatsApp Web client is ready!');
});
client.on('message', async msg => {
console.log('MESSAGE RECEIVED', msg);
const { from, body } = msg;
try {
// Encuentra un agente disponible
const agent = await User.findOne({ role: 'agent' });
// Crea el ticket y asígnalo al agente encontrado
const existingTicket = await Ticket.findOne({ from });
if (existingTicket) {
existingTicket.message = body;
await existingTicket.save();
} else {
const newTicket = new Ticket({ from, message: body, assignedTo: agent._id });
await newTicket.save();
}
console.log('Ticket creado y asignado a:', agent.username);
} catch (error) {
console.error('Error al crear el ticket:', error);
}
});
client.initialize();
// Ruta de registro de usuario
app.post('/register', async (req, res) => {
const { username, password, role } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 8);
const user = new User({ username, password: hashedPassword, role });
await user.save();
res.status(201).json({ message: 'Usuario creado' });
} catch (error) {
res.status(400).json({ error: 'Error al crear el usuario' });
}
});
// Ruta de inicio de sesión
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ error: 'Usuario no encontrado' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ error: 'Contraseña incorrecta' });
}
const token = jwt.sign({ id: user._id, role: user.role }, JWT_SECRET, { expiresIn: '1h' });
res.json({ token, role: user.role });
} catch (error) {
res.status(500).json({ error: 'Error en el servidor' });
}
});
// Middleware de autenticación
const authMiddleware = (req, res, next) => {
const token = req.header('Authorization').replace('Bearer ', '');
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ error: 'No autorizado' });
}
};
// Middleware para verificar si el usuario es administrador
const adminMiddleware = (req, res, next) => {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Acceso denegado' });
}
next();
};
// Middleware para verificar si el usuario es agente
const agentMiddleware = (req, res, next) => {
if (req.user.role !== 'agent') {
return res.status(403).json({ error: 'Acceso denegado' });
}
next();
};
// Integrar rutas de administración
app.use('/admin', authMiddleware, adminMiddleware, adminRoutes);
// Ruta para obtener los tickets asignados al agente
app.get('/agent/tickets', authMiddleware, agentMiddleware, async (req, res) => {
try {
const tickets = await Ticket.find({ assignedTo: req.user.id });
res.status(200).json(tickets);
} catch (error) {
res.status(500).json({ error: 'Error al obtener los tickets' });
}
});
// Ruta para actualizar el estado de los tickets por el agente
app.put('/agent/tickets/:id', authMiddleware, agentMiddleware, async (req, res) => {
const { id } = req.params;
const { status } = req.body;
try {
const ticket = await Ticket.findById(id);
if (!ticket) {
return res.status(404).json({ error: 'Ticket no encontrado' });
}
ticket.status = status;
await ticket.save();
res.status(200).json({ message: 'Ticket actualizado' });
} catch (error) {
res.status(500).json({ error: 'Error al actualizar el ticket' });
}
});
// Configuración de multer para la subida de archivos
const upload = multer({ dest: 'uploads/' });
// Ruta para enviar mensajes desde el agente al cliente
app.post('/agent/tickets/:id/message', authMiddleware, agentMiddleware, async (req, res) => {
const { id } = req.params;
const { message } = req.body;
try {
const ticket = await Ticket.findById(id);
if (!ticket) {
return res.status(404).json({ error: 'Ticket no encontrado' });
}
const chatId = ticket.from; // ID de chat del cliente
await client.sendMessage(chatId, message);
res.status(200).json({ message: 'Mensaje enviado' });
} catch (error) {
res.status(500).json({ error: 'Error al enviar el mensaje' });
}
});
// Ruta para enviar archivos multimedia desde el agente al cliente
app.post('/agent/tickets/:id/media', authMiddleware, agentMiddleware, upload.single('file'), async (req, res) => {
const { id } = req.params;
const file = req.file;
try {
const ticket = await Ticket.findById(id);
if (!ticket) {
return res.status(404).json({ error: 'Ticket no encontrado' });
}
const media = MessageMedia.fromFilePath(file.path);
const chatId = ticket.from; // ID de chat del cliente
await client.sendMessage(chatId, media);
// Elimina el archivo temporal después de enviarlo
fs.unlinkSync(file.path);
res.status(200).json({ message: 'Archivo enviado' });
} catch (error) {
res.status(500).json({ error: 'Error al enviar el archivo' });
}
});
app.listen(3000, () => {
console.log('Servidor escuchando en puerto 3000');
});