
"use strict";

const
  Promise = require('bluebird'),
  moment  = require('moment');

const getUsersWithLeaves = ({
  company,
  startDate=company.get_today(),
  endDate=company.get_today(),
  departmentId=null

}) => {

  let result = company.sequelize.models.Company.scope('with_active_users').findOne({
    where : {id : company.id},
  });

  result = result.then(company => Promise.resolve(company.users));

  if (departmentId) {
    result = result.then(users => Promise.resolve(users.filter(u => String(u.DepartmentId) === String(departmentId))));
  }

  result = result.then(users => Promise.map(users, user => user.reload_with_leave_details({}), { concurrency : 10}));

  result = result.then(
    users => Promise.map(
      users,
      (user) => user.promise_my_active_leaves_ever()
        .then(leaves => Promise.resolve({user, leaves})),
      { concurrency : 10 }
    )
  );

  result = result.then(report => report.map(
    ({user, leaves}) =>
    ({
      user:{
        id:user.id,
        department: user.department.name,
        email:user.email,
        fullName:user.full_name(),
      },
      leaves : leaves.map(l => leaveIntoObject(l)),
    })
  ));

  return result;
};

const leaveIntoObject = (leave) => {

  const dateFormat = 'YYYY-MM-DD';

  const Leave = leave.sequelize.models.Leave;

  const statusMap = {
    [Leave.status_new()]:           'New',
    [Leave.status_approved()]:      'Approved',
    [Leave.status_rejected()]:      'Rejected',
    [Leave.status_pended_revoke()]: 'Pended Revoke',
    [Leave.status_canceled()]:      'Canceled',
  };

  return {
    startDate:    moment.utc(leave.get_start_leave_day().date).format(dateFormat),
    endDate:      moment.utc(leave.get_end_leave_day().date).format(dateFormat),
    type:         leave.leave_type.name,
    deductedDays: leave.get_deducted_days_number(),
    approver:     (leave.approver ? leave.approver.full_name() : 'N/A'),
    status:       statusMap[leave.status]||'Unknown',
  };
};


module.exports = {
  getUsersWithLeaves
};

@@ -668,24 +668,78 @@
 y : 10%7D));%0A%0A
+  const filter = filterLeaves(%7BstartDate, endDate%7D);%0A%0A
   result = r
@@ -750,16 +750,16 @@
 t.then(%0A
-
     user
@@ -842,16 +842,80 @@
 _ever()%0A
+        .then(leaves =%3E Promise.resolve(leaves.filter(filter)))%0A
         
@@ -1286,24 +1286,24 @@
   %7D)%0A  ));%0A%0A
-
   return res
@@ -1311,16 +1311,374 @@
 lt;%0A%7D;%0A%0A
+const filterLeaves = (%7BstartDate, endDate%7D) =%3E (leave) =%3E %7B%0A  const sd = moment.utc(leave.get_start_leave_day().date);%0A  const ed = moment.utc(leave.get_end_leave_day().date)%0A  return (%0A    (sd.isSameOrAfter(startDate, 'day') && sd.isSameOrBefore(endDate, 'day'))%0A    %7C%7C%0A    (ed.isSameOrAfter(startDate, 'day') && ed.isSameOrBefore(endDate, 'day'))%0A  );%0A%7D;%0A%0A
 const le

Add filtering by date