agmission/Others/scripts/updateAppStats.js

88 lines
3.5 KiB
JavaScript

Number.prototype.fixedDown = function(digits) {
var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
m = this.toString().match(re);
return m ? parseFloat(m[1]) : this.valueOf();
};
//{ $and: [{ totalSprayTime: null, totalSprayed : { $gt: 1 } }]}
var apps = db.applications.find({ $and: [{ totalFlightTime: null, totalSprayed : { $gt: 1 } }]}).toArray();
var app;
for(var k = 0; k < apps.length; k++) {
app = apps[k];
var totalSprTime = 0, totalTurn = 0, totalTime = 0;
var files = db.appfiles.find({ appId: app._id }).toArray();
for(var i = 0; i < files.length; i++) {
var turnTime = { line: null, at: null, nextOff: false, total: 0 };
var timeDif = 0, prevTime = prevSprTime = -999, record;
var details = db.application_details.find({ fileId: files[i]._id }, { _id: 0, gpsTime: 1, llnum: 1, sprayStat: 1 }).sort({ gpsTime: 1 }).toArray();
for(var j = 0; j < details.length; j++) {
record = details[j];
// Calculate total flight time
if (prevTime != -999 && prevTime !== record.gpsTime) {
timeDif = record.gpsTime - prevTime;
if (timeDif < 0) {
if (Math.abs(timeDif) >= 0.1)
timeDif = (86400 - prevTime) + record.gpsTime;
}
if (timeDif > 0 && timeDif <= 120)
totalTime += timeDif;
}
prevTime = record.gpsTime;
// Calculate spray time (secs)
if (record.sprayStat > 0) {
if (prevSprTime != -999 && record.sprayStat !== 3) {
timeDif = record.gpsTime - prevSprTime;
if (timeDif > 0 && timeDif <= 120)
totalSprTime += timeDif;
}
prevSprTime = record.gpsTime;
}
if (!(/.asc/i.test(files[i].name))) {
// Calculate turn time (secs)
if (null === turnTime.line && !record.sprayStat) {
turnTime.line = record.llnum;
turnTime.at = record.gpsTime;
continue;
}
if (turnTime.line != record.llnum) {
if (record.sprayStat) {
timeDif = record.gpsTime - turnTime.at;
if (timeDif < 0) {
if (Math.abs(timeDif) >= 0.1)
timeDif = (86400 - turnTime.at) + record.gpsTime;
}
if (timeDif >= 5 && timeDif <= 120)
turnTime.total += timeDif;
turnTime.line = record.llnum;
turnTime.nextOff = true;
}
}
else {
if (!record.sprayStat && turnTime.nextOff) {
turnTime.at = record.gpsTime;
turnTime.nextOff = false;
} else if (record.sprayStat) {
turnTime.nextOff = true;
}
}
}
}
if (!isNaN(turnTime.total))
totalTurn += turnTime.total;
}
// print ('app: ' + app._id + ', totalSpray: ' + totalSprTime + ', totalTurn: ' + totalTurn);
// Update the app with the calculated totals of: sprayTime and turnTurnTime
db.applications.updateOne({ _id: app._id },
{ $set : { totalSprayTime: totalSprTime.fixedDown(2), totalTurnTime: totalTurn.fixedDown(2), totalFlightTime: totalTime.fixedDown(2) } });
}
print ("DONE updating appStats :) for " + apps.length + " apps")