let moment = require('moment')

module.exports = {


    friendlyName: 'Count',


    description: 'Count Product sale.',


    inputs: {
        startDate: {
            type: 'string'
        },
        endDate: {
            type: 'string'
        },

    },


    exits: {
        notFound: {
            statusCode: 404
          },

    },


    fn: async function ({startDate, endDate,}, exits) {

        let id = this.req.token.id

        let user = await User.findOne(id)
        if (!user) {
            throw { notFound: { message: 'user non retrouve !' } }
        }

        let userinfo = await UserInfo.find({ username: user.username }).then(_.first)
        if (!userinfo) {
            throw { notFound: { message: `L\'utilisateur ${user.username} n'appartient actuellement à aucune agence, veuillez l\'affecter dans une agence` } }

        }

        let agences = userinfo.agence

        //console.log("AGENCE", agencesPrincipal, user.groupe, agences)

        let dateEnCours = moment(new Date(), 'DD/MM/YYYY').format('YYYY-MM-DD')

        // let factures;
        let listeArticlesSelected;

            let total = 0;
            listeArticlesSelected = await FactureDetails.find({ codAgence: agences, dateFact: {'>=':startDate,'<=':endDate} })
                .then(listeArticlesSelected => {
                    return Promise.all(listeArticlesSelected.map(async details => {

                        if (details.qtCommander && details.qtCommander !== null) {
                            total = total + parseInt(details.qtCommander)
                        }

                        return total

                    }))

                })
            return exits.success(total);

    }


};
