financeQueryHelper.js

/**
 * Created by WORKER on 01-09-2015.
 */
var async = require('async')
var processSnippets = require('./processSnippets')

/**
 * Construct query for each type of finance module.
 * @param  {Objecct} options Input parameters
 * @param  {Objecct} result  Stores the result after processing
 */
var financeQuery = function (options, result) {
  var DB = options.DB

  var asyncTasks = []

  var queries = {
    SPNT: [],
    RCVD: [],
    BRWD: [],
    LENT: []
  }

  for (var query in queries) {
    /* This code has to be within closure to create array result[query] correctly */
    // find the sum of this query using IIFE
    ;(function (queries, query) {
      /* Build aggregation query */
      queries[query].push({
        $unwind: '$fields'
      })
      queries[query].push({
        $match: { templateCode: query }
      })
      queries[query].push({
        // include all these fields in query result
        $project: {
          _id: 0,
          amount: '$fields.amount'
        }
      })

      asyncTasks.push(function (_callback) {
        function onComplete(err, snippets) {
          processSnippets(query, snippets, result)
          _callback()
        }
        // Execute query
        DB.TemplateClln.aggregate(queries[query], onComplete)
      })
    })(queries, query)
  }

  // calculate the total for the year
  async.parallel(asyncTasks, function () {
    console.log(result)
    options._callback()
  })
}

module.exports = financeQuery