Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- /**
- * @author Copyright RIKSOF (Private) Limited.
- */
- const Promise = require('bluebird');
- const nodeMailer = require('nodemailer');
- const ejs = require('ejs');
- const Email = require('./Email.js');
- const argv = require('minimist')(process.argv.slice(2));
- const JitDocument = require('jit/client').JitDocument;
- const JitDiff = require('jit/client').JitDiff;
- const JitCommits = require('jit/client').JitCommits;
- const JitClient = require('jit/client').JitClient;
- const JitMerge = require('jit/client').JitMerge;
- const moment = require('moment');
- const holidays = require('./../holidays.js');
- const termDuration = '06-11-00-05';
- const runDate = new Date(moment().subtract(0, 'days').format('YYYY-MM-DD'));
- const session = '2017-2018';
- var startDateFT = new Date(moment([session.split('-')[0], termDuration.split('-')[0]]).startOf('month'));
- var endDateFT = new Date(moment([session.split('-')[0], termDuration.split('-')[1]]).endOf('month'));
- var startDateST = new Date(moment([session.split('-')[1], termDuration.split('-')[2], 9]).startOf('day'));
- var endDateST = new Date(moment([session.split('-')[1], termDuration.split('-')[3]]).endOf('month'));
- var htmlString = '';
- var From = '\"KGS\" regcs.sec@kgs.edu.pk';
- var To = argv.email.split(',');
- var subject = 'Late attendance count exceeds to three';
- var isHtml = true;
- var house = {};
- var lastMsgGenerated = 0;
- var emailList = [];
- let parentEmailList = [];
- house['F'] = Array(11);
- house['S'] = Array(11);
- house['N'] = Array(11);
- house['P'] = Array(11);
- const config = {
- jit: {
- url: 'http://localhost:3000',
- username: 'kgs-s2a-io',
- password: 'ZMF[R-tA-j6U$FzH',
- token: 'AXAoUM4TYGscwFzak5PcHMdAQhaZKTCZ'
- },
- email: {
- service: 'SES',
- host: 'email-smtp.us-east-1.amazonaws.com',
- port: 465,
- user: argv.user,
- password: argv.pass
- },
- statsData: {
- branch: 'kgs.s2a.io-Data-student-attendance-stats',
- localBranch: ''
- },
- data: {
- branch: 'kgs.s2a.io-Data-student-personal-information',
- localBranch: '',
- session: session
- }
- }
- const COMMIT_MESSAGE = 'Send email to parents through lambda.';
- const DELAY_AFTER_CONNECTION_ERROR = 10000;
- /**
- * This function is the entry point for send-email.kgs.s2a.io serverless function.
- *
- * @param {any} data Data passed to this function.
- * @param {any} context Client context. Unused.
- * @param {function} callback Callback function to pass back
- * the response.
- *
- * @returns {undefined} None.
- */
- module.exports.handler = function SendEmailHandler(data, context, callback) {
- let client = new JitClient(config.jit.url, config.jit.username,
- config.jit.password);
- for (let key in house) {
- for (let i = 0; i < house[key].length; i++) {
- house[key][i] = key + (i + 1);
- }
- }
- var projections = {
- "map": {
- "keys": [],
- "values": [
- "studentId",
- "parentEmail",
- "freezeStatus"
- ]
- },
- "reduce": {
- "studentId": "current.studentId",
- "parentEmail": "current.parentEmail",
- "freezeStatus": "current.freezeStatus"
- }
- };
- // Connect to the server.
- for (let key in house) {
- let houseGroupDate = {};
- let doc = JitDocument.init({});
- let doc1 = JitDocument.init({});
- let JIT_SEARCH_REFERENCE = 'ref-send-email.kgs.s2a.io-' + house[key] + '-' + runDate;
- JitDocument.setId(doc, JIT_SEARCH_REFERENCE);
- JitDocument.setId(doc1, JIT_SEARCH_REFERENCE);
- let query = {};
- let query1 = {
- studentClass: {
- $in: house[key]
- }
- };
- let students = [];
- connect(client).then(function AfterConnect() {
- return client.search(config.jit.username, config.data.branch,
- JIT_SEARCH_REFERENCE, query1, 0, projections);
- }).then(function AfterStudentInfoSearch(commits) {
- // Save all commits in search results.
- for (let a = 0; a < commits.length; a++) {
- doc1 = JitMerge.merge(doc1, [commits[a].diff]);
- }
- if (doc1.data.length > 0) {
- // console.log("doc1",doc1.data);
- for (let b = 0; b < doc1.data.length; b++) {
- if(doc1.data[b].freezeStatus == "Yes"){
- students.push(doc1.data[b].studentId);
- }
- // else{
- // parentEmailList.push({id : doc1.data[b].studentId , pEmail : doc1.data[b].parentEmail ? doc1.data[b].parentEmail :"no email" });
- // }
- }
- }
- return doc1.data;
- }).then(function StudentStatsSearch() {
- query = {
- studentClass: {
- $in: house[key]
- },
- studentId: {
- $not: {
- $in: students
- }
- }
- };
- return client.search(config.jit.username, config.statsData.branch,
- JIT_SEARCH_REFERENCE, query, 0, null, {
- studentClass: 1,
- secondTermLate: 1
- });
- }).then(function AfterStudentStatsSearch(commits) {
- // Save all commits in search results.
- for (let a = 0; a < commits.length; a++) {
- doc = JitMerge.merge(doc, [commits[a].diff]);
- }
- if (doc.data.length > 0) {
- let p = new Promise.resolve(true);
- let sendEmail = false;
- // console.log(' parentEmailList', parentEmailList);
- for (let k = 0; k < doc.data.length; k++) {
- let base = JSON.parse(JSON.stringify(doc.data[k]));
- let studentDetails = {};
- if (moment(runDate).isBetween(startDateFT, endDateFT, null, []) && doc.data[k].firstTermLate % 3 == 0 && doc.data[k].firstTermLate != 0) {
- // if (doc.data[k].lastMsgGenerated != doc.data[k].firstTermLate) {
- sendEmail = true;
- studentDetails = {
- studentId: doc.data[k].studentId,
- studentName: doc.data[k].studentName,
- studentClass: doc.data[k].studentClass,
- className: doc.data[k].className,
- days: doc.data[k].firstTermlate,
- parentEmail: doc1.data[k].parentEmail ? doc1.data[k].parentEmail :"z@gmail.com"
- };
- if(studentDetails.parentEmail != null){
- To = studentDetails.parentEmail ;
- }
- console.log("to in first term",studentDetails.parentEmail);
- ejs.renderFile(__dirname + '/template.ejs', {
- studentDetails: studentDetails,
- now: moment().format('DD-MMM-YYYY')
- }, function (err, str) {
- if (err) {
- console.log(err);
- } else {
- var email = new Email(config.email.service, config.email.host, config.email.port, config.email.user, config.email.password);
- email.send(From, To, subject, str, isHtml);
- }
- });
- doc.data[k].lastMsgGenerated = doc.data[k].firstTermLate;
- p = p.then(function AfterPush() {
- return update(base, doc.data[k], client);
- }).catch(function OnPushError(e) {
- console.error(e);
- return doc.data[k];
- })
- // }
- } else if (moment(runDate).isBetween(startDateST, endDateST, null, []) && doc.data[k].secondTermLate % 3 == 0 && doc.data[k].secondTermLate != 0) {
- // if (doc.data[k].lastMsgGenerated != doc.data[k].secondTermLate) {
- sendEmail = true;
- studentDetails = {
- studentId: doc.data[k].studentId,
- studentName: doc.data[k].studentName,
- studentClass: doc.data[k].studentClass,
- className: doc.data[k].className,
- days: doc.data[k].secondTermLate,
- parentEmail:doc1.data[k].parentEmail ? doc1.data[k].parentEmail :"y@gmail.com"
- };
- if(studentDetails.parentEmail != null){
- To = studentDetails.parentEmail ;
- }
- console.log("to in 2nd term",studentDetails.parentEmail);
- ejs.renderFile(__dirname + '/template.ejs', {studentDetails: studentDetails,now: moment().format('DD-MMM-YYYY')}, function (err, str) {
- if (err) {
- console.log(err);
- } else {
- var email = new Email(config.email.service, config.email.host, config.email.port, config.email.user, config.email.password);
- email.send(From, To, subject, str, isHtml);
- }
- });
- doc.data[k].lastMsgGenerated = doc.data[k].secondTermLate;
- p = p.then(function AfterPush() {
- return update(base, doc.data[k], client);
- }).catch(function OnPushError(e) {
- console.error(e);
- return doc.data[k];
- })
- // }
- } else {
- sendEmail = false;
- }
- }
- }
- return doc.data;
- }).then(function AfterSaveData(d) {
- // Returns OK if all data read and pushed successfully
- callback(null, {
- House: house[key],
- emailStatus: 'sent'
- });
- }).catch(function OnError(err) {
- console.error(err);
- // Returns FAIL if there is error
- callback(err);
- });
- }
- };
- /**
- * Setup connection.
- *
- * @param {JitClient} client Client to use to connect.
- *
- * @returns {Promise} p Once connection is established.
- */
- function connect(client) {
- return client.reconnect(config.jit.username, config.jit.token, '', 0)
- .then(function SuccessOnConnection() {
- return true;
- }).catch(function OnConnectionError(e) {
- console.error(e);
- return Promise.delay(DELAY_AFTER_CONNECTION_ERROR)
- .then(function AfterDelay() {
- return connect(client);
- });
- });
- }
- function update(base, data, client) {
- // Set values to the doc.
- let updatedData = data;
- //console.log('base', base);
- //console.log('updatedData', updatedData);
- let documentId = JitDocument.getId(updatedData);
- var $jsonitMeta = JitDocument.removeMeta(updatedData);
- JitDocument.removeMeta(base);
- let diff = new JitDiff(base, updatedData);
- // console.log('diff', diff);
- if (diff.didChange()) {
- JitDocument.setMeta(updatedData, $jsonitMeta);
- let cs = new JitCommits(JitDocument.getCommits(updatedData));
- cs.addCommit(diff, COMMIT_MESSAGE, new Date(), config.jit.username);
- let commits = cs.getAllCommits();
- let commitsId = commits[commits.length - 2].commitId;
- return client.push(config.statsData.localBranch, config.jit.username,
- config.statsData.branch, documentId, [commits[commits.length - 1]], commitsId
- );
- } else {
- return base;
- }
- };
- // if ( !moment( new Date() ).isBetween(holidays.holidayStartDate,holidays.holidayEndDate,null,[]) ) {
- if (argv.user && argv.pass && argv.email) {
- module.exports.handler({}, {}, function (err, data) {
- console.log(err);
- console.log(data);
- });
- } else {
- console.log('Please give username, password and email as an argument i.e. --user=? --pass=? --email=?');
- }
- // }
Add Comment
Please, Sign In to add comment