devriksof

lamda file shahwar bhai directed code

May 2nd, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. /**
  4.  * @author Copyright RIKSOF (Private) Limited.
  5.  */
  6. const Promise = require('bluebird');
  7. const nodeMailer = require('nodemailer');
  8. const ejs = require('ejs');
  9. const Email = require('./Email.js');
  10. const argv = require('minimist')(process.argv.slice(2));
  11. const JitDocument = require('jit/client').JitDocument;
  12. const JitDiff = require('jit/client').JitDiff;
  13. const JitCommits = require('jit/client').JitCommits;
  14. const JitClient = require('jit/client').JitClient;
  15. const JitMerge = require('jit/client').JitMerge;
  16. const moment = require('moment');
  17. const holidays = require('./../holidays.js');
  18. const termDuration = '06-11-00-05';
  19. const runDate = new Date(moment().subtract(0, 'days').format('YYYY-MM-DD'));
  20. const session = '2017-2018';
  21. var startDateFT = new Date(moment([session.split('-')[0], termDuration.split('-')[0]]).startOf('month'));
  22. var endDateFT = new Date(moment([session.split('-')[0], termDuration.split('-')[1]]).endOf('month'));
  23. var startDateST = new Date(moment([session.split('-')[1], termDuration.split('-')[2], 9]).startOf('day'));
  24. var endDateST = new Date(moment([session.split('-')[1], termDuration.split('-')[3]]).endOf('month'));
  25. var htmlString = '';
  26. var From = '\"KGS\" regcs.sec@kgs.edu.pk';
  27. var To = argv.email.split(',');
  28. var subject = 'Late attendance count exceeds to three';
  29. var isHtml = true;
  30. var house = {};
  31. var lastMsgGenerated = 0;
  32. var emailList = [];
  33. let parentEmailList = [];
  34. house['F'] = Array(11);
  35. house['S'] = Array(11);
  36. house['N'] = Array(11);
  37. house['P'] = Array(11);
  38. const config = {
  39.   jit: {
  40.     url: 'http://localhost:3000',
  41.     username: 'kgs-s2a-io',
  42.     password: 'ZMF[R-tA-j6U$FzH',
  43.     token: 'AXAoUM4TYGscwFzak5PcHMdAQhaZKTCZ'
  44.   },
  45.   email: {
  46.     service: 'SES',
  47.     host: 'email-smtp.us-east-1.amazonaws.com',
  48.     port: 465,
  49.     user: argv.user,
  50.     password: argv.pass
  51.   },
  52.   statsData: {
  53.     branch: 'kgs.s2a.io-Data-student-attendance-stats',
  54.     localBranch: ''
  55.   },
  56.   data: {
  57.     branch: 'kgs.s2a.io-Data-student-personal-information',
  58.     localBranch: '',
  59.     session: session
  60.   }
  61. }
  62.  
  63. const COMMIT_MESSAGE = 'Send email to parents through lambda.';
  64. const DELAY_AFTER_CONNECTION_ERROR = 10000;
  65.  
  66. /**
  67.  * This function is the entry point for send-email.kgs.s2a.io serverless function.
  68.  *
  69.  * @param {any} data                          Data passed to this function.
  70.  * @param {any} context                       Client context. Unused.
  71.  * @param {function} callback                 Callback function to pass back
  72.  *                                            the response.
  73.  *
  74.  * @returns {undefined} None.
  75.  */
  76. module.exports.handler = function SendEmailHandler(data, context, callback) {
  77.   let client = new JitClient(config.jit.url, config.jit.username,
  78.     config.jit.password);
  79.  
  80.  
  81.   for (let key in house) {
  82.     for (let i = 0; i < house[key].length; i++) {
  83.       house[key][i] = key + (i + 1);
  84.     }
  85.   }
  86.   var projections = {
  87.     "map": {
  88.       "keys": [],
  89.       "values": [
  90.         "studentId",
  91.         "parentEmail",
  92.         "freezeStatus"
  93.       ]
  94.     },
  95.     "reduce": {
  96.       "studentId": "current.studentId",
  97.       "parentEmail": "current.parentEmail",
  98.       "freezeStatus": "current.freezeStatus"
  99.     }
  100.   };
  101.   // Connect to the server.
  102.   for (let key in house) {
  103.     let houseGroupDate = {};
  104.     let doc = JitDocument.init({});
  105.     let doc1 = JitDocument.init({});
  106.     let JIT_SEARCH_REFERENCE = 'ref-send-email.kgs.s2a.io-' + house[key] + '-' + runDate;
  107.     JitDocument.setId(doc, JIT_SEARCH_REFERENCE);
  108.     JitDocument.setId(doc1, JIT_SEARCH_REFERENCE);
  109.     let query = {};
  110.     let query1 = {
  111.       studentClass: {
  112.         $in: house[key]
  113.       }
  114.     };
  115.     let students = [];
  116.    
  117.     connect(client).then(function AfterConnect() {
  118.       return client.search(config.jit.username, config.data.branch,
  119.         JIT_SEARCH_REFERENCE, query1, 0, projections);
  120.     }).then(function AfterStudentInfoSearch(commits) {
  121.       // Save all commits in search results.
  122.       for (let a = 0; a < commits.length; a++) {
  123.         doc1 = JitMerge.merge(doc1, [commits[a].diff]);
  124.       }
  125.       if (doc1.data.length > 0) {
  126.         // console.log("doc1",doc1.data);
  127.         for (let b = 0; b < doc1.data.length; b++) {
  128.           if(doc1.data[b].freezeStatus == "Yes"){
  129.           students.push(doc1.data[b].studentId);
  130.           }
  131.           // else{
  132.           // parentEmailList.push({id : doc1.data[b].studentId , pEmail : doc1.data[b].parentEmail ? doc1.data[b].parentEmail :"no email"  });
  133.           // }
  134.         }
  135.       }
  136.       return doc1.data;
  137.     }).then(function StudentStatsSearch() {
  138.       query = {
  139.         studentClass: {
  140.           $in: house[key]
  141.         },
  142.         studentId: {
  143.           $not: {
  144.             $in: students
  145.           }
  146.         }
  147.       };
  148.       return client.search(config.jit.username, config.statsData.branch,
  149.         JIT_SEARCH_REFERENCE, query, 0, null, {
  150.           studentClass: 1,
  151.           secondTermLate: 1
  152.         });
  153.     }).then(function AfterStudentStatsSearch(commits) {
  154.  
  155.       // Save all commits in search results.
  156.       for (let a = 0; a < commits.length; a++) {
  157.         doc = JitMerge.merge(doc, [commits[a].diff]);
  158.       }
  159.       if (doc.data.length > 0) {
  160.         let p = new Promise.resolve(true);
  161.         let sendEmail = false;
  162.         // console.log(' parentEmailList', parentEmailList);
  163.         for (let k = 0; k < doc.data.length; k++) {
  164.           let base = JSON.parse(JSON.stringify(doc.data[k]));
  165.           let studentDetails = {};
  166.           if (moment(runDate).isBetween(startDateFT, endDateFT, null, []) && doc.data[k].firstTermLate % 3 == 0 && doc.data[k].firstTermLate != 0) {
  167.             // if (doc.data[k].lastMsgGenerated != doc.data[k].firstTermLate) {
  168.               sendEmail = true;
  169.               studentDetails = {
  170.                 studentId: doc.data[k].studentId,
  171.                 studentName: doc.data[k].studentName,
  172.                 studentClass: doc.data[k].studentClass,
  173.                 className: doc.data[k].className,
  174.                 days: doc.data[k].firstTermlate,
  175.                 parentEmail: doc1.data[k].parentEmail  ? doc1.data[k].parentEmail :"z@gmail.com"
  176.               };
  177.               if(studentDetails.parentEmail != null){
  178.                 To = studentDetails.parentEmail ;
  179.                 }
  180.               console.log("to in first term",studentDetails.parentEmail);
  181.               ejs.renderFile(__dirname + '/template.ejs', {
  182.                 studentDetails: studentDetails,
  183.                 now: moment().format('DD-MMM-YYYY')
  184.               }, function (err, str) {
  185.                 if (err) {
  186.                   console.log(err);
  187.                 } else {
  188.                   var email = new Email(config.email.service, config.email.host, config.email.port, config.email.user, config.email.password);
  189.                   email.send(From, To, subject, str, isHtml);
  190.                 }
  191.               });
  192.               doc.data[k].lastMsgGenerated = doc.data[k].firstTermLate;
  193.               p = p.then(function AfterPush() {
  194.                 return update(base, doc.data[k], client);
  195.               }).catch(function OnPushError(e) {
  196.                 console.error(e);
  197.                 return doc.data[k];
  198.               })
  199.            
  200.             // }
  201.           } else if (moment(runDate).isBetween(startDateST, endDateST, null, []) && doc.data[k].secondTermLate % 3 == 0 && doc.data[k].secondTermLate != 0) {
  202.             // if (doc.data[k].lastMsgGenerated != doc.data[k].secondTermLate) {
  203.               sendEmail = true;
  204.               studentDetails = {
  205.                 studentId: doc.data[k].studentId,
  206.                 studentName: doc.data[k].studentName,
  207.                 studentClass: doc.data[k].studentClass,
  208.                 className: doc.data[k].className,
  209.                 days: doc.data[k].secondTermLate,
  210.                 parentEmail:doc1.data[k].parentEmail ? doc1.data[k].parentEmail :"y@gmail.com"
  211.               };
  212.               if(studentDetails.parentEmail != null){
  213.               To = studentDetails.parentEmail ;
  214.               }
  215.               console.log("to in 2nd term",studentDetails.parentEmail);
  216.               ejs.renderFile(__dirname + '/template.ejs', {studentDetails: studentDetails,now: moment().format('DD-MMM-YYYY')}, function (err, str) {
  217.                 if (err) {
  218.                   console.log(err);
  219.                 } else {
  220.                   var email = new Email(config.email.service, config.email.host, config.email.port, config.email.user, config.email.password);
  221.                   email.send(From, To, subject, str, isHtml);
  222.                 }
  223.               });
  224.               doc.data[k].lastMsgGenerated = doc.data[k].secondTermLate;
  225.               p = p.then(function AfterPush() {
  226.                 return update(base, doc.data[k], client);
  227.               }).catch(function OnPushError(e) {
  228.                 console.error(e);
  229.                 return doc.data[k];
  230.               })    
  231.             // }
  232.           } else {
  233.             sendEmail = false;
  234.           }
  235.         }
  236.       }
  237.      
  238.       return doc.data;
  239.     }).then(function AfterSaveData(d) {
  240.       // Returns OK if all data read and pushed successfully
  241.       callback(null, {
  242.         House: house[key],
  243.         emailStatus: 'sent'
  244.       });
  245.     }).catch(function OnError(err) {
  246.       console.error(err);
  247.  
  248.       // Returns FAIL if there is error
  249.       callback(err);
  250.     });
  251.   }
  252. };
  253.  
  254. /**
  255.  * Setup connection.
  256.  *
  257.  * @param {JitClient} client              Client to use to connect.
  258.  *
  259.  * @returns {Promise} p                   Once connection is established.
  260.  */
  261. function connect(client) {
  262.   return client.reconnect(config.jit.username, config.jit.token, '', 0)
  263.     .then(function SuccessOnConnection() {
  264.       return true;
  265.     }).catch(function OnConnectionError(e) {
  266.       console.error(e);
  267.       return Promise.delay(DELAY_AFTER_CONNECTION_ERROR)
  268.         .then(function AfterDelay() {
  269.           return connect(client);
  270.         });
  271.     });
  272. }
  273.  
  274. function update(base, data, client) {
  275.   // Set values to the doc.
  276.   let updatedData = data;
  277.   //console.log('base', base);
  278.   //console.log('updatedData', updatedData);
  279.  
  280.   let documentId = JitDocument.getId(updatedData);
  281.   var $jsonitMeta = JitDocument.removeMeta(updatedData);
  282.   JitDocument.removeMeta(base);
  283.  
  284.   let diff = new JitDiff(base, updatedData);
  285.   // console.log('diff', diff);
  286.  
  287.   if (diff.didChange()) {
  288.     JitDocument.setMeta(updatedData, $jsonitMeta);
  289.     let cs = new JitCommits(JitDocument.getCommits(updatedData));
  290.     cs.addCommit(diff, COMMIT_MESSAGE, new Date(), config.jit.username);
  291.     let commits = cs.getAllCommits();
  292.     let commitsId = commits[commits.length - 2].commitId;
  293.     return client.push(config.statsData.localBranch, config.jit.username,
  294.       config.statsData.branch, documentId, [commits[commits.length - 1]], commitsId
  295.     );
  296.   } else {
  297.     return base;
  298.   }
  299.  
  300. };
  301.  
  302.  
  303. // if ( !moment( new Date() ).isBetween(holidays.holidayStartDate,holidays.holidayEndDate,null,[]) ) {
  304. if (argv.user && argv.pass && argv.email) {
  305.   module.exports.handler({}, {}, function (err, data) {
  306.     console.log(err);
  307.     console.log(data);
  308.   });
  309. } else {
  310.   console.log('Please give username, password and email as an argument i.e. --user=? --pass=? --email=?');
  311. }
  312. // }
Add Comment
Please, Sign In to add comment