"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TZ = exports.UserManagement = void 0;
const RawView_1 = require("../lib/view/RawView");
const RawNonQuery_1 = require("../lib/model/RawNonQuery");
const Session_1 = require("../lib/model/Session");
const _406_1 = require("../lib/view/406");
const AppRoute_1 = require("../lib/AppRoute");
const ModelPdfUpload_1 = require("../lib/model/ModelPdfUpload");
const RawQuery_1 = require("../lib/model/RawQuery");
const Str = require('@supercharge/strings');
var nodemailer = require("nodemailer");
const jwt = require('jsonwebtoken');
const request = require("request");
const server_1 = require("../server");
const md5_1 = __importDefault(require("md5"));
const bcrypt = __importStar(require("bcrypt"));
const markError_1 = __importStar(require("./markError"));
const setting_config_1 = require("./../config/setting.config");
const APIBase_1 = require("./APIBase");
let insertdid = new APIBase_1.APIBase();
let genLink = new setting_config_1.generateLink();
let profile_pic = new setting_config_1.Profile();
const e9taxfile = new setting_config_1.TAXFILE();
const templateURL = new setting_config_1.TemplateURl();
const FromSmtpMail = new setting_config_1.SMTPDetails();
const FromEmail = FromSmtpMail.from;
const makeNumber = (length) => {
    let result = '';
    let characters = '09876543212346543098765123456789';
    let charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
};
const makeChar = (length) => {
    let result = '';
    let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
};
const makeRanChar = (length) => {
    let result = '';
    let characters = 'ABCDE2FGHIJklmno345pqrsUVWXYZabcdefg0hijGHIJKLMNOPQRtuvwxyx354';
    let charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
};
const generatePassword = () => {
    let result = '';
    return result = makeRanChar(5).substring(0, 3).toLowerCase() + makeNumber(1) + makeRanChar(5).substring(3, 5) + makeChar(1).toUpperCase() + makeChar(1).toLowerCase();
};
class UserManagement extends AppRoute_1.AppRoute {
    constructor() {
        super();
    }
    /**
     * To authenticate user with TimeZone
     */
    getMorphingSession(req, res, next) {
        let pData = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT `iduser`, `idaccount`, `username`, `type`, `default`, `idtariff`, `authkey`, `status`, `isEmailVerify`, `isMobileVerify`, `idapi`, `isAddress`, `isPlan`, `tz_diff`, `server_time`, `client_time` FROM `session` WHERE `authkey` = '" + pData.key + "'";
                obj.prepare();
                obj.execute((error, result) => {
                    if (error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Session Data Fetch Successfully!", status: 200, data: result });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong to Fetch Session", status: 502, result: result });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getLogin(req, res, next) {
        let sdata = req.body.data;
        let pass = (0, md5_1.default)(sdata.password);
        let email = sdata.username;
        let pass1 = sdata.password;
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        // let iQry: string = "SELECT us.iduser, us.idaccount, us.username, us.password, us.type, us.default, us.idtariff, us.isEmailVerify, us.isMobileVerify, us.isPlan, us.isAddress, ROUND(TIME_TO_SEC(TIMEDIFF(NOW(), UTC_TIMESTAMP)) / 60) tz_diff, TIMEDIFF(NOW(), UTC_TIMESTAMP) server_time, tz.utc client_time, IF(us.is_deleted = 0, 9, us.is_deleted) acc_status FROM user us\n"
        // iQry += "LEFT JOIN `tbl_timezone_config` tzc ON tzc.id_user=us.iduser\n"
        // iQry += "LEFT JOIN `tbl_timezones` tz ON tz.id=tzc.id_timezone\n"
        // iQry += "WHERE us.`username`='" + checkDesc(sdata.username) + "';"
        // let iQry: string = "SELECT r.iduser, r.idaccount, r.username, r.password, r.type, r.default, r.idtariff, r.isEmailVerify,r.isMobileVerify, r.isPlan, r.isAddress, ROUND(TIME_TO_SEC(TIMEDIFF(NOW(), UTC_TIMESTAMP)) / 60) tz_diff,TIMEDIFF(NOW(), UTC_TIMESTAMP) server_time, tz.utc client_time, IF(r.is_deleted = 0, 9, r.is_deleted)acc_status FROM `reseller` r\n"
        //        iQry += "LEFT JOIN `tbl_timezone_config` tzc ON tzc.id_user=r.iduser\n"
        //        iQry += "LEFT JOIN `tbl_timezones` tz ON tz.id=tzc.id_timezone\n"
        //        iQry += "WHERE r.`username`='" + checkDesc(sdata.username) + "';"
        let iQry = "SELECT r.iduser, r.idaccount, r.username, r.password, r.type, r.default, r.isEmailVerify,r.isMobileVerify, r.isPlan, r.isAddress, ROUND(TIME_TO_SEC(TIMEDIFF(NOW(), UTC_TIMESTAMP)) / 60) tz_diff,TIMEDIFF(NOW(), UTC_TIMESTAMP) server_time, tz.utc client_time, IF(r.is_deleted = 0, 9, r.is_deleted)acc_status FROM `reseller` r\n";
        iQry += "LEFT JOIN `tbl_timezone_config` tzc ON tzc.id_user=r.iduser\n";
        iQry += "LEFT JOIN `tbl_timezones` tz ON tz.id=tzc.id_timezone\n";
        iQry += "WHERE r.`username`='" + (0, markError_1.default)(sdata.username) + "';";
        obj.qrysql = iQry;
        if (obj.prepare()) {
            obj.execute((error, result) => {
                if (result.length > 0) {
                    let Client_time = result[0].client_time == null || result[0].client_time == 'Null' || result[0].client_time == null ? '' : result[0].client_time;
                    let objup = new RawQuery_1.ModelRawQuery(req, res);
                    objup.qrysql = "SELECT email FROM `reseller_profile` WHERE `iduser`='" + result[0].iduser + "'";
                    objup.prepare();
                    objup.execute((__errorE, emailE) => {
                        result[0].server_time = result[0].server_time.slice(0, -3);
                        result[0].client_time = Client_time;
                        if (result[0].server_time.indexOf("+") < 0 && result[0].server_time.indexOf("-") < 0) {
                            result[0].server_time = "+" + result[0].server_time;
                        }
                        //if (pass == md5(result[0].password)) {
                        if ((bcrypt.compareSync(pass1, result[0].password) || (pass1 == result[0].password))) {
                            if (result[0].type == 4) {
                                let data = result[0];
                                let tmp = "{\"sessionType\": \"" + sdata.sessionType + "\"}";
                                let loginType = JSON.parse(tmp);
                                let Result = Object.assign(data, loginType);
                                if ((data.acc_status == 9) || (sdata.typeCheck && sdata.typeCheck == "admin_checking")) {
                                    delete data.acc_status;
                                    let session = new Session_1.SessionManagment(req, res, next);
                                    session.SetSession(Result, (error, sessdata) => {
                                        let sysInfo = (0, markError_1.ipAddressAndBrowser)(req);
                                        let objh = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        objh.nonqrysql = "INSERT INTO `user_login_history`(`iduser`, `idaccount`, `type`, `token`, `ipaddress`, `browser`, `login_time`, `login_type`) VALUES ('" + result[0].iduser + "','" + result[0].idaccount + "','" + result[0].type + "', '" + Result.authkey + "', '" + sysInfo.ipAddress[0] + "', '" + sysInfo.browserName + "', NOW(),'login')";
                                        objh.prepare();
                                        objh.execute((error, data) => {
                                            console.log("User History Data Inserted!");
                                        });
                                        let tmp = "{\"email\": \"" + emailE[0].email + "\"}";
                                        let emType = JSON.parse(tmp);
                                        let data1 = Object.assign(data, emType);
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare(data1);
                                        objv.execute();
                                    });
                                }
                                else {
                                    let errMsg = data.acc_status == 1 ? "Your account deletion in under process!" : "Your account has been deleted, If you want to restore kindly contact with customer support!";
                                    let errCode = data.acc_status == 1 ? "DelInProcess" : "Deleted";
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({
                                        message: errMsg, error: errCode
                                    });
                                    objv.execute();
                                }
                                /**
                                 * It will create default timezone of user if doesn't exist
                                 */
                                // if (data.client_time == null || !data.client_time) {
                                //     let obj2 = new ModelRawNonQuery(req, res);
                                //     obj2.nonqrysql = "REPLACE INTO `tbl_timezone_config`(id_timezone, id_user) VALUES(192, " + data.iduser + ");"
                                //     obj2.prepare()
                                //     obj2.execute((error: any, result: any) => {
                                //         if (error == 1) {
                                //             /**
                                //              * Update the TimeZone in user's session data
                                //              */
                                //             obj2.nonqrysql = "SELECT a.utc client_time FROM tbl_timezones a WHERE a.id=192;"
                                //             obj2.prepare()
                                //             obj2.execute((error: any, result: any) => {
                                //                 if (error == 1 && result.length > 0) {
                                //                     data.client_time = result[0].client_time
                                //                 }
                                //                 session.SetSession(data, (error: any, sessdata: any) => {
                                //                     let objv = new RawView(res);
                                //                     objv.prepare(data);
                                //                     objv.execute();
                                //                 });
                                //             })
                                //         }
                                //         else {
                                //             session.SetSession(data, (error: any, sessdata: any) => {
                                //                 let objv = new RawView(res);
                                //                 objv.prepare(data);
                                //                 objv.execute();
                                //             });
                                //         }
                                //     })
                                // }
                                /**
                                 * If user's timezone exist it will continue
                                 */
                                // else {
                                //     session.SetSession(data, (error: any, sessdata: any) => {
                                //         let objv = new RawView(res);
                                //         objv.prepare(data);
                                //         objv.execute();
                                //     });
                                // }
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "You are not Authorized for this Panel!" });
                                objv.execute();
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                message: "Invalid Username/Password,Kindly check again!"
                            });
                            objv.execute();
                        }
                    });
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Invalid Username/Password, Kindly check again!" });
                    objv.execute();
                }
            });
        }
        else {
            let objv = new RawView_1.RawView(res);
            objv.prepare({
                message: "Few parameter are missing in request!"
            });
            objv.execute();
        }
    }
    /**
     * To save the system timezone into user's profile
     */
    SaveSysTZ(req, res, next) {
        let sdata = null;
        try {
            sdata = JSON.parse(req.body.data);
        }
        catch (e) {
            sdata = req.body.data;
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                let objr = new RawQuery_1.ModelRawQuery(req, res);
                let objv = new RawView_1.RawView(res);
                objr.qrysql = "SELECT id FROM `tbl_timezones` WHERE utc='" + sdata.utc + "' AND tzCode='" + sdata.tzCode + "';";
                objr.prepare();
                objr.execute((error, result) => {
                    if (error == 1) {
                        let id_tz = result.length > 0 ? result[0].id : 0;
                        obj.nonqrysql = "REPLACE INTO `tbl_timezone_config`(id_timezone, id_user) VALUES(" + id_tz + ", " + sessdata.iduser + ");";
                        obj.prepare();
                        obj.execute((error, result) => {
                            if (error == 1) {
                                /**
                                 * It will update the current user's
                                 * session table + session data
                                 */
                                obj.nonqrysql = "UPDATE `session` SET `client_time`='" + sdata.utc + "' WHERE `authkey`='" + sessdata.authkey + "';";
                                obj.prepare();
                                obj.execute((error, result2) => {
                                    sessdata.client_time = sdata.utc;
                                    server_1.sessiondata.set(sessdata.authkey, sessdata);
                                });
                            }
                            else {
                                objv.prepare({
                                    error: 1,
                                    message: "Something went wrong!"
                                });
                                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();
            }
        });
    }
    signUp(req, res, next) {
        const ipAddress = req.socket.remoteAddress;
        let sdata = req.body.data;
        let secret = Str.random(15);
        let validationKey = jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60),
            data: sdata.email + ":" + sdata.password
        }, secret);
        var isPlan;
        var tariff;
        if (sdata.tariff1 == -1 || sdata.tariff1 == 0) {
            isPlan = false;
            tariff = '-1';
        }
        else {
            isPlan = true;
            tariff = sdata.tariff1;
        }
        if (sdata.imgUrl) {
            sdata.imgUrl = sdata.imgUrl;
        }
        else {
            sdata.imgUrl = "https://portal.signalmash.com/assets/img/icon.png";
        }
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        obj.qrysql = "SELECT up.email ,u. username FROM `user` u JOIN `user_profile` up ON up.iduser=u.iduser WHERE email = '" + sdata.email + "' OR username = '" + sdata.email + "'";
        obj.prepare();
        obj.execute((_error, getEmail) => {
            if (_error == 1) {
                if (getEmail.length > 0) {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({
                        message: "Email Or Username Already Exists!",
                        status: 404
                    });
                    objv.execute();
                }
                else {
                    //hash password 
                    let passwd = sdata.password.trim();
                    let password1 = bcrypt.hashSync(passwd, 10);
                    let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj2.nonqrysql = "CALL AddUser(-1, -1, '" + sdata.email + "','" + password1 + "','42','" + sdata.firstName + "','" + sdata.lastName + "','" + sdata.email + "',' ','" + sdata.imgUrl + "','1', '" + tariff + "', '" + sdata.tariff2 + "', '" + sdata.status + "', '10', '0')";
                    obj2.prepare();
                    obj2.execute((__error, __res) => {
                        let iduser = __res[0];
                        if (__error == 1) {
                            let obj4 = new RawQuery_1.ModelRawQuery(req, res);
                            obj4.qrysql = "SELECT body, otp_digit, tmp_type  FROM `2fa_template` WHERE iduser='1' AND tmp_type='sms' AND `default`='1'";
                            obj4.prepare();
                            obj4.execute((sessdata, _res) => {
                                let message = "";
                                let otp_digit = "";
                                let temp_type = "";
                                let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                                let temp_key = '';
                                let charactersLength = characters.length;
                                for (let i = 0; i < 25; i++) {
                                    temp_key += characters.charAt(Math.floor(Math.random() * charactersLength));
                                }
                                if (_res.length > 0) {
                                    message = _res[0].body;
                                    otp_digit = _res[0].otp_digit;
                                    temp_type = _res[0].tmp_type;
                                }
                                else {
                                    message = "Your One time Password is {OTP}";
                                    otp_digit = "5";
                                    temp_type = "sms";
                                }
                                let objTime = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                objTime.nonqrysql = "INSERT INTO `2fa_template`(`iduser`, `otp_digit`,`body`, `tmp_type`,`template_key`,`default`) VALUES ('" + iduser[0].userid + "','" + otp_digit + "','" + message + "', '" + temp_type + "','" + temp_key + "','1')";
                                objTime.prepare();
                                objTime.execute((err, sTime) => {
                                    if (err == 1) {
                                        let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj3.nonqrysql = "UPDATE `user` SET `validationKey`='" + validationKey + "', `secret`='" + secret + "', `isPlan`='"
                                            + isPlan + "', `idtariff`='" + tariff + "',`ipAddress`='" + ipAddress + "'  WHERE `iduser`='" + iduser[0].userid + "'";
                                        obj3.prepare();
                                        obj3.execute((_err, __result) => {
                                            if (_err == 1) {
                                                let objA = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                objA.nonqrysql = "UPDATE `account` SET `san`=(100000000 + '" + iduser[0].account + "') WHERE `idaccount`='" + iduser[0].account + "'";
                                                objA.prepare();
                                                objA.execute((_errAccount, __resultAccount) => {
                                                    if (_errAccount == 1) {
                                                        let obj4 = new RawQuery_1.ModelRawQuery(req, res);
                                                        obj4.qrysql = "SELECT * FROM `email_template` WHERE type='email_verification'";
                                                        obj4.prepare();
                                                        obj4.execute((emlErr, emlRes) => {
                                                            if (emlErr == 1) {
                                                                if (emlRes.length > 0) {
                                                                    let tmpData = emlRes[0].template;
                                                                    tmpData = tmpData.replace(/{FIRST_NAME}/g, sdata.firstName);
                                                                    tmpData = tmpData.replace(/{LAST_NAME}/g, sdata.lastName);
                                                                    tmpData = tmpData.replace(/{VALIDATION_KEY}/g, validationKey);
                                                                    // var smtpTransport = nodemailer.createTransport({
                                                                    //     service: "gmail",
                                                                    //     host: "smtp-relay.gmail.com",
                                                                    //     port: 587,
                                                                    //     secure: true,
                                                                    //     auth: {
                                                                    //         user: "donotreply@nglcommunications.com",
                                                                    //         pass: "yr%5V9GB"
                                                                    //     }
                                                                    // });
                                                                    // var mailOptions = {
                                                                    //     from: 'Signalmash <donotreply@signalmash.com>',
                                                                    //     to: sdata.email,
                                                                    //     usernmae: sdata.email,
                                                                    //     email: sdata.email,
                                                                    //     subject: `${emlRes[0].subject}`,
                                                                    //     text: "Thank You For Registration",
                                                                    //     html: `${tmpData}`
                                                                    // }
                                                                    // smtpTransport.sendMail(mailOptions, (_emailError: any, emailRes: any) => {
                                                                    //     if (emailRes) {
                                                                    // let obj1 = new ModelRawNonQuery(req, res);
                                                                    // obj1.nonqrysql = "INSERT INTO `email_send`(`iduser`, `idaccount`,`from`,`to`, `subject`,`text`,`html`,`type`,`status`,`cc`,`bcc`) VALUES ('" + iduser[0].userid + "','" + iduser[0].account + "','" + FromEmail + "','" + sdata.email + "', '" + parseBody(emlRes[0].subject) + "','Thank You For Registration', '" + parseBody(tmpData) + "','Mail Send for Registration','','" + emlRes[0].cc + "','" + emlRes[0].bcc + "')";
                                                                    // obj1.prepare();
                                                                    // obj1.execute((_err: any, __result: any) => {
                                                                    let logPayload = {
                                                                        funDetail: {
                                                                            tableName: 'email_send',
                                                                            functionName: 'signUp',
                                                                            logName: 'mail'
                                                                        },
                                                                        data: {
                                                                            iduser: iduser[0].userid,
                                                                            idaccount: iduser[0].account,
                                                                            bcc: emlRes[0].bcc,
                                                                            from: FromEmail,
                                                                            to: sdata.email,
                                                                            subject: (0, markError_1.parseBody)(emlRes[0].subject),
                                                                            text: 'Thank You For Registration',
                                                                            html: (0, markError_1.parseBody)(tmpData),
                                                                            type: 'Mail Send for Registration',
                                                                            cc: emlRes[0].cc,
                                                                        }
                                                                    };
                                                                    insertdid.insertLog(req, res, logPayload, (log_error, did_log) => {
                                                                        if (log_error == 1) {
                                                                            const connection_key = Str.random(30);
                                                                            const randDigit = connection_key.slice(4, 12);
                                                                            var rdata = [];
                                                                            let obj2 = new RawQuery_1.ModelRawQuery(req, res);
                                                                            obj2.filter = null;
                                                                            const val = Math.floor(1000 + Math.random() * 9000);
                                                                            let username = Math.random().toString(36).substr(2, 11);
                                                                            //let password = randDigit;
                                                                            let password = generatePassword();
                                                                            const inbound_key = Str.random(30);
                                                                            const outbound_key = Str.random(30);
                                                                            const val1 = Math.floor(1000 + Math.random() * 9000);
                                                                            const connName = sdata.firstName + val1;
                                                                            obj2.qrysql = "CALL addconnection('" + iduser[0].account + "', '" + iduser[0].userid + "', '" + connName + "', '" + connection_key + "', '" + username + "', '" + password + "', '" + inbound_key + "', '" + outbound_key + "', 'true')";
                                                                            obj2.prepare();
                                                                            obj2.execute((__error, allcamp) => {
                                                                                if (__error == 1) {
                                                                                    let objTime = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                                    objTime.nonqrysql = "INSERT INTO `tbl_timezone_config` SET `id_timezone`=16, id_user='" + iduser[0].userid + "'";
                                                                                    objTime.prepare();
                                                                                    objTime.execute((errTime, sTime) => {
                                                                                        if (errTime == 1) {
                                                                                            let objv = new RawView_1.RawView(res);
                                                                                            objv.prepare({ result: sdata, key: validationKey, iduser: iduser[0].userid, status: 201, data: did_log, message: "Signup Successfully!" });
                                                                                            objv.execute();
                                                                                        }
                                                                                        else {
                                                                                            let objv = new RawView_1.RawView(res);
                                                                                            objv.prepare({ status: 502, message: "Registered Successfully! But Default Time Zone has error", error: log_error });
                                                                                            objv.execute();
                                                                                        }
                                                                                    });
                                                                                }
                                                                                else {
                                                                                    let objv = new RawView_1.RawView(res);
                                                                                    objv.prepare({ status: 502, message: "Registered Successfully! But Default Connection Not Created", error: log_error });
                                                                                    objv.execute();
                                                                                }
                                                                            });
                                                                        }
                                                                        else {
                                                                            let objv = new RawView_1.RawView(res);
                                                                            objv.prepare({ status: 401, message: "Registered Successfully! Verification Email not Send!", error: log_error });
                                                                            objv.execute();
                                                                        }
                                                                    });
                                                                }
                                                                else {
                                                                    let objv = new RawView_1.RawView(res);
                                                                    objv.prepare({ message: "Registered Successfully! Verification Email not Send!", status: 502 });
                                                                    objv.execute();
                                                                }
                                                            }
                                                            else {
                                                                let objv = new RawView_1.RawView(res);
                                                                objv.prepare({ message: "Registered But Error With Fetching Email Data!", status: 502 });
                                                                objv.execute();
                                                            }
                                                        });
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ message: "Registered But Error With Connection!", status: 502 });
                                                        objv.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ message: "Registered But Error With Connection!", status: 502 });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Template not Inserted Successfully!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            });
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong with Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                    // res.status(200).json({data: result, message: "Signup Successfully!"});
                }
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Something Went with Connection!", status: 502 });
                objv.execute();
            }
        });
    }
    makeNumber(len) {
        var result = '';
        var characters = '09876543212346543098765123456789';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    makeChar(len) {
        var result = '';
        var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    makeRanChar(len) {
        var result = '';
        var characters = 'ABCDE2FGHIJklmno345pqrsUVWXYZabcdefg0hijGHIJKLMNOPQRtuvwxyx354';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    AdminSave(req, res, next) {
        let sdata;
        let filePath = "https://portal.signalmash.com/assets/img/icon.png";
        try {
            sdata = JSON.parse(req.body.data);
        }
        catch (e) {
            sdata = JSON.parse(req.body.data);
        }
        ;
        if (req.file) {
            const fileName = req.file.filename;
            filePath = 'https://api.signalmash.com' + '/uploads/' + fileName;
        }
        if (sdata.profile_pic) {
            filePath = sdata.profile_pic;
        }
        let passwd = sdata.password.trim();
        let session = new Session_1.SessionManagment(req, res, next);
        let msg = "";
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                if (sdata.idaccount == -1) {
                    let obj = new RawQuery_1.ModelRawQuery(req, res);
                    obj.qrysql = "SELECT up.email ,u. username FROM `user` u JOIN `user_profile` up ON up.iduser=u.iduser WHERE username = '" + sdata.user_name + "' OR email = '" + sdata.email + "'";
                    obj.prepare();
                    obj.execute((_error, getUser) => {
                        if (_error == 1) {
                            if (getUser.length > 0) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    message: "Username or Email Already Exists!",
                                    status: 404
                                });
                                objv.execute();
                            }
                            else {
                                let planVerify = sdata.tariff1 ? 'true' : 'false';
                                let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                let password1 = bcrypt.hashSync(passwd, 10);
                                obj1.nonqrysql = "CALL AddUser(-1, -1, '" + sdata.user_name + "','" + password1 + "','" + sdata.type + "','" + sdata.first_name + "','" + sdata.last_name + "','" + sdata.email + "','" + sdata.contact_number + "','" + filePath + "','1', '" + sdata.tariff1 + "', '" + sdata.tariff2 + "', '" + sdata.status + "', '" + sdata.service + "', '" + sdata.credit_limit + "')";
                                if (sdata.type == 2) {
                                    msg = "Customer Added Successfully";
                                }
                                if (sdata.type == 3) {
                                    msg = "Supplier Added Successfully";
                                }
                                obj1.prepare();
                                obj1.execute((__error, result) => {
                                    if (__error == 1) {
                                        let newRes = result[0];
                                        const connection_key = Str.random(30);
                                        const randDigit = connection_key.slice(4, 12);
                                        var rdata = [];
                                        let obj2 = new RawQuery_1.ModelRawQuery(req, res);
                                        obj2.filter = null;
                                        const val = Math.floor(1000 + Math.random() * 9000);
                                        let username = Math.random().toString(36).substr(2, 11);
                                        //let password = randDigit;
                                        let password = generatePassword();
                                        const inbound_key = Str.random(30);
                                        const outbound_key = Str.random(30);
                                        const val1 = Math.floor(1000 + Math.random() * 9000);
                                        const connName = sdata.first_name + val1;
                                        obj2.qrysql = "CALL addconnection('" + newRes[0].account + "', '" + newRes[0].userid + "', '" + connName + "', '" + connection_key + "', '" + username + "', '" + password + "', '" + inbound_key + "', '" + outbound_key + "', 'true')";
                                        obj2.prepare();
                                        obj2.execute((__error, allcamp) => {
                                            if (__error == 1) {
                                                // added here separete query............start 
                                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                obj.nonqrysql = "INSERT INTO `billing_address` (`idaccount`, `first_name`, `last_name`, `contact`, `email`, `address1`, `address2`, `city`, `state`, `postal_code`, `country`) VALUES ('" + newRes[0].account + "', '" + sdata.first_name + "', '" + sdata.last_name + "', '" + sdata.contact_number + "', '" + sdata.email + "', '" + sdata.address1 + "', '" + sdata.address2 + "', '" + sdata.city + "', '" + sdata.state + "', '" + sdata.postal_code + "', '" + sdata.country + "')";
                                                obj.prepare();
                                                obj.execute((_error, data) => {
                                                    // Added here update query.........
                                                    let obj11 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                    obj11.nonqrysql = "UPDATE `user` SET `isEmailVerify`='" + sdata.isEmailVerify + "',`isMobileVerify`='" + sdata.isMobileVerify + "', `isPlan`= '" + planVerify + "', `isAddress`='" + sdata.isAddress + "' WHERE `idaccount`='" + newRes[0].account + "'";
                                                    obj11.prepare();
                                                    obj11.execute((_errorrr, resultt) => { });
                                                });
                                                // closed here.......................
                                                let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                obj3.nonqrysql = "UPDATE `account` SET `san`=(100000000 + '" + newRes[0].account + "') WHERE `idaccount`='" + newRes[0].account + "'";
                                                obj3.prepare();
                                                obj3.execute((_uperr, __result) => {
                                                    if (_uperr == 1) {
                                                        let objTime = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                        objTime.nonqrysql = "INSERT INTO `tbl_timezone_config` SET `id_timezone`=16, id_user='" + newRes[0].userid + "'";
                                                        objTime.prepare();
                                                        objTime.execute((errTime, sTime) => {
                                                            if (errTime == 1) {
                                                                let obj4 = new RawQuery_1.ModelRawQuery(req, res);
                                                                obj4.qrysql = "SELECT body, otp_digit, tmp_type  FROM `2fa_template` WHERE iduser='1' AND tmp_type='sms' AND `default`='1'";
                                                                obj4.prepare();
                                                                obj4.execute((sessdata, _res) => {
                                                                    let message = "";
                                                                    let otp_digit = "";
                                                                    let temp_type = "";
                                                                    let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                                                                    let temp_key = '';
                                                                    let charactersLength = characters.length;
                                                                    for (let i = 0; i < 25; i++) {
                                                                        temp_key += characters.charAt(Math.floor(Math.random() * charactersLength));
                                                                    }
                                                                    if (_res.length > 0) {
                                                                        message = _res[0].body;
                                                                        otp_digit = _res[0].otp_digit;
                                                                        temp_type = _res[0].tmp_type;
                                                                    }
                                                                    else {
                                                                        message = "Your One time Password is {OTP}";
                                                                        otp_digit = "5";
                                                                        temp_type = "sms";
                                                                    }
                                                                    let objTime = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                    objTime.nonqrysql = "INSERT INTO `2fa_template`(`iduser`, `otp_digit`,`body`, `tmp_type`,`template_key`,`default`) VALUES ('" + newRes[0].userid + "','" + otp_digit + "','" + message + "', '" + temp_type + "','" + temp_key + "','1')";
                                                                    objTime.prepare();
                                                                    objTime.execute((err, sTime) => {
                                                                        let objv = new RawView_1.RawView(res);
                                                                        objv.prepare({ data: result[0], message: "Customer Added Successfully!", status: 201 });
                                                                        objv.execute();
                                                                    });
                                                                });
                                                            }
                                                            else {
                                                                let objv = new RawView_1.RawView(res);
                                                                objv.prepare({ status: 502, message: "Customer Added Successfully! But Default Time Zone has error", error: allcamp });
                                                                objv.execute();
                                                            }
                                                        });
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ data: result[0], message: "Customer Added But Error With Set Time!", status: 502 });
                                                        objv.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ data: result[0], message: "Something Went Wrong With Connection!", status: 502 });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ data: result[0], message: "Something Went Wrong With Connection!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                }
                else {
                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    let password1 = bcrypt.hashSync(passwd, 10);
                    obj1.nonqrysql = "CALL AddUser('" + sdata.idaccount + "', -1, '" + sdata.user_name + "','" + password1 + "','" + sdata.type + "','" + sdata.first_name + "','" + sdata.last_name + "','" + sdata.email + "','" + sdata.contact_number + "','" + filePath + "','0', '" + sdata.tariff1 + "','" + sdata.tariff2 + "', '" + sdata.status + "', '" + sdata.service + "', '" + sdata.credit_limit + "')";
                    if (sdata.type == 2) {
                        msg = "Customer Updated Successfully";
                    }
                    if (sdata.type == 3) {
                        msg = "Supplier Updated Successfully";
                    }
                    obj1.prepare();
                    obj1.execute((_error, result) => {
                        if (_error == 1) {
                            let newRes = result[0];
                            if (sdata.type == 22) {
                                let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                                obj0.qrysql = "SELECT `idtariff`,`idservice` FROM `user` WHERE idaccount = '" + sdata.idaccount + "'";
                                obj0.prepare();
                                obj0.execute((_errorser, getSer) => {
                                    if (_errorser == 1) {
                                        let service = getSer[0].idservice;
                                        let idtariff = getSer[0].idtariff;
                                        let obj11 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj11.nonqrysql = "UPDATE `user` SET `idtariff`='" + idtariff + "',`idservice`='" + service + "',`isAddress`='true' WHERE `iduser`='" + newRes[0].userid + "'";
                                        obj11.prepare();
                                        obj11.execute((_errorrr, resultt) => {
                                            if (_errorrr == 1) {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ data: resultt[0], message: "Customer Updated Successfully!", status: 201 });
                                                objv.execute();
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ data: resultt, message: "Something Went Wrong With Connection!", status: 502 });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Something Went Wrong With Tarif And Service!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ data: result[0], message: "Profile Updated Successfully!", status: 201 });
                                objv.execute();
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    SaveUser(req, res, next) {
        let sdata;
        let filePath = "https://portal.signalmash.com/assets/img/icon.png";
        try {
            sdata = JSON.parse(req.body.data);
        }
        catch (e) {
            sdata = req.body.data;
        }
        if (req.file) {
            const fileName = req.file.filename;
            // var filePath = req.protocol + '://' + req.get("host") + "/uploads/" + fileName;
            filePath = 'https://api.signalmash.com' + '/uploads/' + fileName;
        }
        if (sdata.profile_pic != null || sdata.profile_pic != undefined) {
            filePath = sdata.profile_pic;
        }
        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
        let passwd = sdata.password.trim();
        let session = new Session_1.SessionManagment(req, res, next);
        let message = "";
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                if (sdata.iduser == -1) {
                    let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                    obj1.qrysql = "SELECT up.email ,u. username FROM `user` u JOIN `user_profile` up ON up.iduser=u.iduser WHERE username = '" + sdata.user_name + "' OR email = '" + sdata.email + "'";
                    obj1.prepare();
                    obj1.execute((_error, result) => {
                        if (_error == 1) {
                            if (result.length > 0) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    message: "Username or Email Already Exists!",
                                    status: 404
                                });
                                objv.execute();
                            }
                            else {
                                let password1 = bcrypt.hashSync(passwd, 10);
                                obj.nonqrysql = "CALL AddUser('" + sessdata.idaccount + "', -1, '" + sdata.user_name + "','" + password1 + "','" + sdata.type + "','" + sdata.first_name + "','" + sdata.last_name + "','" + sdata.email + "','" + sdata.contact_number + "','" + filePath + "','0', '" + sdata.tariff1 + "', '" + sdata.tariff2 + "', '" + sdata.status + "', '" + sdata.service + "', '" + sdata.credit_limit + "')";
                                if (sdata.type == 2) {
                                    message = "Customer Added Successfully";
                                }
                                if (sdata.type == 3) {
                                    message = "Supplier Added Successfully";
                                }
                                obj.prepare();
                                obj.execute((__error, result) => {
                                    if (__error == 1) {
                                        let newRes = result[0];
                                        const connection_key = Str.random(30);
                                        const randDigit = connection_key.slice(4, 12);
                                        var rdata = [];
                                        let obj2 = new RawQuery_1.ModelRawQuery(req, res);
                                        obj2.filter = null;
                                        const val = Math.floor(1000 + Math.random() * 9000);
                                        let username = Math.random().toString(36).substr(2, 11);
                                        //let password = randDigit;
                                        let password = generatePassword();
                                        const inbound_key = Str.random(30);
                                        const outbound_key = Str.random(30);
                                        const val1 = Math.floor(1000 + Math.random() * 9000);
                                        const connName = sdata.first_name + val1;
                                        obj2.qrysql = "CALL addconnection('" + newRes[0].account + "', '" + newRes[0].userid + "', '" + connName + "', '" + connection_key + "', '" + username + "', '" + password + "', '" + inbound_key + "', '" + outbound_key + "', 'true')";
                                        obj2.prepare();
                                        obj2.execute((__error, allcamp) => {
                                            if (__error == 1) {
                                                let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                obj3.nonqrysql = "UPDATE `account` SET `san`=(100000000 + '" + newRes[0].account + "') WHERE `idaccount`='" + newRes[0].account + "'";
                                                obj3.prepare();
                                                obj3.execute((_uperr, __result) => {
                                                    if (_uperr == 1) {
                                                        let objTime = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                        objTime.nonqrysql = "INSERT INTO `tbl_timezone_config` SET `id_timezone`=16, id_user='" + newRes[0].userid + "'";
                                                        objTime.prepare();
                                                        objTime.execute((errTime, sTime) => {
                                                            if (errTime == 1) {
                                                                if (sdata.type == 22) {
                                                                    let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                                                                    obj0.qrysql = "SELECT `idtariff`,`idservice` FROM `user` WHERE idaccount = '" + sdata.idaccount + "'";
                                                                    obj0.prepare();
                                                                    obj0.execute((_errorser, getSer) => {
                                                                        if (_errorser == 1) {
                                                                            let service = getSer[0].idservice;
                                                                            let idtariff = getSer[0].idtariff;
                                                                            let obj11 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                            obj11.nonqrysql = "UPDATE `user` SET `idtariff`='" + idtariff + "',`idservice`='" + service + "',`isAddress`='true' WHERE `iduser`='" + newRes[0].userid + "'";
                                                                            obj11.prepare();
                                                                            obj11.execute((_errorrr, resultt) => {
                                                                                if (_errorrr == 1) {
                                                                                    let objv = new RawView_1.RawView(res);
                                                                                    objv.prepare({ data: result[0], message: "Customer Added Successfully!", status: 201 });
                                                                                    objv.execute();
                                                                                }
                                                                                else {
                                                                                    let objv = new RawView_1.RawView(res);
                                                                                    objv.prepare({ data: resultt, message: "Something Went Wrong With Tariff and Service Update!", status: 502 });
                                                                                    objv.execute();
                                                                                }
                                                                            });
                                                                        }
                                                                        else {
                                                                            let objv = new RawView_1.RawView(res);
                                                                            objv.prepare({ message: "Something Went Wrong With Tarif And Service!", status: 502 });
                                                                            objv.execute();
                                                                        }
                                                                    });
                                                                }
                                                                else {
                                                                    let objv = new RawView_1.RawView(res);
                                                                    objv.prepare({ data: result[0], message: "Customer Added Successfully!", status: 201 });
                                                                    objv.execute();
                                                                }
                                                            }
                                                            else {
                                                                let objv = new RawView_1.RawView(res);
                                                                objv.prepare({ status: 502, message: "Registered Successfully! But Default Time Zone has error", error: result });
                                                                objv.execute();
                                                            }
                                                        });
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ data: result[0], message: "Customer Added But Error With Set Time!", status: 502 });
                                                        objv.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ data: result[0], message: "Something Went Wrong With Connection!", status: 502 });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ data: result[0], message: "Something Went Wrong With Connection!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ data: result[0], message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                }
                else {
                    let password1 = bcrypt.hashSync(passwd, 10);
                    obj.nonqrysql = "CALL AddUser('" + sdata.idaccount + "', " + sdata.iduser + ", '" + sdata.user_name + "','" + password1 + "','" + sdata.type + "','" + sdata.first_name + "','" + sdata.last_name + "','" + sdata.email + "','" + sdata.contact_number + "','" + filePath + "','0', '" + sdata.tariff1 + "','" + sdata.tariff2 + "', '" + sdata.status + "', '" + sdata.service + "', '" + sdata.credit_limit + "')";
                    if (sdata.type == 2) {
                        message = "Customer Updated Successfully";
                    }
                    if (sdata.type == 3) {
                        message = "Supplier Updated Successfully";
                    }
                    obj.prepare();
                    obj.execute((_error, result) => {
                        if (_error == 1) {
                            if (sdata.type == 2) {
                                let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                                obj0.qrysql = "SELECT `idtariff`,`idservice` FROM `user` WHERE idaccount = '" + sdata.idaccount + "'";
                                obj0.prepare();
                                obj0.execute((_errorser, getSer) => {
                                    if (_errorser == 1) {
                                        let obj11 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj11.nonqrysql = "UPDATE `billing_address` SET `first_name`='" + sdata.first_name + "',`last_name`='" + sdata.last_name + "', `contact`='" + sdata.contact_number + "',`email`='" + sdata.email + "', `address1`='" + sdata.address1 + "', `address2`='" + sdata.address2 + "', `city`='" + sdata.city + "', `state`='" + sdata.state + "', `postal_code`='" + sdata.postal_code + "', `country`='" + sdata.country + "' WHERE `idaccount`='" + sdata.idaccount + "'";
                                        obj11.prepare();
                                        obj11.execute((_errBil, resultBil) => { });
                                        let service = getSer[0].idservice;
                                        let idtariff = getSer[0].idtariff;
                                        let planVerify = idtariff ? 'true' : 'false';
                                        let obj12 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj12.nonqrysql = "UPDATE `user` SET  `isEmailVerify`='" + sdata.isEmailVerify + "',`isMobileVerify`='" + sdata.isMobileVerify + "', `isPlan`= '" + planVerify + "', `isAddress`='" + sdata.isAddress + "', `idtariff`='" + idtariff + "',`idservice`='" + service + "' WHERE `idaccount`='" + sdata.idaccount + "'";
                                        obj12.prepare();
                                        obj12.execute((_errorrr, resultt) => {
                                            if (_errorrr == 1) {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ data: resultt[0], message: "Customer Updated Successfully!", status: 201 });
                                                objv.execute();
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ data: resultt, message: "Something Went Wrong With Connection!", status: 502 });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Something Went Wrong With Tarif And Service!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ data: result[0], message: "Profile Updated Successfully!", status: 201 });
                                objv.execute();
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ data: result, message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                }
                // }
                // });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    UserList(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                if (sdata.type == "main") {
                    // obj.nonqrysql = "SELECT u.`username` `user_name`, u.password, u.type, up.firstname `first_name`, up.lastname `last_name`, up.email, up.phone `contact_number`,IF(LENGTH(up.profile_pic)=0 || up.profile_pic='undefined' || up.profile_pic=NULL,CONCAT(CEIL(1+RAND()*7),'.jpg'),up.profile_pic) profile_pic FROM `user` u INNER JOIN user_profile up ON u.iduser=up.iduser WHERE u.idaccount='" + sessdata.idaccount + "' AND u.iduser='" + sessdata.iduser + "' AND u.`type`=4";
                    obj.nonqrysql = "SELECT r.type, rp.firstname `first_name`, rp.lastname `last_name`,rp.email, rp.phone `contact_number`,IF(LENGTH(rp.profile_pic)=0 || rp.profile_pic='undefined' || rp.profile_pic=NULL,CONCAT(CEIL(1+RAND()*7),'.jpg'),rp.profile_pic) profile_pic FROM `reseller` r INNER JOIN reseller_profile rp ON r.iduser=rp.iduser WHERE r.idaccount='" + sessdata.idaccount + "' AND r.iduser='" + sessdata.iduser + "' AND r.`type`=4";
                }
                // profile = details of account
                else if (sdata.type == "profile") {
                    // obj.nonqrysql = "SELECT ac.san,u.`created`,u.`username` `user_name`, u.password, u.type, up.firstname `first_name`, up.lastname `last_name`,up.email, up.phone `contact_number`,IF(LENGTH(up.profile_pic)=0 || up.profile_pic='undefined' || up.profile_pic=NULL,CONCAT(CEIL(1+RAND()*7),'.jpg'),up.profile_pic) profile_pic FROM `user` u INNER JOIN user_profile up  ON u.iduser=up.iduser INNER JOIN `account` ac ON ac.idaccount=u.idaccount WHERE u.reseller_iduser='" + sessdata.iduser + "'";
                    obj.nonqrysql = "SELECT ac.san,u.`created`, u.type, up.firstname `first_name`, up.lastname `last_name`,up.email, up.phone `contact_number`,IF(LENGTH(up.profile_pic)=0 || up.profile_pic='undefined' || up.profile_pic=NULL,CONCAT(CEIL(1+RAND()*7),'.jpg'),up.profile_pic) profile_pic FROM `user` u INNER JOIN user_profile up  ON u.iduser=up.iduser INNER JOIN `account` ac ON ac.idaccount=u.idaccount WHERE u.reseller_iduser='" + sessdata.iduser + "'";
                }
                // detail = profile of user
                else if (sdata.type == "detail") {
                    // obj.nonqrysql = "SELECT u.`username` `user_name`, u.password, u.type, up.firstname `first_name`, up.lastname `last_name`, up.email, up.phone `contact_number`,IF(LENGTH(up.profile_pic)=0 || up.profile_pic='undefined' || up.profile_pic=NULL,CONCAT(CEIL(1+RAND()*7),'.jpg'),up.profile_pic) profile_pic FROM `user` u INNER JOIN user_profile up ON u.iduser=up.iduser WHERE u.idaccount='" + sessdata.idaccount + "' AND u.iduser='" + sessdata.iduser + "' AND u.`type`=4";
                    obj.nonqrysql = "SELECT r.`username` `user_name`, r.type, rp.firstname `first_name`, rp.lastname `last_name`, rp.email, rp.phone `contact_number`,IF(LENGTH(rp.profile_pic)=0 || rp.profile_pic='undefined' || rp.profile_pic=NULL,CONCAT(CEIL(1+RAND()*7),'.jpg'),rp.profile_pic) profile_pic FROM `reseller` r INNER JOIN reseller_profile rp ON r.iduser=rp.iduser WHERE r.idaccount='" + sessdata.idaccount + "' AND r.iduser='" + sessdata.iduser + "' AND r.`type`=4";
                }
                // else if (sdata.type == "edit") {
                //     obj.nonqrysql = "CALL ListUser(" + sdata.idaccount + ", " + sdata.iduser + ", 3)";
                // }
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Profile Fetched Successfully!", status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", status: 502, error: result });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    ListUsers(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                if (sdata.type == "profile") {
                    obj.nonqrysql = "CALL ListUser(" + sdata.idaccount + ", " + sdata.iduser + ", 1)";
                }
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        if (result.length > 0) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ data: result, message: "Profile Fetched Successfully!", status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    singleUser(req, res, next) {
        let sdata = req.query;
        let iduser = req.query.type;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                //obj1.qrysql = "SELECT * FROM `user` WHERE `iduser`='" + iduser + "'";
                // obj1.qrysql = "SELECT u.*,uf.firstname,uf.lastname,uf.email,uf.phone FROM `user`u inner join `user_profile`uf on u.iduser=uf.iduser WHERE u.`iduser`='" + iduser + "'";
                obj1.qrysql = "SELECT r.*,rf.firstname,rf.lastname,rf.email,rf.phone FROM `reseller`r inner join `reseller_profile`rf on r.iduser=rf.iduser WHERE r.`iduser`='" + iduser + "'";
                obj1.prepare();
                obj1.execute((_error1, result1) => {
                    if (_error1 == 1) {
                        let obj = new RawQuery_1.ModelRawQuery(req, res);
                        obj.qrysql = "SELECT b.idaccount,b.address1, b.address2,b.city,b.state,b.contact,b.postal_code,b.country, w.balance,w.credit_limit FROM `billing_address` b JOIN `wallet` w ON w.idaccount = b.idaccount WHERE `b`.idaccount='" + result1[0].idaccount + "'";
                        obj.prepare();
                        obj.execute((_error, result) => {
                            if (_error == 1) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ data: result, data1: result1, message: "Profile Fetched Successfully!", status: 200 });
                                objv.execute();
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Something Went Wrong List User", status: 502, error: _error });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With User", status: 502, error: _error1 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    subCustomerList(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                // if(sessdata.type == '1' || sessdata.type == '12'){
                //     obj.nonqrysql = "select * from user where type='22' AND `idaccount`='"+sdata.idaccount+"'";
                // }
                // else{
                obj.qrysql = "SELECT * FROM `user` WHERE `idaccount`='" + sessdata.idaccount + "'";
                // }
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Sub Customer Fetched!", status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    updateProfilePic(req, res, next) {
        let filePath;
        if (req.file) {
            const fileName = req.file.filename;
            //filePath = req.protocol + '://' + req.get('host') + '/uploads/' + fileName;
            filePath = profile_pic.profile_pic + '/uploads/' + fileName;
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj6 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj6.nonqrysql = "UPDATE `reseller_profile` SET `profile_pic`='" + filePath + "' WHERE `iduser`='" + sessdata.iduser + "'";
                obj6.prepare();
                obj6.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Profile Picture Update Successfully!", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    removeProfilePic(req, res, next) {
        let filePath = req.protocol + '://' + req.get('host') + '/uploads/default.jpg';
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj6 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj6.nonqrysql = "UPDATE `reseller_profile` SET `profile_pic`='" + filePath + "' WHERE `iduser`='" + sessdata.iduser + "'";
                obj6.prepare();
                obj6.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Profile Picture Remove Successfully!", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getGeoCode(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let sdata = req.body.data;
            let options = {
                'method': 'POST',
                'url': 'https://communicationsua.avalara.net/api/v2/geo/geocode',
                'headers': {
                    'client_id': '2221',
                    'Authorization': 'Basic dmlrYXNAZ3ZlbnR1cmUubmV0OmshR3BBdDNKNU5GTUt3UA==',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify([
                    {
                        "ref": "Address Request",
                        "cass": true,
                        "addr": sdata.address1,
                        "city": sdata.city,
                        "st": sdata.state,
                        "zip": sdata.postal_code
                    }
                ])
            };
            request(options, function (error, response) {
                let Data = JSON.parse(response.body);
                if (Data[0].err == undefined && Data[0].pcd !== undefined && Data[0].pcd > 0) {
                    let objv = new RawView_1.RawView(res);
                    // objv.prepare({ message: "Geocode Fetched Successfully!", data: { "giocode": Data[0].pcd }, status: 200 });
                    objv.prepare({ data: { "giocode": Data[0].pcd }, status: 200 });
                    objv.execute();
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: 'Please Enter a Validate Address', status: 502 });
                    objv.execute();
                }
            });
        });
    }
    addBillingAddress(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj0.nonqrysql = "SELECT `idaccount` FROM `billing_address` WHERE `idaccount`='" + sessdata.idaccount + "'";
                obj0.prepare();
                obj0.execute((_erro, datachk) => {
                    if (datachk.length > 0) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Your Address Already Exist!", status: 502 });
                        objv.execute();
                    }
                    else {
                        let rdata = req.body.data;
                        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj.nonqrysql = "INSERT INTO `billing_address` (`idaccount`, `first_name`, `last_name`, `contact`, `email`, `address1`, `address2`, `city`, `state`, `postal_code`, `country`) VALUES ('" + sessdata.idaccount + "', '" + rdata.first_name + "', '" + rdata.last_name + "', '" + rdata.contact + "', '" + rdata.email + "', '" + rdata.address1 + "', '" + rdata.address2 + "', '" + rdata.city + "', '" + rdata.state + "', '" + rdata.postal_code + "', '" + rdata.country + "')";
                        obj.prepare();
                        obj.execute((_error, data) => {
                            if (_error == 1) {
                                let obj4 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj4.nonqrysql = "UPDATE `user` SET `isAddress`='true' WHERE `iduser`='" + sessdata.iduser + "'";
                                obj4.prepare();
                                obj4.execute((_error, user) => {
                                    if (_error == 1) {
                                        let obj5 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj5.nonqrysql = "UPDATE `session` SET `isAddress`='true' WHERE `iduser`='" + sessdata.iduser + "'";
                                        obj5.prepare();
                                        obj5.execute((_err, user) => {
                                            if (_err == 1) {
                                                let obj6 = new RawQuery_1.ModelRawQuery(req, res);
                                                obj6.qrysql = "SELECT * FROM `session` WHERE `authkey`='" + sessdata.authkey + "'";
                                                obj6.prepare();
                                                obj6.execute((_sessError, sessData) => {
                                                    if (_sessError == 1) {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ message: "Address Saved Successfully!", session: sessData, data: data, status: 201 });
                                                        objv.execute();
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ message: "Address Saved Successfully Error With Connection!", status: 502 });
                                                        objv.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ message: "Address Saved Successfully Error With Connection!", status: 502 });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Address Saved Successfully Error With Connection!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getBillingAddress(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT ba.idbilling_address as id_billing_address, ba.first_name, ba.last_name, ba.address1, ba.address2, ba.city, ba.state, ba.postal_code, ba.country, up.firstname, up.lastname, up.phone, up.email FROM billing_address ba RIGHT JOIN user_profile up ON ba.idaccount= (SELECT idaccount from user where iduser='" + sessdata.iduser + "') WHERE up.`iduser` = '" + sessdata.iduser + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            error: 0,
                            data: result,
                            message: msg,
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            error: result,
                            message: "Something Went Wrong With Connection!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getInvoice(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let msg = "";
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT * FROM invoice";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            error: 0,
                            data: result,
                            message: msg,
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            error: result,
                            message: "Something Went Wrong With Connection!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    updateBillingAddress(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, _sessdata) => {
            if (error == 1) {
                let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                let sdata = [];
                sdata = req.body.data;
                let rdata = [];
                rdata = req.body.data;
                obj2.nonqrysql = "UPDATE `billing_address` SET `address1`='" + rdata.address1 + "', `address2`='" + rdata.address2 + "', `city`='" + rdata.city + "', `state`='" + rdata.state + "', `postal_code`='" + rdata.postal_code + "', `country`='" + rdata.country + "' WHERE `idbilling_address` = '" + rdata.idbilling_address + "'";
                obj2.prepare();
                obj2.execute((error, allcamp) => {
                    if (error == 1) {
                        let obj4 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj4.nonqrysql = "UPDATE `user` SET `isAddress`='true' WHERE `iduser`='" + _sessdata.iduser + "'";
                        obj4.prepare();
                        obj4.execute((_error, user) => {
                            if (_error == 1) {
                                let obj5 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj5.nonqrysql = "UPDATE `session` SET `isAddress`='true' WHERE `iduser`='" + _sessdata.iduser + "'";
                                obj5.prepare();
                                obj5.execute((_err, user) => {
                                    if (_err == 1) {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Address Updated Successfully!", data: allcamp, session: _sessdata, status: 201 });
                                        objv.execute();
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Address Updated Successfully Error With Connection!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Address Updated Successfully Error With Connection!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            error: error,
                            message: "Something went wrong with Connection!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    getSupplier(req, res, next) {
        let sdata = req.query;
        if (sdata.type == "detail") {
            super.getMethod(req, res, next);
        }
        else {
            let session = new Session_1.SessionManagment(req, res, next);
            session.GetSession((error, sessdata) => {
                let msg = "";
                if (error == 1) {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "CALL getSupplier(" + sessdata.iduser + ")";
                    obj.prepare();
                    obj.execute((_error, result) => {
                        if (_error == 1) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ data: result, message: msg, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ data: result, message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                }
                else {
                    let objv = new _406_1.Res406(res);
                    objv.prepare(session);
                    objv.execute();
                }
            });
        }
    }
    getSuppliers(req, res, next) {
        let sdata = req.query;
        if (sdata.type == "detail") {
            super.getMethod(req, res, next);
        }
        else {
            let session = new Session_1.SessionManagment(req, res, next);
            session.GetSession((error, _sessdata) => {
                let msg = "";
                if (error == 1) {
                    let obj = new RawQuery_1.ModelRawQuery(req, res);
                    obj.qrysql = "SELECT `password` as `value`, `idaccount` as `key`, `selected`,`did`, `sms`, `voice` FROM `user` WHERE `type`=3";
                    obj.prepare();
                    obj.execute((_error, result) => {
                        if (_error == 1) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ data: result, message: "Supplier Fatched Successfully!", status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ error: _error, message: "Something Went Wrong With Connection!", status: 502 });
                            objv.execute();
                        }
                    });
                }
                else {
                    let objv = new _406_1.Res406(res);
                    objv.prepare(session);
                    objv.execute();
                }
            });
        }
    }
    // Upload File
    UploadDocuments(req, res, next) {
        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
        let sdata = {};
        let session = new Session_1.SessionManagment(req, res, next);
        let msg = "";
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                var sdata = req.body;
                let objfile = new ModelPdfUpload_1.ModelPdfUpload(req, res);
                let fdata = objfile.fileUpload();
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                let fileName = fdata[0].replace(/"/g, '\\"').replace(/'/g, "\\'");
                const filePath = req.protocol + '://' + req.get("host") + "/uploads/" + fileName;
                obj.nonqrysql = "INSERT INTO `upload` (`filename`,`destination_path`,`filetype`,`UserID`)VALUES ('" + fileName + "', '" + filePath + "', '" + req.file.mimetype + "','" + sessdata.iduser + "')";
                obj.prepare();
                obj.execute((_error, lastid) => {
                    let objv = new RawView_1.RawView(res);
                    let filepath = req.file.filename + fileName;
                    objv.prepare({ message: "File Uploaded Successfully.", insertedid: lastid.insertId, filename: filepath });
                    objv.execute();
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /**
     *
     *
     * api
     */
    getCompanyProfile(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT * FROM `company` WHERE `idaccount`='" + sessdata.idaccount + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Company Profile Fetched Successfully!", status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Company Profile Details!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    updateCompanyProfile(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let rdata = [];
                rdata = req.body.data;
                if (rdata.idcompany != "") {
                    let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    // obj2.qrysql = "UPDATE `company` SET `company_name`='" + rdata.company_name + "', `ein`='" + rdata.ein + "', `address`='" + rdata.address + "', `city`='" + rdata.city + "', `state`='" + rdata.state + "', `postal_code`='" + rdata.postal_code + "', `website`='" + rdata.website + "', `country`='" + rdata.country[0].name + "', `email`='" + rdata.email + "', `phone`='" + rdata.phone + "' WHERE `idcompany` = '" + rdata.idcompany + "'";
                    obj2.nonqrysql = "UPDATE `company` SET `company_name`='" + rdata.company_name + "', `ein`='" + rdata.ein + "', `address`='" + rdata.address + "', `city`='" + rdata.city + "', `state`='" + rdata.state + "', `postal_code`='" + rdata.postal_code + "', `website`='" + rdata.website + "', `country`='" + rdata.country + "', `email`='" + rdata.email + "', `phone`='" + rdata.phone + "' WHERE `idcompany` = '" + rdata.idcompany + "'";
                    obj2.prepare();
                    obj2.execute((error, allcamp) => {
                        if (error == 1) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                data: allcamp,
                                message: "Company Profile Updated Successfully!",
                                status: 201
                            });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                error: error,
                                message: "Something went wrong With Company Profile Details!",
                                status: 502
                            });
                            objv.execute();
                        }
                    });
                }
                else {
                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj.nonqrysql = "INSERT INTO `company` (`idaccount`, `company_name`, `ein`, `phone`, `email`, `address`, `city`, `state`, `country`, `postal_code`, `website`) VALUES ('" + sessdata.idaccount + "', '" + rdata.company_name + "', '" + rdata.ein + "', '" + rdata.phone + "', '" + rdata.email + "', '" + rdata.address + "', '" + rdata.city + "', '" + rdata.state + "', '" + rdata.country + "', '" + rdata.postal_code + "', '" + rdata.website + "')";
                    obj.prepare();
                    obj.execute((_error, data) => {
                        if (_error == 1) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Company Profile Saved Successfully!", status: 201 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something went wrong With Company Profile Details!", status: 502 });
                            objv.execute();
                        }
                    });
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    ChangePassword(req, res, next) {
        let sdata = JSON.parse(req.body.data);
        if (sdata.old_password == 'undefined' || sdata.old_password == null) {
            let objv = new RawView_1.RawView(res);
            objv.prepare({ message: "Password Not Found.", "error": 0 });
            objv.execute();
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                //obj0.qrysql = "SELECT `password` FROM `user` WHERE `iduser`='" + sessdata.iduser + "' AND `password`='" + sdata.old_password + "'";
                obj0.qrysql = "SELECT `password` FROM `reseller` WHERE `iduser`='" + sessdata.iduser + "'";
                obj0.prepare();
                obj0.execute((_error, result) => {
                    let pass1 = sdata.old_password;
                    if (result[0] !== undefined && bcrypt.compareSync(pass1, result[0].password)) {
                        let passwd = sdata.confirm_password.trim();
                        let password1 = bcrypt.hashSync(passwd, 10);
                        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj.nonqrysql = "CALL ChangePassword(" + sessdata.idaccount + ", " + sessdata.iduser + ", '" + result[0].password + "','" + password1 + "')";
                        obj.prepare();
                        obj.execute((__error, result) => {
                            if (__error == 1) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    result: result,
                                    message: "Password Changed Successfully!",
                                    status: 201
                                });
                                objv.execute();
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    _error: _error,
                                    message: "Something Went Wrong With Connection!",
                                    status: 502
                                });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "The old password you have entered is incorrect!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    deleteUserSingleData(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, _sessdata) => {
            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
            obj.nonqrysql = "delete from user WHERE iduser = '" + req.query.id + "'";
            obj.prepare();
            obj.execute((_error, lastid) => {
                if (_error == 1) {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "User Deleted Successfully!", data: lastid[0], status: 201 });
                    objv.execute();
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Something Went Wrong With Connection!", error: _error, status: 502 });
                    objv.execute();
                }
            });
        });
    }
    deleteUser(req, res, next) {
        let sdata = [];
        sdata = req.query.id;
        let dData = JSON.parse(sdata);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, _sessdata) => {
            if (error == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "CALL DeleteUser('" + dData.idaccount + "', '" + dData.iduser + "')";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Delete User Successfully!", status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    DeleteCustomerAccount(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let sdata = req.body.data ? req.body.data : req.body;
            let isDeleted = req.body.data && req.body.data !== undefined ? sdata.isDeleted : '1';
            let type = req.body.data && req.body.data !== undefined ? 'panel' : 'swagger';
            let sesidaccount = req.body.data && req.body.data !== undefined ? sdata.sesidaccount : sessdata.idaccount;
            if (error == 1) {
                let Obj = new RawQuery_1.ModelRawQuery(req, res);
                Obj.qrysql = "SELECT * FROM `wallet` WHERE `idaccount`='" + sesidaccount + "' AND `balance` + `credit_limit` >= 0";
                Obj.prepare();
                Obj.execute((crErr, crRes) => {
                    if (crErr == 1 && crRes.length > 0) {
                        // from swagger side hit
                        if (isDeleted == 1 && type == 'swagger') {
                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj.nonqrysql = "UPDATE `session` SET `isDeleted` = '1' WHERE `idaccount` = '" + sesidaccount + "'";
                            obj.prepare();
                            obj.execute((__error, delSessRes) => {
                                console.log("All Session Removed");
                                let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj0.nonqrysql = "UPDATE `api` SET `isDeleted` = '1' WHERE `idaccount` = '" + sesidaccount + "'";
                                obj0.prepare();
                                obj0.execute((___error, delApiRes) => {
                                    console.log("Api Details Removed");
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj1.nonqrysql = "UPDATE `endpoint` SET `isDeleted` = '1' WHERE `idaccount` = '" + sesidaccount + "'";
                                    obj1.prepare();
                                    obj1.execute((____error, result) => {
                                        console.log("All Connection Removed");
                                    });
                                });
                            });
                        }
                        // from panel side hit
                        if (isDeleted == 1 && type == 'panel') {
                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj.nonqrysql = "UPDATE `session` SET `isDeleted` = '1' WHERE `idaccount` = '" + sesidaccount + "'";
                            obj.prepare();
                            obj.execute((__error, delSessRes) => {
                                console.log("All Session Removed");
                                let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj0.nonqrysql = "UPDATE `api` SET `isDeleted` = '1' WHERE `idaccount` = '" + sesidaccount + "'";
                                obj0.prepare();
                                obj0.execute((___error, delApiRes) => {
                                    console.log("Api Details Removed");
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj1.nonqrysql = "UPDATE `endpoint` SET `isDeleted` = '1' WHERE `idaccount` = '" + sesidaccount + "'";
                                    obj1.prepare();
                                    obj1.execute((____error, result) => {
                                        console.log("All Connection Removed");
                                    });
                                });
                            });
                        }
                        // from panel side hit
                        if (isDeleted == 0 && type == 'panel') {
                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj.nonqrysql = "UPDATE `session` SET `isDeleted` = '0' WHERE `idaccount` = '" + sesidaccount + "'";
                            obj.prepare();
                            obj.execute((__error, delSessRes) => {
                                console.log("All Session Restored");
                                let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj0.nonqrysql = "UPDATE `api` SET `isDeleted` = '0' WHERE `idaccount` = '" + sesidaccount + "'";
                                obj0.prepare();
                                obj0.execute((___error, delApiRes) => {
                                    console.log("Api Details Restored");
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj1.nonqrysql = "UPDATE `endpoint` SET `isDeleted` = '0' WHERE `idaccount` = '" + sesidaccount + "'";
                                    obj1.prepare();
                                    obj1.execute((____error, result) => {
                                        console.log("All Connection Restored");
                                    });
                                });
                            });
                        }
                        // updation for both side (panel hit and swagger hit)
                        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj.nonqrysql = "UPDATE `user` SET `is_deleted` = '" + isDeleted + "' WHERE `idaccount` = '" + sesidaccount + "'";
                        obj.prepare();
                        obj.execute((_error, result) => {
                            if (_error == 1) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ data: result, message: "Account And Other Data Deleted!", status: 201 });
                                objv.execute();
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ data: result, message: "Something Went Wrong With Delete Customer!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Account Balance is Low!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    DeleteAccount(req, res, next) {
        let sdata = req.body.data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let allDID = [];
                let allDIDId = [];
                let allBrandId = [];
                let allCampaign = [];
                let allIdUsers = [];
                // Delete DID
                let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                obj0.qrysql = "SELECT `iddid`,`did` FROM `did_buy` WHERE `account_id`='" + sdata.sesidaccount + "' AND `disconnect_did_status`='1'";
                obj0.prepare();
                obj0.execute((_errorDID, resultDID) => {
                    if (_errorDID == 1) {
                        for (let d of resultDID) {
                            allDIDId.push(d.iddid);
                            allDID.push(d.did);
                        }
                        if (allDIDId.length > 0) {
                            let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj1.nonqrysql = "UPDATE `did_buy` SET `disconnect_did_status` = '2' WHERE `iddid` IN(" + allDIDId + ")";
                            obj1.prepare();
                            obj1.execute((_error, result) => {
                                if (_error == 1) {
                                    console.log("All DID Removed", allDIDId);
                                }
                            });
                        }
                    }
                });
                let obju = new RawQuery_1.ModelRawQuery(req, res);
                obju.qrysql = "SELECT `iduser` from user WHERE `idaccount`='" + sdata.sesidaccount + "'";
                obju.prepare();
                obju.execute((_uerror, iduserRes) => {
                    if (iduserRes.length > 0) {
                        for (let u of iduserRes) {
                            allIdUsers.push(u.iduser);
                        }
                        if (allIdUsers.length > 0) {
                            // Delete Campaign
                            let objc = new RawQuery_1.ModelRawQuery(req, res);
                            objc.qrysql = "SELECT `id_campaign` from campaign WHERE `deleted`= 0 AND `iduser` IN(" + allIdUsers + ")";
                            objc.prepare();
                            objc.execute((_cerror, campaignRes) => {
                                if (campaignRes.length > 0) {
                                    for (let c of campaignRes) {
                                        allCampaign.push(c.id_campaign);
                                    }
                                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj1.nonqrysql = "UPDATE `campaign` SET `deleted` = '2' WHERE `id_campaign` IN(" + allCampaign + ")";
                                    obj1.prepare();
                                    obj1.execute((_errorCamp, resultCamp) => {
                                        if (resultCamp.length > 0) {
                                            console.log("All Campaign Removed", allCampaign);
                                        }
                                    });
                                }
                            });
                            // Delete Brand
                            let objb = new RawQuery_1.ModelRawQuery(req, res);
                            objb.qrysql = "SELECT `idbrand` from brand WHERE `deleted`= 0 AND `iduser` IN(" + allIdUsers + ")";
                            objb.prepare();
                            objb.execute((_errB, brandRe) => {
                                if (brandRe.length > 0) {
                                    for (let b of brandRe) {
                                        allBrandId.push(b.idbrand);
                                    }
                                    let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj2.nonqrysql = "UPDATE `brand` SET `deleted` = '2' WHERE `idbrand` IN(" + allBrandId + ")";
                                    obj2.prepare();
                                    obj2.execute((_errorBrand, resultBrand) => {
                                        if (resultBrand.length > 0) {
                                            console.log("All Brand Removed", allBrandId);
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
                // add here delete feature for session,api and connection.
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "DELETE FROM `session` WHERE `idaccount`='" + sdata.sesidaccount + "' AND `isDeleted` = '1'";
                obj.prepare();
                obj.execute((__error, delSessRes) => {
                    console.log("All Session Remove");
                    let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj0.nonqrysql = "DELETE FROM `api` WHERE `idaccount`='" + sdata.sesidaccount + "' AND `isDeleted` = '1'";
                    obj0.prepare();
                    obj0.execute((___error, delApiRes) => {
                        console.log("Api Details Remove");
                        let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj1.nonqrysql = "DELETE FROM `endpoint` WHERE `idaccount`='" + sdata.sesidaccount + "' AND `isDeleted` = '1'";
                        obj1.prepare();
                        obj1.execute((____error, result) => {
                            console.log("All Connection Remove");
                        });
                    });
                });
                // closed here
                let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj2.nonqrysql = "UPDATE `user` SET `is_deleted` = '" + sdata.isDeleted + "' WHERE `idaccount` = '" + sdata.sesidaccount + "'";
                obj2.prepare();
                obj2.execute((_errorDEL, resultDEL) => {
                    if (_errorDEL == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: allDID, message: "Account Successfully Deleted!", status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Release DID From Account Delete Process!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    // public TaxAuthentication(req: Request, res: Response, next: NextFunction) {
    //     console.log(req.body.data);
    //     let sdata = req.body.data
    //     var request = require('request');
    //     var options = {
    //         'method': 'POST',
    //         'url': sdata.url,
    //         'headers': {
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify(sdata.data)
    //     };
    //     request(options, function (error: any, response: any) {
    //         console.log(response.body)
    //         let objv = new RawView(res);
    //         objv.prepare(response.body);
    //         objv.execute();
    //     });
    // }
    TaxCalculation(req, res, _next) {
        let sdata = req.body.data;
        var request = require('request');
        var options = {
            'method': 'POST',
            'url': 'http://localhost/avatax/php/trunk/charges/cal_taxaxtion',
            'headers': {
                'Content-Type': 'application/json',
                'Cookie': 'AuthToken=' + sdata.data.token
            },
            body: JSON.stringify(sdata.data)
        };
        request(options, function (_error, response) {
            let objv = new RawView_1.RawView(res);
            objv.prepare(response.body);
            objv.execute();
        });
    }
    detailsCDR(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, _sessdata) => {
            let obj = new RawQuery_1.ModelRawQuery(req, res);
            obj.qrysql = "SELECT * FROM cdr WHERE date1 = '" + sdata.from_date + "' AND date2= '" + sdata.to_date + "' AND ani= '" + sdata.from_ani + "' AND did= '" + sdata.to_did + "' AND callid= '" + sdata.call_id + "' ";
            obj.prepare();
            obj.execute((_error, lastid) => {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Fetched Data Successfully!", data: lastid[0] });
                objv.execute();
            });
        });
    }
    apiToken(req, res, next) {
        const key = Str.random(30);
        var rdata;
        rdata = req.body.data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                obj1.qrysql = "SELECT * FROM `api` where `name` = '" + rdata.name + "' AND `iduser` = '" + rdata.user + "'";
                obj1.prepare();
                obj1.execute((_error, getConn) => {
                    if (getConn[0]) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Token Already Exists at This Account!",
                            status: 404
                        });
                        objv.execute();
                    }
                    else {
                        let iduser = sessdata.type == 2 ? rdata.user : sessdata.iduser;
                        let idaccount = sessdata.type == 2 ? rdata.account : sessdata.idaccount;
                        let idtariff = sessdata.type == 2 ? rdata.idtariff : sessdata.idtariff;
                        let obj = new RawQuery_1.ModelRawQuery(req, res);
                        obj.qrysql = "SELECT `iduser`, `idaccount`, `username`, `password`, `type`, `default`, `idtariff`, `isEmailVerify`, `isMobileVerify`, `isAddress`, `isPlan` FROM `user` WHERE `iduser` = '" + iduser + "'";
                        obj.prepare();
                        obj.execute((__error, getUser) => {
                            if (__error == 1 && getUser.length > 0) {
                                let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj2.nonqrysql = "INSERT INTO `session` (`iduser`, `idaccount`, `username`,`password`, `type`, `default`, `idtariff`, `authkey`, `status`, `isEmailVerify`, `isMobileVerify`, `idapi`, `isAddress`, `isPlan`, `tz_diff`, `server_time`, `client_time`, `sessionType`) VALUES('" + iduser + "', '" + idaccount + "', '" + getUser[0].username + "', '" + getUser[0].password + "', '" + getUser[0].type + "', '" + getUser[0].default + "', '" + idtariff + "', '" + key + "', '" + sessdata.status + "', '" + getUser[0].isEmailVerify + "', '" + getUser[0].isMobileVerify + "', '" + sessdata.idapi + "', '" + getUser[0].isAddress + "', '" + getUser[0].isPlan + "', '" + sessdata.tz_diff + "', '" + sessdata.server_time + "', '" + sessdata.client_time + "', 'API')";
                                obj2.prepare();
                                obj2.execute((___error, resultSess) => {
                                    if (___error == 1) {
                                        let obj5 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj5.nonqrysql = "INSERT INTO `api` (`idaccount`, `iduser`, `idtariff`, `name`, `key`, `path`) VALUES('" + idaccount + "', '" + iduser + "', '" + idtariff + "' ,'" + rdata.name + "', '" + key + "', '" + rdata.status + "')";
                                        obj5.prepare();
                                        obj5.execute((_error, result) => {
                                            if (_error == 1) {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({
                                                    data: result,
                                                    message: "Token Saved Successfully!",
                                                    status: 201
                                                });
                                                objv.execute();
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({
                                                    data: result,
                                                    message: "Something Went Wrong With API Token!",
                                                    status: 502
                                                });
                                                objv.execute();
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    getApiToken(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let user;
                let obj5 = new RawQuery_1.ModelRawQuery(req, res);
                if (sessdata.type == 2) {
                    obj5.qrysql = "select * from `api` where `idaccount`='" + sessdata.idaccount + "'";
                }
                else if (sessdata.type == 22) {
                    obj5.qrysql = "select * from `api` where `iduser`='" + sessdata.iduser + "'";
                }
                else {
                    obj5.qrysql = "select * from `api` where `idaccount`='" + sessdata.idaccount + "'";
                }
                obj5.prepare();
                obj5.execute((_error, result) => {
                    if (_error == 1) {
                        if (result.length > 0) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                data: result,
                                message: "Token Fetched Successfully!",
                                status: 200
                            });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                data: result,
                                message: "No Data Found!",
                                status: 404
                            });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Something Went Wrong With Connection!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    deleteApiToken(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, _sessdata) => {
            if (error == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "delete from `api` WHERE `idapi` = '" + req.query.id + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Api Key Deleted Successfully!", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", data: result, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    saveTheme(req, res, next) {
        var rdata = [];
        rdata = req.body.data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj2.filter = null;
                obj2.nonqrysql = "INSERT into `theme` (`idaccount`, `brandName`, `domain`, `customLogo`, `email`, `phone`, `support_url`, `header_color`, `navbar_color`, `sidebar_color`, `ssl_certificate`, `ssl_key`) VALUES('" + sessdata.idaccount + "', '" + rdata.brandName + "', '" + rdata.domain + "', '" + rdata.custom_logo + "', '" + rdata.email + "', '" + rdata.phone + "', '" + rdata.support_url + "', '" + rdata.header_color + "', '" + rdata.navbar_color + "', '" + rdata.sidebar_color + "', '" + rdata.ssl_certificate + "', '" + rdata.ssl_key + "')";
                obj2.prepare();
                obj2.execute((_error, result) => {
                    if (result) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Theme Saved Successfully!" });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Successfully!" });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No Session Data There");
                objv.execute();
            }
        });
    }
    updateTheme(req, res, next) {
        let filePath;
        let rdata = [];
        rdata = JSON.parse(req.body.data);
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                if (req.file) {
                    const fileName = req.file.filename;
                    filePath = "https://api.signalmash.com/uploads/" + fileName;
                }
                else if (rdata.logo == undefined || rdata.logo == null) {
                    filePath = "./assets/img/logo.png";
                }
                let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj2.filter = null;
                obj2.nonqrysql = "UPDATE `theme` SET `brandName`='" + rdata.brandName + "', `domain`='" + rdata.domain + "', `customLogo`='" + filePath + "', `email`='" + rdata.email + "', `phone`='" + rdata.phone + "', `support_url`='" + rdata.support_url + "', `header_color`='" + rdata.header_color + "', `navbar_color`='" + rdata.navbar_color + "', `sidebar_color`='" + rdata.sidebar_color + "', `ssl_certificate`='" + rdata.ssl_certificate + "', `ssl_key`='" + rdata.ssl_key + "' WHERE `id_theme`='" + rdata.id_theme + "'";
                obj2.prepare();
                obj2.execute((error, allcamp) => {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({
                        error: 0,
                        data: allcamp,
                        message: "Theme Updated Successfully"
                    });
                    objv.execute();
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    getThemes(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            let obj = new RawQuery_1.ModelRawQuery(req, res);
            obj.qrysql = "SELECT * FROM `theme` WHERE `idaccount` = '" + sessdata.idaccount + "'";
            obj.prepare();
            obj.execute((_error, result) => {
                if (result.length > 0) {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Theme data Fetched!", data: result });
                    objv.execute();
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "NO Data Found!" });
                    objv.execute();
                }
            });
        });
    }
    getTheme(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            let obj = new RawQuery_1.ModelRawQuery(req, res);
            obj.qrysql = "select * from theme where id_theme='" + req.query.type + "' AND idaccount = '" + sessdata.idaccount + "'";
            obj.prepare();
            obj.execute((_error, result) => {
                if (_error == 1) {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Theme data Fetched!", data: result });
                    objv.execute();
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Something Went Wrong!" });
                    objv.execute();
                }
            });
        });
    }
    deleteTheme(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
            obj.nonqrysql = "delete from `theme` WHERE `id_theme` = '" + req.query.id + "' AND idaccount = '" + sessdata.idaccount + "'";
            obj.prepare();
            obj.execute((_error, result) => {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Theme Deleted Successfully!", data: result });
                objv.execute();
            });
        });
    }
    saveOtp(req, res, next) {
        let sdata = req.body;
        let otp = Math.floor(100000 + Math.random() * 900000);
        sdata.otp = otp;
        // sdata.BODY = sdata.BODY + otp;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj4 = new RawQuery_1.ModelRawQuery(req, res);
                // obj4.qrysql = "SELECT * FROM `user_profile` WHERE `iduser`='" + sessdata.iduser + "'";
                obj4.qrysql = "SELECT `firstname`,`lastname` FROM `reseller_profile` WHERE `iduser`='" + sessdata.iduser + "'";
                obj4.prepare();
                obj4.execute((_error, user) => {
                    let getUser = user[0];
                    if (error == 1) {
                        let obj5 = new RawQuery_1.ModelRawQuery(req, res);
                        // obj5.qrysql = "SELECT * FROM `sms_template` WHERE type='mobile_verification'";
                        obj5.qrysql = "SELECT `body` FROM `sms_template` WHERE type='mobile_verification'";
                        obj5.prepare();
                        obj5.execute((emlErr, emlRes) => {
                            if (emlErr == 1 && emlRes.length > 0) {
                                let BODY = emlRes[0].body;
                                BODY = BODY.replace(/{FIRST_NAME}/g, getUser.firstname);
                                BODY = BODY.replace(/{LAST_NAME}/g, getUser.lastname);
                                BODY = BODY.replace(/{OTP}/g, sdata.otp);
                                var headers = {
                                    'accept': '*/*',
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                };
                                var dataString = 'Username=Gventure_test&Password=qzcLAGsUh-V8J57xNrFOJiBpZQCHEz';
                                var options = {
                                    url: 'https://api.signalmash.com/apilogin',
                                    method: 'POST',
                                    headers: headers,
                                    body: dataString
                                };
                                request(options, (login_error, login_resp) => {
                                    let auth_key;
                                    let key = Str.random(30);
                                    if (login_resp !== undefined) {
                                        let data = JSON.parse(login_resp.body);
                                        auth_key = data.session;
                                        var headers = {
                                            'accept': '*/*',
                                            'Authorization': auth_key,
                                            'Content-Type': 'application/x-www-form-urlencoded'
                                        };
                                        var dataString = 'FROM=' + sdata.FROM.trim() + '&TO=' + sdata.TO.trim() + '&BODY=' + BODY + '&Connection=&OutboundSMS=';
                                        var options = {
                                            url: 'https://api.signalmash.com/sms',
                                            method: 'POST',
                                            headers: headers,
                                            body: dataString
                                        };
                                        // url: 'https://api.signalmash.com/sms',
                                        request(options, (sms_err, sms_responce) => {
                                            let sms_resp = JSON.parse(sms_responce.body);
                                            if (sms_resp.status == 201) {
                                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                obj.nonqrysql = "INSERT INTO `two_factor_auth` (`iduser`, `otp`, `from`, `to`, `session_id`) VALUES('" + sessdata.iduser + "', '" + sdata.otp + "', '" + sdata.FROM + "', '" + sdata.TO + "', '" + key + "')";
                                                obj.prepare();
                                                obj.execute((mdr_err, mdr_resp) => {
                                                    if (mdr_err == 1) {
                                                        let obj = new RawView_1.RawView(res);
                                                        obj.prepare({ result: "Success", data: mdr_resp, message: "OTP Sent Successfully", status: 201 });
                                                        obj.execute();
                                                    }
                                                    else {
                                                        let obj = new RawView_1.RawView(res);
                                                        obj.prepare({ result: "Failed", message: "Something Went Wrong with Connection!", status: 502 });
                                                        obj.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let obj = new RawView_1.RawView(res);
                                                obj.prepare({ message: sms_resp.message, status: 503 });
                                                obj.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let obj = new RawView_1.RawView(res);
                                        obj.prepare({ message: login_error, status: 502 });
                                        obj.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare("SMS Template not Fateched Successfully!");
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare("User not Fateched Successfully!");
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    verifyOtp(req, res, next) {
        let sdata = req.body;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            let obj = new RawQuery_1.ModelRawQuery(req, res);
            // obj.qrysql = "SELECT `otp` FROM `two_factor_auth` WHERE `iduser` = '" + sessdata.iduser + "' AND `otp`='" + sdata.otp + "' AND UNIX_TIMESTAMP()-UNIX_TIMESTAMP(created)<300";
            obj.qrysql = "SELECT `otp` FROM `two_factor_auth` WHERE `iduser` = '" + sessdata.iduser + "' AND UNIX_TIMESTAMP()-UNIX_TIMESTAMP(created)<300 ORDER BY id DESC LIMIT 1";
            obj.prepare();
            obj.execute((error, getEmail) => {
                if (error == 1) {
                    if (getEmail.length > 0 && getEmail[0].otp == sdata.otp) {
                        let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj1.nonqrysql = "UPDATE `reseller` SET `isEmailVerify`= 'true', `isMobileVerify`='true' WHERE `iduser`='" + sessdata.iduser + "'";
                        obj1.prepare();
                        obj1.execute((_error, success) => {
                            if (_error == 1) {
                                let obj5 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj5.nonqrysql = "UPDATE `session` SET `isMobileVerify`='true' WHERE `iduser`='" + sessdata.iduser + "'";
                                obj5.prepare();
                                obj5.execute((_sessErr, sessRes) => {
                                    if (_sessErr == 1) {
                                        let obj6 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj6.nonqrysql = "UPDATE `reseller_profile` SET `phone`='" + sdata.TO + "' WHERE `iduser`='" + sessdata.iduser + "'";
                                        obj6.prepare();
                                        obj6.execute((_sessError, sessData) => {
                                            if (_sessError == 1) {
                                                let obj7 = new RawQuery_1.ModelRawQuery(req, res);
                                                // obj7.qrysql = "SELECT * FROM `session` WHERE `authkey`='" + sessdata.authkey + "'";
                                                obj7.qrysql = "SELECT `iduser`, `idaccount`, `username`, `type`, `default`, `idtariff`, `authkey`, `status`, `isEmailVerify`, `isMobileVerify`, `idapi`, `isAddress`, `isPlan`,`isCard`,`newUser_status`, `tz_diff`, `server_time`, `client_time` FROM `session` WHERE `authkey`='" + sessdata.authkey + "'";
                                                obj7.prepare();
                                                obj7.execute((sError, sData) => {
                                                    if (sError == 1) {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({
                                                            message: "OTP Verified!",
                                                            status: 200,
                                                            session: sData
                                                        });
                                                        objv.execute();
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({
                                                            message: "OTP Verified Error With Connection!",
                                                            status: 502
                                                        });
                                                        objv.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({
                                                    message: "Mobile Number Not Verified!",
                                                    status: 500
                                                });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({
                                            errMessage: "Mobile Number Not Verified!",
                                            status: 502
                                        });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    message: "Mobile Number Not Verified!",
                                    status: 502
                                });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "You Have Enter Wrong OTP!",
                            status: 502
                        });
                        objv.execute();
                    }
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({
                        message: "Something Went Wrong With Connection!",
                        status: 502
                    });
                    objv.execute();
                }
            });
        });
    }
    resendEmail(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let secret = Str.random(15);
                let validationKey = jwt.sign({
                    exp: Math.floor(Date.now() / 1000) + (60 * 60),
                    data: sessdata.email + sessdata.password
                }, secret);
                let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj3.nonqrysql = "UPDATE `reseller` SET `validationKey`='" + validationKey + "', `secret`='" + secret + "' WHERE `iduser`='" + sessdata.iduser + "'";
                obj3.prepare();
                obj3.execute((_err, __result) => {
                    if (_err == 1) {
                        let obj4 = new RawQuery_1.ModelRawQuery(req, res);
                        obj4.qrysql = "SELECT * FROM `reseller_profile` WHERE `iduser`='" + sessdata.iduser + "'";
                        obj4.prepare();
                        obj4.execute((_error, user) => {
                            let getUser = user[0];
                            if (_err == 1) {
                                let obj5 = new RawQuery_1.ModelRawQuery(req, res);
                                obj5.qrysql = "SELECT * FROM `email_template` WHERE type='email_verification'";
                                obj5.prepare();
                                obj5.execute((emlErr, emlRes) => {
                                    if (emlErr == 1) {
                                        if (emlRes.length > 0) {
                                            let tmpData = emlRes[0].template;
                                            tmpData = tmpData.replace(/{FIRST_NAME}/g, getUser.firstname);
                                            tmpData = tmpData.replace(/{LAST_NAME}/g, getUser.lastname);
                                            tmpData = tmpData.replace(/{VALIDATION_KEY}/g, validationKey);
                                            // var smtpTransport = nodemailer.createTransport({
                                            //     service: "gmail",
                                            //     host: "smtp.gmail.com",
                                            //     port: 587,
                                            //     secure: true,
                                            //     auth: {
                                            //         user: "donotreply@nglcommunications.com",
                                            //         pass: "yr%5V9GB"
                                            //     }
                                            // });
                                            // var mailOptions = {
                                            //     from: 'Signalmash <donotreply@signalmash.com>',
                                            //     to: getUser.email,
                                            //     usernmae: getUser.username,
                                            //     email: getUser.email,
                                            //     subject: `${emlRes[0].subject}`,
                                            //     text: "Thank You For Registration",
                                            //     html: `${tmpData}`
                                            // }
                                            // smtpTransport.sendMail(mailOptions, (_emailError: any, emailRes: any) => {
                                            //     if (_emailError) {
                                            // let obj1 = new ModelRawNonQuery(req, res);
                                            // obj1.nonqrysql = "INSERT INTO `email_send`(`iduser`, `idaccount`,`from`,`to`, `subject`,`text`,`html`,`type`,`status`,`cc`,`bcc`) VALUES ('" + sessdata.iduser + "','" + sessdata.idaccount + "','" + FromEmail + "','" + getUser.email + "', '" + parseBody(emlRes[0].subject) + "','Thank You For Registration', '" + parseBody(tmpData) + "','Mail Send for Registration','','" + emlRes[0].cc + "','" + emlRes[0].bcc + "')";
                                            // obj1.prepare();
                                            // obj1.execute((_err: any, __result: any) => {
                                            let logPayload = {
                                                funDetail: {
                                                    tableName: 'email_send',
                                                    functionName: 'signUp',
                                                    logName: 'mail'
                                                },
                                                data: {
                                                    iduser: sessdata.iduser,
                                                    idaccount: sessdata.idaccount,
                                                    bcc: emlRes[0].bcc,
                                                    from: FromEmail,
                                                    to: getUser.email,
                                                    subject: (0, markError_1.parseBody)(emlRes[0].subject),
                                                    text: 'Thank You For Registration',
                                                    html: (0, markError_1.parseBody)(tmpData),
                                                    type: 'Mail Send for Registration',
                                                    cc: emlRes[0].cc,
                                                }
                                            };
                                            insertdid.insertLog(req, res, logPayload, (log_error, did_log) => {
                                                if (log_error == 1) {
                                                    let objv = new RawView_1.RawView(res);
                                                    objv.prepare({ status: 401, errMessage: "Opps Email Not Sent!", error: log_error });
                                                    objv.execute();
                                                }
                                                else {
                                                    let objv = new RawView_1.RawView(res);
                                                    objv.prepare({ iduser: sessdata.iduser, status: 201, data: did_log, message: "Email Send Succesfully!" });
                                                    objv.execute();
                                                }
                                            });
                                        }
                                        else {
                                            let objv = new RawView_1.RawView(res);
                                            objv.prepare({ status: 401, errMessage: "Templating Data Not Found!" });
                                            objv.execute();
                                        }
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ errMessage: "Something Went Wrong with DB!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ errMessage: "Something Went Wrong with DB!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ errMessage: "Something Went Wrong with DB!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    updateTariff(req, res, next) {
        let sdata = req.body.data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj4 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                //obj4.nonqrysql = "UPDATE `user` LEFT JOIN `account` ON `user`.`idaccount`=`account`.`idaccount` SET `idtariff`='" + sdata.tariff1 + "', `idtariff1`='" + sdata.tariff1 + "', `isPlan`='true' WHERE `iduser`='" + sessdata.iduser + "'";
                obj4.nonqrysql = "UPDATE `user` LEFT JOIN `account` ON `user`.`idaccount`=`account`.`idaccount` SET `idtariff`='" + sdata.tariff1 + "', `idtariff1`='" + sdata.tariff1 + "', `isPlan`='true' WHERE `user`.`idaccount`='" + sessdata.idaccount + "'";
                obj4.prepare();
                obj4.execute((_error, user) => {
                    if (_error == 1) {
                        let obj5 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        //obj5.nonqrysql = "UPDATE `session` SET `isPlan`='true', `idtariff`='" + sdata.tariff1 + "' WHERE `iduser`='" + sessdata.iduser + "'";
                        obj5.nonqrysql = "UPDATE `session` SET `isPlan`='true', `idtariff`='" + sdata.tariff1 + "' WHERE `idaccount`='" + sessdata.idaccount + "'";
                        obj5.prepare();
                        obj5.execute((_err, user) => {
                            if (_err == 1) {
                                let currSess = server_1.sessiondata.get(req.headers.authorization);
                                currSess.idtariff = sdata.tariff1;
                                currSess.isPlan = "true";
                                server_1.sessiondata.set(req.headers.authorization, currSess);
                                let obj6 = new RawQuery_1.ModelRawQuery(req, res);
                                obj6.qrysql = "SELECT * FROM `session` WHERE `authkey`='" + sessdata.authkey + "'";
                                obj6.prepare();
                                obj6.execute((seserr, sessionData) => {
                                    if (seserr == 1) {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Tariff Updated Successfully!", status: 201, session: sessionData });
                                        objv.execute();
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Tariff Updated Error With Connection!", status: 502, error: sessionData });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Tariff Updated Error With Connection! ", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    currentSession(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT * FROM `session` WHERE `authkey`='" + req.query.authkey + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Session Fetched Successfully!", status: 200, session: result });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Session Not Fetched DB Error!", status: 502, error: sessdata });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Session Trying to access", status: 401 });
                objv.execute();
            }
        });
    }
    /**
     * To get the list of TimeZones
     */
    GetTimeZones(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let objv = new RawView_1.RawView(res);
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT id, label utc FROM `tbl_timezones`;";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (error == 1) {
                        result = result || [];
                        objv.prepare({
                            error: 0,
                            message: "Records fetched successfully.",
                            data: result
                        });
                        objv.execute();
                    }
                    else {
                        objv.prepare({
                            error: 1,
                            message: "Something Went Wrong!"
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    /**
     * To get the user's TimeZone
     */
    GetUserTimeZone(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let iduser = sessdata.iduser;
                let iQry = "SELECT a.id, a.id_timezone, b.label utc FROM `tbl_timezone_config` a\n";
                iQry += "INNER JOIN `tbl_timezones` b ON b.id=a.id_timezone\n";
                iQry += "WHERE a.id_user=" + iduser + ";";
                let objv = new RawView_1.RawView(res);
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = iQry;
                obj.prepare();
                obj.execute((_error, result) => {
                    if (error == 1) {
                        result = Array.isArray(result) && result.length > 0 ? result[0] : null;
                        objv.prepare({
                            error: 0,
                            message: "Record fetched successfully.",
                            data: result
                        });
                        objv.execute();
                    }
                    else {
                        objv.prepare({
                            error: 1,
                            message: "Something Went Wrong!"
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    /**
     * To update the user's TimeZone
     */
    UpdateUserTimeZone(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let rdata = req.body.data;
                let objv = new RawView_1.RawView(res);
                if (typeof rdata.timezone != 'undefined' && rdata.timezone) {
                    let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj1.nonqrysql = "REPLACE INTO `tbl_timezone_config`(id_timezone, id_user) VALUES(" + rdata.timezone + ", " + sessdata.iduser + ");";
                    obj1.prepare();
                    obj1.execute((error, result) => {
                        if (error == 1) {
                            /**
                             * Update the TimeZone in user's session data
                             */
                            let obj2 = new RawQuery_1.ModelRawQuery(req, res);
                            obj2.qrysql = "SELECT a.utc client_time FROM tbl_timezones a WHERE a.id=" + rdata.timezone + ";";
                            obj2.prepare();
                            obj2.execute((error, result) => {
                                if (error == 1 && Array.isArray(result) && result.length > 0) {
                                    let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj3.nonqrysql = "UPDATE `session` SET `client_time`='" + result[0].client_time + "' WHERE `authkey`='" + sessdata.authkey + "';";
                                    obj3.prepare();
                                    obj3.execute((error, result2) => {
                                        sessdata.client_time = result[0].client_time;
                                        server_1.sessiondata.set(sessdata.authkey, sessdata);
                                    });
                                }
                            });
                            objv.prepare({
                                error: 0,
                                message: "Successfully saved."
                            });
                            objv.execute();
                        }
                        else {
                            objv.prepare({
                                error: 1,
                                message: "Something Went Wrong!"
                            });
                            objv.execute();
                        }
                    });
                }
                else {
                    objv.prepare({
                        error: 1,
                        message: "Invalid data!"
                    });
                    objv.execute();
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    /**************************
    *  Forgot Password start  *
    **************************/
    sendMailForForgetPass(req, res, next) {
        let email = req.body.data;
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        obj.qrysql = "SELECT rp.email, rp.firstname, rp.lastname, r.username FROM reseller_profile rp JOIN `reseller` r ON rp.iduser=r.iduser WHERE rp.`email`='" + email + "'  ";
        obj.prepare();
        obj.execute((_error, user) => {
            if (_error == 1) {
                if (user.length > 0) {
                    let getUser = user[0];
                    let obj4 = new RawQuery_1.ModelRawQuery(req, res);
                    obj4.qrysql = "SELECT template, subject FROM `email_template` WHERE type='forgot_password'";
                    obj4.prepare();
                    obj4.execute((emlErr, emlRes) => {
                        if (emlErr == 1) {
                            if (emlRes.length > 0) {
                                let secret = Str.random(15);
                                let validationKey = jwt.sign({
                                    exp: Math.floor(Date.now() / 1000) + (60 * 60),
                                    data: email
                                }, secret);
                                let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj3.nonqrysql = "UPDATE `reseller` SET `validationKey`='" + validationKey + "',`isResetPassword` = 'true'  WHERE `username`='" + getUser.username + "'";
                                obj3.prepare();
                                obj3.execute((_uperr, __result) => {
                                    if (_uperr == 1) {
                                        let tmpData = emlRes[0].template;
                                        tmpData = tmpData.replace(/{FIRST_NAME}/g, getUser.firstname);
                                        tmpData = tmpData.replace(/{LAST_NAME}/g, getUser.lastname);
                                        tmpData = tmpData.replace(/{TYPE}/g, 'Reseller');
                                        tmpData = tmpData.replace(/{URL}/g, templateURL.URL + '/#/password/reset-password/' + validationKey);
                                        // var smtpTransport = nodemailer.createTransport({
                                        //     service: "gmail",
                                        //     host: "smtp.gmail.com",
                                        //     port: 587,
                                        //     secure: true,
                                        //     auth: {
                                        //         user: "donotreply@nglcommunications.com",
                                        //         pass: "yr%5V9GB"
                                        //     }
                                        // });
                                        // var mailOptions = {
                                        //     from: 'Signalmash <donotreply@signalmash.com>',
                                        //     to: getUser.email,
                                        //     usernmae: getUser.username,
                                        //     email: getUser.email,
                                        //     subject: `${emlRes[0].subject}`,
                                        //     text: "Thank You For Registration",
                                        //     html: `${tmpData}`
                                        // }
                                        // smtpTransport.sendMail(mailOptions, (_emailError: any, emailRes: any) => {
                                        //     if (_emailError) {
                                        // let obj1 = new ModelRawNonQuery(req, res);
                                        // obj1.nonqrysql = "INSERT INTO `email_send`(`iduser`, `idaccount`,`from`,`to`, `subject`,`text`,`html`,`type`,`status`,`cc`,`bcc`) VALUES ('','','" + FromEmail + "','" + getUser.email + "', '" + parseBody(emlRes[0].subject) + "','Thank You For Registration', '" + parseBody(tmpData) + "','Mail Send for Registration','','" + emlRes[0].cc + "','" + emlRes[0].bcc + "')";
                                        // obj1.prepare();
                                        // obj1.execute((_err: any, __result: any) => {
                                        let logPayload = {
                                            funDetail: {
                                                tableName: 'email_send',
                                                functionName: 'sendMailForForgetPass',
                                                logName: 'mail'
                                            },
                                            data: {
                                                bcc: emlRes[0].bcc,
                                                from: FromEmail,
                                                to: getUser.email,
                                                subject: (0, markError_1.parseBody)(emlRes[0].subject),
                                                text: 'Thank You For Registration',
                                                html: (0, markError_1.parseBody)(tmpData),
                                                type: 'Mail Send for Registration',
                                                cc: emlRes[0].cc,
                                            }
                                        };
                                        insertdid.insertLog(req, res, logPayload, (log_error, did_log) => {
                                            if (log_error == 1) {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ status: 401, message: "Opps Email Not Sent!", error: log_error });
                                                objv.execute();
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ status: 201, message: "Password Reset Email Sent.Please check your email and follow the Included link to finish resetting your password.", did_log });
                                                objv.execute();
                                            }
                                        });
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Something went Wrong!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Verification Email not Send!", status: 502 });
                                objv.execute();
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Error With Fetching Email Data!", status: 502 });
                            objv.execute();
                        }
                    });
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ status: 404, message: "Email Not Found!" });
                    objv.execute();
                }
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ status: 502, message: "Something Went Wrong to Fetch Email!" });
                objv.execute();
            }
        });
    }
    VerifyToken(req, res, next) {
        let key = req.query.type;
        let obj = new RawQuery_1.ModelRawQuery(req, res);
        obj.qrysql = "SELECT * FROM `reseller` WHERE validationKey='" + key + "'";
        obj.prepare();
        obj.execute((error, result) => {
            if (result.length > 0) {
                if (result[0].isResetPassword == 'true') {
                    if (error == 1 && result.length > 0) {
                        let obj4 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj4.nonqrysql = "UPDATE `reseller` SET `isResetPassword`='false' WHERE validationKey='" + key + "'";
                        obj4.prepare();
                        obj4.execute((emlErr, emlRes) => {
                            if (emlErr == 1) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ error: 0, status: 201, message: "Successfull Verified Please Enter Your New Password!", data: result });
                                objv.execute();
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ error: 0, status: 502, message: "Successfull Verified Status Not Changed!", data: result });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ error: 1, status: 502, message: "Something Went Wrong!" });
                        objv.execute();
                    }
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ error: 1, status: 502, message: "The Link You Followed Has Expired!" });
                    objv.execute();
                }
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ error: 1, status: 404, message: "Invalid Account Setting!" });
                objv.execute();
            }
        });
    }
    updatePassword(req, res, next) {
        let alldata = req.body.data;
        let passwd = alldata.password.trim();
        let password1 = bcrypt.hashSync(passwd, 10);
        let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
        obj0.nonqrysql = "UPDATE `reseller` SET `password`='" + password1 + "',`isResetPassword`='true' WHERE `validationKey`= '" + alldata.key + "'";
        obj0.prepare();
        obj0.execute((error, result) => {
            if (error == 1) {
                let objv0 = new RawView_1.RawView(res);
                objv0.prepare({
                    error: 0,
                    status: 201,
                    message: "Successfully Updated."
                });
                objv0.execute();
            }
            else {
                let objv0 = new RawView_1.RawView(res);
                objv0.prepare({
                    error: 1,
                    status: 502,
                    message: "Something Went Wrong!"
                });
                objv0.execute();
            }
        });
    }
    /************************
    *  Forgot Password end  *
    ************************/
    /* added here query for usersCustomer list for dropdown */
    customerList(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                //obj.qrysql = "SELECT a.san,u.username,u.iduser FROM `user`u INNER JOIN account a ON a.idaccount=u.idaccount WHERE a.`idaccount`= '" + sessdata.idaccount + "'";
                obj.qrysql = "SELECT a.san,u.username,u.iduser, up.firstname, up.lastname FROM `user`u LEFT JOIN account a ON a.idaccount=u.idaccount RIGHT JOIN user_profile up ON u.iduser=up.iduser WHERE a.`idaccount`= '" + sessdata.idaccount + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Customer Fetched!", status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    billingEnableOrDisable(req, res, next) {
        let sdata = req.body.data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj0.nonqrysql = "UPDATE `account` SET `is_billing`='" + sdata.bVal + "' WHERE `idaccount`='" + sdata.idaccount + "'";
                obj0.prepare();
                obj0.execute((error, result) => {
                    if (error == 1) {
                        let objv0 = new RawView_1.RawView(res);
                        objv0.prepare({ error: 0, status: 201, message: "Successfully Updated." });
                        objv0.execute();
                    }
                    else {
                        let objv0 = new RawView_1.RawView(res);
                        objv0.prepare({ error: 1, status: 502, message: "Something Went Wrong!" });
                        objv0.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare({ message: "Invalid Session Trying to access", status: 401 });
                objv.execute();
            }
        });
    }
    /** start onBoardingVerification */
    onBoardingVerification(req, res, next) {
        let rdata = JSON.parse(req.body.data);
        let arrData;
        if (rdata.email) {
            arrData = '`isEmailVerify`=' + rdata.email;
        }
        if (rdata.phone) {
            arrData = '`isMobileVerify`=' + rdata.phone;
        }
        if (rdata.isAddress) {
            arrData = '`isAddress`=' + rdata.isAddress;
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                obj0.filter = null;
                obj0.nonqrysql = "UPDATE `user` SET '" + arrData + "'  WHERE `idaccount`='" + sessdata.idaccount + "'";
                obj0.prepare();
                obj0.execute((_error, bvRes) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "onBoarding Verification Updated Successfully",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Brand Update!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    linkGeneration(req, res, next) {
        let sdata = req.body;
        console.log(sdata, '🐝🐝🐝🐝');
        let date_time = new Date();
        let date = ("0" + date_time.getDate()).slice(-2);
        let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
        let year = date_time.getFullYear();
        let hours = date_time.getHours();
        let minutes = date_time.getMinutes();
        let seconds = date_time.getSeconds();
        let CurrentTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let tariff_id = [];
                for (let data of sdata.tariff) {
                    tariff_id.push(data.idtariff);
                }
                let key = Math.random().toString(36).slice(2);
                let gURL = "?iduser=" + sessdata.iduser + "&idtariff=" + tariff_id + "&ukey=" + key;
                let encodeUrl = Buffer.from(gURL, "utf8").toString("base64").replace("=", '_').replace("=", '_');
                let URL = genLink.SIGNALHOST + '/#/signup?url=' + encodeUrl;
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "INSERT INTO `signup_referral_link` (`url`,`name`,`iduser`,`idaccount`,`key`,`updated_at`)VALUES ('" + URL + "', '" + (0, markError_1.default)(sdata.name1.trim()) + "','" + sessdata.iduser + "','" + sessdata.idaccount + "','" + key + "','" + CurrentTime + "')";
                obj.prepare();
                obj.execute((_error, lastid) => {
                    if (_error == 1) {
                        let user = new UserManagement();
                        user.insertOrderDetail(req, res, lastid.insertId, sessdata.iduser, sessdata.idaccount, sdata.orders, (err) => {
                        });
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Link Generated Successfully.", status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    insertOrderDetail(req, res, id, iduser, idaccount, orderddata, callback) {
        if (!orderddata) {
            orderddata = [];
            return;
        }
        if (orderddata.length > 0) {
            let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
            let qry0 = "INSERT INTO `signup_referral_link_tariff` (`iduser`, `idaccount`, `link_id`, `idtariff`, `order_by`) VALUES ";
            for (let i = 0; i < orderddata.length; i++) {
                let data1 = orderddata[i];
                let orderby = (Array.isArray(data1.selectedOrder) && data1.selectedOrder.length > 0 && data1.selectedOrder[0].value) ? data1.selectedOrder[0].value : 0;
                qry0 += "('" + iduser + "','" + idaccount + "','" + id + "','" + data1.tariffId + "','" + orderby + "'),";
            }
            obj1.nonqrysql = qry0.slice(0, -1);
            obj1.prepare();
            obj1.execute((er, result) => {
                if (er == 1) {
                    callback(null);
                }
                else {
                    callback(er);
                }
            });
        }
        else {
            callback(null);
        }
    }
    getLink(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let objv = new RawView_1.RawView(res);
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT `link_id`,`name`,`url`,`created_at`,`updated_at`,`key` FROM `signup_referral_link` WHERE `iduser` ='" + sessdata.iduser + "' AND `idaccount`='" + sessdata.idaccount + "' ORDER BY `link_id` DESC";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (error == 1) {
                        result = result || [];
                        objv.prepare({ error: 0, message: "Records fetched successfully.", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        objv.prepare({ error: 1, message: "Something Went Wrong!", status: 201 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    getsingleLink(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT link_id,`url`,`key`,`name` as iname FROM `signup_referral_link` WHERE `key`='" + sdata.data + "' AND `iduser` ='" + sessdata.iduser + "' ";
                obj.prepare();
                obj.execute((_error, result1) => {
                    if (_error == 1) {
                        let url = result1[0].url;
                        let url1 = url.split(genLink.SIGNALHOST + '/#/signup?url=')[1];
                        let decodeUrl = Buffer.from(url1, "base64").toString("utf8");
                        let idtariff = decodeUrl.split('idtariff=')[1];
                        let idtarifff = idtariff.split('&ukey=')[0];
                        let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                        obj1.qrysql = "SELECT t.*, s.order_by FROM tariff t JOIN signup_referral_link_tariff s ON t.idtariff = s.idtariff WHERE t.idtariff IN (" + idtarifff + ") AND s.link_id = " + result1[0].link_id;
                        obj1.prepare();
                        obj1.execute((_error, result) => {
                            if (_error == 1) {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ data: result, data1: result1, message: "Reseller Fetched Successfully!", status: 200 });
                                objv.execute();
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    updateOrderDetail(req, res, iduser, idaccount, orderddata, key, callback) {
        if (!orderddata) {
            orderddata = [];
            return;
        }
        if (orderddata.length > 0) {
            let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
            obj2.nonqrysql = "SELECT link_id FROM `signup_referral_link` WHERE `key` = '" + key + "'";
            obj2.prepare();
            obj2.execute((err, result) => {
                if (err == 1) {
                    let linkId = result[0].link_id;
                    let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                    obj3.nonqrysql = "DELETE FROM `signup_referral_link_tariff` WHERE `link_id` = '" + linkId + "'";
                    obj3.prepare();
                    obj3.execute((errr, resultdel) => {
                        if (errr == 1) {
                            let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            let qry0 = "INSERT INTO `signup_referral_link_tariff` (`iduser`, `idaccount`, `link_id`, `idtariff`, `order_by`) VALUES ";
                            for (let i = 0; i < orderddata.length; i++) {
                                let data1 = orderddata[i];
                                let orderby = (Array.isArray(data1.selectedOrder) && data1.selectedOrder.length > 0 && data1.selectedOrder[0].value) ? data1.selectedOrder[0].value : 0;
                                qry0 += "('" + iduser + "','" + idaccount + "','" + linkId + "','" + data1.tariffId + "','" + orderby + "'),";
                            }
                            obj1.nonqrysql = qry0.slice(0, -1);
                            obj1.prepare();
                            obj1.execute((er, result) => {
                                if (er == 1) {
                                    callback(null);
                                }
                                else {
                                    callback(er);
                                }
                            });
                        }
                        else {
                            callback(errr);
                        }
                    });
                }
                else {
                    callback(err);
                }
            });
        }
        else {
            callback(null);
        }
    }
    updatelink(req, res, next) {
        let sdata = req.body;
        let data = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let tariff_id = [];
                for (let data of sdata.tariff) {
                    tariff_id.push(data.idtariff);
                }
                let gURL = "?iduser=" + sessdata.iduser + "&idtariff=" + tariff_id + "&ukey=" + data.key;
                let encodeUrl = Buffer.from(gURL, "utf8").toString("base64").replace("=", '_').replace("=", '_');
                let URL = genLink.SIGNALHOST + '/#/signup?url=' + encodeUrl;
                console.log("");
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "update `signup_referral_link` set `name`='" + (0, markError_1.default)(sdata.name1.trim()) + "',`url`='" + URL + "',updated_at=NOW()where `key` = '" + data.key + "' AND `iduser`='" + sessdata.iduser + "'";
                obj.prepare();
                obj.execute((_error, lastid) => {
                    console.log(lastid, '🐝🐝🐝');
                    if (_error == 1) {
                        let user = new UserManagement();
                        user.updateOrderDetail(req, res, sessdata.iduser, sessdata.idaccount, sdata.orders, data.key, (err) => {
                        });
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Link Updated Successfully.", status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    deleteURL(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "DELETE FROM `signup_referral_link` WHERE `key`='" + sdata.data + "' AND `iduser`='" + sessdata.iduser + "' AND `idaccount`='" + sessdata.idaccount + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Signup link deleted Successfully!", status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ data: result, message: "Something Went Wrong With Connection!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    uploadFile(req, res, next) {
        let filePath;
        if (req.file) {
            const fileName = req.file.filename;
            //filePath = req.protocol + '://' + req.get('host') + '/uploads/' + fileName;
            filePath = e9taxfile.e9taxfile + fileName;
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj6 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj6.nonqrysql = "UPDATE `user_file` SET `filepath`='" + filePath + "',`updated_at`=NOW() WHERE `iduser`='" + sessdata.iduser + "' AND `idaccount`='" + sessdata.idaccount + "'";
                obj6.prepare();
                obj6.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "File Uploaded Successfully!", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    sendFile(req, res, next) {
        let filePath;
        if (req.file) {
            const fileName = req.file.filename;
            //filePath = req.protocol + '://' + req.get('host') + '/uploads/' + fileName;
            filePath = e9taxfile.e9taxfile + fileName;
        }
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj6 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj6.nonqrysql = "INSERT INTO `user_file` (`filepath`,`idaccount`,`iduser`)VALUES ('" + filePath + "', '" + sessdata.idaccount + "', '" + sessdata.iduser + "')";
                obj6.prepare();
                obj6.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "File Uploaded Successfully!", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getFile(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let objv = new RawView_1.RawView(res);
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT * from `user_file` WHERE `iduser`='" + sessdata.iduser + "' AND `idaccount`='" + sessdata.idaccount + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (error == 1) {
                        result = result || [];
                        objv.prepare({ error: 0, message: "Records fetched successfully.", data: result, status: 201 });
                        objv.execute();
                    }
                    else {
                        objv.prepare({ error: 1, message: "Something Went Wrong!", status: 201 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    getUrlTariff(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let url = req.query.type;
                let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                obj1.qrysql = "SELECT `link_id` FROM `signup_referral_link` WHERE `url`='" + url + "'";
                obj1.prepare();
                obj1.execute((error, result) => {
                    if (error == 1) {
                        if (result.length > 0) {
                            let obj2 = new RawQuery_1.ModelRawQuery(req, res);
                            obj2.qrysql = "SELECT su.idlinktariff, su.iduser, su.link_id, su.idtariff, su.order_by, t.name FROM `signup_referral_link_tariff` su JOIN `tariff` t ON su.idtariff = t.idtariff WHERE su.link_id='" + result[0].link_id + "'";
                            obj2.prepare();
                            obj2.execute((err, result1) => {
                                if (err == 1) {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: 200, message: "Tariff rate fetched successfully!", data: result1 });
                                    objv.execute();
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: 502, message: "Something went wrong while fetching tarriff rate!" });
                                    objv.execute();
                                }
                            });
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ status: 502, message: "Something went wrong while fetching tarriff rate!" });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare("No session data there");
                objv.execute();
            }
        });
    }
    updateOrdering(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let sdata = req.body.data;
                let orders = sdata.orders;
                console.log(sdata, '❌❌❌❌');
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                let qry0 = "UPDATE `signup_referral_link_tariff` SET `order_by` = CASE `idtariff` ";
                for (let i = 0; i < orders.length; i++) {
                    let dataupdate = orders[i];
                    qry0 += "WHEN '" + dataupdate.idtariff + "' THEN '" + dataupdate.order_by + "' ";
                }
                qry0 += "END WHERE `idtariff` IN (";
                for (let i = 0; i < orders.length; i++) {
                    qry0 += "'" + orders[i].idtariff + "',";
                }
                qry0 = qry0.slice(0, -1) + ") AND `link_id` = '" + sdata.linkid + "'";
                obj.nonqrysql = qry0;
                obj.prepare();
                obj.execute((err, result) => {
                    let objv = new RawView_1.RawView(res);
                    if (err == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Tariff order updated successfull!", status: 201 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something went wrong to update tariff order!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Session Trying to Access!", status: 401 });
                objv.execute();
            }
        });
    }
}
exports.UserManagement = UserManagement;
class TZ {
    /**
     * To create the default TimeZone of user
     */
    CreateTZ(req, res, next, callback) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj1 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj1.nonqrysql = "REPLACE INTO `tbl_timezone_config`(id_timezone, id_user) VALUES(192, " + sessdata.iduser + ");";
                obj1.prepare();
                obj1.execute((error, result) => {
                    if (error == 1) {
                        /**
                         * Update the TimeZone in user's session data
                         */
                        let obj2 = new RawQuery_1.ModelRawQuery(req, res);
                        obj2.qrysql = "SELECT a.utc client_time FROM tbl_timezones a WHERE a.id=192;";
                        obj2.prepare();
                        obj2.execute((error, result) => {
                            if (error == 1 && Array.isArray(result) && result.length > 0) {
                                let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj3.nonqrysql = "UPDATE `session` SET `client_time`='" + result[0].client_time + "' WHERE `authkey`='" + sessdata.authkey + "';";
                                obj3.prepare();
                                obj3.execute((error, result2) => {
                                    sessdata.client_time = result[0].client_time;
                                    server_1.sessiondata.set(sessdata.authkey, sessdata);
                                    callback(error, result);
                                });
                            }
                            else {
                                callback(error, result);
                            }
                        });
                    }
                    else {
                        callback(error, result);
                    }
                });
            }
            else {
                callback(error, "No session data there");
            }
        });
    }
}
exports.TZ = TZ;
