import con from '../db/connect.js'; import conMaster from '../db/connectMaster.js'; import fs from 'node:fs'; export default async uniqueRead => { const reads = new Set([ ...uniqueRead[0], ...uniqueRead[1], ...uniqueRead[2], ...uniqueRead[3], ]); console.log('reads: ', [...reads][0]); let [[palletFk]] = await conMaster.query( `SELECT palletFk FROM expeditionScan WHERE expeditionFk IN (?)`, [[...reads].join(',')] ); palletFk = palletFk?.palletFk; console.log('palletFk: ', palletFk); if (!palletFk) return console.log('LA EXPEDICION NO esta en el pallet'); let [realExpeditions] = await conMaster.query( `SELECT ep.id, e.id, ps.printerRfidFk, ps.code, es.palletFk FROM expeditionPallet ep JOIN expeditionScan es ON es.palletFk = ep.id JOIN expedition e ON e.id = es.expeditionFk JOIN host h ON h.code = e.hostFk COLLATE utf8mb3_unicode_ci JOIN packingSite ps ON ps.hostFk = h.id WHERE ep.id = ? AND ps.printerRfidFk`, [palletFk] ); realExpeditions = realExpeditions.map(r => r.id); console.log('realExpeditions: ', realExpeditions.length); if (realExpeditions.length != reads.size) console.logger.warn('MISSING EXPEDITIONS'); const missing = realExpeditions.filter(x => ![...reads].includes(x)); const extra = [...reads].filter(x => !realExpeditions.includes(x)); if (missing.length) console.warn('MISSING:', missing.length, missing); if (extra.length) console.warn('EXTRA:', extra.length, extra); try { const [[currentMissings]] = await con.query('SELECT missing FROM trys WHERE palletFk = ?', palletFk); if (currentMissings?.missing < missing.length) return console.log('PREVENT REPLACE', currentMissings.missing, missing.length); await con.query( ` REPLACE trys SET palletFk = ?, missing = ?, extra = ?, total = ?, powerType = ?, observationExtra = ?, observationMissing = ?, antenna1 = ?, antenna2 = ?, antenna3 = ?, antenna4 = ? `, [ palletFk, missing.length, extra.length, realExpeditions.length, 'VDT3', extra.join(','), missing.join(','), uniqueRead[0].size, uniqueRead[1].size, uniqueRead[2].size, uniqueRead[3].size, ] ); await saveTable(); } catch (e) { console.log('error debugging', palletFk, e); } }; async function saveTable() { const [table] = await con.query(`SELECT * FROM trys WHERE DATE(timestamp) = CURDATE()`); const date = new Date().toISOString().split('T')[0]; if (!table.length) return; const file = fs.createWriteStream(`${date}.txt`); file.on('error', function(err) { console.error(err); }); table.forEach(function(v) { file.write(JSON.stringify(v) + '\n'); }); file.end(); }