import {Meteor} from "meteor/meteor"; import { _ } from 'underscore'; import { Roles } from 'meteor/alanning:roles'; // console.log("Setting Up Admin...") if (Meteor.isServer) { Meteor.methods({ async 'admin.fixRecords'(input) { if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) { console.log("In Fix Records"); console.log("Deleting invalid records..."); // Delete any records missing key fields. await Meteor.Records.removeAsync({serial: {$exists: false}}); await Meteor.Records.removeAsync({deviceId: {$exists: false}}); await Meteor.Records.removeAsync({endTime: {$exists: false}}); console.log("Consolidating records..."); let emails = _.uniq((await Meteor.Records.find({}, { sort: {email: 1}, fields: {email: true} }).fetchAsync()).map(function (x) { return x.email; }), true); for(const email of emails) { // Find all records for the user sorted from oldest to newest. let records = await Meteor.Records.find({email}, {sort: {startTime: 1}}).fetchAsync(); let newRecords = []; let record = records[0]; for (let index = 1; index < records.length; index++) { let nextRecord = records[index]; if (record.deviceId === nextRecord.deviceId) { record.endTime = nextRecord.endTime; record.count += nextRecord.count; record.internalCount += nextRecord.internalCount; } else { if (!record.endTime) record.endTime = nextRecord.startTime; newRecords.push(record); record = nextRecord; } } newRecords.push(record); await Meteor.Records.removeAsync({email}); for (let index = 0; index < newRecords.length; index++) { await Meteor.Records.insertAsync(newRecords[index]); } } } }, }); } // console.log("Admin setup.")