"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NewCampaign = 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 RawQuery_1 = require("../lib/model/RawQuery");
const setting_config_1 = require("../config/setting.config");
const request = require("request");
const cspSetting = new setting_config_1.CSPApiConfig();
const authKey = cspSetting.AUTHKEY;
const apiUrl = cspSetting.APIURL;
class NewCampaign extends AppRoute_1.AppRoute {
    constructor() {
        super();
    }
    /****************************************************************************
    * Start Brand Functionality  ************************************************
    ****************************************************************************/
    /**************************
    * Get Brand Relationship  *
    **************************/
    brandRelationship(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'enum/brandRelationship',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Brand Relationship Types!", data: JSON.parse(response.body), status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /***************************
    * Get Brand Vertical Type  *
    ***************************/
    brandVertical(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/vertical',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response) => {
                    if (!error) {
                        if (response) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Brand Vertical Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*********************
    * Brand Entity Type  *
    **********************/
    brandEntityType(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/entityType',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Brand Entity Types!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Entity Type Fetching!", error: error, status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*************************
    * Brand DCAs List  *
    *************************/
    brandDCA(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'enum/dca',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Brand DCA Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something went Wrong With Fetch DCAs List!", 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();
            }
        });
    }
    /*************************
    * Brand Identity Status  *
    *************************/
    brandIdentityStatus(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'enum/brandIdentityStatus',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response) => {
                    if (!error) {
                        if (response) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Identity Status Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Identity Status Fetching!", status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /**************************
    * Brand Alt Business Type *
    **************************/
    altBusinessIdType(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'enum/altBusinessIdType',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: 200, message: "Brand Business Type Fetched!", data: data });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: 502, message: "Something went Wrong With Get Brand Business Type Id List!" });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ status: 502, message: "Something went Wrong With Connection!", error: error });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /**********************
    * Brand stockExchange *
    **********************/
    stockExchange(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'enum/stockExchange',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: 200, message: "Brand stockExchange List!", data: data });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: 502, message: "Something went Wrong With Get stockExchange List!" });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ status: 502, message: "Something went Wrong With Connection!", error: error });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*****************
    * Brand Register *
    *****************/
    brandRegisterNonBlocking(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        let brandData = req.body;
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                if (brandData.entityType && brandData.entityType == "SOLE_PROPRIETOR") {
                    let ObjA = new RawQuery_1.ModelRawQuery(req, res);
                    ObjA.qrysql = "SELECT address,city,state,postal_code,country FROM `brand` WHERE `address`='" + brandData.street + "' AND `city`='" + brandData.city + "' AND `state`='" + brandData.state + "' AND `postal_code`='" + brandData.postalCode + "' AND `country`='" + brandData.country + "' AND `entityType`='SOLE_PROPRIETOR' AND `identityStatus`='VERIFIED'";
                    ObjA.prepare();
                    ObjA.execute((adErr, addressRes) => {
                        if (addressRes.length < 10) {
                            let Obj0 = new RawQuery_1.ModelRawQuery(req, res);
                            Obj0.qrysql = "SELECT email FROM `brand` WHERE `email`='" + brandData.email + "' AND `entityType`='SOLE_PROPRIETOR' AND `identityStatus`='VERIFIED'";
                            Obj0.prepare();
                            Obj0.execute((brErr, brandRes) => {
                                if (brandRes.length < 3) {
                                    let Obj00 = new RawQuery_1.ModelRawQuery(req, res);
                                    Obj00.qrysql = "SELECT phone FROM `brand` WHERE `phone`='" + brandData.phone + "' AND `entityType`='SOLE_PROPRIETOR' AND `identityStatus`='VERIFIED'";
                                    Obj00.prepare();
                                    Obj00.execute((brPhErr, brandPhRes) => {
                                        if (brandPhRes.length < 3) {
                                            let fun = new NewCampaign();
                                            fun.inbrandRegisterNonBlocking(req, res, next);
                                        }
                                        else {
                                            let objv = new RawView_1.RawView(res);
                                            objv.prepare({ error: brPhErr, message: "Phone No. Already Exits 3 Times", status: 502 });
                                            objv.execute();
                                        }
                                    });
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ message: "Email Id Already Exits 3 Times", status: 502 });
                                    objv.execute();
                                }
                            });
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ error: adErr, message: "Address Already Exits 10 Times", status: 502 });
                            objv.execute();
                        }
                    });
                }
                else {
                    let fun = new NewCampaign();
                    fun.inbrandRegisterNonBlocking(req, res, next);
                }
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    inbrandRegisterNonBlocking(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        let brandData = req.body;
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let Obj = new RawQuery_1.ModelRawQuery(req, res);
                Obj.qrysql = "SELECT * FROM `wallet` WHERE `idaccount`='" + sessdata.idaccount + "' AND `balance` + `credit_limit` >= 4";
                Obj.prepare();
                Obj.execute((crErr, crRes) => {
                    if (crErr == 1 && crRes.length > 0) {
                        let options = {
                            'method': 'POST',
                            'url': apiUrl + 'brand/nonBlocking',
                            'headers': {
                                'Content-Type': 'application/json',
                                'Authorization': 'Basic ' + authKey
                            },
                            body: JSON.stringify(brandData)
                        };
                        request(options, (error, response, body) => {
                            if (!error) {
                                let resultData = JSON.parse(response.body);
                                if (resultData.brandId && resultData.brandId !== undefined) {
                                    let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    obj3.nonqrysql = "INSERT into `brand` (`idaccount`, `iduser`, `company_name`, `brand_name`,`company_type`, `ein`, `brand_relation`, `address`, `city`, `state`, `postal_code`, `website`, `vertical_type`, `country`, `email`, `phone`, `brandId`,`cspId`, `altBusinessId`, `altBusinessIdType`, `registrationScore`, `universalEin`,  `referenceId`, `entityType`, `identityStatus`, `stockSymbol`, `stockExchange`, `einIssuingCountry`, `mock`, `firstName`, `lastName`, `ipAddress`,`optionalAttributes`, `brandType`) VALUES('" + sessdata.idaccount + "', '" + sessdata.iduser + "', '" + resultData.companyName + "', '" + resultData.displayName + "', '" + resultData.entityType + "', '" + resultData.ein + "', '" + resultData.brandRelationship + "', '" + resultData.street + "', '" + resultData.city + "', '" + resultData.state + "', '" + resultData.postalCode + "', '" + resultData.website + "', '" + resultData.vertical + "', '" + resultData.country + "', '" + resultData.email + "', '" + brandData.phone + "', '" + resultData.brandId + "', '" + resultData.cspId + "', '" + brandData.altBusinessId + "', '" + brandData.altBusinessIdType + "', '" + resultData.registrationScore + "', '" + resultData.universalEin + "',  '" + resultData.referenceId + "', '" + resultData.entityType + "', '" + resultData.identityStatus + "', '" + resultData.stockSymbol + "', '" + resultData.stockExchange + "', '" + resultData.einIssuingCountry + "', '" + resultData.mock + "', '" + brandData.firstName + "', '" + resultData.lastName + "', '" + resultData.ipAddress + "', '" + JSON.stringify(resultData.optionalAttributes) + "', 'register')";
                                    obj3.execute((__error, result) => {
                                        if (__error == 1) {
                                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj.nonqrysql = "UPDATE `wallet` SET `balance`=`balance`-4 WHERE `idaccount`='" + sessdata.idaccount + "'";
                                            obj.prepare();
                                            obj.execute((___error, resp) => {
                                                let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                                iQry += "`idaccount`=" + sessdata.idaccount + ", ";
                                                iQry += "`amount`='-4', ";
                                                iQry += "`purpose`='Wallet amount successfully updated for brand registration', ";
                                                iQry += "`status`=1;";
                                                let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                objWL.nonqrysql = iQry;
                                                objWL.prepare();
                                                objWL.execute((error, result) => {
                                                });
                                                if (___error == 1) {
                                                    let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                    obj3.nonqrysql = "INSERT INTO `brand_log` (`idaccount`, `iduser`, `brand_key`,`cost`, `date`, `description`) VALUES ('" + sessdata.idaccount + "', '" + sessdata.iduser + "','" + resultData.brandId + "', '4', '" + Date.now() + "', 'Brand_Rate')";
                                                    obj3.prepare();
                                                    obj3.execute((log_error, _resp) => {
                                                        if (log_error == 1) {
                                                            let objv = new RawView_1.RawView(res);
                                                            objv.prepare({ status: 201, brandId: resultData.brandId, data: resultData, message: "New Brand Created Successfully." });
                                                            objv.execute();
                                                        }
                                                        else {
                                                            let objv = new RawView_1.RawView(res);
                                                            objv.prepare({ status: 502, brandId: resultData.brandId, message: "Result Not Saved Successfully!" });
                                                            objv.execute();
                                                        }
                                                    });
                                                }
                                                else {
                                                    let objv = new RawView_1.RawView(res);
                                                    objv.prepare({ status: 503, brandId: resultData.brandId, message: "Brand Registered Error With Wallet Update!" });
                                                    objv.execute();
                                                }
                                            });
                                        }
                                        else {
                                            let objv = new RawView_1.RawView(res);
                                            objv.prepare({ status: 504, brandId: resultData.brandId, message: "Result Not Saved Successfully!" });
                                            objv.execute();
                                        }
                                    });
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ message: resultData[0].field + " " + resultData[0].description, status: resultData[0].code });
                                    objv.execute();
                                }
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ error: crErr, message: "Account Balance is Low!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /**********************
    * Start Update Brand  *
    **********************/
    updateBrand(req, res, next) {
        let brandId = req.body.data !== undefined ? JSON.parse(req.body.data).brandId : req.query.brandId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = req.body.data !== undefined ? JSON.parse(req.body.data).iduser : sessdata.iduser;
            let Obj0 = new RawQuery_1.ModelRawQuery(req, res);
            Obj0.qrysql = "SELECT identityStatus FROM `brand` WHERE `brandId`='" + brandId + "' AND `iduser`='" + iduser + "'";
            Obj0.prepare();
            Obj0.execute((_err, resStatus) => {
                if (resStatus[0].identityStatus == 'UNVERIFIED') {
                    let Obj00 = new RawQuery_1.ModelRawQuery(req, res);
                    Obj00.qrysql = "SELECT * FROM `wallet` WHERE `idaccount`='" + sessdata.idaccount + "' AND `balance` + `credit_limit` >= 4";
                    Obj00.prepare();
                    Obj00.execute((crErr, crRes) => {
                        if (crErr == 1 && crRes.length > 0) {
                            let fun = new NewCampaign();
                            fun.inUpdateBrand(req, res, next);
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: 502, message: "Your Wallet Balance is Low From $4!" });
                            objv.execute();
                        }
                    });
                }
                else {
                    let fun = new NewCampaign();
                    fun.inUpdateBrand(req, res, next);
                }
            });
        });
    }
    inUpdateBrand(req, res, next) {
        let data = req.body.data !== undefined ? JSON.parse(req.body.data).mainData : req.body;
        let brandId = req.body.data !== undefined ? JSON.parse(req.body.data).brandId : req.query.brandId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = req.body.data !== undefined ? JSON.parse(req.body.data).iduser : sessdata.iduser;
            let Obj0 = new RawQuery_1.ModelRawQuery(req, res);
            Obj0.qrysql = "SELECT identityStatus FROM `brand` WHERE `brandId`='" + brandId + "' AND `iduser`='" + iduser + "'";
            Obj0.prepare();
            Obj0.execute((_err, resStatus) => {
                var resultAllBrand = [];
                for (var i in data) {
                    if (data[i] !== '' && data[i] !== 'undefined') {
                        resultAllBrand.push([i, data[i]]);
                    }
                }
                let brandData = Object.fromEntries(resultAllBrand);
                if (error == 1) {
                    let options = {
                        'method': 'PUT',
                        'url': apiUrl + 'brand/' + brandId,
                        'headers': {
                            'Content-Type': 'application/json',
                            'Authorization': 'Basic ' + authKey
                        },
                        body: JSON.stringify(brandData)
                    };
                    request(options, (__error, response, body) => {
                        let resultData = JSON.parse(response.body);
                        if (resultData.brandId && resultData.brandId !== undefined) {
                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj.nonqrysql = "UPDATE `brand` SET `company_name`='" + resultData.companyName + "',`brand_name`='" + resultData.displayName + "',`entityType`='" + resultData.entityType + "',`ein`='" + resultData.ein + "',`einIssuingCountry`='" + resultData.einIssuingCountry + "', `identityStatus`='" + resultData.identityStatus + "', `cspId`='" + resultData.cspId + "',`address`='" + resultData.street + "',`city`='" + resultData.city + "',`state`='" + resultData.state + "',`postal_code`='" + resultData.postalCode + "',`country`='" + resultData.country + "',`website`='" + resultData.website + "',`stockSymbol`='" + resultData.stockSymbol + "',`stockExchange`='" + resultData.stockExchange + "',`vertical_type`='" + resultData.vertical + "',`referenceId`='" + resultData.referenceId + "',`brand_relation`='" + resultData.brandRelationship + "',`email`='" + resultData.email + "',`phone`='" + resultData.phone + "',`firstName`='" + resultData.firstName + "',`lastName`='" + resultData.lastName + "',`altBusinessId`='" + brandData.altBusinessId + "',`altBusinessIdType`='" + brandData.altBusinessIdType + "',`ipAddress`='" + resultData.ipAddress + "',`optionalAttributes`='" + JSON.stringify(resultData.optionalAttributes) + "',`mock`='" + resultData.mock + "' WHERE `iduser`='" + iduser + "' AND `brandId`='" + brandId + "'";
                            obj.prepare();
                            obj.execute((___error, result) => {
                                if (___error == 1) {
                                    if (resStatus[0].identityStatus == 'UNVERIFIED' && resultData.identityStatus !== 'UNVERIFIED') {
                                        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj.nonqrysql = "UPDATE `wallet` SET `balance`=`balance`-4 WHERE `idaccount`='" + sessdata.idaccount + "'";
                                        obj.prepare();
                                        obj.execute((____error, resp) => {
                                            let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                            iQry += "`idaccount`=" + sessdata.idaccount + ", ";
                                            iQry += "`amount`='-4', ";
                                            iQry += "`purpose`='Wallet amount successfully updated for brand update', ";
                                            iQry += "`status`=1;";
                                            let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            objWL.nonqrysql = iQry;
                                            objWL.prepare();
                                            objWL.execute((error, result) => {
                                            });
                                        });
                                    }
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({
                                        message: "Brand Updated Successfully!", data: resultData,
                                        status: 201
                                    });
                                    objv.execute();
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: 502, message: "Something Went Wrong With Brand Update!" });
                                    objv.execute();
                                }
                            });
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                message: resultData[0].field + ' ' + resultData[0].description,
                                status: resultData[0].code
                            });
                            objv.execute();
                        }
                    });
                }
                else {
                    let objv = new _406_1.Res406(res);
                    objv.prepare(session);
                    objv.execute();
                }
            });
        });
    }
    /********************
    * End Update Brand  *
    ********************/
    /***********************************
    * Start Identtity Status Of Brand  *
    ***********************************/
    brandIdentityStatusUpdate(req, res, next) {
        let brandId = req.body.data !== undefined ? JSON.parse(req.body.data).brandId : req.body.brandId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = req.body.data !== undefined ? JSON.parse(req.body.data).iduser : sessdata.iduser;
            let Obj00 = new RawQuery_1.ModelRawQuery(req, res);
            Obj00.qrysql = "SELECT * FROM `wallet` WHERE `idaccount`='" + sessdata.idaccount + "' AND `balance` + `credit_limit` >= 4";
            Obj00.prepare();
            Obj00.execute((crErr, crRes) => {
                if (crErr == 1 && crRes.length > 0) {
                    let fun = new NewCampaign();
                    fun.inBrandIdentityStatusUpdate(req, res, next);
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ status: 502, message: "Your Wallet Balance is Low From $4!" });
                    objv.execute();
                }
            });
        });
    }
    inBrandIdentityStatusUpdate(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let brandId = req.body.data !== undefined ? JSON.parse(req.body.data).brandId : req.body.brandId;
            let iduser = req.body.data !== undefined ? JSON.parse(req.body.data).iduser : sessdata.iduser;
            if (error == 1) {
                let Obj0 = new RawQuery_1.ModelRawQuery(req, res);
                Obj0.qrysql = "SELECT identityStatus,brandId FROM `brand` WHERE `brandId`='" + brandId + "' AND `iduser`='" + iduser + "'";
                Obj0.prepare();
                Obj0.execute((_err, resStatus) => {
                    if (resStatus.length > 0) {
                        let options = {
                            'method': 'PUT',
                            'url': apiUrl + 'brand/' + brandId,
                            'headers': {
                                'Content-Type': 'application/json',
                                'Authorization': 'Basic ' + authKey
                            },
                            body: JSON.stringify({ identityStatus: brandId })
                        };
                        request(options, (error, response, body) => {
                            let resultData = JSON.parse(response.body);
                            if (resultData.brandId && resultData.brandId !== undefined) {
                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj.nonqrysql = "UPDATE `brand` SET `identityStatus`='" + resultData.identityStatus + "' WHERE `iduser`='" + iduser + "' AND `brandId`='" + brandId + "'";
                                obj.prepare();
                                obj.execute((___error, resp) => {
                                    if (___error == 1) {
                                        if (resultData.identityStatus !== resStatus[0].identityStatus) {
                                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                            obj.nonqrysql = "UPDATE `wallet` SET `balance`=`balance`-4 WHERE `idaccount`='" + sessdata.idaccount + "'";
                                            obj.prepare();
                                            obj.execute((____error, resp) => {
                                                let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                                iQry += "`idaccount`=" + sessdata.idaccount + ", ";
                                                iQry += "`amount`='-4', ";
                                                iQry += "`purpose`='Wallet amount successfully updated for Resubmit Brand', ";
                                                iQry += "`status`=1;";
                                                let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                objWL.nonqrysql = iQry;
                                                objWL.prepare();
                                                objWL.execute((error, result) => {
                                                });
                                            });
                                        }
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "identityStatus Updated Successfully!", data: resStatus.identityStatus, status: 200, });
                                        objv.execute();
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Something Went Wrong With Update Identity!", status: 502 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    message: resStatus[0].field + ' ' + resStatus[0].description,
                                    status: resStatus[0].code
                                });
                                objv.execute();
                            }
                        });
                    }
                    else {
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /***********************************
    * End Identtity Status Of Brand  *
    ***********************************/
    /****************
    * Delete Brand  *
    ****************/
    deleteBrand(req, res, next) {
        let brandId = req.query.id !== undefined ? req.query.id : req.query.brandId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let options = {
                    'method': 'DELETE',
                    'url': apiUrl + 'brand/' + brandId,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (__error, response, body) => {
                    if ((response.statusCode == 204 && response.statusCode !== undefined) || (JSON.parse(body)[0].code == 502 && JSON.parse(body)[0].code !== undefined)) {
                        let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj0.nonqrysql = "UPDATE `brand` SET `deleted`=1, `delete_date`=NOW() WHERE `brandId`='" + brandId + "' AND `iduser`='" + sessdata.iduser + "'";
                        obj0.prepare();
                        obj0.execute((__errorb, resbrand) => {
                            if (__errorb == 1) {
                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj.nonqrysql = "DELETE FROM `brand_log` WHERE `brand_key`='" + brandId + "' AND `iduser`='" + sessdata.iduser + "'";
                                obj.prepare();
                                obj.execute((__errlog, lastid) => {
                                    if (__errlog == 1) {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({
                                            message: "Brand Deleted Successfully!",
                                            data: lastid[0],
                                            status: 201
                                        });
                                        objv.execute();
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({
                                            message: "Something Went Wrong With Brand!",
                                            error: lastid,
                                            status: 502
                                        });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    message: "Something Went Wrong With Update Brand!",
                                    error: resbrand,
                                    status: 502
                                });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let data = JSON.parse(body);
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: data[0].field + ' ' + data[0].description,
                            status: data[0].code
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*****************
    * Get All Brand  *
    *****************/
    getAllBrands(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = sessdata.iduser;
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT idbrand,iduser, idaccount,brand_name, brandId,CONCAT(brand_name,' - ',brandId)brand_name_with_key, brand_relation, entityType, referenceId, ein,firstName,lastName,company_name,company_type,address,city,postal_code,state,country,website,vertical_type,email,phone,cspId,registrationScore,universalEin,einIssuingCountry,mock,ipAddress,stockSymbol,stockExchange,optionalAttributes,(CASE WHEN deleted ='0' THEN 'NO' ELSE 'YES' END )`deleted`, delete_date , (CASE WHEN identityStatus !='undefined' THEN identityStatus ELSE '' END )`identityStatus` , DATE_FORMAT(created_at, '%Y-%m-%d')  AS Registered_On  FROM brand WHERE `deleted`='0' AND iduser = '" + iduser + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Brand 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();
            }
        });
    }
    /****************
    * Brand Filter  *
    ****************/
    brandFilter(req, res, next) {
        let data = req.body.data;
        let condition = "";
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                if (data.brandId)
                    condition += '`brandId` LIKE "%' + data.brandId + '%" AND ';
                if (data.displayName)
                    condition += '`brand_name` LIKE "%' + data.displayName + '%" AND ';
                if (data.country)
                    condition += '`country`="' + data.country + '" AND ';
                if (data.entityType)
                    condition += '`entityType` LIKE "%' + data.entityType + '%" AND ';
                if (data.ein)
                    condition += '`ein` LIKE "%' + data.ein + '%" AND ';
                if (data.identityStatus)
                    condition += '`identityStatus` LIKE "%' + data.identityStatus + '%" AND ';
                if (data.referenceId)
                    condition += '`referenceId` LIKE "%' + data.referenceId + '%" AND ';
                obj.qrysql = "SELECT iduser, idaccount,brand_name, brandId, brand_relation, entityType, referenceId, ein, country,`identityStatus` , DATE_FORMAT(created_at, '%Y-%m-%d')  AS Registered_On  FROM brand WHERE " + condition + " deleted='0' AND iduser = '" + sessdata.iduser + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Brand 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();
            }
        });
    }
    /*******************
    * Campaign Filter  *
    *******************/
    campaignFilter(req, res, next) {
        let data = req.body.data;
        let condition = "";
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                if (data.brandId)
                    condition += '`brandId` LIKE "%' + data.brandId + '%" AND ';
                if (data.brand_name)
                    condition += '`brand_name` LIKE "%' + data.brand_name + '%" AND ';
                if (data.campaign_key)
                    condition += '`campaign_key` LIKE "%' + data.campaign_key + '%" AND ';
                if (data.usecase)
                    condition += '`usecase`="' + data.usecase + '" AND ';
                // if (data.referenceId)
                //     condition += '`referenceId` LIKE "%' + data.referenceId + '%" AND ';
                obj.qrysql = "SELECT b.brandId, b.brand_name,c.campaign_key,c.usecase,c.start_date,c.did_count,c.did_limit FROM `brand`b INNER JOIN `campaign`c ON c.idbrand = b.brandId WHERE " + condition + " c.`iduser` = '" + sessdata.iduser + "' AND c.`deleted` = 0 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign List Fetched Successfully!",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Something Went Wrong With Fetched Campaign List!",
                            status: 502,
                            error: result
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /********************
    * Get Brand Detail  *
    ********************/
    getBrandsDetail(req, res, next) {
        let gdata = req.query;
        let data = gdata.type !== undefined ? JSON.parse(gdata.type) : gdata;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = data.iduser !== undefined ? data.iduser : sessdata.iduser;
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT idbrand,iduser, idaccount,brand_name, brandId, brand_relation,altBusinessId, altBusinessIdType, entityType, referenceId, ein,firstName,lastName,company_name,company_type,address,city,postal_code,state,country,website,vertical_type,email,phone,cspId,registrationScore,universalEin,einIssuingCountry,mock,ipAddress,stockSymbol,stockExchange,optionalAttributes,(CASE WHEN deleted ='0' THEN 'NO' ELSE 'YES' END )`deleted`, delete_date , (CASE WHEN identityStatus !='undefined' THEN identityStatus ELSE '' END )`identityStatus` , DATE_FORMAT(created_at, '%Y-%m-%d')  AS Registered_On  FROM brand WHERE `deleted`='0' AND brandId='" + data.brandId + "' AND iduser = '" + iduser + "'";
                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: "Brand Fetched Successfully!",
                                status: 200
                            });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({
                                error: result,
                                message: "No Result Found!",
                                status: 502
                            });
                            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();
            }
        });
    }
    /*********************
    * Send OTP For Brand *
    *********************/
    sendOTPforBrand(req, res, next) {
        let sdata = req.body;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let otpdata;
                otpdata = {
                    pinSms: "Please confirm your registration by replying @OTP_YES@"
                };
                let options = {
                    'method': 'POST',
                    'url': apiUrl + 'brand/' + sdata.brandId + '/otp',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    },
                    body: JSON.stringify(otpdata)
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let data = JSON.stringify(response.body);
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'Message to be sent to the moble phone of registered brand !', data: data, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Message Not Sent!", data: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /****************
    * Vetting Class *
    *****************/
    brandVettingClass(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'enum/vettingClass',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Brand Vetting Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something went Wrong With Brand Vetting Fetching!", error: error, status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /***********************
    * Get Vetting Provider *
    ***********************/
    brandVettingProvider(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/extVettingProvider',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Brand Vetting Provider Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something went Wrong With Brand Vetting Provider Fetching!", status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /***********************
    * Get Vetting Status   *
    ***********************/
    brandVettingStatus(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/vettingStatus',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Brand Vetting Status Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something went Wrong With Brand Vetting Status Fetching!", status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /*****************************************
    * Get Vetting Class Class By Entity Type *
    *****************************************/
    getVettingClassByEtype(req, res, next) {
        let sdata = req.query;
        let data = JSON.parse(sdata.type);
        let entityType = data.entityType;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT vettingClass,VC_displayName,evpId,EI_displayName,price,waitTime FROM `brand_vetting_additional` WHERE entityType='" + entityType + "' GROUP BY `vettingClass`";
                obj.prepare();
                obj.execute((err, result) => {
                    if (err == 1 && result.length > 0) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'Vetting Class and Provider Fetched Successfully!', data: result, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Vetting Class and Provider Not Fetched!", data: [], status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /**************************************
    * Get Vetting Provider By Entity Type *
    **************************************/
    getVettingPartner(req, res, next) {
        let sdata = req.query;
        let data = JSON.parse(sdata.type);
        let entityType = data.entityType;
        let vettingClass = data.vettingClass;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT vettingClass,VC_displayName,evpId,EI_displayName,price,waitTime FROM `brand_vetting_additional` WHERE entityType='" + entityType + "' AND `vettingClass`='" + vettingClass + "'";
                obj.prepare();
                obj.execute((err, result) => {
                    if (err == 1 && result.length > 0) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'Vetting Class and Provider Fetched Successfully!', data: result, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Vetting Class and Provider Not Fetched!", data: [], status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /****************************
    * Get Vetting List By Brand *
    ****************************/
    getBrandsVettingList(req, res, next) {
        let sdata = req.query;
        let data = JSON.parse(sdata.type);
        let brandId = data.brandId;
        let iduser = data.iduser;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT iduser,brandID,type,evpId,vettingId,vettingToken,vettingScore,vettingClass,vettingStatus,reasons,vettingDetails,VettedDate,createdDate FROM `brand_vetting` WHERE brandId='" + brandId + "' AND iduser='" + iduser + "' GROUP BY `vettingId`";
                obj.prepare();
                obj.execute((err, result) => {
                    if (err == 1 && result.length > 0) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'Vetting Fatched Successfully!', data: result, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "NO Vetting available in this Brand!", data: [], status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /****************
    * Apply Vetting *
    ****************/
    applyVetting(req, res, next) {
        let vettingData = req.body;
        let vettingData1 = req.query;
        let brandId = vettingData1.brandId !== undefined ? vettingData1.brandId : vettingData.brandId;
        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 entityType,einIssuingCountry FROM `brand` WHERE brandId='" + brandId + "' AND `iduser` = '" + sessdata.iduser + "'";
                obj.prepare();
                obj.execute((errBrand, resultBrand) => {
                    if (errBrand == 1 && resultBrand.length > 0) {
                        let obj = new RawQuery_1.ModelRawQuery(req, res);
                        obj.qrysql = "SELECT vettingClass,evpId,price,waitTime,failedPrice FROM `brand_vetting_additional` WHERE evpId='" + vettingData.evpId + "' AND vettingClass='" + vettingData.vettingClass + "' AND entityType='" + resultBrand[0].entityType + "'";
                        obj.prepare();
                        obj.execute((errV, resulttV) => {
                            let resultV = resulttV.length > 0 ? resulttV : [0];
                            // For pinPreference (swagger side request)
                            let price;
                            if (resultBrand[0].entityType == "NON_PROFIT" && resultBrand[0].einIssuingCountry == "US" && resultV[0].vettingClass == "POLITICAL" && resultV[0].evpId == "AEGIS") {
                                let pinPre = JSON.parse(vettingData.additionalRequestPayload).pinPreference;
                                switch (pinPre) {
                                    case "Regular":
                                        price = 64;
                                        break;
                                    case "Email":
                                        price = 64;
                                        break;
                                    default: // Express
                                        price = 91.95;
                                }
                            }
                            else {
                                price = resultV[0].price !== undefined ? resultV[0].price : 0;
                            }
                            let deductPrice = price;
                            let waittime = resultV[0].waitTime !== undefined ? resultV[0].waitTime : '';
                            let Obj = new RawQuery_1.ModelRawQuery(req, res);
                            Obj.qrysql = "SELECT * FROM `wallet` WHERE `idaccount`='" + sessdata.idaccount + "' AND `balance` + `credit_limit` >= '" + deductPrice + "'";
                            Obj.prepare();
                            Obj.execute((bErr, bRes) => {
                                if (bErr == 1 && bRes.length > 0) {
                                    let options = {
                                        'method': 'POST',
                                        'url': apiUrl + 'brand/' + brandId + '/externalVetting/',
                                        'headers': {
                                            'Content-Type': 'application/json',
                                            'Authorization': 'Basic ' + authKey
                                        },
                                        body: JSON.stringify({
                                            "evpId": vettingData.evpId,
                                            "vettingClass": vettingData.vettingClass,
                                            "additionalRequestPayload": vettingData.additionalRequestPayload
                                        })
                                    };
                                    request(options, (error, response, body) => {
                                        if (!error) {
                                            let resData = JSON.parse(response.body);
                                            if (resData.vettingId && resData.vettingId !== undefined) {
                                                // To Charge deduct from wallet
                                                //let deductPrice: any = price;
                                                /*switch (resData.vettingStatus) {
                                                    case "FAILED":
                                                        switch (vettingData.evpId) {
                                                            case "STANDARD":
                                                                deductPrice = resultV[0].failedPrice;
                                                                break;
                                                            case "POLITICAL":
                                                                deductPrice = resultV[0].failedPrice;
                                                                break;
                                                            default:
                                                                deductPrice = 0;
                                                        }
                                                        break;
                                                    default:
                                                        deductPrice = price;
                                                }*/
                                                // To brand log update
                                                let Objbl = new RawQuery_1.ModelRawQuery(req, res);
                                                Objbl.qrysql = "SELECT brand_key FROM `brand_log` WHERE `brand_key`='" + brandId + "' AND `iduser`='" + sessdata.iduser + "'";
                                                Objbl.prepare();
                                                Objbl.execute((BlErr, BlRes) => {
                                                    if (BlRes.length > 0) {
                                                        let objv00 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                        objv00.nonqrysql = "UPDATE `brand_log` SET `vettingCharge`=`vettingCharge`+" + deductPrice + " WHERE `iduser`='" + sessdata.iduser + "' AND `brand_key`='" + brandId + "'";
                                                        objv00.prepare();
                                                        objv00.execute((errwalleup, sucwalletup) => {
                                                            console.log("Brand Log Updated");
                                                        });
                                                    }
                                                    else {
                                                        let objbl0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                        objbl0.nonqrysql = "INSERT INTO `brand_log` (`idaccount`, `iduser`,`brand_key`,`cost`, `date`, `description`, `vettingCharge`) VALUES ('" + sessdata.idaccount + "', '" + sessdata.iduser + "','" + brandId + "', '', '" + Date.now() + "', 'Vetting_Charge', '" + deductPrice + "')";
                                                        objbl0.prepare();
                                                        objbl0.execute((__errorbl, respbl) => {
                                                            console.log("Brand Log Inserted");
                                                        });
                                                    }
                                                });
                                                //To deduct price from wallet
                                                let objv = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                objv.nonqrysql = "UPDATE `wallet` SET `balance`=`balance`-" + deductPrice + " WHERE `idaccount`='" + sessdata.idaccount + "'";
                                                objv.prepare();
                                                objv.execute((wallet_error, wallet_success) => {
                                                    let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                                    iQry += "`idaccount`=" + sessdata.idaccount + ", ";
                                                    iQry += "`amount`='-" + deductPrice + "', ";
                                                    iQry += "`purpose`='Wallet amount successfully updated for campaign registration', ";
                                                    iQry += "`status`=1;";
                                                    let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                    objWL.nonqrysql = iQry;
                                                    objWL.prepare();
                                                    objWL.execute((error, result) => {
                                                        console.log("Transaction response::", result);
                                                    });
                                                    console.log("Charge deducted $", deductPrice);
                                                });
                                                //To inser brand vetting detail
                                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                obj.nonqrysql = "INSERT INTO `brand_vetting` (`idaccount`, `iduser`, `brandId`,`type`, `evpId`, `vettingId`,`vettingToken`,`vettingScore`,`vettingClass`,`vettingStatus`,`reasons`,`vettingDetails`,`vettedDate`,`createdDate`,`priceDeducted`) VALUES ('" + sessdata.idaccount + "', '" + sessdata.iduser + "', '" + brandId + "', 'applyVetting', '" + resData.evpId + "', '" + resData.vettingId + "','" + resData.vettingToken + "','" + resData.vettingScore + "','" + resData.vettingClass + "','" + resData.vettingStatus + "','" + resData.reasons + "','" + JSON.stringify(resData.vettingDetails) + "','" + resData.vettedDate + "','" + resData.createDate + "','" + deductPrice + "')";
                                                obj.prepare();
                                                obj.execute((___error, resp) => {
                                                    if (___error == 1) {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ status: 200, message: "Vetting Applied Successfully.Vetting Price " + deductPrice + " and Estimated Time for Vetting: " + waittime + "", data: resData });
                                                        objv.execute();
                                                    }
                                                    else {
                                                        let objv = new RawView_1.RawView(res);
                                                        objv.prepare({ status: 501, message: "Vetting Data Not Saved!", data: resData });
                                                        objv.execute();
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ status: resData[0].code, message: resData[0].field + ' ' + resData[0].description });
                                                objv.execute();
                                            }
                                        }
                                        else {
                                            let objv = new RawView_1.RawView(res);
                                            objv.prepare({ error: error, message: "Something Went Wrong With Request!", status: 502 });
                                            objv.execute();
                                        }
                                    });
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ error: error, message: "Your Currect Balance is Low From $" + price + "!", status: 502 });
                                    objv.execute();
                                }
                            });
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ error: error, message: "Brand Does Not Exist!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*****************
    * Import Vetting *
    *****************/
    importVetting(req, res, next) {
        let vettingData = req.body;
        let vettingData1 = req.query;
        let brandId = vettingData1.brandId !== undefined ? vettingData1.brandId : vettingData.brandId;
        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 evpId FROM `brand_vetting` WHERE `evpId`='" + vettingData.evpId + "' AND `vettingId`='" + vettingData.vettingId + "' AND `iduser`='" + sessdata.iduser + "'";
                Obj.prepare();
                Obj.execute((VErr, VRes) => {
                    let options = {
                        'method': 'PUT',
                        'url': apiUrl + 'brand/' + brandId + '/externalVetting/',
                        'headers': {
                            'Content-Type': 'application/json',
                            'Authorization': 'Basic ' + authKey
                        },
                        body: JSON.stringify({
                            "evpId": vettingData.evpId,
                            "vettingId": vettingData.vettingId,
                            "vettingToken": vettingData.vettingToken
                        })
                    };
                    request(options, (error, response, body) => {
                        if (!error) {
                            let resData = JSON.parse(response.body);
                            if (resData.vettingId && resData.vettingId !== undefined) {
                                let qry = '';
                                if (VRes.length > 0) {
                                    qry = "UPDATE `brand_vetting` SET `evpId`='" + resData.evpId + "',`vettingToken`='" + resData.vettingToken + "', `vettingScore`='" + resData.vettingScore + "',`vettingClass`='" + resData.vettingClass + "',`vettingStatus`='" + resData.vettingStatus + "',`reasons`='" + resData.reasons + "',`type`='importVetting',`vettingDetails`='" + JSON.stringify(resData.vettingDetails) + "',`vettedDate`='" + resData.vettedDate + "',`createdDate`='" + resData.createDate + "' WHERE `iduser`='" + sessdata.iduser + "' AND `brandId`='" + brandId + "' AND `vettingId`='" + vettingData.vettingId + "'";
                                }
                                else {
                                    qry = "INSERT INTO `brand_vetting` (`idaccount`, `iduser`, `brandId`,`type`, `evpId`, `vettingId`,`vettingToken`,`vettingScore`,`vettingClass`,`vettingStatus`,`reasons`,`vettingDetails`,`vettedDate`,`createdDate`) VALUES ('" + sessdata.idaccount + "', '" + sessdata.iduser + "', '" + brandId + "', 'importVetting', '" + resData.evpId + "', '" + resData.vettingId + "','" + resData.vettingToken + "','" + resData.vettingScore + "','" + resData.vettingClass + "','" + resData.vettingStatus + "','" + resData.reasons + "','" + JSON.stringify(resData.vettingDetails) + "','" + resData.vettedDate + "','" + resData.createDate + "')";
                                }
                                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                obj.nonqrysql = qry;
                                obj.prepare();
                                obj.execute((___error, resp) => {
                                    if (___error == 1) {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Vetting Imported Successfully!", data: resData, status: 200 });
                                        objv.execute();
                                    }
                                    else {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Vetting Not Inserted", status: 501 });
                                        objv.execute();
                                    }
                                });
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ status: resData[0].code, message: resData[0].field + ' ' + resData[0].description });
                                objv.execute();
                            }
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ error: error, message: "Something Went Wrong With Request!", status: 502 });
                            objv.execute();
                        }
                    });
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*****************************************************************
    * Get Single External Vetting List By Brand Id And Status Update *
    *****************************************************************/
    externalVettingList(req, res, next) {
        let vettingData = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            // To Check Brand Exist Or Not
            let obj = new RawQuery_1.ModelRawQuery(req, res);
            obj.qrysql = "SELECT entityType FROM `brand` WHERE brandId='" + vettingData.brandId + "' AND `iduser` = '" + sessdata.iduser + "'";
            obj.prepare();
            obj.execute((errBrand, resultBrand) => {
                if (errBrand == 1 && resultBrand.length > 0) {
                    if (error == 1) {
                        // To Get Brand Vetting List
                        let options = {
                            'method': 'GET',
                            'url': apiUrl + 'brand/' + vettingData.brandId + '/externalVetting/?evpId=' + vettingData.evpId + '&vettingClass=' + vettingData.vettingClass + '&vettingStatus=' + vettingData.vettingStatus + '',
                            'headers': {
                                'Content-Type': 'application/json',
                                'Authorization': 'Basic ' + authKey
                            }
                        };
                        request(options, (error, response) => {
                            if (!error) {
                                let resData = JSON.parse(response.body);
                                if (resData.length == 0) {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ message: "No Record Found!", status: 502 });
                                    objv.execute();
                                }
                                else if (resData[0].code && resData[0].code !== undefined && resData.length > 0) {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: resData[0].code, message: resData[0].field + ' ' + resData[0].description });
                                    objv.execute();
                                }
                                else {
                                    resData.forEach((element) => {
                                        // To Update Brand Vetting
                                        let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                        obj0.nonqrysql = "UPDATE `brand_vetting` SET `evpId`='" + element.evpId + "', `vettingId`='" + element.vettingId + "',`vettingToken`='" + element.vettingToken + "',`vettingScore`='" + element.vettingScore + "',`vettingClass`='" + element.vettingClass + "',`vettingStatus`='" + element.vettingStatus + "',`reasons`='" + element.reasons + "',`vettingDetails`='" + JSON.stringify(element.vettingDetails) + "',`vettedDate`='" + element.vettedDate + "',`createdDate`='" + element.createDate + "' WHERE `vettingId` = '" + element.vettingId + "' AND `vettingStatus` != 'ACTIVE' AND `iduser`='" + sessdata.iduser + "'";
                                        obj0.prepare();
                                        obj0.execute((___error, resp) => { });
                                    });
                                    // To Show Brand Vetting Response
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: 200, message: "Record Fetched Successfully!", data: resData });
                                    objv.execute();
                                }
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ message: "Something Went Wrong With Request!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new _406_1.Res406(res);
                        objv.prepare(session);
                        objv.execute();
                    }
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ status: 502, message: "Brand Does Not Exist!" });
                    objv.execute();
                }
            });
        });
    }
    /*******************************************************************
    * Get Multiple External Vetting List By Brand Id And Status Update *
    *******************************************************************/
    externalVettingBulkUpdate(req, res, next) {
        let data = JSON.parse(req.body.data);
        let brandId = data.brandId;
        let iduserVal = data.iduser;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = iduserVal !== undefined ? iduserVal : sessdata.iduser;
            // To Check Brand Exist Or Not
            let obj = new RawQuery_1.ModelRawQuery(req, res);
            obj.qrysql = "SELECT entityType FROM `brand` WHERE brandId='" + brandId + "' AND `iduser` = '" + iduser + "'";
            obj.prepare();
            obj.execute((errBrand, resultBrand) => {
                if (errBrand == 1 && resultBrand.length > 0) {
                    if (error == 1) {
                        // To Get All Vetting Detail By Brand
                        let obj00 = new RawQuery_1.ModelRawQuery(req, res);
                        obj00.qrysql = "SELECT vettingStatus,brandId,vettingClass,evpId,paid_time FROM `brand_vetting` WHERE brandId='" + brandId + "' AND `iduser` = '" + iduser + "'";
                        obj00.prepare();
                        obj00.execute((errAll, resultAll) => {
                            if (errAll == 1 && resultAll.length > 0) {
                                resultAll.forEach((ele) => {
                                    // To Get Brand Vetting List
                                    let options = {
                                        'method': 'GET',
                                        'url': apiUrl + 'brand/' + ele.brandId + '/externalVetting',
                                        'headers': {
                                            'Content-Type': 'application/json',
                                            'Authorization': 'Basic ' + authKey
                                        },
                                    };
                                    request(options, (error, response) => {
                                        if (!error) {
                                            let resData = JSON.parse(response.body);
                                            if (resData.length == 0) {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ message: "No Record Found!", status: 502 });
                                                objv.execute();
                                            }
                                            else if (resData[0].code && resData[0].code !== undefined && resData.length > 0) {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ status: resData[0].code, message: resData[0].field + ' ' + resData[0].description });
                                                objv.execute();
                                            }
                                            else {
                                                resData.forEach((element) => {
                                                    // To Update Brand Vetting with Price Deduction
                                                    let obj0 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                    obj0.nonqrysql = "UPDATE `brand_vetting` SET `evpId`='" + element.evpId + "', `vettingId`='" + element.vettingId + "',`vettingToken`='" + element.vettingToken + "',`vettingScore`='" + element.vettingScore + "',`vettingClass`='" + element.vettingClass + "',`vettingStatus`='" + element.vettingStatus + "',`reasons`='" + element.reasons + "',`vettingDetails`='" + JSON.stringify(element.vettingDetails) + "',`vettedDate`='" + element.vettedDate + "',`createdDate`='" + element.createDate + "' WHERE `vettingId` = '" + element.vettingId + "' AND `iduser`='" + iduser + "'";
                                                    obj0.prepare();
                                                    obj0.execute((___error, resp) => { });
                                                });
                                            }
                                        }
                                    });
                                });
                                // To Show Brand Vetting Response
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ status: 200, message: "Record Updated!", data: resultAll });
                                objv.execute();
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ status: 502, message: "No Record Found!" });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new _406_1.Res406(res);
                        objv.prepare(session);
                        objv.execute();
                    }
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ status: 502, message: "Brand Does Not Exist!" });
                    objv.execute();
                }
            });
        });
    }
    /****************
    * 's AutoRenual *
    ****************/
    revetBrand(req, res, next) {
        let reqQry = req.query;
        let reqData = req.body;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = sessdata.iduser;
            if (error == 1) {
                let options = {
                    'method': 'PUT',
                    'url': apiUrl + 'brand/' + reqQry.brandId + '/revet',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    },
                    body: JSON.stringify({ nonBlocking: reqData.nonBlocking })
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let resData = JSON.parse(response.body);
                        if (resData.brandId && resData.brandId !== undefined) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Revet Successfully!", data: resData, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: resData[0].code, message: resData[0].field + ' ' + resData[0].description });
                            objv.execute();
                        }
                    }
                    // if (!error) {
                    //     let resData = JSON.parse(response.body);
                    //     if (resData.campaignId && resData.campaignId !== undefined) {
                    //         let obj = new ModelRawNonQuery(req, res);
                    //         obj.nonqrysql = "UPDATE `campaign` SET `campaign_description`='" + resData.description + "',`sample1`='" + resData.sample1 + "',`sample2`='" + resData.sample2 + "',`sample3`='" + resData.sample3 + "',`sample4`='" + resData.sample4 + "',`sample5`='" + resData.sample5 + "',`messageFlow`='" + resData.messageFlow + "',`helpMessage`='" + resData.helpMessage + "',`optinKeywords`='" + resData.optinKeywords + "',`optoutKeywords`='" + resData.optoutKeywords + "',`helpKeywords`='" + resData.helpKeywords + "',`optinMessage`='" + resData.optinMessage + "',`optoutMessage`='" + resData.optoutMessage + "',`autoRenewal`='" + resData.autoRenewal + "',`campaign_status`='" + resData.status + "' WHERE `campaign_key`='" + campId + "' AND `iduser`='" + iduser + "'";
                    //         obj.prepare();
                    //         obj.execute((___error, resp) => {
                    //             if (!error) {
                    //                 let objv = new RawView(res);
                    //                 objv.prepare({ status: 200, message: "Campaign details Updated Successfully!", data: resData });
                    //                 objv.execute();
                    //             }
                    //             else {
                    //                 let objv = new RawView(res);
                    //                 objv.prepare({ message: "Campaign details Not updated", data: resData, status: 501 });
                    //                 objv.execute();
                    //             }
                    //         })
                    //     }
                    //     else {
                    //         let objv = new RawView(res);
                    //         objv.prepare({ message: resData[0].field + " " + resData[0].description, error: resData, status: resData[0].code });
                    //         objv.execute();
                    //     }
                    // }
                    // else {
                    //     let objv = new RawView(res);
                    //     objv.prepare({ error: error, message: "Something Went Wrong With Request!", status: 502 });
                    //     objv.execute();
                    // }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /****************************************
    * Get campaing's DID limit and counting *
    ****************************************/
    getCampaignDIDCount(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let camp_key = sdata.type;
                let iduser = sdata.filter;
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT did_limit, did_count FROM `campaign` WHERE campaign_key='" + camp_key + "' AND iduser='" + iduser + "' GROUP BY `campaign_key`";
                obj.prepare();
                obj.execute((err, result) => {
                    if (err == 1 && result.length > 0) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'DID Fatched Successfully!', data: result, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "NO DID available in this Campaign!", data: [], status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /*********************
    * Get campaing's DID *
    **********************/
    getCampaignDID(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let camp_key = sdata.type;
                let iduser = sdata.filter;
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT did FROM `did_buy` WHERE camp_registry='" + camp_key + "' AND iduser='" + iduser + "' GROUP BY `did`";
                obj.prepare();
                obj.execute((err, result) => {
                    if (err == 1 && result.length > 0) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'DID Fatched Successfully!', data: result, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "NO DID available in this Campaign!", data: [], status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /****************
    * Update CSP ID *
    ****************/
    updateCSPID(req, res, next) {
        let sdata = req.body;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessdata) => {
            if (sessErr == 1) {
                let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                obj.nonqrysql = "UPDATE `account` SET `csp_id`= '" + sdata.csp_id + "' WHERE idaccount= '" + sessdata.idaccount + "'";
                obj.prepare();
                obj.execute((error, result) => {
                    if (error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "CSP ID Updated Successfully", data: result, 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 RawView_1.RawView(res);
                objv.prepare({ message: "Invalid Session trying to access", status: 401 });
                objv.execute();
            }
        });
    }
    /****************
    * Get CSP ID *
    ****************/
    getCspId(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((sessErr, sessData) => {
            if (sessErr == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT `csp_id` FROM `account` WHERE idaccount='" + sessData.idaccount + "'";
                obj.prepare();
                obj.execute((err, result) => {
                    if (err == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: 'CSP ID Fatched', data: result, 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: "Invalid Authorization!", status: 401 });
                objv.execute();
            }
        });
    }
    /********************
  * CNP Campaigns Filters *
  ********************/
    CNPcampaignFilter(req, res, next) {
        let data = req.body.data;
        let condition = "";
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                if (data.brandId)
                    condition += '`brandId` LIKE "%' + data.brandId + '%" AND ';
                if (data.brand_name)
                    condition += '`brand_name` LIKE "%' + data.brand_name + '%" AND ';
                if (data.campaign_key)
                    condition += '`campaign_key` LIKE "%' + data.campaign_key + '%" AND ';
                if (data.usecase)
                    condition += '`usecase`="' + data.usecase + '" AND ';
                //obj.qrysql = "SELECT * FROM `campaign` WHERE `iduser` = '" + sessdata.iduser + "' AND " + condition + " `status`=1 GROUP BY campaign_key";
                obj.qrysql = "SELECT b.brandId, b.brand_name,c.campaign_key,c.campaign_name,c.usecase,c.start_date,c.did_count,c.did_limit FROM `brand`b INNER JOIN `campaign`c ON c.idbrand = b.brandId WHERE " + condition + " c.`iduser` = '" + sessdata.iduser + "' AND c.`status`= 1 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "CNP Campaign List Fetched Successfully!",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Something Went Wrong With Fetched CNP Campaign List!",
                            status: 502,
                            error: result
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /********************
    * Get CNP Campaigns *
    ********************/
    getCNPCampaign(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 b.brandId, b.brand_name,c.campaign_key,c.campaign_name,c.usecase,c.start_date,c.did_count,c.did_limit FROM `brand`b INNER JOIN `campaign`c ON c.idbrand = b.brandId WHERE c.`iduser` = '" + sessdata.iduser + "' AND c.`status`= 1 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign Fetched Successfully!",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Something Went Wrong With Campaign List!",
                            status: 502,
                            error: result
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /****************************************
    * Send a mock webhook to your endpoint  *
    ****************************************/
    mockWebhookEndpoint(req, res, next) {
        let reqQry = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = sessdata.iduser;
            if (error == 1) {
                let options = {
                    'method': 'PUT',
                    'url': apiUrl + 'webhook/subscription/eventType/' + reqQry.eventType + '/mock',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let resData = JSON.parse(response.body);
                        if (resData.brandId && resData.brandId !== undefined) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Revet Successfully!", data: resData, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ status: resData[0].code, message: resData[0].field + ' ' + resData[0].description });
                            objv.execute();
                        }
                    }
                    // if (!error) {
                    //     let resData = JSON.parse(response.body);
                    //     if (resData.campaignId && resData.campaignId !== undefined) {
                    //         let obj = new ModelRawNonQuery(req, res);
                    //         obj.nonqrysql = "UPDATE `campaign` SET `campaign_description`='" + resData.description + "',`sample1`='" + resData.sample1 + "',`sample2`='" + resData.sample2 + "',`sample3`='" + resData.sample3 + "',`sample4`='" + resData.sample4 + "',`sample5`='" + resData.sample5 + "',`messageFlow`='" + resData.messageFlow + "',`helpMessage`='" + resData.helpMessage + "',`optinKeywords`='" + resData.optinKeywords + "',`optoutKeywords`='" + resData.optoutKeywords + "',`helpKeywords`='" + resData.helpKeywords + "',`optinMessage`='" + resData.optinMessage + "',`optoutMessage`='" + resData.optoutMessage + "',`autoRenewal`='" + resData.autoRenewal + "',`campaign_status`='" + resData.status + "' WHERE `campaign_key`='" + campId + "' AND `iduser`='" + iduser + "'";
                    //         obj.prepare();
                    //         obj.execute((___error, resp) => {
                    //             if (!error) {
                    //                 let objv = new RawView(res);
                    //                 objv.prepare({ status: 200, message: "Campaign details Updated Successfully!", data: resData });
                    //                 objv.execute();
                    //             }
                    //             else {
                    //                 let objv = new RawView(res);
                    //                 objv.prepare({ message: "Campaign details Not updated", data: resData, status: 501 });
                    //                 objv.execute();
                    //             }
                    //         })
                    //     }
                    //     else {
                    //         let objv = new RawView(res);
                    //         objv.prepare({ message: resData[0].field + " " + resData[0].description, error: resData, status: resData[0].code });
                    //         objv.execute();
                    //     }
                    // }
                    // else {
                    //     let objv = new RawView(res);
                    //     objv.prepare({ error: error, message: "Something Went Wrong With Request!", status: 502 });
                    //     objv.execute();
                    // }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /**************************************************************************
    * End Brand Functionality  ************************************************
    **************************************************************************/
    /***************************************************************************
    * Start Campaign Functionality *********************************************
    ***************************************************************************/
    campaignFilterForBrand(req, res, next) {
        let Cdata = JSON.parse(req.body.data);
        let data = Cdata.companyFilter;
        let condition = "";
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                if (data.usecase)
                    condition += '`usecase`="' + data.usecase + '" AND ';
                if (data.description)
                    condition += '`campaign_description` LIKE "%' + data.description + '%" AND ';
                if (data.campaignId)
                    condition += '`campaign_key` LIKE "%' + data.campaignId + '%" AND ';
                obj.qrysql = "SELECT `campaign_key`,`usecase`,`campaign_description`,DATE_FORMAT(start_date,'%Y-%m-%d')`start_date` FROM `campaign` WHERE " + condition + " `idbrand` = '" + Cdata.brandId + "'AND iduser='" + Cdata.iduser + "' AND `deleted`=0 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign 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();
            }
        });
    }
    getCampaignByBrandId(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let data = req.query;
                let brandId = req.query.type !== undefined ? JSON.parse(data.type).brandId : req.query.brandId;
                let iduser = req.query.type !== undefined ? JSON.parse(data.type).iduser : sessdata.iduser;
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT `campaign_key`,`usecase`,`campaign_description`,DATE_FORMAT(start_date,'%Y-%m-%d')`start_date` FROM `campaign` WHERE `idbrand` = '" + brandId + "'AND iduser='" + iduser + "' AND `status`=0 AND `deleted`=0 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign 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();
            }
        });
    }
    getCampaign(req, res, next) {
        let sdata = req.query;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = sdata.type !== undefined && sdata.type !== 'main' ? JSON.parse(sdata.type).iduser : sessdata.iduser;
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT MAX(b.brandId) AS brandId,MAX(b.brand_name) AS brand_name,MAX(b.referenceId) AS referenceId,MAX(c.iduser) AS iduser,MAX(c.idaccount) AS idaccount,c.campaign_key,MAX(c.usecase) AS usecase,MAX(c.start_date) AS start_date,MAX(c.did_count) AS did_count,MAX(c.did_limit) AS did_limit FROM brand b INNER JOIN campaign c ON c.idbrand = b.brandId WHERE c.iduser = '" + iduser + "' AND c.deleted = 0 GROUP BY c.campaign_key;";
                // obj.qrysql = "SELECT b.brandId,b.brand_name,b.referenceId,c.iduser,c.idaccount,c.campaign_key,c.usecase,c.start_date,c.did_count,c.did_limit FROM `brand`b INNER JOIN `campaign`c ON c.idbrand = b.brandId WHERE c.`iduser` = '" + iduser + "' AND c.`deleted` = 0 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign 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();
            }
        });
    }
    // Get Campaign For Admin
    getCampaignForAdmin(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 * FROM `campaign` where `deleted`=0 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign 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();
            }
        });
    }
    getCampaignCases(req, res, callback) {
        let id;
        let options = {
            'method': 'Get',
            'url': apiUrl + 'enum/usecase',
            'headers': {
                'Content-Type': 'application/json',
                'Authorization': 'Basic ' + authKey
            }
        };
        request(options, (_err, response, body) => {
            if (response.body) {
                let data = JSON.parse(response.body);
                if (!_err) {
                    /*let tmp:any=[];
                    Object.entries(data).forEach((ele:any)=>{
                      let t=ele[1];
                      t["isDisable"] = false;
                      t["name"]=ele[0];
                      tmp.push(t);
                    });

                    console.log(tmp);

                    let tmpqurty="INSERT INTO `campaign_cases` (`name`, `displayName`, `minSubUsecases`, `maxSubUsecases`, `validSubUsecase`, `classification`) VALUES ";
                    tmp.forEach((campaignData: any) => {
                        console.log(campaignData, "campData");
                        tmpqurty += "('"+campaignData.name+"', '"+campaignData.displayName+"', '"+campaignData.minSubUsecases+"', '"+campaignData.maxSubUsecases+"', '"+campaignData.validSubUsecase+"', '"+campaignData.classification+"'),";
                    });
                    let obj = new ModelRawNonQuery(req, res);
                    obj.nonqrysql =tmpqurty.slice(0, -1);
                    obj.prepare();
                    obj.execute((_error: any, data: any) => {
                        if(data.length > 0){
                            let objv = new RawView(res);
                            objv.prepare({ message: "Cases Fetched Successfully!", data: data });
                            objv.execute();
                        }
                        else{
                            let objv = new RawView(res);
                            objv.prepare({ message: "Something Went Wrong!", error: _error });
                            objv.execute();
                        }
                    });*/
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Campaign Cases Fetched!", data: data, status: 200 });
                    objv.execute();
                }
                else {
                    let objv = new RawView_1.RawView(res);
                    objv.prepare({ message: "Something Went Wrong With Connection!", error: data, status: 502 });
                    objv.execute();
                }
            }
            else {
                let objv = new RawView_1.RawView(res);
                objv.prepare({ message: "Something Went Wrong With Connection!", error: _err, status: 502 });
                objv.execute();
            }
        });
    }
    campaignCases(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 `idcamp_cases`,`name`,`displayName`,`minSubUsecases`,`validSubUsecase`,`maxSubUsecases`,`rate`,`classification`,`nrc_rates`,`service_limit`,`description` FROM `campaign_cases`";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign Case Fetches",
                            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();
            }
        });
    }
    registerCampaign(req, res, next) {
        let campData = req.body;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let objb = new RawQuery_1.ModelRawQuery(req, res);
                objb.qrysql = "SELECT brandId,entityType,identityStatus From `brand` WHERE `brandId`='" + campData.brandId + "' AND `entityType`='SOLE_PROPRIETOR'";
                objb.prepare();
                objb.execute((bError, bRes) => {
                    if (bError == 1 && bRes.length > 0) {
                        let objc = new RawQuery_1.ModelRawQuery(req, res);
                        objc.qrysql = "SELECT idbrand From `campaign` WHERE `idbrand`='" + bRes[0].brandId + "'";
                        objc.prepare();
                        objc.execute((cError, cRes) => {
                            if (cError == 1 && cRes.length < 1) {
                                // fOR Sole proprietor
                                let fun = new NewCampaign();
                                fun.inRegisterCampaign(req, res, next);
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({ error: cError, message: "1 Campaign Already Exits in This Brand " + campData.brandId, status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        // FOR any entity type 
                        let fun = new NewCampaign();
                        fun.inRegisterCampaign(req, res, next);
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    inRegisterCampaign(req, res, next) {
        let campData = req.body;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((err, sessdata) => {
            if (err == 1) {
                let obj0 = new RawQuery_1.ModelRawQuery(req, res);
                obj0.qrysql = "SELECT *, (IFNULL(rate, 0) + IFNULL(nrc_rates, 0)) totalRates, service_limit From `campaign_cases` WHERE `name`='" + campData.usecase + "'";
                obj0.prepare();
                obj0.execute((campError, camp) => {
                    if (campError == 1) {
                        //-- Get SMS Provider 
                        let obj1 = new RawQuery_1.ModelRawQuery(req, res);
                        obj1.qrysql = "SELECT p.`priority`, UPPER(u.`username`)`username` FROM preference p LEFT JOIN `user` u ON p.idsupplier=u.idaccount WHERE p.idservice=(SELECT idservice FROM `user` WHERE iduser = '" + sessdata.iduser + "' ) AND p.type='sms'";
                        obj1.prepare();
                        obj1.execute((proerr, provider) => {
                            if (proerr == 1 && provider.length > 0) {
                                let CRate = typeof camp[0].totalRates != 'undefined' && camp[0].totalRates > 0 ? camp[0].totalRates : 0;
                                let __rate = typeof camp[0].rate != 'undefined' && camp[0].rate > 0 ? camp[0].rate : 0;
                                let __nrc_rates = typeof camp[0].nrc_rates != 'undefined' && camp[0].nrc_rates > 0 ? camp[0].nrc_rates : 0;
                                if (CRate > 0) {
                                    let Obj = new RawQuery_1.ModelRawQuery(req, res);
                                    Obj.qrysql = "SELECT * FROM `wallet` WHERE `idaccount`='" + sessdata.idaccount + "' AND `balance` + `credit_limit` >= '" + CRate + "'";
                                    Obj.prepare();
                                    Obj.execute((bErr, bRes) => {
                                        if (bErr == 1) {
                                            if (bRes.length > 0) {
                                                var key;
                                                let options = {
                                                    'method': 'POST',
                                                    'url': apiUrl + 'campaignBuilder',
                                                    'headers': {
                                                        'Content-Type': 'application/json',
                                                        'Authorization': 'Basic ' + authKey
                                                    },
                                                    body: JSON.stringify(campData)
                                                };
                                                request(options, (error, response, body) => {
                                                    if (!error) {
                                                        let resData = JSON.parse(response.body);
                                                        if (resData.campaignId) {
                                                            let tmp = [];
                                                            let options = {
                                                                'method': 'PUT',
                                                                'url': apiUrl + 'partnerCampaign/' + resData.campaignId + '/sharing/' + provider[0].username,
                                                                'headers': {
                                                                    'Content-Type': 'application/json',
                                                                    'Authorization': 'Basic ' + authKey
                                                                }
                                                            };
                                                            request(options, (error, response, body) => {
                                                                let partnerCampaign = JSON.parse(response.body);
                                                                if (response.body) {
                                                                    Object.entries(resData.mnoMetadata).forEach((ele) => {
                                                                        let t = ele[1];
                                                                        t["class"] = ele[0];
                                                                        tmp.push(t);
                                                                    });
                                                                    let campaignData1 = tmp;
                                                                    campData.sample1 = campData.sample1.replace(/"/g, '\\"').replace(/'/g, "\\'");
                                                                    campData.sample2 = campData.sample2.replace(/"/g, '\\"').replace(/'/g, "\\'");
                                                                    if (campData.sample3) {
                                                                        campData.sample3 = campData.sample3.replace(/"/g, '\\"').replace(/'/g, "\\'");
                                                                    }
                                                                    else {
                                                                        campData.sample3 = '';
                                                                    }
                                                                    if (campData.sample4) {
                                                                        campData.sample4 = campData.sample4.replace(/"/g, '\\"').replace(/'/g, "\\'");
                                                                    }
                                                                    else {
                                                                        campData.sample4 = '';
                                                                    }
                                                                    if (campData.sample5) {
                                                                        campData.sample5 = campData.sample5.replace(/"/g, '\\"').replace(/'/g, "\\'");
                                                                    }
                                                                    else {
                                                                        campData.sample5 = '';
                                                                    }
                                                                    campData.description = campData.description.replace(/"/g, '\\"').replace(/'/g, "\\'");
                                                                    let tmpqurty = "INSERT INTO `campaign` (`iduser`,`idbrand`,`campaign_key`, `campaign_class`, `campaign_name`, `minMsgSamples`,`mno`, `mnoReview`, `mnoSupport`, `msgClass`, `noEmbeddedLink`, `noEmbeddedPhone`,`qualify`,`reqSubscriberHelp`, `reqSubscriberOptin`, `reqSubscriberOptout`, `surcharge`, `tpn`, `brandTier`, `campaign_description`, `messageFlow`, `optinMessage`, `optoutMessage`, `helpMessage`, `downstreamCnpId`, `upstreamCnpId`, `sharingStatus`, `sharedDate`, `statusDate`, `vertical`, `sample1`, `sample2`, `sample3`, `sample4`, `sample5`, `usecase`, `subUsecases`,`autoRenewal`, `affiliateMarketing`, `termsAndConditions`, `numberPool`,`ageGated`, `directLending`, `did_limit`,`tpm`,`mmsTpm`,`tpmScope`,`brandDailyCap`) VALUES ";
                                                                    campaignData1.forEach((campaignData) => {
                                                                        tmpqurty += "('" + sessdata.iduser + "','" + campData.brandId + "', '" + resData.campaignId + "', '" + campaignData.class + "', '" + campData.campaignName + "', '" + campaignData.minMsgSamples + "', '" + campaignData.mno + "', '" + campaignData.mnoReview + "', '" + campaignData.mnoSupport + "', '" + campaignData.msgClass + "', '" + campaignData.noEmbeddedLink + "', '" + campaignData.noEmbeddedPhone + "', '" + campaignData.qualify + "', '" + campaignData.reqSubscriberHelp + "', '" + campaignData.reqSubscriberOptin + "', '" + campaignData.reqSubscriberOptin + "', '" + campaignData.surcharge + "', '" + campaignData.tpn + "', '" + campaignData.brandTier + "', '" + campData.description + "', '" + campData.messageFlow + "', '" + campData.optinMessage + "', '" + campData.optoutMessage + "', '" + campData.helpMessage + "', '" + partnerCampaign.downstreamCnpId + "', '" + partnerCampaign.upstreamCnpId + "', '" + partnerCampaign.sharingStatus + "', '" + partnerCampaign.sharedDate + "', '" + partnerCampaign.statusDate + "', '" + campData.vertical + "', '" + campData.sample1 + "', '" + campData.sample2 + "', '" + campData.sample3 + "', '" + campData.sample4 + "', '" + campData.sample5 + "', '" + campData.usecase + "', '" + campData.subUsecases + "', '" + campData.autoRenewal + "', '" + campData.affiliateMarketing + "', '" + campData.termsAndConditions + "', '" + campData.numberPool + "', '" + campData.ageGated + "', '" + campData.directLending + "', '" + camp[0].service_limit + "','" + campaignData.tpm + "','" + campaignData.mmsTpm + "','" + campaignData.tpmScope + "','" + campaignData.brandDailyCap + "'),";
                                                                    });
                                                                    let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                    obj.nonqrysql = tmpqurty.slice(0, -1);
                                                                    obj.prepare();
                                                                    obj.execute((_error, data) => {
                                                                        if (_error == 1) {
                                                                            let obj3 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                            obj3.nonqrysql = "INSERT INTO `brand_log` (`idaccount`, `iduser`, `campaign_key`,`cost`, `date`, `description`, `nrc_rates`) VALUES ('" + sessdata.idaccount + "', '" + sessdata.iduser + "','" + resData.campaignId + "', '" + __rate + "', '" + Date.now() + "', 'Campaign_Rate', '" + __nrc_rates + "')";
                                                                            obj3.prepare();
                                                                            obj3.execute((___error, _resp) => {
                                                                                if (___error == 1) {
                                                                                    let obj4 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                                    obj4.nonqrysql = "INSERT INTO `campaign_log` (`idaccount`, `iduser`, `campaign_key`,`cost`, `description`, `nrc_rates`) VALUES ('" + sessdata.idaccount + "', '" + sessdata.iduser + "','" + resData.campaignId + "', '" + __rate + "', 'Campaign_Rate', '" + __nrc_rates + "')";
                                                                                    obj4.prepare();
                                                                                    obj4.execute((campErr, __resp) => {
                                                                                        if (campErr == 1) {
                                                                                            let obj2 = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                                            obj2.nonqrysql = "UPDATE `wallet` SET `balance`=`balance`-" + CRate + " WHERE `idaccount`='" + sessdata.idaccount + "'";
                                                                                            obj2.prepare();
                                                                                            obj2.execute((__error, resp) => {
                                                                                                if (__error == 1) {
                                                                                                    let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                                                                                    iQry += "`idaccount`=" + sessdata.idaccount + ", ";
                                                                                                    iQry += "`amount`='-" + CRate + "', ";
                                                                                                    iQry += "`purpose`='Wallet amount successfully updated for campaign registration', ";
                                                                                                    iQry += "`status`=1;";
                                                                                                    let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                                                                                    objWL.nonqrysql = iQry;
                                                                                                    objWL.prepare();
                                                                                                    objWL.execute((error, result) => {
                                                                                                        console.log("Transaction response::", result);
                                                                                                    });
                                                                                                    let objv = new RawView_1.RawView(res);
                                                                                                    objv.prepare({ status: 201, message: "Campaign Registered Successfully!", campaignId: resData.campaignId, data: resData });
                                                                                                    objv.execute();
                                                                                                }
                                                                                                else {
                                                                                                    let objv = new RawView_1.RawView(res);
                                                                                                    objv.prepare({ status: 502, message: "Campaign Registered Error With Updating Wallet!", campaignId: resData.campaignId, error: resp });
                                                                                                    objv.execute();
                                                                                                }
                                                                                            });
                                                                                        }
                                                                                        else {
                                                                                            let objv = new RawView_1.RawView(res);
                                                                                            objv.prepare({ status: 502, message: "Campaign Registered Error With Campaign Log!", campaignId: resData.campaignId, error: _resp });
                                                                                            objv.execute();
                                                                                        }
                                                                                    });
                                                                                }
                                                                                else {
                                                                                    let objv = new RawView_1.RawView(res);
                                                                                    objv.prepare({ status: 502, message: "Campaign Registered But Error With Log!", campaignId: resData.campaignId, error: _resp });
                                                                                    objv.execute();
                                                                                }
                                                                            });
                                                                        }
                                                                        else {
                                                                            let objv = new RawView_1.RawView(res);
                                                                            objv.prepare({ message: "Campaign Registered Error With Connection!", error: error, status: 502 });
                                                                            objv.execute();
                                                                        }
                                                                    });
                                                                }
                                                                else {
                                                                    let objv = new RawView_1.RawView(res);
                                                                    objv.prepare({ message: "Campaign Registered With Connection Error!", error: error, status: 502 });
                                                                    objv.execute();
                                                                }
                                                            });
                                                        }
                                                        else {
                                                            let objv = new RawView_1.RawView(res);
                                                            objv.prepare({ message: resData[0].field + " " + resData[0].description, status: 502 });
                                                            objv.execute();
                                                        }
                                                    }
                                                });
                                            }
                                            else {
                                                let objv = new RawView_1.RawView(res);
                                                objv.prepare({ error: bErr, message: "Please add funds to your account or contact support.", status: 503 });
                                                objv.execute();
                                            }
                                        }
                                        else {
                                            let objv = new RawView_1.RawView(res);
                                            objv.prepare({ error: bErr, message: "Something Went Wrong to Fetch Account Balance!", status: 502 });
                                            objv.execute();
                                        }
                                    });
                                }
                                else {
                                    let iQry = "INSERT INTO `wallet_recharge_log` SET ";
                                    iQry += "`idaccount`=" + sessdata.idaccount + ", ";
                                    iQry += "`amount`='-" + CRate + "', ";
                                    iQry += "`purpose`='Billing prorate should be greater then 0 to register a campaign', ";
                                    iQry += "`status`=2;";
                                    let objWL = new RawNonQuery_1.ModelRawNonQuery(req, res);
                                    objWL.nonqrysql = iQry;
                                    objWL.prepare();
                                    objWL.execute((error, result) => {
                                        console.log("Transaction response::", result);
                                    });
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({
                                        status: 502,
                                        message: "Billing prorate should be greater then 0 to register a campaign!",
                                        error: ""
                                    });
                                    objv.execute();
                                }
                            }
                            else {
                                let objv = new RawView_1.RawView(res);
                                objv.prepare({
                                    status: 502,
                                    message: "Service Profile not found!",
                                    error: proerr,
                                    campaignId: null
                                });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            status: 502,
                            message: "Error With Fatching Campaign Rates!",
                            error: camp,
                            campaignId: null
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    mnoIddetails(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((_error, sessdata) => {
            if (_error == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/mno',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "MNO Details Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With MNO Details Fetched!", error: error, status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*********************************************
    * get campaign details based on campaign id  *
    *********************************************/
    getCampDetailById(req, res, next) {
        let data = req.query;
        let sdata = req.query.type ? JSON.parse(data.type) : data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                let sdata = req.query.type ? JSON.parse(data.type) : data;
                obj.qrysql = "SELECT b.brandId,b.brand_name,c.iduser,c.idaccount,c.reqSubscriberOptin,c.reqSubscriberOptout,c.reqSubscriberHelp,c.campaign_key,c.usecase,c.start_date,c.sharedDate,c.statusDate,c.subUsecases,c.campaign_description,c.sample1,c.sample2,c.sample3,c.sample4,c.sample5,c.messageFlow,c.helpMessage,c.optinMessage,c.optoutMessage,c.optinKeywords,c.optoutKeywords,c.helpKeywords,c.autoRenewal,c.noEmbeddedLink,c.noEmbeddedPhone,c.affiliateMarketing,c.termsAndConditions,c.numberPool,c.ageGated,c.directLending FROM `campaign`c INNER JOIN `brand`b ON b.brandId = c.idbrand WHERE `campaign_key`='" + sdata.campId + "' AND c.`iduser` = '" + sdata.iduser + "' AND c.`deleted` = 0 GROUP BY campaign_key";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign Detail Fetched Successfully!",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Something Went Wrong With Fetched Campaign Detail!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*********************************************
    * get campaign Mno details based on campaign id  *
    *********************************************/
    getMnoMetaDataDetails(req, res, next) {
        let data = req.query;
        let sdata = req.query.type ? JSON.parse(data.type) : data;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let obj = new RawQuery_1.ModelRawQuery(req, res);
                obj.qrysql = "SELECT iduser,campaign_class,mno,mnoReview,mnoSupport, (CASE WHEN msgClass ='undefined' THEN 'N/A' ELSE msgClass END )`msgClass` ,qualify,reqSubscriberOptin,reqSubscriberOptout,reqSubscriberHelp,noEmbeddedLink,noEmbeddedPhone,tpn,usecase,(CASE WHEN brandTier ='undefined' THEN 'N/A' ELSE brandTier END )`brandTier`,(CASE WHEN tpm ='undefined' THEN 'N/A' ELSE tpm END)`tpm`,(CASE WHEN mmsTpm ='undefined' THEN 'N/A' ELSE mmsTpm END )`mmsTpm`,(CASE WHEN tpmScope ='undefined' THEN 'N/A' ELSE tpmScope END )`tpmScope`,(CASE WHEN brandDailyCap ='undefined' THEN 'N/A' ELSE brandDailyCap END )`brandDailyCap` FROM `campaign` WHERE `campaign_key`='" + sdata.campId + "' AND `iduser`='" + sdata.iduser + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Campaign Mno Detail Fetched Successfully!",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Something Went Wrong With Fetched Campaign Mno Detail!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getMnoMetaDataForRegister(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let data = req.query;
            let brandId = data.type !== undefined ? JSON.parse(data.type).brandId : data.brandId;
            let usecase = data.type !== undefined ? JSON.parse(data.type).usecase : data.usecase;
            if (error == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'campaignBuilder/brand/' + brandId + '/usecase/' + usecase,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let data = JSON.parse(response.body);
                        if (data.mnoMetadata && data.mnoMetadata != undefined) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Mno Meta Details Records Fetched!", data: data.mnoMetadata, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: data[0].field + " " + data[0].description, status: data[0].code });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With API!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    brandQualifyAllUseCases(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let data = req.query;
            let brandId = data.type !== undefined ? JSON.parse(data.type).brandId : data.brandId;
            if (error == 1) {
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'campaignBuilder/brand/' + brandId,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let data = JSON.parse(response.body);
                        if (data && data != undefined) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Use Case Records Fetched!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: data[0].field + " " + data[0].description, status: data[0].code });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With API!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getConnPartnersDetails(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/cnp',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Connectivity Partners Fetched!", data: data, 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!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getResellerDetails(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'reseller/RAP07Z4',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Reseller Records Fetched!", data: data, 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!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getMNOList(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let options = {
                    'method': 'Get',
                    'url': apiUrl + 'enum/mno',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        if (response.body) {
                            let data = JSON.parse(response.body);
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "MNO ID's Fetched Successfully!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Something Went Wrong With Fetched MNO ID's!", error: error, status: 502 });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    mnoMetaData(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let campId = req.query;
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'campaign/' + campId.campaignId + '/mnoMetadata',
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let data = JSON.parse(response.body);
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "MNO MetaData Fetched successfully!", data: data, status: 200 });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    getCampDetails(req, res, next) {
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let campId = req.query;
                let options = {
                    'method': 'GET',
                    'url': apiUrl + 'campaign/' + campId.campaignId,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let data = JSON.parse(response.body);
                        if (data.campaignId && data.campaignId !== undefined) {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: "Campaign Details Fetched successfully!", data: data, status: 200 });
                            objv.execute();
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: data[0].field + " " + data[0].description, error: data, status: data[0].code });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ message: "Something Went Wrong With Connection!", error: error, status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /****************
    * 's AutoRenual *
    ****************/
    updateCamapign(req, res, next) {
        let reqData = req.body.data !== undefined ? JSON.parse(req.body.data).mainData : req.body;
        let campId = req.body.data !== undefined ? JSON.parse(req.body.data).campId : req.query.campaignId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = req.body.data !== undefined ? JSON.parse(req.body.data).iduser : sessdata.iduser;
            var resultAllCampaign = [];
            for (var i in reqData) {
                if (reqData[i] !== '' && reqData[i] !== 'undefined') {
                    resultAllCampaign.push([i, reqData[i]]);
                }
            }
            let campData = Object.fromEntries(resultAllCampaign);
            if (error == 1) {
                let options = {
                    'method': 'PUT',
                    'url': apiUrl + 'campaign/' + campId,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    },
                    body: JSON.stringify(campData)
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let resData = JSON.parse(response.body);
                        if (resData.campaignId && resData.campaignId !== undefined) {
                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj.nonqrysql = "UPDATE `campaign` SET `campaign_description`='" + resData.description + "',`sample1`='" + resData.sample1 + "',`sample2`='" + resData.sample2 + "',`sample3`='" + resData.sample3 + "',`sample4`='" + resData.sample4 + "',`sample5`='" + resData.sample5 + "',`messageFlow`='" + resData.messageFlow + "',`helpMessage`='" + resData.helpMessage + "',`optinKeywords`='" + resData.optinKeywords + "',`optoutKeywords`='" + resData.optoutKeywords + "',`helpKeywords`='" + resData.helpKeywords + "',`optinMessage`='" + resData.optinMessage + "',`optoutMessage`='" + resData.optoutMessage + "',`autoRenewal`='" + resData.autoRenewal + "',`campaign_status`='" + resData.status + "' WHERE `campaign_key`='" + campId + "' AND `iduser`='" + iduser + "'";
                            obj.prepare();
                            obj.execute((___error, resp) => {
                                if (!error) {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: 200, message: "Campaign details Updated Successfully!", data: resData });
                                    objv.execute();
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ message: "Campaign details Not updated", data: resData, status: 501 });
                                    objv.execute();
                                }
                            });
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: resData[0].field + " " + resData[0].description, error: resData, status: resData[0].code });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ error: error, message: "Something Went Wrong With Request!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*******************************
    *  Update Campaign's AutoRenual*
    *******************************/
    updateAutoRenualCampaign(req, res, next) {
        let reqData = req.body;
        let campId = req.query.campaignId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            let iduser = sessdata.iduser;
            var reqCampaign = [];
            for (var i in reqData) {
                if (reqData[i] !== '' && reqData[i] !== 'undefined') {
                    reqCampaign.push([i, reqData[i]]);
                }
            }
            let campData = Object.fromEntries(reqCampaign);
            if (error == 1) {
                let options = {
                    'method': 'PUT',
                    'url': apiUrl + 'campaign/' + campId,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    },
                    body: JSON.stringify(campData)
                };
                request(options, (error, response, body) => {
                    if (!error) {
                        let resData = JSON.parse(response.body);
                        if (resData.campaignId && resData.campaignId !== undefined) {
                            let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                            obj.nonqrysql = "UPDATE `campaign` SET `autoRenewal`='" + resData.autoRenewal + "',`campaign_status`='" + resData.status + "' WHERE `campaign_key`='" + campId + "' AND `iduser`='" + iduser + "'";
                            obj.prepare();
                            obj.execute((___error, resp) => {
                                if (!error) {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ status: 200, message: "autoRenewal Updated Successfully!", data: resData });
                                    objv.execute();
                                }
                                else {
                                    let objv = new RawView_1.RawView(res);
                                    objv.prepare({ message: "autoRenewal Not updated", data: resData, status: 501 });
                                    objv.execute();
                                }
                            });
                        }
                        else {
                            let objv = new RawView_1.RawView(res);
                            objv.prepare({ message: resData[0].field + " " + resData[0].description, error: resData, status: resData[0].code });
                            objv.execute();
                        }
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({ error: error, message: "Something Went Wrong With Request!", status: 502 });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    deleteCampaign(req, res, next) {
        let campID = req.query.id && req.query.id !== undefined ? req.query.id : req.query.campaignId;
        let session = new Session_1.SessionManagment(req, res, next);
        session.GetSession((error, sessdata) => {
            if (error == 1) {
                let options = {
                    'method': 'DELETE',
                    'url': apiUrl + 'campaign/' + campID,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Authorization': 'Basic ' + authKey
                    }
                };
                request(options, (error, response, body) => {
                    if ((response.statusCode == 204 && response.statusCode !== undefined) || (JSON.parse(body)[0].code == 502 && JSON.parse(body)[0].code !== undefined)) {
                        let obj = new RawNonQuery_1.ModelRawNonQuery(req, res);
                        obj.nonqrysql = "UPDATE `campaign` SET `deleted`=1, `delete_date`=NOW() WHERE `campaign_key`='" + campID + "' AND `iduser`='" + sessdata.iduser + "'";
                        obj.prepare();
                        obj.execute((__error, camp) => {
                            if (__error == 1) {
                                obj.nonqrysql = "DELETE FROM `brand_log` WHERE `campaign_key`='" + campID + "' ";
                                obj.prepare();
                                obj.execute((__error, lastid) => {
                                    if (__error == 1) {
                                        let objv = new RawView_1.RawView(res);
                                        objv.prepare({ message: "Campaign Deleted Successfully!", campaignId: campID, data: lastid[0], 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 RawView_1.RawView(res);
                                objv.prepare({ message: "Campaign Delate Not Updated Successfully!", status: 502 });
                                objv.execute();
                            }
                        });
                    }
                    else {
                        let data = JSON.parse(body);
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: data[0].field + ' ' + data[0].description,
                            status: data[0].code
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
    /*************************************************************************
    * End Campaign Functionality *********************************************
    **************************************************************************/
    /*********************************************
    *Start get Tariff details based on TariffId  *
    *********************************************/
    getSubscriptionPlan(req, res, next) {
        let data = req.query;
        let sdata = JSON.parse(data.type);
        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 u.idtariff,t.name FROM `user`u INNER JOIN `tariff`t ON u.idtariff = t.idtariff WHERE u.`iduser`='" + sdata.iduser + "' AND u.`idaccount` = '" + sdata.idaccount + "'";
                obj.prepare();
                obj.execute((_error, result) => {
                    if (_error == 1) {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            data: result,
                            message: "Tariff Detail Fetched Successfully!",
                            status: 200
                        });
                        objv.execute();
                    }
                    else {
                        let objv = new RawView_1.RawView(res);
                        objv.prepare({
                            message: "Something Went Wrong With Fetched Tariff Detail!",
                            status: 502
                        });
                        objv.execute();
                    }
                });
            }
            else {
                let objv = new _406_1.Res406(res);
                objv.prepare(session);
                objv.execute();
            }
        });
    }
}
exports.NewCampaign = NewCampaign;
