dashboardRoutes.js

var jwt = require("jsonwebtoken");
var async = require("async");
var Hashids = require('hashids');
var ObjectId = require('mongodb').ObjectID;
var dbCollections = require('../../../config/db/dbCollections');
var RepetitionHelper = require('../../../components/dashboard/helper/RepetitionHelper');
var NotesHelper = require('../../../components/notes/NotesHelper');
var FinanceHelper = require('../../../components/finance/FinanceHelper');

function dashboardRoutes(app, routeOptions) {
    // List of collections available
    var DB = dbCollections(routeOptions.database);
    var hashids = new Hashids('I am smart');

    app.post('/api/inputbox/notes/getdata', function (req, res) {
        // RETURN ALL DATA FOR CURRENT MONTH
        NotesHelper.getNotesByDateRange(DB, req, res);
    });

    // Submit inputbox data
    app.post('/api/inputbox/submit', function(req, res) {
        console.log(req.body);
        // Note: info can be an object or an array of objects
        var rawtemplates = req.body.templates;
        var newtemplates = [];
        for(var index in rawtemplates) {
            var template = rawtemplates[index];
            // SECURITY SETTING: Save user info while saving data
            template.user = { username: req.decoded.username };
            newtemplates.push(template);
        }

        if(DB && newtemplates.length > 0) {
            console.log('inserting into db');
            DB.TemplateClln.insert(newtemplates, function (err, data) {
                if (err) {
                    console.error(err);
                } else {
                    res.json({
                        success: true
                    });
                }
            });
        }
    });

    // Mark/Unmark habit template
    app.post('/api/inputbox/habit/mark', function(req, res) {
        console.log(req.body);
        var id = hashids.decodeHex(req.body.hashid);
        var isChecked = req.body.isChecked;

        // Convert id to mongodb object id
        DB.TemplateClln.update({'_id': ObjectId(id)}, {$set: {'data.isChecked': isChecked} },
            function(err, result) {
                if(err) {
                    console.error(err);
                }
                else {
                    res.json({
                        success: true,
                        result: result
                    });
                }
            });
    });

    app.post('/api/inputbox/finance/getdata', function (req, res) {
        // RETURN ALL DATA FOR CURRENT YEAR
        FinanceHelper.getFinanceByDateRange(DB, req, res);
    });

    app.post('/api/inputbox/finance/widget/getdata', function (req, res) {
        // Get start and end date based on local timestamp from client
        FinanceHelper.getFinanceWidgetData(DB, req, res);
    });

    // Get inputbox templates
    app.post('/api/inputbox/gettemplates', function(req, res) {
        console.log(req.body);

        // Get start and end date based on local timestamp from client
        var start = req.body.startTimestamp;
        var end   = req.body.endTimestamp;

        var username = req.decoded.username;
        var templates = [];

        console.log(start + ', ' + end);

        var tasks = [];
        var params = {'username': username, 'repetitions': [] };
        /*tasks.push(function (callback) {
            // Create repetition based templates till date
            RepetitionHelper.createRepetitionTemplates(DB, params, callback);
        });*/

        tasks.push(function (callback) {
            var query = [
                {
                    $match: {
                        'user.username': username,
                        'timestamp': {
                            '$gte': start,
                            '$lte': end
                        }
                    }
                },
                {
                    $project: {
                        _id: 0,
                        document: "$$ROOT"
                    }
                }
            ];

            if(DB) {
                console.log('Getting templates for date: ' + req.body.date);
                console.log(JSON.stringify(query));
                DB.TemplateClln.aggregate(query).each(done);
            }

            function done(err, result) {
                if (result !== null) {
                    // Generate hashid for habit and calendar templates
                    if(result.document.type && result.document.data &&
                        (result.document.type === 'HABT' || result.document.type === 'CLDR')) {
                            // UNDO
                            // Disabling habit and calendar
                            return;
                        //result.document.data.hashid = hashids.encodeHex(result.document._id);
                    }
                    delete result.document._id;
                    delete result.document.user;
                    delete result.document.parentid;
                    templates.push(result.document);
                } else {
                    callback();
                }
            }
        });

        async.series(tasks, function(){
            console.log('Number of templates returned:' + templates.length);
            console.log('Number of repetitions returned:' + params.repetitions.length);
            res.json({
                data: {
                    templates: templates,
                    repetitions: params.repetitions
                }
            });
        });
    });

}

module.exports = dashboardRoutes;