73 lines
2.7 KiB
JavaScript
73 lines
2.7 KiB
JavaScript
require('dotenv').config();
|
||
const ZKLib = require('zklib-js');
|
||
const axios = require('axios');
|
||
|
||
const ZKTECO_IP = process.env.ZKTECO_IP || '192.168.0.201';
|
||
const ZKTECO_PORT = process.env.ZKTECO_PORT || 4370;
|
||
const SERVER_API_URL = process.env.SERVER_API_URL || 'https://scxsoftware.com/api/zkteco/sync';
|
||
const API_KEY = process.env.API_KEY || '';
|
||
const BRANCH_ID = process.env.BRANCH_ID || '';
|
||
|
||
async function syncAttendance() {
|
||
console.log(`[${new Date().toLocaleString()}] Starting ZKTeco Sync...`);
|
||
console.log(`Target Device: ${ZKTECO_IP}:${ZKTECO_PORT}`);
|
||
|
||
const zkInstance = new ZKLib(ZKTECO_IP, ZKTECO_PORT, 10000, 4000);
|
||
|
||
try {
|
||
await zkInstance.createSocket();
|
||
console.log('✅ Connected to ZKTeco device.');
|
||
|
||
console.log('Fetching attendance records...');
|
||
const attendances = await zkInstance.getAttendances();
|
||
|
||
if (attendances && attendances.data && attendances.data.length > 0) {
|
||
console.log(`✅ Found total ${attendances.data.length} records on device.`);
|
||
|
||
// Filter to last 15 days
|
||
const fifteenDaysAgo = new Date();
|
||
fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 15);
|
||
|
||
const recentLogs = attendances.data.filter(log => {
|
||
const logDate = new Date(log.recordTime);
|
||
return logDate >= fifteenDaysAgo;
|
||
});
|
||
|
||
console.log(`✅ Filtered to ${recentLogs.length} records from the last 15 days.`);
|
||
|
||
if (recentLogs.length > 0) {
|
||
console.log(`Pushing to Cloud API: ${SERVER_API_URL}`);
|
||
const response = await axios.post(SERVER_API_URL, {
|
||
api_key: API_KEY,
|
||
branch_id: BRANCH_ID,
|
||
zkteco_ip: ZKTECO_IP,
|
||
attendances: recentLogs
|
||
});
|
||
console.log('✅ Sync Successful:', response.data);
|
||
}
|
||
} else {
|
||
console.log('ℹ️ No attendance records found on device.');
|
||
}
|
||
|
||
} catch (e) {
|
||
console.error('❌ Error during sync:', e.message);
|
||
if (e.response && e.response.data) {
|
||
console.error('API Response:', e.response.data);
|
||
}
|
||
} finally {
|
||
try {
|
||
await zkInstance.disconnect();
|
||
console.log('Disconnected from ZKTeco device.');
|
||
} catch (err) {}
|
||
|
||
// Keep window open for user to read logs
|
||
console.log('\nPress any key to exit...');
|
||
process.stdin.setRawMode(true);
|
||
process.stdin.resume();
|
||
process.stdin.on('data', process.exit.bind(process, 0));
|
||
}
|
||
}
|
||
|
||
// Execute the sync
|
||
syncAttendance();
|