WellNuo/backend/check-legacy-deployments.js
Sergei 1dd7eb8289 Remove hardcoded credentials and use environment variables
- Remove hardcoded database credentials from all scripts
- Remove hardcoded Legacy API tokens from backend scripts
- Remove hardcoded MQTT credentials from mqtt-test.js
- Update backend/.env.example with DB_HOST, DB_USER, DB_PASSWORD, DB_NAME
- Update backend/.env.example with LEGACY_API_TOKEN and MQTT credentials
- Add dotenv config to all scripts requiring credentials
- Create comprehensive documentation:
  - scripts/README.md - Root scripts usage
  - backend/scripts/README.md - Backend scripts documentation
  - MQTT_TESTING.md - MQTT testing guide
  - SECURITY_CREDENTIALS_CLEANUP.md - Security changes summary

All scripts now read credentials from backend/.env instead of hardcoded values.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-29 12:13:32 -08:00

230 lines
6.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Скрипт для проверки синхронизации deployments между WellNuo DB и Legacy API
*
* Проверяет:
* 1. Все beneficiaries в нашей БД
* 2. Их legacy_deployment_id
* 3. Существуют ли эти deployments в Legacy API
*/
const https = require('https');
const { Client } = require('pg');
require('dotenv').config();
// Legacy API credentials
const LEGACY_API = {
host: 'eluxnetworks.net',
path: '/function/well-api/api',
user: process.env.LEGACY_API_USERNAME || 'robster',
token: process.env.LEGACY_API_TOKEN
};
// WellNuo DB credentials
const DB_CONFIG = {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || '5432'),
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
connectionTimeoutMillis: 15000,
ssl: { rejectUnauthorized: false }
};
// Helper: make Legacy API request
function legacyRequest(params) {
return new Promise((resolve, reject) => {
const querystring = require('querystring');
const data = querystring.stringify({
user_name: LEGACY_API.user,
token: LEGACY_API.token,
...params
});
const options = {
hostname: LEGACY_API.host,
path: LEGACY_API.path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
try {
resolve(JSON.parse(body));
} catch (e) {
resolve({ error: 'Invalid JSON', raw: body.substring(0, 200) });
}
});
});
req.on('error', reject);
req.write(data);
req.end();
});
}
async function main() {
console.log('='.repeat(70));
console.log('ПРОВЕРКА СИНХРОНИЗАЦИИ DEPLOYMENTS: WellNuo DB ↔ Legacy API');
console.log('='.repeat(70));
console.log();
// 1. Получаем список deployments из Legacy API
console.log('1. Загружаем deployments из Legacy API...');
const legacyDeployments = await legacyRequest({
function: 'deployments_list',
first: '0',
last: '500'
});
const legacyIds = new Set();
if (legacyDeployments.result_list) {
legacyDeployments.result_list.forEach(d => legacyIds.add(d.deployment_id));
console.log(` Найдено ${legacyDeployments.result_list.length} deployments в Legacy API`);
console.log(` IDs: ${[...legacyIds].sort((a,b) => a-b).join(', ')}`);
} else {
console.log(' ОШИБКА: не удалось получить список из Legacy API');
console.log(' Response:', JSON.stringify(legacyDeployments));
}
console.log();
// 2. Подключаемся к WellNuo DB
console.log('2. Загружаем данные из WellNuo DB...');
const client = new Client(DB_CONFIG);
try {
await client.connect();
console.log(' Подключение к БД успешно');
// Получаем всех beneficiaries с их deployments
const result = await client.query(`
SELECT
b.id as beneficiary_id,
b.name as beneficiary_name,
b.equipment_status,
bd.id as deployment_id,
bd.name as deployment_name,
bd.legacy_deployment_id,
bd.is_primary
FROM beneficiaries b
LEFT JOIN beneficiary_deployments bd ON b.id = bd.beneficiary_id
ORDER BY b.id
`);
console.log(` Найдено ${result.rows.length} записей`);
console.log();
// 3. Анализ
console.log('3. АНАЛИЗ СИНХРОНИЗАЦИИ:');
console.log('-'.repeat(70));
console.log(
'Ben.ID'.padEnd(8) +
'Имя'.padEnd(20) +
'Deploy.ID'.padEnd(12) +
'Legacy ID'.padEnd(12) +
'Статус Legacy'
);
console.log('-'.repeat(70));
let okCount = 0;
let missingCount = 0;
let nullCount = 0;
const problems = [];
for (const row of result.rows) {
const legacyId = row.legacy_deployment_id;
const name = (row.beneficiary_name || '').substring(0, 18);
let status;
if (legacyId === null) {
status = '⚠️ NULL';
nullCount++;
problems.push({
beneficiaryId: row.beneficiary_id,
name,
deploymentId: row.deployment_id,
legacyId: null,
issue: 'legacy_deployment_id is NULL'
});
} else if (legacyIds.has(legacyId)) {
status = '✅ EXISTS';
okCount++;
} else {
status = '❌ NOT FOUND';
missingCount++;
problems.push({
beneficiaryId: row.beneficiary_id,
name,
deploymentId: row.deployment_id,
legacyId,
issue: `Legacy deployment ${legacyId} does not exist`
});
}
console.log(
String(row.beneficiary_id).padEnd(8) +
name.padEnd(20) +
String(row.deployment_id || '-').padEnd(12) +
String(legacyId || 'NULL').padEnd(12) +
status
);
}
console.log('-'.repeat(70));
console.log();
// 4. Итоги
console.log('4. ИТОГИ:');
console.log(` ✅ Синхронизированы: ${okCount}`);
console.log(` ⚠️ NULL legacy_id: ${nullCount}`);
console.log(`Не существуют: ${missingCount}`);
console.log();
if (problems.length > 0) {
console.log('5. ПРОБЛЕМНЫЕ ЗАПИСИ (нужно исправить):');
console.log('-'.repeat(70));
for (const p of problems) {
console.log(` Beneficiary #${p.beneficiaryId} (${p.name}):`);
console.log(` - WellNuo deployment_id: ${p.deploymentId}`);
console.log(` - legacy_deployment_id: ${p.legacyId}`);
console.log(` - Проблема: ${p.issue}`);
console.log();
}
}
// 5. Дополнительно: проверим устройства для проблемных deployments
if (problems.filter(p => p.legacyId !== null).length > 0) {
console.log('6. ПРОВЕРКА УСТРОЙСТВ ДЛЯ НЕСУЩЕСТВУЮЩИХ DEPLOYMENTS:');
console.log('-'.repeat(70));
for (const p of problems.filter(p => p.legacyId !== null)) {
const devicesResp = await legacyRequest({
function: 'device_list_by_deployment',
deployment_id: String(p.legacyId),
first: '0',
last: '50'
});
const deviceCount = devicesResp.result_list ? devicesResp.result_list.length : 0;
console.log(` Legacy deployment ${p.legacyId}: ${deviceCount} устройств`);
}
}
} catch (error) {
console.error(' ОШИБКА БД:', error.message);
} finally {
await client.end();
}
console.log();
console.log('='.repeat(70));
console.log('Проверка завершена');
}
main().catch(console.error);