cambios de desarrollo

This commit is contained in:
abiandev
2026-06-01 16:11:02 +02:00
parent 48b349d68b
commit 6b7c7ec462
10 changed files with 1282 additions and 23 deletions
+289
View File
@@ -0,0 +1,289 @@
const assert = require('node:assert/strict');
const http = require('node:http');
const test = require('node:test');
const jwt = require('jsonwebtoken');
const app = require('../app');
const db = require('../src/config/db');
const agheeraPushClient = require('../src/services/agheeraPushClient');
const TEST_JWT_SECRET = 'test-jwt-secret';
let originalQuery;
let originalJwtSecret;
let originalAgheeraApiKey;
const createToken = (payload = {}) =>
jwt.sign(
{
id: 1,
dni: '58045340X',
id_proveedor: 675,
...payload
},
TEST_JWT_SECRET,
{ expiresIn: '1h' }
);
const withServer = async (callback) =>
new Promise((resolve, reject) => {
const server = app.listen(0, '127.0.0.1');
server.on('error', reject);
server.on('listening', async () => {
try {
const result = await callback(server);
server.close((closeError) => {
if (closeError) {
reject(closeError);
return;
}
resolve(result);
});
} catch (error) {
server.close(() => reject(error));
}
});
});
const postJson = async ({ port, path, authorization, body }) =>
new Promise((resolve, reject) => {
const rawBody = JSON.stringify(body);
const req = http.request(
{
hostname: '127.0.0.1',
port,
method: 'POST',
path,
headers: {
authorization,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(rawBody)
}
},
(res) => {
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve({
statusCode: res.statusCode,
body: responseBody ? JSON.parse(responseBody) : null
});
});
}
);
req.on('error', reject);
req.write(rawBody);
req.end();
});
test.before(() => {
originalQuery = db.query;
originalJwtSecret = process.env.JWT_SECRET;
originalAgheeraApiKey = process.env.AGHEERA_API_KEY;
});
test.after(() => {
db.query = originalQuery;
process.env.JWT_SECRET = originalJwtSecret;
process.env.AGHEERA_API_KEY = originalAgheeraApiKey;
agheeraPushClient.__resetHttpClientForTests();
});
test.afterEach(() => {
db.query = originalQuery;
agheeraPushClient.__resetHttpClientForTests();
});
test('POST /api/locations envia posicion a Agheera para cliente 532', async () => {
process.env.JWT_SECRET = TEST_JWT_SECRET;
process.env.AGHEERA_API_KEY = 'test-api-key';
const agheeraCalls = [];
agheeraPushClient.__setHttpClientForTests(async (url, options) => {
agheeraCalls.push({ url, options });
return { ok: true, status: 200, text: async () => 'Messages received.' };
});
let step = 0;
db.query = async (sql, params) => {
step += 1;
if (step === 1) {
assert.match(sql, /INSERT INTO c_trazabilidad_transportista/);
assert.equal(params[0].length, 1);
assert.deepEqual(params[0][0].slice(0, 3), ['40.416775', '-3.70379', '58045340X']);
assert.equal(params[0][0][4], 248230);
return [{ affectedRows: 1 }];
}
if (step === 2) {
assert.match(sql, /FROM c_viajes/);
assert.deepEqual(params, [248230]);
return [[{ id_cliente: 532 }]];
}
assert.match(sql, /FROM c_viajes_proveedor/);
assert.deepEqual(params, [248230, '58045340X']);
return [[{ matricula: '6599LCN' }]];
};
const response = await withServer(async (server) =>
postJson({
port: server.address().port,
path: '/api/locations',
authorization: `Bearer ${createToken()}`,
body: {
latitude: 40.416775,
longitude: -3.70379,
id_viaje: 248230,
timestamp: '2026-06-01T13:20:00Z'
}
})
);
assert.equal(response.statusCode, 200);
assert.deepEqual(response.body, {
success: true,
count: 1,
message: 'Locations saved',
agheera_push: {
trip_id: 248230,
attempted: true,
success: true,
http_status: 200,
error: null
}
});
assert.equal(agheeraCalls.length, 1);
const call = agheeraCalls[0];
assert.equal(call.url, 'https://push-test.agheera.com/Telematics/Positions');
assert.equal(call.options.headers.apiKey, 'test-api-key');
const payload = JSON.parse(call.options.body);
assert.deepEqual(payload, {
Vehicles: [
{
latitude: 40.416775,
longitude: -3.70379,
vehicleId: '6599LCN',
licensePlate: '6599LCN',
measurementTime: '2026-06-01T13:20:00Z'
}
]
});
});
test('POST /api/locations no envia a Agheera para clientes distintos de 532', async () => {
process.env.JWT_SECRET = TEST_JWT_SECRET;
process.env.AGHEERA_API_KEY = 'test-api-key';
const agheeraCalls = [];
agheeraPushClient.__setHttpClientForTests(async (url, options) => {
agheeraCalls.push({ url, options });
return { ok: true, status: 200, text: async () => 'Messages received.' };
});
let step = 0;
db.query = async (sql, params) => {
step += 1;
if (step === 1) {
assert.match(sql, /INSERT INTO c_trazabilidad_transportista/);
return [{ affectedRows: 1 }];
}
assert.match(sql, /FROM c_viajes/);
assert.deepEqual(params, [248230]);
return [[{ id_cliente: 700 }]];
};
const response = await withServer(async (server) =>
postJson({
port: server.address().port,
path: '/api/locations',
authorization: `Bearer ${createToken()}`,
body: {
latitude: 40.416775,
longitude: -3.70379,
id_viaje: 248230,
timestamp: '2026-06-01T13:20:00Z'
}
})
);
assert.equal(response.statusCode, 200);
assert.deepEqual(response.body, {
success: true,
count: 1,
message: 'Locations saved'
});
assert.equal(agheeraCalls.length, 0);
});
test('POST /api/locations devuelve error de Agheera sin romper guardado local', async () => {
process.env.JWT_SECRET = TEST_JWT_SECRET;
process.env.AGHEERA_API_KEY = 'test-api-key';
agheeraPushClient.__setHttpClientForTests(async () => ({
ok: false,
status: 401,
text: async () => 'Unauthorized'
}));
let step = 0;
db.query = async (sql, params) => {
step += 1;
if (step === 1) {
assert.match(sql, /INSERT INTO c_trazabilidad_transportista/);
return [{ affectedRows: 1 }];
}
if (step === 2) {
assert.match(sql, /FROM c_viajes/);
assert.deepEqual(params, [248230]);
return [[{ id_cliente: 532 }]];
}
assert.match(sql, /FROM c_viajes_proveedor/);
assert.deepEqual(params, [248230, '58045340X']);
return [[{ matricula: '6599LCN' }]];
};
const response = await withServer(async (server) =>
postJson({
port: server.address().port,
path: '/api/locations',
authorization: `Bearer ${createToken()}`,
body: {
latitude: 40.416775,
longitude: -3.70379,
id_viaje: 248230,
timestamp: '2026-06-01T13:20:00Z'
}
})
);
assert.equal(response.statusCode, 200);
assert.deepEqual(response.body, {
success: true,
count: 1,
message: 'Locations saved',
agheera_push: {
trip_id: 248230,
attempted: true,
success: false,
http_status: 401,
error: 'Agheera push failed'
}
});
});
+276 -4
View File
@@ -12,8 +12,11 @@ process.env.TRIP_STATUS_UPLOAD_DIR = TEST_UPLOAD_DIR;
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual'
const app = require('../app');
process.env.TRIP_STATUS_UPLOAD_DIR = TEST_UPLOAD_DIR;
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
const db = require('../src/config/db');
const tripStatusPhotoStorage = require('../src/services/tripStatusPhotoStorage');
const agheeraPushClient = require('../src/services/agheeraPushClient');
const JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';
process.env.JWT_SECRET = JWT_SECRET;
@@ -233,6 +236,7 @@ test.after(() => {
db.query = originalQuery;
db.getConnection = originalGetConnection;
tripStatusPhotoStorage.__resetSftpClientFactoryForTests();
agheeraPushClient.__resetHttpClientForTests();
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
delete process.env.TRIP_STATUS_SFTP_HOST;
delete process.env.TRIP_STATUS_SFTP_PORT;
@@ -241,6 +245,8 @@ test.after(() => {
delete process.env.TRIP_STATUS_SFTP_REMOTE_BASE_DIR;
delete process.env.POSTS_LOG_PATH;
delete process.env.TRIP_STATUS_UPDATES_LOG_PATH;
delete process.env.AGHEERA_PUSH_URL;
delete process.env.AGHEERA_API_KEY;
fs.rmSync(TEST_UPLOAD_DIR, { recursive: true, force: true });
fs.rmSync(TEST_POSTS_LOG_PATH, { force: true });
fs.rmSync(TEST_STATUS_LOG_PATH, { force: true });
@@ -250,6 +256,7 @@ test.afterEach(() => {
db.query = originalQuery;
db.getConnection = originalGetConnection;
tripStatusPhotoStorage.__resetSftpClientFactoryForTests();
agheeraPushClient.__resetHttpClientForTests();
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
delete process.env.TRIP_STATUS_SFTP_HOST;
delete process.env.TRIP_STATUS_SFTP_PORT;
@@ -258,6 +265,8 @@ test.afterEach(() => {
delete process.env.TRIP_STATUS_SFTP_REMOTE_BASE_DIR;
delete process.env.POSTS_LOG_PATH;
delete process.env.TRIP_STATUS_UPDATES_LOG_PATH;
delete process.env.AGHEERA_PUSH_URL;
delete process.env.AGHEERA_API_KEY;
fs.rmSync(TEST_POSTS_LOG_PATH, { force: true });
fs.rmSync(TEST_STATUS_LOG_PATH, { force: true });
});
@@ -710,7 +719,7 @@ test('POST /api/trips/:id/status modo dual replica foto a SFTP y mantiene local'
const recorder = createSftpRecorder();
tripStatusPhotoStorage.__setSftpClientFactoryForTests(createFakeSftpClientFactory(recorder));
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
process.env.TRIP_STATUS_SFTP_HOST = 'localhost';
process.env.TRIP_STATUS_SFTP_HOST = '194.164.175.51';
process.env.TRIP_STATUS_SFTP_PORT = '22';
process.env.TRIP_STATUS_SFTP_USERNAME = 'ssh_fotos_estado';
process.env.TRIP_STATUS_SFTP_PASSWORD = 'test-password';
@@ -787,7 +796,7 @@ test('POST /api/trips/:id/status modo dual con fallo SFTP mantiene fallback loca
createFakeSftpClientFactory(recorder, { failPut: true })
);
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
process.env.TRIP_STATUS_SFTP_HOST = 'localhost';
process.env.TRIP_STATUS_SFTP_HOST = '194.164.175.51';
process.env.TRIP_STATUS_SFTP_PORT = '22';
process.env.TRIP_STATUS_SFTP_USERNAME = 'ssh_fotos_estado';
process.env.TRIP_STATUS_SFTP_PASSWORD = 'test-password';
@@ -853,7 +862,7 @@ test('POST /api/trips/:id/status payload inválido tras upload limpia remoto y l
const recorder = createSftpRecorder();
tripStatusPhotoStorage.__setSftpClientFactoryForTests(createFakeSftpClientFactory(recorder));
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
process.env.TRIP_STATUS_SFTP_HOST = 'localhost';
process.env.TRIP_STATUS_SFTP_HOST = '194.164.175.51';
process.env.TRIP_STATUS_SFTP_PORT = '22';
process.env.TRIP_STATUS_SFTP_USERNAME = 'ssh_fotos_estado';
process.env.TRIP_STATUS_SFTP_PASSWORD = 'test-password';
@@ -1121,6 +1130,269 @@ test('POST /api/trips/:id/status propaga estado global al viaje padre', async ()
assert.equal(step, 7);
});
test('POST /api/trips/:id/status cliente 532 envia posicion a Agheera en estado global', async () => {
process.env.AGHEERA_API_KEY = 'test-api-key';
const agheeraCalls = [];
agheeraPushClient.__setHttpClientForTests(async (url, options) => {
agheeraCalls.push({ url, options });
return {
ok: true,
status: 200,
text: async () => 'Messages received.'
};
});
let step = 0;
db.query = async (sql, params) => {
step += 1;
if (step === 1) {
assert.match(sql, /FROM t_viaje_estados/);
assert.deepEqual(params, [6]);
return [[{ id_estado: 6 }]];
}
if (step === 2) {
assert.match(sql, /FROM c_viajes/);
assert.match(sql, /id_cliente/);
assert.deepEqual(params, [248230]);
return [[{ id_viaje: 248230, id_viaje_padre: 0, id_cliente: 532 }]];
}
if (step === 3) {
assert.match(sql, /FROM c_viajes_proveedor/);
assert.match(sql, /id_tipovehiculo AS matricula/);
assert.deepEqual(params, [248230, '58045340X']);
return [[{ n_proveedor: 1, id_proveedor: 675, matricula: '1234ABC' }]];
}
if (step === 4) {
assert.match(sql, /UPDATE c_viajes/);
assert.deepEqual(params, [6, 1, 248230]);
return [{ affectedRows: 1 }];
}
assert.match(sql, /INSERT INTO c_cambios_estado/);
assert.equal(params[6], '40.416775');
assert.equal(params[7], '-3.70379');
return [{ insertId: 6, affectedRows: 1 }];
};
const response = await withServer(async (server) =>
requestJson({
port: server.address().port,
method: 'POST',
path: '/api/trips/248230/status',
authorization: `Bearer ${createToken()}`,
body: {
id_estado: 6,
latitud: '40,416775',
longitud: '-3.703790'
}
})
);
assert.equal(response.statusCode, 200);
assert.equal(response.body.success, true);
assert.deepEqual(response.body.agheera_push, {
trip_id: 248230,
attempted: true,
success: true,
http_status: 200,
error: null
});
assert.equal(agheeraCalls.length, 1);
const call = agheeraCalls[0];
assert.equal(call.url, 'https://push-test.agheera.com/Telematics/Positions');
assert.equal(call.options.method, 'POST');
assert.equal(call.options.headers.apiKey, 'test-api-key');
assert.equal(call.options.headers['Content-Type'], 'application/json');
const payload = JSON.parse(call.options.body);
assert.deepEqual(Object.keys(payload), ['Vehicles']);
assert.equal(payload.Vehicles.length, 1);
assert.equal(payload.Vehicles[0].latitude, 40.416775);
assert.equal(payload.Vehicles[0].longitude, -3.70379);
assert.equal(payload.Vehicles[0].vehicleId, '1234ABC');
assert.equal(payload.Vehicles[0].licensePlate, '1234ABC');
assert.match(payload.Vehicles[0].measurementTime, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
});
test('POST /api/trips/:id/status cliente distinto de 532 no envia a Agheera', async () => {
process.env.AGHEERA_API_KEY = 'test-api-key';
const agheeraCalls = [];
agheeraPushClient.__setHttpClientForTests(async (url, options) => {
agheeraCalls.push({ url, options });
return { ok: true, status: 200, text: async () => 'Messages received.' };
});
let step = 0;
db.query = async (sql, params) => {
step += 1;
if (step === 1) {
return [[{ id_estado: 6 }]];
}
if (step === 2) {
return [[{ id_viaje: 248230, id_viaje_padre: 0, id_cliente: 700 }]];
}
if (step === 3) {
return [[{ n_proveedor: 1, id_proveedor: 675, matricula: '1234ABC' }]];
}
if (step === 4) {
assert.match(sql, /UPDATE c_viajes/);
return [{ affectedRows: 1 }];
}
assert.match(sql, /INSERT INTO c_cambios_estado/);
return [{ insertId: 6, affectedRows: 1 }];
};
const response = await withServer(async (server) =>
requestJson({
port: server.address().port,
method: 'POST',
path: '/api/trips/248230/status',
authorization: `Bearer ${createToken()}`,
body: {
id_estado: 6,
latitud: '40.416775',
longitud: '-3.703790'
}
})
);
assert.equal(response.statusCode, 200);
assert.equal(response.body.success, true);
assert.equal(response.body.agheera_push, undefined);
assert.equal(agheeraCalls.length, 0);
});
test('POST /api/trips/:id/status estado intermedio con id_punto no envia a Agheera', async () => {
process.env.AGHEERA_API_KEY = 'test-api-key';
const agheeraCalls = [];
agheeraPushClient.__setHttpClientForTests(async (url, options) => {
agheeraCalls.push({ url, options });
return { ok: true, status: 200, text: async () => 'Messages received.' };
});
let step = 0;
db.query = async (sql, params) => {
step += 1;
if (step === 1) {
assert.match(sql, /FROM t_viaje_estados/);
return [[{ id_estado: 5 }]];
}
if (step === 2) {
assert.match(sql, /FROM c_viajes/);
return [[{ id_viaje: 248230 }]];
}
if (step === 3) {
assert.match(sql, /FROM c_viajes_proveedor/);
return [[{ n_proveedor: 1 }]];
}
if (step === 4) {
assert.match(sql, /FROM c_viajes_puntos/);
assert.deepEqual(params, [8123, 248230]);
return [[{ id_punto: 8123, id_estado_intermedio: 4, valor: null, foto: null }]];
}
assert.match(sql, /UPDATE c_viajes_puntos/);
return [{ affectedRows: 1 }];
};
const response = await withServer(async (server) =>
requestJson({
port: server.address().port,
method: 'POST',
path: '/api/trips/248230/status',
authorization: `Bearer ${createToken()}`,
body: {
id_estado: 5,
id_punto: 8123,
latitud: '40.416775',
longitud: '-3.703790'
}
})
);
assert.equal(response.statusCode, 200);
assert.equal(response.body.success, true);
assert.equal(response.body.agheera_push, undefined);
assert.equal(agheeraCalls.length, 0);
});
test('POST /api/trips/:id/status fallo de Agheera mantiene respuesta 200', async () => {
process.env.AGHEERA_API_KEY = 'test-api-key';
const agheeraCalls = [];
agheeraPushClient.__setHttpClientForTests(async (url, options) => {
agheeraCalls.push({ url, options });
return {
ok: false,
status: 500,
text: async () => 'temporary error'
};
});
let step = 0;
db.query = async (sql) => {
step += 1;
if (step === 1) {
return [[{ id_estado: 6 }]];
}
if (step === 2) {
return [[{ id_viaje: 248230, id_viaje_padre: 0, id_cliente: 532 }]];
}
if (step === 3) {
return [[{ n_proveedor: 1, id_proveedor: 675, matricula: '1234ABC' }]];
}
if (step === 4) {
assert.match(sql, /UPDATE c_viajes/);
return [{ affectedRows: 1 }];
}
assert.match(sql, /INSERT INTO c_cambios_estado/);
return [{ insertId: 6, affectedRows: 1 }];
};
const response = await withServer(async (server) =>
requestJson({
port: server.address().port,
method: 'POST',
path: '/api/trips/248230/status',
authorization: `Bearer ${createToken()}`,
body: {
id_estado: 6,
latitud: '40.416775',
longitud: '-3.703790'
}
})
);
assert.equal(response.statusCode, 200);
assert.equal(response.body.success, true);
assert.deepEqual(response.body.agheera_push, {
trip_id: 248230,
attempted: true,
success: false,
http_status: 500,
error: 'Agheera push failed'
});
assert.equal(agheeraCalls.length, 1);
});
test('POST /api/trips/:id/status estado intermedio con id_punto inválido => 400', async () => {
db.query = async () => {
throw new Error('db.query should not run for invalid id_punto');
@@ -2523,7 +2795,7 @@ test('DELETE /api/trips/:id/status en modo dual no borra foto en remoto ni local
const recorder = createSftpRecorder();
tripStatusPhotoStorage.__setSftpClientFactoryForTests(createFakeSftpClientFactory(recorder));
process.env.TRIP_STATUS_PHOTO_STORAGE_MODE = 'dual';
process.env.TRIP_STATUS_SFTP_HOST = 'localhost';
process.env.TRIP_STATUS_SFTP_HOST = '194.164.175.51';
process.env.TRIP_STATUS_SFTP_PORT = '22';
process.env.TRIP_STATUS_SFTP_USERNAME = 'ssh_fotos_estado';
process.env.TRIP_STATUS_SFTP_PASSWORD = 'test-password';