FinanceHelper.js

var DateUtility = require('../../lib/modules/DateUtility');

function getFinanceByDateRange(DB, req, res) {
    var matches = [];
        
    function done(err, doc) {   
        if (doc != null) {
            matches.push(doc)
        } else {
            res.json({"message": "show me the money", "documents": matches});
        }
    }
    
    var username = req.decoded.username;
    var start    = new Date(req.body.start).getTime();
    var end      = new Date(req.body.end).getTime();
    var query = {
        'user.username': username,
        'timestamp': {
            '$gte': start,
            '$lte': end
        },
        'type': 'MNEY'
    };

    DB.TemplateClln.find(query, { _id: 0, data: 1, timestamp: 1}).each(done);
}

function getFinanceWidgetData(DB, req, res) {
    var start    = req.body.startTimestamp;
    var end      = req.body.endTimestamp;
    var username = req.decoded.username;

    var query = {
        'user.username': username,
        'timestamp': {
            '$gte': start,
            '$lte': end
        },
        'type': 'MNEY'
    };

    DB.TemplateClln.find(query).toArray(function (err, items) {
        if (err) {
            console.error(err);
        } else {
            var amount_day = 0, amount_month = 0, count = 0;
            var list_day_count = 0, list_month_count = 0;
            for(var index in items) {
                var item = items[index];
                for(var jndex in item.data.list) {
                    var jtem = item.data.list[jndex];
                    if(jtem.paidby.taglist.length === 1 && jtem.paidby.text === '' &&
                        jtem.paidby.taglist[0].text.toLowerCase() === 'myself') {
                        count++;
                        if(jtem.amount) {
                            amount_month += parseInt(jtem.amount);
                        }
                        var today = new Date();
                        if(item.timestamp > DateUtility.getDateOnly(today) &&
                            item.timestamp < DateUtility.getDateEnd(today)) {
                            list_day_count++;
                            amount_day += parseInt(jtem.amount);
                        }
                        list_month_count++;
                    }
                }
            }

            res.json({
                success: true,
                count: count,
                result: {
                    myself: {
                        amount_day: amount_day,
                        amount_month: amount_month
                    }
                },
                list: {
                    myself: {
                        list_day_count: list_day_count,
                        list_month_count: list_month_count
                    }
                }
            });
        }
    });
}

module.exports = {
    getFinanceByDateRange,
    getFinanceWidgetData
};