"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Reports = void 0;
const RawView_1 = require("../lib/view/RawView");
const Session_1 = require("../lib/model/Session");
const _406_1 = require("../lib/view/406");
const MongoDB_1 = require("../lib/model/MongoDB");
const Graph_1 = require("../lib/view/Graph");
const RawQuery_1 = require("../lib/model/RawQuery");
class Reports {
    constructor() { }
    /**
     * To get the dashboard reports for (Admin + Customer + Sub-Customer)
     */
    BasicReports(req, res, next) {
        let sdata = req.query;
        let iduserOrIdaccount = parseInt(sdata.idaccountuser);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let cur_month = (new Date().getMonth() + 1);
                let cur_year = (new Date().getFullYear());
                let Rcondition = {};
                let mdb = new MongoDB_1.MongoDB();
                let query;
                let selection;
                selection = { "$project": { "year": { "$year": { "$dateFromString": { "dateString": "$date", "format": "%Y-%m-%d" } } }, "monthnum": 1, "idaccount": 1, "date": 1, "direction": 1, "unixtime": 1, "cost": 1, "iduser": 1, "duration": 1, "completed": 1, "rejected": 1, "failed": 1, "sec10": 1, "sec20": 1, "sec30": 1, "sec60": 1, "sec120": 1, "sec180": 1, "sec300": 1, "sec600": 1, "sec900": 1, "secmax": 1, "failure": 1, "busy": 1, "noanswer": 1, "conjestion": 1 } };
                let selectionusage;
                selectionusage = { "$project": { "year": { "$year": { "$dateFromString": { "dateString": "$date", "format": "%Y-%m-%d" } } }, "monthnum": 1, "idaccount": 1, "date": 1,
                        "direction": 1, "unixtime": 1, "cost": 1, "iduser": 1, "duration": 1 } };
                switch (sdata.type) {
                    case "usage": {
                        console.log("case 1");
                        if (sessdata.type == 2) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "iduser": user, "year": cur_year, "monthnum": cur_month };
                            }
                        }
                        else if (sessdata.type == 1) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "year": cur_year, "monthnum": cur_month };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month };
                            }
                        }
                        else {
                            Rcondition = { "iduser": iduserOrIdaccount, "year": cur_year, "monthnum": cur_month };
                        }
                        query = [selectionusage, { "$match": Rcondition }, { "$project": { "inbound": { "$cond": [{ "$eq": ["$direction", "inbound"] }, "$cost", 0] }, "outbound": { "$cond": [{ "$eq": ["$direction", "outbound"] }, "$cost", 0] } } }, { "$group": { "_id": 0, "outbound": { "$sum": "$outbound" }, "inbound": { "$sum": "$inbound" } } }, { "$project": { "Outbound Usage": "$outbound", "Inbound Usage": "$inbound" } }];
                        break;
                    }
                    case "outbound": {
                        console.log("case 2");
                        if (sessdata.type == 2) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month, "direction": "outbound" };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "iduser": user, "year": cur_year, "monthnum": cur_month, "direction": "outbound" };
                            }
                        }
                        else if (sessdata.type == 1) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "year": cur_year, "monthnum": cur_month, "direction": "outbound" };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "year": cur_year, "idaccount": user, "monthnum": cur_month, "direction": "outbound" };
                            }
                        }
                        else {
                            Rcondition = { "iduser": iduserOrIdaccount, "year": cur_year, "monthnum": cur_month, "direction": "outbound" };
                        }
                        if (sdata.tab == "voice") {
                            query = [selection, { "$match": Rcondition }, { "$group": { "_id": { "date": { "$dateToString": { "format": "%Y-%m", "date": { "$toDate": "$date" } } } }, "calls": { "$sum": { "$add": ["$sec10", "$sec20", "$sec30", "$sec60", "$sec120", "$sec180", "$sec300", "$sec600", "$sec900", "$secmax"] } }, "failure": { "$sum": "$failure" }, "busy": { "$sum": "$busy" }, "noanswer": { "$sum": "$noanswer" }, "conjestion": { "$sum": "$conjestion" } } }, { "$project": { "Conjestion": "$conjestion", "Connected": "$calls", "Busy": "$busy", "No-Answer": "$noanswer", "Other Failure": "$failure" } }];
                        }
                        else if (sdata.tab == "msg") {
                            query = [selection, { "$match": Rcondition },
                                { "$project": { "date": "$date", "completed": { "$toInt": "$completed" }, "rejected": { "$toInt": "$rejected" }, "failed": { "$toInt": "$failed" } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": "%Y-%m", "date": { "$toDate": "$date" } } } }, "completed": { "$sum": "$completed" }, "failed": { "$sum": "$failed" }, "rejected": { "$sum": "$rejected" } } }, { "$project": { "Completed": "$completed", "Failed": "$failed", "Rejected": "$rejected" } }];
                        }
                        break;
                    }
                    case "inbound": {
                        console.log("case 3");
                        if (sessdata.type == 2) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month, "direction": "inbound" };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "iduser": user, "year": cur_year, "monthnum": cur_month, "direction": "inbound" };
                            }
                        }
                        else if (sessdata.type == 1) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "year": cur_year, "monthnum": cur_month, "direction": "inbound" };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month, "direction": "inbound" };
                            }
                        }
                        else {
                            Rcondition = { "iduser": iduserOrIdaccount, "year": cur_year, "monthnum": cur_month, "direction": "inbound" };
                        }
                        if (sdata.tab == "voice") {
                            query = [selection, { "$match": Rcondition }, { "$group": { "_id": { "date": { "$dateToString": { "format": "%Y-%m", "date": { "$toDate": "$date" } } } }, "calls": { "$sum": { "$add": ["$sec10", "$sec20", "$sec30", "$sec60", "$sec120", "$sec180", "$sec300", "$sec600", "$sec900", "$secmax"] } }, "failure": { "$sum": "$failure" }, "busy": { "$sum": "$busy" }, "noanswer": { "$sum": "$noanswer" }, "conjestion": { "$sum": "$conjestion" } } }, { "$project": { "Conjestion": "$conjestion", "Connected": "$calls", "Busy": "$busy", "No-Answer": "$noanswer", "Other Failure": "$failure" } }];
                        }
                        else if (sdata.tab == "msg") {
                            query = [selection, { "$match": Rcondition }, { "$project": { "date": "$date", "completed": { "$toInt": "$completed" }, "rejected": { "$toInt": "$rejected" }, "failed": { "$toInt": "$failed" } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": "%Y-%m", "date": { "$toDate": "$date" } } } }, "completed": { "$sum": "$completed" }, "failed": { "$sum": "$failed" }, "rejected": { "$sum": "$rejected" } } }, { "$project": { "Completed": "$completed", "Failed": "$failed", "Rejected": "$rejected" } }];
                        }
                        break;
                    }
                    case "udaily": {
                        console.log("case 4");
                        if (sessdata.type == 2) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "iduser": user, "year": cur_year, "monthnum": cur_month };
                            }
                        }
                        else if (sessdata.type == 1) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "year": cur_year, "monthnum": cur_month };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month };
                            }
                        }
                        else {
                            Rcondition = { "iduser": iduserOrIdaccount, "year": cur_year, "monthnum": cur_month };
                        }
                        query = [selection, { "$match": Rcondition }, { "$project": { "unixtime": { "$toLong": "$unixtime" }, "inbound": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "inbound"] }, "$cost", 0] } }, "outbound": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "outbound"] }, "$cost", 0] } } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": "%Y-%m-%d", "date": { "$toDate": "$unixtime" } } } }, "outbound": { "$sum": "$outbound" }, "inbound": { "$sum": "$inbound" } } }, { "$project": { "Outbound Usage": "$outbound", "Inbound Usage": "$inbound" } }, { "$sort": { "date": 1 } }];
                        break;
                    }
                    case "daily": {
                        console.log("case 5");
                        if (sessdata.type == 2) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "iduser": user, "year": cur_year, "monthnum": cur_month };
                            }
                        }
                        else if (sessdata.type == 1) {
                            let user;
                            if (iduserOrIdaccount == '0') {
                                user = sessdata.idaccount;
                                Rcondition = { "year": cur_year, "monthnum": cur_month };
                            }
                            else {
                                user = iduserOrIdaccount;
                                Rcondition = { "idaccount": user, "year": cur_year, "monthnum": cur_month };
                            }
                        }
                        else {
                            Rcondition = { "iduser": iduserOrIdaccount, "year": cur_year, "monthnum": cur_month };
                        }
                        if (sdata.tab == "voice") {
                            query = [selection, { "$match": Rcondition }, { "$project": { "unixtime": { "$toLong": "$unixtime" }, "ibdmin": { "$cond": [{ "$eq": ['$direction', "inbound"] }, '$duration', 0] }, "obdmin": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "inbound"] }, "$completed", 0] } }, "ibdusage": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "inbound"] }, "$cost", 0] } }, "obdusage": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "outbound"] }, "$cost", 0] } } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": "$unixtime" } } } }, "ibdmin": { "$sum": "$ibdmin" }, "obdmin": { "$sum": "$obdmin" }, "ibdusage": { "$sum": "$ibdusage" }, "obdusage": { "$sum": "$obdusage" } } }, { "$project": { "Date": "$_id.date", "Inbound Minutes": "$ibdmin", "Outbound Minutes": "$obdmin", "Inbound Usage": "$ibdusage", "Outbound Usage": "$obdusage" } }, { "$sort": { "Date": 1 } }];
                        }
                        else if (sdata.tab == "msg") {
                            query = [selection, { "$match": Rcondition },
                                { "$project": { "unixtime": { "$toLong": "$unixtime" }, "ibdsms": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "inbound"] }, "$completed", 0] } }, "obdsms": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "outbound"] }, "$completed", 0] } }, "ibdusage": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "inbound"] }, "$cost", 0] } }, "obdusage": { "$toDouble": { "$cond": [{ "$eq": ["$direction", "outbound"] }, "$cost", 0] } } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": "%Y-%m-%d", "date": { "$toDate": "$unixtime" } } } }, "ibdsms": { "$sum": "$ibdsms" }, "obdsms": { "$sum": "$obdsms" }, "ibdusage": { "$sum": "$ibdusage" }, "obdusage": { "$sum": "$obdusage" } } }, { "$project": { "Date": "$_id.date", "Inbound SMS": "$ibdsms", "Inbound Usage": "$ibdusage", "Outbound Usage": "$obdusage", "Outbound  SMS": "$obdsms" } }, { "$sort": { "Date": 1 } }];
                        }
                        break;
                    }
                }
                let dbcol = "";
                if (sdata.tab == "msg")
                    dbcol = "mdr";
                if (sdata.tab == "voice")
                    dbcol = "cdr";
                mdb.rawexecute(dbcol, query, (data) => {
                    if (data.status == 401) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare(data);
                        objv.execute();
                    }
                    else {
                        res.status(200).json({
                            count: data.length,
                            reports: data,
                            message: "Reports Fetched successfully !"
                        });
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*public BasicReports(req: Request, res: Response, next: NextFunction) {
        let sdata: any = req.query;
        console.log('sdata =>', sdata);
        let iduserOrIdaccount:any = parseInt(sdata.idaccountuser);
        let session = new SessionManagment(req, res, next);
        session.GetSession((error: any, sessdata: any) => {
            if (error == 1) {
                let userid:any={};
                let mdb = new MongoDB();
                let query: any;
                switch (sdata.type) {
                    case "usage": {
                        console.log("case 1");
                        if (sessdata.type == 2) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"idaccount": sessdata.idaccount,  "monthnum":(new Date().getMonth())+1};
                            } else {
                                userid = {"iduser": iduserOrIdaccount,  "monthnum":(new Date().getMonth())+1};
                            }
                        }
                        else if (sessdata.type == 1) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"monthnum":(new Date().getMonth())+1};
                            } else {
                                userid = {"idaccount": iduserOrIdaccount,  "monthnum":(new Date().getMonth())+1};
                            }
                        }
                        else {
                            userid = {"iduser": iduserOrIdaccount,  "monthnum":(new Date().getMonth()+1)};
                        }
                        query=[{"$match" : userid}, {"$project":{ "inbound": {$cond: [{$eq: ['$direction', "inbound"]}, '$cost', 0]}, "outbound": {$cond: [{$eq: ['$direction', "outbound"]}, '$cost', 0]}}}, {"$group":{ "_id" : 0, "outbound": { "$sum":"$outbound" }, "inbound": { "$sum":"$inbound" } }}, { "$project" : { "Outbound Usage" : "$outbound", "Inbound Usage" : "$inbound"} } ];
                        break;
                    }
                    case "outbound": {
                        console.log("case 2");
                        if (sessdata.type == 2) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"idaccount": sessdata.idaccount, "monthnum":(new Date().getMonth()+1), "direction": "outbound"};
                            } else {
                                userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1), "direction": "outbound"};
                            }
                        }
                        else if (sessdata.type == 1) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"monthnum":(new Date().getMonth())+1, "direction": "outbound"};
                            } else {
                                userid = {"idaccount": iduserOrIdaccount, "monthnum":(new Date().getMonth())+1, "direction": "outbound"};
                            }
                        }
                        else {
                            userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1), "direction": "outbound"};
                        }
                        if(sdata.tab=="voice"){
                            query=[{"$match" : userid},{ "$group" : {"_id" : { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } }}, "calls" : {"$sum": {"$add": ["$sec10", "$sec20", "$sec30", "$sec60", "$sec120", "$sec180","$sec300", "$sec600", "$sec900","$secmax"]}}, "failure" : { "$sum" : "$failure"}, "busy" : { "$sum" : "$busy"}, "noanswer" : { "$sum" : "$noanswer"}, "conjestion":{"$sum" : "$conjestion"}}}, { "$project" : { "Conjestion" : "$conjestion", "Connected" : "$calls", "Busy" : "$busy", "No-Answer" : "$noanswer", "Other Failure" : "$failure"} } ];
                        }
                        else if (sdata.tab=="msg"){
                            query=[{"$match" : userid},{ "$group" : {"_id" : { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } }}, "completed" : { "$sum" : "$completed"}, "failed" : { "$sum" : "$failed"}, "rejected" : { "$sum" : "$rejected"}}}, { "$project" : { "Complete" : "$completed", "Failed" : "$failed", "Rejected": "$rejected"} } ];
                        }
                        break;
                    }
                    case "inbound": {
                        console.log("case 3");
                        if (sessdata.type == 2) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"idaccount": sessdata.idaccount, "monthnum":(new Date().getMonth()+1), "direction": "inbound"};
                            } else {
                                userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1), "direction": "inbound"};
                            }
                        }
                        else if (sessdata.type == 1) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"monthnum":(new Date().getMonth())+1, "direction": "inbound" };
                            } else {
                                userid = {"idaccount": iduserOrIdaccount, "monthnum":(new Date().getMonth())+1, "direction": "inbound"};
                            }
                        }
                        else {
                            userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1), "direction": "inbound"};
                        }
                        if(sdata.tab=="voice"){
                            query=[{"$match" : userid},{ "$group" : {"_id" : { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } }}, "calls" : { "$sum" : {"$add": ["$sec10", "$sec20", "$sec30", "$sec60", "$sec120", "$sec180","$sec300", "$sec600", "$sec900","$secmax"]}}, "failure" : { "$sum" : "$failure"}, "busy" : { "$sum" : "$busy"}, "noanswer" : { "$sum" : "$noanswer"}, "conjestion":{"$sum" : "$conjestion"}}}, { "$project" : { "Conjestion" : "$conjestion", "Connected" : "$calls", "Busy" : "$busy", "No-Answer" : "$noanswer", "Other Failure" : "$failure"} } ];
                        }
                        else if (sdata.tab=="msg"){
                            query=[{"$match" : userid},{ "$group" : {"_id" : { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } }}, "completed" : { "$sum" : "$completed"}, "failed" : { "$sum" : "$failed"}, "rejected" : { "$sum" : "$rejected"}}}, { "$project" : { "Completed" : "$completed", "Failed" : "$failed", "Rejected": "$rejected"} } ];
                        }
                        break;

                    }
                    case "udaily": {
                        console.log("case 4");
                        if (sessdata.type == 2) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"idaccount": sessdata.idaccount, "monthnum":(new Date().getMonth())+1};
                            } else {
                                userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth())+1};
                            }
                        }
                        else if (sessdata.type == 1) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"monthnum":(new Date().getMonth())+1};
                            } else {
                                userid = {"idaccount": iduserOrIdaccount, "monthnum":(new Date().getMonth())+1};
                            }
                        }
                        else{
                            userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1)};
                        }
                        query=[{"$match" : userid}, {"$project":{ "unixtime": "$unixtime", "inbound": {$cond: [{$eq: ['$direction', "inbound"]}, '$cost', 0]}, "outbound": {$cond: [{$eq: ['$direction', "outbound"]}, '$cost', 0]}}}, {"$group":{ "_id" : { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": "$unixtime" }}}}, "outbound": { "$sum":"$outbound" }, "inbound": { "$sum":"$inbound" } }}, { "$project" : { "Date":"$_id.date", "Outbound Usage" : "$outbound", "Inbound Usage" : "$inbound"} }, {"$sort":{"Date": 1}} ];
                        break;
                    }
                    case "daily": {
                        console.log("case 5");
                        if (sessdata.type == 2) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"idaccount": sessdata.idaccount, "monthnum":(new Date().getMonth()+1)};
                            } else {
                                userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1)};
                            }
                        }
                        else if (sessdata.type == 1) {
                            if (iduserOrIdaccount == '0') {
                                userid = {"monthnum":(new Date().getMonth())+1};
                            } else {
                                userid = {"idaccount": iduserOrIdaccount, "monthnum":(new Date().getMonth())+1};
                            }
                        }
                        else{
                            userid = {"iduser": iduserOrIdaccount, "monthnum":(new Date().getMonth()+1)};
                        }
                        if(sdata.tab=="voice"){
                            query=[{"$match" : userid},{"$project":{ "unixtime": "$unixtime", "ibdmin": {"$cond": [{"$eq": ['$direction', "inbound"]}, '$duration', 0]}, "obdmin": {"$cond": [{"$eq": ['$direction', "outbound"]}, '$duration', 0]}, "ibdusage": {"$cond": [{"$eq": ['$direction', "inbound"]}, '$cost', 0]}, "obdusage": {"$cond": [{"$eq": ['$direction', "outbound"]}, '$cost', 0]} }}, { "$group" : {"_id" : { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": "$unixtime" }}}}, "ibdmin" : { "$sum" : "$ibdmin"}, "obdmin" : { "$sum" : "$obdmin"}, "ibdusage" : { "$sum" : "$ibdusage"}, "obdusage" : { "$sum" : "$obdusage"}}}, { "$project" : {"Date":"$_id.date", "Inbound Minutes" : "$ibdmin", "Outbound Minutes" : "$obdmin", "Inbound Usage" : "$ibdusage", "Outbound Usage" : "$obdusage"}}, {"$sort":{"Date": 1}}];
                        }
                        else if (sdata.tab=="msg"){
                            query=[{"$match" : userid},{"$project":{ "unixtime": "$unixtime", "ibdsms": {"$cond": [{"$eq": ['$direction', "inbound"]}, '$completed', 0]}, "obdsms": {"$cond": [{"$eq": ['$direction', "outbound"]}, "$completed", 0]}, "ibdusage": {"$cond": [{"$eq": ['$direction', "inbound"]}, '$cost', 0]}, "obdusage": {"$cond": [{"$eq": ['$direction', "outbound"]}, '$cost', 0]} }}, { "$group" : {"_id" : { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": '$unixtime' } } }}, "ibdsms" : { "$sum" : "$ibdsms"}, "obdsms" : { "$sum" : "$obdsms"}, "ibdusage" : { "$sum" : "$ibdusage"}, "obdusage" : { "$sum" : "$obdusage"}}}, { "$project" : {"Date":"$_id.date", "Inbound SMS" : "$ibdsms", "Inbound Usage" : "$ibdusage", "Outbound Usage":"$obdusage", "Outbound SMS":"$obdsms"} }, {"$sort":{"Date": 1}} ];
                        }
                        break;
                    }
                }
                let dbcol="";
                if(sdata.tab=="msg")
                    dbcol="mdr";
                if(sdata.tab=="voice")
                    dbcol="cdr";
                mdb.rawexecute(dbcol, query, (data:any)=>{
                    res.status(200).json({
                        count: data.length,
                        reports: data,
                        message: "Reports Fetched successfully!"
                    });
                });
            }
            else {
                let objv = new Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    */
    // public BasicReports(req: Request, res: Response, next: NextFunction) {
    //     let sdata: any = req.query;
    //     console.log('sdata =>', sdata);
    //     let iduserOrIdaccount = sdata.idaccountuser;
    //     let session = new SessionManagment(req, res, next);
    //     session.GetSession((error: any, sessdata: any) => {
    //         if (error == 1) {
    //             let Rcondition: any = {};
    //             let mdb = new MongoDB();
    //             let query: any;
    //             switch (sdata.type) {
    //                 case "usage": {
    //                     if (sessdata.type == 2) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "iduser": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         }
    //                     }
    //                     else if (sessdata.type == 1) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "monthnum": (new Date().getMonth()) + 1 };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         }
    //                     }
    //                     else {
    //                         
    //                         Rcondition = { "iduser": iduserOrIdaccount, "monthnum": (new Date().getMonth() + 1) };
    //                     }
    //                     query = [{ "$match": Rcondition }, { "$project": { "inbound": { $cond: [{ $eq: ['$direction', "inbound"] }, '$cost', 0] }, "outbound": { $cond: [{ $eq: ['$direction', "outbound"] }, '$cost', 0] } } }, { "$group": { "_id": 0, "outbound": { "$sum": "$outbound" }, "inbound": { "$sum": "$inbound" } } }, { "$project": { "Outbound Usage": "$outbound", "Inbound Usage": "$inbound" } }];
    //                     break;
    //                 }
    //                 case "outbound": {
    //                     if (sessdata.type == 2) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth() + 1), "direction": "outbound" };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "iduser": user, "monthnum": (new Date().getMonth() + 1), "direction": "outbound" };
    //                         }
    //                     }
    //                     else if (sessdata.type == 1) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "monthnum": (new Date().getMonth()) + 1, "direction": "outbound" };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1, "direction": "outbound" };
    //                         }
    //                     }
    //                     else {
    //                         Rcondition = { "iduser": iduserOrIdaccount, "monthnum": (new Date().getMonth() + 1), "direction": "outbound" };
    //                     }
    //                     if (sdata.tab == "voice") {
    //                         query = [{ "$match": Rcondition }, { "$group": { "_id": { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } } }, "calls": { "$sum": { "$add": ["$sec10", "$sec20", "$sec30", "$sec60", "$sec120", "$sec180", "$sec300", "$sec600", "$sec900", "$secmax"] } }, "failure": { "$sum": "$failure" }, "busy": { "$sum": "$busy" }, "noanswer": { "$sum": "$noanswer" }, "conjestion": { "$sum": "$conjestion" } } }, { "$project": { "Conjestion": "$conjestion", "Connected": "$calls", "Busy": "$busy", "No-Answer": "$noanswer", "Other Failure": "$failure" } }];
    //                     }
    //                     else if (sdata.tab == "msg") {
    //                         query = [{ "$match": Rcondition }, { "$group": { "_id": { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } } }, "completed": { "$sum": "$completed" }, "failed": { "$sum": "$failed" }, "rejected": { "$sum": "$rejected" } } }, { "$project": { "Complete": "$completed", "Failed": "$failed", "Rejected": "$rejected" } }];
    //                     }
    //                     break;
    //                 }
    //                 case "inbound": {
    //                     if (sessdata.type == 2) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth() + 1), "direction": "inbound" };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "iduser": user, "monthnum": (new Date().getMonth() + 1), "direction": "inbound" };
    //                         }
    //                     }
    //                     else if (sessdata.type == 1) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount;                                 
    //                             Rcondition = { "monthnum": (new Date().getMonth()) + 1, "direction": "inbound" };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1, "direction": "inbound" };
    //                         }
    //                     }
    //                     else {
    //                         Rcondition = { "iduser": iduserOrIdaccount, "monthnum": (new Date().getMonth() + 1), "direction": "inbound" };
    //                     }
    //                     if (sdata.tab == "voice") {
    //                         query = [{ "$match": Rcondition }, { "$group": { "_id": { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } } }, "calls": { "$sum": { "$add": ["$sec10", "$sec20", "$sec30", "$sec60", "$sec120", "$sec180", "$sec300", "$sec600", "$sec900", "$secmax"] } }, "failure": { "$sum": "$failure" }, "busy": { "$sum": "$busy" }, "noanswer": { "$sum": "$noanswer" }, "conjestion": { "$sum": "$conjestion" } } }, { "$project": { "Conjestion": "$conjestion", "Connected": "$calls", "Busy": "$busy", "No-Answer": "$noanswer", "Other Failure": "$failure" } }];
    //                     }
    //                     else if (sdata.tab == "msg") {
    //                         query = [{ "$match": Rcondition }, { "$group": { "_id": { date: { $dateToString: { format: '%Y-%m', date: { $toDate: '$date' } } } }, "completed": { "$sum": "$completed" }, "failed": { "$sum": "$failed" }, "rejected": { "$sum": "$rejected" } } }, { "$project": { "Completed": "$completed", "Failed": "$failed", "Rejected": "$rejected" } }];
    //                     }
    //                     break;
    //                 }
    //                 case "udaily": {
    //                     if (sessdata.type == 2) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "iduser": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         }
    //                     }
    //                     else if (sessdata.type == 1) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount;  
    //                             Rcondition = { "monthnum": (new Date().getMonth()) + 1 };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         }
    //                     }
    //                     else{
    //                         Rcondition = { "iduser": iduserOrIdaccount, "monthnum": (new Date().getMonth() + 1) };
    //                     }
    //                     query = [{ "$match": Rcondition }, { "$project": { "unixtime": "$unixtime", "inbound": { $cond: [{ $eq: ['$direction', "inbound"] }, '$cost', 0] }, "outbound": { $cond: [{ $eq: ['$direction', "outbound"] }, '$cost', 0] } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": "$unixtime" } } } }, "outbound": { "$sum": "$outbound" }, "inbound": { "$sum": "$inbound" } } }, { "$project": { "Date": "$_id.date", "Outbound Usage": "$outbound", "Inbound Usage": "$inbound" } }, { "$sort": { "Date": 1 } }];
    //                     break;
    //                 }
    //                 case "daily": {
    //                     if (sessdata.type == 2) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth() + 1) };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "iduser": user, "monthnum": (new Date().getMonth() + 1) };
    //                         }
    //                     }
    //                     else if (sessdata.type == 1) {
    //                         let user: any;
    //                         if (iduserOrIdaccount == '0') {
    //                             user = sessdata.idaccount;  
    //                             Rcondition = { "monthnum": (new Date().getMonth()) + 1 };
    //                         } else {
    //                             user = iduserOrIdaccount; 
    //                             Rcondition = { "idaccount": user, "monthnum": (new Date().getMonth()) + 1 };
    //                         }
    //                     }
    //                     else{
    //                         Rcondition = { "iduser": iduserOrIdaccount, "monthnum": (new Date().getMonth() + 1) };
    //                     }
    //                     if (sdata.tab == "voice") {
    //                         query = [{ "$match": Rcondition }, { "$project": { "unixtime": "$unixtime", "ibdmin": { "$cond": [{ "$eq": ['$direction', "inbound"] }, '$duration', 0] }, "obdmin": { "$cond": [{ "$eq": ['$direction', "outbound"] }, '$duration', 0] }, "ibdusage": { "$cond": [{ "$eq": ['$direction', "inbound"] }, '$cost', 0] }, "obdusage": { "$cond": [{ "$eq": ['$direction', "outbound"] }, '$cost', 0] } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": "$unixtime" } } } }, "ibdmin": { "$sum": "$ibdmin" }, "obdmin": { "$sum": "$obdmin" }, "ibdusage": { "$sum": "$ibdusage" }, "obdusage": { "$sum": "$obdusage" } } }, { "$project": { "Date": "$_id.date", "Inbound Minutes": "$ibdmin", "Outbound Minutes": "$obdmin", "Inbound Usage": "$ibdusage", "Outbound Usage": "$obdusage" } }, { "$sort": { "Date": 1 } }];
    //                     }
    //                     else if (sdata.tab == "msg") {
    //                         query = [{ "$match": Rcondition }, { "$project": { "unixtime": "$unixtime", "ibdsms": { "$cond": [{ "$eq": ['$direction', "inbound"] }, '$completed', 0] }, "obdsms": { "$cond": [{ "$eq": ['$direction', "outbound"] }, "$completed", 0] }, "ibdusage": { "$cond": [{ "$eq": ['$direction', "inbound"] }, '$cost', 0] }, "obdusage": { "$cond": [{ "$eq": ['$direction', "outbound"] }, '$cost', 0] } } }, { "$group": { "_id": { "date": { "$dateToString": { "format": '%Y-%m-%d', "date": { "$toDate": '$unixtime' } } } }, "ibdsms": { "$sum": "$ibdsms" }, "obdsms": { "$sum": "$obdsms" }, "ibdusage": { "$sum": "$ibdusage" }, "obdusage": { "$sum": "$obdusage" } } }, { "$project": { "Date": "$_id.date", "Inbound SMS": "$ibdsms", "Inbound Usage": "$ibdusage", "Outbound Usage": "$obdusage", "Outbound SMS": "$obdsms" } }, { "$sort": { "Date": 1 } }];
    //                     }
    //                     break;
    //                 }
    //             }
    //             let dbcol = "";
    //             if (sdata.tab == "msg")
    //                 dbcol = "mdr";
    //             if (sdata.tab == "voice")
    //                 dbcol = "cdr";
    //             mdb.rawexecute(dbcol, query, (data: any) => {
    //                 res.status(200).json({
    //                     count: data.length,
    //                     reports: data,
    //                     message: "Reports Fetched successfully !"
    //                 });
    //             });
    //         }
    //         else {
    //             let objv = new Res406(res);
    //             objv.prepare(session);
    //             objv.execute();
    //         }
    //     });
    // }
    getLiveWidget(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let mdb = new MongoDB_1.MongoDB();
                let query;
                query = [{ "$match": { "user": sessdata.username } }, { "$group": { "_id": {}, "COUNT(*)": { "$sum": 1 } } }, { "$project": { "total": "$COUNT(*)", "_id": 0 } }];
                mdb.Table = "transfer_call";
                mdb.execute((transfer) => {
                    mdb.Table = "current_call";
                    mdb.execute((calls) => {
                        query = [{ "$match": { "user": sessdata.username } }, { "$group": { "_id": { "campaign": "$campaign" }, "SUM(duration)": { "$sum": "$duration" } } }, { "$project": { "duration": "$SUM(duration)", "campaign": "$_id.campaign", "_id": 0 } }];
                        mdb.Table = "current_call";
                        mdb.execute((minute) => {
                            res.status(200).json({ call: calls, tran: transfer, min: minute });
                        });
                    });
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getLiveCalls(req, res, next) {
        let sdata;
        let tmp = req.query.filter;
        try {
            sdata = JSON.parse(tmp);
        }
        catch {
            sdata = req.query.filter;
        }
        console.log(sdata);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let mdb = new MongoDB_1.MongoDB();
                let query;
                switch (sdata.type) {
                    case "detailed": {
                        query = [{ "user": sessdata.username }, { "user": "$user", "upload": "$upload", "campaign": "$campaign", "server": "$server", "supplier": "$supplier", "state": "$state", "code": "$code", "callstate": "$callstate", "cid_num": "$cid_num", "ipaddr": "$ipaddr", "date": { "$dateToString": { "format": "%Y-%m-%d", "date": { "$toDate": "$connect" } } }, "time": { "$dateToString": { "format": "%H:%M:%S", "date": { "$toDate": "$connect" } } }, "duration": "$duration", "rate": "$rate", "dest": "$dest", "_id": 0 }];
                        mdb.Type = 1;
                        break;
                    }
                    case "minutes": {
                        query = [{ "$match": { "user": sessdata.username } }, { "$group": { "_id": { "campaign": "$campaign" }, "SUM(duration)": { "$sum": "$duration" } } }, { "$project": { "duration": "$SUM(duration)", "campaign": "$_id.campaign", "_id": 0 } }];
                        break;
                    }
                    default: {
                        query = [{ "$match": { "user": sessdata.username } }, { "$group": { "_id": {}, "COUNT(*)": { "$sum": 1 } } }, { "$project": { "total": "$COUNT(*)", "_id": 0 } }];
                        break;
                    }
                }
                console.log(query);
                if (sdata.calltype == "transfer") {
                    mdb.Table = "transfer_call";
                    mdb.execute((data) => {
                        //console.log(data);
                        res.status(200).json(data);
                    });
                }
                else {
                    mdb.Table = "current_call";
                    mdb.execute((data) => {
                        //console.log(data);
                        res.status(200).json(data);
                    });
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    MixedGraph(req, res, next) {
        let sdata;
        let table = typeof req.query.type != 'undefined' && req.query.type ? req.query.type.toString() : "";
        let tmp = req.query.filter;
        try {
            sdata = JSON.parse(tmp);
        }
        catch {
            sdata = tmp;
        }
        console.log(sdata);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let mdb = new MongoDB_1.MongoDB();
                let filter;
                let group;
                mdb.Type = -1;
                if (sdata.filter != undefined)
                    filter = mdb.Filter(sdata.filter, sessdata);
                if (sdata.data != undefined && sdata.fields != undefined)
                    group = mdb.GroupBy(sdata.data, sdata.fields);
                mdb.Project();
                mdb.prepare();
                if (table != undefined) {
                    mdb.Table = table;
                    mdb.execute((data) => {
                        //console.log(data)
                        let objv = new Graph_1.ChatData(res);
                        objv.ChartType = sdata.gtype;
                        objv.Stacked = sdata.stacked;
                        objv.Size = sdata.size;
                        objv.Zoom = sdata.zoom;
                        objv.prepare(data);
                        objv.getMixedSeries(sdata.series);
                        objv.getMixedCategory(sdata.xaxis);
                        objv.execute();
                    });
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({
                        status: 404,
                        message: "Table did not found!"
                    });
                    objv.execute();
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    CircularGraph(req, res, next) {
        console.log("Leads function called");
        let sdata;
        let table = typeof req.query.type != 'undefined' && req.query.type ? req.query.type.toString() : "";
        console.log(req.query);
        let tmp = req.query.filter;
        try {
            sdata = JSON.parse(tmp);
        }
        catch {
            sdata = tmp;
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let mdb = new MongoDB_1.MongoDB();
                let filter;
                let group;
                mdb.Type = -1;
                if (sdata.filter != undefined)
                    filter = mdb.Filter(sdata.filter, sessdata);
                if (sdata.data != undefined && sdata.fields != undefined)
                    group = mdb.GroupBy(sdata.data, sdata.fields);
                mdb.Project();
                mdb.prepare();
                if (table != undefined) {
                    mdb.Table = table;
                    mdb.execute((data) => {
                        //console.log(data)
                        let objv = new Graph_1.ChatData(res);
                        objv.ChartType = sdata.gtype;
                        objv.Stacked = sdata.stacked;
                        objv.Size = sdata.size;
                        objv.Zoom = sdata.zoom;
                        objv.prepare(data);
                        objv.getConsolidatedSeries(sdata.series);
                        objv.getConsolidatedCategory(sdata.series);
                        objv.execute();
                    });
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({
                        status: 404,
                        message: "Table did not found!"
                    });
                    objv.execute();
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    DataReport(req, res, next) {
        console.log("Leads function called");
        let sdata;
        let table = typeof req.query.type != 'undefined' && req.query.type ? req.query.type.toString() : "";
        console.log(req.query);
        let tmp = req.query.filter;
        try {
            sdata = JSON.parse(tmp);
        }
        catch {
            sdata = tmp;
        }
        console.log(sdata);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let mdb = new MongoDB_1.MongoDB();
                let filter;
                let group;
                mdb.Type = -1;
                if (sdata.filter != undefined)
                    filter = mdb.Filter(sdata.filter, sessdata);
                if (sdata.data != undefined && sdata.fields != undefined)
                    group = mdb.GroupBy(sdata.data, sdata.fields);
                mdb.Project();
                mdb.prepare();
                if (table != undefined) {
                    mdb.Table = table;
                    mdb.execute((data) => {
                        let objv = new RawView_1.RawView(res);
                        //console.log(data);
                        objv.prepare(data);
                        objv.execute();
                    });
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({
                        status: 404,
                        message: "Table did not found!"
                    });
                    objv.execute();
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /** @Dashboard report's data **/
    getChartReportData(req, res, next) {
        console.log("req.body.data::", req.body.data);
        let sdata = JSON.parse(req.body.data);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                let objv = new RawView_1.RawView(res);
                // Voice Usages Report 
                if (sdata.rtype == 1) {
                    let iQry = "SELECT  SUM(IF(direction='outbound', ((IFNULL(IF(leg_from>0,leg_from,0),0)+IFNULL(IF(leg_to>0,leg_to,0),0)+IFNULL(IF(rec_rate>0,rec_rate,0),0)+IFNULL(IF(amd_rate>0,amd_rate,0),0))*billsec)/60,0)) `obdcost`,SUM(IF(direction='inbound', ((IFNULL(IF(leg_from>0,leg_from,0),0)+IFNULL(IF(leg_to>0,leg_to,0),0)+IFNULL(IF(rec_rate>0,rec_rate,0),0)+IFNULL(IF(amd_rate>0,amd_rate,0),0))*billsec)/60,0)) `ibdcost` FROM cdr WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m')";
                    obj.qrysql = iQry;
                    obj.prepare();
                    obj.execute((error, result) => {
                        console.log("result::", result);
                        if (error == 1) {
                            // let total: any = result.length > 0 ? result[0].total : 0
                            objv.prepare({
                                error: 0,
                                message: "Records fetched successfully.",
                                data: result
                            });
                            objv.execute();
                        }
                        else {
                            objv.prepare({
                                error: 1,
                                message: "Something went wrong!"
                            });
                            objv.execute();
                        }
                    });
                }
                // Voice Inbound Report 
                else if (sdata.rtype == 2) {
                    let iQry = "SELECT COUNT(*) calls, IFNULL(SUM(IF(hangup_cause_q850=41 || hangup_cause_q850=63 || hangup_cause_q850=44 || hangup_cause_q850=34,1,0)),0) `conjestion`,IFNULL(SUM(IF(hangup_cause_q850=17,1,0)),0) `busy`, IFNULL(SUM(IF(hangup_cause_q850=19,1,0)),0) `noanswer`, IFNULL(SUM(IF(hangup_cause_q850=57 || hangup_cause_q850=54 || hangup_cause_q850=52,1,0)),0) `failure` FROM cdr  WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m') AND direction='inbound'";
                    obj.qrysql = iQry;
                    obj.prepare();
                    obj.execute((error, result) => {
                        console.log("result::", result);
                        if (error == 1) {
                            // let total: any = result.length > 0 ? result[0].total : 0
                            objv.prepare({
                                error: 0,
                                message: "Records fetched successfully.",
                                data: result
                            });
                            objv.execute();
                        }
                        else {
                            objv.prepare({
                                error: 1,
                                message: "Something went wrong!"
                            });
                            objv.execute();
                        }
                    });
                }
                // Voice Outbound Report 
                else if (sdata.rtype == 3) {
                    let iQry = "SELECT COUNT(*) calls, IFNULL(SUM(IF(hangup_cause_q850=41 || hangup_cause_q850=63 || hangup_cause_q850=44 || hangup_cause_q850=34,1,0)),0) `conjestion`,IFNULL(SUM(IF(hangup_cause_q850=17,1,0)),0) `busy`, IFNULL(SUM(IF(hangup_cause_q850=19,1,0)),0) `noanswer`, IFNULL(SUM(IF(hangup_cause_q850=57 || hangup_cause_q850=54 || hangup_cause_q850=52,1,0)),0) `failure` FROM cdr  WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m') AND direction='outbound'";
                    obj.qrysql = iQry;
                    obj.prepare();
                    obj.execute((error, result) => {
                        console.log("result::", result);
                        if (error == 1) {
                            // let total: any = result.length > 0 ? result[0].total : 0
                            objv.prepare({
                                error: 0,
                                message: "Records fetched successfully.",
                                data: result
                            });
                            objv.execute();
                        }
                        else {
                            objv.prepare({
                                error: 1,
                                message: "Something went wrong!"
                            });
                            objv.execute();
                        }
                    });
                }
                // Voice Received Failed Report
                else if (sdata.rtype == 4) {
                    // Inbound Cost
                    let iQry = "SELECT  DATE_FORMAT(start_stamp, '%Y-%m-%d') `date`, SUM(IF(direction='inbound', ((IFNULL(IF(leg_from>0,leg_from,0),0)+IFNULL(IF(leg_to>0,leg_to,0),0)+IFNULL(IF(rec_rate>0,rec_rate,0),0)+IFNULL(IF(amd_rate>0,amd_rate,0),0))*billsec)/60,0))*1000 `ibdcost` FROM cdr WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m') GROUP BY DATE_FORMAT(start_stamp, '%Y-%m-%d')";
                    obj.qrysql = iQry;
                    obj.prepare();
                    obj.execute((error, result1) => {
                        console.log("result::", result1);
                        if (error == 1) {
                            if (result1.length > 0) {
                                // Outbond Cost
                                let iQry1;
                                let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                                iQry1 = "SELECT  DATE_FORMAT(start_stamp, '%Y-%m-%d') `date`, SUM(IF(direction='outbound', ((IFNULL(IF(leg_from>0,leg_from,0),0)+IFNULL(IF(leg_to>0,leg_to,0),0)+IFNULL(IF(rec_rate>0,rec_rate,0),0)+IFNULL(IF(amd_rate>0,amd_rate,0),0))*billsec)/60,0))*1000 `obdcost` FROM cdr WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m') GROUP BY DATE_FORMAT(start_stamp, '%Y-%m-%d')";
                                obj1.qrysql = iQry1;
                                obj1.prepare();
                                obj1.execute((error, result2) => {
                                    if (error == 1) {
                                        console.log(result1, result2);
                                        let Received = [];
                                        let Failed = [];
                                        // let gD: any = {}
                                        if (result1.length > 0) {
                                            result1.forEach((ele) => {
                                                Received[ele.date] = (Received[ele.date] && Received[ele.ibdcost]);
                                                console.log(Received, "res1");
                                                // gD[ele.date] = 0
                                            });
                                        }
                                        if (result2.length > 0) {
                                            result2.forEach((ele) => {
                                                Failed[ele.date] = (Failed[ele.date] && Failed[ele.obdcost]);
                                                // gD[ele.date] = 0
                                                console.log(Failed, "res2");
                                            });
                                        }
                                        console.log("Received Failed::", Failed, Received);
                                        objv.prepare({
                                            error: 0,
                                            message: "Records fetched successfully.",
                                            data: {
                                                Received: Received,
                                                Failed: Failed
                                            }
                                        });
                                        objv.execute();
                                    }
                                    else {
                                        objv.prepare({
                                            error: 1,
                                            message: "Something went wrong!"
                                        });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                objv.prepare({
                                    error: 0,
                                    message: "Records fetched successfully.",
                                    data: []
                                });
                                objv.execute();
                            }
                        }
                    });
                }
                // Daily Usage
                else if (sdata.rtype == 6) {
                    // Inbound Cost
                    let iQry = "SELECT  DATE_FORMAT(start_stamp, '%Y-%m-%d') `date`, SUM(IF(direction='inbound', ((IFNULL(IF(leg_from>0,leg_from,0),0)+IFNULL(IF(leg_to>0,leg_to,0),0)+IFNULL(IF(rec_rate>0,rec_rate,0),0)+IFNULL(IF(amd_rate>0,amd_rate,0),0))*billsec)/60,0)) `ibdcost` FROM cdr WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m') GROUP BY DATE_FORMAT(start_stamp, '%Y-%m-%d')";
                    obj.qrysql = iQry;
                    obj.prepare();
                    obj.execute((error, result) => {
                        console.log("result::", result);
                        if (error == 1) {
                            if (result.length > 0) {
                                let Result1 = result;
                                // Outbond Cost
                                let iQry1;
                                let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                                iQry1 = "SELECT  DATE_FORMAT(start_stamp, '%Y-%m-%d') `date`, SUM(IF(direction='outbound', ((IFNULL(IF(leg_from>0,leg_from,0),0)+IFNULL(IF(leg_to>0,leg_to,0),0)+IFNULL(IF(rec_rate>0,rec_rate,0),0)+IFNULL(IF(amd_rate>0,amd_rate,0),0))*billsec)/60,0)) `obdcost` FROM cdr WHERE DATE_FORMAT(start_stamp, '%Y-%m')= DATE_FORMAT(NOW(), '%Y-%m') GROUP BY DATE_FORMAT(start_stamp, '%Y-%m-%d')";
                                obj1.qrysql = iQry1;
                                obj1.prepare();
                                obj1.execute((error, result) => {
                                    if (error == 1) {
                                        let Result2 = result;
                                        let Received = {};
                                        let Failed = {};
                                        // let gD: any = {}
                                        if (Result1.length > 0) {
                                            Result1.forEach((ele) => {
                                                Received[ele.date] = (Received[ele.date] || 0) + 1;
                                                // gD[ele.date] = 0
                                            });
                                        }
                                        if (Result2.length > 0) {
                                            Result2.forEach((ele) => {
                                                Failed[ele.date] = (Failed[ele.date] || 0) + 1;
                                                // gD[ele.date] = 0
                                            });
                                        }
                                        console.log("Received Failed6::", Failed, Received);
                                        objv.prepare({
                                            error: 0,
                                            message: "Records fetched successfully.",
                                            data: {
                                                Received: Received,
                                                Failed: Failed
                                            }
                                        });
                                        objv.execute();
                                    }
                                    else {
                                        objv.prepare({
                                            error: 1,
                                            message: "Something went wrong!"
                                        });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                objv.prepare({
                                    error: 0,
                                    message: "Records fetched successfully.",
                                    data: []
                                });
                                objv.execute();
                            }
                        }
                    });
                }
                else {
                    objv.prepare({
                        error: 1,
                        message: "Something went wrong!"
                    });
                    objv.execute();
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
}
exports.Reports = Reports;
