payout_controller

mail@pastecode.io avatar
unknown
plain_text
a year ago
19 kB
2
Indexable
Never
// Author :
// Date (dd-mmm-yy) :
// Last updated by :
// Last updated Date (dd-mmm-yy):
// Description :

import HeaderCommonData from "../controller/HeaderController.js";
import menuactive from "../helpers/menuactive.js";
import MenuModel from "../models/MenuSchema.js";
import SubmenuModel from "../models/SubMenuSchema.js";
import SubsubmenuModel from "../models/SubsubmenuSchema.js";
import PermissionData from "../models/Permission.js";
import PayoutRequestModel from "../models/PayoutRequestSchema.js";
import RejectedReasonModel from "../models/RejectedReasonSchema.js";
import PayoutRequestLogModel from "../models/PayoutRequestLogSchema.js";
import { publicIp, publicIpv4, publicIpv6 } from "public-ip";
import getMAC, { isMAC } from "getmac";
import sql from "mssql";
import config from "../config/config1.js";
const header_data = await HeaderCommonData.CommonData();
import { CheckLogin } from "./helper/AuthController.js";

// const headerdynemicdata = await MenuModel.find({status:"1"})
// const submenu_list = await SubmenuModel.find({status:"1"}).populate('menu_id')
// const subsubmanu_list = await SubsubmenuModel.find({status:"1"}).populate('submenu_id').populate('menu_id')
class PayoutRequestController {
  static AddPayoutRequest = async (request, response, next) => {
    let resp = await CheckLogin(request);
    if (resp == 100) {
      return response.redirect("/login");
    }

    try {
      const url_name = request.url;
      const menu_name = await menuactive.menudata(url_name);
      const roledata = await menuactive.roledata(request.session.role);
      if (roledata[0] != undefined) {
        const all_clients = await HeaderCommonData.CommonData();
        const headerdynemicdata = await MenuModel.find({
          _id: { $in: roledata[0].menu_id },
          status: "1",
        });
        const submenu_list = await SubmenuModel.find({
          _id: { $in: roledata[0].submenu_id },
          status: "1",
        }).populate("menu_id");
        const subsubmanu_list = await SubsubmenuModel.find({
          _id: { $in: roledata[0].subsubmenu_id },
          status: "1",
        })
          .populate("submenu_id")
          .populate("menu_id");
        const submenuid = await menuactive.submenuid(url_name);
        if (
          roledata[0].submenu_id.includes(submenuid) &&
          roledata[0].submenu_id != ""
        ) {
          response.render("home/payout_request/add_payout_request", {
            role: request.session.role,
            client_code: request.session.client_code,
            logged_in_userid: request.session.user_id,
            header_data: header_data,
            headerdynemicdata: headerdynemicdata,
            role_name: request.session.role,
            login_id: request.session.login_Id,
            submenu_list: submenu_list,
            menu_name: menu_name,
            subsubmanu_list: subsubmanu_list,
          });
        } else {
          response.redirect("/home");
        }
      } else {
        response.redirect("/home");
      }
    } catch (e) {
      response.send(e);
    }
  };

  static SavePayoutRequest = async (request, response) => {
    //  console.log(request.body);

    const {
      client_code,
      available_balance,
      request_amount,
      source,
      logged_in_userid,
    } = request.body;

    if ((client_code, available_balance, request_amount, logged_in_userid)) {
      try {
        const doc = new PayoutRequestModel({
          client_code: client_code,
          available_balance: available_balance,
          request_amount: request_amount,
          logged_in_userid: logged_in_userid,
          status: 0,
          rejected_reason: "",
          partial_amount: "",
          source: source,
        });
        await doc.save();

        response.send({
          status: "success",
          message: "Payout request inserted successfully.",
          //data: doc,
        });
      } catch (error) {
        console.log(error);
        response.send({
          status: "failed",
          message: "Unable to register.",
        });
      }
    } else {
      response.send({
        status: "failed",
        message: "all fields are required.",
      });
    }
  };
  static GetPayoutRequestForRMS = async (request, response) => {
    try {
      const result = await PayoutRequestModel.find().sort({ createdAt: -1 });
      const rejected_reason_list = await RejectedReasonModel.find();
      const header_data = await HeaderCommonData.CommonData();
      const headerdynemicdata = await MenuModel.find({ status: "1" });
      const submenu_list = await SubmenuModel.find({ status: "1" }).populate(
        "menu_id"
      );
      const subsubmanu_list = await SubsubmenuModel.find({ status: "1" })
        .populate("submenu_id")
        .populate("menu_id");
      response.render("home/payout_request/get_payout_request_list", {
        data: result,
        rejected_reason_list: rejected_reason_list,
        header_data: header_data,
        headerdynemicdata: headerdynemicdata,
        role_name: request.session.role,
        login_id: request.session.login_Id,
        submenu_list: submenu_list,
        subsubmanu_list: subsubmanu_list,
      });
      response.status(200).send(result);
    } catch (error) {
      console.log(error);
    }
  };

  static findById = async (req, res) => {
    try {
      const result = await PayoutRequestModel.findById(req.params.id).sort({
        createdAt: -1,
      });

      res.status(200).send(result);
    } catch (error) {
      console.log(error);
    }
  };

  // static UpdatePayoutRequestStatus = async (request, response) => {
  //     const updated_date = new Date();
  //     console.log(request.body)
  //     let request_body = {

  //         rejected_reason: request.body.rejected_reason,
  //         partial_amount: request.body.partially_approved_amount,
  //         status: request.body.payout_request_status,
  //         id: request.body.id,
  //         updated_date: new Date(),
  //         logged_in_userid: request.session.userRoleId
  //     };
  //     //console.log(request_body)
  //     try {
  //         // code to insert in payout requset log
  //         const payout_request_data = await PayoutRequestModel.find({ '_id': request.body.id });
  //         if (payout_request_data != '') {
  //             console.log(payout_request_data)
  //             const docs = new PayoutRequestLogModel({
  //                 client_code: payout_request_data[0].client_code,
  //                 available_balance: payout_request_data[0].available_balance,
  //                 request_amount: payout_request_data[0].request_amount,
  //                 logged_in_userid: payout_request_data[0].logged_in_userid,
  //                 status: payout_request_data[0].status,
  //                 rejected_reason: payout_request_data[0].rejected_reason,
  //                 created_date: payout_request_data[0].created_date,
  //                 updated_date: payout_request_data[0].updated_date,
  //                 payout_request_id: payout_request_data[0]._id,
  //                 source: payout_request_data[0].source,

  //             })
  //             await docs.save();
  //         }

  //         if (request_body.status == '2' && request_body.partial_amount == '') {
  //             response.send({
  //                 'status': "failed",
  //                 "message": "Partially approved amount is required."
  //             })
  //         }
  //         if (request_body.status == '3' && request_body.rejected_reason == null) {
  //             response.send({
  //                 'status': "failed",
  //                 "message": "Reject reason is required."
  //             })
  //         }

  //         if (request_body.status == '1') {
  //             request_body.partial_amount = ''
  //             request_body.rejected_reason = null;
  //         }
  //         if (request_body.status == '2') {
  //             request_body.rejected_reason = null;
  //         }
  //         if (request_body.status == '3') {
  //             request_body.partial_amount = ''
  //         }
  //         if (request_body.status) {
  //             const result = await PayoutRequestModel.findByIdAndUpdate(request_body.id, request_body)
  //             response.send({
  //                 'status': "success",
  //                 "message": "Payout request updated successfully."
  //             })
  //         } else {
  //             response.send({
  //                 'status': "failed",
  //                 "message": "Select Status."
  //             })
  //         }

  //     } catch (error) {
  //         console.log(error)
  //     }
  // }

  // ========================================soyal =========================================

  static findByIdandUpdatedata = async (req, res) => {
    const mac_address = getMAC();
    const public_ip_address = await publicIpv4();
    const dt = new Date();
    const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
    const updated_datetime_of_rm = `${padL(dt.getMonth() + 1)}/${padL(
      dt.getDate()
    )}/${dt.getFullYear()} ${padL(dt.getHours())}:${padL(
      dt.getMinutes()
    )}:${padL(dt.getSeconds())}`;

    try {
      let update_data = {
        rejected_reason: req.body.rejected_reason || "",
        partial_amount: req.body.partially_approved_amount || "",
        status_of_rm: req.body.payout_request_status || "",
        updated_datetime_of_rm: updated_datetime_of_rm,
        status: "1",
      };
      // console.log(update_data);
      const data = await PayoutRequestModel.findByIdAndUpdate(
        req.body.id,
        update_data
      );

      const payout_request_data = await PayoutRequestModel.find({
        _id: req.body.id,
      });

      if (payout_request_data != "") {
        // console.log(payout_request_data);
        const docs = new PayoutRequestLogModel({
          client_code: payout_request_data[0].client_code,
          available_balance: payout_request_data[0].available_balance,
          request_amount: payout_request_data[0].request_amount,
          logged_in_userid: payout_request_data[0].logged_in_userid,
          status: payout_request_data[0].status,
          rejected_reason: payout_request_data[0].rejected_reason,
          payout_request_id: payout_request_data[0]._id,
          partial_amount: payout_request_data[0].partial_amount,
          source: payout_request_data[0].source,
          mac_address: mac_address,
          ip4: public_ip_address,
          ip6:
            req.headers["x-forwarded-for"] ||
            req.connection.remoteAddress ||
            null,
        });
        await docs.save();
      }

      res
        .status(200)
        .send({ status: "success", message: "update ", data: data });
    } catch (e) {
      res.send("something went wrong");
    }
  };
  static UpdatePaymentRequestStatusForAccounts = async (req, res) => {
    const mac_address = getMAC();
    const public_ip_address = await publicIpv4();
    const dt = new Date();
    const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
    const updated_datetime_of_rm = `${padL(dt.getMonth() + 1)}/${padL(
      dt.getDate()
    )}/${dt.getFullYear()} ${padL(dt.getHours())}:${padL(
      dt.getMinutes()
    )}:${padL(dt.getSeconds())}`;

    try {
      let update_data = {
        rejected_reason: req.body.rejected_reason || "",
        partial_amount: req.body.partially_approved_amount || "",
        status_of_accounts: req.body.payout_request_status || "",
        updated_datetime_of_accounts: updated_datetime_of_rm,
        status: "1",
      };
      // console.log(update_data);
      const data = await PayoutRequestModel.findByIdAndUpdate(
        req.body.id,
        update_data
      );

      const payout_request_data = await PayoutRequestModel.find({
        _id: req.body.id,
      });

      if (payout_request_data != "") {
        // console.log(payout_request_data);
        const docs = new PayoutRequestLogModel({
          client_code: payout_request_data[0].client_code,
          available_balance: payout_request_data[0].available_balance,
          request_amount: payout_request_data[0].request_amount,
          logged_in_userid: payout_request_data[0].logged_in_userid,
          status: payout_request_data[0].status,
          rejected_reason: payout_request_data[0].rejected_reason,
          payout_request_id: payout_request_data[0]._id,
          partial_amount: payout_request_data[0].partial_amount,
          source: payout_request_data[0].source,
          mac_address: mac_address,
          ip4: public_ip_address,
          ip6:
            req.headers["x-forwarded-for"] ||
            req.connection.remoteAddress ||
            null,
        });
        await docs.save();
      }

      res
        .status(200)
        .send({ status: "success", message: "update ", data: data });
    } catch (e) {
      res.send("something went wrong");
    }
  };

  static GetPayoutRequestForAccounts = async (request, response) => {
    try {
      if (request.session.user_role_id == undefined) {
        return response.redirect("/login");
      }
      const url_name = request.url;
      const menu_name = await menuactive.payoutmenudata(url_name);
      const result = await PayoutRequestModel.find({
        status_of_rm: { $in: ["1", "2"] },
        status: 1,
      }).sort({ created_date: "descending" });

      const header_data = await HeaderCommonData.CommonData();
      const rejected_reason_list = await RejectedReasonModel.find();

      const headerdynemicdata = await MenuModel.find({ status: "1" });
      const submenu_list = await SubmenuModel.find({ status: "1" }).populate(
        "menu_id"
      );
      const subsubmanu_list = await SubsubmenuModel.find({ status: "1" })
        .populate("submenu_id")
        .populate("menu_id");

      response.render(
        "home/payout_request/get_payout_request_list_for_accounts",
        {
          data: result,
          rejected_reason_list: rejected_reason_list,
          header_data: header_data,
          headerdynemicdata: headerdynemicdata,
          role_name: request.session.role,
          login_id: request.session.login_Id,
          submenu_list: submenu_list,
          subsubmanu_list: subsubmanu_list,
          menu_name: menu_name,
        }
      );
    } catch (error) {
      console.log(error);
    }
  };
  static PayoutRequestList = async (request, response, next) => {
    if (request.session.user_role_id == undefined) {
      return response.redirect("/login");
    }
    const url_name = request.url;
    const menu_name = await menuactive.payoutmenudata(url_name);
    const header_data = await HeaderCommonData.CommonData();
    const result = await PayoutRequestModel.find().sort({
      created_date: "descending",
    });
    const rejected_reason_list = await RejectedReasonModel.find();
    const headerdynemicdata = await MenuModel.find({ status: "1" });
    const submenu_list = await SubmenuModel.find({ status: "1" }).populate(
      "menu_id"
    );
    const subsubmanu_list = await SubsubmenuModel.find({ status: "1" })
      .populate("submenu_id")
      .populate("menu_id");

    response.render("home/payout_request/payout_request_list", {
      role: request.session.role,
      client_code: request.session.client_code,
      data: result,
      rejected_reason_list: rejected_reason_list,
      header_data: header_data,
      headerdynemicdata: headerdynemicdata,
      role_name: request.session.role,
      login_id: request.session.login_Id,
      submenu_list: submenu_list,
      subsubmanu_list: subsubmanu_list,
      menu_name: menu_name,
    });
  };
  static GetRejectedReasonModal = async (request, response, next) => {
    response.render("home/payout_request/get_reject_reason_modal", {
      payout_request_id: request.body.payout_request_id,
    });
  };
  static getClientWiseAvailableBalance = async (request, response) => {
    // console.log(request.body);
    if (request.body.client_code != "") {
      try {
        sql.connect(config).then(function (output) {
          // Stored Procedure
          new sql.Request()
            .input("clientcode", request.body.client_code)

            .execute("dbo.PROC_getAvailableBalance")
            .then(function (recordsets) {
              response.send({
                status: 200,
                data: recordsets.recordset || "",
              });

              sql.close();
            })
            .catch(function (err) {
              console.log(err);
            });
        });
      } catch (e) {
        response.status(400).send(e);
        console.log(e);
      }
    } else {
      response.send({
        status: 201,
        data: "",
      });
    }
  };

  static Add_Fund = async (request, response) => {
    if (request.session.user_role_id == undefined) {
      return response.redirect("/login");
    }
    const url_name = request.url;
    const menu_name = await menuactive.payoutmenudata(url_name);
    const header_data = await HeaderCommonData.CommonData();
    const headerdynemicdata = await MenuModel.find({ status: "1" });
    const submenu_list = await SubmenuModel.find({ status: "1" }).populate(
      "menu_id"
    );
    const subsubmanu_list = await SubsubmenuModel.find({ status: "1" })
      .populate("submenu_id")
      .populate("menu_id");
    console.log("test11");
    let url = 'https://pg.mygainn.com/fund/addpayment'
    let input_data = {
      "login_Id": request.session.login_Id,
    }
    // axios({
    //     method: 'get',
    //     url: url,
    //     data:input_data
    // }).then((res) => {

    //console.log(response);
    response.render("home/payout_request/add_fund",
      {
        header_data: header_data,
        headerdynemicdata: headerdynemicdata,
        role_name: request.session.role,
        login_id: request.session.login_Id,
        submenu_list: submenu_list,
        subsubmanu_list: subsubmanu_list,
        menu_name: menu_name,
        login_id: request.session.login_Id,
        data: response.data
      })

    // }).catch((e) => {

    //     console.log(e);
    // })


  };
}

export default PayoutRequestController;