Repository navigation
Expand file tree
/
Copy pathemailService.js
More file actions
353 lines (312 loc) · 13.7 KB
/
Copy pathemailService.js
File metadata and controls
353 lines (312 loc) · 13.7 KB
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
// ============================================================
// emailService.js
// Servicio centralizado de envío de correos para VALTEC.
// Usa nodemailer con SMTP (Resend).
//
// IMPORTANTE: Este servicio es NO BLOQUEANTE.
// Si el correo falla, el movimiento ya quedó grabado en DB.
// Nunca lanzar excepciones que reviertan transacciones.
// ============================================================
require('dotenv').config();
const nodemailer = require('nodemailer');
// ── CONFIGURACIÓN SMTP ────────────────────────────────────────
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT || '465'),
secure: true,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
// ── HELPER: FECHA FORMATEADA ──────────────────────────────────
function fechaChilena(date = new Date()) {
return date.toLocaleString('es-CL', {
timeZone: 'America/Santiago',
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}
// ── HELPER: HTML BASE DEL CORREO ─────────────────────────────
/*
function htmlBase({ titulo, color, icono, filas, nota }) {
const filasHtml = filas.map(([label, valor]) => `
<tr>
<td style="padding:10px 16px; color:#6b7280; font-size:13px; white-space:nowrap; vertical-align:top;">
${label}
</td>
<td style="padding:10px 16px; color:#111827; font-size:14px; font-weight:600; word-break:break-word;">
${valor || '—'}
</td>
</tr>`).join('');
return `<!DOCTYPE html>
<html lang="es">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f3f4f6;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f6;padding:32px 0;">
<tr><td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,0.08);">
<!-- CABECERA -->
<tr>
<td style="background:${color};padding:28px 32px;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="font-size:28px;">${icono}</td>
<td style="padding-left:14px;">
<div style="color:#ffffff;font-size:11px;letter-spacing:2px;text-transform:uppercase;opacity:0.8;">VALTEC Logística</div>
<div style="color:#ffffff;font-size:19px;font-weight:700;margin-top:4px;">${titulo}</div>
</td>
</tr>
</table>
</td>
</tr>
<!-- CUERPO -->
<tr>
<td style="padding:28px 32px 8px;">
<p style="margin:0 0 20px;color:#374151;font-size:14px;line-height:1.6;">
Se ha registrado el siguiente movimiento en el sistema de control de activos:
</p>
<table width="100%" cellpadding="0" cellspacing="0"
style="border:1px solid #e5e7eb;border-radius:8px;border-collapse:collapse;">
${filasHtml}
</table>
${nota ? `<p style="margin:20px 0 0;color:#6b7280;font-size:13px;background:#f9fafb;border-left:4px solid ${color};padding:10px 14px;border-radius:4px;">${nota}</p>` : ''}
</td>
</tr>
<!-- PIE -->
<tr>
<td style="padding:24px 32px 32px;">
<p style="margin:0;color:#9ca3af;font-size:11px;border-top:1px solid #f3f4f6;padding-top:18px;">
Este correo es generado automáticamente por el sistema VALTEC Logística.<br>
<strong>No responda a este mensaje.</strong> — Sistema de Control de Activos
</p>
</td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}*/
function htmlBase({ titulo, color, icono, filas, nota, intro }) {
// 💡 Si no se envía un intro, usa el texto genérico por defecto
const textoIntro = intro || 'Se ha registrado el siguiente movimiento en el sistema de control de activos:';
const filasHtml = filas.map(([label, valor]) => `
<tr>
<td style="padding:10px 16px; color:#6b7280; font-size:13px; white-space:nowrap; vertical-align:top;">
${label}
</td>
<td style="padding:10px 16px; color:#111827; font-size:14px; font-weight:600; word-break:break-word;">
${valor || '—'}
</td>
</tr>`).join('');
return `<!DOCTYPE html>
<html lang="es">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f3f4f6;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f6;padding:32px 0;">
<tr><td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,0.08);">
<!-- CABECERA -->
<tr>
<td style="background:${color};padding:28px 32px;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="font-size:28px;">${icono}</td>
<td style="padding-left:14px;">
<div style="color:#ffffff;font-size:11px;letter-spacing:2px;text-transform:uppercase;opacity:0.8;">VALTEC Logística</div>
<div style="color:#ffffff;font-size:19px;font-weight:700;margin-top:4px;">${titulo}</div>
</td>
</tr>
</table>
</td>
</tr>
<!-- CUERPO -->
<tr>
<td style="padding:28px 32px 8px;">
<p style="margin:0 0 20px;color:#374151;font-size:14px;line-height:1.6;">
${textoIntro}
</p>
<table width="100%" cellpadding="0" cellspacing="0"
style="border:1px solid #e5e7eb;border-radius:8px;border-collapse:collapse;">
${filasHtml}
</table>
${nota ? `<p style="margin:20px 0 0;color:#6b7280;font-size:13px;background:#f9fafb;border-left:4px solid ${color};padding:10px 14px;border-radius:4px;">${nota}</p>` : ''}
</td>
</tr>
<!-- PIE -->
<tr>
<td style="padding:24px 32px 32px;">
<p style="margin:0;color:#9ca3af;font-size:11px;border-top:1px solid #f3f4f6;padding-top:18px;">
Este correo es generado automáticamente por el sistema VALTEC Logística.<br>
<strong>No responda a este mensaje.</strong> — Sistema de Control de Activos
</p>
</td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
/** // Funcion para dev
// ── ENVIAR CORREO (función interna) ───────────────────────────
async function enviar({ asunto, html, to, cc = [] }) {
const from = `"VALTEC Logística" <${process.env.SMTP_FROM || 'sistema@mail.logisticavaltec.cl'}>`;
const copia = 'sistema@logisticavaltec.cl';
// Si el colaborador no tiene mail, la cuenta sistema actúa como destinatario
const destino = to || copia;
const mailOptions = {
from,
to: destino,
cc: [...cc, copia].filter(Boolean).join(', ') || undefined,
subject: asunto,
html,
};
try {
const info = await transporter.sendMail(mailOptions);
console.log(`[EMAIL] Enviado OK — MessageId: ${info.messageId}`);
return { ok: true };
} catch (err) {
// Solo loguear — nunca lanzar. El movimiento ya está guardado.
console.error('[EMAIL] Error al enviar:', err.message);
return { ok: false, error: err.message };
}
}*/
// emailService.js — reemplazar la sección de transporter y la función enviar()
const { Resend } = require('resend'); // npm install resend
const resend = new Resend(process.env.SMTP_PASS); // la API key que ya tienes
async function enviar({ asunto, html, to, cc = [] }) {
const from = `VALTEC Logística <${process.env.SMTP_FROM}>`;
const copia = 'sistema@logisticavaltec.cl';
const destino = to || copia;
try {
const { error } = await resend.emails.send({
from,
to: [destino],
cc: [...cc, copia].filter(Boolean),
subject: asunto,
html,
});
if (error) {
console.error('[EMAIL] Error Resend:', error);
return { ok: false, error: error.message };
}
console.log('[EMAIL] Enviado OK via Resend API');
return { ok: true };
} catch (err) {
console.error('[EMAIL] Error al enviar:', err.message);
return { ok: false, error: err.message };
}
}
// ── API PÚBLICA ───────────────────────────────────────────────
/**
* Notificación de ENTREGA a colaborador.
* @param {Object} datos
* @param {string} datos.descripcion - Nombre del implemento
* @param {string} datos.codigo - N° de serie o ID artículo
* @param {string} datos.custodio - Nombre completo del colaborador
* @param {string} datos.rut - RUT del colaborador
* @param {string} [datos.sector] - Sector/área del colaborador
* @param {string} [datos.ubicacion] - Bodega de origen
* @param {number} [datos.cantidad] - Cantidad entregada
* @param {string} [datos.mailColaborador] - Correo del colaborador (to)
* @param {string[]} [datos.cc] - Correos adicionales en copia
*/
async function notificarEntrega(datos) {
const fecha = fechaChilena();
const filas = [
['📦 Implemento', datos.descripcion],
['🔖 Código / Serie', datos.codigo || datos.id_articulo],
['👤 Custodio', datos.custodio],
['🪪 RUT', datos.rut],
['🏢 Sector', datos.sector || null],
['📍 Bodega Origen', datos.ubicacion || null],
['🔢 Cantidad', datos.cantidad ? String(datos.cantidad) : null],
['📅 Fecha', fecha],
].filter(([, v]) => v);
const html = htmlBase({
titulo: 'Asignación de Custodia',
color: '#2563eb',
icono: '📤',
filas,
nota: '⚠️ Si existe alguna novedad con esta asignación, por favor infórmenos a la brevedad.',
});
return enviar({
asunto: `[VALTEC] Entrega registrada — ${datos.descripcion}`,
html,
to: datos.mailColaborador || null,
cc: datos.cc || [],
});
}
/**
* Notificación de DEVOLUCIÓN a bodega.
* @param {Object} datos
* @param {string} datos.descripcion - Nombre del implemento
* @param {string} datos.codigo - N° de serie o ID artículo
* @param {string} datos.custodio - Nombre completo del colaborador
* @param {string} datos.rut - RUT del colaborador
* @param {string} [datos.ubicacion] - Bodega destino
* @param {string} [datos.observacion] - Observación del movimiento
* @param {string} [datos.mailColaborador] - Correo del colaborador (to)
* @param {string[]} [datos.cc] - Correos adicionales en copia
*/
async function notificarDevolucion(datos) {
const fecha = fechaChilena();
const filas = [
['📦 Implemento', datos.descripcion],
['🔖 Código / Serie', datos.codigo || datos.id_articulo],
['👤 Devuelto por', datos.custodio],
['🪪 RUT', datos.rut],
['📍 Bodega Destino', datos.ubicacion || null],
['📅 Fecha', fecha],
['💬 Observación', datos.observacion || null],
].filter(([, v]) => v);
const html = htmlBase({
titulo: 'Devolución a Bodega',
color: '#16a34a',
icono: '↩️',
filas,
nota: datos.observacion
? null
: '✅ El implemento ha sido devuelto correctamente a bodega.',
});
return enviar({
asunto: `[VALTEC] Devolución registrada — ${datos.descripcion}`,
html,
to: datos.mailColaborador || null,
cc: datos.cc || [],
});
}
/**
* Notificación de UNIFORME O ARTÍCULO PENDIENTE a colaborador.
*/
async function notificarUniforme(datos) {
const fecha = fechaChilena();
const filas = [
// ['📦 Artículo', datos.descripcion],
// ['🔖 N° Registro', datos.codigo],
['👤 Colaborador', datos.custodio], // 🔄 Cambiado a Colaborador
['🪪 RUT', datos.rut],
['📍 Bodega Origen', datos.ubicacion || 'Bodega Central'],
['📅 Fecha', fecha],
].filter(([, v]) => v);
const html = htmlBase({
titulo: 'Artículo Pendiente de Retiro',
color: '#f59e0b', // Color ámbar/naranja de advertencia logística
icono: '📦',
filas,
intro: 'Estimado/a colaborador, se informa que tiene un artículo pendiente por retirar en Bodegas Valtec Puente 15 AMB.',
nota: '⚠️ Por favor, acérquese a la bodega mencionada para coordinar la entrega de sus implementos.',
});
return enviar({
asunto: `[VALTEC] Artículo pendiente por retirar`,
html,
to: datos.mailColaborador || null,
cc: datos.cc || [],
});
}
module.exports = { notificarEntrega, notificarDevolucion,notificarUniforme };