diff --git a/dataprocessing.js b/dataprocessing.js deleted file mode 100644 index 9a9a035..0000000 --- a/dataprocessing.js +++ /dev/null @@ -1,3112 +0,0 @@ - -var mongoose = require('mongoose'); -const FLUCTUATION_THRESHOLD = 50 / 1000; -const ObjectID = require('mongodb').ObjectID; -var Notifs = require('./app_api/models/notifications'); -var MongoClient = require('mongodb').MongoClient -var f = require('./gpsFunctions'); -var crc = require('crc'); -var pushNotifs = require('./notify') -var Device = require('./app_api/models/device'); -var cmdPackets = require('./app_api/models/cmdPackets') -var GeoFence = require('./app_api/models/geofence') -var Route = require('./app_api/models/trackRoute'); -var RouteMap = require('./app_api/models/routeDeviceMap') -var Groups = require('./app_api/models/group'); -var GPS = require('./app_api/models/gps') -//var gpsio = gpsIo -var moment = require('moment-timezone'); -var Mailer = require('./app_api/controllers/mailer'); -var OutgoingIntegrations = require('./outgoingIntegrations'); -var GeofenceReports = require('./app_api/models/geofenceReports'); -var GPS_x03 = require('./GPS_x03'); -//var geoFenceio = geoFenceIo -var TCPUTIL = require('./tcpUtil'); -var Utilities = require('./app_api/controllers/utilities.controller'); -var request = require('request'); -var KafkaService = require('./kafka-producer'); -var url = 'mongodb://'+Utilities.getConfig().dbUserName+':'+Utilities.getConfig().dbPassUrlEncoded+'@'+Utilities.getConfig().dbDomain+':'+Utilities.getConfig().dbPort+'/IOT?authSource='+Utilities.getConfig().dbAuthSource; -var dbOption = { - //user : Utilities.getConfig().dbUserName, - //pass : Utilities.getConfig().dbPass -}; - - -function parseYantraData(raw) { - console.log('yantra') - try { - var rawWOHeadFoot = raw.substring(1); - rawWOHeadFoot = rawWOHeadFoot.substring(0, rawWOHeadFoot.length - 1); - var rawArray = rawWOHeadFoot.split(','); - var latDecimal = rawArray[5] == 'N' ? - parseFloat(rawArray[4].substring(0, 2)) + parseFloat((rawArray[4].substring(2, 9) / 60)) : - (parseFloat(rawArray[4].substring(0, 2)) + parseFloat((rawArray[4].substring(2, 9) / 60))) * -1; - var longDecimal = rawArray[7] == 'E' ? - parseFloat(rawArray[6].substring(0, 3)) + parseFloat((rawArray[6].substring(3, 10) / 60)) : - (parseFloat(rawArray[6].substring(0, 3)) + parseFloat((rawArray[6].substring(3, 10) / 60))) * -1; - /* var ac=rawArray[12].substring(4,6); - var ac1 = (parseInt(ac, 16).toString(2)); - while (ac1.length < 8) { - ac1 = '0' + ac1; - } - ac1 = ac1.substr(5, 1); - var power = rawArray[12].substring(2, 4); - - var power1 = parseInt(power, 16).toString(2); - while (power1.length < 8) { - power1 = '0' + power1; - } - power1 = power1.substr(4, 1); */ - return { - "imei": rawArray[0], - "command": '$', - "date": rawArray[2] ? new Date(parseInt('20' + - rawArray[2].substring(4, 6)), - parseInt(rawArray[2].substring(2, 4) - 1), - parseInt(rawArray[2].substring(0, 2)), - parseInt(rawArray[3].substring(0, 2)), - parseInt(rawArray[3].substring(2, 4)), - parseInt(rawArray[3].substring(4, 6)) - ) : null, - "dateString": rawArray[2], - "latDirection": rawArray[5], - "longDirection" : rawArray[7], - "latDegrees": rawArray[4] + rawArray[5], - "longDegrees": rawArray[6] + rawArray[7], - "latDecimal": latDecimal, - "longDecimal": longDecimal, - "insertionTime": new Date(), - "raw": raw, - "valid": rawArray[1], - "speed": (parseFloat(rawArray[8])).toFixed(2), - "odo" : parseFloat(rawArray[9]), - "timeString": rawArray[3], - "heading": rawArray[10], - "satellites": rawArray[11], - "gsmSignal": rawArray[12], - "DIN1": rawArray[14], - "DIN2" : rawArray[15], - "ignition": rawArray[13], - "boxStatus" : rawArray[17], - "GPS positioned": rawArray[16], - "batteryStatus" : rawArray[18], - "geoJSON": { - "type": "Point", - "coordinates": [ longDecimal, latDecimal ] - } - } -} catch (err) { - console.error("exception handled"); - console.error(err); -} -} - -function parseRawGpsVTX(raw) -{ - var rawArray = raw.split('&'); - var latDecimal = rawArray[3].split(',')[3].charAt(rawArray[3].split(',')[3].length-1) == 'N' ?parseFloat(rawArray[3].split(',')[3].substring(0,2)) + parseFloat((rawArray[3].split(',')[3].substring(2, 9) / 60)):(parseFloat(rawArray[3].split(',')[3].substring(0,2)) + parseFloat((rawArray[3].split(',')[3].substring(2, 9) / 60)))* -1; - var longDecimal = rawArray[3].split(',')[4].charAt(rawArray[3].split(',')[4].length-1) == 'E' ?parseFloat(rawArray[3].split(',')[4].substring(0,3)) + parseFloat((rawArray[3].split(',')[4].substring(3, 10) / 60)):(parseFloat(rawArray[3].split(',')[4].substring(0,3)) + parseFloat((rawArray[3].split(',')[4].substring(3, 10) / 60))) * -1; - - return { - "imei": rawArray[0].split(',')[1], - "command": 'VTX', - "date": new Date(parseInt('20' + - rawArray[3].split(',')[7].substring(4,6)), - parseInt(rawArray[3].split(',')[7].substring(2,4) - 1), - parseInt(rawArray[3].split(',')[7].substring(0,2)), - parseInt(rawArray[3].split(',')[1].substring(0,2)), - parseInt(rawArray[3].split(',')[1].substring(2,4)), - parseInt(rawArray[3].split(',')[1].substring(4,6)) - ), - "dateString": rawArray[3].split(',')[7], - "latDegrees": rawArray[3].split(',')[3], - "longDegrees":rawArray[3].split(',')[4], - "latDecimal": latDecimal, - "longDecimal": longDecimal, - "insertionTime": new Date(), - "raw": raw, - "valid": rawArray[3].split(',')[2], - "speed": rawArray[3].split(',')[5], - "timeString": rawArray[3].split(',')[1], - "heading": rawArray[3].split(',')[6], - "GPS positioned":((rawArray[6]=='A')?1:0), - "ignition":rawArray[3].split(',')[10]=='1'?'0':'1', - "geoJSON": { - "type": "Point", - "coordinates": [longDecimal,latDecimal] - } -} -} - -function parseRawGpsTs(raw,type) -{ - var raw1=raw.substring(0, raw.length - 2); - var rawArray = raw.split(','); - if(type=='first') - { - - } - else if(type=='rest') - { - - return { - "imei": rawArray[1], - "command": 'TS', - "date": new Date(parseInt('20' + - rawArray[5].substring(0,2)), - parseInt(rawArray[5].substring(2,4) - 1), - parseInt(rawArray[5].substring(4,6)), - parseInt(rawArray[5].substring(6,8)), - parseInt(rawArray[5].substring(8,10)), - parseInt(rawArray[5].substring(10,12)) - ), - "dateString": rawArray[5].substring(0,6), - "latDecimal": Number(rawArray[3]), - "longDecimal": Number(rawArray[4]), - "insertionTime": new Date(), - "raw": raw, - "valid": rawArray[6], - "speed": rawArray[8], - "timeString": rawArray[5].substring(6,12), - "heading": rawArray[10], - "GPS positioned":((rawArray[6]=='A')?1:0), - "ignition":rawArray[27], - "gsmSignal":rawArray[7], - "power":rawArray[23]=='0'?'1':'0', - "satellites":rawArray[11], - "batteryStatus":rawArray[48], - "gpsTracking":((rawArray[6]=='A')?'1':'0'), - "geoJSON": { - "type": "Point", - "coordinates": [rawArray[4],rawArray[3]] - } - } - -} -} - -function parseRawGpsGB(raw,gpsModel) -{ - if(gpsModel == 'GB') - { - try { - - var rawArray = raw.split(','); - var latstring=rawArray[4].split(':')[1]; - var lat=(parseFloat(latstring.substring(0,2))+parseFloat(latstring.substring(2,9)/60)); - - var longstring=rawArray[5].split(':')[1]; - var long=(parseFloat(longstring.substring(0,3))+parseFloat(longstring.substring(3,10)/60)); - - return { - "imei": rawArray[0].split(':')[1], - "command": 'GB', - "date": rawArray[11] ? new Date(parseInt('20' + - rawArray[7].split(':')[1].substring(4,6)), - parseInt(rawArray[7].split(':')[1].substring(2,4) - 1), - parseInt(rawArray[7].split(':')[1].substring(0,2)), - - parseInt(rawArray[3].split(':')[1].substring(0,2)), - parseInt(rawArray[3].split(':')[1].substring(2,4)), - parseInt(rawArray[3].split(':')[1].substring(4,6)) - ) : null, - "dateString": rawArray[7].split(':')[1], - "latDegrees": rawArray[4].split(':')[1], - "longDegrees": rawArray[5].split(':')[1], - "latDecimal": lat, - "longDecimal": long, - "insertionTime": new Date(), - "raw": raw, - "valid": rawArray[10].split(':')[1].charAt(7), - "speed": (parseFloat(rawArray[6].split(':')[1]).toFixed(2)), - "timeString": rawArray[3].split(':')[1], - "heading": rawArray[12].split(':')[1].substring(0, rawArray[12].split(':')[1].length - 2), - "GPS positioned":((rawArray[10].split(':')[1].charAt(7)=='A')?1:0), - "ignition": rawArray[9].split(':')[1].charAt(0), - "ac": rawArray[9].split(':')[1].charAt(3), - "sos" : rawArray[9].split(':')[1].charAt(1) == "1" ? true : false, - "debug" : rawArray[9].split(':')[1].charAt(4), - "batteryStatus": rawArray[1].split(':')[1], - "power":rawArray[9].split(':')[1].charAt(5), - "gpsTracking":((rawArray[10].split(':')[1].charAt(7)=='A')?'1':'0'), - "geoJSON": { - "type": "Point", - "coordinates": [long, lat] - } - } - } catch (err) { - console.error("exception handled"); - console.error(err); - } -} -} -function parseRawGpsL(raw) -{ - - try { - - var rawArray = raw.split(','); - var lat=(parseFloat(rawArray[4].substring(0,2))+parseFloat(rawArray[4].substring(2,9)/60)); - var long=(parseFloat(rawArray[6].substring(0,3))+parseFloat(rawArray[6].substring(3,10)/60)); - - return { - "imei": rawArray[0].substring(11), - "command": 'L100', - "date": new Date (Number(rawArray[2])).toISOString().replace('T',' '), - "dateString": new Date(parseInt('20' + - str.split(',')[10].substring(4,6)), - parseInt(str.split(',')[10].substring(2,4) - 1), - parseInt(str.split(',')[10].substring(0,2))), - "latDegrees": rawArray[4]+rawArray[5], - "longDegrees": rawArray[6]+rawArray[7], - "latDecimal": lat, - "longDecimal": long, - "insertionTime": new Date(), - "raw": raw, - "valid": rawArray[3], - "speed": (parseFloat(Number(rawArray[8])*1.85).toFixed(2)), - "timeString": Number(rawArray[2]), - "heading": rawArray[9], - "ignition":rawArray[14].charAt(1), - "geoJSON": { - "type": "Point", - "coordinates": [long, lat] - } - } - } catch (err) { - console.error("exception handled"); - console.error(err); - } - -} - -function parseT8803_data(raw, parsedHead) { - data = Buffer.from(data).toString('hex'); - var date = new Date( - parseInt(data.substr(88, 2), 16) + 2000, - parseInt(data.substr(90, 2), 16) - 1, - parseInt(data.substr(92, 2), 16), - parseInt(data.substr(94, 2), 16), - parseInt(data.substr(96, 2), 16), - parseInt(data.substr(98, 2), 16) - ) - - var course_status = parseInt(data.substr(128, 4), 16).toString(2); - var latitude = Buffer(str.substr(116, 8), 'hex').readFloatBE(0); - var longitude = Buffer(str.substr(108, 8), 'hex').readFloatBE(0); - var speedHex = str.substr(124, 4); - var speed = [speedHex.slice(0, 3), '.', speedHex.slice(3)].join(''); - var gpsPositionedData = parseInt(str.substr(48, 2), 16).toString(2); - var gpsPositioned = gpsPositionedData.charAt(0) == '0' ? '1' : '0'; - var digitalIOData = parseInt(str.substr(62, 4), 16).toString(2); - var ignition = digitalIOData.charAt(1) == '1' ? 1 : 0; - - return { - "imei": parseInt(str.substr(14,16)), - "command": parsedHead.protocal_id, - "date": date, - "dateString": str.substr(88, 6), - "latDecimal": latitude, - "longDecimal": longitude, - "insertionTime": new Date(), - "raw": raw.toString('hex'), - "speed": speed, - "timeString": str.substr(94, 6), - "heading": course_status, - "geoJSON": { - "type": "Point", - "coordinates": [longitude, latitude ] - }, - //'MCC': parseInt(str.substr(36, 4), 16), - //'MNC': parseInt(str.substr(40, 2), 16), - //'LAC': parseInt(str.substr(42, 4), 16), - //'CellT ID': parseInt(str.substr(46, 6), 16), - //'lbs': str.substr(36, 16), - //'real-time gps': course_status.substr(0, 1), - 'GPS positioned': course_status.substr(1, 1), - 'ignition' : ignition - //'satellites': parseInt(str.substr(13, 1), 16) - } -} -function authorizeT8803(device_id, socket) { - socket.imei = parseInt(device_id) - var loginResponse = '232301000F0001' + device_id; - socket.write(new Buffer(loginResponse, 'hex')); -} - -function respond_T8803_heartbeat(device_id, socket) { - socket.imei = parseInt(device_id) - var heartbeatResponse = '232303000F0001' + device_id; - socket.write(new Buffer(heartbeatResponse, 'hex')); -} -function parseT8803_head(raw, socket) { - data = Buffer.from(data).toString('hex') - var parts = { - 'start': data.substr(0, 4) - }; - - if (parts['start'] == '2323') { - parts['length'] = parseInt(data.substr(6, 4), 16); - //parts['finish'] = data.substr(6 + parts['length'] * 2, 4); - parts['protocal_id'] = data.substr(4, 2); - if (parts['protocal_id'] == '01') { - parts['device_id'] = data.substr(14, 16); - parts.cmd = 'login_request'; - parts.action = 'login_request'; - } else if (parts['protocal_id'] == '02') { - parts['device_id'] = socket.imei || data.substr(14, 16); - parts['data'] = data.substr(30); - parts.cmd = 'ping'; - parts.action = 'ping'; - } else if (parts['protocal_id'] == '03') { - parts['device_id'] = socket.imei || data.substr(14, 16); - parts['data'] = data.substr(30); - parts.cmd = 'heartbeat'; - parts.action = 'heartbeat'; - } else if (parts['protocal_id'] == '04') { - parts['device_id'] = socket.imei || ''; - parts['data'] = data.substr(8, parts['length'] * 2); - parts.cmd = 'alert'; - parts.action = 'alert'; - } else { - parts['device_id'] = socket.imei || ''; - parts.cmd = 'noop'; - parts.action = 'noop'; - } - } - else { - parts['device_id'] = ''; - parts.cmd = 'noop'; - parts.action = 'noop'; - } - return parts; -} - -function parseGM06_Head(data, socket) { - data = Buffer.from(data).toString('hex') - var parts = { - 'start': data.substr(0, 4) - }; - - if (parts['start'] == '6767') { - parts['protocal_id'] = data.substr(4, 2); - parts['length'] = parseInt(data.substr(6, 4), 16); - //parts['finish'] = data.substr(6 + parts['length'] * 2, 4); - if (parts['protocal_id'] == '01') { - parts['device_id'] = data.substr(15, 15); - parts.cmd = 'login_request'; - parts.action = 'login_request'; - } else if (parts['protocal_id'] == '02') { - parts['device_id'] = socket.imei || ''; - parts['data'] = data.substr(14, parts['length'] * 2); - parts.cmd = 'ping'; - parts.action = 'ping'; - } else if (parts['protocal_id'] == '03') { - parts['device_id'] = socket.imei || ''; - parts.cmd = 'heartbeat'; - parts['data'] = data/* .substr(8, 10) */; - parts.action = 'heartbeat'; - } else { - parts['device_id'] = socket.imei || ''; - parts.cmd = 'noop'; - parts.action = 'noop'; - } - } - else { - parts['device_id'] = ''; - parts.cmd = 'noop'; - parts.action = 'noop'; - } - return parts; -}; - -function authorizeGM06(socket, request, raw) { - socket.imei = socket.imei || parseInt(request.device_id); - console.log('6767010002' + Buffer.from(raw, 'hex').toString('hex').substr(10, 4)); - socket.write('6767010002' + Buffer.from(raw, 'hex').toString('hex').substr(10,4), 'hex'); -}; - -function get_GM06_ping_data(msg_parts, raw, socket) { - var str = msg_parts.data; - var date = new Date( - parseInt(str.substr(0, 8), 16) * 1000 - ) - - var latitude = dex_to_degrees(str.substr(8, 8), 0); - var longitude = dex_to_degrees(str.substr(16, 8), 0); - var gps = parseInt(str.substr(48, 1), 2).toString(); - gps = gps.charAt(gps.length-1) - - - - - - - return { - "imei": socket.imei.toString(), - "command": msg_parts.protocal_id, - "date": date, - "dateString": str.substr(0, 6), - "latDecimal": latitude, - "longDecimal": longitude, - "insertionTime": new Date(), - "raw": raw.toString('hex'), - "speed": parseInt(str.substr(24, 2), 16).toString(), - "timeString": str.substr(6, 6), - "heading": parseInt(str.substr(26, 4), 16).toString(), - "geoJSON": { - "type": "Point", - "coordinates": [longitude, latitude ] - }, - 'GPS positioned': gps - } -}; - -function receive_GM06_heartbeat(raw, socket) { - socket.write('6767030002' + Buffer.from(raw, 'hex').toString('hex').substr(10,4), 'hex'); -}; - - -function parseVT1000(raw) -{ - var gsm1=str.substring(str.length-20); - var gsmval=gsm1.substring(6,8); - var latstring=raw.substring(31,38)/1000; - var lat=(parseFloat(latstring.toString().substring(0,2))+parseFloat(latstring.toString().substring(2,7)/60)); - - var longstring=raw.substring(38,46)/1000; - var long=(parseFloat(longstring.toString().substring(0,2))+parseFloat(longstring.toString().substring(2,7)/60)); - - var locationStatusBits = parseInt(raw.substr(54, 2), 16).toString(2); - while(locationStatusBits.length < 8) { - locationStatusBits = "0" + locationStatusBits; - } - var alarmPacket = raw.substr(62, 8); - var alarm1Packet = alarmPacket.substr(0, 2); - var alarm1PacketBits = parseInt(alarm1Packet, 16).toString(2); - while(alarm1PacketBits.length < 8) { - alarm1PacketBits = "0" + alarm1PacketBits; - } - var io=raw.substring(62,70).charAt(7); - return { - "imei": raw.substring(10,18), - "command": raw.substring(4,6), - "date": new Date(parseInt('20' + - raw.substring(18, 20)), - parseInt(raw.substring(20, 22) - 1), - parseInt(raw.substring(22, 24)), - parseInt(raw.substring(24, 26)), - parseInt(raw.substring(26, 28)), - parseInt(raw.substring(28, 30)) - ), - "dateString": raw.substring(18, 24), - //"latDecimal": raw.substring(31,38)/100000, - // "longDecimal": raw.substring(38,46)/100000, - "latDecimal": lat, - "longDecimal": long, - "insertionTime": new Date(), - "raw": raw, - "speed": raw.substring(46,50), - "timeString": raw.substring(24,30), - "heading": raw.substring(50, 54), - "GPS positioned": locationStatusBits.charAt(0), - "alarm1PacketBits": alarm1PacketBits, - "locationStatusBits" : locationStatusBits, - "ignition": alarm1PacketBits.charAt(0) == '1' ? '0' : '1', - "power" : alarm1PacketBits.charAt(4) == '1' ? '0' : '1', - "gsmSignal":gsmval, - "geoJSON": { - "type": "Point", - "coordinates": [ long, lat ] - } -} -} - -function fmb_login(hexString, socket) { - - - //disable nagle's algorithm which prevents packets from being sent immediately - //socket.setNoDelay(true); - var imei_scramble = hexString.substr(4); - var imei = ''; - for (var i = 0; i < imei_scramble.length; i++){ - if (i % 2 != 0) { - imei += imei_scramble.charAt(i); - } - } - socket.imei = imei; - socket.write(new Buffer('01', 'hex'), function (z) { - //console.log('fmb accepted') - }); -} - -function parseFmbData(hexString, socket) { - - var allData = []; - - var imei = socket.imei; - var command = hexString.substr(16, 2); - var number_of_data = parseInt(hexString.substr(18, 2), 16) - var startIndex = 20; - for (var q = 1; q <= number_of_data; q++){ - var data = {} - data.startIndex = startIndex; - data.command = command; - data.number_of_data = number_of_data; - data.imei = socket.imei; - data.date = new Date(parseInt(hexString.substr(startIndex + 0, 16), 16)); - data.priority = hexString.substr(startIndex + 16, 2); - var longDecimal = parseInt(hexString.substr(startIndex + 18, 8), 16) / 10000000; - var latDecimal = parseInt(hexString.substr(startIndex + 26, 8), 16) / 10000000; - data.raw = hexString; - data.latDecimal = latDecimal; - data.longDecimal = longDecimal; - data.geoJSON = { - "type": "Point", - "coordinates": [longDecimal, latDecimal] - }; - data.insertionTime = new Date(); - data.altitude = hexString.substr(startIndex + 34, 4) - data.heading = hexString.substr(startIndex + 38, 4); - data.satellites = hexString.substr(startIndex + 42, 2); - data.speed = parseInt(hexString.substr(startIndex + 44, 4), 16).toString(); - data.eventId = parseInt(hexString.substr(startIndex + 48, 2),16); - data.numOfIO = parseInt(hexString.substr(startIndex + 50, 2), 16); - - - //1 byte IO - var num1ByteIO = parseInt(hexString.substr(startIndex + 52, 2), 16); - data.num1ByteIO = num1ByteIO - var _1ByteIO = hexString.substr(startIndex + 54, (num1ByteIO + (num1ByteIO * 1)) * 2); - data._1ByteIO = _1ByteIO - - for (var i = 0; i <= num1ByteIO; i++){ - var IoElement = _1ByteIO.substr(i * 4, 2); - var IoValue = _1ByteIO.substr((i * 4) + 2, 2); - - //digital in - if (parseInt(IoElement, 16) == 1) { - data.ignition = parseInt(IoValue, 16).toString(); - } - //GNSS status - if (parseInt(IoElement, 16) == 69) { - data['GPS positioned'] = parseInt(IoValue, 16).toString(); - } - } - - - - //2 byte IO - var num2ByteIOIndex = startIndex + 54 + ((num1ByteIO + (num1ByteIO * 1)) * 2); - data.num2ByteIOIndex = num2ByteIOIndex; - var num2ByteIO = parseInt(hexString.substr(num2ByteIOIndex, 2), 16); - data.num2ByteIO = num2ByteIO; - - var _2ByteIO = hexString.substr(num2ByteIOIndex + 2, (num2ByteIO * 6)); - data._2ByteIO = _2ByteIO; - - for (var i = 0; i <= num2ByteIO; i++){ - var IoElement = _2ByteIO.substr(i * 6, 2); - var IoValue = _2ByteIO.substr((i * 6) + 2, 4); - - //analog in - if (parseInt(IoElement, 16) == 9) { - data.fuelVoltage = parseInt(IoValue, 16); - } - //ext voltage - if (parseInt(IoElement, 16) == 66) { - data.power = parseInt(IoValue, 16) == 0 ? '0' : '1'; - } - - } - - //4 byte IO - var num4ByteIOIndex = num2ByteIOIndex + ((num2ByteIO * 6/* + (num2ByteIO * 1) */) + 2); - data.num4ByteIOIndex = num4ByteIOIndex; - var num4ByteIO = parseInt(hexString.substr(num4ByteIOIndex, 2), 16); - data.num4ByteIO = num4ByteIO; - - var _4ByteIO = hexString.substr(num4ByteIOIndex + 2, (num4ByteIO * 10)); - startIndex = num4ByteIOIndex + 2 + 2 + (num4ByteIO * 10); - data._4ByteIO = _4ByteIO; - - for (var i = 0; i <= num4ByteIO; i++){ - var IoElement = _4ByteIO.substr(i * 10, 2); - var IoValue = _4ByteIO.substr((i * 10) + 2, 8); - - //analog in - if (parseInt(IoElement, 16) == 16) { - data.odo = parseInt(IoValue, 16) / 1000; - } - - - } - allData.push(data); - } - - var latest = allData[0]; - - if (allData.length > 1) { - Device.findOne({ Device_ID: latest.imei }, function (err, device) { - if(err){ - console.error(err); - } - else if(device) { - allData.shift(); - for (var z = 0; z < allData.length; z++){ - allData[z].group = device.vehicleGroup; - allData[z].vehicle = device.vehicle; - } - GPS.insertMany(allData, { ordered: false }, function (err, docs) { - }) - } - }) - } - - return latest; -} -function numHex(s) -{ - var a = s.toString(16); - if( (a.length % 2) > 0 ){ a = "0" + a; } - return a; -} -function sendFmbAck(socket, number_of_data) { - number_of_data_encoded = parseInt(number_of_data).toString(16); - while (number_of_data_encoded.length < 8) { - number_of_data_encoded = '0' + number_of_data_encoded; - } - var packet = new Buffer(number_of_data_encoded, 'hex'); - socket.write(packet); -} - - - -function crc16(buf) { - - var crcTable = - [ - 0X0000, 0X1189, 0X2312, 0X329B, 0X4624, 0X57AD, 0X6536, 0X74BF, 0X8C48, 0X9DC1, 0XAF5A, - 0XBED3, 0XCA6C, 0XDBE5, 0XE97E, 0XF8F7, 0X1081, 0X0108, 0X3393, 0X221A, 0X56A5, 0X472C, - 0X75B7, 0X643E, 0X9CC9, 0X8D40, 0XBFDB, 0XAE52, 0XDAED, 0XCB64, 0XF9FF, 0XE876, 0X2102, - 0X308B, 0X0210, 0X1399, 0X6726, 0X76AF, 0X4434, 0X55BD, 0XAD4A, 0XBCC3, 0X8E58, 0X9FD1, - 0XEB6E, 0XFAE7, 0XC87C, 0XD9F5, 0X3183, 0X200A, 0X1291, 0X0318, 0X77A7, 0X662E, 0X54B5, - 0X453C, 0XBDCB, 0XAC42, 0X9ED9, 0X8F50, 0XFBEF, 0XEA66, 0XD8FD, 0XC974, 0X4204, 0X538D, - 0X6116, 0X709F, 0X0420, 0X15A9, 0X2732, 0X36BB, 0XCE4C, 0XDFC5, 0XED5E, 0XFCD7, 0X8868, - 0X99E1, 0XAB7A, 0XBAF3, 0X5285, 0X430C, 0X7197, 0X601E, 0X14A1, 0X0528, 0X37B3, 0X263A, - 0XDECD, 0XCF44, 0XFDDF, 0XEC56, 0X98E9, 0X8960, 0XBBFB, 0XAA72, 0X6306, 0X728F, 0X4014, - 0X519D, 0X2522, 0X34AB, 0X0630, 0X17B9, 0XEF4E, 0XFEC7, 0XCC5C, 0XDDD5, 0XA96A, 0XB8E3, - 0X8A78, 0X9BF1, 0X7387, 0X620E, 0X5095, 0X411C, 0X35A3, 0X242A, 0X16B1, 0X0738, 0XFFCF, - 0XEE46, 0XDCDD, 0XCD54, 0XB9EB, 0XA862, 0X9AF9, 0X8B70, 0X8408, 0X9581, 0XA71A, 0XB693, - 0XC22C, 0XD3A5, 0XE13E, 0XF0B7, 0X0840, 0X19C9, 0X2B52, 0X3ADB, 0X4E64, 0X5FED, 0X6D76, - 0X7CFF, 0X9489, 0X8500, 0XB79B, 0XA612, 0XD2AD, 0XC324, 0XF1BF, 0XE036, 0X18C1, 0X0948, - 0X3BD3, 0X2A5A, 0X5EE5, 0X4F6C, 0X7DF7, 0X6C7E, 0XA50A, 0XB483, 0X8618, 0X9791, 0XE32E, - 0XF2A7, 0XC03C, 0XD1B5, 0X2942, 0X38CB, 0X0A50, 0X1BD9, 0X6F66, 0X7EEF, 0X4C74, 0X5DFD, - 0XB58B, 0XA402, 0X9699, 0X8710, 0XF3AF, 0XE226, 0XD0BD, 0XC134, 0X39C3, 0X284A, 0X1AD1, - 0X0B58, 0X7FE7, 0X6E6E, 0X5CF5, 0X4D7C, 0XC60C, 0XD785, 0XE51E, 0XF497, 0X8028, 0X91A1, - 0XA33A, 0XB2B3, 0X4A44, 0X5BCD, 0X6956, 0X78DF, 0X0C60, 0X1DE9, 0X2F72, 0X3EFB, 0XD68D, - 0XC704, 0XF59F, 0XE416, 0X90A9, 0X8120, 0XB3BB, 0XA232, 0X5AC5, 0X4B4C, 0X79D7, 0X685E, - 0X1CE1, 0X0D68, 0X3FF3, 0X2E7A, 0XE70E, 0XF687, 0XC41C, 0XD595, 0XA12A, 0XB0A3, 0X8238, - 0X93B1, 0X6B46, 0X7ACF, 0X4854, 0X59DD, 0X2D62, 0X3CEB, 0X0E70, 0X1FF9, 0XF78F, 0XE606, - 0XD49D, 0XC514, 0XB1AB, 0XA022, 0X92B9, 0X8330, 0X7BC7, 0X6A4E, 0X58D5, 0X495C, 0X3DE3, - 0X2C6A, 0X1EF1, 0X0F78 - ]; - - - crcX = parseInt("FFFF", 16); - cr1 = parseInt("FF", 16); - cr2 = parseInt("FFFF", 16); - i = 0; - - while (i < buf.length) { - str = buf.substring(i, i + 2); - str_hex = parseInt(str, 16); - - j = (crcX ^ str_hex) & cr1; - crcX = (crcX >> 8) ^ crcTable[j]; - - i = i + 2; - } - - crcX = crcX ^ 0xffff; - - return crcX.toString(16); -} - -function receive_heartbeat(raw, socket) { - var data = Buffer.from(raw, 'hex').toString('hex') - if (!socket.__count) { - socket.__count = 1; - } - //socket.imei = parseInt(request.device_id) - var length = '05'; - var protocal_id = '01'; - var serial = Buffer.from(raw).toString('hex').substr(18, 4) - var str = length + protocal_id + serial; - socket.__count++; - var crcResult = crc16(str); - var buff = new Buffer('7878' + str + crcResult + '0d0a', 'hex'); - socket.write(buff); -}; - -function dex_to_degrees(dex, l) { - return (parseInt(dex, 16) / 1800000) -}; - -function parseG500OBD_lat_long(l) { -} - -function parseG500OBD_data(data) { - data = Buffer.from(data).toString('hex') - if (data.substr(14, 4) == '2084') { - var date = new Date( - - parseInt(data.substr(32, 2)) + 2000, - parseInt(data.substr(30, 2)) - 1, - parseInt(data.substr(28, 2)), - parseInt(data.substr(34, 2)), - parseInt(data.substr(36, 2)), - parseInt(data.substr(38, 2)) - ) - var latDecimal = parseInt(data.substr(40, 2)) + (parseFloat(data.substr(42, 2) + '.' + data.substr(44, 4)) / 60) - var longDecimal = parseInt(data.substr(48, 2)) + (parseFloat(data.substr(50, 2) + '.' + data.substr(52, 4)) / 60) - return { - "imei": data.substr(2, 12), - "command": data.substr(14, 4), - "date": date, - "dateString": data.substr(28, 6), - "latDecimal": latDecimal, - "longDecimal": longDecimal, - "insertionTime": new Date(), - "raw": data, - "speed": parseInt(data.substr(58, 2), 16).toString(), - "timeString": data.substr(34, 6), - "heading": (parseInt(data.substr(60, 2), 16) * 2).toString(), - "geoJSON": { - "type": "Point", - "coordinates": [ longDecimal, latDecimal ] - } - } - } - else { - return {} - } -} - -function hex2ASCII(hexx) { - var hex = hexx.toString(); - var str = ''; - for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2) - str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - return str; -} - -function parse_GT06_stringInfo(parsedHead) { - var contentLength = parseInt(parsedHead.data.substr(0, 2), 16); - var serverKeyLength = 4; - var stringInfo = hex2ASCII(parsedHead.data.substr(2 + (4 * 2), contentLength * 2)); - return stringInfo; -} - -function get_GT06_alarm_data(msg_parts, raw, socket) { - var str = msg_parts.data; - var sos = 0; - var date = new Date( - parseInt(str.substr(0, 2), 16) + 2000, - parseInt(str.substr(2, 2), 16) - 1, - parseInt(str.substr(4, 2), 16), - parseInt(str.substr(6, 2), 16), - parseInt(str.substr(8, 2), 16), - parseInt(str.substr(10, 2), 16) - ) - - var course_status = parseInt(str.substr(32, 4), 16).toString(2); - var longDir = course_status.substr(2, 1) == '0' ? 'E' : 'W'; - var latDir = course_status.substr(3, 1) == '0' ? 'S' : 'N'; - //var latitude = latDir == 'N' ? dex_to_degrees(str.substr(14, 8), 0) : dex_to_degrees(str.substr(14, 8), 0)*-1; - //var longitude = longDir == 'E' ? dex_to_degrees(str.substr(22, 8), 1) : dex_to_degrees(str.substr(22, 8), 1)*-1; - var latitude = latDir == 'N' ? dex_to_degrees(str.substr(14, 8), 0) : dex_to_degrees(str.substr(14, 8), 0); - var longitude = longDir == 'E' ? dex_to_degrees(str.substr(22, 8), 1) : dex_to_degrees(str.substr(22, 8), 1); - - - var terminalInfoContentByte = parseInt(str.substr(54, 2), 16).toString(2); - while (terminalInfoContentByte.length < 8) { - terminalInfoContentByte = '0' + terminalInfoContentByte - } - //parse alarms - var sosAlarm = 0; - var powerCutAlarm = 0; - var shockAlarm = 0; - var alarmBits = terminalInfoContentByte.substr(2, 3); - if (alarmBits == '000') { - sosAlarm = 0; - powerCutAlarm = 0; - shockAlarm = 0; - } - if (alarmBits == '001') { - sosAlarm = 0; - powerCutAlarm = 0; - shockAlarm = 1; - } - if (alarmBits == '010') { - sosAlarm = 0; - powerCutAlarm = 1; - shockAlarm = 0; - } - if (alarmBits == '100') { - sosAlarm = 1; - sos = 1; - powerCutAlarm = 0; - shockAlarm = 0; - } - - - - return { - "imei": socket.imei.toString(), - "command": msg_parts.protocal_id, - "date": date, - "dateString": str.substr(0, 6), - "latDecimal": latitude, - "longDecimal": longitude, - "insertionTime": new Date(), - "raw": raw.toString('hex'), - "speed": parseInt(str.substr(30, 2), 16).toString(), - "timeString": str.substr(6, 6), - "heading": parseInt(course_status.substr(4, 10), 2).toString(), - "geoJSON": { - "type": "Point", - "coordinates": [longitude, latitude ] - }, - 'MCC': parseInt(str.substr(36, 4), 16), - 'MNC': parseInt(str.substr(40, 2), 16), - 'LAC': parseInt(str.substr(42, 4), 16), - 'CellT ID': parseInt(str.substr(46, 6), 16), - 'lbs': str.substr(36, 16), - 'real-time gps': course_status.substr(0, 1), - 'GPS positioned': course_status.substr(1, 1), - 'satellites': parseInt(str.substr(13, 1), 16), - "powerCutAlarm": powerCutAlarm, - "sosAlarm": sosAlarm, - "shockAlarm": shockAlarm, - "terminalInfoContentByte": terminalInfoContentByte, - "sos" : sos == 1 ? true : false - } -}; -function get_GT06_ping_data(msg_parts, raw, socket) { - var str = msg_parts.data; - var date = new Date( - parseInt(str.substr(0, 2), 16) + 2000, - parseInt(str.substr(2, 2), 16) - 1, - parseInt(str.substr(4, 2), 16), - parseInt(str.substr(6, 2), 16), - parseInt(str.substr(8, 2), 16), - parseInt(str.substr(10, 2), 16) - ) - - var course_status = parseInt(str.substr(32, 4), 16).toString(2); - var longDir = course_status.substr(2, 1) == '0' ? 'E' : 'W'; - var latDir = course_status.substr(3, 1) == '0' ? 'S' : 'N'; - //var latitude = latDir == 'N' ? dex_to_degrees(str.substr(14, 8), 0) : dex_to_degrees(str.substr(14, 8), 0)*-1; - //var longitude = longDir == 'E' ? dex_to_degrees(str.substr(22, 8), 1) : dex_to_degrees(str.substr(22, 8), 1)*-1; - var latitude = latDir == 'N' ? dex_to_degrees(str.substr(14, 8), 0) : dex_to_degrees(str.substr(14, 8), 0); - var longitude = longDir == 'E' ? dex_to_degrees(str.substr(22, 8), 1) : dex_to_degrees(str.substr(22, 8), 1); - - - var terminalInfoContentByte = parseInt(str.substr(52, 2), 16).toString(2); - while (terminalInfoContentByte.length < 8) { - terminalInfoContentByte = '0' + terminalInfoContentByte - } - //parse alarms - var sosAlarm = 0; - var powerCutAlarm = 0; - var shockAlarm = 0; - var alarmBits = terminalInfoContentByte.substr(2, 3); - if (alarmBits == '000') { - sosAlarm = 0; - powerCutAlarm = 0; - shockAlarm = 0; - } - if (alarmBits == '001') { - sosAlarm = 0; - powerCutAlarm = 0; - shockAlarm = 1; - } - if (alarmBits == '010') { - sosAlarm = 0; - powerCutAlarm = 1; - shockAlarm = 0; - } - if (alarmBits == '100') { - sosAlarm = 1; - powerCutAlarm = 0; - shockAlarm = 0; - } - - - - return { - "imei": socket.imei.toString(), - "command": msg_parts.protocal_id, - "date": date, - "dateString": str.substr(0, 6), - "latDecimal": latitude, - "longDecimal": longitude, - "insertionTime": new Date(), - "raw": raw.toString('hex'), - "speed": parseInt(str.substr(30, 2), 16).toString(), - "timeString": str.substr(6, 6), - "heading": parseInt(course_status.substr(4, 10), 2).toString(), - "geoJSON": { - "type": "Point", - "coordinates": [longitude, latitude ] - }, - 'MCC': parseInt(str.substr(36, 4), 16), - 'MNC': parseInt(str.substr(40, 2), 16), - 'LAC': parseInt(str.substr(42, 4), 16), - 'CellT ID': parseInt(str.substr(46, 6), 16), - 'lbs': str.substr(36, 16), - 'real-time gps': course_status.substr(0, 1), - 'GPS positioned': course_status.substr(1, 1), - 'satellites': parseInt(str.substr(13, 1), 16), - "powerCutAlarm": powerCutAlarm, - "sosAlarm": sosAlarm, - "shockAlarm": shockAlarm, - "terminalInfoContentByte" : terminalInfoContentByte - } -}; - - - -function gt06_ping_response(socket) { - socket.__count++; - //socket.write(new Buffer('787805010001d9dc0d0a', 'hex')) -} -function authorizeGT06(socket, request, raw) { - - if (!socket.__count) { - socket.__count = 1; - } - socket.imei = socket.imei || parseInt(request.device_id) - var length = '05'; - var protocal_id = '01'; - var serial = Buffer.from(raw).toString('hex').substr(24, 4) - var str = length + protocal_id + serial; - socket.__count++; - var crcResult = crc16(str); - var buff = new Buffer('7878' + str + crcResult + '0D0A', 'hex'); - socket.write(buff); -}; - - -function parseGT06_Head(data, socket) { - data = Buffer.from(data).toString('hex') - var parts = { - 'start': data.substr(0, 4) - }; - - if (parts['start'] == '7878' || parts['start'] == '7979') { - parts['length'] = parseInt(data.substr(4, 2), 16); - parts['finish'] = data.substr(6 + parts['length'] * 2, 4); - parts['protocal_id'] = data.substr(6, 2); - if (parts['protocal_id'] == '01') { - parts['device_id'] = data.substr(8, 16); - parts.cmd = 'login_request'; - parts.action = 'login_request'; - } else if (parts['protocal_id'] == '12' || parts['protocal_id'] == '19') { - parts['device_id'] = socket.imei || ''; - parts['data'] = data.substr(8, parts['length'] * 2); - parts.cmd = 'ping'; - parts.action = 'ping'; - } else if (parts['protocal_id'] == '22') { - parts['device_id'] = socket.imei || ''; - parts['data'] = data.substr(8, parts['length'] * 2); - parts.cmd = 'ping'; - parts.action = 'ping'; - } else if (parts['protocal_id'] == '13' || parts['protocal_id'] == '23') { - parts['device_id'] = socket.imei || ''; - parts.cmd = 'heartbeat'; - parts['data'] = data.substr(8, 10); - parts.action = 'heartbeat'; - } else if (parts['protocal_id'] == '16' || parts['protocal_id'] == '18') { - parts['device_id'] = socket.imei || ''; - parts['data'] = data.substr(8, parts['length'] * 2); - parts.cmd = 'alert'; - parts.action = 'alert'; - } else if (parts['protocal_id'] == '15') { - parts['device_id'] = socket.imei || ''; - parts['data'] = data.substr(8, parts['length'] * 2); - parts.cmd = 'stringInfo'; - parts.action = 'stringInfo'; - } else { - parts['device_id'] = socket.imei || ''; - parts.cmd = 'noop'; - parts.action = 'noop'; - } - } - else if (parts['start'].indexOf('28') == 0) { - parts['device_id'] = data.substr(2, 12); - parts.cmd = data.substr(14, 4); - if (parts.cmd == '2084') { - parts.action = 'ping'; - } - else if (parts.cmd == '1088') { - parts.action = 'heartbeat' - } - else - parts.action = 'noop' - } - else { - parts['device_id'] = ''; - parts.cmd = 'noop'; - parts.action = 'noop'; - } - return parts; -}; - - -function isHex(h) { - var re = /[0-9A-Fa-f]{6}/g; - re.lastIndex = 0; - if (re.test(h)) { - - return true; - } else { - return false; - } - - -} - - - - -function change_G900WKMD(socket, device_id) { - //device_id = '865205032299264' - var hh = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours().toString() - var mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes().toString() - var ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds().toString() - - socket.write('*HQ,' + device_id + ',WKMD,' + hh + mm + ss + ',0#') - socket.write('*HQ,' + device_id + ',S26,' + hh + mm + ss + ',W#') - -} -/** move to another file */ -function parseRawGps(raw, gpsModel) { - if (gpsModel == 'TK') { - - var latDecimal = raw.substring(33, 34) == 'N' ? - parseFloat(raw.substring(24, 26)) + parseFloat((raw.substring(26, 33) / 60)) : - (parseFloat(raw.substring(24, 26)) + parseFloat((raw.substring(26, 33) / 60))) * -1; - var longDecimal = raw.substring(44, 45) == 'E' ? - parseFloat(raw.substring(34, 37)) + parseFloat((raw.substring(37, 44) / 60)) : - (parseFloat(raw.substring(34, 37)) + parseFloat((raw.substring(37, 44) / 60))) * -1; - - var io=raw.substr(63,1)?parseInt(raw.substr(63,1)):null; - var ac=raw.substr(64,1)?parseInt(raw.substr(64,1)):null; - var fuel=((parseInt(raw.substr(67,1), 16)*16*16)+(parseInt(raw.substr(68,1), 16)*16)+(parseInt(raw.substr(69,1), 16)))*10; - var ac1=('0000' + parseInt(ac, 16).toString(2)).slice(-4).charAt(3); - var sos=('0000' + parseInt(ac, 16).toString(2)).slice(-4).charAt(2); - - return { - "imei": raw.substring(1, 13), - "command": raw.substring(13, 17), - "date": new Date(parseInt('20' + - raw.substring(17, 19)), - parseInt(raw.substring(19, 21) - 1), - parseInt(raw.substring(21, 23)), - parseInt(raw.substring(50, 52)), - parseInt(raw.substring(52, 54)), - parseInt(raw.substring(54, 56)) - ), - "dateString": raw.substring(17, 23), - "latDegrees": raw.substring(24, 34), - "longDegrees": raw.substring(34, 45), - "latDecimal": latDecimal, - "longDecimal": longDecimal, - "insertionTime": new Date(), - "raw": raw, - "valid": raw.substring(23, 24), - "speed": raw.substring(45, 50), - "timeString": raw.substring(50, 56), - "heading": raw.substring(56, 62), - "power": raw.substr(62,1)=='0'?'1':'0', - "mileage": raw.substring(71, 80), - "ignition": io, - "ac":ac1, - "sos":sos, - "fuelVoltage":fuel, - "GPS positioned":((raw.substring(23, 24)=='A')?1:0), - "geoJSON": { - "type": "Point", - "coordinates": [ longDecimal, latDecimal ] - } - } -} -if (gpsModel == 'G') { - try { - var rawArray = raw.split(',') - var latDecimal = rawArray[6] == 'N' ? - parseFloat(rawArray[5].substring(0, 2)) + parseFloat((rawArray[5].substring(2, 9) / 60)) : - (parseFloat(rawArray[5].substring(0, 2)) + parseFloat((rawArray[5].substring(2, 9) / 60))) * -1; - var longDecimal = rawArray[8] == 'E' ? - parseFloat(rawArray[7].substring(0, 3)) + parseFloat((rawArray[7].substring(3, 10) / 60)) : - (parseFloat(rawArray[7].substring(0, 3)) + parseFloat((rawArray[7].substring(3, 10) / 60))) * -1; - var ac=rawArray[12].substring(4,6); - var ac1 = (parseInt(ac, 16).toString(2)); - while (ac1.length < 8) { - ac1 = '0' + ac1; - } - ac1 = ac1.substr(5, 1); - var power = rawArray[12].substring(2, 4); - - var power1 = parseInt(power, 16).toString(2); - while (power1.length < 8) { - power1 = '0' + power1; - } - power1 = power1.substr(4, 1); - return { - "imei": rawArray[1], - "command": rawArray[2], - "date": rawArray[11] ? new Date(parseInt('20' + - rawArray[11].substring(4, 6)), - parseInt(rawArray[11].substring(2, 4) - 1), - parseInt(rawArray[11].substring(0, 2)), - parseInt(rawArray[3].substring(0, 2)), - parseInt(rawArray[3].substring(2, 4)), - parseInt(rawArray[3].substring(4, 6)) - ) : null, - "dateString": rawArray[11], - "latDegrees": rawArray[5] + rawArray[6], - "longDegrees": rawArray[7] + rawArray[8], - "latDecimal": latDecimal, - "longDecimal": longDecimal, - "insertionTime": new Date(), - "raw": raw, - "valid": rawArray[4], - "speed": (parseFloat(rawArray[9]) * 1.60934).toFixed(2), - "timeString": rawArray[3], - "heading": rawArray[10], - "power": power1/* =='0'?'1':'0' */, - "mileage": rawArray[12], - "ignition":ac1/* =='0'?'1':'0' */, - "GPS positioned":((rawArray[4]=='A')?1:0), - "geoJSON": { - "type": "Point", - "coordinates": [ longDecimal, latDecimal ] - } - } -} catch (err) { - console.error("exception handled"); - console.error(err); -} -} -} - -function parseMobileTrackerData(raw) { - return { - imei: raw.imei.toString(), - command: "mPing", - latDecimal: parseFloat(raw.curLat), - longDecimal: parseFloat(raw.curLong), - date: new Date(raw.curDateTime), - batteryStatus: raw.batteryStatus, - raw : JSON.stringify(raw), - deviceModel: raw.deviceModel, - deviceUUID: raw.deviceUUID, - platform: raw.platform, - platformVersion: raw.platformVersion, - deviceManufacturer: raw.deviceManufacturer, - deviceSerialNo: raw.deviceSerialNo, - isVirtual: raw.isVertual, - insertionTime: new Date(), - sos: raw.SOS, - speed: raw.speed, - mode: raw.mode, - accuracy: raw.accuracy, - geoJSON: { - "type": "Point", - "coordinates": [parseFloat(raw.curLong),parseFloat(raw.curLat)] - } - - } -} - -function parseAIS140Head(packet, socket) { - packet = packet.toString('utf8'); - var msgParts = packet.split(','); - var header = {} - if (msgParts.length == 10) { - header.cmd = 'login_request'; - header.packet = packet; - header.action = 'login_request'; - header['device_id'] = msgParts[3]; - socket.imei = msgParts[3]; - } - if (msgParts.length == 13) { - header.cmd = 'heartbeat'; - header.packet = packet; - header.action = 'heartbeat'; - header['device_id'] = msgParts[3]; - socket.imei = msgParts[3]; - } - if (msgParts.length == 17) { - header.cmd = 'alertPacket'; - header.packet = packet; - header.action = 'alertPacket'; - header['device_id'] = msgParts[3]; - socket.imei = msgParts[3]; - } - if (msgParts.length >= 52) { - header.cmd = 'ping'; - header.packet = packet; - header.action = 'ping'; - header['device_id'] = msgParts[6]; - socket.imei = msgParts[6]; - } - return header; -} - -function parseAIS140Ping(raw) { - raw = raw.toString('utf8'); - raw = "$Header" + raw.split('$Header')[raw.split('$Header').length -1] - var msgParts = raw.split(','); - var date = new Date( - parseInt(msgParts[9].substr(4, 4)), - parseInt(msgParts[9].substr(2, 2)) - 1, - parseInt(msgParts[9].substr(0, 2)), - parseInt(msgParts[10].substr(0, 2)), - parseInt(msgParts[10].substr(2, 2)), - parseInt(msgParts[10].substr(4, 2)), - ); - return { - firmwareVersion: msgParts[2], - command: msgParts[3], - msgID: msgParts[4], - packetStatus: msgParts[5], - isPastData: msgParts[5] == 'L' ? false : true, - imei: msgParts[6], - vehicleRegistration: msgParts[7], - "GPS positioned": msgParts[8], - dateString: msgParts[9], - timeString: msgParts[10], - date: date, - latDecimal: msgParts[11] * (msgParts[12] == 'N'? 1 : -1), - longDecimal: msgParts[13] * (msgParts[14] == 'E' ? 1 : -1), - speed: msgParts[15], - heading: msgParts[16], - satellites: msgParts[17], - altitude: msgParts[18], - ignition: msgParts[22], - power: msgParts[23], - gsmSignal: msgParts[28], - insertionTime : new Date(), - raw: raw, - sos: msgParts[4] == '10' ? true : null, - geoJSON : { - "type" : "Point", - "coordinates" : [ - msgParts[13] * (msgParts[14] == 'E' ? 1 : -1), - msgParts[11] * (msgParts[12] == 'N'? 1 : -1) - ] - } - } -} - -function parseAIS140Packets(packets, socket) { - var pings = []; - var alertPackets = []; - var logins = []; - var hbts = []; - var latestPing; - for (var i = 0; i < packets.length; i++){ - var parsedHead = parseAIS140Head(packets[i], socket); - console.log(parsedHead); - if (parsedHead.cmd == 'ping') { - pings.push(parseAIS140Ping(packets[i])); - } - if (parsedHead.cmd == 'login_request') { - logins.push(packets[i]); - } - if (parsedHead.cmd == 'heartbeat') { - hbts.push(packets[i]); - } - if (parsedHead.cmd == 'alertPacket') { - alertPackets.push(packets[i]); - } - } - - - if (pings.length > 0) { - for (var i = 0; i < pings.length; i++){ - pings[i].processed = false; - if (pings[i].msgID == '10') { - pings[0].sos == true; - } - } - if (alertPackets.length) { - - } - latestPing = pings.splice(0, 1); - GPS.insertMany(pings, function (err, insertedAISPings) { - if(err){ - console.log(err); - - } - else { - //console.log('insertedAISPings', insertedAISPings); - } - }) - } - //console.log('latestPing', latestPing); - if (latestPing) { - latestPing[0].processed = null; - return latestPing[0]; - } - else { - return null; - } -} - - -module.exports.intermediate = function (data) { - // console.log(data.data); - module.exports.process(data, KafkaService); -} - - -module.exports.process = function (data, KafkaService) { - try { - - var raw = data.data - - var socket = data.socket - var parsedData = {} - - - - /** - * mTracker proto - * - */ - - if (!(Buffer.isBuffer(raw))) { - //console.log('mobile tracker : ', raw); - //socket.setTimeout(5000); - if (!raw.imei) return; - parsedData = parseMobileTrackerData(raw); - //console.log(raw); - } - else if (raw.toString('utf8').indexOf('$Header') == 0) { - //console.log('ais140 : ', raw); - var packets = raw.toString('utf8').split('\r\n'); - packets.pop(); - //console.log("AIS PACKETS :: ", packets); - parsedData = parseAIS140Packets(packets, socket); - socket.setTimeout(0); - //var parsedHead = parseAIS140Head(raw, socket); - //console.log(parsedHead); - if (parsedData) { - //parsedData = parseAIS140ping(raw); - //console.log(parsedData); - } else { - return; - } - - } - else if(/* raw.toString("utf8").split('=')[1] */ raw.toString('utf8').indexOf('ApiString') == 0){ - //GB101 - //console.log('gb101 : ', raw); - if (true) { - var raw1 = raw.toString("utf8").split('=')[1]; - socket.write('+##Received OK'); - parsedData = parseRawGpsGB(raw1, 'GB'); - } - } - else if (Buffer.from(raw, 'hex').toString('hex').indexOf('00') == 0) { - //fmb protocol - //console.log('fmb : ', raw); - var hexString = Buffer.from(raw, 'hex').toString('hex'); - if (hexString.indexOf('00000000') == 0) { - parsedData = parseFmbData(hexString, socket); - sendFmbAck(socket, parsedData.number_of_data); - - } - else if(hexString.indexOf('00') == 0){ - - fmb_login(hexString, socket); - //return; - } - } - else if (raw.toString('utf8').indexOf("imei:") != -1) { - //console.log('COBAN GPS103/GPS303 : ', raw); - /** - * COBAN GPS103/GPS303 PROTOCOL - */ - var gps_x03 = new GPS_x03(raw.toString('utf8'), socket); - - if (gps_x03.command == 'login') { - gps_x03.doLogin(); - } - if (gps_x03.command == 'tracker') { - parsedData = gps_x03.getPingData(); - } - - } - else if (raw.toString('utf8').indexOf('(') == 0 && (raw.toString('utf8').lastIndexOf(')') == (raw.toString('utf8').length - 1)) && raw.toString('utf8').indexOf(' ') != 1) { - //tk protocol - - var data = raw.toString('utf8'); - var cmd_start = data.indexOf("B"); - if(data.substr(cmd_start,4)=='BP05') - { - socket.write('('+data.substring(1,cmd_start) + 'AP05)'); - return; - } - parsedData = parseRawGps(raw.toString('utf8'), 'TK'); - //console.log('TK : ', raw, parsedData.imei); - } - else if(raw.toString("utf8").indexOf('$$CLIENT_1')==0) - { - //console.log('$$CLIENT_1 : ', raw); - - if(raw.toString("utf8").indexOf('Ignition') != -1) - { - parsedData = parseRawGpsTs(raw.toString('utf8'), 'first'); - } - else - { - parsedData = parseRawGpsTs(raw.toString('utf8'), 'rest'); - } - } - else if(raw.toString("utf8").indexOf('Sender')==0) - { - //console.log('Sender : ', raw); - parsedData = parseRawGpsVTX(raw.toString("utf8")); - socket.write('Ok'); - } - //'yantra' protocol - else if (raw.toString('utf8').split(',').length >= 3 && raw.toString('utf8').startsWith('$') && raw.toString('utf8').endsWith('#')) { - - //console.log('Yantra : ', raw); - if (raw.toString('utf8').startsWith('$3')) { - //alert packet - //parsedData = parseYantraAlert(raw.toString('utf8')); - } - else { - //data packet - parsedData = parseYantraData(raw.toString('utf8')); - console.log(parsedData); - socket.destroy(); - } - } - else if (raw.toString('utf8').split(',').length >= 3 ) { - - //console.log('g900 : ', raw); - - //g900 protocol - if (raw.toString('utf8').split(',').length == 3) { - /** - * implement authorizeG900 - */ - cmdPacket = Buffer.from(raw).toString('hex') - - cmdPackets.create({ cmd: cmdPacket, device_id: cmdPacket.split(',')[1], time: new Date() }, function (err, inserted) { - if (err) { - console.error(err) - return; - } - else { - - } - }); - - //change_G900WKMD(socket, raw.toString('utf8').split(',')[1]) - return; - } - /* var hh = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours().toString() - var mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes().toString() - var ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds().toString() */ - - if (raw.toString('utf8').split(',').length >= 12) { - - parsedData = parseRawGps(raw.toString('utf8'), 'G'); - } - - } - - else if (Buffer.from(raw, 'hex').toString('hex').indexOf('2323') == 0) { - //t8803 protocol - //console.log('t8803 : ', raw); - var parsedHead = parseT8803_head(raw, socket); - if (parsedHead.cmd == 'login_request') { - authorizeT8803(parsedHead.device_id, socket); - return; - } - if (parsedHead.cmd == 'ping') { - - parsedData = parseT8803_data(raw); - return; - } - if (parsedHead.cmd == 'heartbeat') { - respond_T8803_heartbeat(parsedHead.device_id, socket); - return; - } - } - else if (Buffer.from(raw, 'hex').toString('hex').indexOf('2929') == 0) { - //VT1000 protocol - //console.log('VT1000 : ', raw); - if(Buffer.from(raw, 'hex').toString('hex').indexOf('B1')==4) - { - socket.write('21'); - } - if(Buffer.from(raw, 'hex').toString('hex').indexOf('80')==4) - { - - parsedData = parseVT1000(Buffer.from(raw, 'hex').toString('hex')); - } - - } - - else if (Buffer.from(raw, 'hex').toString('hex').indexOf('20') == 0) { - //L100 protocol - - //console.log('L100 : ', raw); - parsedData = parseRawGpsL(Buffer.from(raw, 'hex').toString('hex')); - - - } - else if (raw.toString('hex').indexOf('24') == 0) { - //console.log('24 : ', raw); - raw = raw.toString('hex'); - var head = raw.substr(0, 2); - var imei = raw.substr(2, 10); - var date = new Date( - parseInt('20' + raw.substr(22, 2)), - parseInt(raw.substr(20, 2) - 1), - parseInt(raw.substr(18, 2)), - parseInt(raw.substr(12, 2)), - parseInt(raw.substr(14, 2)), - parseInt(raw.substr(16, 2)) - ); - var latitude = parseInt(raw.substr(24, 2)) + (parseFloat(raw.substr(26,6)) / 600000); - var longitude = parseInt(raw.substr(34, 3)) + (parseFloat(raw.substr(37,6)) / 600000);//parseInt(raw.substr(34, 9)) / 1000000;//dex_to_degrees(raw.substr(34, 9), 0) // - var speed = parseInt(raw.substr(44, 3)).toString(); - var heading = parseInt(raw.substr(47, 3)).toString(); - - parsedData = { - imei: imei, - date: date, - latDecimal: latitude, - longDecimal: longitude, - latString: raw.substr(24, 8), - longString: raw.substr(34, 9), - raw: raw, - speed: speed, - heading: heading, - insertionTime: new Date(), - geoJSON: { - "type": "Point", - "coordinates": [longitude, latitude] - } - } - console.log(parsedData); - } - else if (Buffer.from(raw, 'hex').toString('hex').indexOf('6767') == 0) { - //gm-06 protocol - //console.log('gm-06 : ', raw); - var parsedHead = parseGM06_Head(raw, socket); - if (parsedHead.cmd == 'login_request') { - console.log(Buffer.from(raw, 'hex').toString('hex')) - authorizeGM06(socket, parsedHead, raw); - parsedHead.insertionTime = new Date(); - - } - else if (parsedHead.cmd == 'ping') { - parsedData = get_GM06_ping_data(parsedHead, raw, socket); - - } - else if (parsedHead.cmd == 'heartbeat') { - receive_GM06_heartbeat(raw, socket) - parsedHead.insertionTime = new Date(); - - - /** - * parse HEARTBEAT DATA - */ - var parsed_HBT = JSON.parse(JSON.stringify(parsedHead)) - parsed_HBT.device_id = parsed_HBT.device_id.toString(); - parsed_HBT.insertionTime = new Date(); - var batteryStatus = parseInt(parsedHead.data.substr(1, 1)).toString(); - var gsmSignal = parseInt(parsedHead.data.substr(2, 1)); - var terminalInfo = parseInt(parsedHead.data.substr(2, 2), 16).toString(2); - while (terminalInfo.length < 8) { - terminalInfo = '0' + terminalInfo - } - parsed_HBT.ignitionLock = terminalInfo.substr(2, 1) == '0' ? '1' : '0'; - parsed_HBT.gpsTracking = terminalInfo.substr(7, 1); - parsed_HBT.alarm = terminalInfo.substr(2, 3); - parsed_HBT.power = terminalInfo.substr(0, 1); - parsed_HBT.activated = terminalInfo.substr(7, 1); - parsed_HBT.ACC = terminalInfo.substr(6, 1); - parsed_HBT.batteryStatus = batteryStatus; - parsed_HBT.gsmSignal = gsmSignal; - if (parsed_HBT.ACC == "") { - parsed_HBT.ACC = "0"; - } - - cmdPackets.create(parsed_HBT, function (err, cmdPkt) { - if (err) { - console.error(err) - return; - } - else { - TCPUTIL.setACCNotif(parsed_HBT.device_id, parsed_HBT.ACC, KafkaService) - - - - - Device.findOne({ "Device_ID": parsed_HBT.device_id }).populate('user').exec(function (err, dev) { - if (err) { - console.error(err); - - } - else if (dev) { - - /** - * update last cmdPacket with the vehicle mapped against device - */ - cmdPackets.update({ _id: cmdPkt._id }, { $set: { vehicle: dev.vehicle } }).exec(); - //---------------------------------------------------------------------------------- - var previousPower = dev.power; - var user = dev.user; - dev['last_ACC'] = parsed_HBT.ACC; - dev['last_ACC_on'] = new Date(); - dev['batteryStatus'] = batteryStatus; - dev['gsmSignal'] = parsed_HBT.gsmSignal; - dev['ignitionLock'] = parsed_HBT.ignitionLock; - dev['gpsTracking'] = parsed_HBT.gpsTracking; - dev['alarm'] = parsed_HBT.alarm; - dev['power'] = parsed_HBT.power; - dev['activated'] = parsed_HBT.activated; - //dev['user'] = dev.user._id; - - dev.save(function (err) { - if (err) { - console.error(err); - } - else { - KafkaService.sendRecord({ namespace: "gpsio", room: parsed_HBT.device_id.toString(), channel: parsed_HBT.device_id.toString() + 'acc', data: [parsed_HBT.ACC, parsed_HBT.device_id.toString(), new Date(), dev] }) - /* gpsio.to(parsed_HBT.device_id.toString()).emit(parsed_HBT.device_id.toString() + 'acc', parsed_HBT.ACC, parsed_HBT.device_id.toString(), new Date(), dev) - */ TCPUTIL.setDeviceStatus(dev, null); - if ((parsed_HBT.power == "0" || parsed_HBT.power == "1") && previousPower != parsed_HBT.power) { - //setPowerNotification - TCPUTIL.setPowerNotif(dev, parsed_HBT.power, KafkaService, user); - } - } - }) - - } - }) - } - }); - - } - else if (parsedHead.cmd == 'alarm') { - } - - - - } - else { - // console.log('gt-06 : ', raw); - //gt-06 protocol - var parsedHead = parseGT06_Head(raw, socket); - var hasCombinedHBT = false; - var indexOfHBT = raw.toString('hex').indexOf('78780a13'); - if (indexOfHBT != -1 && indexOfHBT != 0) { - /** - * parse HEARTBEAT DATA - */ - //console.log('combined HBT detected for ', parsedHead.device_id) - var hbtBuf = Buffer.from(raw.toString('hex').substr(indexOfHBT), 'hex'); - //console.log(hbtBuf); - var parsed_HBT = parseGT06_Head(hbtBuf, socket); - parsed_HBT.device_id = parsed_HBT.device_id.toString(); - parsed_HBT.insertionTime = new Date(); - var batteryStatus = parseInt(parsed_HBT.data.substr(1, 1)).toString(); - var gsmSignal = parseInt(parsed_HBT.data.substr(2, 1)); - var terminalInfo = parseInt(parsed_HBT.data.substr(0, 2), 16).toString(2); - while (terminalInfo.length < 8) { - terminalInfo = '0' + terminalInfo - } - parsed_HBT.ignitionLock = terminalInfo.substr(0, 1); - parsed_HBT.gpsTracking = terminalInfo.substr(1, 1); - parsed_HBT.alarm = terminalInfo.substr(2, 3); - parsed_HBT.power = terminalInfo.substr(5, 1); - parsed_HBT.activated = terminalInfo.substr(7, 1); - parsed_HBT.ACC = terminalInfo.substr(6, 1); - parsed_HBT.batteryStatus = batteryStatus; - parsed_HBT.gsmSignal = gsmSignal; - if (parsed_HBT.ACC == "") { - parsed_HBT.ACC = "0"; - } - - TCPUTIL.processServerCommandQueue(parsed_HBT.device_id, socket); - cmdPackets.create(parsed_HBT, function (err, cmdPkt) { - if (err) { - console.error(err) - return; - } - else { - //console.log('hbt created on dev', cmdPkt._id) - TCPUTIL.setACCNotif(parsed_HBT.device_id, parsed_HBT.ACC, KafkaService) - - - - - Device.findOne({ "Device_ID": parsed_HBT.device_id }).populate('user').exec(function (err, dev) { - if (err) { - console.error(err); - - } - else if (dev) { - - /** - * update last cmdPacket with the vehicle mapped against device - */ - cmdPackets.update({ _id: cmdPkt._id }, { $set: { vehicle: dev.vehicle } }).exec(); - //---------------------------------------------------------------------------------- - var previousPower = dev.power; - var user = dev.user; - dev['last_ACC'] = parsed_HBT.ACC; - dev['last_ACC_on'] = new Date(); - dev['batteryStatus'] = batteryStatus; - dev['gsmSignal'] = parsed_HBT.gsmSignal; - dev['ignitionLock'] = parsed_HBT.ignitionLock; - dev['gpsTracking'] = parsed_HBT.gpsTracking; - dev['alarm'] = parsed_HBT.alarm; - dev['power'] = parsed_HBT.power; - dev['activated'] = parsed_HBT.activated; - dev['status'] = parsed_HBT.ACC == 1 ? 'IDLING' : 'STOPPED' - //dev['user'] = dev.user._id; - - dev.save(function (err) { - - if (err) { - console.error(err); - } - else { - KafkaService.sendRecord({ namespace: "gpsio", room: parsed_HBT.device_id.toString(), channel: parsed_HBT.device_id.toString() + 'acc', data: [parsed_HBT.ACC, parsed_HBT.device_id.toString(), new Date(), dev] }) - /* gpsio.to(parsed_HBT.device_id.toString()).emit(parsed_HBT.device_id.toString() + 'acc', parsed_HBT.ACC, parsed_HBT.device_id.toString(), new Date(), dev) - */ TCPUTIL.setDeviceStatus(dev, null); - if ((parsed_HBT.power == "0" || parsed_HBT.power == "1") && previousPower != parsed_HBT.power) { - //setPowerNotification - TCPUTIL.setPowerNotif(dev, parsed_HBT.power, KafkaService, user); - } - } - }) - - } - }) - } - }); - - } - if (parsedHead.device_id == '') { - socket.destroy(); - return; - } - if (parsedHead.start == '7878') { - if (parsedHead.device_id == '860016021075051') { - console.log(parsedHead); - } - if (parsedHead.cmd == 'login_request') { - authorizeGT06(socket, parsedHead, raw); - parsedHead.insertionTime = new Date(); - - } - else if (parsedHead.cmd == 'ping') { - - gt06_ping_response(socket) - parsedData = get_GT06_ping_data(parsedHead, raw, socket); - - if (parsedData.latDecimal == 0) { - console.info('gt06 0,0 from : ' + socket.imei) - } - } - else if (parsedHead.cmd == 'heartbeat') { - receive_heartbeat(raw, socket) - parsedHead.insertionTime = new Date(); - - - /** - * parse HEARTBEAT DATA - */ - var parsed_HBT = JSON.parse(JSON.stringify(parsedHead)) - parsed_HBT.device_id = parsed_HBT.device_id.toString(); - parsed_HBT.insertionTime = new Date(); - var batteryStatus = parseInt(parsedHead.data.substr(1, 1)).toString(); - var gsmSignal = parseInt(parsedHead.data.substr(2, 1)); - var terminalInfo = parseInt(parsedHead.data.substr(0, 2), 16).toString(2); - while (terminalInfo.length < 8) { - terminalInfo = '0' + terminalInfo - } - parsed_HBT.ignitionLock = terminalInfo.substr(0, 1); - parsed_HBT.gpsTracking = terminalInfo.substr(1, 1); - parsed_HBT.alarm = terminalInfo.substr(2, 3); - parsed_HBT.power = terminalInfo.substr(5, 1); - parsed_HBT.activated = terminalInfo.substr(7, 1); - parsed_HBT.ACC = terminalInfo.substr(6, 1); - parsed_HBT.batteryStatus = batteryStatus; - parsed_HBT.gsmSignal = gsmSignal; - if (parsed_HBT.ACC == "") { - parsed_HBT.ACC = "0"; - } - - TCPUTIL.processServerCommandQueue(parsed_HBT.device_id, socket); - cmdPackets.create(parsed_HBT, function (err, cmdPkt) { - if (err) { - console.error(err) - return; - } - else { - TCPUTIL.setACCNotif(parsed_HBT.device_id, parsed_HBT.ACC, KafkaService) - - - - - Device.findOne({ "Device_ID": parsed_HBT.device_id }).populate('user').exec(function (err, dev) { - if (err) { - console.error(err); - - } - else if (dev) { - - /** - * update last cmdPacket with the vehicle mapped against device - */ - cmdPackets.update({ _id: cmdPkt._id }, { $set: { vehicle: dev.vehicle } }).exec(); - //---------------------------------------------------------------------------------- - var previousPower = dev.power; - var user = dev.user; - dev['last_ACC'] = parsed_HBT.ACC; - dev['last_ACC_on'] = new Date(); - dev['batteryStatus'] = batteryStatus; - dev['gsmSignal'] = parsed_HBT.gsmSignal; - dev['ignitionLock'] = parsed_HBT.ignitionLock; - dev['gpsTracking'] = parsed_HBT.gpsTracking; - dev['alarm'] = parsed_HBT.alarm; - dev['power'] = parsed_HBT.power; - dev['activated'] = parsed_HBT.activated; - dev['status'] = parsed_HBT.ACC == 1 ? 'IDLING' : 'STOPPED' - //dev['user'] = dev.user._id; - - dev.save(function (err) { - if (err) { - console.error(err); - } - else { - KafkaService.sendRecord({ namespace: "gpsio", room: parsed_HBT.device_id.toString(), channel: parsed_HBT.device_id.toString() + 'acc', data: [parsed_HBT.ACC, parsed_HBT.device_id.toString(), new Date(), dev] }) - /* gpsio.to(parsed_HBT.device_id.toString()).emit(parsed_HBT.device_id.toString() + 'acc', parsed_HBT.ACC, parsed_HBT.device_id.toString(), new Date(), dev) - */ TCPUTIL.setDeviceStatus(dev, null); - if ((parsed_HBT.power == "0" || parsed_HBT.power == "1") && previousPower != parsed_HBT.power) { - //setPowerNotification - TCPUTIL.setPowerNotif(dev, parsed_HBT.power, KafkaService, user); - } - } - }) - - } - }) - } - }); - - } - else if (parsedHead.cmd == 'alert') { - parsedData = get_GT06_alarm_data(parsedHead, raw, socket); - } - else if (parsedHead.cmd == 'stringInfo') { - console.log(parsedHead); - console.log(socket.imei, socket.serverCommand) - var parsedStringInfo = parse_GT06_stringInfo(parsedHead); - TCPUTIL.setDCQResponse(parsedStringInfo, socket.imei); - return; - } - - - } - - else if (parsedHead.start.indexOf('28') != -1 || parsedHead.start.indexOf('24') != -1) { - console.log(parsedHead) - parsedData = parseG500OBD_data(raw) - } - else { - console.info("UNKNOWN PROTOCOL DETECTED") - } - } - if (parsedData && parsedData.command == 'BP00') { - socket.write(parsedData.imei + 'AP01HSO') - - } - - /** - * identify if server commands are queued to be sent for this imei - */ - if(parsedData){ - TCPUTIL.processServerCommandQueue(parsedData.imei, socket); - } - - - if (parsedData && parsedData.imei && (parsedData.command == 'BR00' || - parsedData.command == 'V1' || - parsedData.command == '12' || - parsedData.command == '22' || - parsedData.command == '19' || - parsedData.command == '2084' || - parsedData.command == '08' || - parsedData.command == 'GB' || - parsedData.command == 'L100' || - parsedData.command == '80' || - parsedData.command == 'TS' || - parsedData.command == 'VTX' || - parsedData.command == 'mPing' || - parsedData.command == 'tracker' || - parsedData.command == '$' || - parsedData.command == '$3' || - parsedData.command == '02' || - parsedData.command == '16' || - !parsedData.command || - parsedData.command == 'NR' || - parsedData.command == 'EA' || - parsedData.command == 'TA' || - parsedData.command == 'HP' || - parsedData.command == 'IN' || - parsedData.command == 'IF' || - parsedData.command == 'BD' || - parsedData.command == 'BR' || - parsedData.command == 'BL' - )) { - - - - - GPS - .aggregate([ - { $match: { "imei": parsedData.imei , isPastData: {$ne : true} } }, // - { $sort: { "insertionTime": -1 } }, - { $limit: 1 }, - { - $lookup: - { - from: "devInfo", - localField: "imei", - foreignField: "Device_ID", - as: "lookedUpDevice" - } - }, - { $unwind: "$lookedUpDevice" }, - { - $lookup: - { - from: "client_master", - localField: "lookedUpDevice.user", - foreignField: "_id", - as: "lookedUpUser" - } - }, - { - $lookup: - { - from: "trackroutes", - localField: "lookedUpDevice.currentRoute", - foreignField: "_id", - as: "lookedUpCurrentRoute" - } - }, - { - $unwind: { - path: "$lookedUpCurrentRoute", - preserveNullAndEmptyArrays: true - } - }, - { - $lookup: - { - from: "routeDeviceMap", - localField: "lookedUpDevice.currentTrip", - foreignField: "_id", - as: "lookedUpCurrentTrip" - } - }, - { - $unwind: { - path: "$lookedUpCurrentTrip", - preserveNullAndEmptyArrays: true - } - }, - { - $lookup: - { - from: "vehicletypes", - localField: "lookedUpDevice.vehicleType", - foreignField: "_id", - as: "lookedUpVehicleType" - } - }, - { - $unwind: { - path: "$lookedUpVehicleType", - preserveNullAndEmptyArrays: true - } - } - ]).allowDiskUse(true) - .exec(function (err, x) { - if (err) { - console.error(err); - return; - } - var dataForRoadAPI = ''; - if (true) { - - var displacement = 0; - if (x.length > 0) { - displacement = TCPUTIL.getDistanceFromLatLonInKm( - x[0].latDecimal, - x[0].longDecimal, - parsedData.latDecimal, - parsedData.longDecimal - ) - } - if ((parsedData.latDecimal == 0 || parsedData.longDecimal == 0) && x[0]) { - TCPUTIL.setDeviceStatus(x[0].lookedUpDevice, 'nofix'); - } - - if (/*x[0] && displacement > 0.40 && (new Date() - new Date(x[0].insertionTime) < 15000) && parsedData.imei != '868728030654476' && parsedData.imei != '2020202020'*/ false) { - //do nothing - console.log("Too much displacement in short time for " + parsedData.imei); - } - else if (/*new Date(parsedData.insertionTime) - new Date(parsedData.date) > (5 * 60 * 1000) && (parsedData.command == 'BR00' || parsedData.command == '22') && parsedData.imei != '123456789012345' && parsedData.command != "08"*/ false) { - //do nothing - console.log("Insertion time - date > 5 mins " + parsedData.imei); - } - - else if (x[0] && new Date() - new Date(parsedData.date) < (-1 * 365 * 24 * 60 * 60 * 1000) && parsedData.imei != '123456789012345' && parsedData.command != "08") { - //do nothing - console.log("Device from future " + parsedData.imei); - } - else { - if (x[0] && x[0].lookedUpDevice.last_device_time && new Date(parsedData.date) - new Date(x[0].lookedUpDevice.last_device_time) < 1 && parsedData.imei != '123456789012345') { - //do nothing - if(parsedData.isPastData == null) parsedData.isPastData = true; - - if (x[0] && new Date(parsedData.date) - new Date(x[0].date) < 1 && parsedData.imei != '123456789012345') { - //console.log("Chronology not maintained by device " + parsedData.imei); - } - } - if ( x[0] && - displacement < FLUCTUATION_THRESHOLD && parsedData.command != 'mPing' && - ((parsedData.speed == 0 && x.length > 0 && x[0].speed == 0) || (x[0].lookedUpDevice && x[0].lookedUpDevice.ignitionSource != 'MOVEMENT' && x[0].lookedUpDevice.last_ACC == 0 && parsedData.speed <10 && x.length > 0 && x[0].speed < 10)) - ) { - //recalculate displacement on interpolated fields - - parsedData.isFluctuation = true; - /** - * if displacement from last location < FLUCTUATION_THRESHOLD - * and speed == 0 - * then update the last ping data with current time - */ - //("MITIGATING FLUCTUATION") - - - } - if(parsedData.command == 'mPing'){ - if(parsedData.accuracy > 27){ - parsedData.isFluctuation = true; - } - } - - if (parsedData.insertionTime != 'Invalid Date' - && parsedData.latDecimal != 0 - && parsedData.longDecimal != 0 - && typeof parsedData.latDecimal == "number" - && typeof parsedData.longDecimal == "number" - && parsedData.speed != "NaN" - && !isNaN(parseFloat(parsedData.latDecimal)) - && !isNaN(parseFloat(parsedData.longDecimal))) { - - - if (x[0]) { - parsedData.vehicle = ObjectID(x[0].lookedUpDevice.vehicle); - //get distance on interpolated points, if interpolation was returned by google api - var interpolatedDistance = 0; - var previousLat; - var previousLong; - if (x[0].interpolated && x[0].interpolated.length > 0) { - previousLat = x[0].interpolated[x[0].interpolated.length - 1].location.latitude - previousLong = x[0].interpolated[x[0].interpolated.length - 1].location.longitude - } - else { - previousLat = x[0].latDecimal - previousLong = x[0].longDecimal - } - - - if (parsedData.interpolated && parsedData.interpolated.length > 1) { - - interpolatedDistance += TCPUTIL.getDistanceFromLatLonInKm( - previousLat, - previousLong, - parsedData.interpolated[0].location.latitude, - parsedData.interpolated[0].location.longitude - ) - - for (var m = 0; m < parsedData.interpolated.length - 1; m++) { - interpolatedDistance += TCPUTIL.getDistanceFromLatLonInKm( - parsedData.interpolated[m].location.latitude, - parsedData.interpolated[m].location.longitude, - parsedData.interpolated[m + 1].location.latitude, - parsedData.interpolated[m + 1].location.longitude - ) - } - } - else { - interpolatedDistance = TCPUTIL.getDistanceFromLatLonInKm( - previousLat, - previousLong, - parsedData.latDecimal, - parsedData.longDecimal - ) - } - /* parsedData.distanceFromPrevious = interpolatedDistance; - parsedData.odo = x[0].lookedUpDevice.total_odo + parsedData.distanceFromPrevious; */ - if (parsedData.odo != null) { - parsedData.distanceFromPrevious = parsedData.odo - (x[0].lookedUpDevice.total_odo || 0); - interpolatedDistance = parsedData.distanceFromPrevious; - } - else { - parsedData.distanceFromPrevious = interpolatedDistance; - parsedData.odo = x[0].lookedUpDevice.total_odo + parsedData.distanceFromPrevious; - } - } - - - if (parsedData.fuelVoltage && x[0] && parsedData.ignition == '1') { - - if (!(x[0].lookedUpDevice.last_ACC == 1 && (new Date() - new Date(x[0].lookedUpDevice.last_ACC_on) > 3 * 60 * 1000))) { - parsedData.currentFuel = x[0].lookedUpDevice.currentFuel; - } - - else if (x[0].lookedUpDevice.vehicleType !== null) { - if (x[0].lookedUpVehicleType) { - var currentFuel = TCPUTIL.getCurrentFuel(x[0].lookedUpVehicleType, parsedData.fuelVoltage); - if (currentFuel[1] > x[0].lookedUpVehicleType.tank_size) { - parsedData.currentFuel = x[0].lookedUpVehicleType.tank_size - } - else if (currentFuel[1] < 0) { - parsedData.currentFuel = 0; - } - else { - parsedData.currentFuel = currentFuel[1]; - } - } - - - } - } - else if (parsedData.fuelVoltage && x[0] && parsedData.ignition == '0') { - parsedData.currentFuel = x[0].lookedUpDevice.currentFuel; - } - - //if speed is less than 1, ignore - if (parseFloat(parsedData.speed) < 1) { - parsedData.speed = "0"; - } - - parsedData.speed = parsedData.speed ? parsedData.speed.toString().split('.')[0] : null; - if (x[0] && x[0].lookedUpDevice) { - parsedData.group = x[0].lookedUpDevice.vehicleGroup; - parsedData.vehicle = ObjectID(x[0].lookedUpDevice.vehicle); - } - MongoClient.connect(url, dbOption, function (err, db) { - if (err) { - console.error(err) - return; - } - db.collection('gpstracker').insertOne(parsedData, function (err, inserted) { - if (err) { - console.error(err) - console.error('Could not saved gps ping to db') - db.close() - } - else { - - db.close() - if (x[0]) { - if (parsedData.isPastData == true) { - if (parsedData.sos == true) { - TCPUTIL.setSOSNotif(x[0], parsedData, KafkaService); - } - return; - } - if (parsedData.isFluctuation && parsedData.command == 'mPing') { - return; - } - KafkaService.sendRecord({ namespace: "gpsio", room: parsedData.imei, channel: parsedData.imei, data: [parsedData, 'ping', x[0].lookedUpDevice] }) - //gpsio.to(parsedData.imei).emit(parsedData.imei, parsedData, 'ping', x[0].lookedUpDevice); - TCPUTIL.setMaxSpeed(parsedData, x[0].lookedUpDevice, x[0].lookedUpUser[0], new Date()); - //TCPUTIL.routeTracking(x[0].lookedUpDevice.Device_ID, parsedData.longDecimal, parsedData.latDecimal, null, x[0], KafkaService); - //poi tracking - - TCPUTIL.poiTracking(x[0], null, parsedData.longDecimal, parsedData.latDecimal, KafkaService); - - var start = null; - var end = null; - if (parsedData.sos == true) { - TCPUTIL.setSOSNotif(x[0], parsedData, KafkaService); - } - if (parsedData.ignition != null && parsedData.ignition !== undefined) { - if (parsedData.command == 'BR00') { //tk103 - var data = parsedData.raw; - start = "28"; - end = "29"; - var cmd_start = data.indexOf("B"); - var dataval = data.substring(cmd_start + 4, data.length - 1); - } - if (parsedData.command == 'V1') { //tk103 - var data = parsedData.raw; - start = "*HQ"; - end = "#"; - - var dataval = data; - } - - if (parsedData.command == '08') { //fmbXXX - var data = parsedData.raw; - start = "00000000"; - var cmd_start = data.indexOf("00000000"); - var dataval = data.substring(cmd_start + 4, data.length - 1); - } - if (parsedData.command == 'GB') { //fmbXXX - var data = parsedData.raw; - start = "{"; - end = "}" - //var cmd_start = data.indexOf("00000000"); - //var dataval=data.substring(cmd_start+4,data.length-1); - var dataval = ''; - } - if (parsedData.command == 'L100') { //fmbXXX - var data = parsedData.raw; - start = "20"; - end = "02"; - var startcmd = data.indexOf('$GPRMC'); - var dataval = data.substring(startcmd); - //var dataval=data.substring(cmd_start+4,data.length-1); - - } - - if (parsedData.command == '80') { //fmbXXX - var data = parsedData.raw; - start = "2929"; - end = "0d"; - - var dataval = data.substring(10, 90); - - } - - if (parsedData.command == 'TS') { //fmbXXX - var data = parsedData.raw; - start = "$$"; - end = "0a"; - - var dataval = data.substring(0, data.length - 2) - - } - if (parsedData.command == 'VTX') { - var data = parsedData.raw; - start = "Sender"; - end = "PKTEND"; - - var dataval = data.substring(7, data.length - 7); - - } - if (parsedData.command == 'tracker') { - var data = parsedData.raw; - start = "imei:"; - end = ";"; - - var dataval = data; - - } - if (parsedData.command == 'NR' || parsedData.command == 'IF' || parsedData.command == 'EA') { - var data = parsedData.raw; - start = "$Header"; - end = "*"; - - var dataval = data; - - } - TCPUTIL.insertIgnition(parsedData, start, end, dataval, KafkaService); - } - // at line 804, write method to be called from TCPUTIL// - if (parsedData.fuelVoltage && parsedData.currentFuel != null) { - TCPUTIL.checkFuelFill(x[0], parsedData, x[0].lookedUpVehicleType.tank_size, KafkaService) - } - // - if (parsedData.sos == true) { - TCPUTIL.sosAlert(x[0].lookedUpDevice, x[0].lookedUpUser[0], parsedData); - } - var today_odo = 0 - var distFromLastStop = 0 - if (parsedData.isFluctuation) { - interpolatedDistance = 0 - today_odo = (x[0].lookedUpDevice.today_odo || 0) - distFromLastStop = (x[0].lookedUpDevice.distFromLastStop || 0) - } - else { - today_odo = interpolatedDistance + (x[0].lookedUpDevice.today_odo || 0) - distFromLastStop = interpolatedDistance + (x[0].lookedUpDevice.distFromLastStop || 0) - } - - var incObj = { "total_odo": interpolatedDistance }; - var today_start_location = !x[0].lookedUpDevice.today_start_location ? { lat: parsedData.latDecimal, long: parsedData.longDecimal } : x[0].lookedUpDevice.today_start_location; - //increment today_running / today_stopped - if (x[0].lookedUpDevice.last_ACC == 1) { - var today_running = new Date().getTime() - new Date(x[0].insertionTime).getTime(); - incObj['today_running'] = today_running; - - } - else { - var today_stopped = new Date().getTime() - new Date(x[0].insertionTime).getTime(); - incObj['today_stopped'] = today_stopped; - - } - var parsedSpeed = parseInt(parsedData.speed); - if (parsedData.ignition == 1 || (typeof parsedData.ignition === 'undefined' && x[0].lookedUpDevice.last_ACC == '1')) { - if (0 <= parsedSpeed && parsedSpeed < 20) { - incObj['speedChart.0-20'] = 1 - } - else if (20 <= parsedSpeed && parsedSpeed < 40) { - incObj['speedChart.20-40'] = 1 - } - else if (40 <= parsedSpeed && parsedSpeed < 60) { - incObj['speedChart.40-60'] = 1 - } - else if (60 <= parsedSpeed && parsedSpeed < 80) { - incObj['speedChart.60-80'] = 1 - } - else if (80 <= parsedSpeed && parsedSpeed < 100) { - incObj['speedChart.80-100'] = 1 - } - else if (100 <= parsedSpeed) { - incObj['speedChart.>100'] = 1 - } - } - Device.update( - { "Device_ID": parsedData.imei }, - { - $set: { - "last_loc.type": "Point", - "last_loc.coordinates": [parsedData.longDecimal, parsedData.latDecimal], - "sec_last_location.lat": x[0].lookedUpDevice.last_location ? x[0].lookedUpDevice.last_location.lat : null, - "sec_last_location.long": x[0].lookedUpDevice.last_location ? x[0].lookedUpDevice.last_location.long : null, - "sec_last_speed": x[0].lookedUpDevice.last_speed, - "last_location.lat": parsedData.latDecimal, - "last_location.long": parsedData.longDecimal, - "last_ping_on": new Date(), - "last_device_time" : new Date(parsedData.date), - "last_speed": parsedData.speed, - "currentFuel": parsedData.currentFuel != null ? parsedData.currentFuel : null, - "currentFuelVoltage": parsedData.fuelVoltage ? parsedData.fuelVoltage : null, - "satellites": parsedData.satellites ? parsedData.satellites : null, - "gpsTracking": parsedData['GPS positioned'] ? parsedData['GPS positioned'] : "0", - "today_odo": today_odo, - "heading": parsedData.heading, - "distFromLastStop": distFromLastStop, - "power": (parsedData.power == "1" || parsedData.power == "0") ? parsedData.power : x[0].lookedUpDevice.power, - "ac": parsedData.ac, - "today_start_location" : today_start_location - }, - - $inc: incObj - - }, - function (err, numAffected) { - if (err) { - console.error(err); - } - if (!err) { - - Device.find({ "Device_ID": parsedData.imei }).populate('user').exec(function (err, devices) { - if (err) { - console.error(err); - - } - else { - if (devices[0].integrationId) { - OutgoingIntegrations.deliver(devices[0], inserted.ops[0]); - } - KafkaService.sendRecord({ namespace: 'gpsio', room: devices[0].Device_ID, channel: devices[0].Device_ID.toString() + 'acc', data: [devices[0].last_ACC, devices[0].Device_ID.toString(), new Date(), devices[0]] }) - //gpsio.to(devices[0].Device_ID).emit(devices[0].Device_ID.toString() + 'acc', devices[0].last_ACC, devices[0].Device_ID.toString(), new Date(), devices[0]) - - if ((parsedData.power == "0" || parsedData.power == "1") && x[0].lookedUpDevice.power != parsedData.power) { - - TCPUTIL.setPowerNotif(x[0].lookedUpDevice, parsedData.power, KafkaService, devices[0].user); - } - } - }) - TCPUTIL.setDeviceStatus(x[0].lookedUpDevice, null); - if (x[0].lookedUpCurrentTrip) { - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $inc: { "distanceTravelled": interpolatedDistance } }).exec(); - } - } - - }); - - } - else { - var status = 'OUT OF REACH'; - if (parsedData.ignition != null) { - if(parsedData.ignition == 1){ - if (parsedData.speed > 1) { - status = 'RUNNING' - } else { - status = 'IDLING' - } - } - if (parsedData.ignition == 0) { - status = 'STOPPED' - } - } - else{ - status = 'STOPPED' - } - Device.update( - { "Device_ID": parsedData.imei }, - { - $set: { - "last_loc.type": "Point", - "last_loc.coordinates": [parsedData.longDecimal, parsedData.latDecimal], - //"sec_last_location.lat": x[0].lookedUpDevice.last_location ? x[0].lookedUpDevice.last_location.lat : null, - //"sec_last_location.long": x[0].lookedUpDevice.last_location ? x[0].lookedUpDevice.last_location.long : null, - //"sec_last_speed": x[0].lookedUpDevice.last_speed, - "last_location.lat": parsedData.latDecimal, - "last_location.long": parsedData.longDecimal, - "last_ping_on": new Date(), - "last_device_time" : new Date(parsedData.date), - "last_speed": parsedData.speed, - "status": status, - "status_updated_at" : new Date(), - //"currentFuel": parsedData.currentFuel != null ? parsedData.currentFuel : null, - //"currentFuelVoltage": parsedData.fuelVoltage ? parsedData.fuelVoltage : null, - "satellites": parsedData.satellites ? parsedData.satellites : null, - "gpsTracking": parsedData['GPS positioned'] ? parsedData['GPS positioned'] : "0", - //"today_odo": today_odo, - "heading": parsedData.heading, - //"distFromLastStop": distFromLastStop, - "power": parsedData.power, - "ac": parsedData.ac - } - - } - ).exec(); - } - - } - }) - }); - } - else { - if ((parsedData.latDecimal == 0 || parsedData.longDecimal == 0) && x[0]) { - TCPUTIL.setDeviceStatus(x[0].lookedUpDevice, 'nofix'); - Device.update( - { "Device_ID": parsedData.imei }, - { - $set: { - "last_loc.type": "Point", - "last_loc.coordinates": [0, 0], - "sec_last_location.lat": x[0].lookedUpDevice.last_location ? x[0].lookedUpDevice.last_location.lat : null, - "sec_last_location.long": x[0].lookedUpDevice.last_location ? x[0].lookedUpDevice.last_location.long : null, - "sec_last_speed": x[0].lookedUpDevice.last_speed, - "last_location.lat": 0, - "last_location.long": 0, - "last_ping_on": new Date(), - "last_device_time" : new Date(parsedData.date), - "last_speed": parsedData.speed, - "currentFuel": parsedData.currentFuel ? parsedData.currentFuel : null, - "currentFuelVoltage": parsedData.fuelVoltage ? parsedData.fuelVoltage : null, - "satellites": parsedData.satellites ? parsedData.satellites : null, - } - }).exec(); - console.log("0,0 from : " + parsedData.imei); - } - - - } - - //}) - - /** SPEED LIMIT ALERTS */ - if (x[0] && parsedData.latDecimal != 0 && typeof parsedData.latDecimal == "number" - && typeof parsedData.longDecimal == "number" && !isNaN(parseFloat(parsedData.latDecimal)) - && !isNaN(parseFloat(parsedData.longDecimal))) { - if (parseFloat(parsedData.speed) >= x[0].lookedUpDevice.SpeedLimit && x[0].lookedUpDevice.SpeedAlert) { - - if (x[0].lookedUpDevice.overspeeding == true) { - return; - } - - TCPUTIL.sbTracking(null, x[0], 'os', parsedData.latDecimal, parsedData.longDecimal, null, null, parsedData.speed, KafkaService); - Notifs.create({ - "device": x[0].lookedUpDevice.Device_ID, - "vehicle": x[0].lookedUpDevice.vehicle, - "dealer": x[0].lookedUpDevice.created_by, - "user": x[0].lookedUpUser[0]._id, - "type": "overspeed", - "priority" : 3, - "group" : x[0].lookedUpDevice.vehicleGroup, - "trip" : x[0].lookedUpDevice.currentTrip, - "overSpeed" : parseFloat(parsedData.speed), - "lat" : parsedData.latDecimal, - "long" : parsedData.longDecimal, - "vehicleName" : x[0].lookedUpDevice.Device_Name, - "item": { "_type": "Speed Alert", "sentence": x[0].lookedUpDevice.Device_Name + " exceeded the speed limit of " + x[0].lookedUpDevice.SpeedLimit + ". Travelling at " + parseInt(parsedData.speed) + " kmph."} - }, function (err, result) { - if (err) { - console.error(err) - } - else { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { overspeeding: true }, $inc: {today_overspeeds : 1} }).exec(); - pushNotifs.notify(x[0].lookedUpUser[0], result); - KafkaService.sendRecord({ namespace: 'notifIO', room: null, channel : x[0].lookedUpUser[0]._id, data : [result]}) - //notifIO.emit(x[0].lookedUpUser[0]._id, result) - Utilities.setAddress(result.lat,result.long,result._id,"address","notifications"); - } - }) - } - else if (parseFloat(parsedData.speed) < x[0].lookedUpDevice.SpeedLimit) { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { overspeeding: false } }).exec(); - } - } - - /**GEO FENCE ALERTS */ - if (x[0] && parsedData.latDecimal != 0 && typeof parsedData.latDecimal == "number" - && typeof parsedData.longDecimal == "number" && !isNaN(parseFloat(parsedData.latDecimal)) - && !isNaN(parseFloat(parsedData.longDecimal))) { - - GeoFence.find( - { - geofence: { - $geoIntersects: { - $geometry: parsedData.geoJSON - } - }, - uid: {$in : [x[0].lookedUpDevice.user, x[0].lookedUpDevice.created_by]}, - status: true - } - ).exec(function (err, geoWithins) { - if (err) { - console.error(err); - return; - } - if (geoWithins.length > 0) { - - - - - /**if a location is found to be inside, determine if the previous location was inside or outside */ - var geoWithin = geoWithins[0]; - - //update geofence model [field : devicesWithin] - GeoFence.update( - { _id: geoWithin._id }, - { $addToSet: { devicesWithin: x[0].lookedUpDevice._id } }, - function (err, inserted) { - if (err) { - console.error(err); - } - } - ) - - GeoFence - .find( - { - _id: geoWithin._id, - geofence: { - $geoIntersects: { - $geometry: x[0].geoJSON - } - //uid : x[0].lookedUpDevice.user, - //status: true - } - }) - .exec(function (err, previousGeo) { - - if (err) { - console.error(err) - return - } - if (previousGeo.length > 0) { - /** both ultimate and penultimate locations are inside. nothing's changed. */ - } - else { - var tripId = null; - if (x[0].lookedUpCurrentTrip) { - tripId = x[0].lookedUpCurrentTrip._id; - } - //check if this geoFence is assigned as loading site for vehicle's current trip - if (x[0].lookedUpCurrentTrip && x[0].lookedUpCurrentTrip.startSite.toString() == geoWithin._id.toString()) { - tripId = x[0].lookedUpCurrentTrip._id; - //vehicle entering start site - if (x[0].lookedUpCurrentTrip.tripType == 2) { - //two way trip - if (x[0].lookedUpCurrentTrip.endSiteExitAt && x[0].lookedUpCurrentTrip.startSiteExitAt) { - // - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "UNASSIGNED", currentTrip : null, tripPTA : null, tripETA : null, loadingDeparture : null, unloadingDeparture : null } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "COMPLETED", startSiteReEnterAt: new Date(), tripPTA : null, tripETA : null } }).exec() - TCPUTIL.sbTracking(null,x[0],'tripEnd', parsedData.latDecimal, parsedData.longDecimal,null,null,null,KafkaService) - TCPUTIL.setTravelDelay('reverseTransitComplete', x[0].lookedUpCurrentTrip, new Date(), x[0].lookedUpDevice); - if (x[0].lookedUpUser[0].tripGeneration == 'scheduled') { - // createScheduledTrip - /* TCPUTIL.setScheduledTrip(x[0].lookedUpDevice); */ - } - else if (x[0].lookedUpUser[0].tripGeneration == 'auto') { - //change the vehicle's group to geo fence group if it is not the same - - //cancel current trip and create a new trip with the information available - var d = new Date(); - var newId = mongoose.Types.ObjectId(); - tripId = newId; - var newRouteMap = { - "_id" : newId, - "device" : x[0].lookedUpDevice._id, - "user" : x[0].lookedUpUser[0]._id, - "device_name": x[0].lookedUpDevice.Device_Name, - "group" : x[0].lookedUpDevice.vehicleGroup, - "driver" : x[0].lookedUpCurrentTrip ? x[0].lookedUpCurrentTrip.driver : null, - "startSite" : geoWithin._id, - "createdOn": d, - "startSiteEnterAt" : d, - "status" : "LOADING", - "poi" : [], - "tripType" : 2, - "radius" : 500, - "generated" : "auto" - } - RouteMap.create(newRouteMap, function (err, newTrip) { - if (err) { - console.error(err); - return; - } - else { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "LOADING", vehicleGroup: geoWithin.vehicleGroup, currentTrip: newTrip._id, tripPTA : null, tripETA : null, loadingDeparture : null, unloadingDeparture : null } }).exec(); - if (x[0].lookedUpCurrentTrip) { - //RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "COMPLETED", startSiteReEnterAt: new Date(), tripPTA : null, tripETA : null } }).exec() - //TCPUTIL.sbTracking(null,x[0],'tripEnd', parsedData.latDecimal, parsedData.longDecimal,null,null,null,sbNotifIO) - } - Groups.update({ _id: geoWithin.vehicleGroup }, { $addToSet: { devices: x[0].lookedUpDevice._id } }).exec() - Groups.update({ _id: x[0].lookedUpDevice.vehicleGroup }, { $pull: { devices: x[0].lookedUpDevice._id } }).exec(); - } - }) - } - - - } - else { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "LOADING" } }).exec() - RouteMap.update({_id : x[0].lookedUpCurrentTrip._id}, {$set : {status : "LOADING", startSiteEnterAt : new Date()}}).exec() - } - } - if (x[0].lookedUpCurrentTrip.tripType == 1) { - //one way trip; set status to LOADING - if (!x[0].lookedUpCurrentTrip.startSiteEnterAt){ - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "LOADING" } }).exec() - RouteMap.update({_id : x[0].lookedUpCurrentTrip._id}, {$set : {status : "LOADING", startSiteEnterAt : new Date()}}).exec() - } - else if (geoWithin.type == 'Loading' && x[0].lookedUpUser[0].tripGeneration == 'auto') { - //change the vehicle's group to geo fence group if it is not the same - - //cancel current trip and create a new trip with the information available - var d = new Date(); - var newId = mongoose.Types.ObjectId(); - tripId = newId; - var newRouteMap = { - "_id" : newId, - "device" : x[0].lookedUpDevice._id, - "user" : x[0].lookedUpUser[0]._id, - "device_name" : x[0].lookedUpDevice.Device_Name, - "driver" : x[0].lookedUpCurrentTrip ? x[0].lookedUpCurrentTrip.driver : null, - "startSite": geoWithin._id, - "group" : x[0].lookedUpDevice.vehicleGroup, - "createdOn": d, - "startSiteEnterAt" : d, - "status" : "LOADING", - "poi" : [], - "tripType" : 2, - "radius" : 500, - "generated" : "auto" - } - RouteMap.create(newRouteMap, function (err, newTrip) { - if (err) { - console.error(err); - return; - } - else { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "LOADING", vehicleGroup: geoWithin.vehicleGroup, currentTrip: newTrip._id, tripPTA : null, tripETA : null, loadingDeparture : null, unloadingDeparture : null } }).exec(); - if (x[0].lookedUpCurrentTrip) { - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "COMPLETED", cancelledAt: new Date(), tripPTA: null, tripETA: null }, $push: { deviations: {"type": "newLoading","time" : new Date()}} }).exec() - } - Groups.update({ _id: geoWithin.vehicleGroup }, { $addToSet: { devices: x[0].lookedUpDevice._id } }).exec() - Groups.update({ _id: x[0].lookedUpDevice.vehicleGroup }, { $pull: { devices: x[0].lookedUpDevice._id } }).exec(); - } - }) - } - - } - if (x[0].lookedUpCurrentTrip.tripType == 0 && !x[0].lookedUpCurrentTrip.startSiteEnterAt) { - //round trip; set status to LOADING - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "LOADING" } }).exec() - RouteMap.update({_id : x[0].lookedUpCurrentTrip._id}, {$set : {status : "LOADING", startSiteEnterAt : new Date()}}).exec() - } - } - else if (geoWithin.type == 'Loading' && x[0].lookedUpUser[0].tripGeneration == 'auto') { - //change the vehicle's group to geo fence group if it is not the same - - //cancel current trip and create a new trip with the information available - var d = new Date(); - var newId = mongoose.Types.ObjectId(); - tripId = newId; - var newRouteMap = { - "_id" : newId, - "device" : x[0].lookedUpDevice._id, - "user" : x[0].lookedUpUser[0]._id, - "device_name" : x[0].lookedUpDevice.Device_Name, - "driver" : x[0].lookedUpCurrentTrip ? x[0].lookedUpCurrentTrip.driver : null, - "startSite": geoWithin._id, - "group" : x[0].lookedUpDevice.vehicleGroup, - "createdOn": d, - "startSiteEnterAt" : d, - "status" : "LOADING", - "poi" : [], - "tripType" : 2, - "radius" : 500, - "generated" : "auto" - } - RouteMap.create(newRouteMap, function (err, newTrip) { - if (err) { - console.error(err); - return; - } - else { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "LOADING", vehicleGroup: geoWithin.vehicleGroup, currentTrip: newTrip._id, tripPTA : null, tripETA : null, loadingDeparture : null, unloadingDeparture : null } }).exec(); - if (x[0].lookedUpCurrentTrip) { - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "COMPLETED", cancelledAt: new Date(), tripPTA : null, tripETA : null }, $push: { deviations: {"type": "newLoading","time" : new Date()}} }).exec() - } - Groups.update({ _id: geoWithin.vehicleGroup }, { $addToSet: { devices: x[0].lookedUpDevice._id } }).exec() - Groups.update({ _id: x[0].lookedUpDevice.vehicleGroup }, { $pull: { devices: x[0].lookedUpDevice._id } }).exec(); - } - }) - } - //check if this geoFence is assigned as unloading site for vehicle's current trip - if (x[0].lookedUpCurrentTrip && x[0].lookedUpCurrentTrip.endSite && x[0].lookedUpCurrentTrip.endSite.toString() == geoWithin._id.toString()) { - tripId = x[0].lookedUpCurrentTrip._id; - //vehicle entering end site - if (x[0].lookedUpCurrentTrip.tripType == 2) { - //two way trip - if (!x[0].lookedUpCurrentTrip.endSiteEnterAt) { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "UNLOADING", tripPTA : null, tripETA : null } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "UNLOADING", endSiteEnterAt: new Date(), tripPTA: null, tripETA: null } }).exec() - TCPUTIL.setTravelDelay('transitComplete', x[0].lookedUpCurrentTrip, new Date(), x[0].lookedUpDevice); - } - } - if (x[0].lookedUpCurrentTrip.tripType == 1) { - //one way trip; set status to LOADING - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "UNLOADING", tripPTA : null, tripETA : null } }).exec() - RouteMap.update({_id : x[0].lookedUpCurrentTrip._id}, {$set : {status : "UNLOADING", endSiteEnterAt : new Date(), tripPTA : null, tripETA : null}}).exec() - TCPUTIL.setTravelDelay('transitComplete', x[0].lookedUpCurrentTrip, new Date(), x[0].lookedUpDevice); - } - if (x[0].lookedUpCurrentTrip.tripType == 0 && x[0].lookedUpCurrentTrip.startSiteExitAt) { - //one way trip; set status to COMPLETED - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "UNASSIGNED", currentTrip : null, tripPTA : null, tripETA : null, loadingDeparture : null, unloadingDeparture : null } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "COMPLETED", endSiteEnterAt: new Date(), tripPTA : null, tripETA : null } }).exec() - TCPUTIL.sbTracking(null,x[0],'tripEnd', parsedData.latDecimal, parsedData.longDecimal,null,null,null,KafkaService) - - if (x[0].lookedUpUser[0].tripGeneration == 'scheduled') { - // createScheduledTrip - /* TCPUTIL.setScheduledTrip(x[0].lookedUpDevice); */ - } - } - } - else if (x[0].lookedUpCurrentTrip && geoWithin.type == 'Unloading') { - if (geoWithin.vehicleGroup.toString() == x[0].lookedUpDevice.vehicleGroup.toString()) { - tripId = x[0].lookedUpCurrentTrip._id; - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "UNLOADING", tripPTA : null, tripETA : null } }).exec() - RouteMap.update({_id : x[0].lookedUpCurrentTrip._id}, {$set : {status : "UNLOADING", endSite: geoWithin._id, endSiteEnterAt : new Date(), tripPTA : null, tripETA : null}}).exec() - TCPUTIL.setTravelDelay('transitComplete', x[0].lookedUpCurrentTrip, new Date(), x[0].lookedUpDevice); - } - } - - /**socket emit event for this 'imei' ENTERING geoFence 'geoWithin.name' */ - if (geoWithin.entering == true) { - Notifs.create({ - "device": x[0].lookedUpDevice.Device_ID, - "dealer": x[0].lookedUpDevice.created_by, - "vehicle" : x[0].lookedUpDevice.vehicle, - "user": x[0].lookedUpUser[0]._id, - "type": "Geo-Fence", - "org":x[0].lookedUpDevice.org, - "priority" : 1, - "group" : x[0].lookedUpDevice.vehicleGroup, - "direction": "In", - "trip" : tripId, - "geoid" : geoWithin._id, - "lat" : parsedData.latDecimal, - "long" : parsedData.longDecimal, - "vehicleName" : x[0].lookedUpDevice.Device_Name, - "item": { "_type": "Geo-Fence Alert", "sentence": x[0].lookedUpDevice.Device_Name + " entered " + geoWithin.geoname } - }, function (err, result) { - if (err) { - console.error(err) - } - else { - GeofenceReports.create({ - vehicle: x[0].lookedUpDevice.vehicle, - device: x[0].lookedUpDevice._id, - geofence: geoWithin._id, - group : x[0].lookedUpDevice.vehicleGroup, - org:x[0].lookedUpDevice.org, - user: x[0].lookedUpUser[0]._id, - arrivalTime: new Date() - }, function (err, report) { - if (err) { - console.error(err); - return; - } - //Utilities.setAddress(report.lat, report.long,report._id, "address", "geofenceReports") - }) - pushNotifs.notify(x[0].lookedUpUser[0], result); - KafkaService.sendRecord({ namespace: 'notifIO', room: null, channel: x[0].lookedUpUser[0]._id, data: [result] }); - //notifIO.emit(x[0].lookedUpUser[0]._id, result) - Utilities.setAddress(result.lat,result.long,result._id,"address","notifications"); - } - }) - } - } - }) - - } - - else { - /**if a location is not found inside any geoFence, determine if the previous location was inside or outside ANY of the geoFences for that device */ - - - //update geofence model [field : devicesWithin] - GeoFence.update( - {}, - { $pull: { devicesWithin: x[0].lookedUpDevice._id } }, - {multi : true}, - function (err, inserted) { - if(err){ - console.error(err); - } - } - ) - - GeoFence - .find( - { - geofence: { - $geoIntersects: { - $geometry: x[0].geoJSON - } - }, - uid: {$in : [x[0].lookedUpDevice.user, x[0].lookedUpDevice.created_by]}, - status: true - }) - .populate('vehicleGroup') - .exec(function (err, previousGeos) { - if (err) { - console.error(err) - return - } - if (previousGeos.length > 0) { - - var tripId = null; - if (x[0].lookedUpCurrentTrip) { - tripId = x[0].lookedUpCurrentTrip._id; - } - //check if this geoFence is assigned as loading site for vehicle's current trip - if (x[0].lookedUpCurrentTrip && x[0].lookedUpCurrentTrip.startSite.toString() == previousGeos[0]._id.toString()) { - var now = new Date(); - - //vehicle exiting start site - if (x[0].lookedUpCurrentTrip.tripType == 2) { - //two way trip - - - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "TRANSIT", loadingDeparture : now } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "TRANSIT", startSiteExitAt: now } }).exec() - TCPUTIL.sbTracking(null, x[0], 'tripStart', parsedData.latDecimal, parsedData.longDecimal, null, null, null, KafkaService); - } - if (x[0].lookedUpCurrentTrip.tripType == 1) { - //one way trip; set status to LOADING - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "TRANSIT", loadingDeparture : now } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "TRANSIT", startSiteExitAt: now } }).exec() - TCPUTIL.sbTracking(null, x[0], 'tripStart', parsedData.latDecimal, parsedData.longDecimal, null, null, null, KafkaService); - } - if (x[0].lookedUpCurrentTrip.tripType == 0) { - //round trip; set status to Transit - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "TRANSIT", loadingDeparture : now } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "TRANSIT", startSiteExitAt: now } }).exec() - TCPUTIL.sbTracking(null, x[0], 'tripStart', parsedData.latDecimal, parsedData.longDecimal, null, null, null, KafkaService); - } - if (x[0].lookedUpCurrentTrip.startSiteEnterAt) { - TCPUTIL.setTimeAtSite(x[0].lookedUpCurrentTrip.startSiteEnterAt, now , x[0].lookedUpCurrentTrip._id, 'Loading'); - } - } - //check if this geoFence is assigned as unloading site for vehicle's current trip - if (x[0].lookedUpCurrentTrip && x[0].lookedUpCurrentTrip.endSite && x[0].lookedUpCurrentTrip.endSite.toString() == previousGeos[0]._id.toString()) { - var now = new Date(); - - //vehicle exiting end site - if (x[0].lookedUpCurrentTrip.tripType == 2) { - //two way trip - if (!x[0].lookedUpCurrentTrip.endSiteExitAt) { - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "TRANSIT-Return", unloadingDeparture : now } }).exec() - RouteMap.update({_id : x[0].lookedUpCurrentTrip._id}, {$set : {status : "TRANSIT-Return", lastPOIIndex : null, endSiteExitAt : now}}).exec() - } - } - if (x[0].lookedUpCurrentTrip.tripType == 1 && x[0].lookedUpCurrentTrip.status != "COMPLETED") { - //one way trip; set status to LOADING - Device.update({ _id: x[0].lookedUpDevice._id }, { $set: { currentTripStatus: "UNASSIGNED", currentTrip : null, tripPTA : null, tripETA : null, loadingDeparture : null, unloadingDeparture : null } }).exec() - RouteMap.update({ _id: x[0].lookedUpCurrentTrip._id }, { $set: { status: "COMPLETED", endSiteExitAt: now, tripPTA : null, tripETA : null } }).exec() - TCPUTIL.sbTracking(null, x[0], 'tripEnd', parsedData.latDecimal, parsedData.longDecimal, null, null, null, KafkaService); - - if (x[0].lookedUpUser[0].tripGeneration == 'scheduled') { - // createScheduledTrip - /* TCPUTIL.setScheduledTrip(x[0].lookedUpDevice); */ - } - } - - if (x[0].lookedUpCurrentTrip.endSiteEnterAt) { - TCPUTIL.setTimeAtSite(x[0].lookedUpCurrentTrip.endSiteEnterAt, now, x[0].lookedUpCurrentTrip._id, 'Unloading'); - } - } - - - /** socket emit event for this 'imei' EXITING all geoFences 'previousGeos[i].name'. */ - - - for (var i = 0; i < 1; i++) { - - if (previousGeos[i].exiting == true) { - var prevGeo = previousGeos[0]; - Notifs.create({ - "device": x[0].lookedUpDevice.Device_ID, - "vehicle": x[0].lookedUpDevice.vehicle, - "dealer": x[0].lookedUpDevice.created_by, - "user": x[0].lookedUpUser[0]._id, - "group" : x[0].lookedUpDevice.vehicleGroup, - "type": "Geo-Fence", - "priority" : 1, - "direction": "Out", - "trip" : tripId, - "geoid" : previousGeos[0]._id, - "lat" : parsedData.latDecimal, - "long" : parsedData.longDecimal, - "vehicleName" : x[0].lookedUpDevice.Device_Name, - "item": { "_type": "Geo-Fence Alert", "sentence": x[0].lookedUpDevice.Device_Name + " exited " + previousGeos[0].geoname } - }, function (err, result) { - if (err) { - console.error(err) - } - else { - GeofenceReports.findOneAndUpdate( - { - device: x[0].lookedUpDevice._id, - geofence: previousGeos[0]._id, - departureTime: { $exists: false }, - vehicle: x[0].lookedUpDevice.vehicle, - user : x[0].lookedUpUser[0]._id - }, - { - $set: - { group : x[0].lookedUpDevice.vehicleGroup, departureTime: new Date(), vehicle: x[0].lookedUpDevice.vehicle, device: x[0].lookedUpDevice._id, geofence: previousGeos[0]._id, user : x[0].lookedUpUser[0]._id } - }, - { - sort: { "_id": -1 }, new: true, upsert: true - }, - function (err, latest) { - if (err) { - console.error(err); - return; - } - }) - pushNotifs.notify(x[0].lookedUpUser[0], result); - KafkaService.sendRecord({namespace : 'notifIO', room : null, channel : x[0].lookedUpUser[0]._id, data : [result]}) - //notifIO.emit(x[0].lookedUpUser[0]._id, result) - Utilities.setAddress(result.lat, result.long, result._id, "address", "notifications"); - if (prevGeo.vehicleGroup) { - var emails = prevGeo.vehicleGroup.contact_email; - if (emails.length < 1) { - return; - } - Notifs.findOne({ - "device": x[0].lookedUpDevice.Device_ID, - "type": "Geo-Fence", - "direction": "In", - "timestamp": { $lt: result.timestamp }, - "geoid" : prevGeo._id - }, {}, { sort: { 'timestamp' : -1 } }, function (err, lastInNotif) { - if (err) { - console.error(err); - return; - } - if (lastInNotif) { - - if (!x[0].lookedUpUser[0]) { - return; - } - var mailOptions = { - from: Utilities.getConfig().mailUser, // sender address - to: emails, // list of receivers - //cc: emails.length > 1 ? emails.shift() : null, - subject: Utilities.getConfig().orgName+"- GeoFence Activity", // Subject line moment(m.report_lastdate.overspeed).tz(m.timezone).format("YYYY-MM-DDTHH:mm"); - html:'
Geo-Fence Vehicle In Time Out Time
'+prevGeo.geoname+' '+x[0].lookedUpDevice.Device_Name+' '+moment(lastInNotif.timestamp).tz(x[0].lookedUpUser[0].timezone).format("YYYY-MM-DD HH:mm")+' '+moment(result.timestamp).tz(x[0].lookedUpUser[0].timezone).format("YYYY-MM-DD HH:mm")+'
' - } - if(emails.length > 0){ - Mailer.sendMail(mailOptions); - } - } - }) - } - } - }) - - - - } - } - } - else { - /**both ultimate and penultimate locations are inside. nothing's changed. */ - } - }) - - } - }) - } - } - } - - }); - - - - } - - - } catch (error) { - console.error(error); - } - } \ No newline at end of file diff --git a/dms.js b/dms.js deleted file mode 100644 index ee53898..0000000 --- a/dms.js +++ /dev/null @@ -1,225 +0,0 @@ -/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -/* Geodesy representation conversion functions (c) Chris Veness 2002-2017 */ -/* MIT Licence */ -/* www.movable-type.co.uk/scripts/latlong.html */ -/* www.movable-type.co.uk/scripts/geodesy/docs/module-dms.html */ -/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -'use strict'; -/* eslint no-irregular-whitespace: [2, { skipComments: true }] */ - - -/** - * Latitude/longitude points may be represented as decimal degrees, or subdivided into sexagesimal - * minutes and seconds. - * - * @module dms - */ - - -/** - * Functions for parsing and representing degrees / minutes / seconds. - * @class Dms - */ -var Dms = {}; - -// note Unicode Degree = U+00B0. Prime = U+2032, Double prime = U+2033 - - -/** - * Parses string representing degrees/minutes/seconds into numeric degrees. - * - * This is very flexible on formats, allowing signed decimal degrees, or deg-min-sec optionally - * suffixed by compass direction (NSEW). A variety of separators are accepted (eg 3° 37′ 09″W). - * Seconds and minutes may be omitted. - * - * @param {string|number} dmsStr - Degrees or deg/min/sec in variety of formats. - * @returns {number} Degrees as decimal number. - * - * @example - * var lat = Dms.parseDMS('51° 28′ 40.12″ N'); - * var lon = Dms.parseDMS('000° 00′ 05.31″ W'); - * var p1 = new LatLon(lat, lon); // 51.4778°N, 000.0015°W - */ -Dms.parseDMS = function(dmsStr) { - // check for signed decimal degrees without NSEW, if so return it directly - if (typeof dmsStr == 'number' && isFinite(dmsStr)) return Number(dmsStr); - - // strip off any sign or compass dir'n & split out separate d/m/s - var dms = String(dmsStr).trim().replace(/^-/, '').replace(/[NSEW]$/i, '').split(/[^0-9.,]+/); - if (dms[dms.length-1]=='') dms.splice(dms.length-1); // from trailing symbol - - if (dms == '') return NaN; - - // and convert to decimal degrees... - var deg; - switch (dms.length) { - case 3: // interpret 3-part result as d/m/s - deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; - break; - case 2: // interpret 2-part result as d/m - deg = dms[0]/1 + dms[1]/60; - break; - case 1: // just d (possibly decimal) or non-separated dddmmss - deg = dms[0]; - // check for fixed-width unseparated format eg 0033709W - //if (/[NS]/i.test(dmsStr)) deg = '0' + deg; // - normalise N/S to 3-digit degrees - //if (/[0-9]{7}/.test(deg)) deg = deg.slice(0,3)/1 + deg.slice(3,5)/60 + deg.slice(5)/3600; - break; - default: - return NaN; - } - if (/^-|[WS]$/i.test(dmsStr.trim())) deg = -deg; // take '-', west and south as -ve - - return Number(deg); -}; - - -/** - * Separator character to be used to separate degrees, minutes, seconds, and cardinal directions. - * - * Set to '\u202f' (narrow no-break space) for improved formatting. - * - * @example - * var p = new LatLon(51.2, 0.33); // 51°12′00.0″N, 000°19′48.0″E - * Dms.separator = '\u202f'; // narrow no-break space - * var pʹ = new LatLon(51.2, 0.33); // 51° 12′ 00.0″ N, 000° 19′ 48.0″ E - */ -Dms.separator = ''; - - -/** - * Converts decimal degrees to deg/min/sec format - * - degree, prime, double-prime symbols are added, but sign is discarded, though no compass - * direction is added. - * - * @private - * @param {number} deg - Degrees to be formatted as specified. - * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. - * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. - * @returns {string} Degrees formatted as deg/min/secs according to specified format. - */ -Dms.toDMS = function(deg, format, dp) { - if (isNaN(deg)) return null; // give up here if we can't make a number from deg - - // default values - if (format === undefined) format = 'dms'; - if (dp === undefined) { - switch (format) { - case 'd': case 'deg': dp = 4; break; - case 'dm': case 'deg+min': dp = 2; break; - case 'dms': case 'deg+min+sec': dp = 0; break; - default: format = 'dms'; dp = 0; // be forgiving on invalid format - } - } - - deg = Math.abs(deg); // (unsigned result ready for appending compass dir'n) - - var dms, d, m, s; - switch (format) { - default: // invalid format spec! - case 'd': case 'deg': - d = deg.toFixed(dp); // round/right-pad degrees - if (d<100) d = '0' + d; // left-pad with leading zeros (note may include decimals) - if (d<10) d = '0' + d; - dms = d + '°'; - break; - case 'dm': case 'deg+min': - d = Math.floor(deg); // get component deg - m = ((deg*60) % 60).toFixed(dp); // get component min & round/right-pad - if (m == 60) { m = 0; d++; } // check for rounding up - d = ('000'+d).slice(-3); // left-pad with leading zeros - if (m<10) m = '0' + m; // left-pad with leading zeros (note may include decimals) - dms = d + '°'+Dms.separator + m + '′'; - break; - case 'dms': case 'deg+min+sec': - d = Math.floor(deg); // get component deg - m = Math.floor((deg*3600)/60) % 60; // get component min - s = (deg*3600 % 60).toFixed(dp); // get component sec & round/right-pad - if (s == 60) { s = (0).toFixed(dp); m++; } // check for rounding up - if (m == 60) { m = 0; d++; } // check for rounding up - d = ('000'+d).slice(-3); // left-pad with leading zeros - m = ('00'+m).slice(-2); // left-pad with leading zeros - if (s<10) s = '0' + s; // left-pad with leading zeros (note may include decimals) - dms = d + '°'+Dms.separator + m + '′'+Dms.separator + s + '″'; - break; - } - - return dms; -}; - - -/** - * Converts numeric degrees to deg/min/sec latitude (2-digit degrees, suffixed with N/S). - * - * @param {number} deg - Degrees to be formatted as specified. - * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. - * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. - * @returns {string} Degrees formatted as deg/min/secs according to specified format. - */ -Dms.toLat = function(deg, format, dp) { - var lat = Dms.toDMS(deg, format, dp); - return lat===null ? '–' : lat.slice(1)+Dms.separator + (deg<0 ? 'S' : 'N'); // knock off initial '0' for lat! -}; - - -/** - * Convert numeric degrees to deg/min/sec longitude (3-digit degrees, suffixed with E/W) - * - * @param {number} deg - Degrees to be formatted as specified. - * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. - * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. - * @returns {string} Degrees formatted as deg/min/secs according to specified format. - */ -Dms.toLon = function(deg, format, dp) { - var lon = Dms.toDMS(deg, format, dp); - return lon===null ? '–' : lon+Dms.separator + (deg<0 ? 'W' : 'E'); -}; - - -/** - * Converts numeric degrees to deg/min/sec as a bearing (0°..360°) - * - * @param {number} deg - Degrees to be formatted as specified. - * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. - * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. - * @returns {string} Degrees formatted as deg/min/secs according to specified format. - */ -Dms.toBrng = function(deg, format, dp) { - deg = (Number(deg)+360) % 360; // normalise -ve values to 180°..360° - var brng = Dms.toDMS(deg, format, dp); - return brng===null ? '–' : brng.replace('360', '0'); // just in case rounding took us up to 360°! -}; - - -/** - * Returns compass point (to given precision) for supplied bearing. - * - * @param {number} bearing - Bearing in degrees from north. - * @param {number} [precision=3] - Precision (1:cardinal / 2:intercardinal / 3:secondary-intercardinal). - * @returns {string} Compass point for supplied bearing. - * - * @example - * var point = Dms.compassPoint(24); // point = 'NNE' - * var point = Dms.compassPoint(24, 1); // point = 'N' - */ -Dms.compassPoint = function(bearing, precision) { - if (precision === undefined) precision = 3; - // note precision could be extended to 4 for quarter-winds (eg NbNW), but I think they are little used - - bearing = ((bearing%360)+360)%360; // normalise to range 0..360° - - var cardinals = [ - 'N', 'NNE', 'NE', 'ENE', - 'E', 'ESE', 'SE', 'SSE', - 'S', 'SSW', 'SW', 'WSW', - 'W', 'WNW', 'NW', 'NNW' ]; - var n = 4 * Math.pow(2, precision-1); // no of compass points at req’d precision (1=>4, 2=>8, 3=>16) - var cardinal = cardinals[Math.round(bearing*n/360)%n * 16/n]; - - return cardinal; -}; - - -/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -if (typeof module != 'undefined' && module.exports) module.exports = Dms; // ≡ export default Dms \ No newline at end of file diff --git a/gpsFunctions.js b/gpsFunctions.js deleted file mode 100644 index 52a4866..0000000 --- a/gpsFunctions.js +++ /dev/null @@ -1,127 +0,0 @@ - -/***************************************** - FUNCTIONS - ******************************************/ -exports.rad = function (x) { - return x * Math.PI / 180; -}; - -/* - @param p1: {lat:X,lng:Y} - @param p2: {lat:X,lng:Y} - */ -exports.get_distance = function (p1, p2) { - var R = 6378137; // Earth’s mean radius in meter - var dLat = exports.rad(p2.lat - p1.lat); - var dLong = exports.rad(p2.lng - p1.lng); - var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + - Math.cos(exports.rad(p1.lat)) * Math.cos(exports.rad(p2.lat)) * - Math.sin(dLong / 2) * Math.sin(dLong / 2); - var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); - var d = R * c; - return d; // returns the distance in meter -}; - -exports.send = function (socket, msg) { - socket.write(msg); -}; - -exports.parse_data = function (data) { - data = data.replace(/(\r\n|\n|\r)/gm, ''); //Remove 3 type of break lines - var cmd_start = data.indexOf('B'); //al the incomming messages has a cmd starting with 'B' - if (cmd_start > 13)throw 'Device ID is longer than 12 chars!'; - var parts = { - 'start': data.substr(0, 1), - 'device_id': data.substring(1, cmd_start), - 'cmd': data.substr(cmd_start, 4), - 'data': data.substring(cmd_start + 4, data.length - 1), - 'finish': data.substr(data.length - 1, 1) - }; - return parts; -}; - -exports.parse_gps_data = function (str) { - var data = { - 'date': str.substr(0, 6), - 'availability': str.substr(6, 1), - 'latitude': gps_minute_to_decimal(parseFloat(str.substr(7, 9))), - 'latitude_i': str.substr(16, 1), - 'longitude': gps_minute_to_decimal(parseFloat(str.substr(17, 9))), - 'longitude_i': str.substr(27, 1), - 'speed': str.substr(28, 5), - 'time': str.substr(33, 6), - 'orientation': str.substr(39, 6), - 'io_state': str.substr(45, 8), - 'mile_post': str.substr(53, 1), - 'mile_data': parseInt(str.substr(54, 8), 16) - }; - return data; -}; - -exports.send_to = function (socket, cmd, data) { - if (typeof(socket.device_id) == 'undefined')throw 'The socket is not paired with a device_id yet'; - var str = gps_format.start; - str += socket.device_id + gps_format.separator + cmd; - if (typeof(data) != 'undefined') str += gps_format.separator + data; - str += gps_format.end; - send(socket, str); - //Example: (||) - separator: | ,start: (, end: ) -}; - -exports.minute_to_decimal = function (pos, pos_i) { - if (typeof(pos_i) === 'undefined') pos_i = 'N'; - var dg = parseInt(pos / 100); - var minutes = pos - (dg * 100); - var res = (minutes / 60) + dg; - return (pos_i.toUpperCase() === 'S' || pos_i.toUpperCase() === 'W') ? res * -1 : res; -}; - -// Send a message to all clients -exports.broadcast = function (message, sender) { - clients.forEach(function (client) { - if (client === sender) return; - client.write(message); - }); - process.stdout.write(message + '\n'); -}; - -exports.data_to_hex_array = function (data) { - var arr = []; - for (var i = 0; i < data.length; i++)arr.push(data[i].toString(16)); - return arr; -}; - -/* RETRUN AN INTEGER FROM A HEX CHAR OR integer */ -exports.hex_to_int = function (hex_char) { - return parseInt(hex_char, 16); -}; - -exports.sum_hex_array = function (hex_array) { - var sum = 0; - for (var i in hex_array)sum += exports.hex_to_int(hex_array[i]); - return sum; -}; - -exports.hex_array_to_hex_str = function (hex_array) { - var str = ''; - for (var i in hex_array) { - var char; - if (typeof(hex_array[i]) === 'number') char = hex_array[i].toString(16); - else char = hex_array[i].toString(); - str += exports.str_pad(char, 2, '0'); - } - return str; -}; - -exports.str_pad = function (input, length, string) { - string = string || '0'; - input = input + ''; - return input.length >= length ? input : new Array(length - input.length + 1).join(string) + input; -}; - -exports.crc_itu_get_verification = function (hex_data) { - var crc16 = require('crc-itu').crc16; - if (typeof(hex_data) === 'String') str = hex_data; - else str = exports.hex_array_to_hex_str(hex_data); - return crc16(str, 'hex'); -}; \ No newline at end of file diff --git a/src/app/login/login.controller.js b/src/app/login/login.controller.js deleted file mode 100644 index e69de29..0000000 diff --git a/src/assets/image/contact.controller (1).js b/src/assets/image/contact.controller (1).js deleted file mode 100644 index c0a78d9..0000000 --- a/src/assets/image/contact.controller (1).js +++ /dev/null @@ -1,6198 +0,0 @@ - -const Contact = require('../models/contacts'); -const Otp = require('../models/otpdb'); -var jwt = require('jsonwebtoken'); -var nodemailer = require('nodemailer'); -var mailer = require('../controllers/mailer'); -var request = require("request"); -var Count = require('../models/counter') -var crypto = require('crypto'); -const Device = require('../models/device'); -var ObjectId = require('mongodb').ObjectID; -var Utilities = require('../controllers/utilities.controller'); -var mongoose = require('mongoose'); -var org = require('../models/organisation') -var couponCode = require('../controllers/discountCode.controller'); - -const _poi = require('../models/poi'); - -//signUp and Email Verification - -// first_name: "ddddd" -// last_name: "aaaaa" -// email: "ga@adnate.in" -// pass: "q1q1q1" -// phone: "4434345554" -// supAdmin: "59cbbdbe508f164aa2fef3d8" -// isDealer: true -// expdate: "2021-03-31T10:06:06.363Z" -// Dealer: "5ab471736a40122297759ae9" -// user_id: "13123234435" -module.exports.createUserPeronalTracker = function (req, res) { - var pass = req.body.pass; - // delete req.body.pass; - req.body.salt = crypto.randomBytes(16).toString('hex'); - req.body.hash = crypto.pbkdf2Sync(pass, req.body.salt, 1000, 64, 'sha1').toString('hex'); - Contact.findOne({ $or: [{ "email": req.body.email }, { "phone": req.body.phone }] }).exec(function (err, data1) { - if (err) return res.send(err); - - if (data1 == null) { - var _contact = new Contact(req.body); - _contact.save(function (err, data) { - if (err) res.status(500).json({ "message": "Something Is Wrong" }); - res.send(data); - }) - } else { - if (data1.email == req.body.email) - res.status(500).json({ "message": "email already exists" }); - if (data1.phone == req.body.phone) - res.status(500).json({ "message": "Phone already exists" }); - } - }); - -} -module.exports.createUser = function (req, res) { - var pass = req.body.pass; - // delete req.body.pass; - req.body.salt = crypto.randomBytes(16).toString('hex'); - req.body.hash = crypto.pbkdf2Sync(pass, req.body.salt, 1000, 64, 'sha1').toString('hex'); - Contact.findOne({ $or: [{ "email": req.body.email }, { "phone": req.body.phone }] }).exec(function (err, data1) { - if (err) return res.send(err); - - if (data1 == null) { - var _contact = new Contact(req.body); - _contact.save(function (err, data) { - if (err) res.status(500).json({ "message": "Something Is Wrong" }); - res.send(data); - }) - } else { - if (data1.email == req.body.email) - res.status(500).json({ "message": "email already exists" }); - if (data1.phone == req.body.phone) - res.status(500).json({ "message": "Phone already exists" }); - } - }); - -} - -module.exports.createUserMany = function (req, res, next) { - req.trackRoute = req.body.trackRoute; - req.poi = req.body.poi; - req.stopNames = req.body.stopNames; - req.body = req.body.parent; - - //console.log("req.stopNames=>", req.stopNames); - _poi.insertMany(req.stopNames, function (error, docs) { - if (error) { - return console.log("ADD STOP POI DONE ERROR"); - } - // console.log("ADD STOP POI DONE", JSON.stringify(docs)); - }); - for (var i = 0; i < req.body.length; i++) { - (function (reqdata, id) { - Contact.findOne({ phone: reqdata.phone }, function (err, adventure) { - if (adventure == null) { - (function (addPRED, id2) { - addPRED.salt = crypto.randomBytes(16).toString('hex'); - addPRED.hash = crypto.pbkdf2Sync('Reset@123', addPRED.salt, 1000, 64, 'sha1').toString('hex'); - var _contact = new Contact(addPRED); - _contact.save(function (err, data) { - if (id == (req.body.length - 1)) { - //res.send({msg:'if allDONE!'}); - - next(); - } - }) - })(reqdata, id); - } else { - if (id == (req.body.length - 1)) { - //res.send({msg:'else allDONE!'}); - next(); - } - } - }) - })(req.body[i], i); - - } -} -module.exports.createUserMany1 = function (req, res) { - - async function cm() { - for (var dd in req.body) { - - Contact.findOne({ phone: req.body[dd].phone }, function (err, adventure) { - if (err) return; - if (adventure == null) { - // - req.body[dd].salt = crypto.randomBytes(16).toString('hex'); - req.body[dd].hash = crypto.pbkdf2Sync('Reset@123', req.body[dd].salt, 1000, 64, 'sha1').toString('hex'); - var _contact = new Contact(req.body[dd]); - - _contact.save(function (err, data) { - if (err) res.status(500).json({ "message": "Something Is Wrong" }); - // res.send(data); - }) - - // - } - }); - - } - } - cm().then(function (resp) { - res.send({ "mag": "success" }); - }) - - - -} - -module.exports.editUser = function (req, res) { - var pass = req.body.pass; - req.body.salt = crypto.randomBytes(16).toString('hex'); - req.body.hash = crypto.pbkdf2Sync(pass, req.body.salt, 1000, 64, 'sha1').toString('hex'); - - Contact.update({ _id: req.body._id }, { $set: req.body }, { multi: true }, function (err, data) { - if (err) return res.send(err); - else - res.send(data); - }); -} -module.exports.updateImagePath = function (req, res) { - if (req.body.imageDoc) { - - Contact.update({ _id: req.body._id }, { $set: { imageDoc: req.body.imageDoc } }, { multi: true }, function (err, data) { - if (err) return res.send(err); - else - res.send(data); - }); - } - -} - - -module.exports.signUp = function (req, res) { - if (req.body.org_name) { - newOrgJson = { - organisation_name: req.body.org_name, - phone: req.body.org_phone, - email: req.body.org_email, - website: req.body.org_website, - }; - var newOrg = new org(JSON.parse(JSON.stringify(newOrgJson))); - newOrg.save(function (err, organisation) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - if (organisation) { - - if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") { - return res.status(401).json({ "message": "Null Value Error" }); - } - //superadmin can able to add dealer - - else if (req.body.sysadmin == true) { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) { - if (error) { - console.error(error); - } - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) { - if (err) { - console.error(err); - } - if (req.body.email && req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - role: req.body.roles, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: true, - isSuperAdmin: false, - Dealer: req.body.Dealer, - supAdmin: req.body.supAdmin, - custumerid: 'c_' + cuscount.seq, - dealerid: 'd_' + dealcount.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - }; - if (req.body.group != "") { - newUserJson.group = req.body.group; - } - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - else { - res.status(200).json({ "message": "Registered Sucessfully" }); - - } - }) - } - }); - }); - } - else if (req.body.custumer == true) { - - var Distributer_string = req.body.user_id; - var user_regex = new RegExp(["^", Distributer_string, "$"].join(""), "i"); - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { user_id: user_regex }] }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - if (user.email == req.body.email) { - res.status(200).json({ "message": "Email ID already exists" }) - } else if (req.body.user_id == user.user_id) { - res.status(200).json({ "message": "USER_ID already exists" }) - } else if (user.phone == req.body.phone) { - res.status(200).json({ "message": "Mobile Number already exists" }) - } else { - res.status(200).json({ "message": "User Duplicate" }) - } - } - else{ - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) { - if (error) { - console.error(error); - } - if (req.body.email && req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - return; - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - } - else if (req.body.email) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - email: req.body.email.toLowerCase(), - phone: "nophone" + counter.seq, - email_verfi: true, - phone_verfi: true, - isDealer: false, - supAdmin: req.body.supAdmin, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - } - else if (req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - phone: req.body.phone, - email_verfi: true, - supAdmin: req.body.supAdmin, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - email: 'noEmail' + counter.seq, - - custumerid: 'c_' + counter.seq, - - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // email:'noEmail'+ counter.seq - - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - phone: req.body.phone, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - supAdmin: req.body.supAdmin, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - }; - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - } - - - }) - } - }) - - } - else if (req.body.otp && req.body.phone) { - var token; - Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) { - if (err) { - console.error(err); - return err; - } - if (otpres) { - // - var dbtime = new Date(otpres.timestamp); - var curtime = new Date(); - var diffMs = (curtime - dbtime); // milliseconds between now & Christmas - var diffDays = Math.floor(diffMs / 86400000); // days - var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours - var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes - if (otpres.otp == req.body.otp) { - Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) { - if (err) { - console.error(err) - return res.status(400).send(err); - } - else { - return res.status(200).json({ "message": "Mobile Verified" }); - } - }); - } - else { - res.status(500).json({ "message": "Didn't match otp" }); - } - } - }) - } - else if (req.body.phone && req.body.email) { - var Distributer_string = req.body.user_id; - var user_regex = new RegExp(["^", Distributer_string, "$"].join(""), "i"); - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { user_id: user_regex }] }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - if (user.email == req.body.email) { - res.status(200).json({ "message": "Email ID already exists" }) - } else if (req.body.user_id == user.user_id) { - res.status(200).json({ "message": "USER_ID already exists" }) - } else if (user.phone == req.body.phone) { - res.status(200).json({ "message": "Mobile Number already exists" }) - } else { - res.status(200).json({ "message": "User Duplicate" }) - } - } - else { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var otprand = randomString(4, '#'); - var randomemail = randomString(16, '#aA!'); - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - var newUserJson = { - - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - supAdmin: req.body.supAdmin, - org: organisation._id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - otp: otprand, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - - timezone: req.body.timezone - }; - //console.log("Inside otp function0"); - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err) { - if (err) { - if (err.name === 'MongoError' && err.code === 11000) { - // Duplicate username - return res.status(200).send({ succes: false, message: 'User already exist!' }); - } - - // Some other error - return res.status(500).send(err); - } - else { - request({ - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + otprand, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - res.status(200).json({ "message": "OTP sent successfully1" }) - }); - } - }) - - }) - - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - otp: otprand, - id_email_ver: randomemail, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - timezone: req.body.timezone - }; - - // console.log("Inside otp function1"); - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - email(req.body.first_name, req.body.email, randomemail); - request({ - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20to%20validate%20your%20login ' + otprand, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - res.status(200).json({ "message": "OTP sent successfully2" }) - }); - - }) - - } - - }) - - } - }) - - } - - - else if (req.body.phone) { - Contact.findOne({ "phone": req.body.phone }, function (err, ph) { - if (err) { - console.error(err); - } - else if (ph) { - res.status(500).json({ "message": "Mobile Number already Exists" }) - } - else { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - phone: req.body.phone, - supAdmin: req.body.supAdmin, - password: req.body.password, - email_verfi: true, - phone_verfi: true, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - - timezone: req.body.timezone - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - let datastore = newUserJson; - // let a = otp(newUserJson); - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent0" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - } - }) - }) - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - phone: req.body.phone, - supAdmin: req.body.supAdmin, - password: req.body.password, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - email_verfi: true, - phone_verfi: true, - timezone: req.body.timezone - - }; - // otp(newUserJson); - // let a = otp(newUserJson); - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - } - - }) - } - - }) - } - }) - - - } - - - - else if (req.body.email) { - - var randomemail = Math.floor((Math.random() * 100000000000000) + 54); - Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) { - if (err) { - console.error(err); - } - else if (em) { - res.status(500).json({ "message": "Email ID already Exists" }) - } - else { - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - - timezone: req.body.timezone - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - email(req.body.first_name, req.body.email, randomemail); - }) - - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - id_email_ver: randomemail, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - - timezone: req.body.timezone - }; - - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - email(req.body.first_name, req.body.email, randomemail); - } - }) - } - }) - } - else { - res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" }); - } - - } - else { - res.status(400).send({ "message": "Server error" }) - } - - }) - } - else { - // if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") { - // return res.status(401).json({ "message": "Null Value Error" }); - // } - //superadmin can able to add dealer - - // else - if (req.body.sysadmin == true) { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) { - if (error) { - console.error(error); - } - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) { - if (err) { - console.error(err); - } - if (req.body.email && req.body.phone) { - - - var user_string = req.body.user_id; - var user_regex = new RegExp(["^", user_string, "$"].join(""), "i"); - - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { 'user_id': user_regex }] }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - if (user.email == req.body.email) { - res.status(200).json({ "message": "Email ID already exists" }) - } else if (req.body.user_id == user.user_id) { - res.status(200).json({ "message": "USER_ID already exists" }) - } else if (user.phone == req.body.phone) { - res.status(200).json({ "message": "Mobile Number already exists" }) - } else { - res.status(200).json({ "message": "User Duplicate" }) - } - } - else { - - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - role: req.body.roles, - group: req.body.group, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: true, - isSuperAdmin: false, - Dealer: req.body.Dealer, - supAdmin: req.body.supAdmin, - custumerid: 'c_' + cuscount.seq, - dealerid: 'd_' + dealcount.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - if (req.body.customer_role) { - newUserJson['customer_role'] = req.body.customer_role; - } - - var admin_identifier = req.body.supAdmin; - var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic'; - var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1'; - if (req.body.imageDoc) { - newUserJson.imageDoc = req.body.imageDoc; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - return; - } - // res.status(200).json({ "message": "Registered Sucessfully" }); - var SMSURL = Utilities.getConfig().smsUrl; - - var mobile_key = Utilities.getConfig().smsApiMobileKey; - var txt_key = Utilities.getConfig().smsApiTextKey; - - // ======================================sms according to superAdmin ================================================= - Contact.findOne({ _id: admin_identifier }, function (err, adminDetail) { - if (err) { - res.status(400).send({ "message": "not able to fetch supadmin" }); - - } - - var msgOption = adminDetail.welcome_msg; - // Saanvi Security Solution - if ((msgOption != undefined) && (msgOption == true)) { - var organisationName = ((adminDetail.organisation_name != undefined) || (adminDetail.organisation_name != '')) ? adminDetail.organisation_name : 'OneQlik GPS'; - - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password; - if (organisationName == 'Tractive VTS') { - SMSURL += '&sender=TRACTV'; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login'; - } else if (organisationName === 'IConnect Technologies') { - SMSURL = Utilities.getConfig().smsUrl_iconnect; - SMSURL += '&senderid=AMASEC'; - mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect; - txt_key = Utilities.getConfig().smsApiTextKey_iconnect; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in'; - } else if (organisationName === 'Saanvi Security Solution') { - SMSURL = Utilities.getConfig().smsUrl_saanvi; - mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi; - txt_key = Utilities.getConfig().smsApiTextKey_saanvi; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.saanvisecurity.in'; - } - else { - SMSURL += '&sender=OneQlk'; - } - - request({ - uri: SMSURL + mobile_key + req.body.phone + txt_key + userCred1, - method: "GET" - }, function (error, response, body) { - res.status(200).json({ "message": "Registered and Message Sent Successfuly" }) - }); - - } else { - res.status(200).json({ "message": "Registered" }) - } - - - }) - - // ======================================sms according to superAdmin ================================================= - - }) - } - }) - - } else if (req.body.user_id) { - var user_string = req.body.user_id; - var user_regex = new RegExp(["^", user_string, "$"].join(""), "i"); - - Contact.findOne({ 'user_id': user_regex }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - - res.status(200).json({ "message": "User Duplicate" }) - - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - role: req.body.roles, - group: req.body.group, - supAdmin: req.body.supAdmin, - email: 'no_email' + cuscount.seq + '@testmail.com', - phone: 'no_phone' + cuscount.seq, - email_verfi: true, - phone_verfi: true, - - isSuperAdmin: false, - - supAdmin: req.body.supAdmin, - custumerid: 'c_' + cuscount.seq, - dealerid: 'd_' + dealcount.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - }; - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - if (req.body.isDealer === true) { - newUserJson['isDealer'] = req.body.isDealer; - } else { - newUserJson['isDealer'] = false; - newUserJson['Dealer'] = req.body.Dealer; - } - - - if (req.body.imageDoc) { - newUserJson.imageDoc = req.body.imageDoc; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - return; - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - }) - - } - - }); - }); - } - else if (req.body.custumer == true) { - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) { - - if (error) { - console.error(error); - } - - var user_string = req.body.user_id; - var user_regex = new RegExp(["^", user_string, "$"].join(""), "i"); - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { 'user_id': user_regex }] }, function (err, user) { - - if (err) { - console.error(err) - } - else if ((user) && ((req.body.phone) || (req.body.email != null))) { - if (user.email == req.body.email) { - res.status(200).json({ "message": "Email ID already exists" }) - } else if (req.body.user_id == user.user_id) { - res.status(200).json({ "message": "USER_ID already exists" }) - } else if (user.phone == req.body.phone) { - res.status(200).json({ "message": "Mobile Number already exists" }) - } else { - res.status(200).json({ "message": "User Duplicate" }) - } - }else if((user)&&(req.body.phone == undefined)&&(req.body.email == null)){ - if(req.body.user_id == user.user_id){ - res.status(200).json({ "message": "USER_ID already exists" }) - }else{ - res.status(200).json({ "message": "Error in line 1084" }) - } - } - else { - if (req.body.email && req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - supAdmin: req.body.supAdmin, - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - if (req.body.imageDoc) { - newUserJson.imageDoc = req.body.imageDoc; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - var admin_identifier = req.body.supAdmin; - var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic'; - var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1'; - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - return; - } - // res.status(200).json({ "message": "Registered Sucessfully" }); - // console.log("INside Signup function"); - // console.log(req.body.phone); - // console.log(req.body.password); - var SMSURL = Utilities.getConfig().smsUrl; - - var mobile_key = Utilities.getConfig().smsApiMobileKey; - var txt_key = Utilities.getConfig().smsApiTextKey; - - // ======================================sms according to superAdmin ================================================= - Contact.findOne({ _id: admin_identifier }, function (err, adminDetail) { - if (err) { - res.status(400).send({ "message": "not able to fetch supadmin" }); - - } - - - var msgOption = adminDetail.welcome_msg; - - - if ((msgOption != undefined) && (msgOption == true)) { - var organisationName = ((adminDetail.organisation_name != undefined) || (adminDetail.organisation_name != '')) ? adminDetail.organisation_name : 'OneQlik GPS'; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password; - if (organisationName == 'Tractive VTS') { - SMSURL += '&sender=TRACTV'; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login'; - } else if (organisationName === 'IConnect Technologies') { - SMSURL = Utilities.getConfig().smsUrl_iconnect; - SMSURL += '&senderid=AMASEC'; - mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect; - txt_key = Utilities.getConfig().smsApiTextKey_iconnect; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in'; - } else if (organisationName === 'Saanvi Security Solution') { - SMSURL = Utilities.getConfig().smsUrl_saanvi; - mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi; - txt_key = Utilities.getConfig().smsApiTextKey_saanvi; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.saanvisecurity.in'; - } else { - SMSURL += '&sender=OneQlk'; - } - - - - request({ - uri: SMSURL + mobile_key + req.body.phone + txt_key + userCred1, - method: "GET" - }, function (error, response, body) { - res.status(200).json({ "message": "Registered and Message Sent Successfuly" }) - }); - - } else { - res.status(200).json({ "message": "Registered" }) - } - }) - - // ======================================sms according to superAdmin ================================================= - }) - } - else if (req.body.email) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: "nophone" + counter.seq, - email_verfi: true, - supAdmin: req.body.supAdmin, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - if (req.body.imageDoc) { - newUserJson.imageDoc = req.body.imageDoc; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - - }) - } - else if (req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - email_verfi: true, - supAdmin: req.body.supAdmin, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - email: 'noEmail' + counter.seq, - - custumerid: 'c_' + counter.seq, - - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // email:'noEmail'+ counter.seq - - }; - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - if (req.body.imageDoc) { - newUserJson.imageDoc = req.body.imageDoc; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - var admin_identifier = req.body.supAdmin; - var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic'; - var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1'; - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - - var SMSURL = Utilities.getConfig().smsUrl; - var mobile_key = Utilities.getConfig().smsApiMobileKey; - var txt_key = Utilities.getConfig().smsApiTextKey; - - // ======================================sms according to superAdmin ================================================= - Contact.findOne({ _id: admin_identifier }, function (err, adminDetail) { - if (err) { - res.status(400).send({ "message": "not able to fetch supadmin" }); - - } - - var msgOption = adminDetail.welcome_msg; - - if ((msgOption != undefined) && (msgOption == true)) { - var organisationName = ((adminDetail.organisation_name != undefined) || (adminDetail.organisation_name != '')) ? adminDetail.organisation_name : 'OneQlik GPS'; - - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password; - - if (organisationName == 'Tractive VTS') { - SMSURL += '&sender=TRACTV'; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login'; - } else if (organisationName === 'IConnect Technologies') { - SMSURL = Utilities.getConfig().smsUrl_iconnect; - SMSURL += '&senderid=AMASEC'; - mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect; - txt_key = Utilities.getConfig().smsApiTextKey_iconnect; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in'; - } else if (organisation_name === 'Saanvi Security Solution') { - SMSURL = Utilities.getConfig().smsUrl_saanvi; - mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi; - txt_key = Utilities.getConfig().smsApiTextKey_saanvi; - var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.saanvisecurity.in'; - } else { - SMSURL += '&sender=OneQlk'; - } - - - request({ - uri: SMSURL + mobile_key + req.body.phone + txt_key + userCred1, - method: "GET" - }, function (error, response, body) { - res.status(200).json({ "message": "Registered and Message Sent Successfuly" }) - }); - - } else { - res.status(200).json({ "message": "Registered" }) - } - }) - - // ======================================sms according to superAdmin ================================================= - - }) - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: 'no_phone' + counter.seq, - supAdmin: req.body.supAdmin, - email: 'no_email' + counter.seq + '@testmail.com', - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - }; - - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - - if (req.body.imageDoc) { - newUserJson.imageDoc = req.body.imageDoc; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - } - }) - - - }) - - } - else if (req.body.otp && req.body.phone) { - var token; - Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) { - if (err) { - console.error(err); - return err; - } - if (otpres) { - // - var dbtime = new Date(otpres.timestamp); - var curtime = new Date(); - var diffMs = (curtime - dbtime); // milliseconds between now & Christmas - var diffDays = Math.floor(diffMs / 86400000); // days - var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours - var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes - if (otpres.otp == req.body.otp) { - Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) { - if (err) { - console.error(err) - return res.status(400).send(err); - } - else { - return res.status(200).json({ "message": "Mobile Verified" }); - } - }); - } - else { - res.status(500).json({ "message": "Didn't match otp" }); - } - } - }) - } - else if (req.body.phone && req.body.email) { - var Distributer_string = req.body.user_id; - var user_regex = new RegExp(["^", Distributer_string, "$"].join(""), "i"); - - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { 'user_id': user_regex }] }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - - if (user.email == req.body.email) { - res.status(200).json({ "message": "Email ID already exists" }) - } else if (req.body.user_id == user.user_id) { - res.status(200).json({ "message": "USER_ID already exists" }) - } else if (user.phone == req.body.phone) { - res.status(200).json({ "message": "Mobile Number already exists" }) - } else { - res.status(200).json({ "message": "User Duplicate" }) - } - - - } - else { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var otprand = randomString(4, '#'); - var randomemail = randomString(16, '#aA!'); - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - var newUserJson = { - - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - supAdmin: req.body.supAdmin, - phone_verfi: true, - otp: otprand, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - timezone: req.body.timezone - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - if (req.body.organisation) { - newUserJson.organisation = req.body.organisation; - newUserJson.isSuperAdmin = req.body.isSuperAdmin; - newUserJson.isDealer = false; - newUserJson.phone_verfi = true; - newUserJson.organisation_name = req.body.organisation_name; - newUserJson.welcome_msg = req.body.welcome_msg; - - - newUserJson.user_id = req.body.user_id; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err) { - if (err) { - if (err.name === 'MongoError' && err.code === 11000) { - // Duplicate username - return res.status(200).send({ succes: false, message: 'User already exist!' }); - } - - // Some other error - return res.status(500).send(err); - } - else { - request({ - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + otprand, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - res.status(200).json({ "message": "OTP sent successfully3" }) - }); - } - }) - - }) - - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - - supAdmin: req.body.supAdmin, - Dealer: req.body.supAdmin, - phone_verfi: true, - email_verfi: true, - otp: otprand, - id_email_ver: randomemail, - isDealer: req.body.dealer ? req.body.dealer : req.body.isDealer, - custumerid: 'c_' + count.seq, - timezone: req.body.timezone, - custumer: true - }; - //console.log("Inside otp function3"); - //console.log("we are at 1158 while creating distributer"); - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - if (req.body.organisation) { - newUserJson.organisation = req.body.organisation; - newUserJson.user_id = req.body.user_id; - newUserJson.isSuperAdmin = req.body.isSuperAdmin; - newUserJson.organisation_name = req.body.organisation_name; - newUserJson.welcome_msg = req.body.welcome_msg; - newUserJson.isDealer = false; - newUserJson.phone_verfi = true; - } - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - if (req.body.purpose == "zettrack") { - var smsUri = Utilities.getConfig().ZettracksmsUrl + "&mobileNos=" + req.body.phone + "&message=" + "Welcome%20to%20ZTrack%20Sreerampore%20Use%20this%20One%20Time%20Password%20to%20validate%20your%20login" + otprand; - } else { - var smsUri = Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20to%20validate%20your%20login ' + otprand; - } - newUser.save(function (err, userObj) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - email(req.body.first_name, req.body.email, randomemail); - request({ - uri: smsUri, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - res.status(200).json({ "message": "OTP sent successfully", "user": userObj }) - }); - - }) - - } - - - - }) - - - - } - }) - - } - - - else if (req.body.phone) { - Contact.findOne({ "phone": req.body.phone }, function (err, ph) { - if (err) { - console.error(err); - } - else if (ph) { - res.status(500).json({ "message": "Mobile Number already Exists" }) - } - else { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - supAdmin: req.body.supAdmin, - password: req.body.password, - phone_verfi: true, - email_verfi: true, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - - timezone: req.body.timezone - - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - let datastore = newUserJson; - // let a = otp(newUserJson); - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - - } - - }) - - }) - - - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - supAdmin: req.body.supAdmin, - password: req.body.password, - phone_verfi: true, - email_verfi: true, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - - timezone: req.body.timezone - - }; - // otp(newUserJson); - // let a = otp(newUserJson); - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - otp(newUserJson, function (final_data) { - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - } - - }) - } - - }) - } - }) - - - } - - - - else if (req.body.email) { - - var randomemail = Math.floor((Math.random() * 100000000000000) + 54); - Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) { - if (err) { - console.error(err); - } - else if (em) { - res.status(500).json({ "message": "Email ID already Exists" }) - } - else { - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - supAdmin: req.body.supAdmin, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - - timezone: req.body.timezone - }; - - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - }) - email(req.body.first_name, req.body.email, randomemail); - }) - - } - else { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - supAdmin: req.body.supAdmin, - id_email_ver: randomemail, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - - timezone: req.body.timezone - }; - if (req.body.std_code) { - newUserJson['std_code'] = req.body.std_code; - } - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - - }) - email(req.body.first_name, req.body.email, randomemail); - } - }) - - - } - }) - - - } - else { - res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" }); - } - - } -} - - - -// ============================== -module.exports.signUpZogo = function (req, res) { - if (req.body.org_name) { - //console.log("Inside function"); - newOrgJson = { - organisation_name: req.body.org_name, - phone: req.body.org_phone, - email: req.body.org_email, - website: req.body.org_website, - }; - var newOrg = new org(JSON.parse(JSON.stringify(newOrgJson))); - newOrg.save(function (err, organisation) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - if (organisation) { - - if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") { - return res.status(401).json({ "message": "Null Value Error" }); - } - //superadmin can able to add dealer - - else if (req.body.sysadmin == true) { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) { - if (error) { - console.error(error); - } - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) { - if (err) { - console.error(err); - } - if (req.body.email && req.body.phone) { - console.log("1"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - role: req.body.roles, - group: req.body.group, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: true, - isSuperAdmin: false, - Dealer: req.body.Dealer, - supAdmin: req.body.supAdmin, - custumerid: 'c_' + cuscount.seq, - dealerid: 'd_' + dealcount.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - status: req.body.status, - address: req.body.address, - purpose: "zogo", - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - }); - }); - } - else if (req.body.custumer == true) { - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) { - - if (error) { - console.error(error); - } - if (req.body.email && req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - status: req.body.status, - purpose: "zogo", - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - return; - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - else if (req.body.email) { - //console.log("2"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - email: req.body.email.toLowerCase(), - phone: "nophone" + counter.seq, - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - status: req.body.status, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - purpose: "zogo", - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - else if (req.body.phone) { - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: false, - status: req.body.status, - - Dealer: req.body.Dealer, - email: 'noEmail' + counter.seq, - - custumerid: 'c_' + counter.seq, - - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // email:'noEmail'+ counter.seq - - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - else { - // console.log("3"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - phone: req.body.phone, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - status: req.body.status, - purpose: "zogo", - expire_date: new Date(req.body.expdate) - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - - - }) - - } - else if (req.body.otp && req.body.phone) { - - var token; - Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) { - if (err) { - console.error(err); - return err; - } - if (otpres) { - // - var dbtime = new Date(otpres.timestamp); - var curtime = new Date(); - var diffMs = (curtime - dbtime); // milliseconds between now & Christmas - var diffDays = Math.floor(diffMs / 86400000); // days - var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours - var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes - if (otpres.otp == req.body.otp) { - Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) { - if (err) { - console.error(err) - return res.status(400).send(err); - } - else { - return res.status(200).json({ "message": "Mobile Verified" }); - } - }); - } - else { - res.status(500).json({ "message": "Didn't match otp" }); - } - } - }) - } - else if (req.body.phone && req.body.email) { - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }] }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - res.status(200).json({ "message": "Email ID or Mobile Number already exists" }) - } - else { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var otprand = randomString(4, '#'); - var randomemail = randomString(16, '#aA!'); - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - //console.log("4"); - var newUserJson = { - - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: false, - phone_verfi: false, - otp: otprand, - status: req.body.status, - purpose: "zogo", - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - - timezone: req.body.timezone - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err) { - if (err) { - if (err.name === 'MongoError' && err.code === 11000) { - // Duplicate username - return res.status(200).send({ succes: false, message: 'User already exist!' }); - } - - // Some other error - return res.status(500).send(err); - } - else { - request({ - uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - res.status(200).json({ "message": "OTP sent successfully" }) - }); - } - }) - - }) - - } - else { - //console.log("5"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: false, - phone_verfi: false, - otp: otprand, - status: req.body.status, - purpose: "zogo", - id_email_ver: randomemail, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - - timezone: req.body.timezone - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - email(req.body.first_name, req.body.email, randomemail); - request({ - uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - res.status(200).json({ "message": "OTP sent successfully" }) - }); - }) - } - }) - } - }) - - } - else if (req.body.phone) { - Contact.findOne({ "phone": req.body.phone }, function (err, ph) { - if (err) { - console.error(err); - } - else if (ph) { - res.status(500).json({ "message": "Mobile Number already Exists" }) - } - else { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - // console.log("6"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - phone: req.body.phone, - status: req.body.status, - password: req.body.password, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - purpose: "zogo", - timezone: req.body.timezone - - }; - let datastore = newUserJson; - // let a = otp(newUserJson); - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - - } - - }) - - }) - - - } - else { - //console.log("7"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - phone: req.body.phone, - password: req.body.password, - isDealer: req.body.dealer, - status: req.body.status, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - purpose: "zogo", - timezone: req.body.timezone - - }; - // otp(newUserJson); - // let a = otp(newUserJson); - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - } - - }) - } - - }) - } - }) - - - } - - - - else if (req.body.email) { - - var randomemail = Math.floor((Math.random() * 100000000000000) + 54); - Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) { - if (err) { - console.error(err); - } - else if (em) { - res.status(500).json({ "message": "Email ID already Exists" }) - } - else { - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - //console.log("8"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: organisation._id, - email: req.body.email.toLowerCase(), - email_verfi: false, - phone_verfi: false, - status: req.body.status, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - purpose: "zogo", - timezone: req.body.timezone - }; - - - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - email(req.body.first_name, req.body.email, randomemail); - }) - - } - else { - //console.log("9"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - email: req.body.email.toLowerCase(), - email_verfi: false, - status: req.body.status, - phone_verfi: false, - id_email_ver: randomemail, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - purpose: "zogo", - timezone: req.body.timezone - }; - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - email(req.body.first_name, req.body.email, randomemail); - } - }) - - - } - }) - - - } - else { - res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" }); - } - - } - else { - res.status(400).send({ "message": "Server error" }) - } - - }) - } - else { - if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") { - return res.status(401).json({ "message": "Null Value Error" }); - } - //superadmin can able to add dealer - - else if (req.body.sysadmin == true) { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) { - if (error) { - console.error(error); - } - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) { - if (err) { - console.error(err); - } - if (req.body.email && req.body.phone) { - //console.log("10"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - role: req.body.roles, - group: req.body.group, - status: req.body.status, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: true, - isSuperAdmin: false, - Dealer: req.body.Dealer, - supAdmin: req.body.supAdmin, - custumerid: 'c_' + cuscount.seq, - dealerid: 'd_' + dealcount.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - purpose: "zogo", - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - }); - }); - } - else if (req.body.custumer == true) { - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) { - - if (error) { - console.error(error); - } - if (req.body.email && req.body.phone) { - //console.log("11"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - status: req.body.status, - address: req.body.address, - purpose: "zogo", - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err, u) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - return; - } - res.status(200).json({ "message": "Registered Sucessfully" }); - - - }) - } - else if (req.body.email) { - //console.log("12"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: "nophone" + counter.seq, - email_verfi: true, - phone_verfi: true, - status: req.body.status, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - purpose: "zogo", - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // phone:'noNumber'+ counter.seq - - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - else if (req.body.phone) { - //console.log("13"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - email_verfi: true, - phone_verfi: true, - status: req.body.status, - isDealer: false, - Dealer: req.body.Dealer, - email: 'noEmail' + counter.seq, - purpose: "zogo", - custumerid: 'c_' + counter.seq, - - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - expire_date: new Date(req.body.expdate) - // email:'noEmail'+ counter.seq - - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - else { - //console.log("14"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - email: req.body.email.toLowerCase(), - email_verfi: true, - phone_verfi: true, - isDealer: false, - Dealer: req.body.Dealer, - custumerid: 'c_' + counter.seq, - timezone: req.body.timezone, - user_id: req.body.user_id, - address: req.body.address, - purpose: "zogo", - status: req.body.status, - expire_date: new Date(req.body.expdate) - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - // var newUser = new Contact(newUserJson); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - } - - - }) - - } - else if (req.body.otp && req.body.phone) { - var token; - Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) { - if (err) { - console.error(err); - return err; - } - if (otpres) { - // - var dbtime = new Date(otpres.timestamp); - var curtime = new Date(); - var diffMs = (curtime - dbtime); // milliseconds between now & Christmas - var diffDays = Math.floor(diffMs / 86400000); // days - var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours - var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes - if (otpres.otp == req.body.otp) { - Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) { - if (err) { - console.error(err) - return res.status(400).send(err); - } - else { - // otpres.email - //console.log(otpres.email); - var mailOptions = { - from: Utilities.getConfig().mailUserZogo, // sender address - to: otpres.email, // gaurav.gupta@adnate.in list of receivers - subject: 'Zogorides', // Subject line - // text: "New Task", - html: `

` + "Hi " + otpres.first_name + `

Thanks for joining Zogorides.

Now that you have signed up, book and enjoy your ride.

Thanks!
Zogorides Team


© 2019 Zogorides. Join the conversation

Please do not reply directly to this email.

You can get help from our knowledge base.

If you don't want to receive emails like this again, please click hereto unsubscribe.


Plot No â?“ 23 Sector-18 Gurgaon,Haryana 122002
info@zogorides.com , support@zogorides.com
www.zogorides.com

` - } - mailer.sendZogoSignupMail(mailOptions); - return res.status(200).json({ "message": "Mobile Verified" }); - } - }); - } - else { - res.status(500).json({ "message": "Didn't match otp" }); - } - } - }) - } - else if (req.body.phone && req.body.email) { - //console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") - Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }] }, function (err, user) { - if (err) { - console.error(err) - } - else if (user) { - res.status(200).json({ "message": "Email ID or Mobile Number already exists" }) - } - else { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var otprand = randomString(4, '#'); - var randomemail = randomString(16, '#aA!'); - - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - // console.log("15"); - var newUserJson = { - - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: false, - phone_verfi: false, - otp: otprand, - status: req.body.status, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - purpose: "zogo", - timezone: req.body.timezone - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err, u) { - if (err) { - if (err.name === 'MongoError' && err.code === 11000) { - // Duplicate username - return res.status(200).send({ succes: false, message: 'User already exist!' }); - } - - // Some other error - return res.status(500).send(err); - } - if (u) { - //console.log("in uuuuu"); - var newCode = { - "code": "FirstFree", - "isPercent": false, - "amount": "50", - "expireDate": new Date(req.body.expdate), - "isActive": true, - "countMax": "1", - "onOrder": [ - "1" - ], - "maxDiscount": "50", - "minOrderAmount": "", - "type": "ONETIME" - } - newCode.user = u[0]._id - couponCode.addDiscountCodeOnSignup(newCode); - res.status(200).json({ "message": "OTP sent successfully" }); - // request({ - - - // uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand, - // method: "GET" - // }, function (error, response, body) { - // /* var jsonObj = JSON.parse(response.body); - // if(jsonObj.MsgStatus == 'Sent'){ - // email(req.body.first_name,req.body.email,randomemail); - // res.status(200).json({"message" : "OTP sent successfully"}) - - // } - // else{ - // res.status(500).json({"message" : "OTP sent Failed"}) - // Contact.remove({"phone" :req.body.phone}).then(function(err){ - // if(err){ - // res.send(err); - // return err; - // } - // }); - // } */ - // res.status(200).json({ "message": "OTP sent successfully" }); - - // }); - } - }) - - }) - - } - else { - // console.log("16"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - phone: req.body.phone, - email_verfi: false, - phone_verfi: false, - otp: otprand, - id_email_ver: randomemail, - isDealer: req.body.dealer, - status: req.body.status, - custumerid: 'c_' + count.seq, - timezone: req.body.timezone, - purpose: "zogo", - }; - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - newUser.save(function (err, u) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - - - //console.log("in uuuuu", u); - var newCode = { - "code": "FirstFree", - "isPercent": false, - "amount": "50", - "expireDate": new Date(req.body.expdate), - "isActive": true, - "countMax": "1", - "onOrder": [ - "1" - ], - "maxDiscount": "50", - "minOrderAmount": "", - "type": "ONETIME" - } - newCode.user = u._id - couponCode.addDiscountCodeOnSignup(newCode); - email(req.body.first_name, req.body.email, randomemail); - request({ - - - uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent Failed"}) - Contact.remove({"phone" :req.body.phone}).then(function(err){ - if(err){ - res.send(err); - return err; - } - }); - } */ - - // res.status(200).json({ "message": "OTP sent successfully" }); - res.status(200).json({ "message": "OTP sent successfully" }) - }); - - }) - - } - - - - }) - - - - } - }) - - } - - - else if (req.body.phone) { - Contact.findOne({ "phone": req.body.phone }, function (err, ph) { - if (err) { - console.error(err); - } - else if (ph) { - res.status(500).json({ "message": "Mobile Number already Exists" }) - } - else { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - //console.log("17"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - password: req.body.password, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - status: req.body.status, - purpose: "zogo", - timezone: req.body.timezone - - }; - let datastore = newUserJson; - // let a = otp(newUserJson); - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - - } - - }) - - }) - - - } - else { - console.log("18"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - phone: req.body.phone, - password: req.body.password, - isDealer: req.body.dealer, - custumerid: 'c_' + count.seq, - email: 'noEmail' + count.seq, - status: req.body.status, - purpose: "zogo", - timezone: req.body.timezone - - }; - // otp(newUserJson); - // let a = otp(newUserJson); - otp(newUserJson, function (final_data) { - - if (final_data == true) { - res.status(200).json({ "message": "OTP Successfully Sent" }); - } - else { - res.status(500).json({ "message": "OTP sent Failed" }) - Contact.remove({ "phone": req.body.phone }).then(function (err) { - if (err) { - // res.send(err); - // return err; - } - }); - } - - }) - } - - }) - } - }) - - - } - - - - else if (req.body.email) { - - var randomemail = Math.floor((Math.random() * 100000000000000) + 54); - Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) { - if (err) { - console.error(err); - } - else if (em) { - res.status(500).json({ "message": "Email ID already Exists" }) - } - else { - Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) { - if (req.body.dealer == true) { - Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) { - console.log("19"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - email_verfi: false, - phone_verfi: false, - id_email_ver: randomemail, - isDealer: req.body.dealer, - dealerid: 'd_' + counter.seq, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - status: req.body.status, - purpose: "zogo", - timezone: req.body.timezone - }; - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - email(req.body.first_name, req.body.email, randomemail); - }) - - } - else { - console.log("20"); - var newUserJson = { - first_name: req.body.first_name, - last_name: req.body.last_name, - org_name: req.body.org_name, - org: req.body.org_id, - email: req.body.email.toLowerCase(), - email_verfi: false, - phone_verfi: false, - id_email_ver: randomemail, - isDealer: req.body.dealer, - status: req.body.status, - custumerid: 'c_' + count.seq, - phone: 'noNumber' + count.seq, - purpose: "zogo", - timezone: req.body.timezone - }; - - var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson))); - newUser.setPassword(req.body.password); - newUser.setLastReportDate(); - - newUser.save(function (err) { - if (err) { - res.status(500).json({ "message": "Something Is Wrong" } + err); - } - res.status(200).json({ "message": "Registered Sucessfully" }); - }) - email(req.body.first_name, req.body.email, randomemail); - } - }) - - - } - }) - - - } - else { - res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" }); - } - - } -} -// ================================== -function email(fname, emailid, verid) { - - var url = "http://" + Utilities.getConfig().webAppIp + ":" + Utilities.getConfig().EPort + "/users/emailverfi?id=" + encodeURIComponent(verid); - - var mailOptions = { - from: Utilities.getConfig().mailUser, // sender address - to: emailid.toLowerCase(), // list of receivers - subject: Utilities.getConfig().orgName + "- Mail Verification", // Subject line - text: "New Task", // plaintext body emailverfi - html: 'Dear ' + fname + ',

Thank you for registering with us.
You are just one click away from using our services.Please verify your mail by clicking below button.


Thanks
Regards
Team AdnateIOT'// html body - } - mailer.sendMail(mailOptions); - - -} - -module.exports.zogoUserUpdate = function (req, res) { - if (req.body.phone) { - Contact.findOne({ "phone": req.body.phone }, function (err, user) { - if (err) { - console.error(err); - } - if (user) { - if (req.body.img_type == "adharCard") { - user.aadharImg = req.body.image_path; - } - if (req.body.img_type == "drivingLicence") { - user.dl_path = req.body.image_path; - } - if (req.body.img_type == "selfie") { - user.userImg = req.body.image_path; - } - user.save(function (err) { - if (err) { - console.error("otp error :" + err); - return err; - } - else { - res.status(200).send({ "message": "image saved successfully" }) - } - }) - } - else { - res.status(200).send({ "message": "user not found" }) - } - }) - - } - -} - - - -function otp(data, recur) { - - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var randomotp = randomString(4, '#'); - if (data.dealerid) { - var newOtpJson = { - first_name: data.first_name, - last_name: "", - org_name: data.org_name, - phone: data.phone, - otp: randomotp, - email_verfi: false, - phone_verfi: false, - isDealer: data.isDealer, - dealerid: data.dealerid, - custumerid: data.custumerid, - email: 'noEmail' + data.custumerid, - purpose: "zogo", - status: false, - timezone: req.body.timezone - - - }; - var newOtp = new Contact(JSON.parse(JSON.stringify(newOtpJson))); - newOtp.setPassword(data.password); - newOtp.setLastReportDate(); - - - newOtp.save(function (err) { - if (err) { - console.error("otp error :" + err); - return err; - } - - request({ - - - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + data.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - // email(req.body.first_name,req.body.email,randomemail); - // res.status(200).json({"message" : "OTP sent successfully"}) - - recur(true); - } - else{ - // res.status(500).json({"message" : "OTP sent Failed"}) - recur(false); - } */ - recur(true); - }); - - }); - } - else { - var newOtpJson = { - first_name: data.first_name, - last_name: "", - org_name: data.org_name, - phone: data.phone, - otp: randomotp, - email_verfi: false, - phone_verfi: false, - isDealer: data.isDealer, - custumerid: data.custumerid, - email: 'noEmail' + data.custumerid, - purpose: "zogo", - status: false - // timezone: req.body.timezone - - }; - var newOtp = new Contact(JSON.parse(JSON.stringify(newOtpJson))); - - newOtp.setPassword(data.password); - newOtp.setLastReportDate(); - - // var newUser = new Contact(newUserJson); - - - newOtp.save(function (err) { - if (err) { - console.error("otp error :" + err); - return err; - } - - request({ - - - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + data.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - // email(data.first_name,data.email,randomemail); - // res.status(200).json({"message" : "OTP sent successfully"}) - recur(true); - } - else{ - // res.status(500).json({"message" : "OTP sent Failed"}) - recur(false); - } */ - recur(true); - }); - - }); - } - -} - -module.exports.find = function (req, res) { - req.body = evaluate(req.body); - var qr = Contact.find(req.body._find); - if (req.body._limit) - qr.limit(req.body._limit); - if (req.body._sort) - qr.sort(req.body._sort); - if (req.body._select) - qr.select(req.body._select); - if (req.body.school) - qr.populate({ 'path': 'school', select: req.body.school }) - - qr.exec(function (err, data) { - if (err) return res.send(err); - else - res.send(data); - }) -} - -module.exports.emailverfi = function (req, res) { - - Contact.findOne({ "id_email_ver": (req.query.id) }).exec(function (err, sd) { - - if (err) { - return res.status(401).send("Error ::" + err) - console.error(err); - } - else if (sd) { - - Contact.update({ _id: sd._id }, { $set: { email_verfi: true } }, function (err, result) { - if (err) { - console.error(err) - return res.status(400).send(err); - } - else { - - return res.redirect(Utilities.getConfig().webAppDomain + '/login'); - - } - }); - - - } - else { - return res.status(401).send("Error ::" + err) - console.error(err); - } - }) -} - -// module.exports.getAllUsersForSuperUser = function(req, res) { -// Contact.findOne({_id : req.body.user, isSuperUser : true}, function(err, superUser){ -// if(err){ -// console.error(err); -// res.send(500); -// return; -// } -// else if(superUser){ -// Contact.find({isDealer : true},function(err, contacts){ -// if(err){ -// console.error(err); -// res.send(500); -// return; -// } -// res.status(200).send(contacts); - -// }); -// } -// }) - -// } - -//retreve data (signup/login) -module.exports.getAllUsers = function (req, res) { - var id = ""; - if (req.query.dealer) { - id = req.query.dealer - } else if (req.query.user) { - id = req.query.user - } - - Contact.findOne({ _id: id }, function (err, dealer) { - if (err) { - console.error(err); - res.send(500); - return; - } - if (dealer) { - var query = {}; - if (req.query.dealer) { - query = { $or: [{ 'Dealer': req.query.dealer }, { group: { $in: dealer.group } }] } - } - if (req.query.user) { - query = { $or: [{ $and: [{ 'Dealer': dealer.Dealer }, { '_id': { $nin: [req.query.user] } }] }, { '_id': dealer.Dealer }] } - } - Contact.find(query, function (err, contacts) { - if (err) { - console.error(err); - return err; - } - if (contacts.length > 0) { - res.status(200).send(contacts); - } - else { - res.status(500).send("No records found"); - } - }); - } - - else { - res.send(400); - } - }) - -} -module.exports.datatable = function (req, res) { - - var qr = req.body; - var dtop = { - conditions: qr.find, - select: qr.select - }; - Contact.dataTable(qr, dtop, function (err, data) { - if (err) { - console.error(err); - res.sendStatus(500); - return; - } - res.send(data); - }) -} - -module.exports.getAll = function (req, res) { - Contact.find({ supAdmin: req.query.supadm }, function (err, contacts) { - if (err) { - console.error(err); - return err; - } - if (contacts.length > 0) { - res.status(200).send(contacts); - } - else { - res.status(500).send("No records found"); - } - }); - -} - -//delete Data (NOT USED) -module.exports.DeleteUser = function (req, res) { - Contact.remove({ _id: req.query.id }, function (err, del) { - if (err) { - console.error(err); - return err; - } - res.status(200).json({ "message": "Deleted Successfully" }) - - }) -} - -//saving phonenum with otp -module.exports.SendOtp = function (req, res) { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var randomotp = randomString(6, '#'); - /* var randomotp=Math.floor((Math.random() * 100000) + 54); */ - var newOtpJson = { - phone_number: req.body.ph_num, - otp: randomotp - }; - - var newOtp = new Otp(JSON.parse(JSON.stringify(newOtpJson))); - newOtp.save(function (err) { - if (err) { - console.error("otp error :" + err); - return err; - } - // - request({ - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.ph_num + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } */ - res.status(200).json({ "message": "OTP sent successfully" }) - }); - - }); -} - - -module.exports.SendOtpZOGO = function (req, res) { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var randomotp = randomString(4, '#'); - /* var randomotp=Math.floor((Math.random() * 100000) + 54); */ - var newOtpJson = { - phone_number: req.body.ph_num, - otp: randomotp - }; - - var newOtp = new Otp(JSON.parse(JSON.stringify(newOtpJson))); - newOtp.save(function (err) { - if (err) { - console.error("otp error :" + err); - return err; - } - //req.body.ph_num - Contact.findOne({ phone: req.body.ph_num }, function (err, mobileNum) { - if (err) { - res.status(500).json({ "Error": "Device Not Found" }) - } - //console.log("Mobile Number", mobileNum); - //console.log("randonOTP", randomotp); - mobileNum.otp = randomotp; - - mobileNum.save(function (err) { - if (err) { - res.status(500).json({ "errMsg": "OTP not Updated" }) - } else { - // console.log("updatedInfo=>", mobileNum); - request({ - uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.ph_num + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + randomotp, - method: "GET" - }, function (error, response, body) { - res.status(200).json({ "message": "OTP sent successfully" }) - }); - } - }) - }) - }); -} - - -//checking otp with phonenumber - -//saving phonenum with otp -//LOGIN -module.exports.LoginWithOtp = function (req, res) { - var loginType = ''; - // console.log("header",JSON.stringify(req.headers)); - var user_agent = req.headers["user-agent"]; - //console.log("UUUUUUUUUUUUUUUUUUUUUUUU",user_agent); - if (user_agent.includes("Android ") || user_agent.includes("iPhone") || user_agent.includes("blackberry")) { - loginType = "MOBILE" - } - else if (user_agent.includes("Mozilla") || user_agent.includes("AppleWebKit") || user_agent.includes("Chrome") || user_agent.includes("Safari")) { - loginType = "WEB"; - } else { - loginType = "MOBILE" - } - var token; - if (req.body.emailid) { - - Contact.findOne({ "email": req.body.emailid.toLowerCase() }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) { - if (err) { - console.error(err); - return err; - } - if (user) { - //checking user expiration date - if (user.DeletedUser == true) { - res.status(500).json({ "message": "Account Deleted" }); - return; - } - if (user.expire_date) { - if (new Date() > user.expire_date) { - res.status(500).json({ "message": "User account is expired" }); - } - } - //console.log(user); - // - //user is active or not - if ((!user.status) && (user.purpose != 'zogo')) { - res.status(500).json({ "message": "User account is InActive" }); - } - //valid or not - if (user.email_verfi == true) { - // - if (user.validPassword(req.body.psd)) { - Contact.update({ _id: user._id }, { $set: { last_login: new Date, login_type: loginType, "user_agent": user_agent } }, function (err, re) { - if (err) { - console.log(err); - return; - } - token = user.generateJwt(); - res.status(200); - res.json({ - "token": token - }); - }) - - } else { - res.status(500).json({ "message": "Password is Wrong" }); - } - - //res.status(200).json({"message":"LoggedIn Successfully"}); - } - else { - res.status(500).json({ "message": "Email ID Not Verified" }); - } - } - else { - - res.status(500).json({ "message": "User is not registered" }); - - } - }); - - } - else if (req.body.ph_num && req.body.psd) { - - Contact.findOne({ $or: [{ "phone": req.body.ph_num }, { "user_id": req.body.ph_num }] }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) { - if (err) { - console.error(err); - return err; - } - if (user) { - - if (user.DeletedUser == true) { - res.status(500).json({ "message": "Account Deleted" }); - return; - } - //checking user expiration date - if (user.expire_date) { - if (new Date() > user.expire_date) { - res.status(500).json({ "message": "User account is expired" }); - } - } - // - //user is active or not - if (!user.phone_verfi) { - res.status(500).json({ "message": "Mobile Phone Not Verified" }); - - } - if ((!user.status) && (user.purpose != 'zogo')) { - res.status(500).json({ "message": "User account is InActive" }); - } - //valid or not - if (user.phone_verfi == true) { - // - if (user.validPassword(req.body.psd)) { - Contact.update({ _id: user._id }, { $set: { last_login: new Date, login_type: loginType, "user_agent": user_agent } }, function (err, re) { - if (err) { - console.log(err); - return; - } - token = user.generateJwt(); - res.status(200); - res.json({ - "token": token - }); - }) - } else { - res.status(500).json({ "message": "Password is Wrong" }); - } - - //res.status(200).json({"message":"LoggedIn Successfully"}); - } - else { - res.status(500).json({ "message": "Mobile Phone Not Verified" }); - } - } - else { - res.status(500).json({ "message": "User is not registered" }); - } - }); - - } - - else if (req.body.ph_num && req.body.otp) { - - Contact.findOne({ "phone": req.body.ph_num }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) { - if (err) { - console.error(err); - return err; - } - if (user) { - if (user.phone_verfi = true) { - Otp.findOne({ "phone_number": req.body.ph_num }).sort({ "timestamp": -1 }).exec(function (err, otpres) { - if (err) { - console.error(err); - return err; - } - if (otpres) { - // - var dbtime = new Date(otpres.timestamp); - var curtime = new Date(); - var diffMs = (curtime - dbtime); // milliseconds between now & Christmas - var diffDays = Math.floor(diffMs / 86400000); // days - var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours - var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes - if (diffDays == 0 && diffHrs < 1 && diffMins <= 10) { - if (otpres.otp == req.body.otp) { - token = user.generateJwt(); - res.status(200); - res.json({ - "token": token - }); - //res.status(200).json({"message": "Successfully Logged In"}); - } - else { - res.status(500).json({ "message": "Didn't match otp" }); - } - - } - else { - res.status(500).json({ "message": "Otp has been Expired" }); - } - // - - - } - }) - } - else { - res.status(500).json({ "message": "Mobile Number Not Verified" }); - } - } - else { - res.status(500).json({ "message": "This number is not registered.Please SignUp" }) - } - }) - - - } - //checking userid with password - else if (req.body.user_id && req.body.psd) { - - var userIDstring = req.body.user_id; - var user_id_regex = new RegExp(["^", userIDstring, "$"].join(""), "i"); - - Contact.findOne({ $or: [{ "user_id": user_id_regex }, { "phone": req.body.user_id }] }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) { - if (err) { - console.error(err); - return err; - } - if (user) { - //checking user expiration date - if (user.DeletedUser == true) { - res.status(500).json({ "message": "Account Deleted" }); - return; - } - - if (user.expire_date) { - if (new Date() > user.expire_date) { - res.status(500).json({ "message": "User account is expired" }); - } - } - // - //user is active or not - if ((!user.status) && (user.purpose != 'zogo')) { - res.status(500).json({ "message": "User account is InActive" }); - } - if (user.validPassword(req.body.psd)) { - Contact.update({ _id: user._id }, { $set: { last_login: new Date, login_type: loginType, "user_agent": user_agent } }, function (err, re) { - if (err) { - console.log(err); - return; - } - token = user.generateJwt(); - res.status(200); - res.json({ - "token": token - }); - }) - } else { - res.status(500).json({ "message": "Password is Wrong" }); - } - } - else { - - res.status(500).json({ "message": "User is not registered" }); - - } - }); - } -} - -module.exports.SendOtpp = function (phonenumber) { - return new Promise(function (resolve, reject) { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var randomotp = randomString(6, '#'); - //var randomotp=Math.floor((Math.random() * 100000) + 54); - var newOtpJson = { - phone_number: phonenumber, - otp: randomotp - }; - - var newOtp = new Otp(JSON.parse(JSON.stringify(newOtpJson))); - newOtp.save(function (err) { - if (err) { - console.error("otp error :" + err); - return err; - } - request({ - - - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + phonenumber + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } */ - res.status(200).json({ "message": "OTP sent successfully" }) - }); - }); - }); -} -// - -//reset password -module.exports.resetPassword = function (req, res) { - if (req.body.dev == "Mobile") { - Contact.findOne({ "phone": req.body.phone }, function (err, result) { - if (err) { - console.error(err); - return err; - } - if (result) { - Otp.findOne({ "phone_number": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) { - if (err) { - console.error(err); - return err; - } - if (otpres) { - if (otpres.otp == req.body.otp) { - if (req.body.password) result.setPassword(req.body.password); - result.save(function (err) { - if (err) { - console.error("inside error :" + err); - return; - } - res.status(200).send(result._id); - }) - } - } - }) - // - } - else { - res.status(500).json({ "message": "This Number is not registered" }); - } - }) - - } - -} - -//mlogin send otp - -module.exports.LoginSendOtp = function (req, res) { - try { - Contact.findOne({ "phone": req.body.phone }, function (err, result) { - if (err) { - console.error(err); - return; - } - if (result) { - module.exports.SendOtpp(result.phone).then(function (success) { - res.send(success); - }, function (err) { - res.send(err); - }); - } - else { - res.status(500).json({ "message": "This Number is not registered" }); - } - }) - } - catch (e) { - console.error(e); - } -} -//userFeedback -//User Feedback -module.exports.userFeedback = function (req, res) { - - Contact.findOne({ "_id": req.body.uid }, function (err, validUser) { - - if (err) { - console.error(err); - return; - } - else if (validUser) { - Contact.update({ _id: validUser._id }, { $addToSet: { "feedback": req.body.feedback }, $set: { "rating": req.body.rating } }, function (err, result) { - if (err) { - console.error(err); - return; - } - else if (result) { - - - - var mailOptions = { - from: Utilities.getConfig().mailUser, // sender address - to: Utilities.getConfig().adminMailId, // gaurav.gupta@adnate.in list of receivers - subject: Utilities.getConfig().orgName + " - Feedback", // Subject line - text: "New Task", // plaintext body emailverfi - html: 'Dear Sir,
We have recevied a new feedback from ' + Utilities.getConfig().orgName + ' GPS Tracker Mobile App

From: ' + validUser.first_name + ' ' + validUser.last_name + '
Contact Details: ' + validUser.email + ' / ' + validUser.phone + '
Rating: ' + req.body.rating + ' Stars
Feedback: ' + req.body.feedback + '

Thanks
Regards
Team Adnate'// html body - } - mailer.sendMail(mailOptions); - - - res.status(200).json({ "message": "Thanks for your feedback" }); - } - else { - res.status(500).json({ "message": "Invalid User" }); - } - }); - - } - }) - -} - -// Push Notificaion - -module.exports.PushNotification = function (req, res) { - - Contact.update({ _id: req.body.uid }, { - $addToSet: { - "pushNotification": { - token: req.body.token, "imei": req.body.imei, "os": req.body.os - } - } - }, function (err, result) { - if (err) { - console.error(err) - res.sendStatus(500); - return; - } - res.status(200).json({ "message": "Notifcation Updated" }); - }) - -} - - -// Pull Notificaion on logout - -module.exports.PullNotification = function (req, res) { - - Contact.update({ _id: req.body.uid }, { - $pull: { - "pushNotification": { - token: req.body.token, "imei": req.body.imei, "os": req.body.os - } - } - }, function (err, result) { - if (err) { - console.error(err) - res.sendStatus(500); - return; - } - res.status(200).json({ "message": "Notifcation Updated" }); - }) - -} -// Forgot Password - -module.exports.forgotpwd = function (req, res) { - - if (req.query.cred == undefined || req.query.cred == null || req.query.cred == "undefined") { - res.status(500).json({ "message": "Blank Entry" }) - - } - else { - - Contact.findOne({ $or: [{ 'email': req.query.cred }, { 'phone': req.query.cred }] }, function (err, user) { - - if (err) { - console.error(err); - } - else if (user) { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var randomotp = randomString(6, '#'); - // var randomotp=Math.floor((Math.random() * 100000) + 54); - - if (req.query.phone && req.query.otp) { - - Contact.findOne({ $or: [{ 'email': req.query.phone }, { 'phone': req.query.phone }] }, function (err, verify) { - if (err) { - console.error(err); - res.status(500).json(err); - } - else if (verify) { - if (verify.otp == req.query.otp) { - - this.salt = crypto.randomBytes(16).toString('hex'); - this.hash = crypto.pbkdf2Sync(req.query.newpwd, this.salt, 1000, 64, 'sha1').toString('hex'); - var changedPass = req.query.newpwd; - - Contact.update({ _id: verify._id }, { $set: { "hash": this.hash, "salt": this.salt, "pass": changedPass } }, function (err, succ) { - if (err) { - console.error(err); - } - res.status(200).json({ "message": "Password Sucessfully Changes" }) - }) - } - else { - res.status(500).json({ "message": "Wrong OTP try again" }) - } - } - }) - } - else if (user.phone) { - Contact.update({ _id: user._id }, { $set: { "otp": randomotp } }, function (err, result) { - - if (err) { - console.error(err); - res.status(500).json(err); - return; - } - // res.status(200).json({"message" : "OTP sent successfully"}) - - request({ - - - uri: Utilities.getConfig().smsUrl + "&sender=OneQlk" + Utilities.getConfig().smsApiMobileKey + user.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20to%20reset%20your%20password ' + randomotp, - method: "GET" - }, function (error, response, body) { - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - // email(req.body.first_name,req.body.email,randomemail); - res.status(200).json({"message" : "OTP sent successfully"}) - - } - else{ - res.status(500).json({"message" : "OTP sent failed"}) - } */ - res.status(200).json({ "message": "OTP sent successfully" }) - }); - - }) - - } - else if (user.email) { - Contact.update({ _id: user._id }, { $set: { "otp": randomotp } }, function (err, result) { - - if (err) { - res.status(500).json(err); - console.error(err); - } - var url = "http://" + Utilities.getConfig().webAppIp + ":" + Utilities.getConfig().EPort + "/users/foremailver?key=" + randomotp + '&uid=' + user._id; - - var mailOptions = { - from: "", // sender address - to: user.email, // gaurav.gupta@adnate.in list of receivers - subject: Utilities.getConfig().orgName + " - Reset Passwod", // Subject line - text: "New Task", // plaintext body emailverfi - html: 'Dear Sir,
You can reset your password by clicking on following link



Thanks
Regards
Team Adnate'// html body - } - mailer.sendMail(mailOptions); - - - res.status(200).json({ "message": "email sent" }); - }) - - - - } - } - else { - res.status(500).json({ "message": "Email ID / Mobile Number not found" }) - } - }) - } - -} - - -module.exports.foremailver = function (req, res) { - - Contact.findOne({ "_id": req.query.uid }, function (err, res) { - if (err) { - console.error(err) - } - else if (res) { - if (req.query.key == res.otp) { - return res.redirect(Utilities.getConfig().webAppDomain + '/forgotpwd'); - - - } - } - else { - } - }) - -} -module.exports.foremailpwdchg = function (req, res) { - - Contact.findOne({ $or: [{ 'email': req.query.cred.toLowerCase() }, { 'phone': req.query.cred }] }, function (err, verify) { - - this.salt = crypto.randomBytes(16).toString('hex'); - this.hash = crypto.pbkdf2Sync(req.query.newpwd, this.salt, 1000, 64).toString('hex'); - Contact.update({ _id: verify._id }, { $set: { "hash": this.hash, "salt": this.salt } }, function (err, succ) { - if (err) { - console.error(err); - } - res.status(200).json({ "message": "Password Sucessfully Changes" }) - }) - }) - -} - -//Contact OUS -module.exports.contactous = function (req, res) { - if (req.body.phone == null || req.body.phone == undefined || req.body.phone == "undefined") { - req.body.phone == " " - } - var mailOptions = { - from: Utilities.getConfig().mailUser, // sender address - to: req.body.dealerid, // gaurav.gupta@adnate.in list of receivers - subject: Utilities.getConfig().orgName + " - Contact Ous", // Subject line - text: "New Task", // plaintext body emailverfi phone - html: 'Dear Sir,
Someone Wanted to contact ous details are :-

Email ID-' + req.body.email.toLowerCase() + '
Phone Number-' + req.body.phone + '
Title-' + req.body.title + '
Message-' + req.body.msg + '

Thanks
Regards
Team Adnate'// html body - } - mailer.sendMail(mailOptions); - - - res.status(200).json({ "message": "email sent" }); -} - -//Resend OTP -module.exports.otpResend = function (req, res) { - - Contact.findOne({ 'phone': req.query.phone }, function (err, verify) { - if (err) { - console.error(err); - res.status(500); - return; - } - else if (verify) { - function randomString(length, chars) { - var mask = ''; - if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; - if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - if (chars.indexOf('#') > -1) mask += '0123456789'; - if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\'; - var result = ''; - for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)]; - return result; - } - var randomotp = randomString(6, '#'); - Contact.update({ _id: verify._id }, { $set: { otp: randomotp } }, function (err, result) { - if (err) { - console.error(err) - return res.status(400).send(err); - } - else { - request({ - - - uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + verify.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20for%20SignUp%20 ' + randomotp, - method: "GET" - }, function (error, response, body) { - - /* var jsonObj = JSON.parse(response.body); - if(jsonObj.MsgStatus == 'Sent'){ - res.status(200).json({"message" : "OTP sent successfully"}) - } - else{ - res.status(500).json({"message" : "OTP sent failed"}) - - } */ - res.status(200).json({ "message": "OTP sent successfully" }) - }); - - } - }); - - } - else { - res.status(500).json({ "message": "User not Registered" }) - } - }) -} - -//Account Edit -module.exports.Account_Edit = function (req, res) { - var token; - Contact.findOne({ '_id': req.body.uid }, function (err, verify) { - if (err) { - console.error(err); - } - else if (verify) { - console.log("BODY",req.body) - var accountUpdate={} - if(req.body.reportSchedule){ - if(req.body.report_config){ - accountUpdate['report_config'] = req.body.report_config; - } - if(req.body.report_emailid){ - accountUpdate['report_emailid'] = req.body.report_emailid; - } - if(req.body.scheduled_excel_report){ - accountUpdate['scheduled_excel_report'] = req.body.scheduled_excel_report; - } - } - else{ - // accountUpdate = { - accountUpdate['first_name'] = req.body.fname; - accountUpdate['last_name'] = req.body.lname; - accountUpdate['org_name'] = req.body.org; - accountUpdate['GET_notif'] = req.body.noti; - accountUpdate['fuel_unit'] = req.body.fuel_unit; - accountUpdate['show_announcement'] = req.body.show_announcement?req.body.show_announcement:false; - accountUpdate['digital_input'] = req.body.digital_input?req.body.digital_input:1 - accountUpdate['label_setting']=req.body.label_setting?req.body.label_setting:false; - - if(req.body.immobilize_setting!=undefined){ - accountUpdate['immobilize_setting']=req.body.immobilize_setting?req.body.immobilize_setting:false; - } - if(req.body.tow_setting!=undefined){ - accountUpdate['tow_setting']=req.body.tow_setting?req.body.immobilize_setting:false; - } - if(req.body.parking_setting!=undefined){ - accountUpdate['parking_setting']=req.body.parking_setting?req.body.immobilize_setting:false; - } - // show_announcement:req.body.show_announcement?req.body.show_announcement:false, - // digital_input:req.body.digital_input?req.body.digital_input:1, - // first_name: req.body.fname, - // last_name: req.body.lname, - // org_name: req.body.org, - // GET_notif: req.body.noti, - // fuel_unit: req.body.fuel_unit, - } - - - - - if (req.body.timezone) { - accountUpdate['timezone'] = req.body.timezone; - } - Contact.update({ _id: verify._id }, { $set: accountUpdate }, function (err, result) { - if (err) { - console.error(err) - res.status(500); - return; - } - else { - Contact.findOne({ '_id': req.body.uid }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, verifyy) { - if (err) { - console.error(err); - } - else if (verify) { - - if (result.nModified == 1) { - token = verifyy.generateJwt(); - res.status(200); - res.json({ - "token": token - }); - } - else { - token = verify.generateJwt(); - res.status(200); - res.json({ - "token": token - }); - } - } - }) - - } - }) - - - } - else { - res.status(500).json({ "message": "User not Registered" }); - } - }) -} - -module.exports.set_user_setting = function (req, res) { - if (!req.body.uid) { - res.status(200).send({ "message": "uid is mandatory" }); - return; - } - - Contact.findOne({ '_id': req.body.uid }, function (err, user) { - if (err) { - console.error(err); - } - else if (user) { - if (req.body.lang) user.language_code = req.body.lang; - if (req.body.currency_code) user.currency_code = req.body.currency_code; - if (req.body.fuelUnit) user.fuel_unit = req.body.fuelUnit; - if (req.body.notifSound) user.notification_sound = req.body.notifSound; - if (req.body.engine_cut_psd) user.engine_cut_psd = req.body.engine_cut_psd; - if (req.body.tripGeneration) user.tripGeneration = req.body.tripGeneration; - if (req.body.unit_measurement) user.unit_measurement = req.body.unit_measurement; - if (req.body.adminAlert == true || req.body.adminAlert == false) user.adminAlert = req.body.adminAlert; - if (req.body.tripGeneration) user.tripGeneration = req.body.tripGeneration; - if (req.body.voice_alert == true || req.body.voice_alert == false) user.voice_alert = req.body.voice_alert; - if (req.body.announcement) user.announcement = req.body.announcement; - user.save(function (err, result) { - if (err) { - console.error(err) - res.status(500); - return; - } - else if (result) { - if (req.body.lang) res.status(200).send({ "message": "language updated sucessfully" }) - else res.status(200).send({ "message": "announcement updated sucessfully" }) - } - }) - - - } - else { - res.status(500).json({ "message": "User not Registered" }); - } - }) - - - } -/* -module.exports.get_user_setting = function (req, res) { - - if (!req.body.uid) { - res.status(200).send({ "message": "uid is mandatory" }); - return; - } - - Contact.findOne({ '_id': ObjectId(req.body.uid) }) - - .select('language_code fuel_unit notification_sound engine_cut_psd voice_alert currency_code unit_measurement timezone adminAlert') - .lean() - .exec(function (err, user) { - if (err) { - console.error(err); - } - else if (user) { - res.status(200).send(user); - - } - else { - res.status(500).json({ "message": "User not Registered" }); - } - }) -} -*/ - -module.exports.get_user_setting = function (req, res) { - - if (!req.body.uid) { - res.status(200).send({ "message": "uid is mandatory" }); - return; - } - - Contact.findOne({ '_id': ObjectId(req.body.uid) }) - .select('language_code fuel_unit notification_sound engine_cut_psd voice_alert currency_code unit_measurement timezone adminAlert announcement show_announcement isSuperAdmin isDealer supAdmin') - .lean() - .exec(function (err, user) { - if (err) { - console.error(err); - } - else if (user) { - if(user.isSuperAdmin){ - res.status(200).send(user); - - }else{ - Contact.find({_id: ObjectId(user.supAdmin) }).exec(function (err, result) { - console.log("Result--->",result) - console.log("User---",user); - if(result[0].announcement){ - console.log("In If Condition"); - var data={ - "language_code":user.language_code, - "fuel_unit":user.fuel_unit, - "notification_sound":user.notification_sound, - "engine_cut_psd":user.engine_cut_psd, - "voice_alert":user.voice_alert, - "currency_code":user.currency_code, - "unit_measurement":user.unit_measurement, - "timezone":user.timezone, - "adminAlert":user.adminAlert, - "announcement":result[0].announcement, - "show_announcement":user.show_announcement?user.show_announcement:false, - "isSuperAdmin":user.isSuperAdmin, - "isDealer":user.isDealer, - "digital_input":user.digital_input?user.digital_input:1 - } - console.log("Data-=---",data); - res.status(200).send(data); - }else{ - console.log("In else Condition"); - - var data={ - "language_code":user.language_code, - "fuel_unit":user.fuel_unit, - "notification_sound":user.notification_sound, - "engine_cut_psd":user.engine_cut_psd, - "voice_alert":user.voice_alert, - "currency_code":user.currency_code, - "unit_measurement":user.unit_measurement, - "timezone":user.timezone, - "adminAlert":user.adminAlert, - "isSuperAdmin":user.isSuperAdmin, - "show_announcement":user.show_announcement?user.show_announcement:false, - "isDealer":user.isDealer, - "digital_input":user.digital_input?user.digital_input:1 - } - console.log("Data-=---",data); - res.status(200).send(data); - - } - }) - } - } - else { - res.status(500).json({ "message": "User not Registered" }); - } - }) -} - - -module.exports.verify_EngineCut_Password = function (req, res) { - - if (!req.body.uid) { - res.status(200).send({ "message": "uid is mandatory" }); - return; - } - - Contact.findOne({ '_id': ObjectId(req.body.uid) }) - - .exec(function (err, user) { - if (err) { - console.error(err); - } - else if (user) { - if (user.engine_cut_psd == null || user.engine_cut_psd == undefined || user.engine_cut_psd == "") { - res.status(200).send({ message: "password not set for user" }); - } else if (user.engine_cut_psd) { - if (req.body.psd == user.engine_cut_psd) { - res.status(200).send({ message: "password verified" }); - } - else { - res.status(200).send({ message: "password not matched" }); - } - } - // res.status(200).send(user); - - } - else { - res.status(500).json({ "message": "User not Registered" }); - } - }) -} - - -module.exports.cancel_signup = function (req, res) { - Contact.remove({ "phone": req.query.phone }).then(function (err) { - if (err) { - res.send(err); - return err; - } - res.status(200).json({ "message": "Sign_Canceled" }) - }); -} - -module.exports.demo = function (req, res) { - - var mailOptions = { - from: Utilities.getConfig().mailUser, // sender address - to: req.query.dealeID, // dealeID gaurav.gupta@adnate.in list of receivers - subject: "Oneqlik - Demo Request", // Subject line - text: "New Task", // plaintext body emailverfi - html: 'Dear Sir,
Someone Wanted a demo details are :-

First Name-' + req.query.fname + '
Last Name-' + req.query.lname + '
Email-' + req.query.email + '
Mobile Number-' + req.query.mobile + '

Thanks
Regards
Team Adnate'// html body - } - mailer.sendMail(mailOptions); - - - res.status(200).json({ "message": "email sent" }); -} - -//Get Custumer -module.exports.getCust = function (req, res) { - var query = {}; - query = { 'Dealer': req.query.uid, isDealer: false }; - var pageNo = parseInt(req.query.pageNo); - var size = parseInt(req.query.size); - if (pageNo < 0 || pageNo === 0) { - response = { "error": true, "message": "invalid page number, should start with 1" }; - return res.json(response) - } - // query = { isDealer: false }; - - query['$and'] = []; - if (req.query.search) { - query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] }) - } - - var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] }; - query['$and'].push(queryNew); - - Contact.find(query) - .populate({ path: 'Dealer', select: 'first_name last_name' }) - .sort({ first_name: 1, last_name: 1 }) - .skip(size * (pageNo - 1)) - .limit(size) - .exec(function (err, custumer) { - - if (err) { - console.error(err); - res.status(500).json({ "message": "Error Occured" } + err); - } - else if (custumer.length > 0) { - // res.status(200).json(custumer) - var pointer = 0; - var trac_pointer = 0; - let final_data = []; - for (let k = 0; k < custumer.length; k++) { - trac_pointer++; - module.exports.calDevice(custumer[k], function (id) { - final_data.push(id) - pointer++ - if (trac_pointer == pointer) { - res.send(final_data); - } - }) - } - } - else { - res.status(500).json({ "message": "No custumer Found" }); - } - }) -} - -module.exports.calDevice = function (uid, cb) { - - - Device.find({ "user": uid._id }, function (err, data) { - - if (err) { - console.error(err); - } - else if (data.length > 0) { - - if (uid.phone.charAt(0) == "n") { - let r = { - "_id": uid._id, - "first_name": uid.first_name, - "last_name": uid.last_name, - "email": uid.email, - "phone": "", - "total_vehicle": data.length, - "custumerid": uid.custumerid, - "status": uid.status, - "created_on": uid.created_on, - "pass": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "dealer_firstname": uid.Dealer.first_name, - "dealer_lastname": uid.Dealer.last_name, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - - } - cb(r); - } - else if (uid.email.charAt(0) == "n" && uid.email.charAt(2) == "E") { - let r = { - "_id": uid._id, - "first_name": uid.first_name, - "last_name": uid.last_name, - "email": "", - "phone": uid.phone, - "total_vehicle": data.length, - "custumerid": uid.custumerid, - "status": uid.status, - "created_on": uid.created_on, - "pass": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "dealer_firstname": uid.Dealer.first_name, - "dealer_lastname": uid.Dealer.last_name, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(r); - } - else { - let r = { - "_id": uid._id, - "first_name": uid.first_name, - "last_name": uid.last_name, - "email": uid.email, - "phone": uid.phone, - "total_vehicle": data.length, - "custumerid": uid.custumerid, - "status": uid.status, - "created_on": uid.created_on, - "pass": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "dealer_firstname": uid.Dealer.first_name, - "dealer_lastname": uid.Dealer.last_name, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(r); - } - - - - } - else { - - if (uid.phone.charAt(0) == "n") { - let r = { - "_id": uid._id, - "first_name": uid.first_name, - "last_name": uid.last_name, - "email": uid.email, - "phone": "", - "total_vehicle": 0, - "custumerid": uid.custumerid, - "status": uid.status, - "created_on": uid.created_on, - "pass": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "dealer_firstname": uid.Dealer.first_name, - "dealer_lastname": uid.Dealer.last_name, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(r) - } - else if (uid.email.charAt(0) == "n" && uid.email.charAt(2) == "E") { - let r = { - "_id": uid._id, - "first_name": uid.first_name, - "last_name": uid.last_name, - "email": "", - "phone": uid.phone, - "total_vehicle": 0, - "custumerid": uid.custumerid, - "status": uid.status, - "created_on": uid.created_on, - "pass": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "dealer_firstname": uid.Dealer.first_name, - "dealer_lastname": uid.Dealer.last_name, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(r) - } - else { - let r = { - "_id": uid._id, - "first_name": uid.first_name, - "last_name": uid.last_name, - "email": uid.email, - "phone": uid.phone, - "total_vehicle": 0, - "custumerid": uid.custumerid, - "status": uid.status, - "created_on": uid.created_on, - "pass": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "dealer_firstname": uid.Dealer.first_name, - "dealer_lastname": uid.Dealer.last_name, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(r) - } - - } - }) - -} - - -//Get Custumer Token -module.exports.getCustumerDetail = function (req, res) { - - Contact.findOne({ '_id': req.query.uid }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, custumer) { - - if (err) { - console.error(err); - res.status(500).json({ "message": "Error Occured" } + err); - } - else if (custumer) { - - - if (custumer.image_path) { - token = custumer.generateJwt(); - img = Utilities.getImage(custumer.image_path) - res.status(200); - res.json({ - "img": img, - "cust": custumer, - "custumer_token": token, - }); - } - else { - token = custumer.generateJwt(); - res.status(200); - res.json({ - "cust": custumer, - "custumer_token": token, - }); - } - - - } - else { - res.status(500).json({ "message": "Custumer not found" }); - } - }) - -} - -//Get Support -module.exports.getSupport = function (req, res) { - let support = { - "number": "020-65103106", - "email": "poonam.g@processfactory.in" - } - res.status(200).json(support); -} - -//Getabout -module.exports.Getabout = function (req, res) { - let about = { - "org": Utilities.getConfig().orgName, - "address": "404,purple pride square,kalewadi phata Kalewadi, Pune, Maharashtra 411057", - "Contact_Person": "Gaurav Gupta", - "Contact_per_phone": "7507500582", - "Contact_per_email": "info@processfactory.in", - "website": "https://www.oneqlik.in/home" - } - res.status(200).json(about); -} - -//Dealer Information Anshul Saxena 04/02/2018 - -module.exports.getDealerInfo = function (req, res) { - - var json = JSON.parse(require('fs').readFileSync('app_api/dealerConfig/' + req.query.url + '.json', 'utf8')); - - res.status(200).json(json); -} - -module.exports.dealer_status = function (req, res) { - // res.status(500).send({"message":"restricted"}); - Contact.findOne({ _id: ObjectId(req.body.uId) }, function (err, response) { - - if (err) { - console.error(err); - } else { - if (req.body.status == false) { - response.status = false - response.deactivated_by = req.body.loggedIn_id - response.deactivated_on = new Date(); - response.save(function (err) { - if (err) { - console.error(err); - } else { - res.sendStatus(200); - } - }) - } else if (req.body.status == true) { - response.status = true - response.activated_by = req.body.loggedIn_id - response.activated_on = new Date(); - response.save(function (err) { - if (err) { - console.error(err) - } else { - res.sendStatus(200); - } - }) - } - } - }) - -} - - -//get all dealer vehicles added by m.hemanth@12/06/2018 - -module.exports.calDevices = function (uid, cb) { - var pushArray = []; - var summation = 0; - Contact.find({ 'Dealer': uid._id }, function (err, customer) { - if (err) { - console.error(err); - res.sendStatus(500); - return; - } - if (customer.length > 0) { - function syncCustomers(index) { - if (index < customer.length) { - var t = customer[index]; - Device.find({ "user": t._id }, function (err, data) { - if (err) { - console.error(err); - res.sendStatus(500); - return; - } - if (data.length > 0) { - summation = summation + data.length; - } - else { - summation = summation; - } - syncCustomers(index + 1); - } - ); - } - else { - var obj = { - "dealer_id": uid._id, - "dealer_firstname": uid.first_name, - "dealer_lastname": uid.last_name, - "email": uid.email, - "phone": uid.phone, - "vehicleCount": summation, - "status": uid.status, - "created_on": uid.created_on, - "password": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(obj); - } - } - syncCustomers(0) - } - else { - Device.find({ "user": uid._id }, function (err, dealerdev) { - if (err) { - console.error(err); - res.status(500).send(err); - return; - } - var obj = { - "dealer_id": uid._id, - "dealer_firstname": uid.first_name, - "dealer_lastname": uid.last_name, - "email": uid.email, - "phone": uid.phone, - "vehicleCount": dealerdev.length, - "status": uid.status, - "created_on": uid.created_on, - "password": uid.pass, - "expiration_date": uid.expire_date, - "userid": uid.user_id, - "address": uid.address, - "docObject": uid.imageDoc, - "login_type": uid.login_type, - "last_login": uid.last_login, - "last_activity_on": uid.last_activity_on - } - cb(obj); - }) - } - }); - -} - -module.exports.getAllDealerVehicles = function (req, res) { - var final_result = []; - var query = {}; - var pageNo = parseInt(req.query.pageNo); - var size = parseInt(req.query.size); - if (pageNo < 0 || pageNo === 0) { - response = { "error": true, "message": "invalid page number, should start with 1" }; - return res.json(response) - } - - if (req.query.supAdmin) { - query = { $and: [{ isDealer: true }, { supAdmin: req.query.supAdmin }] }; - } - - else { - query = { $and: [{ isDealer: true }] }; - } - - var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] }; - // console.log(queryNew) - query['$and'].push(queryNew); - - if (req.query.search) { - query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] }) - } - // console.log("queryforget Dealer", query) - Contact.find(query) - .sort({ first_name: 1, last_name: 1 }) - .skip(size * (pageNo - 1)) - .limit(size) - .exec(function (err, dealers) { - if (err) { - console.error(err); - res.status(500).send(err); - return; - } - if (dealers.length > 0) { - var pointer = 0; - var trac_pointer = 0; - let final_data = []; - for (var k = 0; k < dealers.length; k++) { - trac_pointer++; - module.exports.calDevices(dealers[k], function (id) { - final_data.push(id) - pointer++ - if (trac_pointer == pointer) { - res.send(final_data); - } - }) - } - } - else { - res.status(500).json({ "message": "No customer Found" }); - } - }) -} - - - -//update user details - -module.exports.editUserDetails = function (req, res) { - Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.contactid) }, function (err, contact) { - if (err) { - console.error(err); - res.status(500).send(err); - return; - } - - if (contact) { - var tempUser = JSON.parse(JSON.stringify(contact)); - if (req.body.first_name) tempUser.first_name = req.body.first_name; - if (req.body.last_name) tempUser.last_name = req.body.last_name; - if (req.body.email) tempUser.email = req.body.email; - if (req.body.phone) tempUser.phone = req.body.phone; - if (req.body.emergencyContact) tempUser.emergency_contact= req.body.emergencyContact; - - // if (typeof (req.body.status) != null) tempUser.status = req.body.status; - if (req.body.expire_date) tempUser.expire_date = req.body.expire_date; - if (req.body.address) tempUser.address = req.body.address; - if (req.body.user_id) tempUser.user_id = req.body.user_id; - if (req.body.alert) tempUser.alert = req.body.alert; - if (req.body.role) tempUser.role = req.body.role; - // if (req.body.role) tempUser.role = req.body.role; - if (req.body.group) tempUser.group = req.body.group; - if (req.body.status) tempUser.status = req.body.status; - - Contact.update({ _id: req.body.contactid }, { $set: tempUser }, function (err, data) { - if (err) { - res.status(400).send({ "message": err.errmsg }); - return; - } - res.status(200).send({ "message": "Saved" }); - }); - } - else { - res.status(500).send("No User Found"); - } - }) - -} - -module.exports.deleteuserDetails = function (req, res) { - //console.log(req.body.userId); - Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.userId) }, function (err, delcontact) { - console.log(delcontact); - if (err) { - console.error(err); - res.status(500).send(err); - return; - } - if (delcontact) { - - delcontact.DeletedUser = req.body.deleteuser; - delcontact.save(function (err) { - if (err) { - console.error("inside error :" + err); - return; - } - res.status(200).send(delcontact._id); - }); - } - else { - res.status(500).send("No User Found"); - } - - }) -} - - - - -//get all customer vehicles under dealer - -module.exports.getAllCustomerVehiclesUnderDealer = function (req, res) { - var final_result = []; - Contact.find({ isDealer: true }, function (err, dealers) { - if (err) { - console.error(err); - res.status(500).send(err); - return; - } - if (dealers.length > 0) { - var pointer = 0; - var trac_pointer = 0; - let final_data = []; - for (var k = 0; k < dealers.length; k++) { - trac_pointer++; - module.exports.callCustomerVehicles(dealers[k], function (id) { - final_data.push(id) - pointer++ - if (trac_pointer == pointer) { - res.send(final_data); - } - }) - } - } - else { - res.status(500).json({ "message": "No customer Found" }); - } - }) -} - -module.exports.callCustomerVehicles = function (uid, cb) { - var pushArray = []; - Contact.find({ 'Dealer': uid._id }, function (err, customer) { - if (err) { - console.error(err); - res.sendStatus(500); - return; - } - if (customer.length > 0) { - function syncCustomers(index) { - if (index < customer.length) { - var t = customer[index]; - Device.find({ "user": t._id }, function (err, data) { - if (err) { - console.error(err); - res.sendStatus(500); - return; - } - if (data.length > 0) { - var cusObj = { - "customerName": t.first_name, - "customerId": t._id, - "vehicleDetails": data - } - pushArray = pushArray.concat(cusObj); - } - else { - var cusObj = { - "customerName": t.first_name, - "customerId": t._id, - "vehicleDetails": [] - } - pushArray = pushArray.concat(cusObj); - } - syncCustomers(index + 1); - } - ); - } - else { - var obj = { - "dealer_id": uid._id, - "dealer_firstname": uid.first_name, - "dealer_lastname": uid.last_name, - "email": uid.email, - "CustomerDetails": pushArray - } - cb(obj); - } - - } - syncCustomers(0) - } - else { - Device.find({ "user": uid._id }, function (err, dealerdev) { - if (err) { - console.error(err); - res.status(500).send(err); - return; - } - var obj = { - "dealer_id": uid._id, - "dealer_firstname": uid.first_name, - "dealer_lastname": uid.last_name, - "email": uid.email, - "phone": uid.phone, - } - cb(obj); - - }) - } - }); - -} - -function evaluate(object) { - if (object && object.constructor === Array) { - for (var i = 0; i < object.length; i++) { - object[i] = evaluate(object[i]); - } - } else if (object && typeof object == 'object' && Object.keys(object).length > 0) { - if (Object.keys(object).indexOf('_eval') < 0) { - for (var key in object) { - object[key] = evaluate(object[key]); - } - } else switch (object['_eval']) { - case 'Id': - { - object = mongoose.Types.ObjectId(object['value']); - break; - } - case 'regex': - { - object = new RegExp(object['value'], 'i'); - break; - } - case 'date': - { - object = new Date(object['value']).getTime(); - break; - } - } - } - return object; -} - - - -module.exports.datatable = function (req, res) { - var dtop = { - conditions: evaluate(req.body.find), - select: req.body.select - }; - //console.log(JSON.stringify(dtop.conditions, null, 4)); - - Contact.dataTable(req.body, dtop, function (err, data) { - if (err) { - console.error(err); - res.sendStatus(500); - return; - } - res.send(data); - }) -} - - -module.exports.editUserMaster = function (req, res) { - Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.contactid) }, function (err, data) { - - if (err) { - res.status(500).send(err); - return; - } else { - if (data) { - if (req.body.first_name) data.first_name = req.body.first_name; - if (req.body.last_name) data.last_name = req.body.last_name; - if (req.body.email) data.email = req.body.email; - if (req.body.organisation_name) data.organisation_name = req.body.organisation_name; - if (req.body.welcome_msg == true) data.welcome_msg = req.body.welcome_msg; - if (req.body.welcome_msg == false) data.welcome_msg = req.body.welcome_msg; - if (req.body.phone) data.phone = req.body.phone; - if (req.body.isDealer == false || req.body.isDealer) data.isDealer = req.body.isDealer; - if (req.body.isSuperAdmin == false || req.body.isSuperAdmin) data.isSuperAdmin = req.body.isSuperAdmin; - if (req.body.Dealer) data.Dealer = req.body.Dealer; - if (req.body.createdOn) data.createdOn = req.body.createdOn; - if (req.body.user_id) data.user_id = req.body.user_id; - if ((req.body.status == false) || req.body.status) data.status = req.body.status; - - - var tempData = JSON.parse(JSON.stringify(data)); - - if ((req.body.isDealer == true) && (req.body.isDealer != undefined)) { - - tempData.isDealer == true; - delete tempData['Dealer']; - var uId = tempData._id; - var updateFlag = 'dealerUpdate'; - - saveUser(uId, updateFlag); - } - - - - else if ((req.body.isSuperAdmin == true) && (req.body.isSuperAdmin != undefined)) { - - if (tempData.supAdmin) { - tempData.organisation = tempData.supAdmin; - - - - } - tempData.isSuperAdmin == true; - tempData.isDealer = false; - delete tempData['Dealer']; - delete tempData['supAdmin']; - var uId = tempData._id; - var updateFlag = 'adminUpdate'; - saveUser(uId, updateFlag); - - } else { - var uId = tempData._id; - var updateFlag = 'null'; - saveUser(uId, updateFlag); - } - - - function saveUser(uId, updateFlag) { - - var updatesupAdmin = false; - var updateId = uId; - // var newObject = new Contact(JSON.parse(JSON.stringify(tempData))); - - - if (updateFlag == 'adminUpdate') { - var unsetKey = { $unset: { supAdmin: "" }, $set: tempData }; - } - if (updateFlag == 'dealerUpdate') { - var unsetKey = { $set: tempData } - } - - - if (updateFlag == 'null') { - var unsetKey = { $set: tempData } - } - - - Contact.update({ _id: tempData._id }, unsetKey, function (err, changedObject) { - if (err) { - res.status(400).send(err); - } else { - - if (updateFlag != undefined) { - - var query = { - $or: [{ user: updateId }, { Dealer: updateId }] - }; - if (updateFlag == 'dealerUpdate') { - var setDevice = { - "Dealer": updateId - }; - - } - if (updateFlag == 'adminUpdate') { - var setDevice = { - "Dealer": updateId, - "supAdmin": updateId - }; - - - - updatesupAdmin = true; - - } - - if (updateFlag == 'null') { - var changeDealer = changedObject.Dealer; - var setDevice = { - "Dealer": changeDealer, - }; - - } - - - - if (updatesupAdmin == true) { - Contact.update({ Dealer: updateId }, { $set: { supAdmin: updateId } }, { multi: true }, function (err, updated) { - if (err) { - res.status(400).send({ "message": "err during supadmin update" }) - } - Device.update(query, { $set: setDevice }, { multi: true }, function (err, deviceUpdate) { - if (err) { - res.status(400).send({ "message": "error during device update" }); - } - res.status(200).send({ "message": "Role changed and devices updated" }); - - }) - - }) - } else { - Device.update(query, { $set: setDevice }, { multi: true }, function (err, deviceUpdate) { - if (err) { - res.status(400).send({ "message": "error during device update" }); - } - res.status(200).send({ "message": "Role changed and devices updated" }); - - }) - } - - } else { - res.status(200).send("Edited Successfully!!!"); - } - } - }) - } - - } else { - res.status(500).send("No user Found !!!"); - } - - } - }) -} -module.exports.tokenCheck = function (req, res, next) { - - if (req.method == "GET") next(); - if (req.method == "POST" || req.method == "PUT") { - var token = req.header('Authorization'); - if (token != "bearer") { - req.user = jwt.decode(token); - next(); - // res.send({res:jwt.decode(token)}); - // jwt.verify(token, 'MY_SECRET', function (err, data) { - // req.user = data; - // if (err) return res.send({ msg: "forbidden" }); - // next(); - // }); - } - else - res.send({ msg: "forbidden" }); - } - -} - -// module.exports.updatePassword = function (req,res){ -// console.log(req.body); -// Contact.find({ "_id": mongoose.Types.ObjectId(req.body.ID) }-, function (err, user) { -// if(err){ -// res.status(400).send(err); -// } -// if(user){ -// console.log(user); -// res.status(200).send({"success":"Password updated"}); -// } -// else{ -// res.status(200).send({"success":"UserNot found"}); -// } -// }) - -// } - -module.exports.updatePassword = function (req, res) { - Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.ID) }, function (err, result) { - if (err) { - console.error(err); - res.status(400).send(err); - return err; - } - if (result) { - //console.log(result); - if (result.validPassword(req.body.OLD_PASS)) { - console.log("old pass found !!!!"); - result.setPassword(req.body.NEW_PASS); - result.save(function (err) { - if (err) { - console.error("inside error :" + err); - return; - } - //console.log(result); - res.status(200).send({ "message": "Password updated !!!" }); - }) - } else { - res.status(400).send({ "message": "Old password not matched" }); - } - } - else { - res.status(500).json({ "message": "USER NOT FOUND !!!" }); - } - }) -} - - -module.exports.getCostumer = function (req, res) { - var query = {}; - if (req.query.all == 'true') { - query = { 'supAdmin': ObjectId(req.query.uid), isDealer: false }; - } else { - query = { 'Dealer': ObjectId(req.query.uid), isDealer: false }; - } - console.log('query', query); - - var pageNo = parseInt(req.query.pageNo); - var size = parseInt(req.query.size); - if (pageNo < 0 || pageNo === 0) { - response = { "error": true, "message": "invalid page number, should start with 1" }; - return res.json(response) - } - // query = { isDealer: false }; - - query['$and'] = []; - if (req.query.search) { - query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] }) - } - - var queryNew = { $or: [{ DeletedUser: { $exists: false } }, { $and: [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] }; - query['$and'].push(queryNew); - Contact.aggregate([ - - { - $match: query - }, - { - $project: { - "user_id": 1, "first_name": 1, "last_name": 1, "Dealer": 1, "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "point_Allocated": 1, - "login_type": 1, "last_login": 1, "last_activity_on": 1, "_id": -1, "status": 1, "imageDoc": 1, "pushNotification": 1, "address": 1, "std_code": 1, "accountSuspended": 1,"emergency_contact":1, "adminAlert": 1 - } - }, - { - $sort: { _id: -1 } - }, - { - $lookup: { - from: "devInfo", - localField: "_id", - foreignField: "user", - as: "total_vehicle" - } - }, - { - $lookup: { - from: "client_master", - localField: "Dealer", - foreignField: "_id", - as: "DealerDetails" - } - }, - { - $project: { - "DealerDetails.first_name": 1, "DealerDetails.last_name": 1, "total_vehicle": { $size: "$total_vehicle" }, "delDevices": { $size: "$total_vehicle.deletedDevice" }, "user_id": 1, "first_name": 1, "last_name": 1, "address": 1, "std_code": 1, "accountSuspended": 1, - "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "point_Allocated": 1, "login_type": 1, "last_login": 1, "last_activity_on": 1, "_id": -1, "status": 1,"emergency_contact":1, "imageDoc": 1, "notificationTokenCount": { $size: "$pushNotification" }, "adminAlert": 1 - } - }, - { - "$skip": (size * (pageNo - 1)) - }, - { - "$limit": size - } - ]).exec(function (err, customers) { - if (err) { - res.status(400).send(err); - } - res.status(200).send(customers); - }) - -} - - - -module.exports.getAllDealerDetails = function (req, res) { - var final_result = []; - var query = {}; - var pageNo = parseInt(req.query.pageNo); - var size = parseInt(req.query.size); - if (pageNo < 0 || pageNo === 0) { - response = { "error": true, "message": "invalid page number, should start with 1" }; - return res.json(response) - } - - if (req.query.supAdmin) { - query = { $and: [{ isDealer: true }, { supAdmin: ObjectId(req.query.supAdmin) }] }; - } - - else { - query = { $and: [{ isDealer: true }] }; - } - - if (req.query.customer_role) { - query = { $and: [{ customer_role: 'subadmin' }] }; - } - - var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] }; - //console.log(queryNew) - query['$and'].push(queryNew); - - if (req.query.search) { - query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] }) - } - console.log("queryforget Dealer", query); - - Contact.aggregate([ - { - $match: query - }, - { - "$skip": (size * (pageNo - 1)) - }, - { - "$limit": size - }, - { - $project: { - "phone": 1, "status": 1, "created_on": 1, "pass": 1, "expire_date": 1, "user_id": 1, "address": 1, "imageDoc": 1, "login_type": 1, "std_code": 1, "accountSuspended": 1, - "last_login": 1, "last_activity_on": 1, "_id": 1, "first_name": 1, "last_name": 1, "email": 1, "pushNotification": 1, "cust_add_permission": 1, "device_add_permission": 1, "point_Allocated": 1, "point_Shared_Other": 1 - } - }, - { - $sort: { _id: -1 } - }, - { - $lookup: { - from: "devInfo", - localField: "_id", - foreignField: "Dealer", - as: "total_vehicle" - } - }, - { - $project: { - "total_vehicle": { $size: "$total_vehicle" }, "delDevices": { $size: "$total_vehicle.deletedDevice" }, "user_id": 1, "first_name": 1, "last_name": 1, "address": 1, "cust_add_permission": 1, "device_add_permission": 1, "point_Allocated": 1, "point_Shared_Other": 1, "std_code": 1, - "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "login_type": 1, "last_login": 1, "last_activity_on": 1, "_id": -1, "status": 1, "imageDoc": 1, "notificationTokenCount": { $size: "$pushNotification" }, "accountSuspended": 1 - } - } - - ]).exec(function (err, Dealers) { - if (err) { - res.status(400).send(err); - } - res.status(200).send(Dealers); - }) - -} - -module.exports.getAllDealerDetailsMobile = function (req, res) { - var final_result = []; - var query = {}; - var pageNo = parseInt(req.query.pageNo); - var size = parseInt(req.query.size); - if (pageNo < 0 || pageNo === 0) { - response = { "error": true, "message": "invalid page number, should start with 1" }; - return res.json(response) - } - - if (req.query.supAdmin) { - query = { $and: [{ isDealer: true }, { supAdmin: ObjectId(req.query.supAdmin) }] }; - } - - else { - query = { $and: [{ isDealer: true }] }; - } - - if (req.query.customer_role) { - query = { $and: [{ customer_role: 'subadmin' }] }; - } - - var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] }; - //console.log(queryNew) - query['$and'].push(queryNew); - - if (req.query.search) { - query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] }) - } - //console.log("queryforget Dealer", query); - - Contact.aggregate([ - { - $match: query - }, - { - "$skip": (size * (pageNo - 1)) - }, - { - "$limit": size - }, - { - $project: { - "phone": 1, "status": 1, "created_on": 1, "pass": 1, "expire_date": 1, "user_id": 1, "address": 1, "imageDoc": 1, "login_type": 1, "std_code": 1, "accountSuspended": 1, - "last_login": 1, "last_activity_on": 1, "_id": 1, "first_name": 1, "last_name": 1, "email": 1, "pushNotification": 1, "cust_add_permission": 1, "device_add_permission": 1, "point_Allocated": 1, "point_Shared_Other": 1 - } - }, - { - $sort: { _id: -1 } - }, - { - $lookup: { - from: "devInfo", - localField: "_id", - foreignField: "Dealer", - as: "total_vehicle" - } - }, - { - $project: { - "total_vehicle": { $size: "$total_vehicle" }, "user_id": 1, "first_name": 1, "last_name": 1, "point_Allocated": 1, "point_Shared_Other": 1, - "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "_id": -1, "status": 1, "accountSuspended": 1, "address": 1 - } - } - // _id, first_name, last_name, email, phone, pass, created_on, total_vehicle, status, expire_date, user_id, address, point_Allocated - - ]).exec(function (err, Dealers) { - if (err) { - res.status(400).send(err); - } - res.status(200).send(Dealers); - }) - -} -module.exports.zogogetDocument = function (req, res) { - Contact.findOne({ _id: req.query.id }, function (err, data) { - if (err) { - res.status(400).send('something went wrong'); - } - res.status(200).send({ 'userdata': data }); - }) - - -} - - -module.exports.restoreUsers = function (req, res) { - Contact.findOneAndUpdate( - { _id: req.query.id }, - { $unset: { DeletedUser: "" } }, - function (err, user) { - if (err) { - res.status(400).send({ message: "no user found" }); - } - res.status(200).send(user); - } - ); -}; - - -module.exports.reportPrefrence = function (req, res) { - //console.log('req.body', req.body); - var setObject = {} - - if (req.body.reportsArr) { - setObject['report_preference'] = req.body.reportsArr; - } - if(req.body.userSetting){ - setObject['user_settings'] = req.body.userSetting; - } - - - Contact.update( - { _id: req.body.id }, - { $set: setObject }, function (err, user) { - if (err) { - req.status(400).send({ err }) - } - res.status(200).send({ "message": "Report preference updated" }); - } - ) -} - -module.exports.dashboardContent = function (req, res) { - //console.log('req.body', req.body); - var setObject = {} - - if (req.body.dashboard_column) { - setObject['dashboard_column'] = req.body.dashboard_column; - } - - - Contact.update( - { _id: req.body.user }, - { $set: setObject }, function (err, user) { - if (err) { - req.status(400).send({ err }) - } - res.status(200).send({ "message": "Dashboard Content updated" }); - } - ) -} - - -module.exports.shareUserDetails = function (req, res) { - Contact.findOne({ _id: req.query.user }) - .populate('supAdmin') - .exec(function (err, data) { - if (err) { - res.status(400).send('something went wrong'); - } - var userdata = data; - var SMSURL = Utilities.getConfig().smsUrl; - var organisation_name = data.supAdmin.organisation_name; - var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic'; - var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1'; - var userCred1 = 'Dear%20' + userdata.first_name + "%20Your%20credentials%20of%20" + organisation_name + "%20are%20userId%20" + userdata.user_id + '%20Password%20' + userdata.pass; - var mobile_key = Utilities.getConfig().smsApiMobileKey; - var txt_key = Utilities.getConfig().smsApiTextKey; - - if (organisation_name == 'Tractive VTS') { - SMSURL += '&sender=TRACTV'; - userCred1 = 'Dear%20' + userdata.first_name + "%20Welcome%20to%20" + organisation_name + "%20Platform%20%2C%20Your%20Login%20credentials%20are%20UserId%20" + userdata.user_id + '%20Password%20' + userdata.pass + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login'; - } else if (organisation_name === 'IConnect Technologies') { - SMSURL = Utilities.getConfig().smsUrl_iconnect; - SMSURL += '&senderid=AMASEC'; - mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect; - txt_key = Utilities.getConfig().smsApiTextKey_iconnect; - var userCred1 = 'Dear%20' + userdata.first_name + "%20Welcome%20to%20" + organisation_name + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + userdata.user_id + '%20Password%20' + userdata.pass + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in'; - } else if (organisation_name === 'Saanvi Security Solution') { - SMSURL = Utilities.getConfig().smsUrl_saanvi; - mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi; - txt_key = Utilities.getConfig().smsApiTextKey_saanvi; - var userCred1 = 'Dear%20' + userdata.first_name + "%20Welcome%20to%20" + organisation_name + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + userdata.user_id + '%20Password%20' + userdata.pass + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in'; - } else { - SMSURL += '&sender=OneQlk'; - } - - - - console.log(SMSURL + mobile_key + userdata.phone + txt_key + userCred1); - - request({ - uri: SMSURL + mobile_key + userdata.phone + txt_key + userCred1, - method: "GET" - }, function (error, response, body) { - res.status(200).json({ "message": "Login Information Sent" }) - }); - }) - -} - -module.exports.hardresetPassword = function (req, res) { - console.log('inside function'); - Contact.findOne({ _id: req.body.id }, function (err, user) { - if (err) { - res.status(500).send({ "message": "No user found" }) - } - console.log('useruseruseruseruseruseruser',user); - var newUser = new Contact(user); - newUser.setPassword(req.body.pass); - newUser.save(function (err) { - if (err) { - res.status(500).send(err) - } else { - res.status(200).send({ "message": "Password updated !!!" }); - } - }) - }) - -} - - - -module.exports.setDealerPermission = function (req, res) { - Contact.findOne({ _id: req.body.uid }, function (err, user) { - if (err) { - res.status(500).send({ "message": "No user found" }) - } - - var newUser = new Contact(user); - newUser.cust_add_permission = req.body.cust_add_permission; - newUser.device_add_permission = req.body.device_add_permission; - newUser.save(function (err) { - if (err) { - res.status(500).send({ "message": "Internal Server Error" }) - } else { - res.status(200).send({ "message": "Permission updated !!!" }); - } - }) - }) -} - - -module.exports.getuserDetail = function (req, res) { - Contact.findOne({ _id: req.query.uid }, function (err, user) { - if (err) { - res.status(500).send({ "message": "No user found" }) - } - res.status(200).send(user) - - }) - - -} - -module.exports.getuserDetailBySchhol = function (req, res) { - Contact.findOne({ school: req.query.uid }, function (err, user) { - if (err) { - res.status(500).send({ "message": "No user found" }) - } - res.status(200).send(user) - - }) - -} - - - -module.exports.DemoRequest = function (req, res) { - console.log("Inside function"); - - var parseJson = req.body.url; - - var parse1 = parseJson.split('.'); - var parse2 = parse1[1]; - console.log("ParsedUrl", parse2); - - var Dealerjson = JSON.parse(require('fs').readFileSync('app_api/dealerConfig/' + parse2 + '.json', 'utf8')); - console.log('Dealerjson', Dealerjson); - if (Dealerjson == undefined) { - return res.status(500).send({ 'message': 'Url is not valid' }); - } - console.log(Dealerjson); - var DealerEmail = (Dealerjson.email != '') ? Dealerjson.email : res.status(500).send({ 'message': 'Update Email in DealerConfig' }); - console.log('DealerEmail', DealerEmail); - var DealerName = Dealerjson.dealerName; - - var client_fName = req.body.first_name; - var client_lName = req.body.last_name ? req.body.last_name : ''; - var client_phone = req.body.phone ? req.body.phone : ''; - var client_email = req.body.email; - - var htmlBody = '
' + - '
' + - '

' + 'Dear ' + DealerName + '

' + - '

' + 'Someone has requested for demo.Please find details below.' + '

' + - '

' + 'First Name : ' + client_fName + '

' + - '

' + 'Last Name : ' + client_lName + '

' + - '

' + 'Eamil : ' + client_email + '

' + - '

' + 'Phone Number :' + client_phone + '

' + - '

' + 'Thank You' + '

' - '
' + - '
'; - - var mainEmail = 'reports@oneqlik.in' - var mailOptions = { - from: mainEmail, // sender address - to: DealerEmail, // list of receivers - subject: 'Demo Request', // Subject line - // text: 'Switch Status', // plaintext body - html: htmlBody - }; - console.log(mailOptions); - mailer.sendMail(mailOptions); - res.status(200).send({ 'message': 'Demo request sent' }) - - -} - -module.exports.checkPointAvailablity = function (req, res) { - console.log('req.body', req.query); - if (!req.query.u_id) { - res.status(200).send({ message: "user_id is mandatory" }); - return; - } - if (!req.query.demanded_points) { - res.status(200).send({ message: "demanded_points is mandatory" }) - return; - } - - - Contact.findOne({ _id: req.query.u_id }, function (err, con) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (con) { - //console.log(con); - if (con.isSuperAdmin) { - Device.find({ $or: [{ user: req.query.u_id }, { Dealer: req.query.u_id }] }).count().exec(function (err, count) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (count >= 0) { - console.log(count); - if (con.point_Allocated > (count + con.point_Shared_Other)) { - - if (con.point_Allocated - (count + con.point_Shared_Other) > req.query.demanded_points) { - res.status(200).send({ available: true, available_points: con.point_Allocated - (count + con.point_Shared_Other) }) - - } - else { - res.status(200).send({ available: true, message: "only " + con.point_Allocated - (count + con.point_Shared_Other) + " points available" }) - } - } else { - res.status(200).send({ available: false, available_points: con.point_Allocated - (count + con.point_Shared_Other) }) - - } - - } - - }) - } - else if (con.isDealer) { - Device.find({ Dealer: req.query.u_id }).count().exec(function (err, count) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (count >= 0) { - console.log(count); - if (con.point_Allocated > (count + con.point_Shared_Other)) { - - if (con.point_Allocated - (count + con.point_Shared_Other) > req.query.demanded_points) { - res.status(200).send({ available: true, available_points: con.point_Allocated - (count + con.point_Shared_Other) }) - - } - else { - res.status(200).send({ available: true, message: "only " + con.point_Allocated - (count + con.point_Shared_Other) + " points available" }) - } - } else { - res.status(200).send({ available: false, available_points: con.point_Allocated - (count + con.point_Shared_Other) }) - - } - - } - - }) - } else { - Contact.findOne({ _id: con.Dealer }, function (err, con1) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (con1) { - Device.find({ Dealer: con.Dealer }).count().exec(function (err, count) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (count >= 0) { - con = con1 - console.log(count); - if (con.point_Allocated > (count + con.point_Shared_Other)) { - - if (con.point_Allocated - (count + con.point_Shared_Other) > req.query.demanded_points) { - res.status(200).send({ available: true, available_points: con.point_Allocated - (count + con.point_Shared_Other) }) - - } - else { - res.status(200).send({ available: true, message: "only " + con.point_Allocated - (count + con.point_Shared_Other) + " points available" }) - } - } else { - res.status(200).send({ available: false, available_points: con.point_Allocated - (count + con.point_Shared_Other) }) - - } - - } - - }) - } - }) - - - } - - - } else { - - res.status(200).send({ "message": "user not found" }) - } - }) -} -module.exports.getColumnSetting = function (req, res) { - - if (!req.query.u_id) { - res.status(200).send({ message: "user_id is mandatory" }); - return; - } - - - - Contact.findOne({ _id: req.query.u_id }, function (err, con) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (con) { - if (con.dashboard_column) { - res.status(200).send({ "dashboard_column": con.dashboard_column }) - } else { - res.status(200).send({ "message": "dashboard_column not found" }) - } - - - - } else { - - res.status(200).send({ "message": "user not found" }) - } - }) -} - -module.exports.setApiKey = function (req, res) { - - if (!req.body.u_id) { - res.status(200).send({ message: "user_id is mandatory" }); - return; - } - if (!req.body.dashboard_column) { - res.status(200).send({ message: "dashboard_column is mandatory" }) - return; - } - - - Contact.findOne({ _id: req.body.u_id }, function (err, con) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (con) { - Contact.update({ _id: req.body.u_id }, { $set: { dashboard_column: req.body.dashboard_column } }, function (err, upd) { - if (err) { - console.log(err); - } - if (upd) { - res.status(200).send("saved successfully"); - } - }) - - - - - } else { - - res.status(200).send({ "message": "user not found" }) - } - }) -} -module.exports.setApiKey = function (req, res) { - - if (!req.query.u_id) { - res.status(200).send({ message: "user_id is mandatory" }); - return; - } - if (!req.query.api_key) { - res.status(200).send({ message: "api key is mandatory" }) - return; - } - - - Contact.findOne({ _id: req.query.u_id }, function (err, con) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (con) { - Contact.update({ _id: req.query.u_id }, { $set: { api_key: req.query.api_key } }, function (err, upd) { - if (err) { - console.log(err); - } - if (upd) { - res.status(200).send("saved successfully"); - } - }) - - - - - } else { - - res.status(200).send({ "message": "user not found" }) - } - }) -} - - -module.exports.getApiKey = function (req, res) { - - if (!req.query.u_id) { - res.status(200).send({ message: "user_id is mandatory" }); - return; - } - - - - Contact.findOne({ _id: req.query.u_id }, function (err, con) { - if (err) { - console.log(err); - res.send(err) - return; - } - if (con) { - if (con.api_key) { - res.status(200).send({ "api_key": con.api_key }) - } else { - res.status(200).send({ "message": "api key not found" }) - } - - - - } else { - - res.status(200).send({ "message": "user not found" }) - } - }) -} -module.exports.accountSuspension = function (req, res) { - if ((req.body.accountSuspended === undefined) || (req.body.acoountId === undefined) || (req.body.suspendedBy === undefined)) { - res.status(500).send({ "message": "missing Parameters" }); - } else { - var query = {}; - - if (req.body.suspendedBy === 'org') { - query = { $or: [{ supAdmin: req.body.acoountId }, { _id: req.body.acoountId }] }; - Contact.update(query, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err1, contactObj) { - if (err1) { - res.status(400).send({ "message": "contact noot updated" }); - } - Device.update({ supAdmin: req.body.acoountId }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err2, deviceObj) { - if (err2) { - res.status(400).send({ "message": "device noot updated" }); - } - res.status(200).send({ "messsage": "Contact and device status updated" }); - }) - }) - } else if (req.body.suspendedBy === 'distributer') { - Contact.update({ $or: [{ Dealer: req.body.acoountId }, { _id: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err1, contactObj) { - if (err1) { - res.status(400).send({ "message": "contact noot updated" }); - } - Device.update({ $or: [{ Dealer: req.body.acoountId }, { user: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err2, deviceObj) { - if (err2) { - res.status(400).send({ "message": "device noot updated" }); - } - res.status(200).send({ "messsage": "Contact and device status updated" }); - }) - }) - } else if (req.body.suspendedBy === 'dealer') { - Contact.update({ $or: [{ _id: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err1, contactObj) { - if (err1) { - res.status(400).send({ "message": "contact noot updated" }); - } - Device.update({ $or: [{ user: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err2, deviceObj) { - if (err2) { - res.status(400).send({ "message": "device noot updated" }); - } - res.status(200).send({ "messsage": "Contact and device status updated" }); - }) - }) - - } else { - res.status(500).send({ "message": "missing parameters" }) - - } - - } - -} - - -module.exports.getsupAdmin = function (req, res) { - Contact.find({ organisation: req.query.supAdmin }, function (err, distributers) { - if (err) { - res.status(500).send({ "message": "no distributers found" }); - } - res.status(200).send(distributers); - }) -} - -module.exports.getDealerAndcust = function (req, res) { - Contact.find({ $or: [{ supAdmin: req.query.supAdmin }, { Dealer: req.query.supAdmin }] }, function (err, distributers) { - if (err) { - res.status(500).send({ "message": "no data found" }); - } - res.status(200).send(distributers); - }) - -} -