2016-06-07 00:37:09 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies.
|
|
|
|
*/
|
|
|
|
var mongoose = require('mongoose'),
|
|
|
|
config = require('../../config/config'),
|
|
|
|
errorHandler = require('../controllers/errors.server.controller'),
|
|
|
|
Form = mongoose.model('Form');
|
|
|
|
|
|
|
|
// Create the chat configuration
|
|
|
|
module.exports = function (io, socket) {
|
|
|
|
var visitorsData = {};
|
|
|
|
|
|
|
|
var saveVisitorData = function (data, cb){
|
|
|
|
|
|
|
|
Form.findById(data.formId, function(err, form) {
|
|
|
|
if (err) {
|
|
|
|
console.log(err);
|
|
|
|
throw new Error(errorHandler.getErrorMessage(err));
|
|
|
|
}
|
|
|
|
|
|
|
|
var newVisitor = {
|
|
|
|
referrer: data.referrer,
|
|
|
|
lastActiveField: data.lastActiveField,
|
|
|
|
timeElapsed: data.timeElapsed,
|
2016-06-17 21:51:17 +00:00
|
|
|
isSubmitted: data.isSubmitted,
|
|
|
|
language: data.language,
|
|
|
|
ipAddr: data.ipAddr,
|
|
|
|
deviceType: data.deviceType
|
2016-06-07 00:37:09 +00:00
|
|
|
};
|
2016-11-09 19:04:47 +00:00
|
|
|
|
2016-06-07 00:37:09 +00:00
|
|
|
form.analytics.visitors.push(newVisitor);
|
|
|
|
|
|
|
|
form.save(function (err) {
|
|
|
|
if (err) {
|
|
|
|
console.log(err);
|
|
|
|
throw new Error(errorHandler.getErrorMessage(err));
|
|
|
|
}
|
|
|
|
console.log('\n\nVisitor data successfully added!');
|
2016-11-09 19:04:47 +00:00
|
|
|
console.log(newVisitor);
|
2016-06-07 00:37:09 +00:00
|
|
|
|
|
|
|
delete visitorsData[socket.id];
|
|
|
|
|
|
|
|
if(cb) cb();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
socket.disconnect(0);
|
|
|
|
};
|
|
|
|
|
|
|
|
io.on('connection', function(socket) {
|
|
|
|
|
|
|
|
|
|
|
|
// a user has visited our page - add them to the visitorsData object
|
|
|
|
socket.on('form-visitor-data', function(data) {
|
2017-03-06 21:06:59 +00:00
|
|
|
socket.id = data.formId;
|
2016-06-07 00:37:09 +00:00
|
|
|
visitorsData[socket.id] = data;
|
2017-03-06 21:06:59 +00:00
|
|
|
visitorsData[socket.id].isSaved = false;
|
|
|
|
|
|
|
|
if (data.isSubmitted) {
|
|
|
|
saveVisitorData(data, function () {
|
|
|
|
console.log('\n\n user submitted form');
|
|
|
|
});
|
|
|
|
visitorsData[socket.id].isSaved = true;
|
|
|
|
socket.disconnect(0);
|
|
|
|
}
|
2016-06-07 00:37:09 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
socket.on('disconnect', function() {
|
2017-03-06 21:06:59 +00:00
|
|
|
console.log('\n\n\n\n\n DISCONNECTED SOCKET');
|
2016-06-07 00:37:09 +00:00
|
|
|
var data = visitorsData[socket.id];
|
|
|
|
|
|
|
|
if(data){
|
2017-03-06 21:06:59 +00:00
|
|
|
if(!data.isSubmitted && !data.isSaved) {
|
|
|
|
data.isSaved = true;
|
2016-06-07 00:37:09 +00:00
|
|
|
saveVisitorData(data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|